code
stringlengths
1
18.2k
def get_input(source, files, threads=4, readtype="1D", combine="simple", names=None, barcoded=False): """Get input and process accordingly. Data can be: - a uncompressed, bgzip, bzip2 or gzip compressed fastq file - a uncompressed, bgzip, bzip2 or gzip compressed fasta file - a rich fastq containing additional key=valu...
file - a sorted cram file - a (compressed) sequencing_summary.txt file generated by albacore Handle is passed to the proper functions to get DataFrame with metrics Multiple files of the same type can be used to extract info from, which is done in parallel Arguments: - source: defines the input data type and the functio...
list of one or more files to operate on, from the type of <source> - threads: is the amount of workers which can be used - readtype: (only relevant for summary input) and specifies which columns have to be extracted - combine: is either 'simple' or 'track', with the difference that with 'track' an additional field is c...
- names: if combine="track", the names to be used for the datasets. Needs to have same length as files, or None """ proc_functions = { 'fastq': ex.process_fastq_plain, 'fasta': ex.process_fasta, 'bam': ex.process_bam, 'summary': ex.process_summary, 'fastq_rich': ex.process_fastq_rich, 'fastq_minimal': ex.process_fastq_...
dfs=[out for out in executor.map(extration_function, files)], names=names or files, method=combine) if "readIDs" in datadf and pd.isna(datadf["readIDs"]).any(): datadf.drop("readIDs", axis='columns', inplace=True) datadf = calculate_start_time(datadf) logging.info("Nanoget: Gathered all metrics of {} reads".format(len(...
def combine_dfs(dfs, names, method): """Combine dataframes. Combination is either done simple by just concatenating the DataFrames or performs tracking by adding the name of the dataset as a column.""" if method == "track": res = list() for df, identifier in zip(dfs, names): df["dataset"] = identifier res.append(df) re...
def calculate_start_time(df): """Calculate the star_time per read. Time data is either a "time" (in seconds, derived from summary files) or a "timestamp" (in UTC, derived from fastq_rich format) and has to be converted appropriately in a datetime format time_arr For both the time_zero is the minimal value of the time_a...
method=track (and dataset is a column in the df) then this subtraction is done per dataset """ if "time" in df: df["time_arr"] = pd.Series(df["time"], dtype='datetime64[s]') elif "timestamp" in df: df["time_arr"] = pd.Series(df["timestamp"], dtype="datetime64[ns]") else: return df if "dataset" in df: for dset in df["da...
= df["time_arr"] - df["time_arr"].min() return df.drop(["time", "timestamp", "time_arr"], axis=1, errors="ignore")
def parser_from_buffer(cls, fp): """Construct YamlParser from a file pointer.""" yaml = YAML(typ="safe") return cls(yaml.load(fp))
def check_dict_expected_keys(self, expected_keys, current, dict_name): """ Check that we don't have unknown keys in a dictionary. It does not raise an error if we have less keys than expected. """ if not isinstance(current, dict): raise ParseError(u"'{}' key must be a dict".format(dict_name), YAML_EXAMPLE) expected_key...
{} are unexpected. (allowed keys: {})" raise ParseError( message.format( dict_name, list(extra_keys), list(expected_keys), ), YAML_EXAMPLE, )
def parse(self): """Check input and return a :class:`Migration` instance.""" if not self.parsed.get('migration'): raise ParseError(u"'migration' key is missing", YAML_EXAMPLE) self.check_dict_expected_keys( {'options', 'versions'}, self.parsed['migration'], 'migration', ) return self._parse_migrations()
def _parse_migrations(self): """Build a :class:`Migration` instance.""" migration = self.parsed['migration'] options = self._parse_options(migration) versions = self._parse_versions(migration, options) return Migration(versions, options)
def _parse_options(self, migration): """Build :class:`MigrationOption` and :class:`MigrationBackupOption` instances.""" options = migration.get('options', {}) install_command = options.get('install_command') backup = options.get('backup') if backup: self.check_dict_expected_keys( {'command', 'ignore_if', 'stop_on_failu...
def set_message(self, title, msg, typ, url=None): """ Sets user notification message. Args: title: Msg. title msg: Msg. text typ: Msg. type url: Additional URL (if exists) Returns: Message ID. """ return self.user.send_notification(title=title, message=msg, typ=typ, url=url)
def is_auth(self): """ A property that indicates if current user is logged in or not. Returns: Boolean. """ if self.user_id is None: self.user_id = self.session.get('user_id') return bool(self.user_id)
def has_permission(self, perm): """ Checks if current user (or role) has the given permission. Args: perm: Permmission code or object. Depends on the :attr:`~zengine.auth.auth_backend.AuthBackend` implementation. Returns: Boolean. """ return self.user.superuser or self.auth.has_permission(perm)
def msg_box(self, msg, title=None, typ='info'): """ Create a message box :param str msg: :param str title: :param str typ: 'info', 'error', 'warning' """ self.output['msgbox'] = {'type': typ, "title": title or msg[:20], "msg": msg}
def sendoff_current_user(self): """ Tell current user that s/he finished it's job for now. We'll notify if workflow arrives again to his/her WF Lane. """ msgs = self.task_data.get('LANE_CHANGE_MSG', DEFAULT_LANE_CHANGE_MSG) self.msg_box(title=msgs['title'], msg=msgs['body'])
def invite_other_parties(self, possible_owners): """ Invites the next lane's (possible) owner(s) to participate """ signals.lane_user_change.send(sender=self.user, current=self, old_lane=self.old_lane, possible_owners=possible_owners )
def _update_task(self, task): """ Assigns current task step to self.task then updates the task's data with self.task_data Args: task: Task object. """ self.task = task self.task.data.update(self.task_data) self.task_type = task.task_spec.__class__.__name__ self.spec = task.task_spec self.task_name = task.get_name() sel...
def set_client_cmds(self): """ This is method automatically called on each request and updates "object_id", "cmd" and "flow" client variables from current.input. "flow" and "object_id" variables will always exists in the task_data so app developers can safely check for their values in workflows. Their values will be re...
there isn't a "cmd" in the current.input cmd will be removed from task_data. """ self.task_data['cmd'] = self.input.get('cmd') self.task_data['flow'] = self.input.get('flow') filters = self.input.get('filters', {}) try: if isinstance(filters, dict): # this is the new form, others will be removed when ui be ready self.t...
def generate_move(self, position): """ Returns valid and legal move given position :type: position: Board :rtype: Move """ while True: print(position) raw = input(str(self.color) + "\'s move \n") move = converter.short_alg(raw, self.color, position) if move is None: continue return move
def in_check_as_result(self, pos, move): """ Finds if playing my move would make both kings meet. :type: pos: Board :type: move: Move :rtype: bool """ test = cp(pos) test.update(move) test_king = test.get_king(move.color) return self.loc_adjacent_to_opponent_king(test_king.location, test)
def loc_adjacent_to_opponent_king(self, location, position): """ Finds if 2 kings are touching given the position of one of the kings. :type: location: Location :type: position: Board :rtype: bool """ for fn in self.cardinal_directions: try: if isinstance(position.piece_at_square(fn(location)), King) and \ position.pie...
def add(self, func, position): """ Adds all 8 cardinal directions as moves for the King if legal. :type: function: function :type: position: Board :rtype: gen """ try: if self.loc_adjacent_to_opponent_king(func(self.location), position): return except IndexError: return if position.is_square_empty(func(self.location)):...
def _rook_legal_for_castle(self, rook): """ Decides if given rook exists, is of this color, and has not moved so it is eligible to castle. :type: rook: Rook :rtype: bool """ return rook is not None and \ type(rook) is Rook and \ rook.color == self.color and \ not rook.has_moved
def _empty_not_in_check(self, position, direction): """ Checks if set of squares in between ``King`` and ``Rook`` are empty and safe for the king to castle. :type: position: Position :type: direction: function :type: times: int :rtype: bool """ def valid_square(square): return position.is_square_empty(square) and \ not...
def add_castle(self, position): """ Adds kingside and queenside castling moves if legal :type: position: Board """ if self.has_moved or self.in_check(position): return if self.color == color.white: rook_rank = 0 else: rook_rank = 7 castle_type = { notation_const.KING_SIDE_CASTLE: { "rook_file": 7, "direction": lambda k...
= position.piece_at_square(Location(rook_rank, castle_dict["rook_file"])) if self._rook_legal_for_castle(castle_rook) and \ self._empty_not_in_check(position, castle_dict["direction"]): yield self.create_move(castle_dict["direction"](self.location, 2), castle_key)
def possible_moves(self, position): """ Generates list of possible moves :type: position: Board :rtype: list """ # Chain used to combine multiple generators for move in itertools.chain(*[self.add(fn, position) for fn in self.cardinal_directions]): yield move for move in self.add_castle(position): yield move
def in_check(self, position, location=None): """ Finds if the king is in check or if both kings are touching. :type: position: Board :return: bool """ location = location or self.location for piece in position: if piece is not None and piece.color != self.color: if not isinstance(piece, King): for move in piece.possibl...
def set_keep_alive(sock, idle=10, interval=5, fails=5): """Sets the keep-alive setting for the peer socket. :param sock: Socket to be configured. :param idle: Interval in seconds after which for an idle connection a keep-alive probes is start being sent. :param interval: Interval in seconds between probes. :param fails...
idle) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, fails) elif sys.platform == 'darwin': sock.setsockopt(socket.IPPROTO_TCP, 0x10, interval) else: # Do nothing precise for unsupported platforms. pass
def init_default(cls): """ Creates a ``Board`` with the standard chess starting position. :rtype: Board """ return cls([ # First rank [Rook(white, Location(0, 0)), Knight(white, Location(0, 1)), Bishop(white, Location(0, 2)), Queen(white, Location(0, 3)), King(white, Location(0, 4)), Bishop(white, Location(0, 5)), Knig...
rank [None for _ in range(8)], # Fifth rank [None for _ in range(8)], # Sixth rank [None for _ in range(8)], # Seventh rank [Pawn(black, Location(6, file)) for file in range(8)], # Eighth rank [Rook(black, Location(7, 0)), Knight(black, Location(7, 1)), Bishop(black, Location(7, 2)), Queen(black, Location(7, 3)), King(...
def material_advantage(self, input_color, val_scheme): """ Finds the advantage a particular side possesses given a value scheme. :type: input_color: Color :type: val_scheme: PieceValues :rtype: double """ if self.get_king(input_color).in_check(self) and self.no_moves(input_color): return -100 if self.get_king(-input_co...
def advantage_as_result(self, move, val_scheme): """ Calculates advantage after move is played :type: move: Move :type: val_scheme: PieceValues :rtype: double """ test_board = cp(self) test_board.update(move) return test_board.material_advantage(move.color, val_scheme)
def all_possible_moves(self, input_color): """ 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 """ position_tuple = self.position_tuple if position_tuple not in sel...
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 square on the board is not empty if piece is not None and piece.color == input_color: for move in piece.possible_moves(self): test = cp(self) test_move = Move(...
if my_king is None or \ not isinstance(my_king, King) or \ my_king.color != input_color: self.king_loc_dict[input_color] = test.find_king(input_color) my_king = test.piece_at_square(self.king_loc_dict[input_color]) if not my_king.in_check(test): yield move
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 in proc: p.join()
def find_piece(self, piece): """ Finds Location of the first piece that matches piece. If none is found, Exception is raised. :type: piece: Piece :rtype: Location """ for i, _ in enumerate(self.position): for j, _ in enumerate(self.position): loc = Location(i, j) if not self.is_square_empty(loc) and \ self.piece_at_squ...
def get_piece(self, piece_type, input_color): """ Gets location of a piece on the board given the type and color. :type: piece_type: Piece :type: input_color: Color :rtype: Location """ for loc in self: piece = self.piece_at_square(loc) if not self.is_square_empty(loc) and \ isinstance(piece, piece_type) and \ piece.co...
def place_piece_at_square(self, piece, location): """ Places piece at given get_location :type: piece: Piece :type: location: Location """ self.position[location.rank][location.file] = piece piece.location = 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(self.piece_at_square(initial), final) self.remove_piece_at_square(initial)
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 and isinstance(move.piece, King): self.king_loc_dict[move.color] = move.end_loc # Invalidates en-passant for square in self: pawn = ...
if type(move.piece) is King or type(move.piece) is Rook: move.piece.has_moved = True elif move.status == notation_const.MOVEMENT and \ isinstance(move.piece, Pawn) and \ fabs(move.end_loc.rank - move.start_loc.rank) == 2: move.piece.just_moved_two_steps = True if move.status == notation_const.KING_SIDE_CASTLE: self.mov...
\ move.status == notation_const.CAPTURE_AND_PROMOTE: try: self.remove_piece_at_square(move.start_loc) self.place_piece_at_square(move.promoted_to_piece(move.color, move.end_loc), move.end_loc) except TypeError as e: raise ValueError("Promoted to piece cannot be None in Move {}\n{}".format(repr(move), e)) return self.mo...
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) new = skin_product[n] cycle_new = cycle(new) atom = h._node[n] dr = atom.p_radical - atom.radical # radical balancing if d...
h._node[m] s_atom.p_multiplicity = radical_unmap[s_atom.p_radical + 1] meta.setdefault('rule #14. atom lost. common atom radical added or increased. ' 'lost atom radical added', []).append((m, n)) for m in lost[dr:]: meta.setdefault('rule #15. atom lost. common atom radical added or increased. ' 'lost atom radical unch...
lost. common atom radical removed or decreased. ' 'lost atom radical unchanged', []).append((m, n)) else: for _, m in zip(range(-dr), cycle_lost): # radical elimination s_atom = h._node[m] s_atom.p_multiplicity = radical_unmap[s_atom.p_radical + 1] meta.setdefault('rule #21. atom lost. common atom radical removed or de...
'lost atom radical unchanged', []).append((m, n)) else: env = h.environment(n) sv = atom.get_valence([(b.reagent, a.reagent) for b, a in env if b.order]) pv = atom.p_get_valence([(b.product, a.product) for b, a in env if b.p_order]) sh, ph = h.atom_total_h(n) dv = pv - sv dh = ph - sh dc = atom.p_charge - atom.charge i...
for m in skins: meta.setdefault('rule #1. atom lost. common atom unchanged. ' 'substitution, elimination, addition', []).append((m, n)) elif dv == dh == dc < 0: # explicit hydrogen removing for m in skins: h._node[m].p_charge = 1 meta.setdefault('rule #4. atom lost. common atom deprotonation', []).append((m, n)) else: ...
n)) pth = ph + sum(h.atom_total_h(x)[1] for x in skins) if n in skin_product: sth = sh + sum(h.atom_total_h(x)[0] for x in skin_product[n]) else: sth = sh dth = pth - sth for n, skins in skin_product.items(): cycle_skins = cycle(skins) atom = h._node[n] dr = atom.p_radical - atom.radical # radical balancing if dr > 0: ...
for m in skins: meta.setdefault('rule #16. atom new. common atom radical added or increased. ' 'new atom radical unchanged', []).append((m, n)) else: for _, m in zip(range(dr), cycle_skins): # radical addition s_atom = h._node[m] s_atom.multiplicity = radical_unmap[s_atom.radical + 1] meta.setdefault('rule #17. atom ne...
common atom radical added or increased. ' 'new atom radical unchanged', []).append((m, n)) elif dr < 0: # radical removed or decreased. for _, m in zip(range(-dr), cycle_skins): # recombination s_atom = h._node[m] s_atom.multiplicity = radical_unmap[s_atom.radical + 1] meta.setdefault('rule #18. atom new. common atom r...
atom radical removed or decreased. ' 'new atom radical unchanged', []).append((m, n)) else: env = h.environment(n) sv = atom.get_valence([(b.reagent, a.reagent) for b, a in env if b.order]) pv = atom.p_get_valence([(b.product, a.product) for b, a in env if b.p_order]) sh, ph = h.atom_total_h(n) dv = pv - sv dh = ph - s...
# common atom unchanged. Substitution, Addition for m in skins: meta.setdefault('rule #2. atom new. common atom unchanged. ' 'substitution, elimination, addition', []).append((m, n)) elif dv == dh == dc > 0: # explicit hydrogen addition for m in skins: h._node[m].charge = 1 h.meta.setdefault('rule #3. atom new. common ...
'convert to reduction or oxidation', []).append((m, n)) sth = sh + sum(h.atom_total_h(x)[0] for x in skins) if n in skin_reagent: pth = ph + sum(h.atom_total_h(x)[1] for x in skin_reagent[n]) else: pth = ph dth = pth - sth for n, sp in reverse_ext.items(): # charge neutralization if dc > 0: for _ in range(dc): h.meta.s...
dc < 0: for _ in range(-dc): h.meta.setdefault('rule #8. charge neutralization. hydrogen radical added', []).append(h.add_atom(H(multiplicity=2), H(charge=1))) # hydrogen balancing if dth > 0: red_e = 0 for m in sp['products']: if h.nodes[m]['element'] == 'H': # set reduction H if explicit H count increased h.nodes[m][...
range(dth - red_e): # add reduction agents m = h.add_atom(H(multiplicity=2), H()) red.append(m) h.meta.setdefault('rule #10. protonation. hydrogen radical added', []).append(m) red = iter(red) dih = sub(*h.atom_implicit_h(n)) if dih < 0: # attach reduction H to central atom if implicit H atoms count increased for _ in ...
sp['reagents']: # attach reduction H if detached group implicit H count increased dih = sub(*h.atom_implicit_h(m)) if dih < 0: for _ in range(-dih): o = next(red) h.add_bond(o, m, None) elif dth < 0: oxo = [] for _ in range(-dth): m = h.add_atom(O(multiplicity=2), O()) oxo.append(m) h.meta.setdefault('rule #9. deproton...
= next(oxo) h.add_bond(o, m, None) h.meta.setdefault('rule #13. hydrogen accepting by hydroxide radical added', []).append(m) return h
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 ''' components, lost_bonds, term_atoms = self.__split_graph(g) lost_map = {x: y for x, y in lost_bonds...
in components: x_terminal_atom = x_terminals.intersection(i) if x_terminal_atom: x_group[x_terminal_atom.pop()] = i continue r_terminal_atom = r_terminals.intersection(i) if r_terminal_atom: r_group.append([r_terminal_atom, i]) continue newcomponents.append(i) ''' search similar R groups and patch. ''' tmp = g for i in...
k.issubset(x) and all(x[y] in term_atoms for y in k)), None) if mapping: r_group_clones.append([k, mapping]) tmp = compose(tmp, self.__remap_group(j, tmp, mapping)[0]) break ''' add lose X groups to R groups ''' for i, j in r_group_clones: for k in i: remappedgroup, mapping = self.__remap_group(x_group[lost_map[k]], tm...
def __get_substitution_paths(g): """ get atoms paths from detached atom to attached :param g: CGRContainer :return: tuple of atoms numbers """ for n, nbrdict in g.adjacency(): for m, l in combinations(nbrdict, 2): nms = nbrdict[m]['sp_bond'] nls = nbrdict[l]['sp_bond'] if nms == (1, None) and nls == (None, 1): yield m,...
m
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: query = """ SELECT number, date_start, date_done, log, addons FROM {} """.format(self.table_name) cursor.execute(query) rows = cursor.f...
[] versions.append( self.VersionRecord(*row) ) self._versions = versions return self._versions
def simple_crud(): """ 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. """ results = defaultdict(list) for mdl in m...
def get_crud_menus(self): """ Generates menu entries according to :attr:`zengine.settings.OBJECT_MENU` and permissions of current user. Returns: Dict of list of dicts (``{'':[{}],}``). Menu entries. """ results = defaultdict(list) for object_type in settings.OBJECT_MENU: for model_data in settings.OBJECT_MENU[object_ty...
def _add_crud(self, model_data, object_type, results): """ Creates a menu entry for given model data. Updates results in place. Args: model_data: Model data. object_type: Relation name. results: Results dict. """ model = model_registry.get_model(model_data['name']) field_name = model_data.get('field') verbose_name = mo...
def _add_to_quick_menu(self, key, wf): """ Appends menu entries to dashboard quickmenu according to :attr:`zengine.settings.QUICK_MENU` Args: key: workflow name wf: workflow menu entry """ if key in settings.QUICK_MENU: self.output['quick_menu'].append(wf)
def _get_workflow_menus(self): """ Creates menu entries for custom workflows. Returns: Dict of list of dicts (``{'':[{}],}``). Menu entries. """ results = defaultdict(list) from zengine.lib.cache import WFSpecNames for name, title, category in WFSpecNames().get_or_set(): if self.current.has_permission(name) and categor...
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('Access-Control-Allow-Origin', origin) else: log.debug("CORS ERROR: %s not allowed, allowed hosts:...
in the resource level response.set_header('Access-Control-Allow-Methods', 'OPTIONS')
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/json') if req.method in ('POST', 'PUT'): if req.content_length != 0 and \ 'application/json' not in...
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_length in (None, 0): # Nothing to do req.context['data'] = req.params.copy() req.context['res...
body', 'A valid JSON document is required.') try: json_data = body.decode('utf-8') req.context['data'] = json.loads(json_data) try: log.info("REQUEST DATA: %s" % json_data) except: log.exception("ERR: REQUEST DATA CANT BE LOGGED ") except (ValueError, UnicodeDecodeError): raise falcon.HTTPError(falcon.HTTP_753, 'Malfor...
def process_response(self, req, resp, resource): """ 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. """ if 'result' not in req.context: return req.context['result']['is_login'] = 'user_id' in req.env['ses...
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.connecting = True self.connection = TornadoConnection(NON_BLOCKING_MQ_PARAMS, stop_ioloop_on_close=False, custom_ioloop=s...
def on_connected(self, connection): """ AMQP connection callback. Creates input channel. Args: connection: AMQP connection """ log.info('PikaClient: connected to RabbitMQ') self.connected = True self.in_channel = self.connection.channel(self.on_channel_open)
def on_channel_open(self, channel): """ Input channel creation callback Queue declaration done here Args: channel: input channel """ self.in_channel.exchange_declare(exchange='input_exc', type='topic', durable=True) channel.queue_declare(callback=self.on_input_queue_declare, queue=self.INPUT_QUEUE_NAME)
def on_input_queue_declare(self, queue): """ Input queue declaration callback. Input Queue/Exchange binding done here Args: queue: input queue """ self.in_channel.queue_bind(callback=None, exchange='input_exc', queue=self.INPUT_QUEUE_NAME, routing_key="#")
def wsgi_app(self, request): """Incoming request handler. :param request: Werkzeug request object """ try: if request.method != 'POST': abort(400) try: # Python 2.7 compatibility data = request.data if isinstance(data, str): body = json.loads(data) else: body = json.loads(data.decode('utf-8')) except ValueError: abort(...
Response(response=json.dumps(resp_obj, indent=4), status=200, mimetype='application/json') except HTTPException as exc: log.exception('Failed to handle request') return exc
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 self.__write = False if not self._is_buffer or force: self._file.close()
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 in reaction[i]: used = set() for atom in molecule['atoms']: m = atom...
length = count(max(max(maps['products'], default=0), max(maps['reactants'], default=0), max(maps['reagents'], default=0)) + 1) ''' map unmapped atoms. ''' for i, tmp in maps.items(): used = set() maps[i] = remap = [] for m in tmp: if not m: remap.append(next(length)) elif m in used: if not self._ignore: raise MappingEr...
changed: {m} to {remap[-1]}') else: remap.append(m) used.add(m) if maps['reagents']: tmp = (set(maps['reactants']) | set(maps['products'])) & set(maps['reagents']) if tmp: e = f'reagents has map intersection with reactants or products: {tmp}' if not self._ignore: raise MappingError(e) warning(e) maps['reagents'] = [x i...
sorted(set(range(1, next(length))) - set(maps['reactants']) - set(maps['products']) - set(maps['reagents']), reverse=True) if lose: for i, tmp in maps.items(): if not tmp: continue for j in lose: maps[i] = tmp = [x if x < j else x - 1 for x in tmp] ''' end ''' rc = ReactionContainer(meta=reaction['meta']) for i, tmp in...
{x: y for x, y in enumerate(tmp[shift: atom_len + shift])} shift += atom_len g = self.__convert_structure(j, remapped) rc[i].append(g) return rc
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 total = 0 while True: c = self._quinonize(rings, 'order') if c: total += c elif total: break c = self._aromatize(rings, 'order') if not c: break tota...
total
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 rounds :return: number of successful rounds ''' print("Num Rounds "+str(n)) cc = self.proxy.Crawl(seed=seed_list, rounds=n) rounds = cc.waitAll() print("Completed %d rounds" % len(rounds)) ret...
def load_xml_conf(self, xml_file, id): ''' 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 ''' # converting nutch-site.xml to key:value pairs import xml.etree.ElementTree as ET tree = ET.parse(xml_file) params = {} for...