_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q22100
Remote._assert_refspec
train
def _assert_refspec(self): """Turns out we can't deal with remotes if the refspec is missing""" config = self.config_reader unset = 'placeholder' try: if config.get_value('fetch', default=unset) is unset: msg = "Remote '%s' has no refspec set.\n" ...
python
{ "resource": "" }
q22101
Remote.fetch
train
def fetch(self, refspec=None, progress=None, **kwargs): """Fetch the latest changes for this remote :param refspec: A "refspec" is used by fetch and push to describe the mapping between remote ref and local ref. They are combined with a colon in the format <src>:<dst...
python
{ "resource": "" }
q22102
Remote.push
train
def push(self, refspec=None, progress=None, **kwargs): """Push changes from source branch in refspec to target branch in refspec. :param refspec: see 'fetch' method :param progress: Can take one of many value types: * None to discard progress information * A...
python
{ "resource": "" }
q22103
Submodule.move
train
def move(self, module_path, configuration=True, module=True): """Move the submodule to a another module path. This involves physically moving the repository at our current path, changing the configuration, as well as adjusting our index entry accordingly. :param module_path: the path to...
python
{ "resource": "" }
q22104
Diffable.diff
train
def diff(self, other=Index, paths=None, create_patch=False, **kwargs): """Creates diffs between two items being trees, trees and index or an index and the working tree. It will detect renames automatically. :param other: Is the item to compare us with. If None, we will b...
python
{ "resource": "" }
q22105
TagObject._set_cache_
train
def _set_cache_(self, attr): """Cache all our attributes at once""" if attr in TagObject.__slots__: ostream = self.repo.odb.stream(self.binsha) lines = ostream.read().decode(defenc).splitlines() obj, hexsha = lines[0].split(" ") # object <hexsha> @UnusedVariabl...
python
{ "resource": "" }
q22106
require_remote_ref_path
train
def require_remote_ref_path(func): """A decorator raising a TypeError if we are not a valid remote, based on the path""" def wrapper(self, *args): if not self.is_remote(): raise ValueError("ref path does not point to a remote reference: %s" % self.path) return func(self, *args) ...
python
{ "resource": "" }
q22107
post_clear_cache
train
def post_clear_cache(func): """Decorator for functions that alter the index using the git command. This would invalidate our possibly existing entries dictionary which is why it must be deleted to allow it to be lazily reread later. :note: This decorator will not be required once all functions ...
python
{ "resource": "" }
q22108
default_index
train
def default_index(func): """Decorator assuring the wrapped method may only run if we are the default repository index. This is as we rely on git commands that operate on that index only. """ @wraps(func) def check_default_index(self, *args, **kwargs): if self._file_path != self._index_path(...
python
{ "resource": "" }
q22109
git_working_dir
train
def git_working_dir(func): """Decorator which changes the current working dir to the one of the git repository in order to assure relative paths are handled correctly""" @wraps(func) def set_git_working_dir(self, *args, **kwargs): cur_wd = os.getcwd() os.chdir(self.repo.working_tree_dir...
python
{ "resource": "" }
q22110
find_first_remote_branch
train
def find_first_remote_branch(remotes, branch_name): """Find the remote branch matching the name of the given branch or raise InvalidGitRepositoryError""" for remote in remotes: try: return remote.refs[branch_name] except IndexError: continue # END exception handli...
python
{ "resource": "" }
q22111
SubmoduleConfigParser.flush_to_index
train
def flush_to_index(self): """Flush changes in our configuration file to the index""" assert self._smref is not None # should always have a file here assert not isinstance(self._file_or_files, BytesIO) sm = self._smref() if sm is not None: index = self._index ...
python
{ "resource": "" }
q22112
RefLog.append_entry
train
def append_entry(cls, config_reader, filepath, oldbinsha, newbinsha, message): """Append a new log entry to the revlog at filepath. :param config_reader: configuration reader of the repository - used to obtain user information. May also be an Actor instance identifying the committer directl...
python
{ "resource": "" }
q22113
unbare_repo
train
def unbare_repo(func): """Methods with this decorator raise InvalidGitRepositoryError if they encounter a bare repository""" @wraps(func) def wrapper(self, *args, **kwargs): if self.repo.bare: raise InvalidGitRepositoryError("Method '%s' cannot operate on bare repositories" % func._...
python
{ "resource": "" }
q22114
rmtree
train
def rmtree(path): """Remove the given recursively. :note: we use shutil rmtree but adjust its behaviour to see whether files that couldn't be deleted are read-only. Windows will not remove them in that case""" def onerror(func, path, exc_info): # Is the error an access error ? os.c...
python
{ "resource": "" }
q22115
stream_copy
train
def stream_copy(source, destination, chunk_size=512 * 1024): """Copy all data from the source stream into the destination stream in chunks of size chunk_size :return: amount of bytes written""" br = 0 while True: chunk = source.read(chunk_size) destination.write(chunk) br +=...
python
{ "resource": "" }
q22116
assure_directory_exists
train
def assure_directory_exists(path, is_file=False): """Assure that the directory pointed to by path exists. :param is_file: If True, path is assumed to be a file and handled correctly. Otherwise it must be a directory :return: True if the directory was created, False if it already existed""" if i...
python
{ "resource": "" }
q22117
RemoteProgress._parse_progress_line
train
def _parse_progress_line(self, line): """Parse progress information from the given line as retrieved by git-push or git-fetch. - Lines that do not contain progress info are stored in :attr:`other_lines`. - Lines that seem to contain an error (i.e. start with error: or fatal:) are stored...
python
{ "resource": "" }
q22118
Stats._list_from_string
train
def _list_from_string(cls, repo, text): """Create a Stat object from output retrieved by git-diff. :return: git.Stat""" hsh = {'total': {'insertions': 0, 'deletions': 0, 'lines': 0, 'files': 0}, 'files': {}} for line in text.splitlines(): (raw_insertions, raw_deletions, file...
python
{ "resource": "" }
q22119
BlockingLockFile._obtain_lock
train
def _obtain_lock(self): """This method blocks until it obtained the lock, or raises IOError if it ran out of time or if the parent directory was not available anymore. If this method returns, you are guaranteed to own the lock""" starttime = time.time() maxtime = starttime + floa...
python
{ "resource": "" }
q22120
Iterable.list_items
train
def list_items(cls, repo, *args, **kwargs): """ Find all items of this type - subclasses can specify args and kwargs differently. If no args are given, subclasses are obliged to return all items if no additional arguments arg given. :note: Favor the iter_items method as it will ...
python
{ "resource": "" }
q22121
main
train
def main(testfiles=None, action=printer): """testfiles can be None, in which case the command line arguments are used as filenames. testfiles can be a string, in which case that file is parsed. testfiles can be a list. In all cases, the filenames will be globbed. If more than one file is parsed...
python
{ "resource": "" }
q22122
expand_state_definition
train
def expand_state_definition(source, loc, tokens): """ Parse action to convert statemachine to corresponding Python classes and methods """ indent = " " * (pp.col(loc, source) - 1) statedef = [] # build list of states states = set() fromTo = {} for tn in tokens.transitions: s...
python
{ "resource": "" }
q22123
debug
train
def debug(ftn, txt): """Used for debugging.""" if debug_p: sys.stdout.write("{0}.{1}:{2}\n".format(modname, ftn, txt)) sys.stdout.flush()
python
{ "resource": "" }
q22124
fatal
train
def fatal(ftn, txt): """If can't continue.""" msg = "{0}.{1}:FATAL:{2}\n".format(modname, ftn, txt) raise SystemExit(msg)
python
{ "resource": "" }
q22125
main
train
def main(pargs): """This should only be used for testing. The primary mode of operation is as an imported library. """ input_file = sys.argv[1] fp = ParseFileLineByLine(input_file) for i in fp: print(i)
python
{ "resource": "" }
q22126
SearchQueryParser.evaluateQuotes
train
def evaluateQuotes(self, argument): """Evaluate quoted strings First is does an 'and' on the indidual search terms, then it asks the function GetQuoted to only return the subset of ID's that contain the literal string. """ r = set() search_terms = [] ...
python
{ "resource": "" }
q22127
ExceptionSharedData.setpos
train
def setpos(self, location, text): """Helper function for setting curently parsed text and position""" self.location = location self.text = text
python
{ "resource": "" }
q22128
SymbolTableEntry.set_attribute
train
def set_attribute(self, name, value): """Sets attribute's name and value""" self.attribute_name = name self.attribute = value
python
{ "resource": "" }
q22129
SymbolTable.display
train
def display(self): """Displays the symbol table content""" #Finding the maximum length for each column sym_name = "Symbol name" sym_len = max(max(len(i.name) for i in self.table),len(sym_name)) kind_name = "Kind" kind_len = max(max(len(SharedData.KINDS[i.kind]) for ...
python
{ "resource": "" }
q22130
SymbolTable.insert_symbol
train
def insert_symbol(self, sname, skind, stype): """Inserts new symbol at the end of the symbol table. Returns symbol index sname - symbol name skind - symbol kind stype - symbol type """ self.table.append(SymbolTableEntry(sname, skind, stype)) ...
python
{ "resource": "" }
q22131
SymbolTable.clear_symbols
train
def clear_symbols(self, index): """Clears all symbols begining with the index to the end of table""" try: del self.table[index:] except Exception: self.error() self.table_len = len(self.table)
python
{ "resource": "" }
q22132
SymbolTable.insert_id
train
def insert_id(self, sname, skind, skinds, stype): """Inserts a new identifier at the end of the symbol table, if possible. Returns symbol index, or raises an exception if the symbol alredy exists sname - symbol name skind - symbol kind skinds - symbol kinds ...
python
{ "resource": "" }
q22133
SymbolTable.insert_global_var
train
def insert_global_var(self, vname, vtype): "Inserts a new global variable" return self.insert_id(vname, SharedData.KINDS.GLOBAL_VAR, [SharedData.KINDS.GLOBAL_VAR, SharedData.KINDS.FUNCTION], vtype)
python
{ "resource": "" }
q22134
SymbolTable.insert_local_var
train
def insert_local_var(self, vname, vtype, position): "Inserts a new local variable" index = self.insert_id(vname, SharedData.KINDS.LOCAL_VAR, [SharedData.KINDS.LOCAL_VAR, SharedData.KINDS.PARAMETER], vtype) self.table[index].attribute = position
python
{ "resource": "" }
q22135
SymbolTable.insert_parameter
train
def insert_parameter(self, pname, ptype): "Inserts a new parameter" index = self.insert_id(pname, SharedData.KINDS.PARAMETER, SharedData.KINDS.PARAMETER, ptype) #set parameter's attribute to it's ordinal number self.table[index].set_attribute("Index", self.shared.function_params) ...
python
{ "resource": "" }
q22136
SymbolTable.insert_function
train
def insert_function(self, fname, ftype): "Inserts a new function" index = self.insert_id(fname, SharedData.KINDS.FUNCTION, [SharedData.KINDS.GLOBAL_VAR, SharedData.KINDS.FUNCTION], ftype) self.table[index].set_attribute("Params",0) return index
python
{ "resource": "" }
q22137
SymbolTable.same_types
train
def same_types(self, index1, index2): """Returns True if both symbol table elements are of the same type""" try: same = self.table[index1].type == self.table[index2].type != SharedData.TYPES.NO_TYPE except Exception: self.error() return same
python
{ "resource": "" }
q22138
CodeGenerator.take_register
train
def take_register(self, rtype = SharedData.TYPES.NO_TYPE): """Reserves one working register and sets its type""" if len(self.free_registers) == 0: self.error("no more free registers") reg = self.free_registers.pop() self.used_registers.append(reg) self.symtab.se...
python
{ "resource": "" }
q22139
CodeGenerator.take_function_register
train
def take_function_register(self, rtype = SharedData.TYPES.NO_TYPE): """Reserves register for function return value and sets its type""" reg = SharedData.FUNCTION_REGISTER if reg not in self.free_registers: self.error("function register already taken") self.free_registers...
python
{ "resource": "" }
q22140
CodeGenerator.free_register
train
def free_register(self, reg): """Releases working register""" if reg not in self.used_registers: self.error("register %s is not taken" % self.REGISTERS[reg]) self.used_registers.remove(reg) self.free_registers.append(reg) self.free_registers.sort(reverse = True)
python
{ "resource": "" }
q22141
CodeGenerator.symbol
train
def symbol(self, index): """Generates symbol name from index""" #if index is actually a string, just return it if isinstance(index, str): return index elif (index < 0) or (index >= self.symtab.table_len): self.error("symbol table index out of range") ...
python
{ "resource": "" }
q22142
CodeGenerator.save_used_registers
train
def save_used_registers(self): """Pushes all used working registers before function call""" used = self.used_registers[:] del self.used_registers[:] self.used_registers_stack.append(used[:]) used.sort() for reg in used: self.newline_text("PUSH\t%s" % Sh...
python
{ "resource": "" }
q22143
CodeGenerator.restore_used_registers
train
def restore_used_registers(self): """Pops all used working registers after function call""" used = self.used_registers_stack.pop() self.used_registers = used[:] used.sort(reverse = True) for reg in used: self.newline_text("POP \t%s" % SharedData.REGISTERS[reg], ...
python
{ "resource": "" }
q22144
CodeGenerator.arithmetic_mnemonic
train
def arithmetic_mnemonic(self, op_name, op_type): """Generates an arithmetic instruction mnemonic""" return self.OPERATIONS[op_name] + self.OPSIGNS[op_type]
python
{ "resource": "" }
q22145
CodeGenerator.arithmetic
train
def arithmetic(self, operation, operand1, operand2, operand3 = None): """Generates an arithmetic instruction operation - one of supporetd operations operandX - index in symbol table or text representation of operand First two operands are input, third one is output ...
python
{ "resource": "" }
q22146
CodeGenerator.relop_code
train
def relop_code(self, relop, operands_type): """Returns code for relational operator relop - relational operator operands_type - int or unsigned """ code = self.RELATIONAL_DICT[relop] offset = 0 if operands_type == SharedData.TYPES.INT else len(SharedData.RELAT...
python
{ "resource": "" }
q22147
CodeGenerator.jump
train
def jump(self, relcode, opposite, label): """Generates a jump instruction relcode - relational operator code opposite - generate normal or opposite jump label - jump label """ jump = self.OPPOSITE_JUMPS[relcode] if opposite else self.CONDITIONAL_JUMPS[r...
python
{ "resource": "" }
q22148
CodeGenerator.compare
train
def compare(self, operand1, operand2): """Generates a compare instruction operandX - index in symbol table """ typ = self.symtab.get_type(operand1) self.free_if_register(operand1) self.free_if_register(operand2) self.newline_text("CMP{0}\t{1},{2}".format...
python
{ "resource": "" }
q22149
CodeGenerator.function_begin
train
def function_begin(self): """Inserts function name label and function frame initialization""" self.newline_label(self.shared.function_name, False, True) self.push("%14") self.move("%15", "%14")
python
{ "resource": "" }
q22150
CodeGenerator.function_body
train
def function_body(self): """Inserts a local variable initialization and body label""" if self.shared.function_vars > 0: const = self.symtab.insert_constant("0{}".format(self.shared.function_vars * 4), SharedData.TYPES.UNSIGNED) self.arithmetic("-", "%15", const, "%15") ...
python
{ "resource": "" }
q22151
CodeGenerator.function_end
train
def function_end(self): """Inserts an exit label and function return instructions""" self.newline_label(self.shared.function_name + "_exit", True, True) self.move("%14", "%15") self.pop("%14") self.newline_text("RET", True)
python
{ "resource": "" }
q22152
MicroC.warning
train
def warning(self, message, print_location=True): """Displays warning message. Uses exshared for current location of parsing""" msg = "Warning" if print_location and (exshared.location != None): wline = lineno(exshared.location, exshared.text) wcol = col(exshared.loca...
python
{ "resource": "" }
q22153
MicroC.global_variable_action
train
def global_variable_action(self, text, loc, var): """Code executed after recognising a global variable""" exshared.setpos(loc, text) if DEBUG > 0: print("GLOBAL_VAR:",var) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return index = self.sy...
python
{ "resource": "" }
q22154
MicroC.local_variable_action
train
def local_variable_action(self, text, loc, var): """Code executed after recognising a local variable""" exshared.setpos(loc, text) if DEBUG > 0: print("LOCAL_VAR:",var, var.name, var.type) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return ...
python
{ "resource": "" }
q22155
MicroC.parameter_action
train
def parameter_action(self, text, loc, par): """Code executed after recognising a parameter""" exshared.setpos(loc, text) if DEBUG > 0: print("PARAM:",par) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return index = self.symtab.insert_param...
python
{ "resource": "" }
q22156
MicroC.constant_action
train
def constant_action(self, text, loc, const): """Code executed after recognising a constant""" exshared.setpos(loc, text) if DEBUG > 0: print("CONST:",const) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return return self.symtab.insert_cons...
python
{ "resource": "" }
q22157
MicroC.function_body_action
train
def function_body_action(self, text, loc, fun): """Code executed after recognising the beginning of function's body""" exshared.setpos(loc, text) if DEBUG > 0: print("FUN_BODY:",fun) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return self...
python
{ "resource": "" }
q22158
MicroC.function_end_action
train
def function_end_action(self, text, loc, fun): """Code executed at the end of function definition""" if DEBUG > 0: print("FUN_END:",fun) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return #set function's attribute to number of function parameters ...
python
{ "resource": "" }
q22159
MicroC.return_action
train
def return_action(self, text, loc, ret): """Code executed after recognising a return statement""" exshared.setpos(loc, text) if DEBUG > 0: print("RETURN:",ret) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return if not self.symtab.same_typ...
python
{ "resource": "" }
q22160
MicroC.lookup_id_action
train
def lookup_id_action(self, text, loc, var): """Code executed after recognising an identificator in expression""" exshared.setpos(loc, text) if DEBUG > 0: print("EXP_VAR:",var) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return var_index =...
python
{ "resource": "" }
q22161
MicroC.assignment_action
train
def assignment_action(self, text, loc, assign): """Code executed after recognising an assignment statement""" exshared.setpos(loc, text) if DEBUG > 0: print("ASSIGN:",assign) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return var_index = ...
python
{ "resource": "" }
q22162
MicroC.argument_action
train
def argument_action(self, text, loc, arg): """Code executed after recognising each of function's arguments""" exshared.setpos(loc, text) if DEBUG > 0: print("ARGUMENT:",arg.exp) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return arg_ordin...
python
{ "resource": "" }
q22163
MicroC.function_call_action
train
def function_call_action(self, text, loc, fun): """Code executed after recognising the whole function call""" exshared.setpos(loc, text) if DEBUG > 0: print("FUN_CALL:",fun) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return #check number...
python
{ "resource": "" }
q22164
MicroC.if_body_action
train
def if_body_action(self, text, loc, arg): """Code executed after recognising if statement's body""" exshared.setpos(loc, text) if DEBUG > 0: print("IF_BODY:",arg) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return #generate conditional ju...
python
{ "resource": "" }
q22165
MicroC.if_else_action
train
def if_else_action(self, text, loc, arg): """Code executed after recognising if statement's else body""" exshared.setpos(loc, text) if DEBUG > 0: print("IF_ELSE:",arg) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return #jump to exit after...
python
{ "resource": "" }
q22166
MicroC.if_end_action
train
def if_end_action(self, text, loc, arg): """Code executed after recognising a whole if statement""" exshared.setpos(loc, text) if DEBUG > 0: print("IF_END:",arg) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return self.codegen.newline_labe...
python
{ "resource": "" }
q22167
MicroC.program_end_action
train
def program_end_action(self, text, loc, arg): """Checks if there is a 'main' function and the type of 'main' function""" exshared.setpos(loc, text) if DEBUG > 0: print("PROGRAM_END:",arg) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return ...
python
{ "resource": "" }
q22168
encode_cookie
train
def encode_cookie(payload, key=None): ''' This will encode a ``unicode`` value into a cookie, and sign that cookie with the app's secret key. :param payload: The value to encode, as `unicode`. :type payload: unicode :param key: The key to use when creating the cookie digest. If not ...
python
{ "resource": "" }
q22169
decode_cookie
train
def decode_cookie(cookie, key=None): ''' This decodes a cookie given by `encode_cookie`. If verification of the cookie fails, ``None`` will be implicitly returned. :param cookie: An encoded cookie. :type cookie: str :param key: The key to use when creating the cookie digest. If not ...
python
{ "resource": "" }
q22170
make_next_param
train
def make_next_param(login_url, current_url): ''' Reduces the scheme and host from a given URL so it can be passed to the given `login` URL more efficiently. :param login_url: The login URL being redirected to. :type login_url: str :param current_url: The URL to reduce. :type current_url: st...
python
{ "resource": "" }
q22171
login_url
train
def login_url(login_view, next_url=None, next_field='next'): ''' Creates a URL for redirecting to a login page. If only `login_view` is provided, this will just return the URL for it. If `next_url` is provided, however, this will append a ``next=URL`` parameter to the query string so that the login ...
python
{ "resource": "" }
q22172
login_user
train
def login_user(user, remember=False, duration=None, force=False, fresh=True): ''' Logs a user in. You should pass the actual user object to this. If the user's `is_active` property is ``False``, they will not be logged in unless `force` is ``True``. This will return ``True`` if the log in attempt s...
python
{ "resource": "" }
q22173
confirm_login
train
def confirm_login(): ''' This sets the current session as fresh. Sessions become stale when they are reloaded from a cookie. ''' session['_fresh'] = True session['_id'] = current_app.login_manager._session_identifier_generator() user_login_confirmed.send(current_app._get_current_object())
python
{ "resource": "" }
q22174
fresh_login_required
train
def fresh_login_required(func): ''' If you decorate a view with this, it will ensure that the current user's login is fresh - i.e. their session was not restored from a 'remember me' cookie. Sensitive operations, like changing a password or e-mail, should be protected with this, to impede the effort...
python
{ "resource": "" }
q22175
set_login_view
train
def set_login_view(login_view, blueprint=None): ''' Sets the login view for the app or blueprint. If a blueprint is passed, the login view is set for this blueprint on ``blueprint_login_views``. :param login_view: The user object to log in. :type login_view: str :param blueprint: The blueprint ...
python
{ "resource": "" }
q22176
LoginManager._update_request_context_with_user
train
def _update_request_context_with_user(self, user=None): '''Store the given user as ctx.user.''' ctx = _request_ctx_stack.top ctx.user = self.anonymous_user() if user is None else user
python
{ "resource": "" }
q22177
LoginManager._load_user
train
def _load_user(self): '''Loads user from session or remember_me cookie as applicable''' if self._user_callback is None and self._request_callback is None: raise Exception( "Missing user_loader or request_loader. Refer to " "http://flask-login.readthedocs.io/#...
python
{ "resource": "" }
q22178
_tree_to_labels
train
def _tree_to_labels(X, single_linkage_tree, min_cluster_size=10, cluster_selection_method='eom', allow_single_cluster=False, match_reference_implementation=False): """Converts a pretrained tree and cluster size into a set of labels and probabilities. ...
python
{ "resource": "" }
q22179
HDBSCAN.fit
train
def fit(self, X, y=None): """Perform HDBSCAN clustering from features or distance matrix. Parameters ---------- X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ array of shape (n_samples, n_samples) A feature array, or array of distance...
python
{ "resource": "" }
q22180
_bfs_from_cluster_tree
train
def _bfs_from_cluster_tree(tree, bfs_root): """ Perform a breadth first search on a tree in condensed tree format """ result = [] to_process = [bfs_root] while to_process: result.extend(to_process) to_process = tree['child'][np.in1d(tree['parent'], to_process)].tolist() re...
python
{ "resource": "" }
q22181
CondensedTree.to_pandas
train
def to_pandas(self): """Return a pandas dataframe representation of the condensed tree. Each row of the dataframe corresponds to an edge in the tree. The columns of the dataframe are `parent`, `child`, `lambda_val` and `child_size`. The `parent` and `child` are the ids of the ...
python
{ "resource": "" }
q22182
CondensedTree.to_networkx
train
def to_networkx(self): """Return a NetworkX DiGraph object representing the condensed tree. Edge weights in the graph are the lamba values at which child nodes 'leave' the parent cluster. Nodes have a `size` attribute attached giving the number of points that are in the cluster...
python
{ "resource": "" }
q22183
SingleLinkageTree.to_pandas
train
def to_pandas(self): """Return a pandas dataframe representation of the single linkage tree. Each row of the dataframe corresponds to an edge in the tree. The columns of the dataframe are `parent`, `left_child`, `right_child`, `distance` and `size`. The `parent`, `left_child` a...
python
{ "resource": "" }
q22184
SingleLinkageTree.to_networkx
train
def to_networkx(self): """Return a NetworkX DiGraph object representing the single linkage tree. Edge weights in the graph are the distance values at which child nodes merge to form the parent cluster. Nodes have a `size` attribute attached giving the number of points that are ...
python
{ "resource": "" }
q22185
MinimumSpanningTree.to_pandas
train
def to_pandas(self): """Return a Pandas dataframe of the minimum spanning tree. Each row is an edge in the tree; the columns are `from`, `to`, and `distance` giving the two vertices of the edge which are indices into the dataset, and the distance between those datapoints. ...
python
{ "resource": "" }
q22186
MinimumSpanningTree.to_networkx
train
def to_networkx(self): """Return a NetworkX Graph object representing the minimum spanning tree. Edge weights in the graph are the distance between the nodes they connect. Nodes have a `data` attribute attached giving the data vector of the associated point. """ try: ...
python
{ "resource": "" }
q22187
all_points_core_distance
train
def all_points_core_distance(distance_matrix, d=2.0): """ Compute the all-points-core-distance for all the points of a cluster. Parameters ---------- distance_matrix : array (cluster_size, cluster_size) The pairwise distance matrix between points in the cluster. d : integer The...
python
{ "resource": "" }
q22188
all_points_mutual_reachability
train
def all_points_mutual_reachability(X, labels, cluster_id, metric='euclidean', d=None, **kwd_args): """ Compute the all-points-mutual-reachability distances for all the points of a cluster. If metric is 'precomputed' then assume X is a distance matrix for the full ...
python
{ "resource": "" }
q22189
internal_minimum_spanning_tree
train
def internal_minimum_spanning_tree(mr_distances): """ Compute the 'internal' minimum spanning tree given a matrix of mutual reachability distances. Given a minimum spanning tree the 'internal' graph is the subgraph induced by vertices of degree greater than one. Parameters ---------- mr_dis...
python
{ "resource": "" }
q22190
density_separation
train
def density_separation(X, labels, cluster_id1, cluster_id2, internal_nodes1, internal_nodes2, core_distances1, core_distances2, metric='euclidean', **kwd_args): """ Compute the density separation between two clusters. This is the minimum a...
python
{ "resource": "" }
q22191
validity_index
train
def validity_index(X, labels, metric='euclidean', d=None, per_cluster_scores=False, **kwd_args): """ Compute the density based cluster validity index for the clustering specified by `labels` and for each cluster in `labels`. Parameters ---------- X : array (n_samples, n_featu...
python
{ "resource": "" }
q22192
RobustSingleLinkage.fit
train
def fit(self, X, y=None): """Perform robust single linkage clustering from features or distance matrix. Parameters ---------- X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \ array of shape (n_samples, n_samples) A feature array...
python
{ "resource": "" }
q22193
_find_neighbor_and_lambda
train
def _find_neighbor_and_lambda(neighbor_indices, neighbor_distances, core_distances, min_samples): """ Find the nearest mutual reachability neighbor of a point, and compute the associated lambda value for the point, given the mutual reachability distance to a nearest neighb...
python
{ "resource": "" }
q22194
membership_vector
train
def membership_vector(clusterer, points_to_predict): """Predict soft cluster membership. The result produces a vector for each point in ``points_to_predict`` that gives a probability that the given point is a member of a cluster for each of the selected clusters of the ``clusterer``. Parameters ...
python
{ "resource": "" }
q22195
all_points_membership_vectors
train
def all_points_membership_vectors(clusterer): """Predict soft cluster membership vectors for all points in the original dataset the clusterer was trained on. This function is more efficient by making use of the fact that all points are already in the condensed tree, and processing in bulk. Paramete...
python
{ "resource": "" }
q22196
filter_cells
train
def filter_cells( data: AnnData, min_counts: Optional[int] = None, min_genes: Optional[int] = None, max_counts: Optional[int] = None, max_genes: Optional[int] = None, inplace: bool = True, copy: bool = False, ) -> Optional[Tuple[np.ndarray, np.ndarray]]: """Filter cell outliers based o...
python
{ "resource": "" }
q22197
filter_genes
train
def filter_genes( data: AnnData, min_counts: Optional[int] = None, min_cells: Optional[int] = None, max_counts: Optional[int] = None, max_cells: Optional[int] = None, inplace: bool = True, copy: bool = False, ) -> Union[AnnData, None, Tuple[np.ndarray, np.ndarray]]: """Filter genes bas...
python
{ "resource": "" }
q22198
log1p
train
def log1p( data: Union[AnnData, np.ndarray, spmatrix], copy: bool = False, chunked: bool = False, chunk_size: Optional[int] = None, ) -> Optional[AnnData]: """Logarithmize the data matrix. Computes :math:`X = \\log(X + 1)`, where :math:`log` denotes the natural logarithm. Parameters --...
python
{ "resource": "" }
q22199
sqrt
train
def sqrt( data: AnnData, copy: bool = False, chunked: bool = False, chunk_size: Optional[int] = None, ) -> Optional[AnnData]: """Square root the data matrix. Computes :math:`X = \\sqrt(X)`. Parameters ---------- data The (annotated) data matrix of shape ``n_obs`` × ``n_vars...
python
{ "resource": "" }