_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q57000
map_or_apply
train
def map_or_apply(function, param): """ Map the function on ``param``, or apply it, depending whether ``param`` \ is a list or an item. :param function: The function to apply. :param param: The parameter to feed the function with (list or item). :returns: The computed value or ``None``. ...
python
{ "resource": "" }
q57001
batch
train
def batch(iterable, size): """ Get items from a sequence a batch at a time. .. note: Adapted from https://code.activestate.com/recipes/303279-getting-items-in-batches/. .. note: All batches must be exhausted immediately. :params iterable: An iterable to get batches from...
python
{ "resource": "" }
q57002
slugify
train
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens to have nice filenames. From Django's "django/template/defaultfilters.py". >>> slugify("El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y frío, añoraba a su q...
python
{ "resource": "" }
q57003
get_plaintext_citations
train
def get_plaintext_citations(arxiv_id): """ Get the citations of a given preprint, in plain text. .. note:: Bulk download of sources from arXiv is not permitted by their API. \ You should have a look at http://arxiv.org/help/bulk_data_s3. :param arxiv_id: The arXiv id (e.g. ``1...
python
{ "resource": "" }
q57004
get_cited_dois
train
def get_cited_dois(arxiv_id): """ Get the DOIs of the papers cited in a .bbl file. .. note:: Bulk download of sources from arXiv is not permitted by their API. \ You should have a look at http://arxiv.org/help/bulk_data_s3. :param arxiv_id: The arXiv id (e.g. ``1401.2910`` or ...
python
{ "resource": "" }
q57005
get_subcommand_kwargs
train
def get_subcommand_kwargs(mgr, name, namespace): """Get subcommand options from global parsed arguments. """ subcmd = mgr.get(name) subcmd_kwargs = {} for opt in list(subcmd.args.values()) + list(subcmd.options.values()): if hasattr(namespace, opt.dest): subcmd_kwargs[opt.des...
python
{ "resource": "" }
q57006
get_plaintext_citations
train
def get_plaintext_citations(file): """ Parse a plaintext file to get a clean list of plaintext citations. The \ file should have one citation per line. :param file: Either the path to the plaintext file or the content of a \ plaintext file. :returns: A list of cleaned plaintext...
python
{ "resource": "" }
q57007
get_cited_dois
train
def get_cited_dois(file): """ Get the DOIs of the papers cited in a plaintext file. The file should \ have one citation per line. .. note:: This function is also used as a backend tool by most of the others \ citations processors, to factorize the code. :param file: Either...
python
{ "resource": "" }
q57008
is_valid
train
def is_valid(isbn_id): """ Check that a given string is a valid ISBN. :param isbn_id: the isbn to be checked. :returns: boolean indicating whether the isbn is valid or not. >>> is_valid("978-3-16-148410-0") True >>> is_valid("9783161484100") True >>> is_valid("9783161484100aa") ...
python
{ "resource": "" }
q57009
extract_from_text
train
def extract_from_text(text): """ Extract ISBNs from a text. :param text: Some text. :returns: A list of canonical ISBNs found in the text. >>> extract_from_text("978-3-16-148410-0 9783161484100 9783161484100aa abcd 0136091814 0136091812 9780136091817 123456789X") ['9783161484100', '97831614841...
python
{ "resource": "" }
q57010
get_bibtex
train
def get_bibtex(isbn_identifier): """ Get a BibTeX string for the given ISBN. :param isbn_identifier: ISBN to fetch BibTeX entry for. :returns: A BibTeX string or ``None`` if could not fetch it. >>> get_bibtex('9783161484100') '@book{9783161484100,\\n title = {Berkeley, Oakland: Albany, Eme...
python
{ "resource": "" }
q57011
CommandParser.used_options
train
def used_options(self): """Return options already used in the command line rtype: command.Option generator """ for option_str in filter(lambda c: c.startswith('-'), self.words): for option in list(self.cmd.options.values()): if option_str in option.op...
python
{ "resource": "" }
q57012
CommandParser.available_options
train
def available_options(self): """Return options that can be used given the current cmd line rtype: command.Option generator """ for option in list(self.cmd.options.values()): if (option.is_multiple or option not in list(self.used_options)): ...
python
{ "resource": "" }
q57013
CommandParser.used_args
train
def used_args(self): """Return args already used in the command line rtype: command.Arg generator """ # get all arguments values from the command line values = [] for idx, c in enumerate(self.words[1:]): if c.startswith('-'): continue ...
python
{ "resource": "" }
q57014
CommandParser.available_args
train
def available_args(self): """Return args that can be used given the current cmd line rtype: command.Arg generator """ used = list(self.used_args) logger.debug('Found used args: %s' % used) for arg in list(self.cmd.args.values()): if (arg.is_multiple o...
python
{ "resource": "" }
q57015
is_elem_ref
train
def is_elem_ref(elem_ref): """ Returns true if the elem_ref is an element reference :param elem_ref: :return: """ return ( elem_ref and isinstance(elem_ref, tuple) and len(elem_ref) == 3 and (elem_ref[0] == ElemRefObj or elem_ref[0] == ElemRefArr) )
python
{ "resource": "" }
q57016
get_elem
train
def get_elem(elem_ref, default=None): """ Gets the element referenced by elem_ref or returns the elem_ref directly if its not a reference. :param elem_ref: :param default: :return: """ if not is_elem_ref(elem_ref): return elem_ref elif elem_ref[0] == ElemRefObj: return g...
python
{ "resource": "" }
q57017
set_elem
train
def set_elem(elem_ref, elem): """ Sets element referenced by the elem_ref. Returns the elem. :param elem_ref: :param elem: :return: """ if elem_ref is None or elem_ref == elem or not is_elem_ref(elem_ref): return elem elif elem_ref[0] == ElemRefObj: setattr(elem_ref[1],...
python
{ "resource": "" }
q57018
MathService._preprocess
train
def _preprocess(inp): """Revise wording to match canonical and expected forms.""" inp = re.sub(r'(\b)a(\b)', r'\g<1>one\g<2>', inp) inp = re.sub(r'to the (.*) power', r'to \g<1>', inp) inp = re.sub(r'to the (.*?)(\b)', r'to \g<1>\g<2>', inp) inp = re.sub(r'log of', r'log', inp) ...
python
{ "resource": "" }
q57019
MathService._calculate
train
def _calculate(numbers, symbols): """Calculates a final value given a set of numbers and symbols.""" if len(numbers) is 1: return numbers[0] precedence = [[pow], [mul, div], [add, sub]] # Find most important operation for op_group in precedence: for i, o...
python
{ "resource": "" }
q57020
MathService.parseEquation
train
def parseEquation(self, inp): """Solves the equation specified by the input string. Args: inp (str): An equation, specified in words, containing some combination of numbers, binary, and unary operations. Returns: The floating-point result of carrying out...
python
{ "resource": "" }
q57021
CommandsListPlugin.register
train
def register(self, command, description, function, params=[]): """ Registers a new command for a plugin. :param command: Name of the command :param description: Description of the command. Is used as help message on cli :param function: function reference, which gets invoked if ...
python
{ "resource": "" }
q57022
CommandsListPlugin.get
train
def get(self, name=None): """ Returns commands, which can be filtered by name. :param name: name of the command :type name: str :return: None, single command or dict of commands """ return self.app.commands.get(name, self.plugin)
python
{ "resource": "" }
q57023
CommandsListApplication.get
train
def get(self, name=None, plugin=None): """ Returns commands, which can be filtered by name or plugin. :param name: name of the command :type name: str :param plugin: plugin object, which registers the commands :type plugin: instance of GwBasePattern :return: None...
python
{ "resource": "" }
q57024
CommandsListApplication.unregister
train
def unregister(self, command): """ Unregisters an existing command, so that this command is no longer available on the command line interface. This function is mainly used during plugin deactivation. :param command: Name of the command """ if command not in self._comman...
python
{ "resource": "" }
q57025
declared_caveat
train
def declared_caveat(key, value): '''Returns a "declared" caveat asserting that the given key is set to the given value. If a macaroon has exactly one first party caveat asserting the value of a particular key, then infer_declared will be able to infer the value, and then the check will allow the de...
python
{ "resource": "" }
q57026
_operation_caveat
train
def _operation_caveat(cond, ops): ''' Helper for allow_caveat and deny_caveat. It checks that all operation names are valid before creating the caveat. ''' for op in ops: if op.find(' ') != -1: return error_caveat('invalid operation name "{}"'.format(op)) return _first_party(con...
python
{ "resource": "" }
q57027
to_bytes
train
def to_bytes(s): '''Return s as a bytes type, using utf-8 encoding if necessary. @param s string or bytes @return bytes ''' if isinstance(s, six.binary_type): return s if isinstance(s, six.string_types): return s.encode('utf-8') raise TypeError('want string or bytes, got {}',...
python
{ "resource": "" }
q57028
b64decode
train
def b64decode(s): '''Base64 decodes a base64-encoded string in URL-safe or normal format, with or without padding. The argument may be string or bytes. @param s bytes decode @return bytes decoded @raises ValueError on failure ''' # add padding if necessary. s = to_bytes(s) if no...
python
{ "resource": "" }
q57029
raw_urlsafe_b64encode
train
def raw_urlsafe_b64encode(b): '''Base64 encode using URL-safe encoding with padding removed. @param b bytes to decode @return bytes decoded ''' b = to_bytes(b) b = base64.urlsafe_b64encode(b) b = b.rstrip(b'=') # strip padding return b
python
{ "resource": "" }
q57030
cookie
train
def cookie( url, name, value, expires=None): '''Return a new Cookie using a slightly more friendly API than that provided by six.moves.http_cookiejar @param name The cookie name {str} @param value The cookie value {str} @param url The URL path of the cookie {str} ...
python
{ "resource": "" }
q57031
Im._login
train
def _login(self): """ LOGIN CAN ONLY BE DONE BY POSTING TO A HTTP FORM. A COOKIE IS THEN USED FOR INTERACTING WITH THE API """ self.logger.debug("Logging into " + "{}/{}".format(self._im_api_url, "j_spring_security_check")) self._im_session.headers.update({'Content-Type':...
python
{ "resource": "" }
q57032
Im._do_get
train
def _do_get(self, uri, **kwargs): """ Convinient method for GET requests Returns http request status value from a POST request """ #TODO: # Add error handling. Check for HTTP status here would be much more conveinent than in each calling method scaleioapi_get_head...
python
{ "resource": "" }
q57033
Im.uploadFileToIM
train
def uploadFileToIM (self, directory, filename, title): """ Parameters as they look in the form for uploading packages to IM """ self.logger.debug("uploadFileToIM(" + "{},{},{})".format(directory, filename, title)) parameters = {'data-filename-placement':'inside', ...
python
{ "resource": "" }
q57034
dump_varint_t
train
async def dump_varint_t(writer, type_or, pv): """ Binary dump of the integer of given type :param writer: :param type_or: :param pv: :return: """ width = int_mark_to_size(type_or) n = (pv << 2) | type_or buffer = _UINT_BUFFER for _ in range(width): buffer[0] = n & 0...
python
{ "resource": "" }
q57035
dump_varint
train
async def dump_varint(writer, val): """ Binary dump of the variable size integer :param writer: :param val: :return: """ if val <= 63: return await dump_varint_t(writer, PortableRawSizeMark.BYTE, val) elif val <= 16383: return await dump_varint_t(writer, PortableRawSizeM...
python
{ "resource": "" }
q57036
load_varint
train
async def load_varint(reader): """ Binary load of variable size integer serialized by dump_varint :param reader: :return: """ buffer = _UINT_BUFFER await reader.areadinto(buffer) width = int_mark_to_size(buffer[0] & PortableRawSizeMark.MASK) result = buffer[0] shift = 8 fo...
python
{ "resource": "" }
q57037
dump_string
train
async def dump_string(writer, val): """ Binary string dump :param writer: :param val: :return: """ await dump_varint(writer, len(val)) await writer.awrite(val)
python
{ "resource": "" }
q57038
load_string
train
async def load_string(reader): """ Loads string from binary stream :param reader: :return: """ ivalue = await load_varint(reader) fvalue = bytearray(ivalue) await reader.areadinto(fvalue) return bytes(fvalue)
python
{ "resource": "" }
q57039
dump_blob
train
async def dump_blob(writer, elem, elem_type, params=None): """ Dumps blob to a binary stream :param writer: :param elem: :param elem_type: :param params: :return: """ elem_is_blob = isinstance(elem, x.BlobType) data = bytes(getattr(elem, x.BlobType.DATA_ATTR) if elem_is_blob els...
python
{ "resource": "" }
q57040
Blobber.container_load
train
async def container_load(self, container_type, params=None, container=None, obj=None): """ Loads container of elements from the reader. Supports the container ref. Returns loaded container. Blob array writer as in XMRRPC is serialized without size serialization. :param container...
python
{ "resource": "" }
q57041
make_index_for
train
def make_index_for(package, index_dir, verbose=True): """ Create an 'index.html' for one package. :param package: Package object to use. :param index_dir: Where 'index.html' should be created. """ index_template = """\ <html> <head><title>{title}</title></head> <body> <h1>{title}</h1> <ul> {p...
python
{ "resource": "" }
q57042
make_package_index
train
def make_package_index(download_dir): """ Create a pypi server like file structure below download directory. :param download_dir: Download directory with packages. EXAMPLE BEFORE: +-- downloads/ +-- alice-1.0.zip +-- alice-1.0.tar.gz +-- bob-1.3.0.tar.gz ...
python
{ "resource": "" }
q57043
VSGConfigParser._convert_to_list
train
def _convert_to_list(self, value, delimiters): """ Return a list value translating from other types if necessary. :param str value: The value to convert. """ if not value: return [] if delimiters: return [l.strip() for l in value.split(delimiters...
python
{ "resource": "" }
q57044
VSGConfigParser.getlist
train
def getlist(self, section, option, raw=False, vars=None, fallback=[], delimiters=','): """ A convenience method which coerces the option in the specified section to a list of strings. """ v = self.get(section, option, raw=raw, vars=vars, fallback=fallback) return self._convert_to...
python
{ "resource": "" }
q57045
VSGConfigParser.getfile
train
def getfile(self, section, option, raw=False, vars=None, fallback="", validate=False): """ A convenience method which coerces the option in the specified section to a file. """ v = self.get(section, option, raw=raw, vars=vars, fallback=fallback) v = self._convert_to_path(v) ...
python
{ "resource": "" }
q57046
VSGConfigParser.getdir
train
def getdir(self, section, option, raw=False, vars=None, fallback="", validate=False): """ A convenience method which coerces the option in the specified section to a directory. """ v = self.get(section, option, raw=raw, vars=vars, fallback=fallback) v = self._convert_to_path(v) ...
python
{ "resource": "" }
q57047
VSGConfigParser.getdirs
train
def getdirs(self, section, option, raw=False, vars=None, fallback=[]): """ A convenience method which coerces the option in the specified section to a list of directories. """ globs = self.getlist(section, option, fallback=[]) return [f for g in globs for f in glob.glob(g) if os....
python
{ "resource": "" }
q57048
DocumentsListPlugin.register
train
def register(self, name, content, description=None): """ Register a new document. :param content: Content of this document. Jinja and rst are supported. :type content: str :param name: Unique name of the document for documentation purposes. :param description: Short desc...
python
{ "resource": "" }
q57049
DocumentsListApplication.unregister
train
def unregister(self, document): """ Unregisters an existing document, so that this document is no longer available. This function is mainly used during plugin deactivation. :param document: Name of the document """ if document not in self.documents.keys(): s...
python
{ "resource": "" }
q57050
DocumentsListApplication.get
train
def get(self, document=None, plugin=None): """ Get one or more documents. :param document: Name of the document :type document: str :param plugin: Plugin object, under which the document was registered :type plugin: GwBasePattern """ if plugin is not None...
python
{ "resource": "" }
q57051
PluginManager.initialise_by_names
train
def initialise_by_names(self, plugins=None): """ Initialises given plugins, but does not activate them. This is needed to import and configure libraries, which are imported by used patterns, like GwFlask. After this action, all needed python modules are imported and configured. ...
python
{ "resource": "" }
q57052
PluginManager.activate
train
def activate(self, plugins=[]): """ Activates given plugins. This calls mainly plugin.activate() and plugins register needed resources like commands, signals or documents. If given plugins have not been initialised, this is also done via :func:`_load`. :param plugins: ...
python
{ "resource": "" }
q57053
PluginManager.deactivate
train
def deactivate(self, plugins=[]): """ Deactivates given plugins. A given plugin must be activated, otherwise it is ignored and no action takes place (no signals are fired, no deactivate functions are called.) A deactivated plugin is still loaded and initialised and can be react...
python
{ "resource": "" }
q57054
PluginManager.get
train
def get(self, name=None): """ Returns the plugin object with the given name. Or if a name is not given, the complete plugin dictionary is returned. :param name: Name of a plugin :return: None, single plugin or dictionary of plugins """ if name is None: ...
python
{ "resource": "" }
q57055
PluginManager.is_active
train
def is_active(self, name): """ Returns True if plugin exists and is active. If plugin does not exist, it returns None :param name: plugin name :return: boolean or None """ if name in self._plugins.keys(): return self._plugins["name"].active re...
python
{ "resource": "" }
q57056
PluginClassManager.register
train
def register(self, classes=[]): """ Registers new plugins. The registration only creates a new entry for a plugin inside the _classes dictionary. It does not activate or even initialise the plugin. A plugin must be a class, which inherits directly or indirectly from GwBasePatte...
python
{ "resource": "" }
q57057
PluginClassManager.get
train
def get(self, name=None): """ Returns the plugin class object with the given name. Or if a name is not given, the complete plugin dictionary is returned. :param name: Name of a plugin :return: None, single plugin or dictionary of plugins """ if name is None: ...
python
{ "resource": "" }
q57058
VSGSolution.write
train
def write(self): """ Writes the ``.sln`` file to disk. """ filters = { 'MSGUID': lambda x: ('{%s}' % x).upper(), 'relslnfile': lambda x: os.path.relpath(x, os.path.dirname(self.FileName)) } context = { 'sln': self } retu...
python
{ "resource": "" }
q57059
SAM.load_annotations
train
def load_annotations(self, aname, sep=','): """Loads cell annotations. Loads the cell annoations specified by the 'aname' path. Parameters ---------- aname - string The path to the annotations file. First column should be cell IDs and second column shoul...
python
{ "resource": "" }
q57060
SAM.dispersion_ranking_NN
train
def dispersion_ranking_NN(self, nnm, num_norm_avg=50): """Computes the spatial dispersion factors for each gene. Parameters ---------- nnm - scipy.sparse, float Square cell-to-cell nearest-neighbor matrix. num_norm_avg - int, optional, default 50 The top...
python
{ "resource": "" }
q57061
SAM.plot_correlated_groups
train
def plot_correlated_groups(self, group=None, n_genes=5, **kwargs): """Plots orthogonal expression patterns. In the default mode, plots orthogonal gene expression patterns. A specific correlated group of genes can be specified to plot gene expression patterns within that group. ...
python
{ "resource": "" }
q57062
SAM.plot_correlated_genes
train
def plot_correlated_genes( self, name, n_genes=5, number_of_features=1000, **kwargs): """Plots gene expression patterns correlated with the input gene. Parameters ---------- name - string The name of the gene with r...
python
{ "resource": "" }
q57063
SAM.run_tsne
train
def run_tsne(self, X=None, metric='correlation', **kwargs): """Wrapper for sklearn's t-SNE implementation. See sklearn for the t-SNE documentation. All arguments are the same with the exception that 'metric' is set to 'precomputed' by default, implying that this function expects a dista...
python
{ "resource": "" }
q57064
SAM.run_umap
train
def run_umap(self, X=None, metric=None, **kwargs): """Wrapper for umap-learn. See https://github.com/lmcinnes/umap sklearn for the documentation and source code. """ import umap as umap if metric is None: metric = self.distance if(X is not None): ...
python
{ "resource": "" }
q57065
SAM.scatter
train
def scatter(self, projection=None, c=None, cmap='rainbow', linewidth=0.0, edgecolor='k', axes=None, colorbar=True, s=10, **kwargs): """Display a scatter plot. Displays a scatter plot using the SAM projection or another input projection with or without annotations. Param...
python
{ "resource": "" }
q57066
SAM.show_gene_expression
train
def show_gene_expression(self, gene, avg=True, axes=None, **kwargs): """Display a gene's expressions. Displays a scatter plot using the SAM projection or another input projection with a particular gene's expressions overlaid. Parameters ---------- gene - string ...
python
{ "resource": "" }
q57067
SAM.louvain_clustering
train
def louvain_clustering(self, X=None, res=1, method='modularity'): """Runs Louvain clustering using the vtraag implementation. Assumes that 'louvain' optional dependency is installed. Parameters ---------- res - float, optional, default 1 The resolution parameter whic...
python
{ "resource": "" }
q57068
SAM.kmeans_clustering
train
def kmeans_clustering(self, numc, X=None, npcs=15): """Performs k-means clustering. Parameters ---------- numc - int Number of clusters npcs - int, optional, default 15 Number of principal components to use as inpute for k-means clustering. ...
python
{ "resource": "" }
q57069
SAM.identify_marker_genes_rf
train
def identify_marker_genes_rf(self, labels=None, clusters=None, n_genes=4000): """ Ranks marker genes for each cluster using a random forest classification approach. Parameters ---------- labels - numpy.array or str, optional, default Non...
python
{ "resource": "" }
q57070
SAM.identify_marker_genes_corr
train
def identify_marker_genes_corr(self, labels=None, n_genes=4000): """ Ranking marker genes based on their respective magnitudes in the correlation dot products with cluster-specific reference expression profiles. Parameters ---------- labels - numpy.array or str...
python
{ "resource": "" }
q57071
Ability.add
train
def add(self, action=None, subject=None, **conditions): """ Add ability are allowed using two arguments. The first one is the action you're setting the permission for, the second one is the class of object you're setting it on. the third one is the subject's conditions must be m...
python
{ "resource": "" }
q57072
Ability.addnot
train
def addnot(self, action=None, subject=None, **conditions): """ Defines an ability which cannot be done. """ self.add_rule(Rule(False, action, subject, **conditions))
python
{ "resource": "" }
q57073
Ability.can
train
def can(self, action, subject, **conditions): """ Check if the user has permission to perform a given action on an object """ for rule in self.relevant_rules_for_match(action, subject): if rule.matches_conditions(action, subject, **conditions): return rule.bas...
python
{ "resource": "" }
q57074
Ability.relevant_rules_for_match
train
def relevant_rules_for_match(self, action, subject): """retrive match action and subject""" matches = [] for rule in self.rules: rule.expanded_actions = self.expand_actions(rule.actions) if rule.is_relevant(action, subject): matches.append(rule) r...
python
{ "resource": "" }
q57075
Ability.expand_actions
train
def expand_actions(self, actions): """ Accepts an array of actions and returns an array of actions which match """ r = [] for action in actions: r.append(action) if action in self.aliased_actions: r.extend(self.aliased_actions[action]) ...
python
{ "resource": "" }
q57076
Ability.alias_action
train
def alias_action(self, *args, **kwargs): """ Alias one or more actions into another one. self.alias_action('create', 'read', 'update', 'delete', to='crud') """ to = kwargs.pop('to', None) if not to: return error_message = ("You can't specify target (...
python
{ "resource": "" }
q57077
fetch
train
def fetch(table, cols="*", where=(), group="", order=(), limit=(), **kwargs): """Convenience wrapper for database SELECT and fetch all.""" return select(table, cols, where, group, order, limit, **kwargs).fetchall()
python
{ "resource": "" }
q57078
fetchone
train
def fetchone(table, cols="*", where=(), group="", order=(), limit=(), **kwargs): """Convenience wrapper for database SELECT and fetch one.""" return select(table, cols, where, group, order, limit, **kwargs).fetchone()
python
{ "resource": "" }
q57079
insert
train
def insert(table, values=(), **kwargs): """Convenience wrapper for database INSERT.""" values = dict(values, **kwargs).items() sql, args = makeSQL("INSERT", table, values=values) return execute(sql, args).lastrowid
python
{ "resource": "" }
q57080
select
train
def select(table, cols="*", where=(), group="", order=(), limit=(), **kwargs): """Convenience wrapper for database SELECT.""" where = dict(where, **kwargs).items() sql, args = makeSQL("SELECT", table, cols, where, group, order, limit) return execute(sql, args)
python
{ "resource": "" }
q57081
update
train
def update(table, values, where=(), **kwargs): """Convenience wrapper for database UPDATE.""" where = dict(where, **kwargs).items() sql, args = makeSQL("UPDATE", table, values=values, where=where) return execute(sql, args).rowcount
python
{ "resource": "" }
q57082
delete
train
def delete(table, where=(), **kwargs): """Convenience wrapper for database DELETE.""" where = dict(where, **kwargs).items() sql, args = makeSQL("DELETE", table, where=where) return execute(sql, args).rowcount
python
{ "resource": "" }
q57083
make_cursor
train
def make_cursor(path, init_statements=(), _connectioncache={}): """Returns a cursor to the database, making new connection if not cached.""" connection = _connectioncache.get(path) if not connection: is_new = not os.path.exists(path) or not os.path.getsize(path) try: is_new and os.maked...
python
{ "resource": "" }
q57084
continue_prompt
train
def continue_prompt(message=""): """Prompt the user to continue or not Returns True when the user type Yes. :param message: message to display :type message: str :rtype: bool """ answer = False message = message + "\n'Yes' or 'No' to continue: " while answer not in ('Yes', 'No'): ...
python
{ "resource": "" }
q57085
printo
train
def printo(msg, encoding=None, errors='replace', std_type='stdout'): """Write msg on stdout. If no encoding is specified the detected encoding of stdout is used. If the encoding can't encode some chars they are replaced by '?' :param msg: message :type msg: unicode on python2 | str on python3 "...
python
{ "resource": "" }
q57086
format_tree
train
def format_tree(tree): """Format a python tree structure Given the python tree:: tree = { 'node': ['ROOT', 'This is the root of the tree'], 'childs': [{ 'node': 'A1', 'childs': [{ 'node': 'B1', 'childs': [{...
python
{ "resource": "" }
q57087
parallel_map
train
def parallel_map(func, iterable, args=None, kwargs=None, workers=None): """Map func on a list using gevent greenlets. :param func: function applied on iterable elements :type func: function :param iterable: elements to map the function over :type iterable: iterable :param args: arguments of fun...
python
{ "resource": "" }
q57088
NumberService.parse
train
def parse(self, words): """A general method for parsing word-representations of numbers. Supports floats and integers. Args: words (str): Description of an arbitrary number. Returns: A double representation of the words. """ def exact(words): ...
python
{ "resource": "" }
q57089
NumberService.parseFloat
train
def parseFloat(self, words): """Convert a floating-point number described in words to a double. Supports two kinds of descriptions: those with a 'point' (e.g., "one point two five") and those with a fraction (e.g., "one and a quarter"). Args: words (str): Descriptio...
python
{ "resource": "" }
q57090
NumberService.parseInt
train
def parseInt(self, words): """Parses words to the integer they describe. Args: words (str): Description of the integer. Returns: An integer representation of the words. """ # Remove 'and', case-sensitivity words = words.replace(" and ", " ").lowe...
python
{ "resource": "" }
q57091
NumberService.parseMagnitude
train
def parseMagnitude(m): """Parses a number m into a human-ready string representation. For example, crops off floats if they're too accurate. Arguments: m (float): Floating-point number to be cleaned. Returns: Human-ready string description of the number. ...
python
{ "resource": "" }
q57092
PrivateKey.serialize
train
def serialize(self, raw=False): '''Encode the private part of the key in a base64 format by default, but when raw is True it will return hex encoded bytes. @return: bytes ''' if raw: return self._key.encode() return self._key.encode(nacl.encoding.Base64Encoder...
python
{ "resource": "" }
q57093
Connection._do_get
train
def _do_get(self, url, **kwargs): """ Convenient method for GET requests Returns http request status value from a POST request """ #TODO: # Add error handling. Check for HTTP status here would be much more conveinent than in each calling method scaleioapi_post_hea...
python
{ "resource": "" }
q57094
Connection._do_post
train
def _do_post(self, url, **kwargs): """ Convenient method for POST requests Returns http request status value from a POST request """ #TODO: # Add error handling. Check for HTTP status here would be much more conveinent than in each calling method scaleioapi_post_h...
python
{ "resource": "" }
q57095
discharge_required_response
train
def discharge_required_response(macaroon, path, cookie_suffix_name, message=None): ''' Get response content and headers from a discharge macaroons error. @param macaroon may hold a macaroon that, when discharged, may allow access to a service. @param path holds the URL p...
python
{ "resource": "" }
q57096
request_version
train
def request_version(req_headers): ''' Determines the bakery protocol version from a client request. If the protocol cannot be determined, or is invalid, the original version of the protocol is used. If a later version is found, the latest known version is used, which is OK because versions are backwardl...
python
{ "resource": "" }
q57097
Error.from_dict
train
def from_dict(cls, serialized): '''Create an error from a JSON-deserialized object @param serialized the object holding the serialized error {dict} ''' # Some servers return lower case field names for message and code. # The Go client is tolerant of this, so be similarly tolerant...
python
{ "resource": "" }
q57098
Error.interaction_method
train
def interaction_method(self, kind, x): ''' Checks whether the error is an InteractionRequired error that implements the method with the given name, and JSON-unmarshals the method-specific data into x by calling its from_dict method with the deserialized JSON object. @param kind T...
python
{ "resource": "" }
q57099
ErrorInfo.from_dict
train
def from_dict(cls, serialized): '''Create a new ErrorInfo object from a JSON deserialized dictionary @param serialized The JSON object {dict} @return ErrorInfo object ''' if serialized is None: return None macaroon = serialized.get('Macaroon') ...
python
{ "resource": "" }