text
stringlengths
81
112k
Creates a ``Board`` with the standard chess starting position. :rtype: Board def init_default(cls): """ Creates a ``Board`` with the standard chess starting position. :rtype: Board """ return cls([ # First rank [Rook(white, Location(0, 0)), Kni...
Finds the advantage a particular side possesses given a value scheme. :type: input_color: Color :type: val_scheme: PieceValues :rtype: double def material_advantage(self, input_color, val_scheme): """ Finds the advantage a particular side possesses given a value scheme. ...
Calculates advantage after move is played :type: move: Move :type: val_scheme: PieceValues :rtype: double def advantage_as_result(self, move, val_scheme): """ Calculates advantage after move is played :type: move: Move :type: val_scheme: PieceValues :rt...
Checks if all the possible moves has already been calculated and is stored in `possible_moves` dictionary. If not, it is calculated with `_calc_all_possible_moves`. :type: input_color: Color :rtype: list def all_possible_moves(self, input_color): """ Checks if a...
Returns list of all possible moves :type: input_color: Color :rtype: list def _calc_all_possible_moves(self, input_color): """ Returns list of all possible moves :type: input_color: Color :rtype: list """ for piece in self: # Tests if squar...
Runs multiple processes in parallel. :type: fns: def def runInParallel(*fns): """ Runs multiple processes in parallel. :type: fns: def """ proc = [] for fn in fns: p = Process(target=fn) p.start() proc.append(p) for p...
Finds Location of the first piece that matches piece. If none is found, Exception is raised. :type: piece: Piece :rtype: Location def find_piece(self, piece): """ Finds Location of the first piece that matches piece. If none is found, Exception is raised. :type...
Gets location of a piece on the board given the type and color. :type: piece_type: Piece :type: input_color: Color :rtype: Location def get_piece(self, piece_type, input_color): """ Gets location of a piece on the board given the type and color. :type:...
Places piece at given get_location :type: piece: Piece :type: location: Location def place_piece_at_square(self, piece, location): """ Places piece at given get_location :type: piece: Piece :type: location: Location """ self.position[location.rank][loca...
Moves piece from one location to another :type: initial: Location :type: final: Location def move_piece(self, initial, final): """ Moves piece from one location to another :type: initial: Location :type: final: Location """ self.place_piece_at_square(se...
Updates position by applying selected move :type: move: Move def update(self, move): """ Updates position by applying selected move :type: move: Move """ if move is None: raise TypeError("Move cannot be type None") if self.king_loc_dict is not None...
calc unbalanced charges and radicals for skin atoms def _balance(self, ): """ calc unbalanced charges and radicals for skin atoms """ meta = h.meta for n in (skin_reagent.keys() | skin_product.keys()): lost = skin_reagent[n] cycle_lost = cycle(lost) n...
search bond breaks and creations def clone_subgraphs(self, g): if not isinstance(g, CGRContainer): raise InvalidData('only CGRContainer acceptable') r_group = [] x_group = {} r_group_clones = [] newcomponents = [] ''' search bond breaks and creations ...
get atoms paths from detached atom to attached :param g: CGRContainer :return: tuple of atoms numbers def __get_substitution_paths(g): """ get atoms paths from detached atom to attached :param g: CGRContainer :return: tuple of atoms numbers """ for n, n...
Read versions from the table The versions are kept in cache for the next reads. def versions(self): """ Read versions from the table The versions are kept in cache for the next reads. """ if self._versions is None: with self.database.cursor_autocommit() as cursor: ...
Prepares menu entries for auto-generated model CRUD views. This is simple version of :attr:`get_crud_menus()` without Category support and permission control. Just for development purposes. Returns: Dict of list of dicts (``{'':[{}],}``). Menu entries. def simple_crud(): ...
Generates menu entries according to :attr:`zengine.settings.OBJECT_MENU` and permissions of current user. Returns: Dict of list of dicts (``{'':[{}],}``). Menu entries. def get_crud_menus(self): """ Generates menu entries according to :attr:`zengine.settings...
Creates a menu entry for given model data. Updates results in place. Args: model_data: Model data. object_type: Relation name. results: Results dict. def _add_crud(self, model_data, object_type, results): """ Creates a menu entry for given model data...
Appends menu entries to dashboard quickmenu according to :attr:`zengine.settings.QUICK_MENU` Args: key: workflow name wf: workflow menu entry def _add_to_quick_menu(self, key, wf): """ Appends menu entries to dashboard quickmenu according to :attr:`zengi...
Creates menu entries for custom workflows. Returns: Dict of list of dicts (``{'':[{}],}``). Menu entries. def _get_workflow_menus(self): """ Creates menu entries for custom workflows. Returns: Dict of list of dicts (``{'':[{}],}``). Menu entries. """ ...
Do response processing def process_response(self, request, response, resource): """ Do response processing """ origin = request.get_header('Origin') if not settings.DEBUG: if origin in settings.ALLOWED_ORIGINS or not origin: response.set_header('Acces...
Do response processing def process_request(self, req, resp): """ Do response processing """ if not req.client_accepts_json: raise falcon.HTTPNotAcceptable( 'This API only supports responses encoded as JSON.', href='http://docs.examples.com/api...
Do response processing def process_request(self, req, resp): """ Do response processing """ # req.stream corresponds to the WSGI wsgi.input environ variable, # and allows you to read bytes from the request body. # # See also: PEP 3333 if req.content_lengt...
Serializes ``req.context['result']`` to resp.body as JSON. If :attr:`~zengine.settings.DEBUG` is True, ``sys._debug_db_queries`` (set by pyoko) added to response. def process_response(self, req, resp, resource): """ Serializes ``req.context['result']`` to resp.body as JSON. If...
Creates connection to RabbitMQ server def connect(self): """ Creates connection to RabbitMQ server """ if self.connecting: log.info('PikaClient: Already connecting to RabbitMQ') return log.info('PikaClient: Connecting to RabbitMQ') self.connectin...
AMQP connection callback. Creates input channel. Args: connection: AMQP connection def on_connected(self, connection): """ AMQP connection callback. Creates input channel. Args: connection: AMQP connection """ log.info('PikaClien...
Input channel creation callback Queue declaration done here Args: channel: input channel def on_channel_open(self, channel): """ Input channel creation callback Queue declaration done here Args: channel: input channel """ self.in...
Input queue declaration callback. Input Queue/Exchange binding done here Args: queue: input queue def on_input_queue_declare(self, queue): """ Input queue declaration callback. Input Queue/Exchange binding done here Args: queue: input queue ...
Incoming request handler. :param request: Werkzeug request object def wsgi_app(self, request): """Incoming request handler. :param request: Werkzeug request object """ try: if request.method != 'POST': abort(400) try: #...
close opened file :param force: force closing of externally opened file or buffer def close(self, force=False): """ close opened file :param force: force closing of externally opened file or buffer """ if self.__write: self.write = self.__write_adhoc ...
map unmapped atoms. def _convert_reaction(self, reaction): if not (reaction['reactants'] or reaction['products'] or reaction['reagents']): raise ValueError('empty reaction') maps = {'reactants': [], 'products': [], 'reagents': []} for i, tmp in maps.items(): for molecule...
convert structure to aromatic form :return: number of processed rings def aromatize(self): """ convert structure to aromatic form :return: number of processed rings """ rings = [x for x in self.sssr if 4 < len(x) < 7] if not rings: return 0 ...
Runs the crawl job for n rounds :param seed_list: lines of seed URLs :param n: number of rounds :return: number of successful rounds def crawl_cmd(self, seed_list, n): ''' Runs the crawl job for n rounds :param seed_list: lines of seed URLs :param n: number of ro...
Creates a new config from xml file. :param xml_file: path to xml file. Format : nutch-site.xml or nutch-default.xml :param id: :return: config object def load_xml_conf(self, xml_file, id): ''' Creates a new config from xml file. :param xml_file: path to xml file. Format ...
'create' sub-command :param args: cli arguments :return: def create_cmd(self, args): ''' 'create' sub-command :param args: cli arguments :return: ''' cmd = args.get('cmd_create') if cmd == 'conf': conf_file = args['conf_file'] ...
write close tag of MRV file and close opened file :param force: force closing of externally opened file or buffer def close(self, *args, **kwargs): """ write close tag of MRV file and close opened file :param force: force closing of externally opened file or buffer """ ...
write single molecule or reaction into file def write(self, data): """ write single molecule or reaction into file """ self._file.write('<cml>') self.__write(data) self.write = self.__write
the method is implemented for the purpose of optimization, byte positions will not be re-read from a file that has already been used, if the content of the file has changed, and the name has been left the same, the old version of byte offsets will be loaded :return: list of byte offsets from exi...
_shifts dumps in /tmp directory after reboot it will drop def _dump_cache(self, _shifts): """ _shifts dumps in /tmp directory after reboot it will drop """ with open(self.__cache_path, 'wb') as f: dump(_shifts, f)
List task types for current user .. code-block:: python # request: { 'view': '_zops_get_task_types', } # response: { 'task_types': [ {'name': string, # wf ...
Show task details .. code-block:: python # request: { 'view': '_zops_get_task_detail', 'key': key, } # response: { 'task_title': string, 'tas...
List task types for current user .. code-block:: python # request: { 'view': '_zops_get_task_actions', 'key': key, } # response: { 'key': key, ...
List task invitations of current user .. code-block:: python # request: { 'view': '_zops_get_tasks', 'state': string, # one of these: # "active", "future", "finished", "expired" 'inverted': boolean, ...
reduce memory usage of the dataframe - convert runIDs to categorical - downcast ints and floats def reduce_memory_usage(df): """reduce memory usage of the dataframe - convert runIDs to categorical - downcast ints and floats """ usage_pre = df.memory_usage(deep=True).sum() if "runIDs" ...
Check if the file supplied as input exists. def check_existance(f): """Check if the file supplied as input exists.""" if not opath.isfile(f): logging.error("Nanoget: File provided doesn't exist or the path is incorrect: {}".format(f)) sys.exit("File provided doesn't exist or the path is incorre...
Lists user roles as selectable except user's current role. def list_user_roles(self): """ Lists user roles as selectable except user's current role. """ _form = JsonForm(current=self.current, title=_(u"Switch Role")) _form.help_text = "Your current role: %s %s" % (self.current.r...
Changes user's role from current role to chosen role. def change_user_role(self): """ Changes user's role from current role to chosen role. """ # Get chosen role_key from user form. role_key = self.input['form']['role_options'] # Assign chosen switch role key to user's ...
Returns user's role list except current role as a tuple (role.key, role.name) Returns: (list): list of tuples, user's role list except current role def get_user_switchable_roles(self): """ Returns user's role list except current role as a tuple (role.key, role.name)...
Wrapper for es.index, determines metadata needed to index from obj. If you have a raw object json string you can hard code these: index is .kibana (as of kibana4); id can be A-Za-z0-9\- and must be unique; doc_type is either visualization, dashboard, search or for settings do...
Debug deletes obj of obj[_type] with id of obj['_id'] def del_object(self, obj): """Debug deletes obj of obj[_type] with id of obj['_id']""" if obj['_index'] is None or obj['_index'] == "": raise Exception("Invalid Object") if obj['_id'] is None or obj['_id'] == "": rais...
Serializer for consistency def json_dumps(self, obj): """Serializer for consistency""" return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
Santize obj name into fname and verify doesn't already exist def safe_filename(self, otype, oid): """Santize obj name into fname and verify doesn't already exist""" permitted = set(['_', '-', '(', ')']) oid = ''.join([c for c in oid if c.isalnum() or c in permitted]) while oid.find('--'...
Convert obj (dict) to json string and write to file def write_object_to_file(self, obj, path='.', filename=None): """Convert obj (dict) to json string and write to file""" output = self.json_dumps(obj) + '\n' if filename is None: filename = self.safe_filename(obj['_type'], obj['_id'...
Write a list of related objs to file def write_pkg_to_file(self, name, objects, path='.', filename=None): """Write a list of related objs to file""" # Kibana uses an array of docs, do the same # as opposed to a dict of docs pkg_objs = [] for _, obj in iteritems(objects): ...
Return all objects of type (assumes < MAX_HITS) def get_objects(self, search_field, search_val): """Return all objects of type (assumes < MAX_HITS)""" query = ("{ size: " + str(self.max_hits) + ", " + "query: { filtered: { filter: { " + search_field + ": { value: \"" +...
Get DB and all objs needed to duplicate it def get_dashboard_full(self, db_name): """Get DB and all objs needed to duplicate it""" objects = {} dashboards = self.get_objects("type", "dashboard") vizs = self.get_objects("type", "visualization") searches = self.get_objects("type",...
Overrides ProcessParser.parse_node Parses and attaches the inputOutput tags that created by Camunda Modeller Args: node: xml task node Returns: TaskSpec def parse_node(self, node): """ Overrides ProcessParser.parse_node Parses and attaches the i...
Tries to get WF description from 'collabration' or 'process' or 'pariticipant' Returns: def _get_description(self): """ Tries to get WF description from 'collabration' or 'process' or 'pariticipant' Returns: """ ns = {'ns': '{%s}' % BPMN_MODEL_NS} desc = ( ...
Tries to get WF name from 'process' or 'collobration' or 'pariticipant' Returns: str. WF name. def get_name(self): """ Tries to get WF name from 'process' or 'collobration' or 'pariticipant' Returns: str. WF name. """ ns = {'ns': '{%s}' % BPMN_M...
Parses inputOutput part camunda modeller extensions. Args: node: SpiffWorkflow Node object. Returns: Data dict. def _parse_input_data(self, node): """ Parses inputOutput part camunda modeller extensions. Args: node: SpiffWorkflow Node object....
Parses the given XML node Args: node (xml): XML node. .. code-block:: xml <bpmn2:lane id="Lane_8" name="Lane 8"> <bpmn2:extensionElements> <camunda:properties> <camunda:property value="foo,bar" name="perms"/> ...
:param node: xml node :return: dict def _parse_input_node(cls, node): """ :param node: xml node :return: dict """ data = {} child = node.getchildren() if not child and node.get('name'): val = node.text elif child: # if tag = "{http://...
Generates wf packages from workflow diagrams. Args: workflow_name: Name of wf workflow_files: Diagram file. Returns: Workflow package (file like) object def package_in_memory(cls, workflow_name, workflow_files): """ Generates wf packages from work...
condense reaction container to CGR. see init for details about cgr_type :param data: ReactionContainer :return: CGRContainer def compose(self, data): """ condense reaction container to CGR. see init for details about cgr_type :param data: ReactionContainer :return: CGR...
new atom addition def add_atom(self, atom, _map=None): """ new atom addition """ if _map is None: _map = max(self, default=0) + 1 elif _map in self._node: raise KeyError('atom with same number exists') attr_dict = self.node_attr_dict_factory() ...
implementation of bond addition def add_bond(self, atom1, atom2, bond): """ implementation of bond addition """ if atom1 == atom2: raise KeyError('atom loops impossible') if atom1 not in self._node or atom2 not in self._node: raise KeyError('atoms not fou...
implementation of bond removing def delete_bond(self, n, m): """ implementation of bond removing """ self.remove_edge(n, m) self.flush_cache()
pairs of (bond, atom) connected to atom :param atom: number :return: list def environment(self, atom): """ pairs of (bond, atom) connected to atom :param atom: number :return: list """ return tuple((bond, self._node[n]) for n, bond in self._adj[atom].it...
create substructure containing atoms from nbunch list :param atoms: list of atoms numbers of substructure :param meta: if True metadata will be copied to substructure :param as_view: If True, the returned graph-view provides a read-only view of the original structure scaffold withou...
create substructure containing atoms and their neighbors :param atoms: list of core atoms in graph :param dante: if True return list of graphs containing atoms, atoms + first circle, atoms + 1st + 2nd, etc up to deep or while new nodes available :param deep: number of bonds between ...
split disconnected structure to connected substructures :param meta: copy metadata to each substructure :return: list of substructures def split(self, meta=False): """ split disconnected structure to connected substructures :param meta: copy metadata to each substructure ...
iterate other all bonds def bonds(self): """ iterate other all bonds """ seen = set() for n, m_bond in self._adj.items(): seen.add(n) for m, bond in m_bond.items(): if m not in seen: yield n, m, bond
need for cyclic import solving def _get_subclass(name): """ need for cyclic import solving """ return next(x for x in BaseContainer.__subclasses__() if x.__name__ == name)
Creates a urllib3.PoolManager object that has SSL verification enabled and uses the certifi certificates. def _default_make_pool(http, proxy_info): """Creates a urllib3.PoolManager object that has SSL verification enabled and uses the certifi certificates.""" if not http.ca_certs: http.ca_cert...
Monkey-patches httplib2.Http to be httplib2shim.Http. This effectively makes all clients of httplib2 use urlilb3. It's preferable to specify httplib2shim.Http explicitly where you can, but this can be useful in situations where you do not control the construction of the http object. Args: ...
Checks if a given address is an IPv6 address. def _is_ipv6(addr): """Checks if a given address is an IPv6 address.""" try: socket.inet_pton(socket.AF_INET6, addr) return True except socket.error: return False
Gets the right location for certifi certifications for the current SSL version. Older versions of SSL don't support the stronger set of root certificates. def _certifi_where_for_ssl_version(): """Gets the right location for certifi certifications for the current SSL version. Older versions of SSL...
Maps a urllib3 response to a httplib/httplib2 Response. def _map_response(response, decode=False): """Maps a urllib3 response to a httplib/httplib2 Response.""" # This causes weird deepcopy errors, so it's commented out for now. # item._urllib3_response = response item = httplib2.Response(response.geth...
Maps an exception from urlib3 to httplib2. def _map_exception(e): """Maps an exception from urlib3 to httplib2.""" if isinstance(e, urllib3.exceptions.MaxRetryError): if not e.reason: return e e = e.reason message = e.args[0] if e.args else '' if isinstance(e, urllib3.except...
subprocess handler def run_workers(no_subprocess, watch_paths=None, is_background=False): """ subprocess handler """ import atexit, os, subprocess, signal if watch_paths: from watchdog.observers import Observer # from watchdog.observers.fsevents import FSEventsObserver as Observer ...
Properly close the AMQP connections def exit(self, signal=None, frame=None): """ Properly close the AMQP connections """ self.input_channel.close() self.client_queue.close() self.connection.close() log.info("Worker exiting") sys.exit(0)
make amqp connection and create channels and queue binding def connect(self): """ make amqp connection and create channels and queue binding """ self.connection = pika.BlockingConnection(BLOCKING_MQ_PARAMS) self.client_queue = ClientQueue() self.input_channel = self.conn...
clear outs all messages from INPUT_QUEUE_NAME def clear_queue(self): """ clear outs all messages from INPUT_QUEUE_NAME """ def remove_message(ch, method, properties, body): print("Removed message: %s" % body) self.input_channel.basic_consume(remove_message, queue=sel...
actual consuming of incoming works starts here def run(self): """ actual consuming of incoming works starts here """ self.input_channel.basic_consume(self.handle_message, queue=self.INPUT_QUEUE_NAME, no_ac...
this is a pika.basic_consumer callback handles client inputs, runs appropriate workflows and views Args: ch: amqp channel method: amqp method properties: body: message body def handle_message(self, ch, method, properties, body): """ this ...
Args: start (DateTime): start date finish (DateTime): finish date Returns: def get_progress(start, finish): """ Args: start (DateTime): start date finish (DateTime): finish date Returns: """ now = datetime.now() dif_time_start = start - now dif_time_fini...
BG Job for storing wf state to DB def sync_wf_cache(current): """ BG Job for storing wf state to DB """ wf_cache = WFCache(current) wf_state = wf_cache.get() # unicode serialized json to dict, all values are unicode if 'role_id' in wf_state: # role_id inserted by engine, so it's a sign...
if xml content updated, create a new entry for given wf name Args: name: name of wf content: xml content Returns (DiagramXML(), bool): A tuple with two members. (DiagramXML instance and True if it's new or False it's already exists def get_or_create_by_content(cls, name...
Tries to get WF description from 'collabration' or 'process' or 'pariticipant' Returns str: WF description def get_description(self): """ Tries to get WF description from 'collabration' or 'process' or 'pariticipant' Returns str: WF description """ paths = ['bpmn:coll...
Tries to get WF name from 'process' or 'collobration' or 'pariticipant' Returns: str. WF name. def get_name(self): """ Tries to get WF name from 'process' or 'collobration' or 'pariticipant' Returns: str. WF name. """ paths = ['bpmn:process', ...
updates xml link if there aren't any running instances of this wf Args: diagram: XMLDiagram object def set_xml(self, diagram, force=False): """ updates xml link if there aren't any running instances of this wf Args: diagram: XMLDiagram object """ ...
Creates wf instances. Args: roles (list): role list Returns: (list): wf instances def create_wf_instances(self, roles=None): """ Creates wf instances. Args: roles (list): role list Returns: (list): wf instances ""...
will create a WFInstance per object and per TaskInvitation for each role and WFInstance def create_tasks(self): """ will create a WFInstance per object and per TaskInvitation for each role and WFInstance """ roles = self.get_roles() if self.task_type in ["A", "D...
returns objects keys according to self.object_query_code which can be json encoded queryset filter dict or key=value set in the following format: ```"key=val, key2 = val2 , key3= value with spaces"``` Returns: (dict): Queryset filtering dicqt def get_object_query_dict(self): ...
returns object keys according to task definition which can be explicitly selected one object (self.object_key) or result of a queryset filter. Returns: list of object keys def get_object_keys(self, wfi_role=None): """returns object keys according to task definition ...
Fetches model objects by filtering with kwargs If wfi_role is specified, then we expect kwargs contains a filter value starting with role, e.g. {'user': 'role.program.user'} We replace this `role` key with role instance parameter `wfi_role` and try to get object that filter va...
Returns: Role instances according to task definition. def get_roles(self): """ Returns: Role instances according to task definition. """ if self.role.exist: # return explicitly selected role return [self.role] else: rol...
can be removed when a proper task manager admin interface implemented def post_save(self): """can be removed when a proper task manager admin interface implemented""" if self.run: self.run = False self.create_tasks() self.save()
When one person use an invitation, we should delete other invitations def delete_other_invitations(self): """ When one person use an invitation, we should delete other invitations """ # TODO: Signal logged-in users to remove the task from their task list self.objects.filter(inst...
write wf state to DB through MQ >> Worker >> _zops_sync_wf_cache Args: wf_state dict: wf state def save(self, wf_state): """ write wf state to DB through MQ >> Worker >> _zops_sync_wf_cache Args: wf_state dict: wf state """ self.wf_state = wf_st...