text
stringlengths
81
112k
match each pattern to each molecule. if all patterns matches with all molecules return generator of all possible mapping. :param structures: disjoint molecules :return: mapping generator def __get_mapping(self, structures): """ match each pattern to each molecule. ...
return the cached value or default if it can't be found :param default: default value :return: cached value def get(self, default=None): """ return the cached value or default if it can't be found :param default: default value :return: cached value """ ...
set cache value :param val: any picklable object :param lifetime: exprition time in sec :return: val def set(self, val, lifetime=None): """ set cache value :param val: any picklable object :param lifetime: exprition time in sec :return: val """ ...
Add given value to item (list) Args: val: A JSON serializable object. Returns: Cache backend response. def add(self, val): """ Add given value to item (list) Args: val: A JSON serializable object. Returns: Cache backend...
Get all list items. Returns: Cache backend response. def get_all(self): """ Get all list items. Returns: Cache backend response. """ result = cache.lrange(self.key, 0, -1) return (json.loads(item.decode('utf-8')) for item in result if ...
Removes given item from the list. Args: val: Item Returns: Cache backend response. def remove_item(self, val): """ Removes given item from the list. Args: val: Item Returns: Cache backend response. """ r...
Removes all keys of this namespace Without args, clears all keys starting with cls.PREFIX if called with args, clears keys starting with given cls.PREFIX + args Args: *args: Arbitrary number of arguments. Returns: List of removed keys. def flush(cls, *args): ...
Deletes session if keepalive request expired otherwise updates the keepalive timestamp value def update_or_expire_session(self): """ Deletes session if keepalive request expired otherwise updates the keepalive timestamp value """ if not hasattr(self, 'key'): ...
Sends a message to possible owners of the current workflows next lane. Args: **kwargs: ``current`` and ``possible_owners`` are required. sender (User): User object def send_message_for_lane_change(sender, **kwargs): """ Sends a message to possible owners of the current workflows ...
Encrypts password of the user. def set_password(sender, **kwargs): """ Encrypts password of the user. """ if sender.model_class.__name__ == 'User': usr = kwargs['object'] if not usr.password.startswith('$pbkdf2'): usr.set_password(usr.password) usr.save()
Main screen for channel management. Channels listed and operations can be chosen on the screen. If there is an error message like non-choice, it is shown here. def channel_list(self): """ Main screen for channel management. Channels listed and operations can be chosen on...
It controls errors. If there is an error, returns channel list screen with error message. def channel_choice_control(self): """ It controls errors. If there is an error, returns channel list screen with error message. """ self.current.task_data['control'], self.current.t...
Features of new channel are specified like channel's name, owner etc. def create_new_channel(self): """ Features of new channel are specified like channel's name, owner etc. """ self.current.task_data['new_channel'] = True _form = NewChannelForm(Channel(), current=self.current)...
It saves new channel according to specified channel features. def save_new_channel(self): """ It saves new channel according to specified channel features. """ form_info = self.input['form'] channel = Channel(typ=15, name=form_info['name'], description...
It is a channel choice list and chosen channels at previous step shouldn't be on the screen. def choose_existing_channel(self): """ It is a channel choice list and chosen channels at previous step shouldn't be on the screen. """ if self.current.task_data.get('msg', Fals...
It controls errors. It generates an error message if zero or more than one channels are selected. def existing_choice_control(self): """ It controls errors. It generates an error message if zero or more than one channels are selected. """ self.current.task_data['existing...
A channel can be splitted to new channel or other existing channel. It creates subscribers list as selectable to moved. def split_channel(self): """ A channel can be splitted to new channel or other existing channel. It creates subscribers list as selectable to moved. """ ...
It controls subscribers choice and generates error message if there is a non-choice. def subscriber_choice_control(self): """ It controls subscribers choice and generates error message if there is a non-choice. """ self.current.task_data['option'] = None self.cur...
Channels and theirs subscribers are moved completely to new channel or existing channel. def move_complete_channel(self): """ Channels and theirs subscribers are moved completely to new channel or existing channel. """ to_channel = Channel.objects.get(self.current.task_...
After splitting operation, only chosen subscribers are moved to new channel or existing channel. def move_chosen_subscribers(self): """ After splitting operation, only chosen subscribers are moved to new channel or existing channel. """ from_channel = Channel.objects.get...
While splitting channel and moving chosen subscribers to new channel, old channel's messages are copied and moved to new channel. Args: from_channel (Channel object): move messages from channel to_channel (Channel object): move messages to channel def copy_and_move_messages(f...
It shows incorrect operations or successful operation messages. Args: title (string): title of message box box_type (string): type of message box (warning, info) def show_warning_messages(self, title=_(u"Incorrect Operation"), box_type='warning'): """ It shows incorrect...
It returns chosen keys list from a given form. Args: form_info: serialized list of dict form data Returns: selected_keys(list): Chosen keys list selected_names(list): Chosen channels' or subscribers' names. def return_selected_form_items(form_info): """ ...
It controls the selection from the form according to the operations, and returns an error message if it does not comply with the rules. Args: form_info: Channel or subscriber form from the user Returns: True or False error message def selection_error_contr...
Yields the sequence of prime numbers via the Sieve of Eratosthenes. def _eratosthenes(): """Yields the sequence of prime numbers via the Sieve of Eratosthenes.""" d = {} # map each composite integer to its first-found prime factor for q in count(2): # q gets 2, 3, 4, 5, ... ad infinitum p = d.pop...
Morgan like algorithm for graph nodes ordering :return: dict of atom-weight pairs def atoms_order(self): """ Morgan like algorithm for graph nodes ordering :return: dict of atom-weight pairs """ if not len(self): # for empty containers return {} el...
Manual init method for external piece values :type: PAWN_VALUE: int :type: KNIGHT_VALUE: int :type: BISHOP_VALUE: int :type: ROOK_VALUE: int :type: QUEEN_VALUE: int def init_manual(cls, pawn_value, knight_value, bishop_value, rook_value, queen_value, king_value): """ ...
Finds value of ``Piece`` :type: piece: Piece :type: ref_color: Color :rtype: int def val(self, piece, ref_color): """ Finds value of ``Piece`` :type: piece: Piece :type: ref_color: Color :rtype: int """ if piece is None: retu...
Starts game and returns one of 3 results . Iterates between methods ``white_move()`` and ``black_move()`` until game ends. Each method calls the respective player's ``generate_move()`` method. :rtype: int def play(self): """ Starts game and returns one of 3 res...
Calls the white player's ``generate_move()`` method and updates the board with the move returned. def white_move(self): """ Calls the white player's ``generate_move()`` method and updates the board with the move returned. """ move = self.player_white.generate_move(self.p...
Calls the black player's ``generate_move()`` method and updates the board with the move returned. def black_move(self): """ Calls the black player's ``generate_move()`` method and updates the board with the move returned. """ move = self.player_black.generate_move(self.p...
Return a list of fields' mappings def get_field_cache(self, cache_type='es'): """Return a list of fields' mappings""" if cache_type == 'kibana': try: search_results = urlopen(self.get_url).read().decode('utf-8') except HTTPError: # as e: # self.p...
Where field_cache is a list of fields' mappings def post_field_cache(self, field_cache): """Where field_cache is a list of fields' mappings""" index_pattern = self.field_cache_to_index_pattern(field_cache) # self.pr_dbg("request/post: %s" % index_pattern) resp = requests.post(self.post_...
Return a .kibana index-pattern doc_type def field_cache_to_index_pattern(self, field_cache): """Return a .kibana index-pattern doc_type""" mapping_dict = {} mapping_dict['customFormats'] = "{}" mapping_dict['title'] = self.index_pattern # now post the data into .kibana m...
Assert minimum set of fields in cache, does not validate contents def check_mapping(self, m): """Assert minimum set of fields in cache, does not validate contents""" if 'name' not in m: self.pr_dbg("Missing %s" % "name") return False # self.pr_dbg("Checking %s" % m['name...
Converts all index's doc_types to .kibana def get_index_mappings(self, index): """Converts all index's doc_types to .kibana""" fields_arr = [] for (key, val) in iteritems(index): # self.pr_dbg("\tdoc_type: %s" % key) doc_mapping = self.get_doc_type_mappings(index[key]) ...
Converts all doc_types' fields to .kibana def get_doc_type_mappings(self, doc_type): """Converts all doc_types' fields to .kibana""" doc_fields_arr = [] found_score = False for (key, val) in iteritems(doc_type): # self.pr_dbg("\t\tfield: %s" % key) # self.pr_dbg(...
Converts ES field mappings to .kibana field mappings def get_field_mappings(self, field): """Converts ES field mappings to .kibana field mappings""" retdict = {} retdict['indexed'] = False retdict['analyzed'] = False for (key, val) in iteritems(field): if key in self...
Test if k_cache is incomplete Assume k_cache is always correct, but could be missing new fields that es_cache has def is_kibana_cache_incomplete(self, es_cache, k_cache): """Test if k_cache is incomplete Assume k_cache is always correct, but could be missing new fields that es...
Convert list into a data structure we can query easier def list_to_compare_dict(self, list_form): """Convert list into a data structure we can query easier""" compare_dict = {} for field in list_form: if field['name'] in compare_dict: self.pr_dbg("List has duplicate ...
Verify original is subset of replica def compare_field_caches(self, replica, original): """Verify original is subset of replica""" if original is None: original = [] if replica is None: replica = [] self.pr_dbg("Comparing orig with %s fields to replica with %s fi...
starts a deamon thread for a given target function and arguments. def start_daemon_thread(target, args=()): """starts a deamon thread for a given target function and arguments.""" th = Thread(target=target, args=args) th.daemon = True th.start() return th
returns all the keys in a dictionary. >>> serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } }) ['a', 'a.b', 'a.b.c', 'a.b.b'] def serialize_dict_keys(d, prefix=""): """returns all the keys in a dictionary. >>> serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } }) ['a', 'a.b', 'a.b.c', 'a.b.b'] ...
Writes user data to session. Args: user: User object def set_user(self, user): """ Writes user data to session. Args: user: User object """ self.session['user_id'] = user.key self.session['user_data'] = user.clean_value() role =...
Finds if square on the board is occupied by a ``Piece`` belonging to the opponent. :type: square: Location :type: position: Board :rtype: bool def contains_opposite_color_piece(self, square, position): """ Finds if square on the board is occupied by a ``Piece`` ...
Mark a message as translateable, and translate it. All messages in the application that are translateable should be wrapped with this function. When importing this function, it should be renamed to '_'. For example: .. code-block:: python from zengine.lib.translation import gettext as _ p...
Mark a message as translatable, but delay the translation until the message is used. Sometimes, there are some messages that need to be translated, but the translation can't be done at the point the message itself is written. For example, the names of the fields in a Model can't be translated at the point ...
Mark a message as translateable, and translate it considering plural forms. Some messages may need to change based on a number. For example, consider a message like the following: .. code-block:: python def alert_msg(msg_count): print( 'You have %d %s' % (msg_count, 'message' if msg_count...
Mark a message with plural forms translateable, and delay the translation until the message is used. Works the same was a `ngettext`, with a delaying functionality similiar to `gettext_lazy`. Args: singular (unicode): The singular form of the message. plural (unicode): The plural form of t...
Wrap a Babel data formatting function to automatically format for currently installed locale. def _wrap_locale_formatter(fn, locale_type): """Wrap a Babel data formatting function to automatically format for currently installed locale.""" def wrapped_locale_formatter(*args, **kwargs): """A Bab...
Install the translations for language specified by `language_code`. If we don't have translations for this language, then the default language will be used. If the language specified is already installed, then this is a no-op. def install_language(cls, language_code): """Install the translati...
Install the locale specified by `language_code`, for localizations of type `locale_type`. If we can't perform localized formatting for the specified locale, then the default localization format will be used. If the locale specified is already installed for the selected type, then this is a no-...
rotate x,y vector over x2-x1, y2-y1 angle def _rotate_vector(x, y, x2, y2, x1, y1): """ rotate x,y vector over x2-x1, y2-y1 angle """ angle = atan2(y2 - y1, x2 - x1) cos_rad = cos(angle) sin_rad = sin(angle) return cos_rad * x + sin_rad * y, -sin_rad * x + cos_ra...
Build static table mapping from header name to tuple with next structure: (<minimal index of header>, <mapping from header value to it index>). static_table_mapping used for hash searching. def _build_static_table_mapping(): """ Build static table mapping from header name to tuple with next structure:...
Returns the entry specified by index Note that the table is 1-based ie an index of 0 is invalid. This is due to the fact that a zero value index signals that a completely unindexed header follows. The entry will either be from the static table or the dynamic table depe...
Adds a new entry to the table We reduce the table size if the entry will make the table size greater than maxsize. def add(self, name, value): """ Adds a new entry to the table We reduce the table size if the entry will make the table size greater than maxsize. ...
Searches the table for the entry specified by name and value Returns one of the following: - ``None``, no match at all - ``(index, name, None)`` for partial matches on name only. - ``(index, name, value)`` for perfect matches. def search(self, name, value): ...
Shrinks the dynamic table to be at or below maxsize def _shrink(self): """ Shrinks the dynamic table to be at or below maxsize """ cursize = self._current_size while cursize > self._maxsize: name, value = self.dynamic_entries.pop() cursize -= table_entry_...
Adds a new value for the given key. def add(self, name, value): # type: (str, str) -> None """Adds a new value for the given key.""" self._last_key = name if name in self: self._dict[name] = value self._as_list[name].append(value) else: self[n...
Returns an iterable of all (name, value) pairs. If a header has multiple values, multiple pairs will be returned with the same name. def get_all(self): # type: () -> typing.Iterable[typing.Tuple[str, str]] """Returns an iterable of all (name, value) pairs. If a header has mult...
Safely print a unicode string def safe_print(ustring, errors='replace', **kwargs): """ Safely print a unicode string """ encoding = sys.stdout.encoding or 'utf-8' if sys.version_info[0] == 3: print(ustring, **kwargs) else: bytestr = ustring.encode(encoding, errors=errors) print(...
Creates the view used to edit permissions. To create the view, data in the following format is passed to the UI in the objects field: .. code-block:: python { "type": "tree-toggle", "action": "set_permission", "tree": [ ...
Get the cached permission tree, or build a new one if necessary. def _permission_trees(permissions): """Get the cached permission tree, or build a new one if necessary.""" treecache = PermissionTreeCache() cached = treecache.get() if not cached: tree = PermissionTreeBuilder(...
In permission tree, sets `'checked': True` for the permissions that the role has. def _apply_role_tree(self, perm_tree, role): """In permission tree, sets `'checked': True` for the permissions that the role has.""" role_permissions = role.get_permissions() for perm in role_permissions: ...
Traverses the permission tree, returning the permission at given permission path. def _traverse_tree(tree, path): """Traverses the permission tree, returning the permission at given permission path.""" path_steps = (step for step in path.split('.') if step != '') # Special handling for first st...
Recursively format all subtrees. def _format_subtree(self, subtree): """Recursively format all subtrees.""" subtree['children'] = list(subtree['children'].values()) for child in subtree['children']: self._format_subtree(child) return subtree
Applies changes to the permissions of the role. To make a change to the permission of the role, a request in the following format should be sent: .. code-block:: python { 'change': { 'id': 'workflow2.lane1.task1', ...
shifts on a given number of record in the original file :param offset: number of record def seek(self, offset): """ shifts on a given number of record in the original file :param offset: number of record """ if self._shifts: if 0 <= offset < len(self._shifts)...
:return: number of records processed from the original file def tell(self): """ :return: number of records processed from the original file """ if self._shifts: t = self._file.tell() return bisect_left(self._shifts, t) raise self._implement_error
write single molecule into file def write(self, data): """ write single molecule into file """ m = self._convert_structure(data) self._file.write(self._format_mol(*m)) self._file.write('M END\n') for k, v in data.meta.items(): self._file.write(f'> ...
If we aren't come to the end of the wf, saves the wf state and task_data to cache Task_data items that starts with underscore "_" are treated as local and does not passed to subsequent task steps. def save_workflow_to_cache(self, serialized_wf_instance): """ If we aren't come ...
Builds context for the WF pool. Returns: Context dict. def get_pool_context(self): # TODO: Add in-process caching """ Builds context for the WF pool. Returns: Context dict. """ context = {self.current.lane_id: self.current.role, 'self': ...
loads the serialized wf state and data from cache updates the self.current.task_data def load_workflow_from_cache(self): """ loads the serialized wf state and data from cache updates the self.current.task_data """ if not self.current.new_token: self.wf_state ...
Serializes the current WF. Returns: WF state data. def serialize_workflow(self): """ Serializes the current WF. Returns: WF state data. """ self.workflow.refresh_waiting_tasks() return CompactWorkflowSerializer().serialize_workflow(self....
Tries to load the previously serialized (and saved) workflow Creates a new one if it can't def load_or_create_workflow(self): """ Tries to load the previously serialized (and saved) workflow Creates a new one if it can't """ self.workflow_spec = self.get_worfklow_spec() ...
Tries to find the path of the workflow diagram file in `WORKFLOW_PACKAGES_PATHS`. Returns: Path of the workflow spec file (BPMN diagram) def find_workflow_path(self): """ Tries to find the path of the workflow diagram file in `WORKFLOW_PACKAGES_PATHS`. Retu...
Generates and caches the workflow spec package from BPMN diagrams that read from disk Returns: SpiffWorkflow Spec object. def get_worfklow_spec(self): """ Generates and caches the workflow spec package from BPMN diagrams that read from disk Returns: ...
Calls the real save method if we pass the beggining of the wf def _save_or_delete_workflow(self): """ Calls the real save method if we pass the beggining of the wf """ if not self.current.task_type.startswith('Start'): if self.current.task_name.startswith('End') and not self...
Initializes the workflow with given request, response objects and diagram name. Args: session: input: workflow_name (str): Name of workflow diagram without ".bpmn" suffix. File must be placed under one of configured :py:attr:`~zengine.settings.WORKFLOW_PACKAGES_...
Logs the state of workflow and content of task_data. def generate_wf_state_log(self): """ Logs the state of workflow and content of task_data. """ output = '\n- - - - - -\n' output += "WORKFLOW: %s ( %s )" % (self.current.workflow_name.upper(), ...
Main workflow switcher. This method recreates main workflow from `main wf` dict which was set by external workflow swicther previously. def switch_from_external_to_main_wf(self): """ Main workflow switcher. This method recreates main workflow from `main wf` dict which ...
External workflow switcher. This method copies main workflow information into a temporary dict `main_wf` and makes external workflow acting as main workflow. def switch_to_external_wf(self): """ External workflow switcher. This method copies main workflow information i...
Clear tasks related attributes, checks permissions While switching WF to WF, authentication and permissions are checked for new WF. def _clear_current_task(self): """ Clear tasks related attributes, checks permissions While switching WF to WF, authentication and permissions are checked...
Main loop of the workflow engine - Updates ::class:`~WFCurrent` object. - Checks for Permissions. - Activates all READY tasks. - Runs referenced activities (method calls). - Saves WF states. - Stops if current task is a UserTask or EndTask. - Deletes state object...
Checks that the user task needs to re-run. If necessary, current task and pre task's states are changed and re-run. If wf_meta not in data(there is no user interaction from pre-task) and last completed task type is user task and current step is not EndEvent and there is no lane change, t...
Switch to the language of the current user. If the current language is already the specified one, nothing will be done. def switch_lang(self): """Switch to the language of the current user. If the current language is already the specified one, nothing will be done. """ locale ...
trigger a lane_user_change signal if we switched to a new lane and new lane's user is different from current one def catch_lane_change(self): """ trigger a lane_user_change signal if we switched to a new lane and new lane's user is different from current one """ if self....
Transmits client message that defined in a workflow task's inputOutput extension .. code-block:: xml <bpmn2:extensionElements> <camunda:inputOutput> <camunda:inputParameter name="client_message"> <camunda:map> <camunda:entry key="title">Teşe...
runs the method that referenced from current task def run_activity(self): """ runs the method that referenced from current task """ activity = self.current.activity if activity: if activity not in self.wf_activities: self._load_activity(activity) ...
Imports the module that contains the referenced method. Args: path: python path of class/function look_for_cls_method (bool): If True, treat the last part of path as class method. Returns: Tuple. (class object, class name, method to be called) def _import_object(se...
Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path. def _load_activity(self, activity): """ Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path. """ fpths = [] full_path = ...
Checks current workflow against :py:data:`~zengine.settings.ANONYMOUS_WORKFLOWS` list. Raises: HTTPUnauthorized: if WF needs an authenticated user and current user isn't. def check_for_authentication(self): """ Checks current workflow against :py:data:`~zengine.settings.ANONYMOUS_W...
One or more permissions can be associated with a lane of a workflow. In a similar way, a lane can be restricted with relation to other lanes of the workflow. This method called on lane changes and checks user has required permissions and relations. Raises: HTTPForb...
Checks if current user (or role) has the required permission for current workflow step. Raises: HTTPError: if user doesn't have required permissions. def check_for_permission(self): # TODO: Works but not beautiful, needs review! """ Checks if current user (or role) ...
Removes the ``token`` key from ``current.output`` if WF is over. def handle_wf_finalization(self): """ Removes the ``token`` key from ``current.output`` if WF is over. """ if ((not self.current.flow_enabled or ( self.current.task_type.startswith('End') and not self.are_we_in...
RDKit molecule object to MoleculeContainer converter def from_rdkit_molecule(data): """ RDKit molecule object to MoleculeContainer converter """ m = MoleculeContainer() atoms, mapping = [], [] for a in data.GetAtoms(): atom = {'element': a.GetSymbol(), 'charge': a.GetFormalCharge()} ...
MoleculeContainer to RDKit molecule object converter def to_rdkit_molecule(data): """ MoleculeContainer to RDKit molecule object converter """ mol = RWMol() conf = Conformer() mapping = {} is_3d = False for n, a in data.atoms(): ra = Atom(a.number) ra.SetAtomMapNum(n) ...
modified NX dfs def __dfs(self, start, weights, depth_limit): """ modified NX dfs """ adj = self._adj stack = [(start, depth_limit, iter(sorted(adj[start], key=weights)))] visited = {start} disconnected = defaultdict(list) edges = defaultdict(list) ...
Return a parser for command line options. def get_args_parser(): """Return a parser for command line options.""" parser = argparse.ArgumentParser( description='Marabunta: Migrating ants for Odoo') parser.add_argument('--migration-file', '-f', action=EnvDefault, ...
Constructor from command line args. :param args: parse command line arguments :type args: argparse.ArgumentParser def from_parse_args(cls, args): """Constructor from command line args. :param args: parse command line arguments :type args: argparse.ArgumentParser """ ...