_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q50200 | add_time | train | def add_time(data):
"""And a friendly update time to the supplied data.
Arguments:
data (:py:class:`dict`): The response data and its update time.
Returns:
:py:class:`dict`: The data with a friendly update time.
"""
payload = data['data']
updated = data['updated'].date()
if up... | python | {
"resource": ""
} |
q50201 | DataFrame.dtypes | train | def dtypes(self):
"""Series of NumPy dtypes present in the DataFrame with index of column names.
Returns
-------
Series
"""
return Series(np.array(list(self._gather_dtypes().values()), dtype=np.bytes_),
self.keys()) | python | {
"resource": ""
} |
q50202 | DataFrame.columns | train | def columns(self):
"""Index of the column names present in the DataFrame in order.
Returns
-------
Index
"""
return Index(np.array(self._gather_column_names(), dtype=np.bytes_), np.dtype(np.bytes_)) | python | {
"resource": ""
} |
q50203 | DataFrame.astype | train | def astype(self, dtype):
"""Cast DataFrame columns to given dtype.
Parameters
----------
dtype : numpy.dtype or dict
Dtype or column_name -> dtype mapping to cast columns to. Note index is excluded.
Returns
-------
DataFrame
With casted c... | python | {
"resource": ""
} |
q50204 | DataFrame.evaluate | train | def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True):
"""Evaluates by creating a DataFrame containing evaluated data and index.
See `LazyResult`
Returns
-------
DataFrame
DataFrame with evaluated data and index.
... | python | {
"resource": ""
} |
q50205 | DataFrame.tail | train | def tail(self, n=5):
"""Return DataFrame with last n values per column.
Parameters
----------
n : int
Number of values.
Returns
-------
DataFrame
DataFrame containing the last n values per column.
Examples
--------
... | python | {
"resource": ""
} |
q50206 | DataFrame.rename | train | def rename(self, columns):
"""Returns a new DataFrame with renamed columns.
Currently a simplified version of Pandas' rename.
Parameters
----------
columns : dict
Old names to new names.
Returns
-------
DataFrame
With columns ren... | python | {
"resource": ""
} |
q50207 | DataFrame.drop | train | def drop(self, columns):
"""Drop 1 or more columns. Any column which does not exist in the DataFrame is skipped, i.e. not removed,
without raising an exception.
Unlike Pandas' drop, this is currently restricted to dropping columns.
Parameters
----------
columns : str or... | python | {
"resource": ""
} |
q50208 | DataFrame.set_index | train | def set_index(self, keys):
"""Set the index of the DataFrame to be the keys columns.
Note this means that the old index is removed.
Parameters
----------
keys : str or list of str
Which column(s) to set as the index.
Returns
-------
DataFram... | python | {
"resource": ""
} |
q50209 | DataFrame.sort_index | train | def sort_index(self, ascending=True):
"""Sort the index of the DataFrame.
Currently MultiIndex is not supported since Weld is missing multiple-column sort.
Note this is an expensive operation (brings all data to Weld).
Parameters
----------
ascending : bool, optional
... | python | {
"resource": ""
} |
q50210 | DataFrame.sort_values | train | def sort_values(self, by, ascending=True):
"""Sort the DataFrame based on a column.
Unlike Pandas, one can sort by data from both index and regular columns.
Currently possible to sort only on a single column since Weld is missing multiple-column sort.
Note this is an expensive operatio... | python | {
"resource": ""
} |
q50211 | DataFrame.dropna | train | def dropna(self, subset=None):
"""Remove missing values according to Baloo's convention.
Parameters
----------
subset : list of str, optional
Which columns to check for missing values in.
Returns
-------
DataFrame
DataFrame with no null v... | python | {
"resource": ""
} |
q50212 | DataFrame.fillna | train | def fillna(self, value):
"""Returns DataFrame with missing values replaced with value.
Parameters
----------
value : {int, float, bytes, bool} or dict
Scalar value to replace missing values with. If dict, replaces missing values
only in the key columns with the v... | python | {
"resource": ""
} |
q50213 | DataFrame.groupby | train | def groupby(self, by):
"""Group by certain columns, excluding index.
Simply reset_index if desiring to group by some index column too.
Parameters
----------
by : str or list of str
Column(s) to groupby.
Returns
-------
DataFrameGroupBy
... | python | {
"resource": ""
} |
q50214 | DataFrame.from_pandas | train | def from_pandas(cls, df):
"""Create baloo DataFrame from pandas DataFrame.
Parameters
----------
df : pandas.frame.DataFrame
Returns
-------
DataFrame
"""
from pandas import DataFrame as PandasDataFrame, Index as PandasIndex, MultiIndex as Panda... | python | {
"resource": ""
} |
q50215 | BabelfyClient.babelfy | train | def babelfy(self, text, params=None):
"""make a request to the babelfy api and babelfy param text
set self._data with the babelfied text as json object
"""
self._entities = list()
self._all_entities = list()
self._merged_entities = list()
self._all_merged_entities... | python | {
"resource": ""
} |
q50216 | BabelfyClient._parse_entities | train | def _parse_entities(self):
"""enrich the babelfied data with the text an the isEntity items
set self._entities with the enriched data
"""
entities = list()
for result in self._data:
entity = dict()
char_fragment = result.get('charFragment')
st... | python | {
"resource": ""
} |
q50217 | BabelfyClient._parse_non_entities | train | def _parse_non_entities(self):
"""create data for all non-entities in the babelfied text
set self._all_entities with merged entity and non-entity data
"""
def _differ(tokens):
inner, outer = tokens
not_same_start = inner.get('start') != outer.get('start')
... | python | {
"resource": ""
} |
q50218 | BabelfyClient._wraps | train | def _wraps(self, tokens):
"""determine if a token is wrapped by another token
"""
def _differ(tokens):
inner, outer = tokens
not_same_start = inner.get('start') != outer.get('start')
not_same_end = inner.get('end') != outer.get('end')
return not_sa... | python | {
"resource": ""
} |
q50219 | BabelfyClient._is_wrapped | train | def _is_wrapped(self, token, tokens):
"""check if param token is wrapped by any token in tokens
"""
for t in tokens:
is_wrapped = self._wraps((token, t))
if is_wrapped:
return True
return False | python | {
"resource": ""
} |
q50220 | Advice.apply | train | def apply(self, joinpoint):
"""Apply this advice on input joinpoint.
TODO: improve with internal methods instead of conditional test.
"""
if self._enable:
result = self._impl(joinpoint)
else:
result = joinpoint.proceed()
return result | python | {
"resource": ""
} |
q50221 | Advice.set_enable | train | def set_enable(target, enable=True, advice_ids=None):
"""Enable or disable all target Advices designated by input advice_ids.
If advice_ids is None, apply (dis|en)able state to all advices.
"""
advices = get_advices(target)
for advice in advices:
try:
... | python | {
"resource": ""
} |
q50222 | Advice.weave | train | def weave(target, advices, pointcut=None, depth=1, public=False):
"""Weave advices such as Advice objects."""
advices = (
advice if isinstance(advice, Advice) else Advice(advice)
for advice in advices
)
weave(
target=target, advices=advices, pointcut... | python | {
"resource": ""
} |
q50223 | Advice.unweave | train | def unweave(target, *advices):
"""Unweave advices from input target."""
advices = (
advice if isinstance(advice, Advice) else Advice(advice)
for advice in advices
)
unweave(target=target, *advices) | python | {
"resource": ""
} |
q50224 | SummaryExperiment.summarise | train | def summarise( self, results ):
"""Generate a summary of results from a list of result dicts
returned by running the underlying experiment. By default we generate
mean, median, variance, and extrema for each value recorded.
Override this method to create different or extra summary stati... | python | {
"resource": ""
} |
q50225 | SummaryExperiment.do | train | def do( self, params ):
"""Perform the underlying experiment and summarise its results.
Our results are the summary statistics extracted from the results of
the instances of the underlying experiment that we performed.
We drop from the calculations any experiments whose completion statu... | python | {
"resource": ""
} |
q50226 | ss_to_xy | train | def ss_to_xy(s: str):
"""convert spreadsheet coordinates to zero-index xy coordinates.
return None if input is invalid"""
result = re.match(r'\$*([A-Z]+)\$*([0-9]+)', s, re.I)
if result == None:
return None
xstring = result.group(1).upper()
multiplier = 1
x = 0
for i in xstring:
... | python | {
"resource": ""
} |
q50227 | SqliteLabNotebook.open | train | def open( self ):
"""Open the database connection."""
if self._connection is None:
self._connection = sqlite3.connect(self._dbfile) | python | {
"resource": ""
} |
q50228 | SqliteLabNotebook._createDatabase | train | def _createDatabase( self ):
"""Private method to create the SQLite database file."""
# create experiment metadata table
command = """
CREATE TABLE {tn} (
{k} INT PRIMARY KEY NOT NULL,
START_TIME INT NOT NULL,
... | python | {
"resource": ""
} |
q50229 | alchemyencoder | train | def alchemyencoder(obj):
"""JSON encoder function for SQLAlchemy special classes."""
if isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance(obj, decimal.Decimal):
return float(obj) | python | {
"resource": ""
} |
q50230 | AuthTokenAuthentication.authenticate_credentials | train | def authenticate_credentials(self, token: bytes, request=None):
"""
Authenticate the token with optional request for context.
"""
user = AuthToken.get_user_for_token(token)
if user is None:
raise AuthenticationFailed(_('Invalid auth token.'))
if not user.is_... | python | {
"resource": ""
} |
q50231 | Hashcache.set | train | def set(self, key, *args):
"""Hash the key and set it in the cache"""
return self.cache.set(self._hashed(key), *args) | python | {
"resource": ""
} |
q50232 | conv_from_name | train | def conv_from_name(name):
"""
Understand simulink syntax for fixed types and returns the proper
conversion structure.
@param name: the type name as in simulin (i.e. UFix_8_7 ... )
@raise ConversionError: When cannot decode the string
"""
_match = re.match(r"^(?P<signed>u?fix)_(?P<bits>\d+)_... | python | {
"resource": ""
} |
q50233 | _get_unsigned_params | train | def _get_unsigned_params(conv):
"""
Fill the sign-dependent params of the conv structure in case of unsigned
conversion
@param conv: the structure to be filled
"""
conv["sign_mask"] = 0
conv["int_min"] = 0
conv["int_mask"] = sum([2 ** i for i in range(conv["bin_point"],
conv["b... | python | {
"resource": ""
} |
q50234 | _get_signed_params | train | def _get_signed_params(conv):
"""
Fill the sign-dependent params of the conv structure in case of signed
conversion
@param conv: the structure to be filled
"""
conv["sign_mask"] = 2 ** (conv["bits"] - 1)
conv["int_min"] = -1 * (2 ** (conv["bits"] - 1 - conv["bin_point"]))
conv["int_mask... | python | {
"resource": ""
} |
q50235 | fix2real | train | def fix2real(uval, conv):
"""
Convert a 32 bit unsigned int register into the value it represents in its Fixed arithmetic form.
@param uval: the numeric unsigned value in simulink representation
@param conv: conv structure with conversion specs as generated by I{get_conv}
@return: the real number re... | python | {
"resource": ""
} |
q50236 | bin2real | train | def bin2real(binary_string, conv, endianness="@"):
"""
Converts a binary string representing a number to its Fixed arithmetic representation
@param binary_string: binary number in simulink representation
@param conv: conv structure containing conversion specs
@param endianness: optionally specify by... | python | {
"resource": ""
} |
q50237 | stream2real | train | def stream2real(binary_stream, conv, endianness="@"):
"""
Converts a binary stream into a sequence of real numbers
@param binary_stream: a binary string representing a sequence of numbers
@param conv: conv structure containing conversion specs
@param endianness: optionally specify bytes endianness f... | python | {
"resource": ""
} |
q50238 | real2fix | train | def real2fix(real, conv):
"""
Convert a real number to its fixed representation so
that it can be written into a 32 bit register.
@param real: the real number to be converted into fixed representation
@param conv: conv structre with conversion specs
@return: the fixed representation of the real... | python | {
"resource": ""
} |
q50239 | QueueSet._emulated | train | def _emulated(self, timeout=None):
"""Get the next message avaiable in the queue.
:returns: The message and the name of the queue it came from as
a tuple.
:raises Empty: If there are no more items in any of the queues.
"""
# A set of queues we've already tried.
... | python | {
"resource": ""
} |
q50240 | fallback_render | train | def fallback_render(template, context, at_paths=None,
at_encoding=anytemplate.compat.ENCODING,
**kwargs):
"""
Render from given template and context.
This is a basic implementation actually does nothing and just returns
the content of given template file `templat... | python | {
"resource": ""
} |
q50241 | Engine.filter_options | train | def filter_options(cls, kwargs, keys):
"""
Make optional kwargs valid and optimized for each template engines.
:param kwargs: keyword arguements to process
:param keys: optional argument names
>>> Engine.filter_options(dict(aaa=1, bbb=2), ("aaa", ))
{'aaa': 1}
>... | python | {
"resource": ""
} |
q50242 | main | train | def main(tex_file, output, verbose):
"""
FLaP merges your LaTeX projects into a single LaTeX file that
refers to images in the same directory.
It reads the given root TEX_FILE and generates a flatten version in the
given OUTPUT directory. It inlines the content of any TeX files refered by
\\inp... | python | {
"resource": ""
} |
q50243 | deploy | train | def deploy(overwrite=False):
"""
deploy a versioned project on the host
"""
check_settings()
if overwrite:
rmvirtualenv()
deploy_funcs = [deploy_project,deploy_templates, deploy_static, deploy_media, deploy_webconf, deploy_wsgi]
if not patch_project() or overwrite:
deploy_fu... | python | {
"resource": ""
} |
q50244 | setupnode | train | def setupnode(overwrite=False):
"""
Install a baseline host. Can be run multiple times
"""
if not port_is_open():
if not skip_disable_root():
disable_root()
port_changed = change_ssh_port()
#avoid trying to take shortcuts if setupnode did not finish
#on previous exe... | python | {
"resource": ""
} |
q50245 | Bonjour.publish | train | def publish(self, daap_server, preferred_database=None):
"""
Publish a given `DAAPServer` instance.
The given instances should be fully configured, including the provider.
By default Zeroconf only advertises the first database, but the DAAP
protocol has support for multiple data... | python | {
"resource": ""
} |
q50246 | Bonjour.unpublish | train | def unpublish(self, daap_server):
"""
Unpublish a given server.
If the server was not published, this method will not do anything.
:param DAAPServer daap_server: DAAP Server instance to publish.
"""
if daap_server not in self.daap_servers:
return
s... | python | {
"resource": ""
} |
q50247 | VarianceDecomposition.addRandomEffect | train | def addRandomEffect(self, K=None, is_noise=False, normalize=False, Kcross=None, trait_covar_type='freeform', rank=1, fixed_trait_covar=None, jitter=1e-4):
"""
Add random effects term.
Args:
K: Sample Covariance Matrix [N, N]
is_noise: Boolean indicator specifying ... | python | {
"resource": ""
} |
q50248 | VarianceDecomposition.addFixedEffect | train | def addFixedEffect(self, F=None, A=None, Ftest=None):
"""
add fixed effect term to the model
Args:
F: sample design matrix for the fixed effect [N,K]
A: trait design matrix for the fixed effect (e.g. sp.ones((1,P)) common effect; sp.eye(P) any effect) [L,P]
... | python | {
"resource": ""
} |
q50249 | VarianceDecomposition.optimize | train | def optimize(self, init_method='default', inference=None, n_times=10, perturb=False, pertSize=1e-3, verbose=None):
"""
Train the model using the specified initialization strategy
Args:
init_method: initialization strategy:
'default': variance is eq... | python | {
"resource": ""
} |
q50250 | VarianceDecomposition.getWeights | train | def getWeights(self, term_i=None):
"""
Return weights for fixed effect term term_i
Args:
term_i: fixed effect term index
Returns:
weights of the spefied fixed effect term.
The output will be a KxL matrix of weights will be returned,
wh... | python | {
"resource": ""
} |
q50251 | VarianceDecomposition.getVarianceComps | train | def getVarianceComps(self, univariance=False):
"""
Return the estimated variance components
Args:
univariance: Boolean indicator, if True variance components are normalized to sum up to 1 for each trait
Returns:
variance components of all random effects on all ... | python | {
"resource": ""
} |
q50252 | VarianceDecomposition._init_params_default | train | def _init_params_default(self):
"""
Internal method for default parameter initialization
"""
# if there are some nan -> mean impute
Yimp = self.Y.copy()
Inan = sp.isnan(Yimp)
Yimp[Inan] = Yimp[~Inan].mean()
if self.P==1: C = sp.array([[Yimp.var()]])
... | python | {
"resource": ""
} |
q50253 | VarianceDecomposition._det_inference | train | def _det_inference(self):
"""
Internal method for determining the inference method
"""
# 2 random effects with complete design -> gp2KronSum
# TODO: add check for low-rankness, use GP3KronSumLR and GP2KronSumLR when possible
if (self.n_randEffs==2) and (~sp.isnan(self.Y).... | python | {
"resource": ""
} |
q50254 | VarianceDecomposition._check_inference | train | def _check_inference(self, inference):
"""
Internal method for checking that the selected inference scheme is compatible with the specified model
"""
if inference=='GP2KronSum':
assert self.n_randEffs==2, 'VarianceDecomposition: for fast inference number of random effect term... | python | {
"resource": ""
} |
q50255 | VarianceDecomposition._initGP | train | def _initGP(self):
"""
Internal method for initialization of the GP inference objetct
"""
if self._inference=='GP2KronSum':
signalPos = sp.where(sp.arange(self.n_randEffs)!=self.noisPos)[0][0]
gp = GP2KronSum(Y=self.Y, F=self.sample_designs, A=self.trait_designs,... | python | {
"resource": ""
} |
q50256 | VarianceDecomposition._buildTraitCovar | train | def _buildTraitCovar(self, trait_covar_type='freeform', rank=1, fixed_trait_covar=None, jitter=1e-4):
"""
Internal functions that builds the trait covariance matrix using the LIMIX framework
Args:
trait_covar_type: type of covaraince to use. Default 'freeform'. possible values are
... | python | {
"resource": ""
} |
q50257 | VarianceDecomposition.optimize_with_repeates | train | def optimize_with_repeates(self,fast=None,verbose=None,n_times=10,lambd=None,lambd_g=None,lambd_n=None):
"""
Train the model repeadly up to a number specified by the users with random restarts and
return a list of all relative minima that have been found. This list is sorted according to
... | python | {
"resource": ""
} |
q50258 | VarianceDecomposition._getScalesDiag | train | def _getScalesDiag(self,termx=0):
"""
Internal function for parameter initialization
Uses 2 term single trait model to get covar params for initialization
Args:
termx: non-noise term terms that is used for initialization
"""
assert self.P>1, 'VarianceDec... | python | {
"resource": ""
} |
q50259 | VarianceDecomposition._getScalesRand | train | def _getScalesRand(self):
"""
Internal function for parameter initialization
Return a vector of random scales
"""
if self.P>1:
scales = []
for term_i in range(self.n_randEffs):
_scales = sp.randn(self.diag[term_i].shape[0])
... | python | {
"resource": ""
} |
q50260 | VarianceDecomposition._perturbation | train | def _perturbation(self):
"""
Internal function for parameter initialization
Returns Gaussian perturbation
"""
if self.P>1:
scales = []
for term_i in range(self.n_randEffs):
_scales = sp.randn(self.diag[term_i].shape[0])
if s... | python | {
"resource": ""
} |
q50261 | join_tokens_to_sentences | train | def join_tokens_to_sentences(tokens):
""" Correctly joins tokens to multiple sentences
Instead of always placing white-space between the tokens, it will distinguish
between the next symbol and *not* insert whitespace if it is a sentence
symbol (e.g. '.', or '?')
Args:
tokens: array of stri... | python | {
"resource": ""
} |
q50262 | split | train | def split(inp_str, sep_char, maxsplit=-1, escape_char='\\'):
"""Separates a string on a character, taking into account escapes.
:param str inp_str: string to split.
:param str sep_char: separator character.
:param int maxsplit: maximum number of times to split from left.
:param str escape_char: esc... | python | {
"resource": ""
} |
q50263 | _split_path | train | def _split_path(xj_path):
"""Extract the last piece of XJPath.
:param str xj_path: A XJPath expression.
:rtype: tuple[str|None, str]
:return: A tuple where first element is a root XJPath and the second is
a last piece of key.
"""
res = xj_path.rsplit('.', 1)
root_key = res[0]
... | python | {
"resource": ""
} |
q50264 | validate_path | train | def validate_path(xj_path):
"""Validates XJ path.
:param str xj_path: XJ Path
:raise: XJPathError if validation fails.
"""
if not isinstance(xj_path, str):
raise XJPathError('XJPath must be a string')
for path in split(xj_path, '.'):
if path == '*':
continue
... | python | {
"resource": ""
} |
q50265 | _clean_key_type | train | def _clean_key_type(key_name, escape_char=ESCAPE_SEQ):
"""Removes type specifier returning detected type and
a key name without type specifier.
:param str key_name: A key name containing type postfix.
:rtype: tuple[type|None, str]
:returns: Type definition and cleaned key name.
"""
for i i... | python | {
"resource": ""
} |
q50266 | sort_prefixes | train | def sort_prefixes(orig, prefixes='@+'):
"""Returns a sorted list of prefixes.
Args:
orig (str): Unsorted list of prefixes.
prefixes (str): List of prefixes, from highest-priv to lowest.
"""
new = ''
for prefix in prefixes:
if prefix in orig:
new += prefix
ret... | python | {
"resource": ""
} |
q50267 | parse_modes | train | def parse_modes(params, mode_types=None, prefixes=''):
"""Return a modelist.
Args:
params (list of str): Parameters from MODE event.
mode_types (list): CHANMODES-like mode types.
prefixes (str): PREFIX-like mode types.
"""
# we don't accept bare strings because we don't want to ... | python | {
"resource": ""
} |
q50268 | read_envfile | train | def read_envfile(fpath):
"""Reads environment variables from .env key-value file.
Rules:
* Lines starting with # (hash) considered comments. Inline comments not supported;
* Multiline values not supported.
* Invalid lines are ignored;
* Matching opening-closing quotes are stripp... | python | {
"resource": ""
} |
q50269 | HttpBL._decode_response | train | def _decode_response(self, ip_address):
"""Decodes a HttpBL response IP and return data structure of response
data.
:param ip_address: IP address to query
:type ip_address: str
:rtype: dict
:raises: ValueError
"""
# Reverse the IP, reassign the octets to... | python | {
"resource": ""
} |
q50270 | verify_claims | train | def verify_claims(app_req, issuer=None):
"""
Verify JWT claims.
All times must be UTC unix timestamps.
These claims will be verified:
- iat: issued at time. If JWT was issued more than an hour ago it is
rejected.
- exp: expiration time.
All exceptions are derived from
:class:`m... | python | {
"resource": ""
} |
q50271 | verify_keys | train | def verify_keys(app_req, required_keys, issuer=None):
"""
Verify all JWT object keys listed in required_keys.
Each required key is specified as a dot-separated path.
The key values are returned as a list ordered by how
you specified them.
Take this JWT for example::
{
"iss... | python | {
"resource": ""
} |
q50272 | verify_sig | train | def verify_sig(signed_request, secret, issuer=None, algorithms=None,
expected_aud=None):
"""
Verify the JWT signature.
Given a raw JWT, this verifies it was signed with
*secret*, decodes it, and returns the JSON dict.
"""
if not issuer:
issuer = _get_issuer(signed_request... | python | {
"resource": ""
} |
q50273 | _re_raise_as | train | def _re_raise_as(NewExc, *args, **kw):
"""Raise a new exception using the preserved traceback of the last one."""
etype, val, tb = sys.exc_info()
raise NewExc(*args, **kw), None, tb | python | {
"resource": ""
} |
q50274 | generators | train | def generators():
"""
List all the available generators.
"""
from populous import generators
base = generators.Generator
for name in dir(generators):
generator = getattr(generators, name)
if isinstance(generator, type) and issubclass(generator, base):
name = genera... | python | {
"resource": ""
} |
q50275 | snake_case | train | def snake_case(string):
''' Takes a string that represents for example a class name and returns
the snake case version of it. It is used for model-to-key conversion '''
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | python | {
"resource": ""
} |
q50276 | Field.value_or_default | train | def value_or_default(self, value):
''' Returns the given value or the specified default value for this
field '''
if value is None:
if callable(self.default):
return self.default()
else:
return self.default
return value | python | {
"resource": ""
} |
q50277 | Field.validate_required | train | def validate_required(self, value):
''' Validates the given value agains this field's 'required' property
'''
if self.required and (value is None or value==''):
raise MissingFieldError(self.name) | python | {
"resource": ""
} |
q50278 | Field.recover | train | def recover(self, data, redis=None):
''' Retrieve this field's value from the database '''
value = data.get(self.name)
if value is None or value == 'None':
return None
return str(value) | python | {
"resource": ""
} |
q50279 | Field.save | train | def save(self, value, redis, *, commit=True):
''' Sets this fields value in the databse '''
value = self.prepare(value)
if value is not None:
redis.hset(self.obj.key(), self.name, value)
else:
redis.hdel(self.obj.key(), self.name)
if self.index:
... | python | {
"resource": ""
} |
q50280 | Field.validate | train | def validate(self, value, redis):
'''
Validates data obtained from a request and returns it in the apropiate
format
'''
# cleanup
if type(value) == str:
value = value.strip()
value = self.value_or_default(value)
# validation
self.vali... | python | {
"resource": ""
} |
q50281 | Hash.init | train | def init(self, value):
''' hash passwords given in the constructor '''
value = self.value_or_default(value)
if value is None: return None
if is_hashed(value):
return value
return make_password(value) | python | {
"resource": ""
} |
q50282 | Hash.validate | train | def validate(self, value, redis):
''' hash passwords given via http '''
value = super().validate(value, redis)
if is_hashed(value):
return value
return make_password(value) | python | {
"resource": ""
} |
q50283 | Datetime.validate | train | def validate(self, value, redis):
'''
Validates data obtained from a request in ISO 8061 and returns it in Datetime data type
'''
value = self.value_or_default(value)
self.validate_required(value)
if value is None:
return None
if type(value) == str... | python | {
"resource": ""
} |
q50284 | MultipleRelation.fill | train | def fill(self, **kwargs):
''' Loads the relationships into this model. They are not loaded by
default '''
setattr(self.obj, self.name, self.get(**kwargs)) | python | {
"resource": ""
} |
q50285 | MultipleRelation.get | train | def get(self, **kwargs):
''' Returns this relation '''
redis = type(self.obj).get_redis()
related = list(map(
lambda id : self.model().get(debyte_string(id)),
self.get_related_ids(redis, **kwargs)
))
return related | python | {
"resource": ""
} |
q50286 | _add_expansion_to_acronym_dict | train | def _add_expansion_to_acronym_dict(acronym, expansion, level, dictionary):
"""Add an acronym to the dictionary.
Takes care of avoiding duplicates and keeping the expansion marked with
the best score.
"""
if len(acronym) >= len(expansion) or acronym in expansion:
return
for punctuation ... | python | {
"resource": ""
} |
q50287 | _equivalent_expansions | train | def _equivalent_expansions(expansion1, expansion2):
"""Compare two expansions."""
words1 = _words(expansion1)
words2 = _words(expansion2)
simplified_versions = []
if words1 == words2:
return True
for words in (words1, words2):
store = []
for word in words:
... | python | {
"resource": ""
} |
q50288 | ClientAuthMethod._getAuth | train | def _getAuth(self):
"""
Main step in authorizing with Reader.
Sends request to Google ClientAuthMethod URL which returns an Auth token.
Returns Auth token or raises IOError on error.
"""
parameters = {
'service' : 'reader',
'Email' : sel... | python | {
"resource": ""
} |
q50289 | ClientAuthMethod._getToken | train | def _getToken(self):
"""
Second step in authorizing with Reader.
Sends authorized request to Reader token URL and returns a token value.
Returns token or raises IOError on error.
"""
headers = {'Authorization':'GoogleLogin auth=%s' % self.auth_token}
req = reques... | python | {
"resource": ""
} |
q50290 | GAPDecoratorAuthMethod._setupHttp | train | def _setupHttp(self):
"""
Setup an HTTP session authorized by OAuth2.
"""
if self._http == None:
http = httplib2.Http()
self._http = self._credentials.authorize(http) | python | {
"resource": ""
} |
q50291 | GAPDecoratorAuthMethod.get | train | def get(self, url, parameters=None):
"""
Implement libgreader's interface for authenticated GET request
"""
if self._http == None:
self._setupHttp()
uri = url + "?" + self.getParameters(parameters)
response, content = self._http.request(uri, "GET")
ret... | python | {
"resource": ""
} |
q50292 | GAPDecoratorAuthMethod.post | train | def post(self, url, postParameters=None, urlParameters=None):
"""
Implement libgreader's interface for authenticated POST request
"""
if self._action_token == None:
self._action_token = self.get(ReaderUrl.ACTION_TOKEN_URL)
if self._http == None:
self._set... | python | {
"resource": ""
} |
q50293 | Doxy2SWIG.generic_parse | train | def generic_parse(self, node, pad=0):
"""A Generic parser for arbitrary tags in a node.
Parameters:
- node: A node in the DOM.
- pad: `int` (default: 0)
If 0 the node data is not padded with newlines. If 1 it
appends a newline after parsing the childNodes. I... | python | {
"resource": ""
} |
q50294 | Doxy2SWIG.clean_pieces | train | def clean_pieces(self, pieces):
"""Cleans the list of strings given as `pieces`. It replaces
multiple newlines by a maximum of 2 and returns a new list.
It also wraps the paragraphs nicely.
"""
ret = []
count = 0
for i in pieces:
if i == '\n':
... | python | {
"resource": ""
} |
q50295 | http._format_json | train | def _format_json(self, ans, q):
"""
Generate a json response string.
"""
params = {}
try: params['indent'] = int(q.get('indent')[0])
except: pass
return json.dumps(ans, **params)+'\n' | python | {
"resource": ""
} |
q50296 | http._format | train | def _format(self, ans, q):
"""
Returns the response tuple according to the selected format.
A format is available if the method "_format_xxx" is callable.
The default format is json.
"""
if 'fmt' in q:
fmt = q['fmt'][0]
else:
fmt = 'json'
... | python | {
"resource": ""
} |
q50297 | http.version | train | def version(self, path, postmap=None, **params):
"""
Return the taskforce version.
Supports standard options.
"""
q = httpd.merge_query(path, postmap)
ans = {
'taskforce': taskforce_version,
'python': '.'.join(str(x) for x in sys.version_info[:3]),
... | python | {
"resource": ""
} |
q50298 | http.config | train | def config(self, path, postmap=None, **params):
"""
Return the running configuration which almost always matches the
configuration in the config file. During a reconfiguration, it may
be transitioning to the new state, in which case it will be different
to the pending config. N... | python | {
"resource": ""
} |
q50299 | http.tasks | train | def tasks(self, path, postmap=None, **params):
"""
Return the task status. This delves into the operating structures
and picks out information about tasks that is useful for status
monitoring.
For each task, the response includes:
control - The active task control ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.