prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def <|fim_middle|>(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
on_trash
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def <|fim_middle|>(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
add_assign_comment
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def <|fim_middle|>(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
delete_communication_links
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def <|fim_middle|>(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
update_in_reference
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def <|fim_middle|>(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
get_owners
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def <|fim_middle|>(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
on_doctype_update
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def <|fim_middle|>(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
get_permission_query_conditions
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def <|fim_middle|>(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def new_todo(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
has_permission
<|file_name|>todo.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe import json from frappe.model.document import Document from frappe.utils import get_fullname, parse_addr exclude_from_linked_with = True class ToDo(Document): DocType = 'ToDo' def validate(self): self._assignment = None if self.is_new(): if self.assigned_by == self.allocated_to: assignment_message = frappe._("{0} self assigned this task: {1}").format(get_fullname(self.assigned_by), self.description) else: assignment_message = frappe._("{0} assigned {1}: {2}").format(get_fullname(self.assigned_by), get_fullname(self.allocated_to), self.description) self._assignment = { "text": assignment_message, "comment_type": "Assigned" } else: # NOTE the previous value is only available in validate method if self.get_db_value("status") != self.status: if self.allocated_to == frappe.session.user: removal_message = frappe._("{0} removed their assignment.").format( get_fullname(frappe.session.user)) else: removal_message = frappe._("Assignment of {0} removed by {1}").format( get_fullname(self.allocated_to), get_fullname(frappe.session.user)) self._assignment = { "text": removal_message, "comment_type": "Assignment Completed" } def on_update(self): if self._assignment: self.add_assign_comment(**self._assignment) self.update_in_reference() def on_trash(self): self.delete_communication_links() self.update_in_reference() def add_assign_comment(self, text, comment_type): if not (self.reference_type and self.reference_name): return frappe.get_doc(self.reference_type, self.reference_name).add_comment(comment_type, text) def delete_communication_links(self): # unlink todo from linked comments return frappe.db.delete("Communication Link", { "link_doctype": self.doctype, "link_name": self.name }) def update_in_reference(self): if not (self.reference_type and self.reference_name): return try: assignments = frappe.get_all("ToDo", filters={ "reference_type": self.reference_type, "reference_name": self.reference_name, "status": ("!=", "Cancelled") }, pluck="allocated_to") assignments.reverse() frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) except Exception as e: if frappe.db.is_table_missing(e) and frappe.flags.in_install: # no table return elif frappe.db.is_column_missing(e): from frappe.database.schema import add_column add_column(self.reference_type, "_assign", "Text") self.update_in_reference() else: raise @classmethod def get_owners(cls, filters=None): """Returns list of owners after applying filters on todo's. """ rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to']) return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to] # NOTE: todo is viewable if a user is an owner, or set as assigned_to value, or has any role that is allowed to access ToDo doctype. def on_doctype_update(): frappe.db.add_index("ToDo", ["reference_type", "reference_name"]) def get_permission_query_conditions(user): if not user: user = frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo') if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return None else: return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by = {user})"""\ .format(user=frappe.db.escape(user)) def has_permission(doc, ptype="read", user=None): user = user or frappe.session.user todo_roles = frappe.permissions.get_doctype_roles('ToDo', ptype) if 'All' in todo_roles: todo_roles.remove('All') if any(check in todo_roles for check in frappe.get_roles(user)): return True else: return doc.allocated_to==user or doc.assigned_by==user @frappe.whitelist() def <|fim_middle|>(description): frappe.get_doc({ 'doctype': 'ToDo', 'description': description }).insert() <|fim▁end|>
new_todo
<|file_name|>active.py<|end_file_name|><|fim▁begin|>import re from django import template from django.core.urlresolvers import NoReverseMatch from django.core.urlresolvers import reverse register = template.Library() @register.simple_tag(takes_context=True) def active(context, name): try: pattern = reverse(name) except NoReverseMatch: return '' if re.match(pattern, context['request'].path):<|fim▁hole|><|fim▁end|>
return 'active' return ''
<|file_name|>active.py<|end_file_name|><|fim▁begin|>import re from django import template from django.core.urlresolvers import NoReverseMatch from django.core.urlresolvers import reverse register = template.Library() @register.simple_tag(takes_context=True) def active(context, name): <|fim_middle|> <|fim▁end|>
try: pattern = reverse(name) except NoReverseMatch: return '' if re.match(pattern, context['request'].path): return 'active' return ''
<|file_name|>active.py<|end_file_name|><|fim▁begin|>import re from django import template from django.core.urlresolvers import NoReverseMatch from django.core.urlresolvers import reverse register = template.Library() @register.simple_tag(takes_context=True) def active(context, name): try: pattern = reverse(name) except NoReverseMatch: return '' if re.match(pattern, context['request'].path): <|fim_middle|> return '' <|fim▁end|>
return 'active'
<|file_name|>active.py<|end_file_name|><|fim▁begin|>import re from django import template from django.core.urlresolvers import NoReverseMatch from django.core.urlresolvers import reverse register = template.Library() @register.simple_tag(takes_context=True) def <|fim_middle|>(context, name): try: pattern = reverse(name) except NoReverseMatch: return '' if re.match(pattern, context['request'].path): return 'active' return '' <|fim▁end|>
active
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from django.http import HttpResponse from django.template import RequestContext, loader from django.views.decorators.csrf import csrf_exempt import django.shortcuts from wlokalu.api import presence #----------------------------------------------------------------------------- from wlokalu.logging import getLogger, message as log<|fim▁hole|>#----------------------------------------------------------------------------- @csrf_exempt def list(request, nick = None): template = loader.get_template("list.html") from django.core.urlresolvers import reverse from forms import PresenceForm form = PresenceForm() if nick is not None: form.initial['nick'] = nick form_target = reverse(list, kwargs = {'nick': nick}) else: form_target = reverse(list) if request.POST.get('nick', '') != '': context = { 'address': request.META['REMOTE_ADDR'], 'uri': request.META['REQUEST_URI'], } if 'enter' in request.POST: presence.person_entered(request.POST['nick'], context) else: # 'leave' in request.POST presence.person_left(request.POST['nick'], context) # tell the browser to reload the page, but with GET request return django.shortcuts.redirect(request.path) context = RequestContext(request, { 'form_target': form_target, 'form': form, 'present': presence.list_people(), 'sensors': presence.list_simple_sensors(), 'complex_sensors': presence.list_complex_sensors(), }) return HttpResponse(template.render(context)) #----------------------------------------------------------------------------- # vim:ft=python:foldmethod=marker<|fim▁end|>
logger = getLogger(__name__)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from django.http import HttpResponse from django.template import RequestContext, loader from django.views.decorators.csrf import csrf_exempt import django.shortcuts from wlokalu.api import presence #----------------------------------------------------------------------------- from wlokalu.logging import getLogger, message as log logger = getLogger(__name__) #----------------------------------------------------------------------------- @csrf_exempt def list(request, nick = None): <|fim_middle|> #----------------------------------------------------------------------------- # vim:ft=python:foldmethod=marker <|fim▁end|>
template = loader.get_template("list.html") from django.core.urlresolvers import reverse from forms import PresenceForm form = PresenceForm() if nick is not None: form.initial['nick'] = nick form_target = reverse(list, kwargs = {'nick': nick}) else: form_target = reverse(list) if request.POST.get('nick', '') != '': context = { 'address': request.META['REMOTE_ADDR'], 'uri': request.META['REQUEST_URI'], } if 'enter' in request.POST: presence.person_entered(request.POST['nick'], context) else: # 'leave' in request.POST presence.person_left(request.POST['nick'], context) # tell the browser to reload the page, but with GET request return django.shortcuts.redirect(request.path) context = RequestContext(request, { 'form_target': form_target, 'form': form, 'present': presence.list_people(), 'sensors': presence.list_simple_sensors(), 'complex_sensors': presence.list_complex_sensors(), }) return HttpResponse(template.render(context))
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from django.http import HttpResponse from django.template import RequestContext, loader from django.views.decorators.csrf import csrf_exempt import django.shortcuts from wlokalu.api import presence #----------------------------------------------------------------------------- from wlokalu.logging import getLogger, message as log logger = getLogger(__name__) #----------------------------------------------------------------------------- @csrf_exempt def list(request, nick = None): template = loader.get_template("list.html") from django.core.urlresolvers import reverse from forms import PresenceForm form = PresenceForm() if nick is not None: <|fim_middle|> else: form_target = reverse(list) if request.POST.get('nick', '') != '': context = { 'address': request.META['REMOTE_ADDR'], 'uri': request.META['REQUEST_URI'], } if 'enter' in request.POST: presence.person_entered(request.POST['nick'], context) else: # 'leave' in request.POST presence.person_left(request.POST['nick'], context) # tell the browser to reload the page, but with GET request return django.shortcuts.redirect(request.path) context = RequestContext(request, { 'form_target': form_target, 'form': form, 'present': presence.list_people(), 'sensors': presence.list_simple_sensors(), 'complex_sensors': presence.list_complex_sensors(), }) return HttpResponse(template.render(context)) #----------------------------------------------------------------------------- # vim:ft=python:foldmethod=marker <|fim▁end|>
form.initial['nick'] = nick form_target = reverse(list, kwargs = {'nick': nick})
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from django.http import HttpResponse from django.template import RequestContext, loader from django.views.decorators.csrf import csrf_exempt import django.shortcuts from wlokalu.api import presence #----------------------------------------------------------------------------- from wlokalu.logging import getLogger, message as log logger = getLogger(__name__) #----------------------------------------------------------------------------- @csrf_exempt def list(request, nick = None): template = loader.get_template("list.html") from django.core.urlresolvers import reverse from forms import PresenceForm form = PresenceForm() if nick is not None: form.initial['nick'] = nick form_target = reverse(list, kwargs = {'nick': nick}) else: <|fim_middle|> if request.POST.get('nick', '') != '': context = { 'address': request.META['REMOTE_ADDR'], 'uri': request.META['REQUEST_URI'], } if 'enter' in request.POST: presence.person_entered(request.POST['nick'], context) else: # 'leave' in request.POST presence.person_left(request.POST['nick'], context) # tell the browser to reload the page, but with GET request return django.shortcuts.redirect(request.path) context = RequestContext(request, { 'form_target': form_target, 'form': form, 'present': presence.list_people(), 'sensors': presence.list_simple_sensors(), 'complex_sensors': presence.list_complex_sensors(), }) return HttpResponse(template.render(context)) #----------------------------------------------------------------------------- # vim:ft=python:foldmethod=marker <|fim▁end|>
form_target = reverse(list)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from django.http import HttpResponse from django.template import RequestContext, loader from django.views.decorators.csrf import csrf_exempt import django.shortcuts from wlokalu.api import presence #----------------------------------------------------------------------------- from wlokalu.logging import getLogger, message as log logger = getLogger(__name__) #----------------------------------------------------------------------------- @csrf_exempt def list(request, nick = None): template = loader.get_template("list.html") from django.core.urlresolvers import reverse from forms import PresenceForm form = PresenceForm() if nick is not None: form.initial['nick'] = nick form_target = reverse(list, kwargs = {'nick': nick}) else: form_target = reverse(list) if request.POST.get('nick', '') != '': <|fim_middle|> context = RequestContext(request, { 'form_target': form_target, 'form': form, 'present': presence.list_people(), 'sensors': presence.list_simple_sensors(), 'complex_sensors': presence.list_complex_sensors(), }) return HttpResponse(template.render(context)) #----------------------------------------------------------------------------- # vim:ft=python:foldmethod=marker <|fim▁end|>
context = { 'address': request.META['REMOTE_ADDR'], 'uri': request.META['REQUEST_URI'], } if 'enter' in request.POST: presence.person_entered(request.POST['nick'], context) else: # 'leave' in request.POST presence.person_left(request.POST['nick'], context) # tell the browser to reload the page, but with GET request return django.shortcuts.redirect(request.path)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from django.http import HttpResponse from django.template import RequestContext, loader from django.views.decorators.csrf import csrf_exempt import django.shortcuts from wlokalu.api import presence #----------------------------------------------------------------------------- from wlokalu.logging import getLogger, message as log logger = getLogger(__name__) #----------------------------------------------------------------------------- @csrf_exempt def list(request, nick = None): template = loader.get_template("list.html") from django.core.urlresolvers import reverse from forms import PresenceForm form = PresenceForm() if nick is not None: form.initial['nick'] = nick form_target = reverse(list, kwargs = {'nick': nick}) else: form_target = reverse(list) if request.POST.get('nick', '') != '': context = { 'address': request.META['REMOTE_ADDR'], 'uri': request.META['REQUEST_URI'], } if 'enter' in request.POST: <|fim_middle|> else: # 'leave' in request.POST presence.person_left(request.POST['nick'], context) # tell the browser to reload the page, but with GET request return django.shortcuts.redirect(request.path) context = RequestContext(request, { 'form_target': form_target, 'form': form, 'present': presence.list_people(), 'sensors': presence.list_simple_sensors(), 'complex_sensors': presence.list_complex_sensors(), }) return HttpResponse(template.render(context)) #----------------------------------------------------------------------------- # vim:ft=python:foldmethod=marker <|fim▁end|>
presence.person_entered(request.POST['nick'], context)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from django.http import HttpResponse from django.template import RequestContext, loader from django.views.decorators.csrf import csrf_exempt import django.shortcuts from wlokalu.api import presence #----------------------------------------------------------------------------- from wlokalu.logging import getLogger, message as log logger = getLogger(__name__) #----------------------------------------------------------------------------- @csrf_exempt def list(request, nick = None): template = loader.get_template("list.html") from django.core.urlresolvers import reverse from forms import PresenceForm form = PresenceForm() if nick is not None: form.initial['nick'] = nick form_target = reverse(list, kwargs = {'nick': nick}) else: form_target = reverse(list) if request.POST.get('nick', '') != '': context = { 'address': request.META['REMOTE_ADDR'], 'uri': request.META['REQUEST_URI'], } if 'enter' in request.POST: presence.person_entered(request.POST['nick'], context) else: # 'leave' in request.POST <|fim_middle|> # tell the browser to reload the page, but with GET request return django.shortcuts.redirect(request.path) context = RequestContext(request, { 'form_target': form_target, 'form': form, 'present': presence.list_people(), 'sensors': presence.list_simple_sensors(), 'complex_sensors': presence.list_complex_sensors(), }) return HttpResponse(template.render(context)) #----------------------------------------------------------------------------- # vim:ft=python:foldmethod=marker <|fim▁end|>
presence.person_left(request.POST['nick'], context)
<|file_name|>views.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from django.http import HttpResponse from django.template import RequestContext, loader from django.views.decorators.csrf import csrf_exempt import django.shortcuts from wlokalu.api import presence #----------------------------------------------------------------------------- from wlokalu.logging import getLogger, message as log logger = getLogger(__name__) #----------------------------------------------------------------------------- @csrf_exempt def <|fim_middle|>(request, nick = None): template = loader.get_template("list.html") from django.core.urlresolvers import reverse from forms import PresenceForm form = PresenceForm() if nick is not None: form.initial['nick'] = nick form_target = reverse(list, kwargs = {'nick': nick}) else: form_target = reverse(list) if request.POST.get('nick', '') != '': context = { 'address': request.META['REMOTE_ADDR'], 'uri': request.META['REQUEST_URI'], } if 'enter' in request.POST: presence.person_entered(request.POST['nick'], context) else: # 'leave' in request.POST presence.person_left(request.POST['nick'], context) # tell the browser to reload the page, but with GET request return django.shortcuts.redirect(request.path) context = RequestContext(request, { 'form_target': form_target, 'form': form, 'present': presence.list_people(), 'sensors': presence.list_simple_sensors(), 'complex_sensors': presence.list_complex_sensors(), }) return HttpResponse(template.render(context)) #----------------------------------------------------------------------------- # vim:ft=python:foldmethod=marker <|fim▁end|>
list
<|file_name|>testtermopi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python """ title : testtermopi.py description : This program runs the termopi.py <|fim▁hole|> : Displays the status of the resources (cpu load and memory usage) consumed by a Raspberry Pi computer and the resources consumed by one or more containers instantiated in the Pi. source : author : Carlos Molina-Jimenez ([email protected]) date : 27 Mar 2017 institution : Computer Laboratory, University of Cambridge version : 1.0 usage : notes : compile and run : % python termopi.py : It imports pidict.py, dockerctl.py and picheck.py which are found in : ./modules. : You need to include "./modules" in the PYTHONPATH environment variable to : indicate python where to find the pidict.py, dockerctl.py and picheck.py. : For example, in a bash shell, you need to include the following lines : in your .bash_profile file located in you home directory (you can see it with : (# ls -la). : : PYTHONPATH="./modules" : export PYTHONPATH python_version : Python 2.7.12 ==================================================== """ from modules.tools.termopi import termopi # class with dictionary data structure # Threshold of cpu exhaustion cpuUsageThreshold= 50 cpuLoadThreshold= 3 termo= termopi() termo.prt_pi_resources() termo.create_jsonfile_with_pi_status() #termo.check_pi_resource_status(cpuUsageThreshold)<|fim▁end|>
<|file_name|>network_cls.py<|end_file_name|><|fim▁begin|>import tensorflow as tf from ocnn import * # octree-based resnet55 def network_resnet(octree, flags, training=True, reuse=None): depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) with tf.variable_scope("conv1"): data = octree_conv_bn_relu(data, octree, depth, channels[depth], training) for d in range(depth, 2, -1): for i in range(0, flags.resblock_num): with tf.variable_scope('resblock_%d_%d' % (d, i)): data = octree_resblock(data, octree, d, channels[d], 1, training) with tf.variable_scope('max_pool_%d' % d): data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("global_average"): data = octree_full_voxel(data, depth=2) data = tf.reduce_mean(data, 2) if flags.dropout[0]: data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit # the ocnn in the paper def network_ocnn(octree, flags, training=True, reuse=None): depth = flags.depth channels = [512, 256, 128, 64, 32, 16, 8, 4, 2] with tf.variable_scope("ocnn", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) for d in range(depth, 2, -1): with tf.variable_scope('depth_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training)<|fim▁hole|> with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit def cls_network(octree, flags, training, reuse=False): if flags.name.lower() == 'ocnn': return network_ocnn(octree, flags, training, reuse) elif flags.name.lower() == 'resnet': return network_resnet(octree, flags, training, reuse) else: print('Error, no network: ' + flags.name)<|fim▁end|>
data, _ = octree_max_pool(data, octree, d)
<|file_name|>network_cls.py<|end_file_name|><|fim▁begin|>import tensorflow as tf from ocnn import * # octree-based resnet55 def network_resnet(octree, flags, training=True, reuse=None): <|fim_middle|> # the ocnn in the paper def network_ocnn(octree, flags, training=True, reuse=None): depth = flags.depth channels = [512, 256, 128, 64, 32, 16, 8, 4, 2] with tf.variable_scope("ocnn", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) for d in range(depth, 2, -1): with tf.variable_scope('depth_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training) data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit def cls_network(octree, flags, training, reuse=False): if flags.name.lower() == 'ocnn': return network_ocnn(octree, flags, training, reuse) elif flags.name.lower() == 'resnet': return network_resnet(octree, flags, training, reuse) else: print('Error, no network: ' + flags.name) <|fim▁end|>
depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) with tf.variable_scope("conv1"): data = octree_conv_bn_relu(data, octree, depth, channels[depth], training) for d in range(depth, 2, -1): for i in range(0, flags.resblock_num): with tf.variable_scope('resblock_%d_%d' % (d, i)): data = octree_resblock(data, octree, d, channels[d], 1, training) with tf.variable_scope('max_pool_%d' % d): data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("global_average"): data = octree_full_voxel(data, depth=2) data = tf.reduce_mean(data, 2) if flags.dropout[0]: data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit
<|file_name|>network_cls.py<|end_file_name|><|fim▁begin|>import tensorflow as tf from ocnn import * # octree-based resnet55 def network_resnet(octree, flags, training=True, reuse=None): depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) with tf.variable_scope("conv1"): data = octree_conv_bn_relu(data, octree, depth, channels[depth], training) for d in range(depth, 2, -1): for i in range(0, flags.resblock_num): with tf.variable_scope('resblock_%d_%d' % (d, i)): data = octree_resblock(data, octree, d, channels[d], 1, training) with tf.variable_scope('max_pool_%d' % d): data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("global_average"): data = octree_full_voxel(data, depth=2) data = tf.reduce_mean(data, 2) if flags.dropout[0]: data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit # the ocnn in the paper def network_ocnn(octree, flags, training=True, reuse=None): <|fim_middle|> def cls_network(octree, flags, training, reuse=False): if flags.name.lower() == 'ocnn': return network_ocnn(octree, flags, training, reuse) elif flags.name.lower() == 'resnet': return network_resnet(octree, flags, training, reuse) else: print('Error, no network: ' + flags.name) <|fim▁end|>
depth = flags.depth channels = [512, 256, 128, 64, 32, 16, 8, 4, 2] with tf.variable_scope("ocnn", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) for d in range(depth, 2, -1): with tf.variable_scope('depth_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training) data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit
<|file_name|>network_cls.py<|end_file_name|><|fim▁begin|>import tensorflow as tf from ocnn import * # octree-based resnet55 def network_resnet(octree, flags, training=True, reuse=None): depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) with tf.variable_scope("conv1"): data = octree_conv_bn_relu(data, octree, depth, channels[depth], training) for d in range(depth, 2, -1): for i in range(0, flags.resblock_num): with tf.variable_scope('resblock_%d_%d' % (d, i)): data = octree_resblock(data, octree, d, channels[d], 1, training) with tf.variable_scope('max_pool_%d' % d): data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("global_average"): data = octree_full_voxel(data, depth=2) data = tf.reduce_mean(data, 2) if flags.dropout[0]: data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit # the ocnn in the paper def network_ocnn(octree, flags, training=True, reuse=None): depth = flags.depth channels = [512, 256, 128, 64, 32, 16, 8, 4, 2] with tf.variable_scope("ocnn", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) for d in range(depth, 2, -1): with tf.variable_scope('depth_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training) data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit def cls_network(octree, flags, training, reuse=False): <|fim_middle|> <|fim▁end|>
if flags.name.lower() == 'ocnn': return network_ocnn(octree, flags, training, reuse) elif flags.name.lower() == 'resnet': return network_resnet(octree, flags, training, reuse) else: print('Error, no network: ' + flags.name)
<|file_name|>network_cls.py<|end_file_name|><|fim▁begin|>import tensorflow as tf from ocnn import * # octree-based resnet55 def network_resnet(octree, flags, training=True, reuse=None): depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) with tf.variable_scope("conv1"): data = octree_conv_bn_relu(data, octree, depth, channels[depth], training) for d in range(depth, 2, -1): for i in range(0, flags.resblock_num): with tf.variable_scope('resblock_%d_%d' % (d, i)): data = octree_resblock(data, octree, d, channels[d], 1, training) with tf.variable_scope('max_pool_%d' % d): data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("global_average"): data = octree_full_voxel(data, depth=2) data = tf.reduce_mean(data, 2) if flags.dropout[0]: <|fim_middle|> with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit # the ocnn in the paper def network_ocnn(octree, flags, training=True, reuse=None): depth = flags.depth channels = [512, 256, 128, 64, 32, 16, 8, 4, 2] with tf.variable_scope("ocnn", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) for d in range(depth, 2, -1): with tf.variable_scope('depth_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training) data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit def cls_network(octree, flags, training, reuse=False): if flags.name.lower() == 'ocnn': return network_ocnn(octree, flags, training, reuse) elif flags.name.lower() == 'resnet': return network_resnet(octree, flags, training, reuse) else: print('Error, no network: ' + flags.name) <|fim▁end|>
data = tf.layers.dropout(data, rate=0.5, training=training)
<|file_name|>network_cls.py<|end_file_name|><|fim▁begin|>import tensorflow as tf from ocnn import * # octree-based resnet55 def network_resnet(octree, flags, training=True, reuse=None): depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) with tf.variable_scope("conv1"): data = octree_conv_bn_relu(data, octree, depth, channels[depth], training) for d in range(depth, 2, -1): for i in range(0, flags.resblock_num): with tf.variable_scope('resblock_%d_%d' % (d, i)): data = octree_resblock(data, octree, d, channels[d], 1, training) with tf.variable_scope('max_pool_%d' % d): data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("global_average"): data = octree_full_voxel(data, depth=2) data = tf.reduce_mean(data, 2) if flags.dropout[0]: data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit # the ocnn in the paper def network_ocnn(octree, flags, training=True, reuse=None): depth = flags.depth channels = [512, 256, 128, 64, 32, 16, 8, 4, 2] with tf.variable_scope("ocnn", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) for d in range(depth, 2, -1): with tf.variable_scope('depth_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training) data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit def cls_network(octree, flags, training, reuse=False): if flags.name.lower() == 'ocnn': <|fim_middle|> elif flags.name.lower() == 'resnet': return network_resnet(octree, flags, training, reuse) else: print('Error, no network: ' + flags.name) <|fim▁end|>
return network_ocnn(octree, flags, training, reuse)
<|file_name|>network_cls.py<|end_file_name|><|fim▁begin|>import tensorflow as tf from ocnn import * # octree-based resnet55 def network_resnet(octree, flags, training=True, reuse=None): depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) with tf.variable_scope("conv1"): data = octree_conv_bn_relu(data, octree, depth, channels[depth], training) for d in range(depth, 2, -1): for i in range(0, flags.resblock_num): with tf.variable_scope('resblock_%d_%d' % (d, i)): data = octree_resblock(data, octree, d, channels[d], 1, training) with tf.variable_scope('max_pool_%d' % d): data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("global_average"): data = octree_full_voxel(data, depth=2) data = tf.reduce_mean(data, 2) if flags.dropout[0]: data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit # the ocnn in the paper def network_ocnn(octree, flags, training=True, reuse=None): depth = flags.depth channels = [512, 256, 128, 64, 32, 16, 8, 4, 2] with tf.variable_scope("ocnn", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) for d in range(depth, 2, -1): with tf.variable_scope('depth_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training) data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit def cls_network(octree, flags, training, reuse=False): if flags.name.lower() == 'ocnn': return network_ocnn(octree, flags, training, reuse) elif flags.name.lower() == 'resnet': <|fim_middle|> else: print('Error, no network: ' + flags.name) <|fim▁end|>
return network_resnet(octree, flags, training, reuse)
<|file_name|>network_cls.py<|end_file_name|><|fim▁begin|>import tensorflow as tf from ocnn import * # octree-based resnet55 def network_resnet(octree, flags, training=True, reuse=None): depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) with tf.variable_scope("conv1"): data = octree_conv_bn_relu(data, octree, depth, channels[depth], training) for d in range(depth, 2, -1): for i in range(0, flags.resblock_num): with tf.variable_scope('resblock_%d_%d' % (d, i)): data = octree_resblock(data, octree, d, channels[d], 1, training) with tf.variable_scope('max_pool_%d' % d): data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("global_average"): data = octree_full_voxel(data, depth=2) data = tf.reduce_mean(data, 2) if flags.dropout[0]: data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit # the ocnn in the paper def network_ocnn(octree, flags, training=True, reuse=None): depth = flags.depth channels = [512, 256, 128, 64, 32, 16, 8, 4, 2] with tf.variable_scope("ocnn", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) for d in range(depth, 2, -1): with tf.variable_scope('depth_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training) data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit def cls_network(octree, flags, training, reuse=False): if flags.name.lower() == 'ocnn': return network_ocnn(octree, flags, training, reuse) elif flags.name.lower() == 'resnet': return network_resnet(octree, flags, training, reuse) else: <|fim_middle|> <|fim▁end|>
print('Error, no network: ' + flags.name)
<|file_name|>network_cls.py<|end_file_name|><|fim▁begin|>import tensorflow as tf from ocnn import * # octree-based resnet55 def <|fim_middle|>(octree, flags, training=True, reuse=None): depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) with tf.variable_scope("conv1"): data = octree_conv_bn_relu(data, octree, depth, channels[depth], training) for d in range(depth, 2, -1): for i in range(0, flags.resblock_num): with tf.variable_scope('resblock_%d_%d' % (d, i)): data = octree_resblock(data, octree, d, channels[d], 1, training) with tf.variable_scope('max_pool_%d' % d): data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("global_average"): data = octree_full_voxel(data, depth=2) data = tf.reduce_mean(data, 2) if flags.dropout[0]: data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit # the ocnn in the paper def network_ocnn(octree, flags, training=True, reuse=None): depth = flags.depth channels = [512, 256, 128, 64, 32, 16, 8, 4, 2] with tf.variable_scope("ocnn", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) for d in range(depth, 2, -1): with tf.variable_scope('depth_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training) data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit def cls_network(octree, flags, training, reuse=False): if flags.name.lower() == 'ocnn': return network_ocnn(octree, flags, training, reuse) elif flags.name.lower() == 'resnet': return network_resnet(octree, flags, training, reuse) else: print('Error, no network: ' + flags.name) <|fim▁end|>
network_resnet
<|file_name|>network_cls.py<|end_file_name|><|fim▁begin|>import tensorflow as tf from ocnn import * # octree-based resnet55 def network_resnet(octree, flags, training=True, reuse=None): depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) with tf.variable_scope("conv1"): data = octree_conv_bn_relu(data, octree, depth, channels[depth], training) for d in range(depth, 2, -1): for i in range(0, flags.resblock_num): with tf.variable_scope('resblock_%d_%d' % (d, i)): data = octree_resblock(data, octree, d, channels[d], 1, training) with tf.variable_scope('max_pool_%d' % d): data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("global_average"): data = octree_full_voxel(data, depth=2) data = tf.reduce_mean(data, 2) if flags.dropout[0]: data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit # the ocnn in the paper def <|fim_middle|>(octree, flags, training=True, reuse=None): depth = flags.depth channels = [512, 256, 128, 64, 32, 16, 8, 4, 2] with tf.variable_scope("ocnn", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) for d in range(depth, 2, -1): with tf.variable_scope('depth_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training) data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit def cls_network(octree, flags, training, reuse=False): if flags.name.lower() == 'ocnn': return network_ocnn(octree, flags, training, reuse) elif flags.name.lower() == 'resnet': return network_resnet(octree, flags, training, reuse) else: print('Error, no network: ' + flags.name) <|fim▁end|>
network_ocnn
<|file_name|>network_cls.py<|end_file_name|><|fim▁begin|>import tensorflow as tf from ocnn import * # octree-based resnet55 def network_resnet(octree, flags, training=True, reuse=None): depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) with tf.variable_scope("conv1"): data = octree_conv_bn_relu(data, octree, depth, channels[depth], training) for d in range(depth, 2, -1): for i in range(0, flags.resblock_num): with tf.variable_scope('resblock_%d_%d' % (d, i)): data = octree_resblock(data, octree, d, channels[d], 1, training) with tf.variable_scope('max_pool_%d' % d): data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("global_average"): data = octree_full_voxel(data, depth=2) data = tf.reduce_mean(data, 2) if flags.dropout[0]: data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit # the ocnn in the paper def network_ocnn(octree, flags, training=True, reuse=None): depth = flags.depth channels = [512, 256, 128, 64, 32, 16, 8, 4, 2] with tf.variable_scope("ocnn", reuse=reuse): data = octree_property(octree, property_name="feature", dtype=tf.float32, depth=depth, channel=flags.channel) data = tf.reshape(data, [1, flags.channel, -1, 1]) for d in range(depth, 2, -1): with tf.variable_scope('depth_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training) data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit def <|fim_middle|>(octree, flags, training, reuse=False): if flags.name.lower() == 'ocnn': return network_ocnn(octree, flags, training, reuse) elif flags.name.lower() == 'resnet': return network_resnet(octree, flags, training, reuse) else: print('Error, no network: ' + flags.name) <|fim▁end|>
cls_network
<|file_name|>test_cli.py<|end_file_name|><|fim▁begin|>from pathlib import Path from inxs.cli import main as _main from tests import equal_documents def main(*args): _args = () for arg in args: if isinstance(arg, Path): _args += (str(arg),) else: _args += (arg,) _main(_args) # TODO case-study with this use-case def test_mods_to_tei(datadir): main("--inplace", datadir / "mods_to_tei.py", datadir / "mods_to_tei.xml")<|fim▁hole|><|fim▁end|>
assert equal_documents(datadir / "mods_to_tei.xml", datadir / "mods_to_tei_exp.xml")
<|file_name|>test_cli.py<|end_file_name|><|fim▁begin|>from pathlib import Path from inxs.cli import main as _main from tests import equal_documents def main(*args): <|fim_middle|> # TODO case-study with this use-case def test_mods_to_tei(datadir): main("--inplace", datadir / "mods_to_tei.py", datadir / "mods_to_tei.xml") assert equal_documents(datadir / "mods_to_tei.xml", datadir / "mods_to_tei_exp.xml") <|fim▁end|>
_args = () for arg in args: if isinstance(arg, Path): _args += (str(arg),) else: _args += (arg,) _main(_args)
<|file_name|>test_cli.py<|end_file_name|><|fim▁begin|>from pathlib import Path from inxs.cli import main as _main from tests import equal_documents def main(*args): _args = () for arg in args: if isinstance(arg, Path): _args += (str(arg),) else: _args += (arg,) _main(_args) # TODO case-study with this use-case def test_mods_to_tei(datadir): <|fim_middle|> <|fim▁end|>
main("--inplace", datadir / "mods_to_tei.py", datadir / "mods_to_tei.xml") assert equal_documents(datadir / "mods_to_tei.xml", datadir / "mods_to_tei_exp.xml")
<|file_name|>test_cli.py<|end_file_name|><|fim▁begin|>from pathlib import Path from inxs.cli import main as _main from tests import equal_documents def main(*args): _args = () for arg in args: if isinstance(arg, Path): <|fim_middle|> else: _args += (arg,) _main(_args) # TODO case-study with this use-case def test_mods_to_tei(datadir): main("--inplace", datadir / "mods_to_tei.py", datadir / "mods_to_tei.xml") assert equal_documents(datadir / "mods_to_tei.xml", datadir / "mods_to_tei_exp.xml") <|fim▁end|>
_args += (str(arg),)
<|file_name|>test_cli.py<|end_file_name|><|fim▁begin|>from pathlib import Path from inxs.cli import main as _main from tests import equal_documents def main(*args): _args = () for arg in args: if isinstance(arg, Path): _args += (str(arg),) else: <|fim_middle|> _main(_args) # TODO case-study with this use-case def test_mods_to_tei(datadir): main("--inplace", datadir / "mods_to_tei.py", datadir / "mods_to_tei.xml") assert equal_documents(datadir / "mods_to_tei.xml", datadir / "mods_to_tei_exp.xml") <|fim▁end|>
_args += (arg,)
<|file_name|>test_cli.py<|end_file_name|><|fim▁begin|>from pathlib import Path from inxs.cli import main as _main from tests import equal_documents def <|fim_middle|>(*args): _args = () for arg in args: if isinstance(arg, Path): _args += (str(arg),) else: _args += (arg,) _main(_args) # TODO case-study with this use-case def test_mods_to_tei(datadir): main("--inplace", datadir / "mods_to_tei.py", datadir / "mods_to_tei.xml") assert equal_documents(datadir / "mods_to_tei.xml", datadir / "mods_to_tei_exp.xml") <|fim▁end|>
main
<|file_name|>test_cli.py<|end_file_name|><|fim▁begin|>from pathlib import Path from inxs.cli import main as _main from tests import equal_documents def main(*args): _args = () for arg in args: if isinstance(arg, Path): _args += (str(arg),) else: _args += (arg,) _main(_args) # TODO case-study with this use-case def <|fim_middle|>(datadir): main("--inplace", datadir / "mods_to_tei.py", datadir / "mods_to_tei.xml") assert equal_documents(datadir / "mods_to_tei.xml", datadir / "mods_to_tei_exp.xml") <|fim▁end|>
test_mods_to_tei
<|file_name|>test_clock_resolution.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Wed Sep 09 13:04:53 2015 * If TimerTool.exe is running, kill the process. * If input parameter is given, start TimerTool and set clock resolution Starts TimerTool.exe and sets the clock resolution to argv[0] ms Ex: python set_clock_resolution 0.5 @author: marcus """ import time, datetime from socket import gethostname, gethostbyname import os import numpy as np def main(): my_path = os.path.join('C:',os.sep,'Share','sync_clocks') os.chdir(my_path) # Initial timestamps t1 = time.clock() t2 = time.time() t3 = datetime.datetime.now() td1 = [] td2 = [] td3 = [] for i in xrange(100): td1.append(time.clock()-t1) td2.append(time.time() -t2) td3.append((datetime.datetime.now()-t3).total_seconds()) time.sleep(0.001) # Create text file and write header t = datetime.datetime.now() ip = gethostbyname(gethostname()).split('.')[-1] f_name = '_'.join([ip,'test_clock_res',str(t.year),str(t.month),str(t.day), str(t.hour),str(t.minute),str(t.second)]) f = open(f_name+'.txt','w') f.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' % ('mean_clock','median_clock','sd_clock', 'mean_time','median_time','sd_time', 'mean_datetime','median_datetime','sd_datetime',)) # Write results to text file f.write('%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n' % <|fim▁hole|> np.mean(np.diff(td2))*1000, np.median(np.diff(td2))*1000,np.std(np.diff(td2))*1000, np.mean(np.diff(td3))*1000, np.median(np.diff(td3))*1000,np.std(np.diff(td3))*1000)) f.close() if __name__ == "__main__": main()<|fim▁end|>
(np.mean(np.diff(td1))*1000, np.median(np.diff(td1))*1000,np.std(np.diff(td1))*1000,
<|file_name|>test_clock_resolution.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Wed Sep 09 13:04:53 2015 * If TimerTool.exe is running, kill the process. * If input parameter is given, start TimerTool and set clock resolution Starts TimerTool.exe and sets the clock resolution to argv[0] ms Ex: python set_clock_resolution 0.5 @author: marcus """ import time, datetime from socket import gethostname, gethostbyname import os import numpy as np def main(): <|fim_middle|> if __name__ == "__main__": main() <|fim▁end|>
my_path = os.path.join('C:',os.sep,'Share','sync_clocks') os.chdir(my_path) # Initial timestamps t1 = time.clock() t2 = time.time() t3 = datetime.datetime.now() td1 = [] td2 = [] td3 = [] for i in xrange(100): td1.append(time.clock()-t1) td2.append(time.time() -t2) td3.append((datetime.datetime.now()-t3).total_seconds()) time.sleep(0.001) # Create text file and write header t = datetime.datetime.now() ip = gethostbyname(gethostname()).split('.')[-1] f_name = '_'.join([ip,'test_clock_res',str(t.year),str(t.month),str(t.day), str(t.hour),str(t.minute),str(t.second)]) f = open(f_name+'.txt','w') f.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' % ('mean_clock','median_clock','sd_clock', 'mean_time','median_time','sd_time', 'mean_datetime','median_datetime','sd_datetime',)) # Write results to text file f.write('%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n' % (np.mean(np.diff(td1))*1000, np.median(np.diff(td1))*1000,np.std(np.diff(td1))*1000, np.mean(np.diff(td2))*1000, np.median(np.diff(td2))*1000,np.std(np.diff(td2))*1000, np.mean(np.diff(td3))*1000, np.median(np.diff(td3))*1000,np.std(np.diff(td3))*1000)) f.close()
<|file_name|>test_clock_resolution.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Wed Sep 09 13:04:53 2015 * If TimerTool.exe is running, kill the process. * If input parameter is given, start TimerTool and set clock resolution Starts TimerTool.exe and sets the clock resolution to argv[0] ms Ex: python set_clock_resolution 0.5 @author: marcus """ import time, datetime from socket import gethostname, gethostbyname import os import numpy as np def main(): my_path = os.path.join('C:',os.sep,'Share','sync_clocks') os.chdir(my_path) # Initial timestamps t1 = time.clock() t2 = time.time() t3 = datetime.datetime.now() td1 = [] td2 = [] td3 = [] for i in xrange(100): td1.append(time.clock()-t1) td2.append(time.time() -t2) td3.append((datetime.datetime.now()-t3).total_seconds()) time.sleep(0.001) # Create text file and write header t = datetime.datetime.now() ip = gethostbyname(gethostname()).split('.')[-1] f_name = '_'.join([ip,'test_clock_res',str(t.year),str(t.month),str(t.day), str(t.hour),str(t.minute),str(t.second)]) f = open(f_name+'.txt','w') f.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' % ('mean_clock','median_clock','sd_clock', 'mean_time','median_time','sd_time', 'mean_datetime','median_datetime','sd_datetime',)) # Write results to text file f.write('%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n' % (np.mean(np.diff(td1))*1000, np.median(np.diff(td1))*1000,np.std(np.diff(td1))*1000, np.mean(np.diff(td2))*1000, np.median(np.diff(td2))*1000,np.std(np.diff(td2))*1000, np.mean(np.diff(td3))*1000, np.median(np.diff(td3))*1000,np.std(np.diff(td3))*1000)) f.close() if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
main()
<|file_name|>test_clock_resolution.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Created on Wed Sep 09 13:04:53 2015 * If TimerTool.exe is running, kill the process. * If input parameter is given, start TimerTool and set clock resolution Starts TimerTool.exe and sets the clock resolution to argv[0] ms Ex: python set_clock_resolution 0.5 @author: marcus """ import time, datetime from socket import gethostname, gethostbyname import os import numpy as np def <|fim_middle|>(): my_path = os.path.join('C:',os.sep,'Share','sync_clocks') os.chdir(my_path) # Initial timestamps t1 = time.clock() t2 = time.time() t3 = datetime.datetime.now() td1 = [] td2 = [] td3 = [] for i in xrange(100): td1.append(time.clock()-t1) td2.append(time.time() -t2) td3.append((datetime.datetime.now()-t3).total_seconds()) time.sleep(0.001) # Create text file and write header t = datetime.datetime.now() ip = gethostbyname(gethostname()).split('.')[-1] f_name = '_'.join([ip,'test_clock_res',str(t.year),str(t.month),str(t.day), str(t.hour),str(t.minute),str(t.second)]) f = open(f_name+'.txt','w') f.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' % ('mean_clock','median_clock','sd_clock', 'mean_time','median_time','sd_time', 'mean_datetime','median_datetime','sd_datetime',)) # Write results to text file f.write('%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n' % (np.mean(np.diff(td1))*1000, np.median(np.diff(td1))*1000,np.std(np.diff(td1))*1000, np.mean(np.diff(td2))*1000, np.median(np.diff(td2))*1000,np.std(np.diff(td2))*1000, np.mean(np.diff(td3))*1000, np.median(np.diff(td3))*1000,np.std(np.diff(td3))*1000)) f.close() if __name__ == "__main__": main() <|fim▁end|>
main
<|file_name|>cleanfilecache.py<|end_file_name|><|fim▁begin|>import os from django.core.management.base import BaseCommand, CommandError from django.conf import settings<|fim▁hole|>from cacheops.simple import file_cache, FILE_CACHE_DIR class Command(BaseCommand): help = 'Clean filebased cache' def handle(self, **options): os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % FILE_CACHE_DIR)<|fim▁end|>
from django.core.exceptions import ImproperlyConfigured
<|file_name|>cleanfilecache.py<|end_file_name|><|fim▁begin|>import os from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.core.exceptions import ImproperlyConfigured from cacheops.simple import file_cache, FILE_CACHE_DIR class Command(BaseCommand): <|fim_middle|> <|fim▁end|>
help = 'Clean filebased cache' def handle(self, **options): os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % FILE_CACHE_DIR)
<|file_name|>cleanfilecache.py<|end_file_name|><|fim▁begin|>import os from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.core.exceptions import ImproperlyConfigured from cacheops.simple import file_cache, FILE_CACHE_DIR class Command(BaseCommand): help = 'Clean filebased cache' def handle(self, **options): <|fim_middle|> <|fim▁end|>
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % FILE_CACHE_DIR)
<|file_name|>cleanfilecache.py<|end_file_name|><|fim▁begin|>import os from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.core.exceptions import ImproperlyConfigured from cacheops.simple import file_cache, FILE_CACHE_DIR class Command(BaseCommand): help = 'Clean filebased cache' def <|fim_middle|>(self, **options): os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % FILE_CACHE_DIR) <|fim▁end|>
handle
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__()<|fim▁hole|> self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name<|fim▁end|>
self._canned_results = {}
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): <|fim_middle|> <|fim▁end|>
def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): <|fim_middle|> def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)'
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): <|fim_middle|> def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): <|fim_middle|> def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step)
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): <|fim_middle|> def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
self._canned_results[build.build_id] = results
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): <|fim_middle|> def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): <|fim_middle|> def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
self._webdriver_results[(build, m)] = results
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): <|fim_middle|> def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m))
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): <|fim_middle|> def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
self._canned_retry_summary_json[build] = content
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): <|fim_middle|> def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
return self._canned_retry_summary_json.get(build)
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): <|fim_middle|> def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
self._layout_test_step_name = name
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): <|fim_middle|> <|fim▁end|>
return self._layout_test_step_name
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: <|fim_middle|> return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
rv.extend(results)
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def <|fim_middle|>(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
__init__
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def <|fim_middle|>(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
set_results
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def <|fim_middle|>(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
fetch_results
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def <|fim_middle|>(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
set_results_to_resultdb
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def <|fim_middle|>(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
fetch_results_from_resultdb
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def <|fim_middle|>(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
set_webdriver_test_results
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def <|fim_middle|>(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
fetch_webdriver_test_results
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def <|fim_middle|>(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
set_retry_sumary_json
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def <|fim_middle|>(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
fetch_retry_summary_json
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def <|fim_middle|>(self, name): self._layout_test_step_name = name def get_layout_test_step_name(self, build): return self._layout_test_step_name <|fim▁end|>
set_layout_test_step_name
<|file_name|>results_fetcher_mock.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from collections import namedtuple from blinkpy.common.net.results_fetcher import TestResultsFetcher BuilderStep = namedtuple('BuilderStep', ['build', 'step_name']) # TODO(qyearsley): To be consistent with other fake ("mock") classes, this # could be changed so it's not a subclass of TestResultsFetcher. class MockTestResultsFetcher(TestResultsFetcher): def __init__(self): super(MockTestResultsFetcher, self).__init__() self._canned_results = {} self._canned_retry_summary_json = {} self._webdriver_results = {} self.fetched_builds = [] self.fetched_webdriver_builds = [] self._layout_test_step_name = 'blink_web_tests (with patch)' def set_results(self, build, results, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self._canned_results[step] = results def fetch_results(self, build, full=False, step_name=None): step_name = step_name or self.get_layout_test_step_name(build) step = BuilderStep(build=build, step_name=step_name) self.fetched_builds.append(step) return self._canned_results.get(step) def set_results_to_resultdb(self, build, results): self._canned_results[build.build_id] = results def fetch_results_from_resultdb(self, host, builds, predicate): rv = [] for build in builds: results = self._canned_results.get(build.build_id) if results: rv.extend(results) return rv def set_webdriver_test_results(self, build, m, results): self._webdriver_results[(build, m)] = results def fetch_webdriver_test_results(self, build, m): self.fetched_webdriver_builds.append((build, m)) return self._webdriver_results.get((build, m)) def set_retry_sumary_json(self, build, content): self._canned_retry_summary_json[build] = content def fetch_retry_summary_json(self, build): return self._canned_retry_summary_json.get(build) def set_layout_test_step_name(self, name): self._layout_test_step_name = name def <|fim_middle|>(self, build): return self._layout_test_step_name <|fim▁end|>
get_layout_test_step_name
<|file_name|>global_defaults.py<|end_file_name|><|fim▁begin|>__author__ = 'brianoneill' from log_calls import log_calls global_settings = dict( log_call_numbers=True, log_exit=False, log_retval=True, )<|fim▁hole|><|fim▁end|>
log_calls.set_defaults(global_settings, args_sep=' $ ')
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass<|fim▁hole|> return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True<|fim▁end|>
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): <|fim_middle|> def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): <|fim_middle|> def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return True
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): <|fim_middle|> def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): <|fim_middle|> def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0]
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): <|fim_middle|> def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return check_type(input_value, bytes)
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed <|fim_middle|> def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC <|fim_middle|> <|fim▁end|>
if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): <|fim_middle|> if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return True
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): <|fim_middle|> return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
for value in input_value: if not isinstance(value, value_type): return False return True
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): <|fim_middle|> return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return False
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): <|fim_middle|> try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return True
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: <|fim_middle|> except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return True
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): <|fim_middle|> if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return False
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too <|fim_middle|> else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
if check_type(input_value, (int, long)): return True
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): <|fim_middle|> else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return True
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only <|fim_middle|> sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
if check_type(input_value, int): return True
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): <|fim_middle|> sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return True
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): <|fim_middle|> else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
sequence = False input_value = [input_value]
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: <|fim_middle|> valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
sequence = True # indicates if a sequence must be returned
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: <|fim_middle|> else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
valid_values.append(int(element))
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: <|fim_middle|> except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return False
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: <|fim_middle|> else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return valid_values
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: <|fim_middle|> def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
return valid_values[0]
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element <|fim_middle|> return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
if isinstance(input_value, SEQUENCE_TYPES): input_value = input_value[0] if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE'
<|file_name|>validators.py<|end_file_name|><|fim▁begin|>""" """ # Created on 2016.08.09 # # Author: Giovanni Cannata # # Copyright 2016, 2017 Giovanni Cannata # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from datetime import datetime from ... import SEQUENCE_TYPES, STRING_TYPES from .formatters import format_time from ...utils.conv import to_raw # Validators return True if value is valid, False if value is not valid, # or a value different from True and False that is a valid value to substitute to the input value def check_type(input_value, value_type): if isinstance(input_value, value_type): return True if isinstance(input_value, SEQUENCE_TYPES): for value in input_value: if not isinstance(value, value_type): return False return True return False def always_valid(input_value): return True def validate_generic_single_value(input_value): if not isinstance(input_value, SEQUENCE_TYPES): return True try: # object couldn't have a __len__ method if len(input_value) == 1: return True except Exception: pass return False def validate_integer(input_value): if check_type(input_value, (float, bool)): return False if str is bytes: # Python 2, check for long too if check_type(input_value, (int, long)): return True else: # Python 3, int only if check_type(input_value, int): return True sequence = True # indicates if a sequence must be returned if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] # builds a list of valid int values for element in input_value: try: # try to convert any type to int, an invalid conversion raise TypeError of ValueError, if both are valid and equal then then int() value is used float_value = float(element) int_value = int(element) if float_value == int_value: valid_values.append(int(element)) else: return False except (ValueError, TypeError): return False if sequence: return valid_values else: return valid_values[0] def validate_bytes(input_value): return check_type(input_value, bytes) def validate_boolean(input_value): # it could be a real bool or the string TRUE or FALSE, # only a single valued is allowed if validate_generic_single_value(input_value): # valid only if a single value or a sequence with a single element if isinstance(input_value, SEQUENCE_TYPES): <|fim_middle|> if isinstance(input_value, bool): if input_value: return 'TRUE' else: return 'FALSE' if isinstance(input_value, STRING_TYPES): if input_value.lower() == 'true': return 'TRUE' elif input_value.lower() == 'false': return 'FALSE' return False def validate_time(input_value): # if datetime object doesn't have a timezone it's considered local time and is adjusted to UTC if not isinstance(input_value, SEQUENCE_TYPES): sequence = False input_value = [input_value] else: sequence = True # indicates if a sequence must be returned valid_values = [] changed = False for element in input_value: if isinstance(element, STRING_TYPES): # tries to check if it is already be a Generalized Time if isinstance(format_time(to_raw(element)), datetime): # valid Generalized Time string valid_values.append(element) else: return False elif isinstance(element, datetime): changed = True if element.tzinfo: # a datetime with a timezone valid_values.append(element.strftime('%Y%m%d%H%M%S%z')) else: # datetime without timezone, assumed local and adjusted to UTC offset = datetime.now() - datetime.utcnow() valid_values.append((element - offset).strftime('%Y%m%d%H%M%SZ')) else: return False if changed: if sequence: return valid_values else: return valid_values[0] else: return True <|fim▁end|>
input_value = input_value[0]