repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
PMBio/limix-backup
limix/mtSet/core/preprocessCore.py
computePCsPlink
def computePCsPlink(plink_path,k,out_dir,bfile,ffile): """ computing the covariance matrix via plink """ print("Using plink to compute principal components") cmd = '%s --bfile %s --pca %d '%(plink_path,bfile,k) cmd+= '--out %s'%(os.path.join(out_dir,'plink')) subprocess.call(cmd,shell=True) ...
python
def computePCsPlink(plink_path,k,out_dir,bfile,ffile): """ computing the covariance matrix via plink """ print("Using plink to compute principal components") cmd = '%s --bfile %s --pca %d '%(plink_path,bfile,k) cmd+= '--out %s'%(os.path.join(out_dir,'plink')) subprocess.call(cmd,shell=True) ...
[ "def", "computePCsPlink", "(", "plink_path", ",", "k", ",", "out_dir", ",", "bfile", ",", "ffile", ")", ":", "print", "(", "\"Using plink to compute principal components\"", ")", "cmd", "=", "'%s --bfile %s --pca %d '", "%", "(", "plink_path", ",", "bfile", ",", ...
computing the covariance matrix via plink
[ "computing", "the", "covariance", "matrix", "via", "plink" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/preprocessCore.py#L56-L69
PMBio/limix-backup
limix/mtSet/core/preprocessCore.py
computePCsPython
def computePCsPython(out_dir,k,bfile,ffile): """ reading in """ RV = plink_reader.readBED(bfile,useMAFencoding=True) X = np.ascontiguousarray(RV['snps']) """ normalizing markers """ print('Normalizing SNPs...') p_ref = X.mean(axis=0)/2. X -= 2*p_ref with warnings.catch_warnings(): ...
python
def computePCsPython(out_dir,k,bfile,ffile): """ reading in """ RV = plink_reader.readBED(bfile,useMAFencoding=True) X = np.ascontiguousarray(RV['snps']) """ normalizing markers """ print('Normalizing SNPs...') p_ref = X.mean(axis=0)/2. X -= 2*p_ref with warnings.catch_warnings(): ...
[ "def", "computePCsPython", "(", "out_dir", ",", "k", ",", "bfile", ",", "ffile", ")", ":", "RV", "=", "plink_reader", ".", "readBED", "(", "bfile", ",", "useMAFencoding", "=", "True", ")", "X", "=", "np", ".", "ascontiguousarray", "(", "RV", "[", "'snp...
reading in
[ "reading", "in" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/preprocessCore.py#L73-L99
PMBio/limix-backup
limix/mtSet/core/preprocessCore.py
computeCovarianceMatrixPython
def computeCovarianceMatrixPython(out_dir,bfile,cfile,sim_type='RRM'): print("Using python to create covariance matrix. This might be slow. We recommend using plink instead.") if sim_type is not 'RRM': raise Exception('sim_type %s is not known'%sim_type) """ loading data """ data = plink_reade...
python
def computeCovarianceMatrixPython(out_dir,bfile,cfile,sim_type='RRM'): print("Using python to create covariance matrix. This might be slow. We recommend using plink instead.") if sim_type is not 'RRM': raise Exception('sim_type %s is not known'%sim_type) """ loading data """ data = plink_reade...
[ "def", "computeCovarianceMatrixPython", "(", "out_dir", ",", "bfile", ",", "cfile", ",", "sim_type", "=", "'RRM'", ")", ":", "print", "(", "\"Using python to create covariance matrix. This might be slow. We recommend using plink instead.\"", ")", "if", "sim_type", "is", "no...
loading data
[ "loading", "data" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/preprocessCore.py#L103-L139
PMBio/limix-backup
limix/mtSet/core/preprocessCore.py
computePCs
def computePCs(plink_path,k,bfile,ffile): """ compute the first k principal components Input: k : number of principal components plink_path : plink path bfile : binary bed file (bfile.bed, bfile.bim and bfile.fam are required) ffile : name of output file ...
python
def computePCs(plink_path,k,bfile,ffile): """ compute the first k principal components Input: k : number of principal components plink_path : plink path bfile : binary bed file (bfile.bed, bfile.bim and bfile.fam are required) ffile : name of output file ...
[ "def", "computePCs", "(", "plink_path", ",", "k", ",", "bfile", ",", "ffile", ")", ":", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "'%s --version --noweb'", "%", "plink_path", ",", "shell", "=", "True", ")", "use_plink", "=", "float...
compute the first k principal components Input: k : number of principal components plink_path : plink path bfile : binary bed file (bfile.bed, bfile.bim and bfile.fam are required) ffile : name of output file
[ "compute", "the", "first", "k", "principal", "components" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/preprocessCore.py#L144-L174
PMBio/limix-backup
limix/mtSet/core/preprocessCore.py
computeCovarianceMatrix
def computeCovarianceMatrix(plink_path,bfile,cfile,sim_type='RRM'): """ compute similarity matrix using plink Input: plink_path : plink path bfile : binary bed file (bfile.bed, bfile.bim and bfile.fam are required) cfile : the covariance matrix will be written to cfile.cov...
python
def computeCovarianceMatrix(plink_path,bfile,cfile,sim_type='RRM'): """ compute similarity matrix using plink Input: plink_path : plink path bfile : binary bed file (bfile.bed, bfile.bim and bfile.fam are required) cfile : the covariance matrix will be written to cfile.cov...
[ "def", "computeCovarianceMatrix", "(", "plink_path", ",", "bfile", ",", "cfile", ",", "sim_type", "=", "'RRM'", ")", ":", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "'%s --version --noweb'", "%", "plink_path", ",", "shell", "=", "True",...
compute similarity matrix using plink Input: plink_path : plink path bfile : binary bed file (bfile.bed, bfile.bim and bfile.fam are required) cfile : the covariance matrix will be written to cfile.cov and the corresponding identifiers to cfile.cov.id. If ...
[ "compute", "similarity", "matrix", "using", "plink" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/preprocessCore.py#L190-L226
PMBio/limix-backup
limix/mtSet/core/preprocessCore.py
eighCovarianceMatrix
def eighCovarianceMatrix(cfile): """ compute similarity matrix using plink Input: cfile : the covariance matrix will be read from cfile.cov while the eigenvalues and the eigenverctors will be written to cfile.cov.eval and cfile.cov.evec respectively """ # precom...
python
def eighCovarianceMatrix(cfile): """ compute similarity matrix using plink Input: cfile : the covariance matrix will be read from cfile.cov while the eigenvalues and the eigenverctors will be written to cfile.cov.eval and cfile.cov.evec respectively """ # precom...
[ "def", "eighCovarianceMatrix", "(", "cfile", ")", ":", "# precompute eigenvalue decomposition", "K", "=", "np", ".", "loadtxt", "(", "cfile", "+", "'.cov'", ")", "K", "+=", "1e-4", "*", "sp", ".", "eye", "(", "K", ".", "shape", "[", "0", "]", ")", "S",...
compute similarity matrix using plink Input: cfile : the covariance matrix will be read from cfile.cov while the eigenvalues and the eigenverctors will be written to cfile.cov.eval and cfile.cov.evec respectively
[ "compute", "similarity", "matrix", "using", "plink" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/preprocessCore.py#L228-L241
PMBio/limix-backup
limix/mtSet/core/preprocessCore.py
fit_null
def fit_null(Y,S_XX,U_XX,nfile,F): """ fit null model Y NxP phenotype matrix S_XX eigenvalues of the relatedness matrix U_XX eigen vectors of the relatedness matrix """ mtSet = limix.MTSet(Y, S_R=S_XX, U_R=U_XX, F=F) RV = mtSet.fitNull(cache=False) params = np.array([RV...
python
def fit_null(Y,S_XX,U_XX,nfile,F): """ fit null model Y NxP phenotype matrix S_XX eigenvalues of the relatedness matrix U_XX eigen vectors of the relatedness matrix """ mtSet = limix.MTSet(Y, S_R=S_XX, U_R=U_XX, F=F) RV = mtSet.fitNull(cache=False) params = np.array([RV...
[ "def", "fit_null", "(", "Y", ",", "S_XX", ",", "U_XX", ",", "nfile", ",", "F", ")", ":", "mtSet", "=", "limix", ".", "MTSet", "(", "Y", ",", "S_R", "=", "S_XX", ",", "U_R", "=", "U_XX", ",", "F", "=", "F", ")", "RV", "=", "mtSet", ".", "fit...
fit null model Y NxP phenotype matrix S_XX eigenvalues of the relatedness matrix U_XX eigen vectors of the relatedness matrix
[ "fit", "null", "model" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/preprocessCore.py#L244-L259
PMBio/limix-backup
limix/mtSet/core/preprocessCore.py
preprocess
def preprocess(options): assert options.bfile!=None, 'Please specify a bfile.' """ computing the covariance matrix """ if options.compute_cov: assert options.bfile!=None, 'Please specify a bfile.' assert options.cfile is not None, 'Specify covariance matrix basename' print('Computing ...
python
def preprocess(options): assert options.bfile!=None, 'Please specify a bfile.' """ computing the covariance matrix """ if options.compute_cov: assert options.bfile!=None, 'Please specify a bfile.' assert options.cfile is not None, 'Specify covariance matrix basename' print('Computing ...
[ "def", "preprocess", "(", "options", ")", ":", "assert", "options", ".", "bfile", "!=", "None", ",", "'Please specify a bfile.'", "if", "options", ".", "compute_cov", ":", "assert", "options", ".", "bfile", "!=", "None", ",", "'Please specify a bfile.'", "assert...
computing the covariance matrix
[ "computing", "the", "covariance", "matrix" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/preprocessCore.py#L263-L340
bretth/woven
bin/woven-admin.py
copy_helper
def copy_helper(app_or_project, name, directory, dist, template_dir, noadmin): """ Replacement for django copy_helper Copies a Django project layout template into the specified distribution directory """ import shutil if not re.search(r'^[_a-zA-Z]\w*$', name): # If it's not a valid direct...
python
def copy_helper(app_or_project, name, directory, dist, template_dir, noadmin): """ Replacement for django copy_helper Copies a Django project layout template into the specified distribution directory """ import shutil if not re.search(r'^[_a-zA-Z]\w*$', name): # If it's not a valid direct...
[ "def", "copy_helper", "(", "app_or_project", ",", "name", ",", "directory", ",", "dist", ",", "template_dir", ",", "noadmin", ")", ":", "import", "shutil", "if", "not", "re", ".", "search", "(", "r'^[_a-zA-Z]\\w*$'", ",", "name", ")", ":", "# If it's not a v...
Replacement for django copy_helper Copies a Django project layout template into the specified distribution directory
[ "Replacement", "for", "django", "copy_helper", "Copies", "a", "Django", "project", "layout", "template", "into", "the", "specified", "distribution", "directory" ]
train
https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/bin/woven-admin.py#L22-L70
bretth/woven
bin/woven-admin.py
start_distribution
def start_distribution(project_name, template_dir, dist, noadmin): """ Custom startproject command to override django default """ directory = os.getcwd() # Check that the project_name cannot be imported. try: import_module(project_name) except ImportError: pass else: ...
python
def start_distribution(project_name, template_dir, dist, noadmin): """ Custom startproject command to override django default """ directory = os.getcwd() # Check that the project_name cannot be imported. try: import_module(project_name) except ImportError: pass else: ...
[ "def", "start_distribution", "(", "project_name", ",", "template_dir", ",", "dist", ",", "noadmin", ")", ":", "directory", "=", "os", ".", "getcwd", "(", ")", "# Check that the project_name cannot be imported.", "try", ":", "import_module", "(", "project_name", ")",...
Custom startproject command to override django default
[ "Custom", "startproject", "command", "to", "override", "django", "default" ]
train
https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/bin/woven-admin.py#L73-L114
PMBio/limix-backup
limix/deprecated/utils/preprocess.py
variance_K
def variance_K(K, verbose=False): """estimate the variance explained by K""" c = SP.sum((SP.eye(len(K)) - (1.0 / len(K)) * SP.ones(K.shape)) * SP.array(K)) scalar = (len(K) - 1) / c return 1.0/scalar
python
def variance_K(K, verbose=False): """estimate the variance explained by K""" c = SP.sum((SP.eye(len(K)) - (1.0 / len(K)) * SP.ones(K.shape)) * SP.array(K)) scalar = (len(K) - 1) / c return 1.0/scalar
[ "def", "variance_K", "(", "K", ",", "verbose", "=", "False", ")", ":", "c", "=", "SP", ".", "sum", "(", "(", "SP", ".", "eye", "(", "len", "(", "K", ")", ")", "-", "(", "1.0", "/", "len", "(", "K", ")", ")", "*", "SP", ".", "ones", "(", ...
estimate the variance explained by K
[ "estimate", "the", "variance", "explained", "by", "K" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/utils/preprocess.py#L22-L26
PMBio/limix-backup
limix/deprecated/utils/preprocess.py
scale_K
def scale_K(K, verbose=False,trace_method=True): """scale covariance K such that it explains unit variance trace_method: standardize to unit trace (deafault: True) """ if trace_method: scalar=1.0/(K.diagonal().mean()) else: c = SP.sum((SP.eye(len(K)) - (1.0 / len(K)) * SP.ones(K.shap...
python
def scale_K(K, verbose=False,trace_method=True): """scale covariance K such that it explains unit variance trace_method: standardize to unit trace (deafault: True) """ if trace_method: scalar=1.0/(K.diagonal().mean()) else: c = SP.sum((SP.eye(len(K)) - (1.0 / len(K)) * SP.ones(K.shap...
[ "def", "scale_K", "(", "K", ",", "verbose", "=", "False", ",", "trace_method", "=", "True", ")", ":", "if", "trace_method", ":", "scalar", "=", "1.0", "/", "(", "K", ".", "diagonal", "(", ")", ".", "mean", "(", ")", ")", "else", ":", "c", "=", ...
scale covariance K such that it explains unit variance trace_method: standardize to unit trace (deafault: True)
[ "scale", "covariance", "K", "such", "that", "it", "explains", "unit", "variance", "trace_method", ":", "standardize", "to", "unit", "trace", "(", "deafault", ":", "True", ")" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/utils/preprocess.py#L29-L41
PMBio/limix-backup
limix/deprecated/utils/preprocess.py
rankStandardizeNormal
def rankStandardizeNormal(X): """ Gaussianize X: [samples x phenotypes] - each phentoype is converted to ranks and transformed back to normal using the inverse CDF """ Is = X.argsort(axis=0) RV = SP.zeros_like(X) rank = SP.zeros_like(X) for i in range(X.shape[1]): x = X[:,i] i_nan = SP.isnan(x) if 0: ...
python
def rankStandardizeNormal(X): """ Gaussianize X: [samples x phenotypes] - each phentoype is converted to ranks and transformed back to normal using the inverse CDF """ Is = X.argsort(axis=0) RV = SP.zeros_like(X) rank = SP.zeros_like(X) for i in range(X.shape[1]): x = X[:,i] i_nan = SP.isnan(x) if 0: ...
[ "def", "rankStandardizeNormal", "(", "X", ")", ":", "Is", "=", "X", ".", "argsort", "(", "axis", "=", "0", ")", "RV", "=", "SP", ".", "zeros_like", "(", "X", ")", "rank", "=", "SP", ".", "zeros_like", "(", "X", ")", "for", "i", "in", "range", "...
Gaussianize X: [samples x phenotypes] - each phentoype is converted to ranks and transformed back to normal using the inverse CDF
[ "Gaussianize", "X", ":", "[", "samples", "x", "phenotypes", "]", "-", "each", "phentoype", "is", "converted", "to", "ranks", "and", "transformed", "back", "to", "normal", "using", "the", "inverse", "CDF" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/utils/preprocess.py#L62-L86
heuer/cablemap
helpers/fix_subjects.py
_aftenposten_cable_ids
def _aftenposten_cable_ids(): """\ Returns a set of cable identifiers of cables published by Aftenposten. See: <http://aebr.home.xs4all.nl/wl/aftenposten/> """ s = urllib2.urlopen(_AP_IRI).read() return set(_WL_CABLE_ID_PATTERN.findall(s))
python
def _aftenposten_cable_ids(): """\ Returns a set of cable identifiers of cables published by Aftenposten. See: <http://aebr.home.xs4all.nl/wl/aftenposten/> """ s = urllib2.urlopen(_AP_IRI).read() return set(_WL_CABLE_ID_PATTERN.findall(s))
[ "def", "_aftenposten_cable_ids", "(", ")", ":", "s", "=", "urllib2", ".", "urlopen", "(", "_AP_IRI", ")", ".", "read", "(", ")", "return", "set", "(", "_WL_CABLE_ID_PATTERN", ".", "findall", "(", "s", ")", ")" ]
\ Returns a set of cable identifiers of cables published by Aftenposten. See: <http://aebr.home.xs4all.nl/wl/aftenposten/>
[ "\\", "Returns", "a", "set", "of", "cable", "identifiers", "of", "cables", "published", "by", "Aftenposten", ".", "See", ":", "<http", ":", "//", "aebr", ".", "home", ".", "xs4all", ".", "nl", "/", "wl", "/", "aftenposten", "/", ">" ]
train
https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/helpers/fix_subjects.py#L48-L54
heuer/cablemap
helpers/fix_subjects.py
_russianreporter_cable_ids
def _russianreporter_cable_ids(): """\ Returns a set of cable identifiers of cables published by Russian Reporter. See <http://aebr.home.xs4all.nl/wl/rusrep/> """ s = urllib2.urlopen(_RR_IRI).read() return set(_WL_CABLE_ID_PATTERN.findall(s))
python
def _russianreporter_cable_ids(): """\ Returns a set of cable identifiers of cables published by Russian Reporter. See <http://aebr.home.xs4all.nl/wl/rusrep/> """ s = urllib2.urlopen(_RR_IRI).read() return set(_WL_CABLE_ID_PATTERN.findall(s))
[ "def", "_russianreporter_cable_ids", "(", ")", ":", "s", "=", "urllib2", ".", "urlopen", "(", "_RR_IRI", ")", ".", "read", "(", ")", "return", "set", "(", "_WL_CABLE_ID_PATTERN", ".", "findall", "(", "s", ")", ")" ]
\ Returns a set of cable identifiers of cables published by Russian Reporter. See <http://aebr.home.xs4all.nl/wl/rusrep/>
[ "\\", "Returns", "a", "set", "of", "cable", "identifiers", "of", "cables", "published", "by", "Russian", "Reporter", ".", "See", "<http", ":", "//", "aebr", ".", "home", ".", "xs4all", ".", "nl", "/", "wl", "/", "rusrep", "/", ">" ]
train
https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/helpers/fix_subjects.py#L56-L62
rjw57/starman
starman/util.py
as_square_array
def as_square_array(arr): """Return arr massaged into a square array. Raises ValueError if arr cannot be so massaged. """ arr = np.atleast_2d(arr) if len(arr.shape) != 2 or arr.shape[0] != arr.shape[1]: raise ValueError("Expected square array") return arr
python
def as_square_array(arr): """Return arr massaged into a square array. Raises ValueError if arr cannot be so massaged. """ arr = np.atleast_2d(arr) if len(arr.shape) != 2 or arr.shape[0] != arr.shape[1]: raise ValueError("Expected square array") return arr
[ "def", "as_square_array", "(", "arr", ")", ":", "arr", "=", "np", ".", "atleast_2d", "(", "arr", ")", "if", "len", "(", "arr", ".", "shape", ")", "!=", "2", "or", "arr", ".", "shape", "[", "0", "]", "!=", "arr", ".", "shape", "[", "1", "]", "...
Return arr massaged into a square array. Raises ValueError if arr cannot be so massaged.
[ "Return", "arr", "massaged", "into", "a", "square", "array", ".", "Raises", "ValueError", "if", "arr", "cannot", "be", "so", "massaged", "." ]
train
https://github.com/rjw57/starman/blob/1f9475e2354c9630a61f4898ad871de1d2fdbc71/starman/util.py#L7-L15
PMBio/limix-backup
limix/mtSet/core/postprocessCore.py
postprocess
def postprocess(options): """ perform parametric fit of the test statistics and provide permutation and test pvalues """ resdir = options.resdir out_file = options.outfile tol = options.tol print('.. load permutation results') file_name = os.path.join(resdir,'perm*','*.res') files = glob.g...
python
def postprocess(options): """ perform parametric fit of the test statistics and provide permutation and test pvalues """ resdir = options.resdir out_file = options.outfile tol = options.tol print('.. load permutation results') file_name = os.path.join(resdir,'perm*','*.res') files = glob.g...
[ "def", "postprocess", "(", "options", ")", ":", "resdir", "=", "options", ".", "resdir", "out_file", "=", "options", ".", "outfile", "tol", "=", "options", ".", "tol", "print", "(", "'.. load permutation results'", ")", "file_name", "=", "os", ".", "path", ...
perform parametric fit of the test statistics and provide permutation and test pvalues
[ "perform", "parametric", "fit", "of", "the", "test", "statistics", "and", "provide", "permutation", "and", "test", "pvalues" ]
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/postprocessCore.py#L24-L72
carljm/django-icanhaz
icanhaz/templatetags/icanhaz.py
icanhaz
def icanhaz(parser, token): """ Finds the ICanHaz template for the given name and renders it surrounded by the requisite ICanHaz <script> tags. """ bits = token.contents.split() if len(bits) not in [2, 3]: raise template.TemplateSyntaxError( "'icanhaz' tag takes one argument...
python
def icanhaz(parser, token): """ Finds the ICanHaz template for the given name and renders it surrounded by the requisite ICanHaz <script> tags. """ bits = token.contents.split() if len(bits) not in [2, 3]: raise template.TemplateSyntaxError( "'icanhaz' tag takes one argument...
[ "def", "icanhaz", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "bits", ")", "not", "in", "[", "2", ",", "3", "]", ":", "raise", "template", ".", "TemplateSyntaxError", "(", ...
Finds the ICanHaz template for the given name and renders it surrounded by the requisite ICanHaz <script> tags.
[ "Finds", "the", "ICanHaz", "template", "for", "the", "given", "name", "and", "renders", "it", "surrounded", "by", "the", "requisite", "ICanHaz", "<script", ">", "tags", "." ]
train
https://github.com/carljm/django-icanhaz/blob/57939325850058959c1ee8dce13e2b8c28156532/icanhaz/templatetags/icanhaz.py#L40-L50
inveniosoftware-contrib/invenio-classifier
invenio_classifier/api.py
output_keywords_for_sources
def output_keywords_for_sources( input_sources, taxonomy_name, output_mode="text", output_limit=None, spires=False, match_mode="full", no_cache=False, with_author_keywords=False, rebuild_cache=False, only_core_tags=False, extract_acronyms=False, **kwargs): """Output the keywo...
python
def output_keywords_for_sources( input_sources, taxonomy_name, output_mode="text", output_limit=None, spires=False, match_mode="full", no_cache=False, with_author_keywords=False, rebuild_cache=False, only_core_tags=False, extract_acronyms=False, **kwargs): """Output the keywo...
[ "def", "output_keywords_for_sources", "(", "input_sources", ",", "taxonomy_name", ",", "output_mode", "=", "\"text\"", ",", "output_limit", "=", "None", ",", "spires", "=", "False", ",", "match_mode", "=", "\"full\"", ",", "no_cache", "=", "False", ",", "with_au...
Output the keywords for each source in sources.
[ "Output", "the", "keywords", "for", "each", "source", "in", "sources", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/api.py#L38-L106
inveniosoftware-contrib/invenio-classifier
invenio_classifier/api.py
get_keywords_from_local_file
def get_keywords_from_local_file( local_file, taxonomy_name, output_mode="text", output_limit=None, spires=False, match_mode="full", no_cache=False, with_author_keywords=False, rebuild_cache=False, only_core_tags=False, extract_acronyms=False): """Output keywords reading a local file...
python
def get_keywords_from_local_file( local_file, taxonomy_name, output_mode="text", output_limit=None, spires=False, match_mode="full", no_cache=False, with_author_keywords=False, rebuild_cache=False, only_core_tags=False, extract_acronyms=False): """Output keywords reading a local file...
[ "def", "get_keywords_from_local_file", "(", "local_file", ",", "taxonomy_name", ",", "output_mode", "=", "\"text\"", ",", "output_limit", "=", "None", ",", "spires", "=", "False", ",", "match_mode", "=", "\"full\"", ",", "no_cache", "=", "False", ",", "with_auth...
Output keywords reading a local file. Arguments and output are the same as for :see: get_keywords_from_text().
[ "Output", "keywords", "reading", "a", "local", "file", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/api.py#L109-L135
inveniosoftware-contrib/invenio-classifier
invenio_classifier/api.py
get_keywords_from_text
def get_keywords_from_text(text_lines, taxonomy_name, output_mode="text", output_limit=None, spires=False, match_mode="full", no_cache=False, with_author_keywords=False, rebuild_cache=False, only_core_tags=False,...
python
def get_keywords_from_text(text_lines, taxonomy_name, output_mode="text", output_limit=None, spires=False, match_mode="full", no_cache=False, with_author_keywords=False, rebuild_cache=False, only_core_tags=False,...
[ "def", "get_keywords_from_text", "(", "text_lines", ",", "taxonomy_name", ",", "output_mode", "=", "\"text\"", ",", "output_limit", "=", "None", ",", "spires", "=", "False", ",", "match_mode", "=", "\"full\"", ",", "no_cache", "=", "False", ",", "with_author_key...
Extract keywords from the list of strings. :param text_lines: list of strings (will be normalized before being joined into one string) :param taxonomy_name: string, name of the taxonomy_name :param output_mode: string - text|html|marcxml|raw :param output_limit: int :param spires: boolean, ...
[ "Extract", "keywords", "from", "the", "list", "of", "strings", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/api.py#L138-L207
timofurrer/tag-expressions
tagexpressions/parser.py
parse
def parse(infix): """Parse the given infix string to an expression which can be evaluated. Known operators are: * or * and * not With the following precedences (from high to low): * not * and * or * ) * ( :param str infix: the input str...
python
def parse(infix): """Parse the given infix string to an expression which can be evaluated. Known operators are: * or * and * not With the following precedences (from high to low): * not * and * or * ) * ( :param str infix: the input str...
[ "def", "parse", "(", "infix", ")", ":", "tokens", "=", "infix", ".", "replace", "(", "'('", ",", "' ( '", ")", ".", "replace", "(", "')'", ",", "' ) '", ")", ".", "strip", "(", ")", ".", "split", "(", ")", "#: Holds the parsed operations", "ops", "="...
Parse the given infix string to an expression which can be evaluated. Known operators are: * or * and * not With the following precedences (from high to low): * not * and * or * ) * ( :param str infix: the input string expression :retu...
[ "Parse", "the", "given", "infix", "string", "to", "an", "expression", "which", "can", "be", "evaluated", "." ]
train
https://github.com/timofurrer/tag-expressions/blob/9b58c34296b31530f31517ffefc8715516c73da3/tagexpressions/parser.py#L26-L84
timofurrer/tag-expressions
tagexpressions/parser.py
create_and_push_expression
def create_and_push_expression(token, expressions): """Creates an expression from the given token and adds it to the stack of the given expression. In the case of "and" and "or" expressions the last expression is poped from the expression stack to link it to the new created one. """ if toke...
python
def create_and_push_expression(token, expressions): """Creates an expression from the given token and adds it to the stack of the given expression. In the case of "and" and "or" expressions the last expression is poped from the expression stack to link it to the new created one. """ if toke...
[ "def", "create_and_push_expression", "(", "token", ",", "expressions", ")", ":", "if", "token", "==", "'and'", ":", "right_expr", "=", "expressions", ".", "pop", "(", ")", "expressions", ".", "append", "(", "And", "(", "expressions", ".", "pop", "(", ")", ...
Creates an expression from the given token and adds it to the stack of the given expression. In the case of "and" and "or" expressions the last expression is poped from the expression stack to link it to the new created one.
[ "Creates", "an", "expression", "from", "the", "given", "token", "and", "adds", "it", "to", "the", "stack", "of", "the", "given", "expression", "." ]
train
https://github.com/timofurrer/tag-expressions/blob/9b58c34296b31530f31517ffefc8715516c73da3/tagexpressions/parser.py#L101-L118
StyXman/ayrton
ayrton/parser/astcompiler/misc.py
dict_to_switch
def dict_to_switch(d): """Convert of dictionary with integer keys to a switch statement.""" def lookup(query): return d[query] lookup._always_inline_ = True unrolling_items = unrolling_iterable(d.items()) return lookup
python
def dict_to_switch(d): """Convert of dictionary with integer keys to a switch statement.""" def lookup(query): return d[query] lookup._always_inline_ = True unrolling_items = unrolling_iterable(d.items()) return lookup
[ "def", "dict_to_switch", "(", "d", ")", ":", "def", "lookup", "(", "query", ")", ":", "return", "d", "[", "query", "]", "lookup", ".", "_always_inline_", "=", "True", "unrolling_items", "=", "unrolling_iterable", "(", "d", ".", "items", "(", ")", ")", ...
Convert of dictionary with integer keys to a switch statement.
[ "Convert", "of", "dictionary", "with", "integer", "keys", "to", "a", "switch", "statement", "." ]
train
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/astcompiler/misc.py#L79-L85
jhshi/wltrace
wltrace/dot11.py
mcs_to_rate
def mcs_to_rate(mcs, bw=20, long_gi=True): """Convert MCS index to rate in Mbps. See http://mcsindex.com/ Args: mcs (int): MCS index bw (int): bandwidth, 20, 40, 80, ... long_gi(bool): True if long GI is used. Returns: rate (float): bitrate in Mbps >>> mcs_to_rat...
python
def mcs_to_rate(mcs, bw=20, long_gi=True): """Convert MCS index to rate in Mbps. See http://mcsindex.com/ Args: mcs (int): MCS index bw (int): bandwidth, 20, 40, 80, ... long_gi(bool): True if long GI is used. Returns: rate (float): bitrate in Mbps >>> mcs_to_rat...
[ "def", "mcs_to_rate", "(", "mcs", ",", "bw", "=", "20", ",", "long_gi", "=", "True", ")", ":", "if", "bw", "not", "in", "[", "20", ",", "40", ",", "80", ",", "160", "]", ":", "raise", "Exception", "(", "\"Unknown bandwidth: %d MHz\"", "%", "(", "bw...
Convert MCS index to rate in Mbps. See http://mcsindex.com/ Args: mcs (int): MCS index bw (int): bandwidth, 20, 40, 80, ... long_gi(bool): True if long GI is used. Returns: rate (float): bitrate in Mbps >>> mcs_to_rate(5, bw=20, long_gi=False) 57.8 >>> mcs_t...
[ "Convert", "MCS", "index", "to", "rate", "in", "Mbps", "." ]
train
https://github.com/jhshi/wltrace/blob/4c8441162f7cddd47375da2effc52c95b97dc81d/wltrace/dot11.py#L141-L175
jhshi/wltrace
wltrace/dot11.py
rate_to_mcs
def rate_to_mcs(rate, bw=20, long_gi=True): """Convert bit rate to MCS index. Args: rate (float): bit rate in Mbps bw (int): bandwidth, 20, 40, 80, ... long_gi (bool): True if long GI is used. Returns: mcs (int): MCS index >>> rate_to_mcs(120, bw=40, long_gi=False) ...
python
def rate_to_mcs(rate, bw=20, long_gi=True): """Convert bit rate to MCS index. Args: rate (float): bit rate in Mbps bw (int): bandwidth, 20, 40, 80, ... long_gi (bool): True if long GI is used. Returns: mcs (int): MCS index >>> rate_to_mcs(120, bw=40, long_gi=False) ...
[ "def", "rate_to_mcs", "(", "rate", ",", "bw", "=", "20", ",", "long_gi", "=", "True", ")", ":", "if", "bw", "not", "in", "[", "20", ",", "40", ",", "80", ",", "160", "]", ":", "raise", "Exception", "(", "\"Unknown bandwidth: %d MHz\"", "%", "(", "b...
Convert bit rate to MCS index. Args: rate (float): bit rate in Mbps bw (int): bandwidth, 20, 40, 80, ... long_gi (bool): True if long GI is used. Returns: mcs (int): MCS index >>> rate_to_mcs(120, bw=40, long_gi=False) 5
[ "Convert", "bit", "rate", "to", "MCS", "index", "." ]
train
https://github.com/jhshi/wltrace/blob/4c8441162f7cddd47375da2effc52c95b97dc81d/wltrace/dot11.py#L178-L208
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
extract_abbreviations
def extract_abbreviations(fulltext): """Extract acronyms from the fulltext. :param fulltext: utf-8 string :return: dictionary of matches in a formt { <keyword object>, [matched skw or ckw object, ....] } or empty {} """ acronyms = {} for k, v in get_acronyms(fullte...
python
def extract_abbreviations(fulltext): """Extract acronyms from the fulltext. :param fulltext: utf-8 string :return: dictionary of matches in a formt { <keyword object>, [matched skw or ckw object, ....] } or empty {} """ acronyms = {} for k, v in get_acronyms(fullte...
[ "def", "extract_abbreviations", "(", "fulltext", ")", ":", "acronyms", "=", "{", "}", "for", "k", ",", "v", "in", "get_acronyms", "(", "fulltext", ")", ".", "items", "(", ")", ":", "acronyms", "[", "KeywordToken", "(", "k", ",", "type", "=", "'acronym'...
Extract acronyms from the fulltext. :param fulltext: utf-8 string :return: dictionary of matches in a formt { <keyword object>, [matched skw or ckw object, ....] } or empty {}
[ "Extract", "acronyms", "from", "the", "fulltext", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L72-L84
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
extract_author_keywords
def extract_author_keywords(skw_db, ckw_db, fulltext): """Find out human defined keywords in a text string. Searches for the string "Keywords:" and its declinations and matches the following words. :param skw_db: list single kw object :param ckw_db: list of composite kw objects :param fulltext...
python
def extract_author_keywords(skw_db, ckw_db, fulltext): """Find out human defined keywords in a text string. Searches for the string "Keywords:" and its declinations and matches the following words. :param skw_db: list single kw object :param ckw_db: list of composite kw objects :param fulltext...
[ "def", "extract_author_keywords", "(", "skw_db", ",", "ckw_db", ",", "fulltext", ")", ":", "akw", "=", "{", "}", "for", "k", ",", "v", "in", "get_author_keywords", "(", "skw_db", ",", "ckw_db", ",", "fulltext", ")", ".", "items", "(", ")", ":", "akw", ...
Find out human defined keywords in a text string. Searches for the string "Keywords:" and its declinations and matches the following words. :param skw_db: list single kw object :param ckw_db: list of composite kw objects :param fulltext: utf-8 string :return: dictionary of matches in a formt {...
[ "Find", "out", "human", "defined", "keywords", "in", "a", "text", "string", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L87-L104
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
get_keywords_output
def get_keywords_output(single_keywords, composite_keywords, taxonomy_name, author_keywords=None, acronyms=None, output_mode="text", output_limit=0, spires=False, only_core_tags=False): """Return a formatted string representing the keywords in ...
python
def get_keywords_output(single_keywords, composite_keywords, taxonomy_name, author_keywords=None, acronyms=None, output_mode="text", output_limit=0, spires=False, only_core_tags=False): """Return a formatted string representing the keywords in ...
[ "def", "get_keywords_output", "(", "single_keywords", ",", "composite_keywords", ",", "taxonomy_name", ",", "author_keywords", "=", "None", ",", "acronyms", "=", "None", ",", "output_mode", "=", "\"text\"", ",", "output_limit", "=", "0", ",", "spires", "=", "Fal...
Return a formatted string representing the keywords in the chosen style. This is the main routing call, this function will also strip unwanted keywords before output and limits the number of returned keywords. :param single_keywords: list of single keywords :param composite_keywords: list of compo...
[ "Return", "a", "formatted", "string", "representing", "the", "keywords", "in", "the", "chosen", "style", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L107-L164
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
build_marc
def build_marc(recid, single_keywords, composite_keywords, spires=False, author_keywords=None, acronyms=None): """Create xml record. :var recid: integer :var single_keywords: dictionary of kws :var composite_keywords: dictionary of kws :keyword spires: please don't use, left for hist...
python
def build_marc(recid, single_keywords, composite_keywords, spires=False, author_keywords=None, acronyms=None): """Create xml record. :var recid: integer :var single_keywords: dictionary of kws :var composite_keywords: dictionary of kws :keyword spires: please don't use, left for hist...
[ "def", "build_marc", "(", "recid", ",", "single_keywords", ",", "composite_keywords", ",", "spires", "=", "False", ",", "author_keywords", "=", "None", ",", "acronyms", "=", "None", ")", ":", "output", "=", "[", "'<collection><record>\\n'", "'<controlfield tag=\"0...
Create xml record. :var recid: integer :var single_keywords: dictionary of kws :var composite_keywords: dictionary of kws :keyword spires: please don't use, left for historical reasons :keyword author_keywords: dictionary of extracted keywords :keyword acronyms: dictionary of extracted ...
[ "Create", "xml", "record", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L167-L196
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
_output_marc
def _output_marc(output_complete, categories, kw_field=None, auth_field=None, acro_field=None, provenience='Classifier'): """Output the keywords in the MARCXML format. :var skw_matches: list of single keywords :var ckw_matches: list of com...
python
def _output_marc(output_complete, categories, kw_field=None, auth_field=None, acro_field=None, provenience='Classifier'): """Output the keywords in the MARCXML format. :var skw_matches: list of single keywords :var ckw_matches: list of com...
[ "def", "_output_marc", "(", "output_complete", ",", "categories", ",", "kw_field", "=", "None", ",", "auth_field", "=", "None", ",", "acro_field", "=", "None", ",", "provenience", "=", "'Classifier'", ")", ":", "if", "kw_field", "is", "None", ":", "kw_field"...
Output the keywords in the MARCXML format. :var skw_matches: list of single keywords :var ckw_matches: list of composite keywords :var author_keywords: dictionary of extracted author keywords :var acronyms: dictionary of acronyms :var spires: boolean, True=generate spires output - BUT NOTE: it is ...
[ "Output", "the", "keywords", "in", "the", "MARCXML", "format", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L199-L263
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
_output_text
def _output_text(complete_output, categories): """Output the results obtained in text format. :return: str, html formatted output """ output = "" for result in complete_output: list_result = complete_output[result] if list_result: list_result_sorted = sorted(list_result...
python
def _output_text(complete_output, categories): """Output the results obtained in text format. :return: str, html formatted output """ output = "" for result in complete_output: list_result = complete_output[result] if list_result: list_result_sorted = sorted(list_result...
[ "def", "_output_text", "(", "complete_output", ",", "categories", ")", ":", "output", "=", "\"\"", "for", "result", "in", "complete_output", ":", "list_result", "=", "complete_output", "[", "result", "]", "if", "list_result", ":", "list_result_sorted", "=", "sor...
Output the results obtained in text format. :return: str, html formatted output
[ "Output", "the", "results", "obtained", "in", "text", "format", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L302-L321
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
_get_singlekws
def _get_singlekws(skw_matches, spires=False): """Get single keywords. :var skw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted keywords """ output = {} for single_keyword, info in skw_matches: output[single_keyword.o...
python
def _get_singlekws(skw_matches, spires=False): """Get single keywords. :var skw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted keywords """ output = {} for single_keyword, info in skw_matches: output[single_keyword.o...
[ "def", "_get_singlekws", "(", "skw_matches", ",", "spires", "=", "False", ")", ":", "output", "=", "{", "}", "for", "single_keyword", ",", "info", "in", "skw_matches", ":", "output", "[", "single_keyword", ".", "output", "(", "spires", ")", "]", "=", "le...
Get single keywords. :var skw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted keywords
[ "Get", "single", "keywords", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L348-L360
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
_get_compositekws
def _get_compositekws(ckw_matches, spires=False): """Get composite keywords. :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted keywords """ output = {} for composite_keyword, info in ckw_matches: output[composi...
python
def _get_compositekws(ckw_matches, spires=False): """Get composite keywords. :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted keywords """ output = {} for composite_keyword, info in ckw_matches: output[composi...
[ "def", "_get_compositekws", "(", "ckw_matches", ",", "spires", "=", "False", ")", ":", "output", "=", "{", "}", "for", "composite_keyword", ",", "info", "in", "ckw_matches", ":", "output", "[", "composite_keyword", ".", "output", "(", "spires", ")", "]", "...
Get composite keywords. :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted keywords
[ "Get", "composite", "keywords", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L363-L378
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
_get_acronyms
def _get_acronyms(acronyms): """Return a formatted list of acronyms.""" acronyms_str = {} if acronyms: for acronym, expansions in iteritems(acronyms): expansions_str = ", ".join(["%s (%d)" % expansion for expansion in expansions]) acron...
python
def _get_acronyms(acronyms): """Return a formatted list of acronyms.""" acronyms_str = {} if acronyms: for acronym, expansions in iteritems(acronyms): expansions_str = ", ".join(["%s (%d)" % expansion for expansion in expansions]) acron...
[ "def", "_get_acronyms", "(", "acronyms", ")", ":", "acronyms_str", "=", "{", "}", "if", "acronyms", ":", "for", "acronym", ",", "expansions", "in", "iteritems", "(", "acronyms", ")", ":", "expansions_str", "=", "\", \"", ".", "join", "(", "[", "\"%s (%d)\"...
Return a formatted list of acronyms.
[ "Return", "a", "formatted", "list", "of", "acronyms", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L381-L391
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
_get_fieldcodes
def _get_fieldcodes(skw_matches, ckw_matches, spires=False): """Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of tuples with (fieldcodes, keywords) ...
python
def _get_fieldcodes(skw_matches, ckw_matches, spires=False): """Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of tuples with (fieldcodes, keywords) ...
[ "def", "_get_fieldcodes", "(", "skw_matches", ",", "ckw_matches", ",", "spires", "=", "False", ")", ":", "fieldcodes", "=", "{", "}", "output", "=", "{", "}", "for", "skw", ",", "_", "in", "skw_matches", ":", "for", "fieldcode", "in", "skw", ".", "fiel...
Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of tuples with (fieldcodes, keywords)
[ "Return", "the", "output", "for", "the", "field", "codes", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L412-L442
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
_get_core_keywords
def _get_core_keywords(skw_matches, ckw_matches, spires=False): """Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted core keywords """ ...
python
def _get_core_keywords(skw_matches, ckw_matches, spires=False): """Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted core keywords """ ...
[ "def", "_get_core_keywords", "(", "skw_matches", ",", "ckw_matches", ",", "spires", "=", "False", ")", ":", "output", "=", "{", "}", "category", "=", "{", "}", "def", "_get_value_kw", "(", "kw", ")", ":", "\"\"\"Help to sort the Core keywords.\"\"\"", "i", "="...
Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted core keywords
[ "Return", "the", "output", "for", "the", "field", "codes", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L445-L482
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
filter_core_keywords
def filter_core_keywords(keywords): """Only return keywords that are CORE.""" matches = {} for kw, info in keywords.items(): if kw.core: matches[kw] = info return matches
python
def filter_core_keywords(keywords): """Only return keywords that are CORE.""" matches = {} for kw, info in keywords.items(): if kw.core: matches[kw] = info return matches
[ "def", "filter_core_keywords", "(", "keywords", ")", ":", "matches", "=", "{", "}", "for", "kw", ",", "info", "in", "keywords", ".", "items", "(", ")", ":", "if", "kw", ".", "core", ":", "matches", "[", "kw", "]", "=", "info", "return", "matches" ]
Only return keywords that are CORE.
[ "Only", "return", "keywords", "that", "are", "CORE", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L485-L491
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
clean_before_output
def clean_before_output(kw_matches): """Return a clean copy of the keywords data structure. Stripped off the standalone and other unwanted elements. """ filtered_kw_matches = {} for kw_match, info in iteritems(kw_matches): if not kw_match.nostandalone: filtered_kw_matches[kw_ma...
python
def clean_before_output(kw_matches): """Return a clean copy of the keywords data structure. Stripped off the standalone and other unwanted elements. """ filtered_kw_matches = {} for kw_match, info in iteritems(kw_matches): if not kw_match.nostandalone: filtered_kw_matches[kw_ma...
[ "def", "clean_before_output", "(", "kw_matches", ")", ":", "filtered_kw_matches", "=", "{", "}", "for", "kw_match", ",", "info", "in", "iteritems", "(", "kw_matches", ")", ":", "if", "not", "kw_match", ".", "nostandalone", ":", "filtered_kw_matches", "[", "kw_...
Return a clean copy of the keywords data structure. Stripped off the standalone and other unwanted elements.
[ "Return", "a", "clean", "copy", "of", "the", "keywords", "data", "structure", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L494-L505
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
_skw_matches_comparator
def _skw_matches_comparator(kw0, kw1): """Compare 2 single keywords objects. First by the number of their spans (ie. how many times they were found), if it is equal it compares them by lenghts of their labels. """ def compare(a, b): return (a > b) - (a < b) list_comparison = compare(le...
python
def _skw_matches_comparator(kw0, kw1): """Compare 2 single keywords objects. First by the number of their spans (ie. how many times they were found), if it is equal it compares them by lenghts of their labels. """ def compare(a, b): return (a > b) - (a < b) list_comparison = compare(le...
[ "def", "_skw_matches_comparator", "(", "kw0", ",", "kw1", ")", ":", "def", "compare", "(", "a", ",", "b", ")", ":", "return", "(", "a", ">", "b", ")", "-", "(", "a", "<", "b", ")", "list_comparison", "=", "compare", "(", "len", "(", "kw1", "[", ...
Compare 2 single keywords objects. First by the number of their spans (ie. how many times they were found), if it is equal it compares them by lenghts of their labels.
[ "Compare", "2", "single", "keywords", "objects", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L512-L532
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
_kw
def _kw(keywords): """Turn list of keywords into dictionary.""" r = {} for k, v in keywords: r[k] = v return r
python
def _kw(keywords): """Turn list of keywords into dictionary.""" r = {} for k, v in keywords: r[k] = v return r
[ "def", "_kw", "(", "keywords", ")", ":", "r", "=", "{", "}", "for", "k", ",", "v", "in", "keywords", ":", "r", "[", "k", "]", "=", "v", "return", "r" ]
Turn list of keywords into dictionary.
[ "Turn", "list", "of", "keywords", "into", "dictionary", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L535-L540
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
_sort_kw_matches
def _sort_kw_matches(skw_matches, limit=0): """Return a resized version of keywords to the given length.""" sorted_keywords = list(skw_matches.items()) sorted(sorted_keywords, key=cmp_to_key(_skw_matches_comparator)) return limit and sorted_keywords[:limit] or sorted_keywords
python
def _sort_kw_matches(skw_matches, limit=0): """Return a resized version of keywords to the given length.""" sorted_keywords = list(skw_matches.items()) sorted(sorted_keywords, key=cmp_to_key(_skw_matches_comparator)) return limit and sorted_keywords[:limit] or sorted_keywords
[ "def", "_sort_kw_matches", "(", "skw_matches", ",", "limit", "=", "0", ")", ":", "sorted_keywords", "=", "list", "(", "skw_matches", ".", "items", "(", ")", ")", "sorted", "(", "sorted_keywords", ",", "key", "=", "cmp_to_key", "(", "_skw_matches_comparator", ...
Return a resized version of keywords to the given length.
[ "Return", "a", "resized", "version", "of", "keywords", "to", "the", "given", "length", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L543-L547
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
get_partial_text
def get_partial_text(fulltext): """Return a short version of the fulltext used with partial matching mode. The version is composed of 20% in the beginning and 20% in the middle of the text. """ def _get_index(x): return int(float(x) / 100 * len(fulltext)) partial_text = [ fullt...
python
def get_partial_text(fulltext): """Return a short version of the fulltext used with partial matching mode. The version is composed of 20% in the beginning and 20% in the middle of the text. """ def _get_index(x): return int(float(x) / 100 * len(fulltext)) partial_text = [ fullt...
[ "def", "get_partial_text", "(", "fulltext", ")", ":", "def", "_get_index", "(", "x", ")", ":", "return", "int", "(", "float", "(", "x", ")", "/", "100", "*", "len", "(", "fulltext", ")", ")", "partial_text", "=", "[", "fulltext", "[", "_get_index", "...
Return a short version of the fulltext used with partial matching mode. The version is composed of 20% in the beginning and 20% in the middle of the text.
[ "Return", "a", "short", "version", "of", "the", "fulltext", "used", "with", "partial", "matching", "mode", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L550-L566
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
save_keywords
def save_keywords(filename, xml): """Save keyword XML to filename.""" tmp_dir = os.path.dirname(filename) if not os.path.isdir(tmp_dir): os.mkdir(tmp_dir) file_desc = open(filename, "w") file_desc.write(xml) file_desc.close()
python
def save_keywords(filename, xml): """Save keyword XML to filename.""" tmp_dir = os.path.dirname(filename) if not os.path.isdir(tmp_dir): os.mkdir(tmp_dir) file_desc = open(filename, "w") file_desc.write(xml) file_desc.close()
[ "def", "save_keywords", "(", "filename", ",", "xml", ")", ":", "tmp_dir", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "tmp_dir", ")", ":", "os", ".", "mkdir", "(", "tmp_dir", ")",...
Save keyword XML to filename.
[ "Save", "keyword", "XML", "to", "filename", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L569-L577
inveniosoftware-contrib/invenio-classifier
invenio_classifier/engine.py
_parse_marc_code
def _parse_marc_code(field): """Parse marc field and return default indicators if not filled in.""" field = str(field) if len(field) < 4: raise Exception('Wrong field code: %s' % field) else: field += '__' tag = field[0:3] ind1 = field[3].replace('_', '') ind2 = field[4].repl...
python
def _parse_marc_code(field): """Parse marc field and return default indicators if not filled in.""" field = str(field) if len(field) < 4: raise Exception('Wrong field code: %s' % field) else: field += '__' tag = field[0:3] ind1 = field[3].replace('_', '') ind2 = field[4].repl...
[ "def", "_parse_marc_code", "(", "field", ")", ":", "field", "=", "str", "(", "field", ")", "if", "len", "(", "field", ")", "<", "4", ":", "raise", "Exception", "(", "'Wrong field code: %s'", "%", "field", ")", "else", ":", "field", "+=", "'__'", "tag",...
Parse marc field and return default indicators if not filled in.
[ "Parse", "marc", "field", "and", "return", "default", "indicators", "if", "not", "filled", "in", "." ]
train
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/engine.py#L580-L590
gregmuellegger/django-debug-toolbar-autoreload
debug_toolbar_autoreload/views.py
notify
def notify(request): ''' This view gets a POST request from the Javascript part of the AutoreloadPanel that contains a body that looks like:: template=/full/path/to/template.html&template=/another/template.eml:123456789& media=/static/url/to/a/file:133456780&media=http://media.localhost.loc...
python
def notify(request): ''' This view gets a POST request from the Javascript part of the AutoreloadPanel that contains a body that looks like:: template=/full/path/to/template.html&template=/another/template.eml:123456789& media=/static/url/to/a/file:133456780&media=http://media.localhost.loc...
[ "def", "notify", "(", "request", ")", ":", "def", "get_resources", "(", "names", ",", "resource_class", ")", ":", "resources", "=", "[", "]", "for", "name", "in", "names", ":", "timestamp", "=", "None", "if", "':'", "in", "name", ":", "name", ",", "t...
This view gets a POST request from the Javascript part of the AutoreloadPanel that contains a body that looks like:: template=/full/path/to/template.html&template=/another/template.eml:123456789& media=/static/url/to/a/file:133456780&media=http://media.localhost.local/base.css It is a list of ...
[ "This", "view", "gets", "a", "POST", "request", "from", "the", "Javascript", "part", "of", "the", "AutoreloadPanel", "that", "contains", "a", "body", "that", "looks", "like", "::" ]
train
https://github.com/gregmuellegger/django-debug-toolbar-autoreload/blob/8cbdb06b9b40f2548bcccfd9dcb04ef56166771a/debug_toolbar_autoreload/views.py#L40-L95
StyXman/ayrton
ayrton/__init__.py
run_tree
def run_tree (tree, g, l): """Main entry point for remote().""" runner= Ayrton (g=g, l=l) return runner.run_tree (tree, 'unknown_tree')
python
def run_tree (tree, g, l): """Main entry point for remote().""" runner= Ayrton (g=g, l=l) return runner.run_tree (tree, 'unknown_tree')
[ "def", "run_tree", "(", "tree", ",", "g", ",", "l", ")", ":", "runner", "=", "Ayrton", "(", "g", "=", "g", ",", "l", "=", "l", ")", "return", "runner", ".", "run_tree", "(", "tree", ",", "'unknown_tree'", ")" ]
Main entry point for remote().
[ "Main", "entry", "point", "for", "remote", "()", "." ]
train
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/__init__.py#L496-L499
StyXman/ayrton
ayrton/__init__.py
run_file_or_script
def run_file_or_script (script=None, file_name='script_from_command_line', argv=None, params=None, **kwargs): """Main entry point for bin/ayrton and unittests.""" runner= Ayrton (**kwargs) if params is None: params= ExecParams () if script is None: v= runner.run...
python
def run_file_or_script (script=None, file_name='script_from_command_line', argv=None, params=None, **kwargs): """Main entry point for bin/ayrton and unittests.""" runner= Ayrton (**kwargs) if params is None: params= ExecParams () if script is None: v= runner.run...
[ "def", "run_file_or_script", "(", "script", "=", "None", ",", "file_name", "=", "'script_from_command_line'", ",", "argv", "=", "None", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "runner", "=", "Ayrton", "(", "*", "*", "kwargs", ")", ...
Main entry point for bin/ayrton and unittests.
[ "Main", "entry", "point", "for", "bin", "/", "ayrton", "and", "unittests", "." ]
train
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/__init__.py#L502-L519
StyXman/ayrton
ayrton/__init__.py
Ayrton.run_code
def run_code (self, code, file_name, argv=None): if logger.parent.level<=logging.DEBUG2: # pragma: no cover logger.debug2 ('------------------') logger.debug2 ('main (gobal) code:') handler= logger.parent.handlers[0] handler.acquire () dis.dis (code,...
python
def run_code (self, code, file_name, argv=None): if logger.parent.level<=logging.DEBUG2: # pragma: no cover logger.debug2 ('------------------') logger.debug2 ('main (gobal) code:') handler= logger.parent.handlers[0] handler.acquire () dis.dis (code,...
[ "def", "run_code", "(", "self", ",", "code", ",", "file_name", ",", "argv", "=", "None", ")", ":", "if", "logger", ".", "parent", ".", "level", "<=", "logging", ".", "DEBUG2", ":", "# pragma: no cover", "logger", ".", "debug2", "(", "'------------------'",...
exec(): If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module ...
[ "exec", "()", ":", "If", "only", "globals", "is", "provided", "it", "must", "be", "a", "dictionary", "which", "will", "be", "used", "for", "both", "the", "global", "and", "the", "local", "variables", ".", "If", "globals", "and", "locals", "are", "given",...
train
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/__init__.py#L358-L442
uw-it-aca/django-userservice
userservice/decorators.py
override_admin_required
def override_admin_required(view_func): """ View decorator that checks whether the user is permitted to override (act as) users. Calls login_required in case the user is not authenticated. """ def wrapper(request, *args, **kwargs): func_str = getattr( settings, 'USERSERVICE_OVERR...
python
def override_admin_required(view_func): """ View decorator that checks whether the user is permitted to override (act as) users. Calls login_required in case the user is not authenticated. """ def wrapper(request, *args, **kwargs): func_str = getattr( settings, 'USERSERVICE_OVERR...
[ "def", "override_admin_required", "(", "view_func", ")", ":", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func_str", "=", "getattr", "(", "settings", ",", "'USERSERVICE_OVERRIDE_AUTH_MODULE'", ",", "'userservice.decora...
View decorator that checks whether the user is permitted to override (act as) users. Calls login_required in case the user is not authenticated.
[ "View", "decorator", "that", "checks", "whether", "the", "user", "is", "permitted", "to", "override", "(", "act", "as", ")", "users", ".", "Calls", "login_required", "in", "case", "the", "user", "is", "not", "authenticated", "." ]
train
https://github.com/uw-it-aca/django-userservice/blob/45a3c37debb995a24cf0662346ef8b60066e4738/userservice/decorators.py#L13-L29
rjw57/starman
starman/kalman.py
KalmanFilter.clone
def clone(self): """Return a new :py:class:`.KalmanFilter` instance which is a shallow clone of this one. By "shallow", although the lists of measurements, etc, are cloned, the :py:class:`.MultivariateNormal` instances within them are not. Since :py:meth:`.predict` and :py:meth:`.update`...
python
def clone(self): """Return a new :py:class:`.KalmanFilter` instance which is a shallow clone of this one. By "shallow", although the lists of measurements, etc, are cloned, the :py:class:`.MultivariateNormal` instances within them are not. Since :py:meth:`.predict` and :py:meth:`.update`...
[ "def", "clone", "(", "self", ")", ":", "new_f", "=", "KalmanFilter", "(", "initial_state_estimate", "=", "self", ".", "_initial_state_estimate", ")", "new_f", ".", "_defaults", "=", "self", ".", "_defaults", "# pylint:disable=protected-access", "new_f", ".", "stat...
Return a new :py:class:`.KalmanFilter` instance which is a shallow clone of this one. By "shallow", although the lists of measurements, etc, are cloned, the :py:class:`.MultivariateNormal` instances within them are not. Since :py:meth:`.predict` and :py:meth:`.update` do not modify the e...
[ "Return", "a", "new", ":", "py", ":", "class", ":", ".", "KalmanFilter", "instance", "which", "is", "a", "shallow", "clone", "of", "this", "one", ".", "By", "shallow", "although", "the", "lists", "of", "measurements", "etc", "are", "cloned", "the", ":", ...
train
https://github.com/rjw57/starman/blob/1f9475e2354c9630a61f4898ad871de1d2fdbc71/starman/kalman.py#L107-L129
rjw57/starman
starman/kalman.py
KalmanFilter.predict
def predict(self, control=None, control_matrix=None, process_matrix=None, process_covariance=None): """ Predict the next *a priori* state mean and covariance given the last posterior. As a special case the first call to this method will initialise the posterior and prior ...
python
def predict(self, control=None, control_matrix=None, process_matrix=None, process_covariance=None): """ Predict the next *a priori* state mean and covariance given the last posterior. As a special case the first call to this method will initialise the posterior and prior ...
[ "def", "predict", "(", "self", ",", "control", "=", "None", ",", "control_matrix", "=", "None", ",", "process_matrix", "=", "None", ",", "process_covariance", "=", "None", ")", ":", "# Sanitise arguments", "if", "process_matrix", "is", "None", ":", "process_ma...
Predict the next *a priori* state mean and covariance given the last posterior. As a special case the first call to this method will initialise the posterior and prior estimates from the *initial_state_estimate* and *initial_covariance* arguments passed when this object was created. In t...
[ "Predict", "the", "next", "*", "a", "priori", "*", "state", "mean", "and", "covariance", "given", "the", "last", "posterior", ".", "As", "a", "special", "case", "the", "first", "call", "to", "this", "method", "will", "initialise", "the", "posterior", "and"...
train
https://github.com/rjw57/starman/blob/1f9475e2354c9630a61f4898ad871de1d2fdbc71/starman/kalman.py#L131-L204
rjw57/starman
starman/kalman.py
KalmanFilter.update
def update(self, measurement, measurement_matrix): """ After each :py:meth:`predict`, this method may be called repeatedly to provide additional measurements for each time step. Args: measurement (MultivariateNormal): Measurement for this time step with speci...
python
def update(self, measurement, measurement_matrix): """ After each :py:meth:`predict`, this method may be called repeatedly to provide additional measurements for each time step. Args: measurement (MultivariateNormal): Measurement for this time step with speci...
[ "def", "update", "(", "self", ",", "measurement", ",", "measurement_matrix", ")", ":", "# Sanitise input arguments", "measurement_matrix", "=", "np", ".", "atleast_2d", "(", "measurement_matrix", ")", "expected_meas_mat_shape", "=", "(", "measurement", ".", "mean", ...
After each :py:meth:`predict`, this method may be called repeatedly to provide additional measurements for each time step. Args: measurement (MultivariateNormal): Measurement for this time step with specified mean and covariance. measurement_matrix (array): Measu...
[ "After", "each", ":", "py", ":", "meth", ":", "predict", "this", "method", "may", "be", "called", "repeatedly", "to", "provide", "additional", "measurements", "for", "each", "time", "step", "." ]
train
https://github.com/rjw57/starman/blob/1f9475e2354c9630a61f4898ad871de1d2fdbc71/starman/kalman.py#L206-L246
rjw57/starman
starman/kalman.py
KalmanFilter.truncate
def truncate(self, new_count): """Truncate the filter as if only *new_count* :py:meth:`.predict`, :py:meth:`.update` steps had been performed. If *new_count* is greater than :py:attr:`.state_count` then this function is a no-op. Measurements, state estimates, process matrices and proces...
python
def truncate(self, new_count): """Truncate the filter as if only *new_count* :py:meth:`.predict`, :py:meth:`.update` steps had been performed. If *new_count* is greater than :py:attr:`.state_count` then this function is a no-op. Measurements, state estimates, process matrices and proces...
[ "def", "truncate", "(", "self", ",", "new_count", ")", ":", "self", ".", "posterior_state_estimates", "=", "self", ".", "posterior_state_estimates", "[", ":", "new_count", "]", "self", ".", "prior_state_estimates", "=", "self", ".", "prior_state_estimates", "[", ...
Truncate the filter as if only *new_count* :py:meth:`.predict`, :py:meth:`.update` steps had been performed. If *new_count* is greater than :py:attr:`.state_count` then this function is a no-op. Measurements, state estimates, process matrices and process noises which are truncated are d...
[ "Truncate", "the", "filter", "as", "if", "only", "*", "new_count", "*", ":", "py", ":", "meth", ":", ".", "predict", ":", "py", ":", "meth", ":", ".", "update", "steps", "had", "been", "performed", ".", "If", "*", "new_count", "*", "is", "greater", ...
train
https://github.com/rjw57/starman/blob/1f9475e2354c9630a61f4898ad871de1d2fdbc71/starman/kalman.py#L248-L264
alexandrovteam/cpyMSpec
cpyMSpec/spectrum.py
isotopePattern
def isotopePattern(sum_formula, threshold=1e-4, rel_threshold=True, desired_prob=None): """ Calculates isotopic peaks for a sum formula. :param sum_formula: text representation of an atomic composition :type sum_formula: str :param threshold: minimum peak abundance :type threshold: float :p...
python
def isotopePattern(sum_formula, threshold=1e-4, rel_threshold=True, desired_prob=None): """ Calculates isotopic peaks for a sum formula. :param sum_formula: text representation of an atomic composition :type sum_formula: str :param threshold: minimum peak abundance :type threshold: float :p...
[ "def", "isotopePattern", "(", "sum_formula", ",", "threshold", "=", "1e-4", ",", "rel_threshold", "=", "True", ",", "desired_prob", "=", "None", ")", ":", "assert", "threshold", ">=", "0", "and", "threshold", "<", "1", "assert", "desired_prob", "is", "None",...
Calculates isotopic peaks for a sum formula. :param sum_formula: text representation of an atomic composition :type sum_formula: str :param threshold: minimum peak abundance :type threshold: float :param rel_threshold: if True, threshold is relative to the highest peak, otherwise it is a probabilit...
[ "Calculates", "isotopic", "peaks", "for", "a", "sum", "formula", "." ]
train
https://github.com/alexandrovteam/cpyMSpec/blob/99d9ea18036d65d2d76744102e9304c5df67a1e1/cpyMSpec/spectrum.py#L301-L321
alexandrovteam/cpyMSpec
cpyMSpec/spectrum.py
SpectrumBase.masses
def masses(self): """ :returns: peak masses :rtype: list of floats """ buf = ffi.new("double[]", self.size) ims.spectrum_masses(self.ptr, buf) return list(buf)
python
def masses(self): """ :returns: peak masses :rtype: list of floats """ buf = ffi.new("double[]", self.size) ims.spectrum_masses(self.ptr, buf) return list(buf)
[ "def", "masses", "(", "self", ")", ":", "buf", "=", "ffi", ".", "new", "(", "\"double[]\"", ",", "self", ".", "size", ")", "ims", ".", "spectrum_masses", "(", "self", ".", "ptr", ",", "buf", ")", "return", "list", "(", "buf", ")" ]
:returns: peak masses :rtype: list of floats
[ ":", "returns", ":", "peak", "masses", ":", "rtype", ":", "list", "of", "floats" ]
train
https://github.com/alexandrovteam/cpyMSpec/blob/99d9ea18036d65d2d76744102e9304c5df67a1e1/cpyMSpec/spectrum.py#L97-L104
alexandrovteam/cpyMSpec
cpyMSpec/spectrum.py
SpectrumBase.intensities
def intensities(self): """ :returns: peak intensities :rtype: list of floats """ buf = ffi.new("double[]", self.size) ims.spectrum_intensities(self.ptr, buf) return list(buf)
python
def intensities(self): """ :returns: peak intensities :rtype: list of floats """ buf = ffi.new("double[]", self.size) ims.spectrum_intensities(self.ptr, buf) return list(buf)
[ "def", "intensities", "(", "self", ")", ":", "buf", "=", "ffi", ".", "new", "(", "\"double[]\"", ",", "self", ".", "size", ")", "ims", ".", "spectrum_intensities", "(", "self", ".", "ptr", ",", "buf", ")", "return", "list", "(", "buf", ")" ]
:returns: peak intensities :rtype: list of floats
[ ":", "returns", ":", "peak", "intensities", ":", "rtype", ":", "list", "of", "floats" ]
train
https://github.com/alexandrovteam/cpyMSpec/blob/99d9ea18036d65d2d76744102e9304c5df67a1e1/cpyMSpec/spectrum.py#L107-L114
alexandrovteam/cpyMSpec
cpyMSpec/spectrum.py
SpectrumBase.trim
def trim(self, n_peaks): """ Sorts mass and intensities arrays in descending intensity order, then removes low-intensity peaks from the spectrum. :param n_peaks: number of peaks to keep """ self.sortByIntensity() ims.spectrum_trim(self.ptr, n_peaks)
python
def trim(self, n_peaks): """ Sorts mass and intensities arrays in descending intensity order, then removes low-intensity peaks from the spectrum. :param n_peaks: number of peaks to keep """ self.sortByIntensity() ims.spectrum_trim(self.ptr, n_peaks)
[ "def", "trim", "(", "self", ",", "n_peaks", ")", ":", "self", ".", "sortByIntensity", "(", ")", "ims", ".", "spectrum_trim", "(", "self", ".", "ptr", ",", "n_peaks", ")" ]
Sorts mass and intensities arrays in descending intensity order, then removes low-intensity peaks from the spectrum. :param n_peaks: number of peaks to keep
[ "Sorts", "mass", "and", "intensities", "arrays", "in", "descending", "intensity", "order", "then", "removes", "low", "-", "intensity", "peaks", "from", "the", "spectrum", "." ]
train
https://github.com/alexandrovteam/cpyMSpec/blob/99d9ea18036d65d2d76744102e9304c5df67a1e1/cpyMSpec/spectrum.py#L126-L134
alexandrovteam/cpyMSpec
cpyMSpec/spectrum.py
ProfileSpectrum.centroids
def centroids(self, window_size=5): """ Detects peaks in raw data. :param mzs: sorted array of m/z values :param intensities: array of corresponding intensities :param window_size: size of m/z averaging window :returns: isotope pattern containing the centroids :...
python
def centroids(self, window_size=5): """ Detects peaks in raw data. :param mzs: sorted array of m/z values :param intensities: array of corresponding intensities :param window_size: size of m/z averaging window :returns: isotope pattern containing the centroids :...
[ "def", "centroids", "(", "self", ",", "window_size", "=", "5", ")", ":", "self", ".", "sortByMass", "(", ")", "mzs", "=", "_cffi_buffer", "(", "self", ".", "masses", ",", "'d'", ")", "intensities", "=", "_cffi_buffer", "(", "self", ".", "intensities", ...
Detects peaks in raw data. :param mzs: sorted array of m/z values :param intensities: array of corresponding intensities :param window_size: size of m/z averaging window :returns: isotope pattern containing the centroids :rtype: CentroidedSpectrum
[ "Detects", "peaks", "in", "raw", "data", "." ]
train
https://github.com/alexandrovteam/cpyMSpec/blob/99d9ea18036d65d2d76744102e9304c5df67a1e1/cpyMSpec/spectrum.py#L159-L175
alexandrovteam/cpyMSpec
cpyMSpec/spectrum.py
TheoreticalSpectrum.centroids
def centroids(self, instrument, min_abundance=1e-4, points_per_fwhm=25): """ Estimates centroided peaks for a given instrument model. :param instrument: instrument model :param min_abundance: minimum abundance for including a peak :param points_per_fwhm: grid density used for en...
python
def centroids(self, instrument, min_abundance=1e-4, points_per_fwhm=25): """ Estimates centroided peaks for a given instrument model. :param instrument: instrument model :param min_abundance: minimum abundance for including a peak :param points_per_fwhm: grid density used for en...
[ "def", "centroids", "(", "self", ",", "instrument", ",", "min_abundance", "=", "1e-4", ",", "points_per_fwhm", "=", "25", ")", ":", "assert", "self", ".", "ptr", "!=", "ffi", ".", "NULL", "centroids", "=", "ims", ".", "spectrum_envelope_centroids", "(", "s...
Estimates centroided peaks for a given instrument model. :param instrument: instrument model :param min_abundance: minimum abundance for including a peak :param points_per_fwhm: grid density used for envelope calculation :returns: peaks visible with the instrument used :rtype: T...
[ "Estimates", "centroided", "peaks", "for", "a", "given", "instrument", "model", "." ]
train
https://github.com/alexandrovteam/cpyMSpec/blob/99d9ea18036d65d2d76744102e9304c5df67a1e1/cpyMSpec/spectrum.py#L207-L220
alexandrovteam/cpyMSpec
cpyMSpec/spectrum.py
TheoreticalSpectrum.envelope
def envelope(self, instrument): """ Computes isotopic envelope for a given instrument model :param instrument: instrument model to use :returns: isotopic envelope as a function of mass :rtype: function float(mz: float) """ def envelopeFunc(mz): if is...
python
def envelope(self, instrument): """ Computes isotopic envelope for a given instrument model :param instrument: instrument model to use :returns: isotopic envelope as a function of mass :rtype: function float(mz: float) """ def envelopeFunc(mz): if is...
[ "def", "envelope", "(", "self", ",", "instrument", ")", ":", "def", "envelopeFunc", "(", "mz", ")", ":", "if", "isinstance", "(", "mz", ",", "numbers", ".", "Number", ")", ":", "return", "ims", ".", "spectrum_envelope", "(", "self", ".", "ptr", ",", ...
Computes isotopic envelope for a given instrument model :param instrument: instrument model to use :returns: isotopic envelope as a function of mass :rtype: function float(mz: float)
[ "Computes", "isotopic", "envelope", "for", "a", "given", "instrument", "model" ]
train
https://github.com/alexandrovteam/cpyMSpec/blob/99d9ea18036d65d2d76744102e9304c5df67a1e1/cpyMSpec/spectrum.py#L240-L260
alexandrovteam/cpyMSpec
cpyMSpec/spectrum.py
CentroidedSpectrum.charged
def charged(self, charge): """ Adds/subtracts electrons and returns a new object. :param charge: number of electrons to add :type charge: integer :returns: a spectrum with appropriately shifted masses :rtype: CentroidedSpectrum """ result = self.copy() ...
python
def charged(self, charge): """ Adds/subtracts electrons and returns a new object. :param charge: number of electrons to add :type charge: integer :returns: a spectrum with appropriately shifted masses :rtype: CentroidedSpectrum """ result = self.copy() ...
[ "def", "charged", "(", "self", ",", "charge", ")", ":", "result", "=", "self", ".", "copy", "(", ")", "result", ".", "addCharge", "(", "charge", ")", "return", "result" ]
Adds/subtracts electrons and returns a new object. :param charge: number of electrons to add :type charge: integer :returns: a spectrum with appropriately shifted masses :rtype: CentroidedSpectrum
[ "Adds", "/", "subtracts", "electrons", "and", "returns", "a", "new", "object", "." ]
train
https://github.com/alexandrovteam/cpyMSpec/blob/99d9ea18036d65d2d76744102e9304c5df67a1e1/cpyMSpec/spectrum.py#L274-L286
alexandrovteam/cpyMSpec
cpyMSpec/spectrum.py
CentroidedSpectrum.trimmed
def trimmed(self, n_peaks): """ :param n_peaks: number of peaks to keep :returns: an isotope pattern with removed low-intensity peaks :rtype: CentroidedSpectrum """ result = self.copy() result.trim(n_peaks) return result
python
def trimmed(self, n_peaks): """ :param n_peaks: number of peaks to keep :returns: an isotope pattern with removed low-intensity peaks :rtype: CentroidedSpectrum """ result = self.copy() result.trim(n_peaks) return result
[ "def", "trimmed", "(", "self", ",", "n_peaks", ")", ":", "result", "=", "self", ".", "copy", "(", ")", "result", ".", "trim", "(", "n_peaks", ")", "return", "result" ]
:param n_peaks: number of peaks to keep :returns: an isotope pattern with removed low-intensity peaks :rtype: CentroidedSpectrum
[ ":", "param", "n_peaks", ":", "number", "of", "peaks", "to", "keep", ":", "returns", ":", "an", "isotope", "pattern", "with", "removed", "low", "-", "intensity", "peaks", ":", "rtype", ":", "CentroidedSpectrum" ]
train
https://github.com/alexandrovteam/cpyMSpec/blob/99d9ea18036d65d2d76744102e9304c5df67a1e1/cpyMSpec/spectrum.py#L288-L296
ssato/python-anytemplate
anytemplate/engines/mako.py
_render
def _render(tmpl, ctx): """ :param tmpl: mako.template.Template object :param ctx: A dict or dict-like object to instantiate given """ is_py3k = anytemplate.compat.IS_PYTHON_3 return tmpl.render_unicode(**ctx) if is_py3k else tmpl.render(**ctx)
python
def _render(tmpl, ctx): """ :param tmpl: mako.template.Template object :param ctx: A dict or dict-like object to instantiate given """ is_py3k = anytemplate.compat.IS_PYTHON_3 return tmpl.render_unicode(**ctx) if is_py3k else tmpl.render(**ctx)
[ "def", "_render", "(", "tmpl", ",", "ctx", ")", ":", "is_py3k", "=", "anytemplate", ".", "compat", ".", "IS_PYTHON_3", "return", "tmpl", ".", "render_unicode", "(", "*", "*", "ctx", ")", "if", "is_py3k", "else", "tmpl", ".", "render", "(", "*", "*", ...
:param tmpl: mako.template.Template object :param ctx: A dict or dict-like object to instantiate given
[ ":", "param", "tmpl", ":", "mako", ".", "template", ".", "Template", "object", ":", "param", "ctx", ":", "A", "dict", "or", "dict", "-", "like", "object", "to", "instantiate", "given" ]
train
https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/mako.py#L47-L53
ssato/python-anytemplate
anytemplate/engines/mako.py
Engine.renders_impl
def renders_impl(self, template_content, context, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): """ Render given template string and return the result. :param template_content: Template content :param context: A dict or dict...
python
def renders_impl(self, template_content, context, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): """ Render given template string and return the result. :param template_content: Template content :param context: A dict or dict...
[ "def", "renders_impl", "(", "self", ",", "template_content", ",", "context", ",", "at_paths", "=", "None", ",", "at_encoding", "=", "anytemplate", ".", "compat", ".", "ENCODING", ",", "*", "*", "kwargs", ")", ":", "if", "\"filename\"", "in", "kwargs", ":",...
Render given template string and return the result. :param template_content: Template content :param context: A dict or dict-like object to instantiate given template file :param at_paths: Template search paths :param at_encoding: Template encoding :param kwargs: Key...
[ "Render", "given", "template", "string", "and", "return", "the", "result", "." ]
train
https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/mako.py#L89-L124
ssato/python-anytemplate
anytemplate/engines/mako.py
Engine.render_impl
def render_impl(self, template, context, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): """ Render given template file and return the result. :param template: Template file path :param context: A dict or dict-like object to instantiate given ...
python
def render_impl(self, template, context, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): """ Render given template file and return the result. :param template: Template file path :param context: A dict or dict-like object to instantiate given ...
[ "def", "render_impl", "(", "self", ",", "template", ",", "context", ",", "at_paths", "=", "None", ",", "at_encoding", "=", "anytemplate", ".", "compat", ".", "ENCODING", ",", "*", "*", "kwargs", ")", ":", "if", "\"text\"", "in", "kwargs", ":", "kwargs", ...
Render given template file and return the result. :param template: Template file path :param context: A dict or dict-like object to instantiate given template file :param at_paths: Template search paths :param at_encoding: Template encoding :param kwargs: Keyword arg...
[ "Render", "given", "template", "file", "and", "return", "the", "result", "." ]
train
https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/mako.py#L126-L165
fitnr/twitter_bot_utils
twitter_bot_utils/archive.py
read_csv
def read_csv(directory): ''' Scrape a twitter archive csv, yielding tweet text. Args: directory (str): CSV file or (directory containing tweets.csv). field (str): Field with the tweet's text (default: text). fieldnames (list): The column names for a csv with no header. Must contain ...
python
def read_csv(directory): ''' Scrape a twitter archive csv, yielding tweet text. Args: directory (str): CSV file or (directory containing tweets.csv). field (str): Field with the tweet's text (default: text). fieldnames (list): The column names for a csv with no header. Must contain ...
[ "def", "read_csv", "(", "directory", ")", ":", "if", "path", ".", "isdir", "(", "directory", ")", ":", "csvfile", "=", "path", ".", "join", "(", "directory", ",", "'tweets.csv'", ")", "else", ":", "csvfile", "=", "directory", "with", "open", "(", "csvf...
Scrape a twitter archive csv, yielding tweet text. Args: directory (str): CSV file or (directory containing tweets.csv). field (str): Field with the tweet's text (default: text). fieldnames (list): The column names for a csv with no header. Must contain <field>. ...
[ "Scrape", "a", "twitter", "archive", "csv", "yielding", "tweet", "text", "." ]
train
https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/archive.py#L22-L47
fitnr/twitter_bot_utils
twitter_bot_utils/archive.py
read_json
def read_json(directory, data_files='data/js/tweets/*.js'): ''' Scrape a twitter archive file. Inspiration from https://github.com/mshea/Parse-Twitter-Archive ''' files = path.join(directory, data_files) for fname in iglob(files): with open(fname, 'r') as f: # Twitter's JSON...
python
def read_json(directory, data_files='data/js/tweets/*.js'): ''' Scrape a twitter archive file. Inspiration from https://github.com/mshea/Parse-Twitter-Archive ''' files = path.join(directory, data_files) for fname in iglob(files): with open(fname, 'r') as f: # Twitter's JSON...
[ "def", "read_json", "(", "directory", ",", "data_files", "=", "'data/js/tweets/*.js'", ")", ":", "files", "=", "path", ".", "join", "(", "directory", ",", "data_files", ")", "for", "fname", "in", "iglob", "(", "files", ")", ":", "with", "open", "(", "fna...
Scrape a twitter archive file. Inspiration from https://github.com/mshea/Parse-Twitter-Archive
[ "Scrape", "a", "twitter", "archive", "file", ".", "Inspiration", "from", "https", ":", "//", "github", ".", "com", "/", "mshea", "/", "Parse", "-", "Twitter", "-", "Archive" ]
train
https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/archive.py#L50-L65
KelSolaar/Foundations
foundations/namespace.py
set_namespace
def set_namespace(namespace, attribute, namespace_splitter=NAMESPACE_SPLITTER): """ Sets given namespace to given attribute. Usage:: >>> set_namespace("parent", "child") u'parent|child' :param namespace: Namespace. :type namespace: unicode :param attribute: Attribute. :typ...
python
def set_namespace(namespace, attribute, namespace_splitter=NAMESPACE_SPLITTER): """ Sets given namespace to given attribute. Usage:: >>> set_namespace("parent", "child") u'parent|child' :param namespace: Namespace. :type namespace: unicode :param attribute: Attribute. :typ...
[ "def", "set_namespace", "(", "namespace", ",", "attribute", ",", "namespace_splitter", "=", "NAMESPACE_SPLITTER", ")", ":", "long_name", "=", "\"{0}{1}{2}\"", ".", "format", "(", "namespace", ",", "namespace_splitter", ",", "attribute", ")", "LOGGER", ".", "debug"...
Sets given namespace to given attribute. Usage:: >>> set_namespace("parent", "child") u'parent|child' :param namespace: Namespace. :type namespace: unicode :param attribute: Attribute. :type attribute: unicode :param namespace_splitter: Namespace splitter character. :type ...
[ "Sets", "given", "namespace", "to", "given", "attribute", "." ]
train
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/namespace.py#L43-L64
KelSolaar/Foundations
foundations/namespace.py
get_namespace
def get_namespace(attribute, namespace_splitter=NAMESPACE_SPLITTER, root_only=False): """ Returns given attribute foundations.namespace. Usage:: >>> get_namespace("grandParent|parent|child") u'grandParent|parent' >>> get_namespace("grandParent|parent|child", root_only=True) ...
python
def get_namespace(attribute, namespace_splitter=NAMESPACE_SPLITTER, root_only=False): """ Returns given attribute foundations.namespace. Usage:: >>> get_namespace("grandParent|parent|child") u'grandParent|parent' >>> get_namespace("grandParent|parent|child", root_only=True) ...
[ "def", "get_namespace", "(", "attribute", ",", "namespace_splitter", "=", "NAMESPACE_SPLITTER", ",", "root_only", "=", "False", ")", ":", "attribute_tokens", "=", "attribute", ".", "split", "(", "namespace_splitter", ")", "if", "len", "(", "attribute_tokens", ")",...
Returns given attribute foundations.namespace. Usage:: >>> get_namespace("grandParent|parent|child") u'grandParent|parent' >>> get_namespace("grandParent|parent|child", root_only=True) u'grandParent' :param attribute: Attribute. :type attribute: unicode :param namespac...
[ "Returns", "given", "attribute", "foundations", ".", "namespace", "." ]
train
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/namespace.py#L67-L95
KelSolaar/Foundations
foundations/namespace.py
remove_namespace
def remove_namespace(attribute, namespace_splitter=NAMESPACE_SPLITTER, root_only=False): """ Returns attribute with stripped foundations.namespace. Usage:: >>> remove_namespace("grandParent|parent|child") u'child' >>> remove_namespace("grandParent|parent|child", root_only=True) ...
python
def remove_namespace(attribute, namespace_splitter=NAMESPACE_SPLITTER, root_only=False): """ Returns attribute with stripped foundations.namespace. Usage:: >>> remove_namespace("grandParent|parent|child") u'child' >>> remove_namespace("grandParent|parent|child", root_only=True) ...
[ "def", "remove_namespace", "(", "attribute", ",", "namespace_splitter", "=", "NAMESPACE_SPLITTER", ",", "root_only", "=", "False", ")", ":", "attribute_tokens", "=", "attribute", ".", "split", "(", "namespace_splitter", ")", "stripped_attribute", "=", "root_only", "...
Returns attribute with stripped foundations.namespace. Usage:: >>> remove_namespace("grandParent|parent|child") u'child' >>> remove_namespace("grandParent|parent|child", root_only=True) u'parent|child' :param attribute: Attribute. :type attribute: unicode :param namesp...
[ "Returns", "attribute", "with", "stripped", "foundations", ".", "namespace", "." ]
train
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/namespace.py#L98-L123
KelSolaar/Foundations
foundations/namespace.py
get_leaf
def get_leaf(attribute, namespace_splitter=NAMESPACE_SPLITTER): """ Returns given attribute leaf. Usage:: >>> get_leaf("grandParent|parent|child") u'child' :param attribute: Attribute. :type attribute: unicode :param namespace_splitter: Namespace splitter character. :type ...
python
def get_leaf(attribute, namespace_splitter=NAMESPACE_SPLITTER): """ Returns given attribute leaf. Usage:: >>> get_leaf("grandParent|parent|child") u'child' :param attribute: Attribute. :type attribute: unicode :param namespace_splitter: Namespace splitter character. :type ...
[ "def", "get_leaf", "(", "attribute", ",", "namespace_splitter", "=", "NAMESPACE_SPLITTER", ")", ":", "return", "foundations", ".", "common", ".", "get_last_item", "(", "attribute", ".", "split", "(", "namespace_splitter", ")", ")" ]
Returns given attribute leaf. Usage:: >>> get_leaf("grandParent|parent|child") u'child' :param attribute: Attribute. :type attribute: unicode :param namespace_splitter: Namespace splitter character. :type namespace_splitter: unicode :return: Attribute foundations.namespace. ...
[ "Returns", "given", "attribute", "leaf", "." ]
train
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/namespace.py#L146-L163
TAPPGuild/sqlalchemy-models
sqlalchemy_models/wallet.py
Balance.load_commodities
def load_commodities(self): """ Load the commodities for Amounts in this object. """ if isinstance(self.available, Amount): self.available = Amount("{0:.8f} {1}".format(self.available.to_double(), self.currency)) else: self.available = Amount("{0:.8f} {1}"...
python
def load_commodities(self): """ Load the commodities for Amounts in this object. """ if isinstance(self.available, Amount): self.available = Amount("{0:.8f} {1}".format(self.available.to_double(), self.currency)) else: self.available = Amount("{0:.8f} {1}"...
[ "def", "load_commodities", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "available", ",", "Amount", ")", ":", "self", ".", "available", "=", "Amount", "(", "\"{0:.8f} {1}\"", ".", "format", "(", "self", ".", "available", ".", "to_double", ...
Load the commodities for Amounts in this object.
[ "Load", "the", "commodities", "for", "Amounts", "in", "this", "object", "." ]
train
https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/wallet.py#L44-L55
TAPPGuild/sqlalchemy-models
sqlalchemy_models/wallet.py
Credit.load_commodities
def load_commodities(self): """ Load the commodities for Amounts in this object. """ if isinstance(self.amount, Amount): self.amount = Amount("{0:.8f} {1}".format(self.amount.to_double(), self.currency)) else: self.amount = Amount("{0:.8f} {1}".format(self...
python
def load_commodities(self): """ Load the commodities for Amounts in this object. """ if isinstance(self.amount, Amount): self.amount = Amount("{0:.8f} {1}".format(self.amount.to_double(), self.currency)) else: self.amount = Amount("{0:.8f} {1}".format(self...
[ "def", "load_commodities", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "amount", ",", "Amount", ")", ":", "self", ".", "amount", "=", "Amount", "(", "\"{0:.8f} {1}\"", ".", "format", "(", "self", ".", "amount", ".", "to_double", "(", "...
Load the commodities for Amounts in this object.
[ "Load", "the", "commodities", "for", "Amounts", "in", "this", "object", "." ]
train
https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/wallet.py#L131-L138
TAPPGuild/sqlalchemy-models
sqlalchemy_models/wallet.py
Debit.load_commodities
def load_commodities(self): """ Load the commodities for Amounts in this object. """ if isinstance(self.fee, Amount): self.fee = Amount("{0:.8f} {1}".format(self.fee.to_double(), self.currency)) else: self.fee = Amount("{0:.8f} {1}".format(self.fee, self.c...
python
def load_commodities(self): """ Load the commodities for Amounts in this object. """ if isinstance(self.fee, Amount): self.fee = Amount("{0:.8f} {1}".format(self.fee.to_double(), self.currency)) else: self.fee = Amount("{0:.8f} {1}".format(self.fee, self.c...
[ "def", "load_commodities", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "fee", ",", "Amount", ")", ":", "self", ".", "fee", "=", "Amount", "(", "\"{0:.8f} {1}\"", ".", "format", "(", "self", ".", "fee", ".", "to_double", "(", ")", ","...
Load the commodities for Amounts in this object.
[ "Load", "the", "commodities", "for", "Amounts", "in", "this", "object", "." ]
train
https://github.com/TAPPGuild/sqlalchemy-models/blob/75988a23bdd98e79af8b8b0711c657c79b2f8eac/sqlalchemy_models/wallet.py#L197-L208
KelSolaar/Foundations
foundations/ui/common.py
center_widget_on_screen
def center_widget_on_screen(widget, screen=None): """ Centers given Widget on the screen. :param widget: Current Widget. :type widget: QWidget :param screen: Screen used for centering. :type screen: int :return: Definition success. :rtype: bool """ screen = screen and screen or...
python
def center_widget_on_screen(widget, screen=None): """ Centers given Widget on the screen. :param widget: Current Widget. :type widget: QWidget :param screen: Screen used for centering. :type screen: int :return: Definition success. :rtype: bool """ screen = screen and screen or...
[ "def", "center_widget_on_screen", "(", "widget", ",", "screen", "=", "None", ")", ":", "screen", "=", "screen", "and", "screen", "or", "QApplication", ".", "desktop", "(", ")", ".", "primaryScreen", "(", ")", "desktop_width", "=", "QApplication", ".", "deskt...
Centers given Widget on the screen. :param widget: Current Widget. :type widget: QWidget :param screen: Screen used for centering. :type screen: int :return: Definition success. :rtype: bool
[ "Centers", "given", "Widget", "on", "the", "screen", "." ]
train
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/ui/common.py#L42-L58
KelSolaar/Foundations
foundations/ui/common.py
QWidget_factory
def QWidget_factory(ui_file=None, *args, **kwargs): """ Defines a class factory creating `QWidget <http://doc.qt.nokia.com/qwidget.html>`_ classes using given ui file. :param ui_file: Ui file. :type ui_file: unicode :param \*args: Arguments. :type \*args: \* :param \*\*kwargs: Keywords ...
python
def QWidget_factory(ui_file=None, *args, **kwargs): """ Defines a class factory creating `QWidget <http://doc.qt.nokia.com/qwidget.html>`_ classes using given ui file. :param ui_file: Ui file. :type ui_file: unicode :param \*args: Arguments. :type \*args: \* :param \*\*kwargs: Keywords ...
[ "def", "QWidget_factory", "(", "ui_file", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "file", "=", "ui_file", "or", "DEFAULT_UI_FILE", "if", "not", "foundations", ".", "common", ".", "path_exists", "(", "file", ")", ":", "raise", ...
Defines a class factory creating `QWidget <http://doc.qt.nokia.com/qwidget.html>`_ classes using given ui file. :param ui_file: Ui file. :type ui_file: unicode :param \*args: Arguments. :type \*args: \* :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* :return: QWidget class...
[ "Defines", "a", "class", "factory", "creating", "QWidget", "<http", ":", "//", "doc", ".", "qt", ".", "nokia", ".", "com", "/", "qwidget", ".", "html", ">", "_", "classes", "using", "given", "ui", "file", "." ]
train
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/ui/common.py#L61-L175
nirum-lang/nirum-python
nirum/deserialize.py
is_support_abstract_type
def is_support_abstract_type(t): """FIXME: 3.5 only""" if hasattr(t, '__origin__') and t.__origin__: data_type = t.__origin__ else: data_type = t abstract_types = { typing.Sequence, typing.List, typing.Set, typing.AbstractSet, typing.Mapping, ...
python
def is_support_abstract_type(t): """FIXME: 3.5 only""" if hasattr(t, '__origin__') and t.__origin__: data_type = t.__origin__ else: data_type = t abstract_types = { typing.Sequence, typing.List, typing.Set, typing.AbstractSet, typing.Mapping, ...
[ "def", "is_support_abstract_type", "(", "t", ")", ":", "if", "hasattr", "(", "t", ",", "'__origin__'", ")", "and", "t", ".", "__origin__", ":", "data_type", "=", "t", ".", "__origin__", "else", ":", "data_type", "=", "t", "abstract_types", "=", "{", "typ...
FIXME: 3.5 only
[ "FIXME", ":", "3", ".", "5", "only" ]
train
https://github.com/nirum-lang/nirum-python/blob/3f6af2f8f404fd7d5f43359661be76b4fdf00e96/nirum/deserialize.py#L38-L52
theonion/djes
djes/utils/query.py
batched_queryset
def batched_queryset(queryset, chunksize=1000): ''''' Iterate over a Django Queryset ordered by the primary key This method loads a maximum of chunksize (default: 1000) rows in it's memory at the same time while django normally would load all rows in it's memory. Using the iterator() method only ca...
python
def batched_queryset(queryset, chunksize=1000): ''''' Iterate over a Django Queryset ordered by the primary key This method loads a maximum of chunksize (default: 1000) rows in it's memory at the same time while django normally would load all rows in it's memory. Using the iterator() method only ca...
[ "def", "batched_queryset", "(", "queryset", ",", "chunksize", "=", "1000", ")", ":", "try", ":", "last_pk", "=", "queryset", ".", "order_by", "(", "'-pk'", ")", "[", "0", "]", ".", "pk", "except", "IndexError", ":", "# Support empty querysets", "return", "...
Iterate over a Django Queryset ordered by the primary key This method loads a maximum of chunksize (default: 1000) rows in it's memory at the same time while django normally would load all rows in it's memory. Using the iterator() method only causes it to not preload all the classes. Note that the...
[ "Iterate", "over", "a", "Django", "Queryset", "ordered", "by", "the", "primary", "key" ]
train
https://github.com/theonion/djes/blob/8f7347382c74172e82e959e3dfbc12b18fbb523f/djes/utils/query.py#L4-L29
deeplook/vbbvg
vbbvg/vbbvg.py
load_data
def load_data(verbose=False): "Load all VBB stop names and IDs into a Pandas dataframe." df = pd.read_csv(STOPS_PATH, usecols=['stop_id', 'stop_name']) if verbose: print('- Loaded %d entries from "%s".' % (len(df), STOPS_PATH)) return df
python
def load_data(verbose=False): "Load all VBB stop names and IDs into a Pandas dataframe." df = pd.read_csv(STOPS_PATH, usecols=['stop_id', 'stop_name']) if verbose: print('- Loaded %d entries from "%s".' % (len(df), STOPS_PATH)) return df
[ "def", "load_data", "(", "verbose", "=", "False", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "STOPS_PATH", ",", "usecols", "=", "[", "'stop_id'", ",", "'stop_name'", "]", ")", "if", "verbose", ":", "print", "(", "'- Loaded %d entries from \"%s\".'", ...
Load all VBB stop names and IDs into a Pandas dataframe.
[ "Load", "all", "VBB", "stop", "names", "and", "IDs", "into", "a", "Pandas", "dataframe", "." ]
train
https://github.com/deeplook/vbbvg/blob/3e4455e302b7126684b66b48c589f1af0d9553e7/vbbvg/vbbvg.py#L36-L42
deeplook/vbbvg
vbbvg/vbbvg.py
filter_data
def filter_data(df, filter_name, verbose=False): "Filter certain entries with given name." # pick only entries ending with 'Berlin' in column stop_name, incl. '(Berlin)' # df = df[df.stop_name.apply(lambda cell: 'Berlin' in cell)] df = df[df.stop_name.apply( lambda cell: filter_name.encode('ut...
python
def filter_data(df, filter_name, verbose=False): "Filter certain entries with given name." # pick only entries ending with 'Berlin' in column stop_name, incl. '(Berlin)' # df = df[df.stop_name.apply(lambda cell: 'Berlin' in cell)] df = df[df.stop_name.apply( lambda cell: filter_name.encode('ut...
[ "def", "filter_data", "(", "df", ",", "filter_name", ",", "verbose", "=", "False", ")", ":", "# pick only entries ending with 'Berlin' in column stop_name, incl. '(Berlin)' ", "# df = df[df.stop_name.apply(lambda cell: 'Berlin' in cell)]", "df", "=", "df", "[", "df", ".", "st...
Filter certain entries with given name.
[ "Filter", "certain", "entries", "with", "given", "name", "." ]
train
https://github.com/deeplook/vbbvg/blob/3e4455e302b7126684b66b48c589f1af0d9553e7/vbbvg/vbbvg.py#L45-L64
deeplook/vbbvg
vbbvg/vbbvg.py
get_name_id_interactive
def get_name_id_interactive(stop, df): """ Return VBB/BVG ID for given stop name in given table. Enter interactive dialog when result is not unique. """ # this is very fast, but searching in a list of ca. 2900 tuples might be also # fast enough, and that would mean removing some repeated prepr...
python
def get_name_id_interactive(stop, df): """ Return VBB/BVG ID for given stop name in given table. Enter interactive dialog when result is not unique. """ # this is very fast, but searching in a list of ca. 2900 tuples might be also # fast enough, and that would mean removing some repeated prepr...
[ "def", "get_name_id_interactive", "(", "stop", ",", "df", ")", ":", "# this is very fast, but searching in a list of ca. 2900 tuples might be also", "# fast enough, and that would mean removing some repeated preprocessing...", "# pick only entries containing the given stop substring in column st...
Return VBB/BVG ID for given stop name in given table. Enter interactive dialog when result is not unique.
[ "Return", "VBB", "/", "BVG", "ID", "for", "given", "stop", "name", "in", "given", "table", "." ]
train
https://github.com/deeplook/vbbvg/blob/3e4455e302b7126684b66b48c589f1af0d9553e7/vbbvg/vbbvg.py#L69-L121
deeplook/vbbvg
vbbvg/vbbvg.py
wait_time
def wait_time(departure, now=None): """ Calculate waiting time until the next departure time in 'HH:MM' format. Return time-delta (as 'MM:SS') from now until next departure time in the future ('HH:MM') given as (year, month, day, hour, minute, seconds). Time-deltas shorter than 60 seconds are red...
python
def wait_time(departure, now=None): """ Calculate waiting time until the next departure time in 'HH:MM' format. Return time-delta (as 'MM:SS') from now until next departure time in the future ('HH:MM') given as (year, month, day, hour, minute, seconds). Time-deltas shorter than 60 seconds are red...
[ "def", "wait_time", "(", "departure", ",", "now", "=", "None", ")", ":", "now", "=", "now", "or", "datetime", ".", "datetime", ".", "now", "(", ")", "yn", ",", "mn", ",", "dn", "=", "now", ".", "year", ",", "now", ".", "month", ",", "now", ".",...
Calculate waiting time until the next departure time in 'HH:MM' format. Return time-delta (as 'MM:SS') from now until next departure time in the future ('HH:MM') given as (year, month, day, hour, minute, seconds). Time-deltas shorter than 60 seconds are reduced to 0.
[ "Calculate", "waiting", "time", "until", "the", "next", "departure", "time", "in", "HH", ":", "MM", "format", "." ]
train
https://github.com/deeplook/vbbvg/blob/3e4455e302b7126684b66b48c589f1af0d9553e7/vbbvg/vbbvg.py#L124-L145
deeplook/vbbvg
vbbvg/vbbvg.py
get_next_departures
def get_next_departures(stop, filter_line=None, num_line_groups=1, verbose=False): """ Get all real-time departure times for given stop and return as filtered table. Terminate if we can assume there is no connection to the internet. """ # Get departures table from online service # (great: we ...
python
def get_next_departures(stop, filter_line=None, num_line_groups=1, verbose=False): """ Get all real-time departure times for given stop and return as filtered table. Terminate if we can assume there is no connection to the internet. """ # Get departures table from online service # (great: we ...
[ "def", "get_next_departures", "(", "stop", ",", "filter_line", "=", "None", ",", "num_line_groups", "=", "1", ",", "verbose", "=", "False", ")", ":", "# Get departures table from online service", "# (great: we don't have to iterate over multiple pages).", "url", "=", "BVG...
Get all real-time departure times for given stop and return as filtered table. Terminate if we can assume there is no connection to the internet.
[ "Get", "all", "real", "-", "time", "departure", "times", "for", "given", "stop", "and", "return", "as", "filtered", "table", "." ]
train
https://github.com/deeplook/vbbvg/blob/3e4455e302b7126684b66b48c589f1af0d9553e7/vbbvg/vbbvg.py#L148-L207
deeplook/vbbvg
vbbvg/vbbvg.py
show_header
def show_header(**header): "Display a HTTP-style header on the command-line." print('%s: %s' % ('Now', header['now'])) print('%s: %s' % ('Stop-Name', header['name'])) print('%s: %s' % ('Stop-ID', header.get('id', None))) print('')
python
def show_header(**header): "Display a HTTP-style header on the command-line." print('%s: %s' % ('Now', header['now'])) print('%s: %s' % ('Stop-Name', header['name'])) print('%s: %s' % ('Stop-ID', header.get('id', None))) print('')
[ "def", "show_header", "(", "*", "*", "header", ")", ":", "print", "(", "'%s: %s'", "%", "(", "'Now'", ",", "header", "[", "'now'", "]", ")", ")", "print", "(", "'%s: %s'", "%", "(", "'Stop-Name'", ",", "header", "[", "'name'", "]", ")", ")", "print...
Display a HTTP-style header on the command-line.
[ "Display", "a", "HTTP", "-", "style", "header", "on", "the", "command", "-", "line", "." ]
train
https://github.com/deeplook/vbbvg/blob/3e4455e302b7126684b66b48c589f1af0d9553e7/vbbvg/vbbvg.py#L212-L218
deeplook/vbbvg
vbbvg/vbbvg.py
show_table
def show_table(args): "Output table on standard out." df = load_data(verbose=args.verbose) df = filter_data(df, filter_name=args.filter_name, verbose=args.verbose) stop = re.sub(' +', ' ', args.stop) if re.match('^\d+$', stop.decode('utf-8')): _id = stop name = df[df.stop_id==int(_...
python
def show_table(args): "Output table on standard out." df = load_data(verbose=args.verbose) df = filter_data(df, filter_name=args.filter_name, verbose=args.verbose) stop = re.sub(' +', ' ', args.stop) if re.match('^\d+$', stop.decode('utf-8')): _id = stop name = df[df.stop_id==int(_...
[ "def", "show_table", "(", "args", ")", ":", "df", "=", "load_data", "(", "verbose", "=", "args", ".", "verbose", ")", "df", "=", "filter_data", "(", "df", ",", "filter_name", "=", "args", ".", "filter_name", ",", "verbose", "=", "args", ".", "verbose",...
Output table on standard out.
[ "Output", "table", "on", "standard", "out", "." ]
train
https://github.com/deeplook/vbbvg/blob/3e4455e302b7126684b66b48c589f1af0d9553e7/vbbvg/vbbvg.py#L223-L250
idlesign/envbox
envbox/cli.py
show
def show(): """Show (print out) current environment variables.""" env = get_environment() for key, val in sorted(env.env.items(), key=lambda item: item[0]): click.secho('%s = %s' % (key, val))
python
def show(): """Show (print out) current environment variables.""" env = get_environment() for key, val in sorted(env.env.items(), key=lambda item: item[0]): click.secho('%s = %s' % (key, val))
[ "def", "show", "(", ")", ":", "env", "=", "get_environment", "(", ")", "for", "key", ",", "val", "in", "sorted", "(", "env", ".", "env", ".", "items", "(", ")", ",", "key", "=", "lambda", "item", ":", "item", "[", "0", "]", ")", ":", "click", ...
Show (print out) current environment variables.
[ "Show", "(", "print", "out", ")", "current", "environment", "variables", "." ]
train
https://github.com/idlesign/envbox/blob/4d10cc007e1bc6acf924413c4c16c3b5960d460a/envbox/cli.py#L22-L27
heuer/cablemap
examples/convertgermancablestocsv.py
generate_csv
def generate_csv(src, out): """\ Walks through `src` and generates the CSV file `out` """ writer = UnicodeWriter(open(out, 'wb'), delimiter=';') writer.writerow(('Reference ID', 'Created', 'Origin', 'Subject')) for cable in cables_from_source(src, predicate=pred.origin_filter(pred.origin_germany...
python
def generate_csv(src, out): """\ Walks through `src` and generates the CSV file `out` """ writer = UnicodeWriter(open(out, 'wb'), delimiter=';') writer.writerow(('Reference ID', 'Created', 'Origin', 'Subject')) for cable in cables_from_source(src, predicate=pred.origin_filter(pred.origin_germany...
[ "def", "generate_csv", "(", "src", ",", "out", ")", ":", "writer", "=", "UnicodeWriter", "(", "open", "(", "out", ",", "'wb'", ")", ",", "delimiter", "=", "';'", ")", "writer", ".", "writerow", "(", "(", "'Reference ID'", ",", "'Created'", ",", "'Origi...
\ Walks through `src` and generates the CSV file `out`
[ "\\", "Walks", "through", "src", "and", "generates", "the", "CSV", "file", "out" ]
train
https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/examples/convertgermancablestocsv.py#L43-L50
heuer/cablemap
cablemap.core/cablemap/core/handler.py
handle_cable
def handle_cable(cable, handler, standalone=True): """\ Emits event from the provided `cable` to the handler. `cable` A cable object. `handler` A ICableHandler instance. `standalone` Indicates if a `start` and `end` event should be issued (default: ``True``). ...
python
def handle_cable(cable, handler, standalone=True): """\ Emits event from the provided `cable` to the handler. `cable` A cable object. `handler` A ICableHandler instance. `standalone` Indicates if a `start` and `end` event should be issued (default: ``True``). ...
[ "def", "handle_cable", "(", "cable", ",", "handler", ",", "standalone", "=", "True", ")", ":", "def", "datetime", "(", "dt", ")", ":", "date", ",", "time", "=", "dt", ".", "split", "(", "u' '", ")", "if", "len", "(", "time", ")", "==", "5", ":", ...
\ Emits event from the provided `cable` to the handler. `cable` A cable object. `handler` A ICableHandler instance. `standalone` Indicates if a `start` and `end` event should be issued (default: ``True``). If `standalone` is set to ``False``, no ``handler.start()...
[ "\\", "Emits", "event", "from", "the", "provided", "cable", "to", "the", "handler", "." ]
train
https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/cablemap.core/cablemap/core/handler.py#L234-L295
heuer/cablemap
cablemap.core/cablemap/core/handler.py
handle_cables
def handle_cables(cables, handler): """\ Issues one ``handler.start()`` event, processes all `cables` and issues a ``handler.end()`` event. `cables` An iterable of Cable objects. `handler` The `ICableHandler` instance which should receive the events. """ handler.start() ...
python
def handle_cables(cables, handler): """\ Issues one ``handler.start()`` event, processes all `cables` and issues a ``handler.end()`` event. `cables` An iterable of Cable objects. `handler` The `ICableHandler` instance which should receive the events. """ handler.start() ...
[ "def", "handle_cables", "(", "cables", ",", "handler", ")", ":", "handler", ".", "start", "(", ")", "for", "cable", "in", "cables", ":", "handle_cable", "(", "cable", ",", "handler", ",", "False", ")", "handler", ".", "end", "(", ")" ]
\ Issues one ``handler.start()`` event, processes all `cables` and issues a ``handler.end()`` event. `cables` An iterable of Cable objects. `handler` The `ICableHandler` instance which should receive the events.
[ "\\", "Issues", "one", "handler", ".", "start", "()", "event", "processes", "all", "cables", "and", "issues", "a", "handler", ".", "end", "()", "event", "." ]
train
https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/cablemap.core/cablemap/core/handler.py#L297-L310
peterldowns/djoauth2
djoauth2/authorization.py
make_authorization_endpoint
def make_authorization_endpoint(missing_redirect_uri, authorization_endpoint_uri, authorization_template_name): """ Returns a endpoint that handles OAuth authorization requests. The template described by ``authorization_template_name`` is rendered wi...
python
def make_authorization_endpoint(missing_redirect_uri, authorization_endpoint_uri, authorization_template_name): """ Returns a endpoint that handles OAuth authorization requests. The template described by ``authorization_template_name`` is rendered wi...
[ "def", "make_authorization_endpoint", "(", "missing_redirect_uri", ",", "authorization_endpoint_uri", ",", "authorization_template_name", ")", ":", "@", "login_required", "@", "require_http_methods", "(", "[", "'GET'", ",", "'POST'", "]", ")", "def", "authorization_endpoi...
Returns a endpoint that handles OAuth authorization requests. The template described by ``authorization_template_name`` is rendered with a Django ``RequestContext`` with the following variables: * ``form``: a Django ``Form`` that may hold data internal to the ``djoauth2`` application. * ``client``: The :...
[ "Returns", "a", "endpoint", "that", "handles", "OAuth", "authorization", "requests", "." ]
train
https://github.com/peterldowns/djoauth2/blob/151c7619d1d7a91d720397cfecf3a29fcc9747a9/djoauth2/authorization.py#L359-L416
peterldowns/djoauth2
djoauth2/authorization.py
AuthorizationCodeGenerator.validate
def validate(self, request): """ Check that a Client's authorization request is valid. If the request is invalid or malformed in any way, raises the appropriate exception. Read `the relevant section of the specification <http://tools.ietf.org/html/rfc6749#section-4.1 .>`_ for descriptions of each ...
python
def validate(self, request): """ Check that a Client's authorization request is valid. If the request is invalid or malformed in any way, raises the appropriate exception. Read `the relevant section of the specification <http://tools.ietf.org/html/rfc6749#section-4.1 .>`_ for descriptions of each ...
[ "def", "validate", "(", "self", ",", "request", ")", ":", "# From http://tools.ietf.org/html/rfc6749#section-3.1 :", "#", "# The authorization server MUST support the use of the HTTP \"GET\"", "# method [RFC2616] for the authorization endpoint and MAY support the", "# use of the ...
Check that a Client's authorization request is valid. If the request is invalid or malformed in any way, raises the appropriate exception. Read `the relevant section of the specification <http://tools.ietf.org/html/rfc6749#section-4.1 .>`_ for descriptions of each type of error. :raises: a :py:cl...
[ "Check", "that", "a", "Client", "s", "authorization", "request", "is", "valid", "." ]
train
https://github.com/peterldowns/djoauth2/blob/151c7619d1d7a91d720397cfecf3a29fcc9747a9/djoauth2/authorization.py#L109-L262
peterldowns/djoauth2
djoauth2/authorization.py
AuthorizationCodeGenerator.get_request_uri_parameters
def get_request_uri_parameters(self, as_dict=False): """ Return the URI parameters from a request passed to the 'validate' method The query parameters returned by this method **MUST** be included in the ``action=""`` URI of the authorization form presented to the user. This carries the original authori...
python
def get_request_uri_parameters(self, as_dict=False): """ Return the URI parameters from a request passed to the 'validate' method The query parameters returned by this method **MUST** be included in the ``action=""`` URI of the authorization form presented to the user. This carries the original authori...
[ "def", "get_request_uri_parameters", "(", "self", ",", "as_dict", "=", "False", ")", ":", "if", "not", "self", ".", "request", ":", "raise", "ValueError", "(", "'request must have been passed to the \"validate\" method'", ")", "return", "(", "dict", "if", "as_dict",...
Return the URI parameters from a request passed to the 'validate' method The query parameters returned by this method **MUST** be included in the ``action=""`` URI of the authorization form presented to the user. This carries the original authorization request parameters across the request to show the ...
[ "Return", "the", "URI", "parameters", "from", "a", "request", "passed", "to", "the", "validate", "method" ]
train
https://github.com/peterldowns/djoauth2/blob/151c7619d1d7a91d720397cfecf3a29fcc9747a9/djoauth2/authorization.py#L266-L281
peterldowns/djoauth2
djoauth2/authorization.py
AuthorizationCodeGenerator.make_error_redirect
def make_error_redirect(self, authorization_error=None): """ Return a Django ``HttpResponseRedirect`` describing the request failure. If the :py:meth:`validate` method raises an error, the authorization endpoint should return the result of calling this method like so: >>> auth_code_generator = ( ...
python
def make_error_redirect(self, authorization_error=None): """ Return a Django ``HttpResponseRedirect`` describing the request failure. If the :py:meth:`validate` method raises an error, the authorization endpoint should return the result of calling this method like so: >>> auth_code_generator = ( ...
[ "def", "make_error_redirect", "(", "self", ",", "authorization_error", "=", "None", ")", ":", "if", "not", "self", ".", "redirect_uri", ":", "return", "HttpResponseRedirect", "(", "self", ".", "missing_redirect_uri", ")", "authorization_error", "=", "(", "authoriz...
Return a Django ``HttpResponseRedirect`` describing the request failure. If the :py:meth:`validate` method raises an error, the authorization endpoint should return the result of calling this method like so: >>> auth_code_generator = ( >>> AuthorizationCodeGenerator('/oauth2/missing_redirect_u...
[ "Return", "a", "Django", "HttpResponseRedirect", "describing", "the", "request", "failure", "." ]
train
https://github.com/peterldowns/djoauth2/blob/151c7619d1d7a91d720397cfecf3a29fcc9747a9/djoauth2/authorization.py#L283-L326
peterldowns/djoauth2
djoauth2/authorization.py
AuthorizationCodeGenerator.make_success_redirect
def make_success_redirect(self): """ Return a Django ``HttpResponseRedirect`` describing the request success. The custom authorization endpoint should return the result of this method when the user grants the Client's authorization request. The request is assumed to have successfully been vetted by the...
python
def make_success_redirect(self): """ Return a Django ``HttpResponseRedirect`` describing the request success. The custom authorization endpoint should return the result of this method when the user grants the Client's authorization request. The request is assumed to have successfully been vetted by the...
[ "def", "make_success_redirect", "(", "self", ")", ":", "new_authorization_code", "=", "AuthorizationCode", ".", "objects", ".", "create", "(", "user", "=", "self", ".", "user", ",", "client", "=", "self", ".", "client", ",", "redirect_uri", "=", "(", "self",...
Return a Django ``HttpResponseRedirect`` describing the request success. The custom authorization endpoint should return the result of this method when the user grants the Client's authorization request. The request is assumed to have successfully been vetted by the :py:meth:`validate` method.
[ "Return", "a", "Django", "HttpResponseRedirect", "describing", "the", "request", "success", "." ]
train
https://github.com/peterldowns/djoauth2/blob/151c7619d1d7a91d720397cfecf3a29fcc9747a9/djoauth2/authorization.py#L328-L353
StyXman/ayrton
ayrton/parser/error.py
strerror
def strerror(errno): """Translate an error code to a message string.""" from pypy.module._codecs.locale import str_decode_locale_surrogateescape return str_decode_locale_surrogateescape(os.strerror(errno))
python
def strerror(errno): """Translate an error code to a message string.""" from pypy.module._codecs.locale import str_decode_locale_surrogateescape return str_decode_locale_surrogateescape(os.strerror(errno))
[ "def", "strerror", "(", "errno", ")", ":", "from", "pypy", ".", "module", ".", "_codecs", ".", "locale", "import", "str_decode_locale_surrogateescape", "return", "str_decode_locale_surrogateescape", "(", "os", ".", "strerror", "(", "errno", ")", ")" ]
Translate an error code to a message string.
[ "Translate", "an", "error", "code", "to", "a", "message", "string", "." ]
train
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/error.py#L14-L17
StyXman/ayrton
ayrton/parser/error.py
oefmt
def oefmt(w_type, valuefmt, *args): """Equivalent to OperationError(w_type, space.wrap(valuefmt % args)). More efficient in the (common) case where the value is not actually needed. Note that in the py3k branch the exception message will always be unicode. Supports the standard %s and %d formats, p...
python
def oefmt(w_type, valuefmt, *args): """Equivalent to OperationError(w_type, space.wrap(valuefmt % args)). More efficient in the (common) case where the value is not actually needed. Note that in the py3k branch the exception message will always be unicode. Supports the standard %s and %d formats, p...
[ "def", "oefmt", "(", "w_type", ",", "valuefmt", ",", "*", "args", ")", ":", "if", "not", "len", "(", "args", ")", ":", "return", "OpErrFmtNoArgs", "(", "w_type", ",", "valuefmt", ")", "OpErrFmt", ",", "strings", "=", "get_operr_class", "(", "valuefmt", ...
Equivalent to OperationError(w_type, space.wrap(valuefmt % args)). More efficient in the (common) case where the value is not actually needed. Note that in the py3k branch the exception message will always be unicode. Supports the standard %s and %d formats, plus the following: %8 - The result of ...
[ "Equivalent", "to", "OperationError", "(", "w_type", "space", ".", "wrap", "(", "valuefmt", "%", "args", "))", ".", "More", "efficient", "in", "the", "(", "common", ")", "case", "where", "the", "value", "is", "not", "actually", "needed", ".", "Note", "th...
train
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/error.py#L353-L370
StyXman/ayrton
ayrton/parser/error.py
OperationError.async
def async(self, space): "Check if this is an exception that should better not be caught." return (self.match(space, space.w_SystemExit) or self.match(space, space.w_KeyboardInterrupt))
python
def async(self, space): "Check if this is an exception that should better not be caught." return (self.match(space, space.w_SystemExit) or self.match(space, space.w_KeyboardInterrupt))
[ "def", "async", "(", "self", ",", "space", ")", ":", "return", "(", "self", ".", "match", "(", "space", ",", "space", ".", "w_SystemExit", ")", "or", "self", ".", "match", "(", "space", ",", "space", ".", "w_KeyboardInterrupt", ")", ")" ]
Check if this is an exception that should better not be caught.
[ "Check", "if", "this", "is", "an", "exception", "that", "should", "better", "not", "be", "caught", "." ]
train
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/error.py#L56-L59
StyXman/ayrton
ayrton/parser/error.py
OperationError.errorstr
def errorstr(self, space, use_repr=False): "The exception class and value, as a string." w_value = self.get_w_value(space) if space is None: # this part NOT_RPYTHON exc_typename = str(self.w_type) exc_value = str(w_value) else: w = space.wr...
python
def errorstr(self, space, use_repr=False): "The exception class and value, as a string." w_value = self.get_w_value(space) if space is None: # this part NOT_RPYTHON exc_typename = str(self.w_type) exc_value = str(w_value) else: w = space.wr...
[ "def", "errorstr", "(", "self", ",", "space", ",", "use_repr", "=", "False", ")", ":", "w_value", "=", "self", ".", "get_w_value", "(", "space", ")", "if", "space", "is", "None", ":", "# this part NOT_RPYTHON", "exc_typename", "=", "str", "(", "self", "....
The exception class and value, as a string.
[ "The", "exception", "class", "and", "value", "as", "a", "string", "." ]
train
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/error.py#L74-L102
StyXman/ayrton
ayrton/parser/error.py
OperationError.print_application_traceback
def print_application_traceback(self, space, file=None): "NOT_RPYTHON: Dump a standard application-level traceback." if file is None: file = sys.stderr self.print_app_tb_only(file) print >> file, self.errorstr(space)
python
def print_application_traceback(self, space, file=None): "NOT_RPYTHON: Dump a standard application-level traceback." if file is None: file = sys.stderr self.print_app_tb_only(file) print >> file, self.errorstr(space)
[ "def", "print_application_traceback", "(", "self", ",", "space", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "sys", ".", "stderr", "self", ".", "print_app_tb_only", "(", "file", ")", "print", ">>", "file", ",", "se...
NOT_RPYTHON: Dump a standard application-level traceback.
[ "NOT_RPYTHON", ":", "Dump", "a", "standard", "application", "-", "level", "traceback", "." ]
train
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/error.py#L112-L117