INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
statement: CREATE EVENT INSTANCE variable_name OF event_specification TO identifier CLASS
def p_create_class_event_statement(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier CLASS''' p[0] = CreateClassEventNode(variable_name=p[4], event_specification=p[6], key_letter=p[8])
statement: CREATE EVENT INSTANCE variable_name OF event_specification TO identifier ASSIGNER
def p_create_assigner_event_statement(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier ASSIGNER''' p[0] = CreateClassEventNode(variable_name=p[4], event_specification=p[6], key_letter...
statement: CREATE EVENT INSTANCE variable_name OF event_specification TO identifier CREATOR
def p_create_creator_event_statement(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO identifier CREATOR''' p[0] = CreateCreatorEventNode(variable_name=p[4], event_specification=p[6], key_le...
statement: CREATE EVENT INSTANCE variable_name OF event_specification TO variable_access
def p_create_instance_event_statement_1(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO variable_access''' p[0] = CreateInstanceEventNode(variable_name=p[4], event_specification=p[6], to_...
statement: CREATE EVENT INSTANCE variable_name OF event_specification TO self_access
def p_create_instance_event_statement_2(self, p): '''statement : CREATE EVENT INSTANCE variable_name OF event_specification TO self_access''' p[0] = CreateInstanceEventNode(variable_name=p[4], event_specification=p[6], to_vari...
event_specification: identifier event_meaning event_data
def p_event_specification(self, p): '''event_specification : identifier event_meaning event_data''' p[0] = EventSpecNode(identifier=p[1], meaning=p[2], event_data=p[3])
event_specification: identifier TIMES event_meaning event_data
def p_ploymorphic_event_spec(self, p): '''event_specification : identifier TIMES event_meaning event_data''' p[0] = EventSpecNode(identifier=p[1], meaning=p[3], event_data=p[4])
statement: FOR EACH variable_name IN variable_name block END_FOR
def p_for_statement(self, p): '''statement : FOR EACH variable_name IN variable_name block END_FOR''' p[0] = ForEachNode(instance_variable_name=p[3], set_variable_name=p[5], block=p[6])
statement: IF expression block elif_list else_clause END_IF
def p_if_statement(self, p): '''statement : IF expression block elif_list else_clause END_IF''' p[0] = IfNode(expression=p[2], block=p[3], elif_list=p[4], else_clause=p[5])
statement: RELATE instance_name TO instance_name ACROSS rel_id
def p_relate_statement_1(self, p): '''statement : RELATE instance_name TO instance_name ACROSS rel_id''' p[0] = RelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=None)
statement: RELATE instance_name TO instance_name ACROSS rel_id DOT phrase
def p_relate_statement_2(self, p): '''statement : RELATE instance_name TO instance_name ACROSS rel_id DOT phrase''' p[0] = RelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=p[8])
statement: RELATE instance_name TO instance_name ACROSS rel_id USING instance_name
def p_relate_using_statement_1(self, p): '''statement : RELATE instance_name TO instance_name ACROSS rel_id USING instance_name''' p[0] = RelateUsingNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], ...
statement: UNRELATE instance_name FROM instance_name ACROSS rel_id
def p_unrelate_statement_1(self, p): '''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id''' p[0] = UnrelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=None)
statement: UNRELATE instance_name FROM instance_name ACROSS rel_id DOT phrase
def p_unrelate_statement_2(self, p): '''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id DOT phrase''' p[0] = UnrelateNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], phrase=p[8])
statement: UNRELATE instance_name FROM instance_name ACROSS rel_id USING instance_name
def p_unrelate_statement_using_1(self, p): '''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id USING instance_name''' p[0] = UnrelateUsingNode(from_variable_name=p[2], to_variable_name=p[4], rel_id=p[6], ...
statement: SELECT ANY variable_name FROM INSTANCES OF identifier | SELECT MANY variable_name FROM INSTANCES OF identifier
def p_select_from_statement_1(self, p): ''' statement : SELECT ANY variable_name FROM INSTANCES OF identifier | SELECT MANY variable_name FROM INSTANCES OF identifier ''' p[0] = SelectFromNode(cardinality=p[2], variable_name=p[3], ...
statement: SELECT ANY variable_name FROM identifier | SELECT MANY variable_name FROM identifier
def p_select_from_statement_2(self, p): ''' statement : SELECT ANY variable_name FROM identifier | SELECT MANY variable_name FROM identifier ''' p[0] = SelectFromNode(cardinality=p[2], variable_name=p[3], key_l...
statement: SELECT ANY variable_name FROM INSTANCES OF identifier WHERE expression | SELECT MANY variable_name FROM INSTANCES OF identifier WHERE expression
def p_select_from_where_statement_1(self, p): ''' statement : SELECT ANY variable_name FROM INSTANCES OF identifier WHERE expression | SELECT MANY variable_name FROM INSTANCES OF identifier WHERE expression ''' p[0] = SelectFromWhereNode(cardinality=p[2], ...
statement: SELECT ANY variable_name FROM identifier WHERE expression | SELECT MANY variable_name FROM identifier WHERE expression
def p_select_from_where_statement_2(self, p): ''' statement : SELECT ANY variable_name FROM identifier WHERE expression | SELECT MANY variable_name FROM identifier WHERE expression ''' p[0] = SelectFromWhereNode(cardinality=p[2], varia...
statement: SELECT ONE variable_name RELATED BY navigation_hook navigation_chain | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain | SELECT MANY variable_name RELATED BY navigation_hook navigation_chain
def p_select_related_statement(self, p): ''' statement : SELECT ONE variable_name RELATED BY navigation_hook navigation_chain | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain | SELECT MANY variable_name RELATED BY navigation_hook navigation_cha...
statement: SELECT ONE variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT MANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression
def p_select_related_where_statement(self, p): ''' statement : SELECT ONE variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT ANY variable_name RELATED BY navigation_hook navigation_chain WHERE expression | SELECT MANY variable_name R...
navigation_step: ARROW identifier LSQBR identifier RSQBR
def p_navigation_step_1(self, p): '''navigation_step : ARROW identifier LSQBR identifier RSQBR''' p[0] = NavigationStepNode(key_letter=p[2], rel_id=p[4], phrase=None)
navigation_step: ARROW identifier LSQBR identifier DOT phrase RSQBR
def p_navigation_step_2(self, p): '''navigation_step : ARROW identifier LSQBR identifier DOT phrase RSQBR''' p[0] = NavigationStepNode(key_letter=p[2], rel_id=p[4], phrase=p[6])
implicit_invocation: namespace DOUBLECOLON identifier LPAREN parameter_list RPAREN
def p_implicit_invocation(self, p): '''implicit_invocation : namespace DOUBLECOLON identifier LPAREN parameter_list RPAREN''' p[0] = ImplicitInvocationNode(namespace=p[1], action_name=p[3], parameter_list=p[5])
instance_invocation: structure DOT identifier LPAREN parameter_list RPAREN
def p_operation_invocation_1(self, p): '''instance_invocation : structure DOT identifier LPAREN parameter_list RPAREN''' p[0] = InstanceInvocationNode(handle=p[1], action_name=p[3], parameter_list=p[5])
expression: expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIV expression | expression MOD expression
def p_arithmetic_expression(self, p): ''' expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIV expression | expression MOD expression ''' p[0] ...
expression: expression LE expression | expression LESSTHAN expression | expression DOUBLEEQUAL expression | expression NOTEQUAL expression | expression GE expression | expression GT expression | expression AND expression | expression OR expression
def p_boolean_expression(self, p): ''' expression : expression LE expression | expression LESSTHAN expression | expression DOUBLEEQUAL expression | expression NOTEQUAL expression | expression GE expressio...
Wraps exceptions in the context with: exc: MalformedMessage.
def wrap(cls, message_parts): """Wraps exceptions in the context with :exc:`MalformedMessage`.""" try: yield except BaseException as exception: __, __, tb = sys.exc_info() reraise(cls, cls(exception, message_parts), tb)
Gets the crime nearby to a given postcode.: param request: The aiohttp request.: return: A json representation of the crimes near the postcode.
async def api_crime(request): """ Gets the crime nearby to a given postcode. :param request: The aiohttp request. :return: A json representation of the crimes near the postcode. """ postcode: Optional[str] = request.match_info.get('postcode', None) try: coroutine = get_postcode_rand...
Gets police data about a neighbourhood.: param request: The aiohttp request.: return: The police data for that post code.
async def api_neighbourhood(request): """ Gets police data about a neighbourhood. :param request: The aiohttp request. :return: The police data for that post code. """ postcode: Optional[str] = request.match_info.get('postcode', None) try: postcode = (await get_postcode_random()) if...
Create message content and properties to create queue with QMFv2
def create_queue(self, name, strict=True, auto_delete=False, auto_delete_timeout=0): """Create message content and properties to create queue with QMFv2 :param name: Name of queue to create :type name: str :param strict: Whether command should fail when unrecognized properties are provi...
Create message content and properties to delete queue with QMFv2
def delete_queue(self, name): """Create message content and properties to delete queue with QMFv2 :param name: Name of queue to delete :type name: str :returns: Tuple containing content and method properties """ content = {"_object_id": {"_object_name": self.object_name...
Create message content and properties to list all queues with QMFv2
def list_queues(self): """Create message content and properties to list all queues with QMFv2 :returns: Tuple containing content and query properties """ content = {"_what": "OBJECT", "_schema_id": {"_class_name": "queue"}} logger.debug("Message content -> {0}...
Create message content and properties to list all exchanges with QMFv2
def list_exchanges(self): """Create message content and properties to list all exchanges with QMFv2 :returns: Tuple containing content and query properties """ content = {"_what": "OBJECT", "_schema_id": {"_class_name": "exchange"}} logger.debug("Message conte...
Create message content and properties to purge queue with QMFv2
def purge_queue(self, name): """Create message content and properties to purge queue with QMFv2 :param name: Name of queue to purge :type name: str :returns: Tuple containing content and method properties """ content = {"_object_id": {"_object_name": "org.apache.qpid.br...
attachments should be a list of paths
def _create_msg(self, to, subject, msgHtml, msgPlain, attachments=None): ''' attachments should be a list of paths ''' sender = self.sender if attachments and isinstance(attachments, str): attachments = [attachments] else: attachments = list(attach...
Raises an exception as a: exc: RemoteException.
def set_remote_exception(self, remote_exc_info): """Raises an exception as a :exc:`RemoteException`.""" exc_type, exc_str, filename, lineno = remote_exc_info[:4] exc_type = RemoteException.compose(exc_type) exc = exc_type(exc_str, filename, lineno, self.worker_info) if len(remote...
Returns the text from an image at a given url.
def read(self): """ Returns the text from an image at a given url. """ # Only download the image if it has changed if self.connection.has_changed(): image_path = self.connection.download_image() image = Image.open(image_path) self.text_cache =...
Returns true or false based on if the OCR process has read actual words. This is needed to prevent non - words from being added to the queue since the ocr process can sometimes return values that are not meaningfull.
def text_visible(self): """ Returns true or false based on if the OCR process has read actual words. This is needed to prevent non-words from being added to the queue since the ocr process can sometimes return values that are not meaningfull. """ # Split the inpu...
Gets the most recently cached bike from the database.: return: The bike that was cached most recently.
def get_most_recent_bike() -> Optional['Bike']: """ Gets the most recently cached bike from the database. :return: The bike that was cached most recently. """ try: return Bike.select().order_by(Bike.cached_date.desc()).get() except pw.DoesNotExist: ...
Parse command line options and launch the interpreter
def main(): ''' Parse command line options and launch the interpreter ''' parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path..]", version=xtuml.version.complete_string, formatter=optparse.TitledHelp...
Parse argv for options and arguments and start schema generation.
def main(): ''' Parse argv for options and arguments, and start schema generation. ''' parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path...]", version=xtuml.version.complete_string, formatter=optpa...
See: http:// nodotcom. org/ python - facebook - tutorial. html
def get_token(client_id, client_secret, client_access_token, page=None): """ See: http://nodotcom.org/python-facebook-tutorial.html """ payload = { 'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret, } if client_access_token: ...
You can also skip the above if you get a page token: http:// stackoverflow. com/ questions/ 8231877 and make that long - lived token as in Step 3
def get_page_api(client_access_token, page_id): """ You can also skip the above if you get a page token: http://stackoverflow.com/questions/8231877 and make that long-lived token as in Step 3 """ graph = GraphAPI(client_access_token) # Get page token to post as the page. You can skip # t...
Serialize a value from an xtuml metamodel instance.
def serialize_value(value, ty): ''' Serialize a value from an xtuml metamodel instance. ''' ty = ty.upper() null_value = { 'BOOLEAN' : False, 'INTEGER' : 0, 'REAL' : 0.0, 'STRING' : '', 'UNIQUE_ID' : 0 } transfer_fn = { 'B...
Serialize an * instance * from a metamodel.
def serialize_instance(instance): ''' Serialize an *instance* from a metamodel. ''' attr_count = 0 metaclass = xtuml.get_metaclass(instance) s = 'INSERT INTO %s VALUES (' % metaclass.kind for name, ty in metaclass.attributes: value = getattr(instance, name) s += ...
Serialize all instances in a * metamodel *.
def serialize_instances(metamodel): ''' Serialize all instances in a *metamodel*. ''' s = '' for inst in metamodel.instances: s += serialize_instance(inst) return s
Serialize an xtuml metamodel association.
def serialize_association(ass): ''' Serialize an xtuml metamodel association. ''' s1 = '%s %s (%s)' % (ass.source_link.cardinality, ass.source_link.to_metaclass.kind, ', '.join(ass.source_keys)) if ass.target_link.phrase: s1 += " PHRASE '%s'...
Serialize an xtUML metamodel class.
def serialize_class(Cls): ''' Serialize an xtUML metamodel class. ''' metaclass = xtuml.get_metaclass(Cls) attributes = ['%s %s' % (name, ty.upper()) for name, ty in metaclass.attributes] s = 'CREATE TABLE %s (\n ' % metaclass.kind s += ',\n '.join(attributes) s += '\n);\n' ...
Serialize all class and association definitions in a * metamodel *.
def serialize_schema(metamodel): ''' Serialize all class and association definitions in a *metamodel*. ''' s = '' for kind in sorted(metamodel.metaclasses.keys()): s += serialize_class(metamodel.metaclasses[kind].clazz) for ass in sorted(metamodel.associations, key=lambda x: x.rel_i...
Serialize all instances class definitions association definitions and unique identifiers in a * metamodel *.
def serialize_database(metamodel): ''' Serialize all instances, class definitions, association definitions, and unique identifiers in a *metamodel*. ''' schema = serialize_schema(metamodel) instances = serialize_instances(metamodel) identifiers = serialize_unique_identifiers(metamodel) ...
Serialize some xtuml * resource * e. g. an instance or a complete metamodel.
def serialize(resource): ''' Serialize some xtuml *resource*, e.g. an instance or a complete metamodel. ''' if isinstance(resource, xtuml.MetaModel): return serialize_database(resource) elif isinstance(resource, type) and issubclass(resource, xtuml.Class): return serialize_class(res...
Persist all instances in a * metamodel * by serializing them and saving to a * path * on disk.
def persist_instances(metamodel, path, mode='w'): ''' Persist all instances in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for inst in metamodel.instances: s = serialize_instance(inst) f.write(s)
Persist all class and association definitions in a * metamodel * by serializing them and saving to a * path * on disk.
def persist_schema(metamodel, path, mode='w'): ''' Persist all class and association definitions in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for kind in sorted(metamodel.metaclasses.keys()): s = serialize_class(metamodel.m...
Persist all unique identifiers in a * metamodel * by serializing them and saving to a * path * on disk.
def persist_unique_identifiers(metamodel, path, mode='w'): ''' Persist all unique identifiers in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for metaclass in metamodel.metaclasses.values(): for index_name, attribute_names in m...
Persist all instances class definitions and association definitions in a * metamodel * by serializing them and saving to a * path * on disk.
def persist_database(metamodel, path, mode='w'): ''' Persist all instances, class definitions and association definitions in a *metamodel* by serializing them and saving to a *path* on disk. ''' with open(path, mode) as f: for kind in sorted(metamodel.metaclasses.keys()): metacla...
Save variable on given path using Pickle Args: variable: what to save path ( str ): path of the output
def save(variable, filename): """Save variable on given path using Pickle Args: variable: what to save path (str): path of the output """ fileObj = open(filename, 'wb') pickle.dump(variable, fileObj) fileObj.close()
Load variable from Pickle file Args: path ( str ): path of the file to load
def load(filename): """Load variable from Pickle file Args: path (str): path of the file to load Returns: variable read from path """ fileObj = open(filename, 'rb') variable = pickle.load(fileObj) fileObj.close() return variable
Function for command line execution
def main(): """Function for command line execution""" parser = ArgumentParser(description="search files using n-grams") parser.add_argument('--path', dest='path', help="where to search", nargs=1, action="store", default=getcwd()) parser.add_argument('--update', dest='update', help="update the index", a...
Searches files satisfying query
def search(self, query, verbose=0): """Searches files satisfying query It first decompose the query in ngrams, then score each document containing at least one ngram with the number. The ten document having the most ngrams in common with the query are selected. Args: ...
Partitions a list into two based on a condition.
def partition(condition, collection) -> Tuple[List, List]: """Partitions a list into two based on a condition.""" succeed, fail = [], [] for x in collection: if condition(x): succeed.append(x) else: fail.append(x) return succeed, fail
Runs the CLI app. Tries to execute as many steps as possible to give the user the best understanding of the errors ( if there are any ).
async def cli(location_strings: Tuple[str], random_postcodes_count: int, *, bikes: bool = False, crime: bool = False, nearby: bool = False, as_json: bool = False): """ Runs the CLI app. Tries to execute as many steps as possible to give the user the best understanding of the ...
Gets the neighbourhood from the fetch that is associated with the given postcode.: return: A neighbourhood object parsed from the fetch.: raise ApiError: When there was an error connecting to the API.
async def fetch_neighbourhood(lat: float, long: float) -> Optional[dict]: """ Gets the neighbourhood from the fetch that is associated with the given postcode. :return: A neighbourhood object parsed from the fetch. :raise ApiError: When there was an error connecting to the API. """ lookup_url =...
Gets crime for a given lat and long.: raise ApiError: When there was an error connecting to the API.
async def fetch_crime(lat: float, long: float) -> List[Dict]: """ Gets crime for a given lat and long. :raise ApiError: When there was an error connecting to the API. todo cache """ crime_lookup = f"https://data.police.uk/api/crimes-street/all-crime?lat={lat}&lng={long}" async with ClientSe...
Runs the program. Takes a list of postcodes or coordinates and returns various information about them. If using the cli make sure to update the bikes database with the - u command.
def run(locations, random, bikes, crime, nearby, json, update_bikes, api_server, cross_origin, host, port, db_path, verbose): """ Runs the program. Takes a list of postcodes or coordinates and returns various information about them. If using the cli, make sure to update the bikes database with t...
Adds to the context BiDi related variables
def bidi(request): """Adds to the context BiDi related variables LANGUAGE_DIRECTION -- Direction of current language ('ltr' or 'rtl') LANGUAGE_START -- Start of language layout ('right' for rtl, 'left' for 'ltr') LANGUAGE_END -- End of language layout ('left' for rtl, 'right' ...
Determine if an attribute of an * instance * with a specific * name * is null.
def _is_null(instance, name): ''' Determine if an attribute of an *instance* with a specific *name* is null. ''' if name in instance.__dict__: value = instance.__dict__[name] else: value = getattr(instance, name) if value: return False elif value is None: ...
Apply a series of query operators to a sequence of instances e. g. where_eq () order_by () or filter functions.
def apply_query_operators(iterable, ops): ''' Apply a series of query operators to a sequence of instances, e.g. where_eq(), order_by() or filter functions. ''' for op in ops: if isinstance(op, WhereEqual): iterable = op(iterable) elif isinstance(op, OrderBy)...
Perform a navigation from * supertype * to its subtype across * rel_id *. The navigated association must be modeled as a subtype - supertype association. The return value will an instance or None.
def navigate_subtype(supertype, rel_id): ''' Perform a navigation from *supertype* to its subtype across *rel_id*. The navigated association must be modeled as a subtype-supertype association. The return value will an instance or None. ''' if not supertype: return if isinst...
Sort a * set of instances * in the order they appear across a conditional and reflexive association. The first instance in the resulting ordered set is ** not ** associated to an instance across the given * phrase *.
def sort_reflexive(set_of_instances, rel_id, phrase): ''' Sort a *set of instances* in the order they appear across a conditional and reflexive association. The first instance in the resulting ordered set is **not** associated to an instance across the given *phrase*. ''' if not isinstance(set_o...
Find links that correspond to the given arguments.
def _find_link(inst1, inst2, rel_id, phrase): ''' Find links that correspond to the given arguments. ''' metaclass1 = get_metaclass(inst1) metaclass2 = get_metaclass(inst2) if isinstance(rel_id, int): rel_id = 'R%d' % rel_id for ass in metaclass1.metamodel.associations: ...
Relate * from_instance * to * to_instance * across * rel_id *. For reflexive association a * phrase * indicating the direction must also be provided. The two instances are related to each other by copying the identifying attributes from the instance on the TO side of a association to the instance n the FROM side. Updat...
def relate(from_instance, to_instance, rel_id, phrase=''): ''' Relate *from_instance* to *to_instance* across *rel_id*. For reflexive association, a *phrase* indicating the direction must also be provided. The two instances are related to each other by copying the identifying attributes from t...
Unrelate * from_instance * from * to_instance * across * rel_id *. For reflexive associations a * phrase * indicating the direction must also be provided. The two instances are unrelated from each other by reseting the identifying attributes on the FROM side of the association. Updated values which affect existing asso...
def unrelate(from_instance, to_instance, rel_id, phrase=''): ''' Unrelate *from_instance* from *to_instance* across *rel_id*. For reflexive associations, a *phrase* indicating the direction must also be provided. The two instances are unrelated from each other by reseting the identifying attrib...
Get the metaclass for a * class_or_instance *.
def get_metaclass(class_or_instance): ''' Get the metaclass for a *class_or_instance*. ''' if isinstance(class_or_instance, Class): return class_or_instance.__metaclass__ elif issubclass(class_or_instance, Class): return class_or_instance.__metaclass__ raise MetaExcepti...
Delete an * instance * from its metaclass instance pool and optionally * disconnect * it from any links it might be connected to.
def delete(instance, disconnect=True): ''' Delete an *instance* from its metaclass instance pool and optionally *disconnect* it from any links it might be connected to. ''' if not isinstance(instance, Class): raise DeleteException("the provided argument is not an xtuml instance") ...
Formalize the association and expose referential attributes on instances.
def formalize(self): ''' Formalize the association and expose referential attributes on instances. ''' source_class = self.source_link.to_metaclass target_class = self.target_link.to_metaclass source_class.referential_attributes |= set(self.source_keys) ...
Obtain the cardinality string. Example: 1C for a conditional link with a single instance [ 0.. 1 ] MC for a link with any number of instances [ 0.. * ] M for a more than one instance [ 1.. * ] M for a link with exactly one instance [ 1 ]
def cardinality(self): ''' Obtain the cardinality string. Example: '1C' for a conditional link with a single instance [0..1] 'MC' for a link with any number of instances [0..*] 'M' for a more than one instance [1..*] 'M' for a link wi...
Connect an * instance * to * another_instance *. Optionally disable any cardinality * check * that would prevent the two instances from being connected.
def connect(self, instance, another_instance, check=True): ''' Connect an *instance* to *another_instance*. Optionally, disable any cardinality *check* that would prevent the two instances from being connected. ''' if instance not in self: self[instan...
Disconnect an * instance * from * another_instance *.
def disconnect(self, instance, another_instance): ''' Disconnect an *instance* from *another_instance*. ''' if instance not in self: return False if another_instance not in self[instance]: return False self[instance].remove(another_insta...
Compute the lookup key for an instance i. e. a foreign key that can be used to identify an instance at the end of the link.
def compute_lookup_key(self, from_instance): ''' Compute the lookup key for an instance, i.e. a foreign key that can be used to identify an instance at the end of the link. ''' kwargs = dict() for attr, other_attr in self.key_map.items(): if _is_null(from_inst...
Compute the index key that can be used to identify an instance on the link.
def compute_index_key(self, to_instance): ''' Compute the index key that can be used to identify an instance on the link. ''' kwargs = dict() for attr in self.key_map.values(): if _is_null(to_instance, attr): return None ...
Obtain the type of an attribute.
def attribute_type(self, attribute_name): ''' Obtain the type of an attribute. ''' attribute_name = attribute_name.upper() for name, ty in self.attributes: if name.upper() == attribute_name: return ty
Add a new link from * self * to * metaclass *.
def add_link(self, metaclass, rel_id, phrase, conditional, many): ''' Add a new link from *self* to *metaclass*. ''' link = Link(self, rel_id, metaclass, phrase, conditional, many) key = (metaclass.kind.upper(), rel_id, phrase) self.links[key] = link return link
Append an attribute with a given * name * and * type name * at the end of the list of attributes.
def append_attribute(self, name, type_name): ''' Append an attribute with a given *name* and *type name* at the end of the list of attributes. ''' attr = (name, type_name) self.attributes.append(attr)
Insert an attribute with a given * name * and * type name * at some * index * in the list of attributes.
def insert_attribute(self, index, name, type_name): ''' Insert an attribute with a given *name* and *type name* at some *index* in the list of attributes. ''' attr = (name, type_name) self.attributes.insert(index, attr)
Delete an attribute with a given * name * from the list of attributes.
def delete_attribute(self, name): ''' Delete an attribute with a given *name* from the list of attributes. ''' for idx, attr in enumerate(self.attributes): attr_name, _ = attr if attr_name == name: del self.attributes[idx] return
Obtain the default value for some * type name *.
def default_value(self, type_name): ''' Obtain the default value for some *type name*. ''' uname = type_name.upper() if uname == 'BOOLEAN': return False elif uname == 'INTEGER': return 0 elif uname == 'REAL': ...
Create and return a new instance.
def new(self, *args, **kwargs): ''' Create and return a new instance. ''' inst = self.clazz() self.storage.append(inst) # set all attributes with an initial default value referential_attributes = dict() for name, ty in self.attributes: ...
Create a shallow clone of an * instance *. ** Note: ** the clone and the original instance ** does not ** have to be part of the same metaclass.
def clone(self, instance): ''' Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass. ''' args = list() for name, _ in get_metaclass(instance).attributes: val...
Delete an * instance * from the instance pool and optionally * disconnect * it from any links it might be connected to. If the * instance * is not part of the metaclass a * MetaException * is thrown.
def delete(self, instance, disconnect=True): ''' Delete an *instance* from the instance pool and optionally *disconnect* it from any links it might be connected to. If the *instance* is not part of the metaclass, a *MetaException* is thrown. ''' if instance in self.storag...
Select a single instance from the instance pool. Query operators such as where_eq () order_by () or filter functions may be passed as optional arguments.
def select_one(self, *args): ''' Select a single instance from the instance pool. Query operators such as where_eq(), order_by() or filter functions may be passed as optional arguments. ''' s = apply_query_operators(self.storage, args) return next(iter(s), None)
Select several instances from the instance pool. Query operators such as where_eq () order_by () or filter functions may be passed as optional arguments.
def select_many(self, *args): ''' Select several instances from the instance pool. Query operators such as where_eq(), order_by() or filter functions may be passed as optional arguments. ''' s = apply_query_operators(self.storage, args) if isinstance(s, QuerySet):...
Navigate across a link with some * rel_id * and * phrase * that yields instances of some * kind *.
def navigate(self, inst, kind, rel_id, phrase=''): ''' Navigate across a link with some *rel_id* and *phrase* that yields instances of some *kind*. ''' key = (kind.upper(), rel_id, phrase) if key in self.links: link = self.links[key] return link.na...
Obtain a sequence of all instances in the metamodel.
def instances(self): ''' Obtain a sequence of all instances in the metamodel. ''' for metaclass in self.metaclasses.values(): for inst in metaclass.storage: yield inst
Define a new class in the metamodel and return its metaclass.
def define_class(self, kind, attributes, doc=''): ''' Define a new class in the metamodel, and return its metaclass. ''' ukind = kind.upper() if ukind in self.metaclasses: raise MetaModelException('A class with the name %s is already defined' % kind) metaclas...
Find a metaclass of some * kind * in the metamodel.
def find_metaclass(self, kind): ''' Find a metaclass of some *kind* in the metamodel. ''' ukind = kind.upper() if ukind in self.metaclasses: return self.metaclasses[ukind] else: raise UnknownClassException(kind)
Create and return a new instance in the metamodel of some * kind *. Optionally initial attribute values may be assigned to the new instance by passing them as positional or keyword arguments. Positional arguments are assigned in the order in which they appear in the metaclass.
def new(self, kind, *args, **kwargs): ''' Create and return a new instance in the metamodel of some *kind*. Optionally, initial attribute values may be assigned to the new instance by passing them as positional or keyword arguments. Positional arguments are assigned in t...
Create a shallow clone of an * instance *. ** Note: ** the clone and the original instance ** does not ** have to be part of the same metaclass.
def clone(self, instance): ''' Create a shallow clone of an *instance*. **Note:** the clone and the original instance **does not** have to be part of the same metaclass. ''' metaclass = get_metaclass(instance) metaclass = self.find_metaclass(metaclass.ki...
Define and return an association from one kind of class ( the source kind ) to some other kind of class ( the target kind ).
def define_association(self, rel_id, source_kind, source_keys, source_many, source_conditional, source_phrase, target_kind, target_keys, target_many, target_conditional, target_phrase): ''' Define and return an associatio...
Define a unique identifier for some * kind * of class based on its * named attributes *.
def define_unique_identifier(self, kind, name, *named_attributes): ''' Define a unique identifier for some *kind* of class based on its *named attributes*. ''' if not named_attributes: return if isinstance(name, int): name = 'I%d' % name ...