INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Initialize the logger
def init_logger(log_requests=False): """ Initialize the logger """ logger = logging.getLogger(__name__.split(".")[0]) for handler in logger.handlers: # pragma: nocover logger.removeHandler(handler) formatter = coloredlogs.ColoredFormatter(fmt="%(asctime)s: %(message)s") handler = logging....
Close the connection.
def close(self): """Close the connection.""" if self.connection: self.connection.close() self.connection = None logging.debug("Connection closed.")
Send a control command.
def control(self, key): """Send a control command.""" if not self.connection: raise exceptions.ConnectionClosed() payload = json.dumps({ "method": "ms.remote.control", "params": { "Cmd": "Click", "DataOfCmd": key, ...
Send a control command.
def control(self, key): """Send a control command.""" if not self.connection: raise exceptions.ConnectionClosed() payload = b"\x00\x00\x00" + self._serialize_string(key) packet = b"\x00\x00\x00" + self._serialize_string(payload, True) logging.info("Sending control c...
Factory method, registers new node.
def register_new_node(suffix_node_id=None): """Factory method, registers new node. """ node_id = uuid4() event = Node.Created(originator_id=node_id, suffix_node_id=suffix_node_id) entity = Node.mutate(event=event) publish(event) return entity
Factory method, registers new edge.
def register_new_edge(edge_id, first_char_index, last_char_index, source_node_id, dest_node_id): """Factory method, registers new edge. """ event = Edge.Created( originator_id=edge_id, first_char_index=first_char_index, last_char_index=last_char_index, source_node_id=source_n...
Factory method, returns new suffix tree object.
def register_new_suffix_tree(case_insensitive=False): """Factory method, returns new suffix tree object. """ assert isinstance(case_insensitive, bool) root_node = register_new_node() suffix_tree_id = uuid4() event = SuffixTree.Created( originator_id=suffix_tree_id, root_node_id=...
Returns the index if substring in tree, otherwise -1.
def find_substring(substring, suffix_tree, edge_repo): """Returns the index if substring in tree, otherwise -1. """ assert isinstance(substring, str) assert isinstance(suffix_tree, SuffixTree) assert isinstance(edge_repo, EventSourcedRepository) if not substring: return -1 if suffix_...
The core construction method.
def _add_prefix(self, last_char_index): """The core construction method. """ last_parent_node_id = None while True: parent_node_id = self.active.source_node_id if self.active.explicit(): edge_id = make_edge_id(self.active.source_node_id, self.strin...
This canonizes the suffix, walking along its suffix string until it is explicit or there are no more matched nodes.
def _canonize_suffix(self, suffix): """This canonizes the suffix, walking along its suffix string until it is explicit or there are no more matched nodes. """ if not suffix.explicit(): edge_id = make_edge_id(suffix.source_node_id, self.string[suffix.first_char_index]) ...
Reconstructs domain entity from given snapshot.
def entity_from_snapshot(snapshot): """ Reconstructs domain entity from given snapshot. """ assert isinstance(snapshot, AbstractSnapshop), type(snapshot) if snapshot.state is not None: entity_class = resolve_topic(snapshot.topic) return reconstruct_object(entity_class, snapshot.state...
Gets the last snapshot for entity, optionally until a particular version number. :rtype: Snapshot
def get_snapshot(self, entity_id, lt=None, lte=None): """ Gets the last snapshot for entity, optionally until a particular version number. :rtype: Snapshot """ snapshots = self.snapshot_store.get_domain_events(entity_id, lt=lt, lte=lte, limit=1, is_ascending=False) if le...
Creates a Snapshot from the given state, and appends it to the snapshot store. :rtype: Snapshot
def take_snapshot(self, entity_id, entity, last_event_version): """ Creates a Snapshot from the given state, and appends it to the snapshot store. :rtype: Snapshot """ # Create the snapshot. snapshot = Snapshot( originator_id=entity_id, o...
Returns entity with given ID, optionally until position.
def get_entity(self, entity_id, at=None): """ Returns entity with given ID, optionally until position. """ # Get a snapshot (None if none exist). if self._snapshot_strategy is not None: snapshot = self._snapshot_strategy.get_snapshot(entity_id, lte=at) else: ...
Reconstitutes requested domain entity from domain events found in event store.
def get_and_project_events(self, entity_id, gt=None, gte=None, lt=None, lte=None, limit=None, initial_state=None, query_descending=False): """ Reconstitutes requested domain entity from domain events found in event store. """ # Decide if query is in ascendi...
Takes a snapshot of the entity as it existed after the most recent event, optionally less than, or less than or equal to, a particular position.
def take_snapshot(self, entity_id, lt=None, lte=None): """ Takes a snapshot of the entity as it existed after the most recent event, optionally less than, or less than or equal to, a particular position. """ snapshot = None if self._snapshot_strategy: # Get th...
Entity object factory.
def create_new_example(self, foo='', a='', b=''): """Entity object factory.""" return create_new_example(foo=foo, a=a, b=b)
Returns an integer value representing a unix timestamp in tenths of microseconds. :param uuid_arg: :return: Unix timestamp integer in tenths of microseconds. :rtype: int
def timestamp_long_from_uuid(uuid_arg): """ Returns an integer value representing a unix timestamp in tenths of microseconds. :param uuid_arg: :return: Unix timestamp integer in tenths of microseconds. :rtype: int """ if isinstance(uuid_arg, str): uuid_arg = UUID(uuid_arg) asser...
A UNIX timestamp as a Decimal object (exact number type). Returns current time when called without args, otherwise converts given floating point number ``t`` to a Decimal with 9 decimal places. :param t: Floating point UNIX timestamp ("seconds since epoch"). :return: A Decimal with 6 decimal place...
def decimaltimestamp(t=None): """ A UNIX timestamp as a Decimal object (exact number type). Returns current time when called without args, otherwise converts given floating point number ``t`` to a Decimal with 9 decimal places. :param t: Floating point UNIX timestamp ("seconds since epoch"). ...
Decorator for making a custom event handler function subscribe to a certain class of event. The decorated function will be called once for each matching event that is published, and will be given one argument, the event, when it is called. If events are published in lists, for example the AggregateRoot pub...
def subscribe_to(*event_classes): """ Decorator for making a custom event handler function subscribe to a certain class of event. The decorated function will be called once for each matching event that is published, and will be given one argument, the event, when it is called. If events are published i...
Structures mutator functions by allowing handlers to be registered for different types of event. When the decorated function is called with an initial value and an event, it will call the handler that has been registered for that type of event. It works like singledispatch, which it uses. The d...
def mutator(arg=None): """Structures mutator functions by allowing handlers to be registered for different types of event. When the decorated function is called with an initial value and an event, it will call the handler that has been registered for that type of event. It works like singledisp...
When used as a method decorator, returns a property object with the method as the getter and a setter defined to call instance method change_attribute(), which publishes an AttributeChanged event.
def attribute(getter): """ When used as a method decorator, returns a property object with the method as the getter and a setter defined to call instance method change_attribute(), which publishes an AttributeChanged event. """ if isfunction(getter): def setter(self, value): ...
Return ciphertext for given plaintext.
def encrypt(self, plaintext): """Return ciphertext for given plaintext.""" # String to bytes. plainbytes = plaintext.encode('utf8') # Compress plaintext bytes. compressed = zlib.compress(plainbytes) # Construct AES-GCM cipher, with 96-bit nonce. cipher = AES.ne...
Return plaintext for given ciphertext.
def decrypt(self, ciphertext): """Return plaintext for given ciphertext.""" # String to bytes. cipherbytes = ciphertext.encode('utf8') # Decode from Base64. try: combined = base64.b64decode(cipherbytes) except (base64.binascii.Error, TypeError) as e: ...
Returns domain events for given entity ID.
def get_domain_events(self, originator_id, gt=None, gte=None, lt=None, lte=None, limit=None, is_ascending=True, page_size=None): """ Returns domain events for given entity ID. """
Appends given domain event, or list of domain events, to their sequence. :param domain_event_or_events: domain event, or list of domain events
def store(self, domain_event_or_events): """ Appends given domain event, or list of domain events, to their sequence. :param domain_event_or_events: domain event, or list of domain events """ # Convert to sequenced item. sequenced_item_or_items = self.item_from_event(do...
Maps domain event to sequenced item namedtuple. :param domain_event_or_events: application-level object (or list) :return: namedtuple: sequence item namedtuple (or list)
def item_from_event(self, domain_event_or_events): """ Maps domain event to sequenced item namedtuple. :param domain_event_or_events: application-level object (or list) :return: namedtuple: sequence item namedtuple (or list) """ # Convert the domain event(s) to sequenced...
Gets domain events from the sequence identified by `originator_id`. :param originator_id: ID of a sequence of events :param gt: get items after this position :param gte: get items at or after this position :param lt: get items before this position :param lte: get items before or...
def get_domain_events(self, originator_id, gt=None, gte=None, lt=None, lte=None, limit=None, is_ascending=True, page_size=None): """ Gets domain events from the sequence identified by `originator_id`. :param originator_id: ID of a sequence of events :param gt: ...
Gets a domain event from the sequence identified by `originator_id` at position `eq`. :param originator_id: ID of a sequence of events :param position: get item at this position :return: domain event
def get_domain_event(self, originator_id, position): """ Gets a domain event from the sequence identified by `originator_id` at position `eq`. :param originator_id: ID of a sequence of events :param position: get item at this position :return: domain event """ ...
Gets a domain event from the sequence identified by `originator_id` at the highest position. :param originator_id: ID of a sequence of events :param lt: get highest before this position :param lte: get highest at or before this position :return: domain event
def get_most_recent_event(self, originator_id, lt=None, lte=None): """ Gets a domain event from the sequence identified by `originator_id` at the highest position. :param originator_id: ID of a sequence of events :param lt: get highest before this position :param lte: ge...
Yields all domain events in the event store.
def all_domain_events(self): """ Yields all domain events in the event store. """ for originator_id in self.record_manager.all_sequence_ids(): for domain_event in self.get_domain_events(originator_id=originator_id, page_size=100): yield domain_event
Publishes prompt for a given event. Used to prompt downstream process application when an event is published by this application's model, which can happen when application command methods, rather than the process policy, are called. Wraps exceptions with PromptFailed, to avoid ...
def publish_prompt(self, event=None): """ Publishes prompt for a given event. Used to prompt downstream process application when an event is published by this application's model, which can happen when application command methods, rather than the process policy, are call...
With transaction isolation level of "read committed" this should generate records with a contiguous sequence of integer IDs, using an indexed ID column, the database-side SQL max function, the insert-select-from form, and optimistic concurrency control.
def _prepare_insert(self, tmpl, record_class, field_names, placeholder_for_id=False): """ With transaction isolation level of "read committed" this should generate records with a contiguous sequence of integer IDs, using an indexed ID column, the database-side SQL max function, the ...
Returns all records in the table.
def get_notifications(self, start=None, stop=None, *args, **kwargs): """ Returns all records in the table. """ filter_kwargs = {} # Todo: Also support sequencing by 'position' if items are sequenced by timestamp? if start is not None: filter_kwargs['%s__gte' %...
Starts all the actors to run a system of process applications.
def start(self): """ Starts all the actors to run a system of process applications. """ # Subscribe to broadcast prompts published by a process # application in the parent operating system process. subscribe(handler=self.forward_prompt, predicate=self.is_prompt) ...
Stops all the actors running a system of process applications.
def close(self): """Stops all the actors running a system of process applications.""" super(ActorModelRunner, self).close() unsubscribe(handler=self.forward_prompt, predicate=self.is_prompt) if self.shutdown_on_close: self.shutdown()
Returns a new suffix tree entity.
def register_new_suffix_tree(self, case_insensitive=False): """Returns a new suffix tree entity. """ suffix_tree = register_new_suffix_tree(case_insensitive=case_insensitive) suffix_tree._node_repo = self.node_repo suffix_tree._node_child_collection_repo = self.node_child_collect...
Returns a suffix tree entity, equipped with node and edge repos it (at least at the moment) needs.
def get_suffix_tree(self, suffix_tree_id): """Returns a suffix tree entity, equipped with node and edge repos it (at least at the moment) needs. """ suffix_tree = self.suffix_tree_repo[suffix_tree_id] assert isinstance(suffix_tree, GeneralizedSuffixTree) suffix_tree._node_repo = ...
Returns a set of IDs for strings that contain the given substring.
def find_string_ids(self, substring, suffix_tree_id, limit=None): """Returns a set of IDs for strings that contain the given substring. """ # Find an edge for the substring. edge, ln = self.find_substring_edge(substring=substring, suffix_tree_id=suffix_tree_id) # If there isn't...
Returns an edge that matches the given substring.
def find_substring_edge(self, substring, suffix_tree_id): """Returns an edge that matches the given substring. """ suffix_tree = self.suffix_tree_repo[suffix_tree_id] started = datetime.datetime.now() edge, ln = find_substring_edge(substring=substring, suffix_tree=suffix_tree, ed...
First caller adds a prompt to queue and runs followers until there are no more pending prompts. Subsequent callers just add a prompt to the queue, avoiding recursion.
def run_followers(self, prompt): """ First caller adds a prompt to queue and runs followers until there are no more pending prompts. Subsequent callers just add a prompt to the queue, avoiding recursion. """ assert isinstance(prompt, Prompt) # Put...
Puts prompt in each downstream inbox (an actual queue).
def put(self, prompt): """ Puts prompt in each downstream inbox (an actual queue). """ for queue in self.downstream_inboxes.values(): queue.put(prompt)
Factory method for example entities. :rtype: Example
def create_new_example(foo='', a='', b=''): """ Factory method for example entities. :rtype: Example """ return Example.__create__(foo=foo, a=a, b=b)
:rtype: InfrastructureFactory
def construct_infrastructure_factory(self, *args, **kwargs): """ :rtype: InfrastructureFactory """ factory_class = self.infrastructure_factory_class assert issubclass(factory_class, InfrastructureFactory) return factory_class( record_manager_class=self.record_...
Decorator for application policy method. Allows policy to be built up from methods registered for different event classes.
def applicationpolicy(arg=None): """ Decorator for application policy method. Allows policy to be built up from methods registered for different event classes. """ def _mutator(func): wrapped = singledispatch(func) @wraps(wrapped) def wrapper(*args, **kwargs): ...
With transaction isolation level of "read committed" this should generate records with a contiguous sequence of integer IDs, assumes an indexed ID column, the database-side SQL max function, the insert-select-from form, and optimistic concurrency control.
def _prepare_insert(self, tmpl, record_class, field_names, placeholder_for_id=False): """ With transaction isolation level of "read committed" this should generate records with a contiguous sequence of integer IDs, assumes an indexed ID column, the database-side SQL max function, the ...
Permanently removes record from table.
def delete_record(self, record): """ Permanently removes record from table. """ try: self.session.delete(record) self.session.commit() except Exception as e: self.session.rollback() raise ProgrammingError(e) finally: ...
Gets or creates a log. :rtype: Timebucketedlog
def get_or_create(self, log_name, bucket_size): """ Gets or creates a log. :rtype: Timebucketedlog """ try: return self[log_name] except RepositoryKeyError: return start_new_timebucketedlog(log_name, bucket_size=bucket_size)
Evolves initial state using the sequence of domain events and a mutator function.
def project_events(self, initial_state, domain_events): """ Evolves initial state using the sequence of domain events and a mutator function. """ return reduce(self._mutator_func or self.mutate, domain_events, initial_state)
Returns last array in compound. :rtype: CompoundSequenceReader
def get_last_array(self): """ Returns last array in compound. :rtype: CompoundSequenceReader """ # Get the root array (might not have been registered). root = self.repo[self.id] # Get length and last item in the root array. apex_id, apex_height = root.ge...
Returns get_big_array and end of span of parent sequence that contains given child.
def calc_parent(self, i, j, h): """ Returns get_big_array and end of span of parent sequence that contains given child. """ N = self.repo.array_size c_i = i c_j = j c_h = h # Calculate the number of the sequence in its row (sequences # with same he...
Constructs a sequenced item from a domain event.
def item_from_event(self, domain_event): """ Constructs a sequenced item from a domain event. """ item_args = self.construct_item_args(domain_event) return self.construct_sequenced_item(item_args)
Constructs attributes of a sequenced item from the given domain event.
def construct_item_args(self, domain_event): """ Constructs attributes of a sequenced item from the given domain event. """ # Get the sequence ID. sequence_id = domain_event.__dict__[self.sequence_id_attr_name] # Get the position in the sequence. position = getat...
Reconstructs domain event from stored event topic and event attrs. Used in the event store when getting domain events.
def event_from_item(self, sequenced_item): """ Reconstructs domain event from stored event topic and event attrs. Used in the event store when getting domain events. """ assert isinstance(sequenced_item, self.sequenced_item_class), ( self.sequenced_item_class, type(se...
Gets sequenced item from the datastore.
def get_item(self, sequence_id, position): """ Gets sequenced item from the datastore. """ return self.from_record(self.get_record(sequence_id, position))
Returns sequenced item generator.
def get_items(self, sequence_id, gt=None, gte=None, lt=None, lte=None, limit=None, query_ascending=True, results_ascending=True): """ Returns sequenced item generator. """ records = self.get_records( sequence_id=sequence_id, gt=gt, gt...
Returns records for a sequence.
def get_records(self, sequence_id, gt=None, gte=None, lt=None, lte=None, limit=None, query_ascending=True, results_ascending=True): """ Returns records for a sequence. """
Constructs a record object from given sequenced item object.
def to_record(self, sequenced_item): """ Constructs a record object from given sequenced item object. """ kwargs = self.get_field_kwargs(sequenced_item) # Supply application_name, if needed. if hasattr(self.record_class, 'application_name'): kwargs['applicatio...
Constructs and returns a sequenced item object, from given ORM object.
def from_record(self, record): """ Constructs and returns a sequenced item object, from given ORM object. """ kwargs = self.get_field_kwargs(record) return self.sequenced_item_class(**kwargs)
Returns pipeline ID and notification ID for event at given position in given sequence.
def get_pipeline_and_notification_id(self, sequence_id, position): """ Returns pipeline ID and notification ID for event at given position in given sequence. """ # Todo: Optimise query by selecting only two columns, pipeline_id and id (notification ID)? record = self.get_...
SQL statement that inserts records with contiguous IDs, by selecting max ID from indexed table records.
def insert_select_max(self): """ SQL statement that inserts records with contiguous IDs, by selecting max ID from indexed table records. """ if self._insert_select_max is None: if hasattr(self.record_class, 'application_name'): # Todo: Maybe make it su...
SQL statement that inserts records without ID.
def insert_values(self): """ SQL statement that inserts records without ID. """ if self._insert_values is None: self._insert_values = self._prepare_insert( tmpl=self._insert_values_tmpl, placeholder_for_id=True, record_class=sel...
SQL statement that inserts tracking records.
def insert_tracking_record(self): """ SQL statement that inserts tracking records. """ if self._insert_tracking_record is None: self._insert_tracking_record = self._prepare_insert( tmpl=self._insert_values_tmpl, placeholder_for_id=True, ...
Returns instance of PaxosInstance (protocol implementation).
def paxos_instance(self): """ Returns instance of PaxosInstance (protocol implementation). """ # Construct instance with the constant attributes. instance = PaxosInstance(self.network_uid, self.quorum_size) # Set the variable attributes from the aggregate. for na...
Factory method that returns a new Paxos aggregate.
def start(cls, originator_id, quorum_size, network_uid): """ Factory method that returns a new Paxos aggregate. """ assert isinstance(quorum_size, int), "Not an integer: {}".format(quorum_size) return cls.__create__( event_class=cls.Started, originator_id=...
Proposes a value to the network.
def propose_value(self, value, assume_leader=False): """ Proposes a value to the network. """ if value is None: raise ValueError("Not allowed to propose value None") paxos = self.paxos_instance paxos.leader = assume_leader msg = paxos.propose_value(val...
Responds to messages from other participants.
def receive_message(self, msg): """ Responds to messages from other participants. """ if isinstance(msg, Resolution): return paxos = self.paxos_instance while msg: if isinstance(msg, Resolution): self.print_if_verbose("{} resolved v...
Announces a Paxos message.
def announce(self, msg): """ Announces a Paxos message. """ self.print_if_verbose("{} -> {}".format(self.network_uid, msg.__class__.__name__)) self.__trigger_event__( event_class=self.MessageAnnounced, msg=msg, )
Registers changes of attribute value on Paxos instance.
def setattrs_from_paxos(self, paxos): """ Registers changes of attribute value on Paxos instance. """ changes = {} for name in self.paxos_variables: paxos_value = getattr(paxos, name) if paxos_value != getattr(self, name, None): self.print_...
Starts new Paxos aggregate and proposes a value for a key. Decorated with retry in case of notification log conflict or operational error.
def propose_value(self, key, value, assume_leader=False): """ Starts new Paxos aggregate and proposes a value for a key. Decorated with retry in case of notification log conflict or operational error. """ assert isinstance(key, UUID) paxos_aggregate = PaxosAggreg...
Message dispatching function. This function accepts any PaxosMessage subclass and calls the appropriate handler function
def receive(self, msg): ''' Message dispatching function. This function accepts any PaxosMessage subclass and calls the appropriate handler function ''' handler = getattr(self, 'receive_' + msg.__class__.__name__.lower(), None) if handler is None: raise Invali...
Sets the proposal value for this node iff this node is not already aware of a previous proposal value. If the node additionally believes itself to be the current leader, an Accept message will be returned
def propose_value(self, value): ''' Sets the proposal value for this node iff this node is not already aware of a previous proposal value. If the node additionally believes itself to be the current leader, an Accept message will be returned ''' if self.proposed_value is N...
Returns a new Prepare message with a proposal id higher than that of any observed proposals. A side effect of this method is to clear the leader flag if it is currently set.
def prepare(self): ''' Returns a new Prepare message with a proposal id higher than that of any observed proposals. A side effect of this method is to clear the leader flag if it is currently set. ''' self.leader = False self.promises_received = set() sel...
Returns a new Prepare message if the number of Nacks received reaches a quorum.
def receive_nack(self, msg): ''' Returns a new Prepare message if the number of Nacks received reaches a quorum. ''' self.observe_proposal(msg.promised_proposal_id) if msg.proposal_id == self.proposal_id and self.nacks_received is not None: self.nacks_receive...
Returns an Accept messages if a quorum of Promise messages is achieved
def receive_promise(self, msg): ''' Returns an Accept messages if a quorum of Promise messages is achieved ''' self.observe_proposal(msg.proposal_id) if not self.leader and msg.proposal_id == self.proposal_id and msg.from_uid not in self.promises_received: self.prom...
Returns either a Promise or a Nack in response. The Acceptor's state must be persisted to disk prior to transmitting the Promise message.
def receive_prepare(self, msg): ''' Returns either a Promise or a Nack in response. The Acceptor's state must be persisted to disk prior to transmitting the Promise message. ''' if self.promised_id is None or msg.proposal_id >= self.promised_id: self.promised_id = msg...
Returns either an Accepted or Nack message in response. The Acceptor's state must be persisted to disk prior to transmitting the Accepted message.
def receive_accept(self, msg): ''' Returns either an Accepted or Nack message in response. The Acceptor's state must be persisted to disk prior to transmitting the Accepted message. ''' if self.promised_id is None or msg.proposal_id >= self.promised_id: self.promised_...
Called when an Accepted message is received from an acceptor. Once the final value is determined, the return value of this method will be a Resolution message containing the consentual value. Subsequent calls after the resolution is chosen will continue to add new Acceptors to the final_acceptor...
def receive_accepted(self, msg): ''' Called when an Accepted message is received from an acceptor. Once the final value is determined, the return value of this method will be a Resolution message containing the consentual value. Subsequent calls after the resolution is chosen will contin...
Return class described by given topic. Args: topic: A string describing a class. Returns: A class. Raises: TopicResolutionError: If there is no such class.
def resolve_topic(topic): """Return class described by given topic. Args: topic: A string describing a class. Returns: A class. Raises: TopicResolutionError: If there is no such class. """ try: module_name, _, class_name = topic.partition('#') module = ...
A recursive version of getattr for navigating dotted paths. Args: obj: An object for which we want to retrieve a nested attribute. path: A dot separated string containing zero or more attribute names. Returns: The attribute referred to by obj.a1.a2.a3... Raises: AttributeE...
def resolve_attr(obj, path): """A recursive version of getattr for navigating dotted paths. Args: obj: An object for which we want to retrieve a nested attribute. path: A dot separated string containing zero or more attribute names. Returns: The attribute referred to by obj.a1.a2.a...
Helper function to return dictionary of countries in {"country" : "iso"} form.
def country_list_maker(): """ Helper function to return dictionary of countries in {"country" : "iso"} form. """ cts = {"Afghanistan":"AFG", "Åland Islands":"ALA", "Albania":"ALB", "Algeria":"DZA", "American Samoa":"ASM", "Andorra":"AND", "Angola":"AGO", "Anguilla":"AIA", "Antarctica":"ATA", "An...
Return hand-defined list of place names to skip and not attempt to geolocate. If users would like to exclude country names, this would be the function to do it with.
def make_skip_list(cts): """ Return hand-defined list of place names to skip and not attempt to geolocate. If users would like to exclude country names, this would be the function to do it with. """ # maybe make these non-country searches but don't discard, at least for # some (esp. bodies of wa...
NLP countries so we can use for vector comparisons
def country_list_nlp(cts): """NLP countries so we can use for vector comparisons""" ct_nlp = [] for i in cts.keys(): nlped = nlp(i) ct_nlp.append(nlped) return ct_nlp
Combine list of countries and list of nationalities
def make_country_nationality_list(cts, ct_file): """Combine list of countries and list of nationalities""" countries = pd.read_csv(ct_file) nationality = dict(zip(countries.nationality,countries.alpha_3_code)) both_codes = {**nationality, **cts} return both_codes
cts is e.g. {"Germany" : "DEU"}. inv_cts is the inverse: {"DEU" : "Germany"}
def make_inv_cts(cts): """ cts is e.g. {"Germany" : "DEU"}. inv_cts is the inverse: {"DEU" : "Germany"} """ inv_ct = {} for old_k, old_v in cts.items(): if old_v not in inv_ct.keys(): inv_ct.update({old_v : old_k}) return inv_ct
Small helper function to read in a admin1 code <--> admin1 name document. Parameters ---------- filepath: string path to the admin1 mapping JSON. This file is usually mordecai/resources/data/admin1CodesASCII.json Returns ------- admin1_dict: dictionary ...
def read_in_admin1(filepath): """ Small helper function to read in a admin1 code <--> admin1 name document. Parameters ---------- filepath: string path to the admin1 mapping JSON. This file is usually mordecai/resources/data/admin1CodesASCII.json Returns -------...
Format Elasticsearch result as Python dictionary
def structure_results(res): """Format Elasticsearch result as Python dictionary""" out = {'hits': {'hits': []}} keys = [u'admin1_code', u'admin2_code', u'admin3_code', u'admin4_code', u'alternativenames', u'asciiname', u'cc2', u'coordinates', u'country_code2', u'country_code3', u'dem...
Setup an Elasticsearch connection Parameters ---------- hosts: list Hostnames / IP addresses for elasticsearch cluster port: string Port for elasticsearch cluster use_ssl: boolean Whether to use SSL for the elasticsearch connection auth: tuple (us...
def setup_es(hosts, port, use_ssl=False, auth=None): """ Setup an Elasticsearch connection Parameters ---------- hosts: list Hostnames / IP addresses for elasticsearch cluster port: string Port for elasticsearch cluster use_ssl: boolean Whether to use SSL...
Given a document, count how many times different country names and adjectives are mentioned. These are features used in the country picking phase. Parameters --------- doc: a spaCy nlp'ed piece of text Returns ------- countries: dict the top two coun...
def _feature_country_mentions(self, doc): """ Given a document, count how many times different country names and adjectives are mentioned. These are features used in the country picking phase. Parameters --------- doc: a spaCy nlp'ed piece of text Returns ...
Strip out extra words that often get picked up by spaCy's NER. To do: preserve info about what got stripped out to help with ES/Geonames resolution later. Parameters --------- ent: a spaCy named entity Span Returns ------- new_ent: a spaCy Span, wit...
def clean_entity(self, ent): """ Strip out extra words that often get picked up by spaCy's NER. To do: preserve info about what got stripped out to help with ES/Geonames resolution later. Parameters --------- ent: a spaCy named entity Span Returns ...
Find the most common country name in ES/Geonames results Paramaters ---------- results: dict output of `query_geonames` Returns ------- most_common: str ISO code of most common country, or empty string if none
def _feature_most_common(self, results): """ Find the most common country name in ES/Geonames results Paramaters ---------- results: dict output of `query_geonames` Returns ------- most_common: str ISO code of most common country,...
Find the placename with the most alternative names and return its country. More alternative names are a rough measure of importance. Paramaters ---------- results: dict output of `query_geonames` Returns ------- most_alt: str ISO code of ...
def _feature_most_alternative(self, results, full_results=False): """ Find the placename with the most alternative names and return its country. More alternative names are a rough measure of importance. Paramaters ---------- results: dict output of `query_geo...
Find the placename with the largest population and return its country. More population is a rough measure of importance. Paramaters ---------- results: dict output of `query_geonames` Returns ------- most_pop: str ISO code of country of p...
def _feature_most_population(self, results): """ Find the placename with the largest population and return its country. More population is a rough measure of importance. Paramaters ---------- results: dict output of `query_geonames` Returns -...
Given a word, guess the appropriate country by word vector. Parameters --------- text: str the text to extract locations from. Returns ------- country_picking: dict The top two countries (ISO codes) and two measures confidence for the...
def _feature_word_embedding(self, text): """ Given a word, guess the appropriate country by word vector. Parameters --------- text: str the text to extract locations from. Returns ------- country_picking: dict The top two countrie...
Get the country of the first two results back from geonames. Parameters ----------- results: dict elasticsearch results Returns ------- top: tuple first and second results' country name (ISO)
def _feature_first_back(self, results): """ Get the country of the first two results back from geonames. Parameters ----------- results: dict elasticsearch results Returns ------- top: tuple first and second results' country name ...
Check if a piece of text is in the list of countries
def is_country(self, text): """Check if a piece of text is in the list of countries""" ct_list = self._just_cts.keys() if text in ct_list: return True else: return False
Wrap search parameters into an elasticsearch query to the geonames index and return results. Parameters --------- conn: an elasticsearch Search conn, like the one returned by `setup_es()` placename: str the placename text extracted by NER system Returns ...
def query_geonames(self, placename): """ Wrap search parameters into an elasticsearch query to the geonames index and return results. Parameters --------- conn: an elasticsearch Search conn, like the one returned by `setup_es()` placename: str the pl...
Like query_geonames, but this time limited to a specified country.
def query_geonames_country(self, placename, country): """ Like query_geonames, but this time limited to a specified country. """ # first, try for an exact phrase match q = {"multi_match": {"query": placename, "fields": ['name^5', 'asciiname^5', 'alter...
Count forward 1 word from each entity, looking for defined terms that indicate geographic feature types (e.g. "village" = "P"). Parameters ----------- ent : spacy entity span It has to be an entity to handle indexing in the document Returns -------- ...
def _feature_location_type_mention(self, ent): """ Count forward 1 word from each entity, looking for defined terms that indicate geographic feature types (e.g. "village" = "P"). Parameters ----------- ent : spacy entity span It has to be an entity to handle ...
Create features for the country picking model. Function where all the individual feature maker functions are called and aggregated. (Formerly "process_text") Parameters ----------- doc : str or spaCy doc Returns ------- task_list : list of dicts Each...
def make_country_features(self, doc, require_maj=False): """ Create features for the country picking model. Function where all the individual feature maker functions are called and aggregated. (Formerly "process_text") Parameters ----------- doc : str or spaCy doc ...