code stringlengths 1 18.2k |
|---|
def set(self, **kwargs): ''' Override existing settings, taking precedence over both user settings object and default settings. Useful for specific runtime requirements, such as overriding PORT or HOST. ''' for lower_key, value in kwargs.items(): if lower_key.lower() != lower_key: raise ValueError('Requires lowercase: ... |
def use_settings(self, settings_module): ''' Useful for tests for overriding current settings manually ''' self._previous_settings = self.settings_module self.settings_module = settings_module self.reconfigure() |
def use_settings_dict(self, settings_dict): ''' Slightly cleaner interface to override settings that autogenerates a settings module based on a given dict. ''' class SettingsDictModule: __slots__ = tuple(key.upper() for key in settings_dict.keys()) settings_obj = SettingsDictModule() for key, value in settings_dict.ite... |
def import_path_to_absolute_path(import_path, file_marker): ''' Given a Python import path, convert to a likely absolute filesystem path, by searching for the given filename marker (such as 'package.json' or '__init__.py') through the Python system path. Do not return given filename. ''' path_fragment = import_path.rep... |
def get_telex_definition(w_shorthand=True, brackets_shorthand=True): """Create a definition dictionary for the TELEX input method Args: w_shorthand (optional): allow a stand-alone w to be interpreted as an ư. Default to True. brackets_shorthand (optional, True): allow typing ][ as shorthand for ươ. Default to True. Ret... |
def process_sequence(sequence, rules=None, skip_non_vietnamese=True): """\ Convert a key sequence into a Vietnamese string with diacritical marks. Args: rules (optional): see docstring for process_key(). skip_non_vietnamese (optional): see docstring for process_key(). It even supports continous key sequences connected ... |
def process_key(string, key, fallback_sequence="", rules=None, skip_non_vietnamese=True): """Process a keystroke. Args: string: The previously processed string or "". key: The keystroke. fallback_sequence: The previous keystrokes. rules (optional): A dictionary listing transformation rules. Defaults to get_telex_defini... |
'aa') (aa, aa) `rules` is a dictionary that maps keystrokes to their effect string. The effects can be one of the following: 'a^': a with circumflex (â), only affect an existing 'a family' 'a+': a with breve (ă), only affect an existing 'a family' 'e^': e with circumflex (ê), only affect an existing 'e family' 'o^': o ... |
A keystroke entry can have multiple effects, in which case the dictionary entry's value should be a list of the possible effect strings. Although you should try to avoid this if you are defining a custom input method rule. """ # TODO Figure out a way to remove the `string` argument. Perhaps only the # key sequence is n... |
of the transformations (if any) work # then this keystroke is probably an undo key. if _can_undo(new_comps, trans_list): # The prefix "_" means undo. for trans in map(lambda x: "_" + x, trans_list): new_comps = _transform(new_comps, trans) # Undoing the w key with the TELEX input method with the # w:<ư extension requir... |
return '<ư' in rules["w"] def undone_vowel_ends_with_u(): return new_comps[1] and new_comps[1][-1].lower() == "u" def not_first_key_press(): return len(fallback_sequence) >= 1 def user_typed_ww(): return (fallback_sequence[-1:]+key).lower() == "ww" def user_didnt_type_uww(): return not (len(fallback_sequence) >= 2 and ... |
def _get_transformation_list(key, im, fallback_sequence): """ Return the list of transformations inferred from the entered key. The map between transform types and keys is given by module bogo_config (if exists) or by variable simple_telex_im if entered key is not in im, return "+key", meaning appending the entered key... |
fallback_sequence. t = list(map(lambda x: "_" + x, _get_transformation_list(fallback_sequence[-2], im, fallback_sequence[:-1]))) # print(t) trans_list = t # else: # trans_list = ['+' + key] return trans_list else: return ['+' + key] |
def _get_action(trans): """ Return the action inferred from the transformation `trans`. and the parameter going with this action An _Action.ADD_MARK goes with a Mark while an _Action.ADD_ACCENT goes with an Accent """ # TODO: VIQR-like convention mark_action = { '^': (_Action.ADD_MARK, Mark.HAT), '+': (_Action.ADD_MARK... |
def _transform(comps, trans): """ Transform the given string with transform type trans """ logging.debug("== In _transform(%s, %s) ==", comps, trans) components = list(comps) action, parameter = _get_action(trans) if action == _Action.ADD_MARK and \ components[2] == "" and \ mark.strip(components[1]).lower() in ['oe', ... |
into the word then change back to "ươ". # # NOTE: In the dictionary, these are the only words having this strange # vowel so we don't need to worry about other cases. if accent.remove_accent_string(components[1]).lower() == "ươ" and \ not components[2] and components[0].lower() in ["", "h", "th", "kh"]: # Backup accent... |
'' if not components[1] or \ (components[1].lower(), trans[1].lower()) == ('ư', 'ơ'): components[1] += trans[1] else: components = utils.append_comps(components, parameter) if parameter.isalpha() and \ accent.remove_accent_string(components[1]).lower().startswith("uơ"): ac = accent.get_accent_string(components[1]) comp... |
def _reverse(components, trans): """ Reverse the effect of transformation 'trans' on 'components' If the transformation does not affect the components, return the original string. """ action, parameter = _get_action(trans) comps = list(components) string = utils.join(comps) if action == _Action.ADD_CHAR and string[-1].... |
def _can_undo(comps, trans_list): """ Return whether a components can be undone with one of the transformation in trans_list. """ comps = list(comps) accent_list = list(map(accent.get_accent_char, comps[1])) mark_list = list(map(mark.get_mark_char, utils.join(comps))) action_list = list(map(lambda x: _get_action(x), tr... |
def handle_backspace(converted_string, raw_sequence, im_rules=None): """ Returns a new raw_sequence after a backspace. This raw_sequence should be pushed back to process_sequence(). """ # I can't find a simple explanation for this, so # I hope this example can help clarify it: # # handle_backspace(thương, thuwongw) -> ... |
in "aeiouyd": i += 1 break else: ime_keys_at_end = raw_sequence[i] + ime_keys_at_end i -= 1 # Try to find a subsequence from that sequence # that can be converted to the deleted_char k = 0 while k < len_raw_sequence: if process_sequence(raw_sequence[i + k:], im_rules) == deleted_char: # Delete that subsequence raw_sequ... |
def get_mark_char(char): """ Get the mark of a single char, if any. """ char = accent.remove_accent_char(char.lower()) if char == "": return Mark.NONE if char == "đ": return Mark.BAR if char in "ă": return Mark.BREVE if char in "ơư": return Mark.HORN if char in "âêô": return Mark.HAT return Mark.NONE |
def add_mark_at(string, index, mark): """ Add mark to the index-th character of the given string. Return the new string after applying change. Notice: index > 0 """ if index == -1: return string # Python can handle the case which index is out of range of given string return string[:index] + add_mark_char(string[index],... |
def add_mark_char(char, mark): """ Add mark to a single char. """ if char == "": return "" case = char.isupper() ac = accent.get_accent_char(char) char = accent.add_accent_char(char.lower(), Accent.NONE) new_char = char if mark == Mark.HAT: if char in FAMILY_A: new_char = "â" elif char in FAMILY_O: new_char = "ô" elif ... |
char in FAMILY_D: new_char = "d" new_char = accent.add_accent_char(new_char, ac) return utils.change_case(new_char, case) |
def is_valid_mark(comps, mark_trans): """ Check whether the mark given by mark_trans is valid to add to the components """ if mark_trans == "*_": return True components = list(comps) if mark_trans[0] == 'd' and components[0] \ and components[0][-1].lower() in ("d", "đ"): return True elif components[1] != "" and \ strip... |
def delete(self, path): """Call the Infoblox device to delete the ref :param str ref: The reference id :rtype: requests.Response """ return self.session.delete(self._request_url(path), auth=self.auth, verify=False) |
def get(self, path, data=None, return_fields=None): """Call the Infoblox device to get the obj for the data passed in :param str obj_reference: The object reference data :param dict data: The data for the get request :rtype: requests.Response """ return self.session.get(self._request_url(path, return_fields), data=json... |
def post(self, path, data): """Call the Infoblox device to post the obj for the data passed in :param str obj: The object type :param dict data: The data for the post :rtype: requests.Response """ LOGGER.debug('Posting data: %r', data) return self.session.post(self._request_url(path), data=json.dumps(data or {}), heade... |
def main(): """Main entry-point for oz's cli""" # Hack to make user code available for import sys.path.append(".") # Run the specified action oz.initialize() retr = optfn.run(list(oz._actions.values())) if retr == optfn.ERROR_RETURN_CODE: sys.exit(-1) elif retr == None: sys.exit(0) elif isinstance(retr, int): sys.exit(... |
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params={},\ working_dir='/tmp'): """Returns a tree from Alignment object aln. aln: an cogent.core.alignment.Alignment object, or data that can be used to build one. - Clearcut only accepts aligned sequences. Alignment object used to handle unaligned seque... |
tree, disable alignment app = Clearcut(InputHandler='_input_as_multiline_string', params=params, \ WorkingDir=working_dir, SuppressStdout=True,\ SuppressStderr=True) #Input is an alignment app.Parameters['-a'].on() #Turn off input as distance matrix app.Parameters['-d'].off() #If moltype = RNA, we must convert to DNA. ... |
def build_tree_from_distance_matrix(matrix, best_tree=False, params={},\ working_dir='/tmp'): """Returns a tree from a distance matrix. matrix: a square Dict2D object (cogent.util.dict2d) best_tree: if True (default:False), uses a slower but more accurate algorithm to build the tree. params: dict of parameters to pass ... |
in tree.tips(): node.Name = int_keys[node.Name] # Clean up result.cleanUp() del(app, result, params) return tree |
def _matrix_input_from_dict2d(matrix): """makes input for running clearcut on a matrix from a dict2D object""" #clearcut truncates names to 10 char- need to rename before and #reassign after #make a dict of env_index:full name int_keys = dict([('env_' + str(i), k) for i,k in \ enumerate(sorted(matrix.keys()))]) #invert... |
a square matrix only for index, key1 in enumerate(names): row = [] for key2 in names: row.append(str(int_map_dists[key1][key2])) rows.append(row) input_matrix = phylipMatrix(rows, names) #input needs a trailing whitespace or it will fail! input_matrix += '\n' return input_matrix, int_keys |
def _input_as_multiline_string(self, data): """Writes data to tempfile and sets -infile parameter data -- list of lines """ if data: self.Parameters['--in']\ .on(super(Clearcut,self)._input_as_multiline_string(data)) return '' |
def _input_as_lines(self,data): """Writes data to tempfile and sets -infile parameter data -- list of lines, ready to be written to file """ if data: self.Parameters['--in']\ .on(super(Clearcut,self)._input_as_lines(data)) return '' |
def _tree_filename(self): """Return name of file containing the alignment prefix -- str, prefix of alignment file. """ if self.Parameters['--out']: aln_filename = self._absolute(self.Parameters['--out'].Value) else: raise ValueError, "No tree output file specified." return aln_filename |
def _make_request(self, request, uri, **kwargs): """ This is final step of calling out to the remote API. We set up our headers, proxy, debugging etc. The only things in **kwargs are parameters that are overridden on an API method basis (like timeout) We have a simple attempt/while loop to implement retries w/ delays t... |
parser since we have no business parsing that here. It could be argued that handling API exceptions/errors shouldn't belong in this method but it is simple enough for now. """ attempts = 0 response = None while attempts <= self.retries: try: response = request(uri, headers=self.headers, proxies=self.proxy, **kwargs) ex... |
def _make_get_request(self, uri, parameters=None, timeout=None): """ Given a request add in the required parameters and return the parsed XML object. """ if not timeout: timeout = self.timeout return self._make_request(requests.get, uri, params=parameters, timeout=timeout) |
def _make_post_request(self, uri, payload, timeout=None): """ Given a request add in the required parameters and return the parsed XML object. """ if not timeout: timeout = self.timeout return self._make_request(requests.post, uri, data=payload, timeout=timeout) |
def _make_delete_request(self, uri, timeout=None): """ Given a request add in the required parameters and return the parsed XML object. """ if not timeout: timeout = self.timeout return self._make_request(requests.delete, uri, timeout=timeout) |
def _close(self): ''' Closes aiohttp session and all open file descriptors ''' if hasattr(self, 'aiohttp'): if not self.aiohttp.closed: self.aiohttp.close() if hasattr(self, 'file_descriptors'): for fd in self.file_descriptors.values(): if not fd.closed: fd.close() |
def checkAndRaise(pageNum, itemsPerPage): """Check and Raise an Exception if needed Args: pageNum (int): Page number itemsPerPage (int): Number of items per Page Raises: ErrPaginationLimits: If we are out of limits """ if pageNum < 1: raise ErrPaginationLimits(ErrPaginationLimits.ERR_PAGE_NUM) if itemsPerPage < Setting... |
def parse_packet(data, format=None): """ Parses a Lifx data packet (as a bytestring), returning into a Header object for the fields that are common to all data packets, and a bytestring of payload data for the type-specific fields (suitable for passing to `parse_payload`). """ unpacked = struct.unpack(BASE_FORMAT, data... |
def parse_payload(data, payload_fmt, *payload_names): """ Parses a bytestring of Lifx payload data (the bytes after the common fields), as returned by `parse_packet`. Returns a dictionary where the keys are from `payload_names` and the values are the corresponding values from the bytestring. """ payload = struct.unpack... |
def build_packet(packet_type, gateway, bulb, payload_fmt, *payload_args, **kwargs): """ Constructs a Lifx packet, returning a bytestring. The arguments are as follows: - `packet_type`, an integer - `gateway`, a 6-byte string containing the mac address of the gateway bulb - `bulb`, a 6-byte string containing either the ... |
def _unbytes(bytestr): """ Returns a bytestring from the human-friendly string returned by `_bytes`. >>> _unbytes('123456') '\x12\x34\x56' """ return ''.join(chr(int(bytestr[k:k + 2], 16)) for k in range(0, len(bytestr), 2)) |
def _spawn(func, *args, **kwargs): """ Calls `func(*args, **kwargs)` in a daemon thread, and returns the (started) Thread object. """ thr = Thread(target=func, args=args, kwargs=kwargs) thr.daemon = True thr.start() return thr |
def _retry(event, attempts, delay): """ An iterator of pairs of (attempt number, event set), checking whether `event` is set up to `attempts` number of times, and delaying `delay` seconds in between. Terminates as soon as `event` is set, or until `attempts` have been made. Intended to be used in a loop, as in: for num,... |
def _blocking(lock, state_dict, event, timeout=None): """ A contextmanager that clears `state_dict` and `event`, yields, and waits for the event to be set. Clearing an yielding are done within `lock`. Used for blocking request/response semantics on the request side, as in: with _blocking(lock, state, event): send_reque... |
def register(self, event, fn): """ Tell the object to run `fn` whenever a message of type `event` is received. """ self._callbacks.setdefault(event, []).append(fn) return fn |
def put(self, event, *args, **kwargs): """ Schedule a callback for `event`, passing `args` and `kwargs` to each registered callback handler. """ self._queue.put((event, args, kwargs)) |
def run(self): """ Process all callbacks, until `stop()` is called. Intended to run in its own thread. """ while True: msg = self._queue.get() if msg is _SHUTDOWN: break event, args, kwargs = msg self._logger('<< %s', event) for func in self._callbacks.get(event, []): func(*args, **kwargs) |
def run(self): """ Process all incoming packets, until `stop()` is called. Intended to run in its own thread. """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(self._addr) sock.settimeout(self._timeout) with closing(sock): while not self._shutdown.is_set(): try: data, addr = sock.recvfrom(self._buff... |
def run(self): """ Process all outgoing packets, until `stop()` is called. Intended to run in its own thread. """ while True: to_send = self._queue.get() if to_send is _SHUTDOWN: break # If we get a gateway object, connect to it. Otherwise, assume # it's a bytestring and send it out on the socket. if isinstance(to_send... |
def run(self): """ Process all log messages, until `stop()` is called. Intended to run in its own thread. """ while True: msg = self._queue.get() if msg is _SHUTDOWN: break if self._enabled: print msg |
def _on_gateway(self, header, payload, rest, addr): """ Records a discovered gateway, for connecting to later. """ if payload.get('service') == SERVICE_UDP: self.gateway = Gateway(addr[0], payload['port'], header.gateway) self.gateway_found_event.set() |
def _on_power_state(self, header, payload, rest, addr): """ Records the power (on/off) state of bulbs, and forwards to a high-level callback with human-friendlier arguments. """ with self.lock: self.power_state[header.mac] = payload if len(self.power_state) >= self.num_bulbs: self.power_state_event.set() self.callbacks... |
def _on_light_state(self, header, payload, rest, addr): """ Records the light state of bulbs, and forwards to a high-level callback with human-friendlier arguments. """ with self.lock: label = payload['label'].strip('\x00') self.bulbs[header.mac] = bulb = Bulb(label, header.mac) if len(self.bulbs) >= self.num_bulbs: se... |
def get_bulb(self, mac): """ Returns a Bulb object corresponding to the bulb with the mac address `mac` (a 6-byte bytestring). """ return self.bulbs.get(mac, Bulb('Bulb %s' % _bytes(mac), mac)) |
def send(self, packet_type, bulb, packet_fmt, *packet_args): """ Builds and sends a packet to one or more bulbs. """ packet = build_packet(packet_type, self.gateway.mac, bulb, packet_fmt, *packet_args) self.logger('>> %s', _bytes(packet)) self.sender.put(packet) |
def set_power_state(self, is_on, bulb=ALL_BULBS, timeout=None): """ Sets the power state of one or more bulbs. """ with _blocking(self.lock, self.power_state, self.light_state_event, timeout): self.send(REQ_SET_POWER_STATE, bulb, '2s', '\x00\x01' if is_on else '\x00\x00') self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '') r... |
def set_light_state_raw(self, hue, saturation, brightness, kelvin, bulb=ALL_BULBS, timeout=None): """ Sets the (low-level) light state of one or more bulbs. """ with _blocking(self.lock, self.light_state, self.light_state_event, timeout): self.send(REQ_SET_LIGHT_STATE, bulb, 'xHHHHI', hue, saturation, brightness, kelvi... |
def set_light_state(self, hue, saturation, brightness, kelvin, bulb=ALL_BULBS, timeout=None): """ Sets the light state of one or more bulbs. Hue is a float from 0 to 360, saturation and brightness are floats from 0 to 1, and kelvin is an integer. """ raw_hue = int((hue % 360) / 360.0 * 0xffff) & 0xffff raw_sat = int(sa... |
def on_packet(self, packet_type): """ Registers a function to be called when packet data is received with a specific type. """ def _wrapper(fn): return self.callbacks.register(packet_type, fn) return _wrapper |
def connect(self, attempts=20, delay=0.5): """ Connects to a gateway, blocking until a connection is made and bulbs are found. Step 1: send a gateway discovery packet to the broadcast address, wait until we've received some info about the gateway. Step 2: connect to a discovered gateway, wait until the connection has b... |
to the gateway until it does. for _, ok in _retry(self.sender.is_connected, 1, 3): self.sender.put(self.gateway) if not ok: raise ConnectException('connection failed') self.callbacks.put(EVENT_CONNECTED) # Send light state packets to the gateway until we find bulbs. for _, ok in _retry(self.bulbs_found_event, attempts,... |
def run(self): """ A context manager starting up threads to send and receive data from a gateway and handle callbacks. Yields when a connection has been made, and cleans up connections and threads when it's done. """ listener_thr = _spawn(self.receiver.run) callback_thr = _spawn(self.callbacks.run) sender_thr = _spawn(... |
async def run_multiconvert(self, url_string, to_type): ''' Enqueues in succession all conversions steps necessary to take the given URL and convert it to to_type, storing the result in the cache ''' async def enq_convert(*args): await self.enqueue(Task.CONVERT, args) await tasks.multiconvert(url_string, to_type, enq_co... |
def parse_otu_list(lines, precision=0.0049): """Parser for mothur *.list file To ensure all distances are of type float, the parser returns a distance of 0.0 for the unique groups. However, if some sequences are very similar, mothur may return a grouping at zero distance. What Mothur really means by this, however, is t... |
float(distance_str) num_otus = int(tokens.pop(0)) otu_list = [t.split(',') for t in tokens] yield (distance, otu_list) |
def mothur_classify_file( query_file, ref_fp, tax_fp, cutoff=None, iters=None, ksize=None, output_fp=None, tmp_dir=None): """Classify a set of sequences using Mothur's naive bayes method Dashes are used in Mothur to provide multiple filenames. A filepath with a dash typically breaks an otherwise valid command in Mothur... |
continue # MOTHUR is particular that each assignment end with a semicolon. if not line.endswith(";"): line = line + ";" id_token, _, _ = line.partition("\t") if id_token in ref_seq_ids: tmp_tax_file.write(line) tmp_tax_file.write("\n") tmp_tax_file.seek(0) params = {"reference": tmp_ref_file.name, "taxonomy": tmp_tax_f... |
= ";".join(taxa) f.write("%s\t%s\t%.2f\n" % (query_id, taxa_str, conf)) f.close() return None return dict((a, (b, c)) for a, b, c in assignments) |
def _compile_mothur_script(self): """Returns a Mothur batch script as a string""" def format_opts(*opts): """Formats a series of options for a Mothur script""" return ', '.join(filter(None, map(str, opts))) vars = { 'in': self._input_filename, 'unique': self._derive_unique_path(), 'dist': self._derive_dist_path(), 'nam... |
def _derive_log_path(self): """Guess logfile path produced by Mothur This method checks the working directory for log files generated by Mothur. It will raise an ApplicationError if no log file can be found. Mothur generates log files named in a nondeterministic way, using the current time. We return the log file with ... |
def _derive_unique_path(self): """Guess unique sequences path produced by Mothur""" base, ext = path.splitext(self._input_filename) return '%s.unique%s' % (base, ext) |
def __get_method_abbrev(self): """Abbreviated form of clustering method parameter. Used to guess output filenames for MOTHUR. """ abbrevs = { 'furthest': 'fn', 'nearest': 'nn', 'average': 'an', } if self.Parameters['method'].isOn(): method = self.Parameters['method'].Value else: method = self.Parameters['method'].Defau... |
def _derive_list_path(self): """Guess otu list file path produced by Mothur""" base, ext = path.splitext(self._input_filename) return '%s.unique.%s.list' % (base, self.__get_method_abbrev()) |
def _derive_rank_abundance_path(self): """Guess rank abundance file path produced by Mothur""" base, ext = path.splitext(self._input_filename) return '%s.unique.%s.rabund' % (base, self.__get_method_abbrev()) |
def _derive_species_abundance_path(self): """Guess species abundance file path produced by Mothur""" base, ext = path.splitext(self._input_filename) return '%s.unique.%s.sabund' % (base, self.__get_method_abbrev()) |
def getTmpFilename(self, tmp_dir=None, prefix='tmp', suffix='.txt'): """Returns a temporary filename Similar interface to tempfile.mktmp() """ # Override to change default constructor to str(). FilePath # objects muck up the Mothur script. return super(Mothur, self).getTmpFilename( tmp_dir=tmp_dir, prefix=prefix, suffi... |
def _input_as_multiline_string(self, data): """Write multiline string to temp file, return filename data: a multiline string to be written to a file. """ self._input_filename = self.getTmpFilename( self.WorkingDir, suffix='.fasta') with open(self._input_filename, 'w') as f: f.write(data) return self._input_filename |
def _input_as_lines(self, data): """Write sequence of lines to temp file, return filename data: a sequence to be written to a file, each element of the sequence will compose a line in the file * Note: '\n' will be stripped off the end of each sequence element before writing to a file in order to avoid multiple new line... |
def _input_as_path(self, data): """Copys the provided file to WorkingDir and returns the new filename data: path or filename """ self._input_filename = self.getTmpFilename( self.WorkingDir, suffix='.fasta') copyfile(data, self._input_filename) return self._input_filename |
def _set_WorkingDir(self, path): """Sets the working directory """ self._curr_working_dir = path try: mkdir(self.WorkingDir) except OSError: # Directory already exists pass |
def _format_function_arguments(self, opts): """Format a series of function arguments in a Mothur script.""" params = [self.Parameters[x] for x in opts] return ', '.join(filter(None, map(str, params))) |
def _compile_mothur_script(self): """Returns a Mothur batch script as a string""" fasta = self._input_filename required_params = ["reference", "taxonomy"] for p in required_params: if self.Parameters[p].Value is None: raise ValueError("Must provide value for parameter %s" % p) optional_params = ["ksize", "cutoff", "ite... |
def _add_parameter(self, parameter): ''' Force adds a `Parameter` object to the instance. ''' if isinstance(parameter, MethodParameter): # create a bound instance of the MethodParameter parameter = parameter.bind(alloy=self) self._parameters[parameter.name] = parameter for alias in parameter.aliases: self._aliases[alia... |
def add_parameter(self, parameter, overload=False): ''' Adds a `Parameter` object to the instance. If a `Parameter` with the same name or alias has already been added and `overload` is False (the default), a `ValueError` is thrown. If a class member or method with the same name or alias is already defined, a `ValueErro... |
False.' ''.format(parameter.name)) for alias in parameter.aliases: if alias in self._aliases and not overload: raise ValueError('Alias "{}" has already been added' ' and overload is False.' ''.format(parameter.name)) self._add_parameter(parameter) |
def get_parameter(self, name, default=None): ''' Returns the named parameter if present, or the value of `default`, otherwise. ''' if hasattr(self, name): item = getattr(self, name) if isinstance(item, Parameter): return item return default |
def get_unique_parameters(self): ''' Returns a list of the unique parameters (no duplicates). ''' # start with parameters in the `_parameters` dictionary parameters = self._parameters.values() # add parameters defined with the class for name in dir(self): item = getattr(self, name) if isinstance(item, Parameter): if it... |
def set_log_level(self, level: str) -> None: """Override the default log level of the class.""" if level == 'info': to_set = logging.INFO if level == 'debug': to_set = logging.DEBUG if level == 'error': to_set = logging.ERROR self.log.setLevel(to_set) |
def _request_bulk(self, urls: List[str]) -> List: """Batch the requests going out.""" if not urls: raise Exception("No results were found") session: FuturesSession = FuturesSession(max_workers=len(urls)) self.log.info("Bulk requesting: %d" % len(urls)) futures = [session.get(u, headers=gen_headers(), timeout=3) for u i... |
def bind(self, alloy): ''' Shallow copies this MethodParameter, and binds it to an alloy. This is required before calling. ''' param = MethodParameter(self.name, self.method, self.dependencies, self.units, self.aliases, self._references) param.alloy = alloy return param |
def align_unaligned_seqs(seqs,moltype=DNA,params=None,accurate=False): """Aligns unaligned sequences seqs: either list of sequence objects or list of strings add_seq_names: boolean. if True, sequence names are inserted in the list of sequences. if False, it assumes seqs is a list of lines of some proper format that the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.