repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
andialbrecht/sentry-comments
sentry_comments/plugin.py
CommentsPlugin.view
def view(self, request, group, **kwargs): """Display and store comments.""" if request.method == 'POST': message = request.POST.get('message') if message is not None and message.strip(): comment = GroupComments(group=group, author=request.user, ...
python
def view(self, request, group, **kwargs): """Display and store comments.""" if request.method == 'POST': message = request.POST.get('message') if message is not None and message.strip(): comment = GroupComments(group=group, author=request.user, ...
[ "def", "view", "(", "self", ",", "request", ",", "group", ",", "*", "*", "kwargs", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "message", "=", "request", ".", "POST", ".", "get", "(", "'message'", ")", "if", "message", "is", "not...
Display and store comments.
[ "Display", "and", "store", "comments", "." ]
b9319320dc3b25b6d813377e69b2d379bcbf6197
https://github.com/andialbrecht/sentry-comments/blob/b9319320dc3b25b6d813377e69b2d379bcbf6197/sentry_comments/plugin.py#L49-L69
train
Display and store comments.
TheGhouls/oct
oct/results/output.py
generate_graphs
def generate_graphs(data, name, results_dir): """Generate all reports from original dataframe :param dic data: dict containing raw and compiled results dataframes :param str name: name for prefixing graphs output :param str results_dir: results output directory """ graphs.resp_graph_raw(data['r...
python
def generate_graphs(data, name, results_dir): """Generate all reports from original dataframe :param dic data: dict containing raw and compiled results dataframes :param str name: name for prefixing graphs output :param str results_dir: results output directory """ graphs.resp_graph_raw(data['r...
[ "def", "generate_graphs", "(", "data", ",", "name", ",", "results_dir", ")", ":", "graphs", ".", "resp_graph_raw", "(", "data", "[", "'raw'", "]", ",", "name", "+", "'_response_times.svg'", ",", "results_dir", ")", "graphs", ".", "resp_graph", "(", "data", ...
Generate all reports from original dataframe :param dic data: dict containing raw and compiled results dataframes :param str name: name for prefixing graphs output :param str results_dir: results output directory
[ "Generate", "all", "reports", "from", "original", "dataframe" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/output.py#L12-L21
train
Generate all reports from original dataframe containing raw and compiled results
TheGhouls/oct
oct/results/output.py
print_infos
def print_infos(results): """Print informations in standard output :param ReportResults results: the report result containing all compiled informations """ print('transactions: %i' % results.total_transactions) print('timers: %i' % results.total_timers) print('errors: %i' % results.total_errors...
python
def print_infos(results): """Print informations in standard output :param ReportResults results: the report result containing all compiled informations """ print('transactions: %i' % results.total_transactions) print('timers: %i' % results.total_timers) print('errors: %i' % results.total_errors...
[ "def", "print_infos", "(", "results", ")", ":", "print", "(", "'transactions: %i'", "%", "results", ".", "total_transactions", ")", "print", "(", "'timers: %i'", "%", "results", ".", "total_timers", ")", "print", "(", "'errors: %i'", "%", "results", ".", "tota...
Print informations in standard output :param ReportResults results: the report result containing all compiled informations
[ "Print", "informations", "in", "standard", "output" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/output.py#L24-L33
train
Print informations in standard output
TheGhouls/oct
oct/results/output.py
write_template
def write_template(data, results_dir, parent): """Write the html template :param dict data: the dict containing all data for output :param str results_dir: the ouput directory for results :param str parent: the parent directory """ print("Generating html report...") partial = time.time() ...
python
def write_template(data, results_dir, parent): """Write the html template :param dict data: the dict containing all data for output :param str results_dir: the ouput directory for results :param str parent: the parent directory """ print("Generating html report...") partial = time.time() ...
[ "def", "write_template", "(", "data", ",", "results_dir", ",", "parent", ")", ":", "print", "(", "\"Generating html report...\"", ")", "partial", "=", "time", ".", "time", "(", ")", "j_env", "=", "Environment", "(", "loader", "=", "FileSystemLoader", "(", "o...
Write the html template :param dict data: the dict containing all data for output :param str results_dir: the ouput directory for results :param str parent: the parent directory
[ "Write", "the", "html", "template" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/output.py#L36-L50
train
Write the html template
TheGhouls/oct
oct/results/output.py
output
def output(results_dir, config, parent='../../'): """Write the results output for the given test :param str results_dir: the directory for the results :param dict config: the configuration of the test :param str parents: the parent directory """ start = time.time() print("Compiling results....
python
def output(results_dir, config, parent='../../'): """Write the results output for the given test :param str results_dir: the directory for the results :param dict config: the configuration of the test :param str parents: the parent directory """ start = time.time() print("Compiling results....
[ "def", "output", "(", "results_dir", ",", "config", ",", "parent", "=", "'../../'", ")", ":", "start", "=", "time", ".", "time", "(", ")", "print", "(", "\"Compiling results...\"", ")", "results_dir", "=", "os", ".", "path", ".", "abspath", "(", "results...
Write the results output for the given test :param str results_dir: the directory for the results :param dict config: the configuration of the test :param str parents: the parent directory
[ "Write", "the", "results", "output", "for", "the", "given", "test" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/output.py#L53-L91
train
Write the results output for the given test
Kortemme-Lab/klab
klab/klfilesystem.py
safeMkdir
def safeMkdir(p, permissions = permissions755): '''Wrapper around os.mkdir which does not raise an error if the directory exists.''' try: os.mkdir(p) except OSError: pass os.chmod(p, permissions)
python
def safeMkdir(p, permissions = permissions755): '''Wrapper around os.mkdir which does not raise an error if the directory exists.''' try: os.mkdir(p) except OSError: pass os.chmod(p, permissions)
[ "def", "safeMkdir", "(", "p", ",", "permissions", "=", "permissions755", ")", ":", "try", ":", "os", ".", "mkdir", "(", "p", ")", "except", "OSError", ":", "pass", "os", ".", "chmod", "(", "p", ",", "permissions", ")" ]
Wrapper around os.mkdir which does not raise an error if the directory exists.
[ "Wrapper", "around", "os", ".", "mkdir", "which", "does", "not", "raise", "an", "error", "if", "the", "directory", "exists", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/klfilesystem.py#L107-L113
train
Wrapper around os. mkdir which does not raise an error.
Kortemme-Lab/klab
klab/klfilesystem.py
getSubdirectories
def getSubdirectories(d): '''Returns a list of subdirectories in a directory. This function performed three times better for me than "for root, dirs, files in os.walk(d): return dirs" ''' return [f for f in os.listdir(d) if os.path.isdir(os.path.join(d, f)) ]
python
def getSubdirectories(d): '''Returns a list of subdirectories in a directory. This function performed three times better for me than "for root, dirs, files in os.walk(d): return dirs" ''' return [f for f in os.listdir(d) if os.path.isdir(os.path.join(d, f)) ]
[ "def", "getSubdirectories", "(", "d", ")", ":", "return", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "d", ")", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "d", ",", "f", ")", ")", "]" ]
Returns a list of subdirectories in a directory. This function performed three times better for me than "for root, dirs, files in os.walk(d): return dirs"
[ "Returns", "a", "list", "of", "subdirectories", "in", "a", "directory", ".", "This", "function", "performed", "three", "times", "better", "for", "me", "than", "for", "root", "dirs", "files", "in", "os", ".", "walk", "(", "d", ")", ":", "return", "dirs" ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/klfilesystem.py#L115-L121
train
Returns a list of subdirectories in a directory. This function performs three times better for me than return dirs
Kortemme-Lab/klab
klab/klfilesystem.py
computeMD5
def computeMD5(filepath, relativepath = ""): '''Computes an MD5 checksum. Depending on the file size, we either run the computation in Python or spawn a subprocess. The implementation is slower in Python than the tested OS but there is an overhead associated with the spawning. On my one-machine test (CentOS rele...
python
def computeMD5(filepath, relativepath = ""): '''Computes an MD5 checksum. Depending on the file size, we either run the computation in Python or spawn a subprocess. The implementation is slower in Python than the tested OS but there is an overhead associated with the spawning. On my one-machine test (CentOS rele...
[ "def", "computeMD5", "(", "filepath", ",", "relativepath", "=", "\"\"", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "filepath", ")", "checksum", "=", "None", "sz", "=", "os", ".", "path", ".", "getsize", "(", "filepath", ")", ...
Computes an MD5 checksum. Depending on the file size, we either run the computation in Python or spawn a subprocess. The implementation is slower in Python than the tested OS but there is an overhead associated with the spawning. On my one-machine test (CentOS release 5.4 final on the webserver), @2MB was where t...
[ "Computes", "an", "MD5", "checksum", ".", "Depending", "on", "the", "file", "size", "we", "either", "run", "the", "computation", "in", "Python", "or", "spawn", "a", "subprocess", ".", "The", "implementation", "is", "slower", "in", "Python", "than", "the", ...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/klfilesystem.py#L123-L152
train
Compute an MD5 checksum of a file.
projectshift/shift-boiler
boiler/cli/boiler.py
version
def version(): """ Version Imports and displays current boiler version. :return: """ echo(green('\nshift-boiler:')) echo(green('-' * 40)) echo(yellow('Version: ') + '{}'.format(boiler_version)) echo(yellow('GitHub: ') + 'https://github.com/projectshift/shift-boiler') echo(yellow(...
python
def version(): """ Version Imports and displays current boiler version. :return: """ echo(green('\nshift-boiler:')) echo(green('-' * 40)) echo(yellow('Version: ') + '{}'.format(boiler_version)) echo(yellow('GitHub: ') + 'https://github.com/projectshift/shift-boiler') echo(yellow(...
[ "def", "version", "(", ")", ":", "echo", "(", "green", "(", "'\\nshift-boiler:'", ")", ")", "echo", "(", "green", "(", "'-'", "*", "40", ")", ")", "echo", "(", "yellow", "(", "'Version: '", ")", "+", "'{}'", ".", "format", "(", "boiler_version", ")",...
Version Imports and displays current boiler version. :return:
[ "Version", "Imports", "and", "displays", "current", "boiler", "version", ".", ":", "return", ":" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/boiler.py#L21-L32
train
Version of shift - boiler
projectshift/shift-boiler
boiler/cli/boiler.py
sign_python
def sign_python(): """ Sign python (MacOS) Signing your python interpreter using self-signed certificate is used to get rid of annoying firewall questions about whether to allow incoming connections to the interpreter that happen on each app restart. This only makes sense on Mac. In order to use...
python
def sign_python(): """ Sign python (MacOS) Signing your python interpreter using self-signed certificate is used to get rid of annoying firewall questions about whether to allow incoming connections to the interpreter that happen on each app restart. This only makes sense on Mac. In order to use...
[ "def", "sign_python", "(", ")", ":", "from", "subprocess", "import", "check_output", "from", "os", "import", "system", "echo", "(", "green", "(", "'\\nSign python:'", ")", ")", "echo", "(", "green", "(", "'-'", "*", "40", ")", ")", "# get python", "python"...
Sign python (MacOS) Signing your python interpreter using self-signed certificate is used to get rid of annoying firewall questions about whether to allow incoming connections to the interpreter that happen on each app restart. This only makes sense on Mac. In order to use this command you must first cr...
[ "Sign", "python", "(", "MacOS", ")", "Signing", "your", "python", "interpreter", "using", "self", "-", "signed", "certificate", "is", "used", "to", "get", "rid", "of", "annoying", "firewall", "questions", "about", "whether", "to", "allow", "incoming", "connect...
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/boiler.py#L41-L81
train
Signs a Python interpreter using self - signed certificate
projectshift/shift-boiler
boiler/cli/boiler.py
init
def init(destination, force=False, skip=True): """ Initialise new project """ import os from uuid import uuid1 import fileinput ignores = ['.DS_Store', '__pycache__', ] echo(green('\nInitialise project:')) echo(green('-' * 40)) destination = os.path.realpath(destination) source = ...
python
def init(destination, force=False, skip=True): """ Initialise new project """ import os from uuid import uuid1 import fileinput ignores = ['.DS_Store', '__pycache__', ] echo(green('\nInitialise project:')) echo(green('-' * 40)) destination = os.path.realpath(destination) source = ...
[ "def", "init", "(", "destination", ",", "force", "=", "False", ",", "skip", "=", "True", ")", ":", "import", "os", "from", "uuid", "import", "uuid1", "import", "fileinput", "ignores", "=", "[", "'.DS_Store'", ",", "'__pycache__'", ",", "]", "echo", "(", ...
Initialise new project
[ "Initialise", "new", "project" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/boiler.py#L101-L222
train
Initialise a new project.
projectshift/shift-boiler
boiler/cli/boiler.py
install_dependencies
def install_dependencies(feature=None): """ Install dependencies for a feature """ import subprocess echo(green('\nInstall dependencies:')) echo(green('-' * 40)) req_path = os.path.realpath(os.path.dirname(__file__) + '/../_requirements') # list all features if no feature name if not feat...
python
def install_dependencies(feature=None): """ Install dependencies for a feature """ import subprocess echo(green('\nInstall dependencies:')) echo(green('-' * 40)) req_path = os.path.realpath(os.path.dirname(__file__) + '/../_requirements') # list all features if no feature name if not feat...
[ "def", "install_dependencies", "(", "feature", "=", "None", ")", ":", "import", "subprocess", "echo", "(", "green", "(", "'\\nInstall dependencies:'", ")", ")", "echo", "(", "green", "(", "'-'", "*", "40", ")", ")", "req_path", "=", "os", ".", "path", "....
Install dependencies for a feature
[ "Install", "dependencies", "for", "a", "feature" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/boiler.py#L231-L289
train
Install dependencies for a feature
Kortemme-Lab/klab
klab/bio/blast.py
BLAST.by_pdb
def by_pdb(self, pdb_id, take_top_percentile = 30.0, cut_off = None, matrix = None, sequence_identity_cut_off = None, silent = None): '''Returns a list of all PDB files which contain protein sequences similar to the protein sequences of pdb_id. Only protein chains are considered in the matching so e....
python
def by_pdb(self, pdb_id, take_top_percentile = 30.0, cut_off = None, matrix = None, sequence_identity_cut_off = None, silent = None): '''Returns a list of all PDB files which contain protein sequences similar to the protein sequences of pdb_id. Only protein chains are considered in the matching so e....
[ "def", "by_pdb", "(", "self", ",", "pdb_id", ",", "take_top_percentile", "=", "30.0", ",", "cut_off", "=", "None", ",", "matrix", "=", "None", ",", "sequence_identity_cut_off", "=", "None", ",", "silent", "=", "None", ")", ":", "self", ".", "log", "(", ...
Returns a list of all PDB files which contain protein sequences similar to the protein sequences of pdb_id. Only protein chains are considered in the matching so e.g. some results may have DNA or RNA chains or ligands while some may not.
[ "Returns", "a", "list", "of", "all", "PDB", "files", "which", "contain", "protein", "sequences", "similar", "to", "the", "protein", "sequences", "of", "pdb_id", ".", "Only", "protein", "chains", "are", "considered", "in", "the", "matching", "so", "e", ".", ...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/blast.py#L63-L89
train
Returns a list of all PDB files which contain the same protein sequences similar to the protein sequences of the given PDB ID.
Kortemme-Lab/klab
klab/bio/blast.py
BLAST._post
def _post(self, xml_query): '''POST the request.''' req = urllib2.Request(url = 'http://www.rcsb.org/pdb/rest/search', data=xml_query) f = urllib2.urlopen(req) return f.read().strip()
python
def _post(self, xml_query): '''POST the request.''' req = urllib2.Request(url = 'http://www.rcsb.org/pdb/rest/search', data=xml_query) f = urllib2.urlopen(req) return f.read().strip()
[ "def", "_post", "(", "self", ",", "xml_query", ")", ":", "req", "=", "urllib2", ".", "Request", "(", "url", "=", "'http://www.rcsb.org/pdb/rest/search'", ",", "data", "=", "xml_query", ")", "f", "=", "urllib2", ".", "urlopen", "(", "req", ")", "return", ...
POST the request.
[ "POST", "the", "request", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/blast.py#L222-L226
train
POST the request.
uogbuji/versa
tools/py/contrib/datachefids.py
simple_hashstring
def simple_hashstring(obj, bits=64): ''' Creates a simple hash in brief string form from obj bits is an optional bit width, defaulting to 64, and should be in multiples of 8 with a maximum of 64 >>> from bibframe.contrib.datachefids import simple_hashstring >>> simple_hashstring("The quick brown fo...
python
def simple_hashstring(obj, bits=64): ''' Creates a simple hash in brief string form from obj bits is an optional bit width, defaulting to 64, and should be in multiples of 8 with a maximum of 64 >>> from bibframe.contrib.datachefids import simple_hashstring >>> simple_hashstring("The quick brown fo...
[ "def", "simple_hashstring", "(", "obj", ",", "bits", "=", "64", ")", ":", "#Useful discussion of techniques here: http://stackoverflow.com/questions/1303021/shortest-hash-in-python-to-name-cache-files", "#Use MurmurHash3", "#Get a 64-bit integer, the first half of the 128-bit tuple from mmh ...
Creates a simple hash in brief string form from obj bits is an optional bit width, defaulting to 64, and should be in multiples of 8 with a maximum of 64 >>> from bibframe.contrib.datachefids import simple_hashstring >>> simple_hashstring("The quick brown fox jumps over the lazy dog") 'bBsHvHu8S-M' ...
[ "Creates", "a", "simple", "hash", "in", "brief", "string", "form", "from", "obj", "bits", "is", "an", "optional", "bit", "width", "defaulting", "to", "64", "and", "should", "be", "in", "multiples", "of", "8", "with", "a", "maximum", "of", "64" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/contrib/datachefids.py#L35-L55
train
Returns a simple hash string from obj
uogbuji/versa
tools/py/contrib/datachefids.py
create_slug
def create_slug(title, plain_len=None): ''' Tries to create a slug from a title, trading off collision risk with readability and minimized cruft title - a unicode object with a title to use as basis of the slug plain_len - the maximum character length preserved (from the beginning) of the title >>...
python
def create_slug(title, plain_len=None): ''' Tries to create a slug from a title, trading off collision risk with readability and minimized cruft title - a unicode object with a title to use as basis of the slug plain_len - the maximum character length preserved (from the beginning) of the title >>...
[ "def", "create_slug", "(", "title", ",", "plain_len", "=", "None", ")", ":", "if", "plain_len", ":", "title", "=", "title", "[", ":", "plain_len", "]", "pass1", "=", "OMIT_FROM_SLUG_PAT", ".", "sub", "(", "'_'", ",", "title", ")", ".", "lower", "(", ...
Tries to create a slug from a title, trading off collision risk with readability and minimized cruft title - a unicode object with a title to use as basis of the slug plain_len - the maximum character length preserved (from the beginning) of the title >>> from versa.contrib.datachefids import create_slug ...
[ "Tries", "to", "create", "a", "slug", "from", "a", "title", "trading", "off", "collision", "risk", "with", "readability", "and", "minimized", "cruft" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/contrib/datachefids.py#L58-L73
train
Creates a slug from a title
uogbuji/versa
tools/py/contrib/datachefids.py
slugify
def slugify(value, hyphenate=True, lower=True): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata value = unicodedata.normalize('NFKD', value).strip() replacement = '-' if hyphenate else '' if lower: value =...
python
def slugify(value, hyphenate=True, lower=True): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata value = unicodedata.normalize('NFKD', value).strip() replacement = '-' if hyphenate else '' if lower: value =...
[ "def", "slugify", "(", "value", ",", "hyphenate", "=", "True", ",", "lower", "=", "True", ")", ":", "import", "unicodedata", "value", "=", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "value", ")", ".", "strip", "(", ")", "replacement", "=", "'...
Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.
[ "Normalizes", "string", "converts", "to", "lowercase", "removes", "non", "-", "alpha", "characters", "and", "converts", "spaces", "to", "hyphens", "." ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/contrib/datachefids.py#L80-L89
train
Returns a slug of the given string.
uogbuji/versa
tools/py/contrib/datachefids.py
idgen
def idgen(idbase, tint=None, bits=64): ''' Generate an IRI as a hash of given information, or just make one up if None given idbase -- Base URI for generating links tint -- String that affects the sequence of IDs generated if sent None >>> from bibframe.contrib.datachefids import idgen >>> g = ...
python
def idgen(idbase, tint=None, bits=64): ''' Generate an IRI as a hash of given information, or just make one up if None given idbase -- Base URI for generating links tint -- String that affects the sequence of IDs generated if sent None >>> from bibframe.contrib.datachefids import idgen >>> g = ...
[ "def", "idgen", "(", "idbase", ",", "tint", "=", "None", ",", "bits", "=", "64", ")", ":", "counter", "=", "-", "1", "to_hash", "=", "None", "while", "True", ":", "if", "to_hash", "is", "None", ":", "to_hash", "=", "str", "(", "counter", ")", "if...
Generate an IRI as a hash of given information, or just make one up if None given idbase -- Base URI for generating links tint -- String that affects the sequence of IDs generated if sent None >>> from bibframe.contrib.datachefids import idgen >>> g = idgen(None) >>> next(g) #Or g.send(None) 'g...
[ "Generate", "an", "IRI", "as", "a", "hash", "of", "given", "information", "or", "just", "make", "one", "up", "if", "None", "given", "idbase", "--", "Base", "URI", "for", "generating", "links", "tint", "--", "String", "that", "affects", "the", "sequence", ...
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/contrib/datachefids.py#L96-L127
train
Generator that generates an IRI as a hash of given information.
peergradeio/flask-mongo-profiler
flask_mongo_profiler/contrib/flask_admin/formatters/profiling.py
http_method_formatter
def http_method_formatter(view, context, model, name): """Wrap HTTP method value in a bs3 label.""" method_map = { 'GET': 'label-success', 'PUT': 'label-info', 'POST': 'label-primary', 'DELETE': 'label-danger', } return Markup( '<span class="label {}">{}</span>'.f...
python
def http_method_formatter(view, context, model, name): """Wrap HTTP method value in a bs3 label.""" method_map = { 'GET': 'label-success', 'PUT': 'label-info', 'POST': 'label-primary', 'DELETE': 'label-danger', } return Markup( '<span class="label {}">{}</span>'.f...
[ "def", "http_method_formatter", "(", "view", ",", "context", ",", "model", ",", "name", ")", ":", "method_map", "=", "{", "'GET'", ":", "'label-success'", ",", "'PUT'", ":", "'label-info'", ",", "'POST'", ":", "'label-primary'", ",", "'DELETE'", ":", "'label...
Wrap HTTP method value in a bs3 label.
[ "Wrap", "HTTP", "method", "value", "in", "a", "bs3", "label", "." ]
a267eeb49fea07c9a24fb370bd9d7a90ed313ccf
https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/formatters/profiling.py#L33-L45
train
Wrap HTTP method value in a bs3 label.
peergradeio/flask-mongo-profiler
flask_mongo_profiler/contrib/flask_admin/formatters/profiling.py
profiling_request_formatter
def profiling_request_formatter(view, context, model, name): """Wrap HTTP method value in a bs3 label.""" document = model[name] return Markup( ''.join( [ '<p class="profiling-request">', '<a href="{}">'.format(document.get_admin_url(_external=True)), ...
python
def profiling_request_formatter(view, context, model, name): """Wrap HTTP method value in a bs3 label.""" document = model[name] return Markup( ''.join( [ '<p class="profiling-request">', '<a href="{}">'.format(document.get_admin_url(_external=True)), ...
[ "def", "profiling_request_formatter", "(", "view", ",", "context", ",", "model", ",", "name", ")", ":", "document", "=", "model", "[", "name", "]", "return", "Markup", "(", "''", ".", "join", "(", "[", "'<p class=\"profiling-request\">'", ",", "'<a href=\"{}\"...
Wrap HTTP method value in a bs3 label.
[ "Wrap", "HTTP", "method", "value", "in", "a", "bs3", "label", "." ]
a267eeb49fea07c9a24fb370bd9d7a90ed313ccf
https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/formatters/profiling.py#L48-L63
train
Wrap HTTP method value in a bs3 label.
peergradeio/flask-mongo-profiler
flask_mongo_profiler/contrib/flask_admin/formatters/profiling.py
profiling_query_formatter
def profiling_query_formatter(view, context, query_document, name): """Format a ProfilingQuery entry for a ProfilingRequest detail field Parameters ---------- query_document : model.ProfilingQuery """ return Markup( ''.join( [ '<div class="pymongo-query row">...
python
def profiling_query_formatter(view, context, query_document, name): """Format a ProfilingQuery entry for a ProfilingRequest detail field Parameters ---------- query_document : model.ProfilingQuery """ return Markup( ''.join( [ '<div class="pymongo-query row">...
[ "def", "profiling_query_formatter", "(", "view", ",", "context", ",", "query_document", ",", "name", ")", ":", "return", "Markup", "(", "''", ".", "join", "(", "[", "'<div class=\"pymongo-query row\">'", ",", "'<div class=\"col-md-1\">'", ",", "'<a href=\"{}\">'", "...
Format a ProfilingQuery entry for a ProfilingRequest detail field Parameters ---------- query_document : model.ProfilingQuery
[ "Format", "a", "ProfilingQuery", "entry", "for", "a", "ProfilingRequest", "detail", "field" ]
a267eeb49fea07c9a24fb370bd9d7a90ed313ccf
https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/formatters/profiling.py#L94-L127
train
Formats a ProfilingQuery entry for a ProfilingRequest detail field.
trendels/rhino
rhino/resource.py
make_response
def make_response(obj): """Try to coerce an object into a Response object.""" if obj is None: raise TypeError("Handler return value cannot be None.") if isinstance(obj, Response): return obj return Response(200, body=obj)
python
def make_response(obj): """Try to coerce an object into a Response object.""" if obj is None: raise TypeError("Handler return value cannot be None.") if isinstance(obj, Response): return obj return Response(200, body=obj)
[ "def", "make_response", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "raise", "TypeError", "(", "\"Handler return value cannot be None.\"", ")", "if", "isinstance", "(", "obj", ",", "Response", ")", ":", "return", "obj", "return", "Response", "(", "...
Try to coerce an object into a Response object.
[ "Try", "to", "coerce", "an", "object", "into", "a", "Response", "object", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/resource.py#L90-L96
train
Try to coerce an object into a Response object.
trendels/rhino
rhino/resource.py
resolve_handler
def resolve_handler(request, view_handlers): """Select a suitable handler to handle the request. Returns a (handler, vary) tuple, where handler is a handler_metadata tuple and vary is a set containing header names that were used during content negotiation and that should be included in the 'Vary' heade...
python
def resolve_handler(request, view_handlers): """Select a suitable handler to handle the request. Returns a (handler, vary) tuple, where handler is a handler_metadata tuple and vary is a set containing header names that were used during content negotiation and that should be included in the 'Vary' heade...
[ "def", "resolve_handler", "(", "request", ",", "view_handlers", ")", ":", "view", "=", "None", "if", "request", ".", "_context", ":", "# Allow context to be missing for easier testing", "route_name", "=", "request", ".", "_context", "[", "-", "1", "]", ".", "rou...
Select a suitable handler to handle the request. Returns a (handler, vary) tuple, where handler is a handler_metadata tuple and vary is a set containing header names that were used during content negotiation and that should be included in the 'Vary' header of the outgoing response. When no suitabl...
[ "Select", "a", "suitable", "handler", "to", "handle", "the", "request", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/resource.py#L99-L151
train
Select a suitable handler to handle the request.
trendels/rhino
rhino/resource.py
negotiate_content_type
def negotiate_content_type(content_type, handlers): """Filter handlers that accept a given content-type. Finds the most specific media-range that matches `content_type`, and returns those handlers that accept it. """ accepted = [h.accepts for h in handlers] scored_ranges = [(mimeparse.fitness_a...
python
def negotiate_content_type(content_type, handlers): """Filter handlers that accept a given content-type. Finds the most specific media-range that matches `content_type`, and returns those handlers that accept it. """ accepted = [h.accepts for h in handlers] scored_ranges = [(mimeparse.fitness_a...
[ "def", "negotiate_content_type", "(", "content_type", ",", "handlers", ")", ":", "accepted", "=", "[", "h", ".", "accepts", "for", "h", "in", "handlers", "]", "scored_ranges", "=", "[", "(", "mimeparse", ".", "fitness_and_quality_parsed", "(", "content_type", ...
Filter handlers that accept a given content-type. Finds the most specific media-range that matches `content_type`, and returns those handlers that accept it.
[ "Filter", "handlers", "that", "accept", "a", "given", "content", "-", "type", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/resource.py#L154-L172
train
Filter handlers that accept a given content - type and return those handlers that accept it.
trendels/rhino
rhino/resource.py
negotiate_accept
def negotiate_accept(accept, handlers): """Filter handlers that provide an acceptable mime-type. Finds the best match among handlers given an Accept header, and returns those handlers that provide the matching mime-type. """ provided = [h.provides for h in handlers] if None in provided: ...
python
def negotiate_accept(accept, handlers): """Filter handlers that provide an acceptable mime-type. Finds the best match among handlers given an Accept header, and returns those handlers that provide the matching mime-type. """ provided = [h.provides for h in handlers] if None in provided: ...
[ "def", "negotiate_accept", "(", "accept", ",", "handlers", ")", ":", "provided", "=", "[", "h", ".", "provides", "for", "h", "in", "handlers", "]", "if", "None", "in", "provided", ":", "# Not all handlers are annotated - disable content-negotiation", "# for Accept."...
Filter handlers that provide an acceptable mime-type. Finds the best match among handlers given an Accept header, and returns those handlers that provide the matching mime-type.
[ "Filter", "handlers", "that", "provide", "an", "acceptable", "mime", "-", "type", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/resource.py#L175-L199
train
Filter handlers that provide an acceptable mime - type and returns a list of handlers that provide the matching mime - type.
trendels/rhino
rhino/request.py
QueryDict.get
def get(self, key, default=None, type=None): """Returns the first value for a key. If `type` is not None, the value will be converted by calling `type` with the value as argument. If type() raises `ValueError`, it will be treated as if the value didn't exist, and `default` will be ...
python
def get(self, key, default=None, type=None): """Returns the first value for a key. If `type` is not None, the value will be converted by calling `type` with the value as argument. If type() raises `ValueError`, it will be treated as if the value didn't exist, and `default` will be ...
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ",", "type", "=", "None", ")", ":", "try", ":", "value", "=", "self", "[", "key", "]", "if", "type", "is", "not", "None", ":", "return", "type", "(", "value", ")", "return", "v...
Returns the first value for a key. If `type` is not None, the value will be converted by calling `type` with the value as argument. If type() raises `ValueError`, it will be treated as if the value didn't exist, and `default` will be returned instead.
[ "Returns", "the", "first", "value", "for", "a", "key", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L91-L105
train
Returns the first value for a key.
trendels/rhino
rhino/request.py
QueryDict.getall
def getall(self, key, type=None): """Return a list of values for the given key. If `type` is not None, all values will be converted by calling `type` with the value as argument. if type() raises `ValueError`, the value will not appear in the result list. """ values = [] ...
python
def getall(self, key, type=None): """Return a list of values for the given key. If `type` is not None, all values will be converted by calling `type` with the value as argument. if type() raises `ValueError`, the value will not appear in the result list. """ values = [] ...
[ "def", "getall", "(", "self", ",", "key", ",", "type", "=", "None", ")", ":", "values", "=", "[", "]", "for", "k", ",", "v", "in", "self", ".", "_items", ":", "if", "k", "==", "key", ":", "if", "type", "is", "not", "None", ":", "try", ":", ...
Return a list of values for the given key. If `type` is not None, all values will be converted by calling `type` with the value as argument. if type() raises `ValueError`, the value will not appear in the result list.
[ "Return", "a", "list", "of", "values", "for", "the", "given", "key", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L107-L124
train
Return a list of values for the given key.
trendels/rhino
rhino/request.py
Request.url_for
def url_for(*args, **kw): """Build the URL for a target route. The target is the first positional argument, and can be any valid target for `Mapper.path`, which will be looked up on the current mapper object and used to build the URL for that route. Additionally, it can be one o...
python
def url_for(*args, **kw): """Build the URL for a target route. The target is the first positional argument, and can be any valid target for `Mapper.path`, which will be looked up on the current mapper object and used to build the URL for that route. Additionally, it can be one o...
[ "def", "url_for", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "# Allow passing 'self' as named parameter", "self", ",", "target", ",", "args", "=", "args", "[", "0", "]", ",", "args", "[", "1", "]", ",", "list", "(", "args", "[", "2", ":", "]"...
Build the URL for a target route. The target is the first positional argument, and can be any valid target for `Mapper.path`, which will be looked up on the current mapper object and used to build the URL for that route. Additionally, it can be one of: '.' : Builds th...
[ "Build", "the", "URL", "for", "a", "target", "route", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L220-L268
train
Builds the URL for a named route.
trendels/rhino
rhino/request.py
Request.query
def query(self): """A QueryDict object holding the query parameters (QUERY_STRING).""" if self._query is None: query_string = self.environ.get('QUERY_STRING') self._query = QueryDict([ (k.decode('utf-8'), v.decode('utf-8')) for k, v in urlparse.par...
python
def query(self): """A QueryDict object holding the query parameters (QUERY_STRING).""" if self._query is None: query_string = self.environ.get('QUERY_STRING') self._query = QueryDict([ (k.decode('utf-8'), v.decode('utf-8')) for k, v in urlparse.par...
[ "def", "query", "(", "self", ")", ":", "if", "self", ".", "_query", "is", "None", ":", "query_string", "=", "self", ".", "environ", ".", "get", "(", "'QUERY_STRING'", ")", "self", ".", "_query", "=", "QueryDict", "(", "[", "(", "k", ".", "decode", ...
A QueryDict object holding the query parameters (QUERY_STRING).
[ "A", "QueryDict", "object", "holding", "the", "query", "parameters", "(", "QUERY_STRING", ")", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L286-L295
train
A QueryDict object holding the query parameters.
trendels/rhino
rhino/request.py
Request.url
def url(self): """The reconstructed request URL (absolute).""" if self._url is None: self._url = request_uri(self.environ, include_query=1) return self._url
python
def url(self): """The reconstructed request URL (absolute).""" if self._url is None: self._url = request_uri(self.environ, include_query=1) return self._url
[ "def", "url", "(", "self", ")", ":", "if", "self", ".", "_url", "is", "None", ":", "self", ".", "_url", "=", "request_uri", "(", "self", ".", "environ", ",", "include_query", "=", "1", ")", "return", "self", ".", "_url" ]
The reconstructed request URL (absolute).
[ "The", "reconstructed", "request", "URL", "(", "absolute", ")", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L298-L302
train
The reconstructed request URL ( absolute ).
trendels/rhino
rhino/request.py
Request.application_uri
def application_uri(self): """The base URI of the application (wsgiref.util.application_uri).""" if self._application_uri is None: self._application_uri = application_uri(self.environ) return self._application_uri
python
def application_uri(self): """The base URI of the application (wsgiref.util.application_uri).""" if self._application_uri is None: self._application_uri = application_uri(self.environ) return self._application_uri
[ "def", "application_uri", "(", "self", ")", ":", "if", "self", ".", "_application_uri", "is", "None", ":", "self", ".", "_application_uri", "=", "application_uri", "(", "self", ".", "environ", ")", "return", "self", ".", "_application_uri" ]
The base URI of the application (wsgiref.util.application_uri).
[ "The", "base", "URI", "of", "the", "application", "(", "wsgiref", ".", "util", ".", "application_uri", ")", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L305-L309
train
The base URI of the application.
trendels/rhino
rhino/request.py
Request.input
def input(self): """Returns a file-like object representing the request body.""" if self._input is None: input_file = self.environ['wsgi.input'] content_length = self.content_length or 0 self._input = WsgiInput(input_file, self.content_length) return self._inp...
python
def input(self): """Returns a file-like object representing the request body.""" if self._input is None: input_file = self.environ['wsgi.input'] content_length = self.content_length or 0 self._input = WsgiInput(input_file, self.content_length) return self._inp...
[ "def", "input", "(", "self", ")", ":", "if", "self", ".", "_input", "is", "None", ":", "input_file", "=", "self", ".", "environ", "[", "'wsgi.input'", "]", "content_length", "=", "self", ".", "content_length", "or", "0", "self", ".", "_input", "=", "Ws...
Returns a file-like object representing the request body.
[ "Returns", "a", "file", "-", "like", "object", "representing", "the", "request", "body", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L364-L370
train
Returns a file - like object representing the request body.
trendels/rhino
rhino/request.py
Request.body
def body(self): """Reads and returns the entire request body. On first access, reads `content_length` bytes from `input` and stores the result on the request object. On subsequent access, returns the cached value. """ if self._body is None: if self._body_read...
python
def body(self): """Reads and returns the entire request body. On first access, reads `content_length` bytes from `input` and stores the result on the request object. On subsequent access, returns the cached value. """ if self._body is None: if self._body_read...
[ "def", "body", "(", "self", ")", ":", "if", "self", ".", "_body", "is", "None", ":", "if", "self", ".", "_body_reader", "is", "None", ":", "self", ".", "_body", "=", "self", ".", "input", ".", "read", "(", "self", ".", "content_length", "or", "0", ...
Reads and returns the entire request body. On first access, reads `content_length` bytes from `input` and stores the result on the request object. On subsequent access, returns the cached value.
[ "Reads", "and", "returns", "the", "entire", "request", "body", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L373-L385
train
Reads and returns the entire request body.
trendels/rhino
rhino/request.py
Request.form
def form(self): """Reads the request body and tries to parse it as a web form. Parsing is done using the stdlib's `cgi.FieldStorage` class which supports multipart forms (file uploads). Returns a `QueryDict` object holding the form fields. Uploaded files are represented as form ...
python
def form(self): """Reads the request body and tries to parse it as a web form. Parsing is done using the stdlib's `cgi.FieldStorage` class which supports multipart forms (file uploads). Returns a `QueryDict` object holding the form fields. Uploaded files are represented as form ...
[ "def", "form", "(", "self", ")", ":", "if", "self", ".", "_form", "is", "None", ":", "# Make sure FieldStorage always parses the form content,", "# and never the query string.", "environ", "=", "self", ".", "environ", ".", "copy", "(", ")", "environ", "[", "'QUERY...
Reads the request body and tries to parse it as a web form. Parsing is done using the stdlib's `cgi.FieldStorage` class which supports multipart forms (file uploads). Returns a `QueryDict` object holding the form fields. Uploaded files are represented as form fields with a 'filename' at...
[ "Reads", "the", "request", "body", "and", "tries", "to", "parse", "it", "as", "a", "web", "form", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L389-L418
train
Reads the request body and parses it as a web form.
trendels/rhino
rhino/request.py
Request.cookies
def cookies(self): """Returns a dictionary mapping cookie names to their values.""" if self._cookies is None: c = SimpleCookie(self.environ.get('HTTP_COOKIE')) self._cookies = dict([ (k.decode('utf-8'), v.value.decode('utf-8')) for k, v in c.items(...
python
def cookies(self): """Returns a dictionary mapping cookie names to their values.""" if self._cookies is None: c = SimpleCookie(self.environ.get('HTTP_COOKIE')) self._cookies = dict([ (k.decode('utf-8'), v.value.decode('utf-8')) for k, v in c.items(...
[ "def", "cookies", "(", "self", ")", ":", "if", "self", ".", "_cookies", "is", "None", ":", "c", "=", "SimpleCookie", "(", "self", ".", "environ", ".", "get", "(", "'HTTP_COOKIE'", ")", ")", "self", ".", "_cookies", "=", "dict", "(", "[", "(", "k", ...
Returns a dictionary mapping cookie names to their values.
[ "Returns", "a", "dictionary", "mapping", "cookie", "names", "to", "their", "values", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/request.py#L421-L429
train
Returns a dictionary mapping cookie names to their values.
reillysiemens/layabout
layabout.py
_format_parameter_error_message
def _format_parameter_error_message(name: str, sig: Signature, num_params: int) -> str: """ Format an error message for missing positional arguments. Args: name: The function name. sig: The function's signature. num_params: The number of function ...
python
def _format_parameter_error_message(name: str, sig: Signature, num_params: int) -> str: """ Format an error message for missing positional arguments. Args: name: The function name. sig: The function's signature. num_params: The number of function ...
[ "def", "_format_parameter_error_message", "(", "name", ":", "str", ",", "sig", ":", "Signature", ",", "num_params", ":", "int", ")", "->", "str", ":", "if", "num_params", "==", "0", ":", "plural", "=", "'s'", "missing", "=", "2", "arguments", "=", "\"'sl...
Format an error message for missing positional arguments. Args: name: The function name. sig: The function's signature. num_params: The number of function parameters. Returns: str: A formatted error message.
[ "Format", "an", "error", "message", "for", "missing", "positional", "arguments", "." ]
a146c47f2558e66bb51cf708d39909b93eaea7f4
https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L252-L275
train
Format an error message for missing positional arguments.
reillysiemens/layabout
layabout.py
_create_slack_with_env_var
def _create_slack_with_env_var(env_var: EnvVar) -> SlackClient: """ Create a :obj:`SlackClient` with a token from an env var. """ token = os.getenv(env_var) if token: return SlackClient(token=token) raise MissingToken(f"Could not acquire token from {env_var}")
python
def _create_slack_with_env_var(env_var: EnvVar) -> SlackClient: """ Create a :obj:`SlackClient` with a token from an env var. """ token = os.getenv(env_var) if token: return SlackClient(token=token) raise MissingToken(f"Could not acquire token from {env_var}")
[ "def", "_create_slack_with_env_var", "(", "env_var", ":", "EnvVar", ")", "->", "SlackClient", ":", "token", "=", "os", ".", "getenv", "(", "env_var", ")", "if", "token", ":", "return", "SlackClient", "(", "token", "=", "token", ")", "raise", "MissingToken", ...
Create a :obj:`SlackClient` with a token from an env var.
[ "Create", "a", ":", "obj", ":", "SlackClient", "with", "a", "token", "from", "an", "env", "var", "." ]
a146c47f2558e66bb51cf708d39909b93eaea7f4
https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L291-L296
train
Create a SlackClient with a token from an env var.
reillysiemens/layabout
layabout.py
_create_slack_with_token
def _create_slack_with_token(token: Token) -> SlackClient: """ Create a :obj:`SlackClient` with a provided token. """ if token != Token(''): return SlackClient(token=token) raise MissingToken("The empty string is an invalid Slack API token")
python
def _create_slack_with_token(token: Token) -> SlackClient: """ Create a :obj:`SlackClient` with a provided token. """ if token != Token(''): return SlackClient(token=token) raise MissingToken("The empty string is an invalid Slack API token")
[ "def", "_create_slack_with_token", "(", "token", ":", "Token", ")", "->", "SlackClient", ":", "if", "token", "!=", "Token", "(", "''", ")", ":", "return", "SlackClient", "(", "token", "=", "token", ")", "raise", "MissingToken", "(", "\"The empty string is an i...
Create a :obj:`SlackClient` with a provided token.
[ "Create", "a", ":", "obj", ":", "SlackClient", "with", "a", "provided", "token", "." ]
a146c47f2558e66bb51cf708d39909b93eaea7f4
https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L300-L304
train
Create a SlackClient with a provided token.
reillysiemens/layabout
layabout.py
_SlackClientWrapper.connect_with_retry
def connect_with_retry(self) -> None: """ Attempt to connect to the Slack API. Retry on failures. """ if self.is_connected(): log.debug('Already connected to the Slack API') return for retry in range(1, self.retries + 1): self.connect() if self.is...
python
def connect_with_retry(self) -> None: """ Attempt to connect to the Slack API. Retry on failures. """ if self.is_connected(): log.debug('Already connected to the Slack API') return for retry in range(1, self.retries + 1): self.connect() if self.is...
[ "def", "connect_with_retry", "(", "self", ")", "->", "None", ":", "if", "self", ".", "is_connected", "(", ")", ":", "log", ".", "debug", "(", "'Already connected to the Slack API'", ")", "return", "for", "retry", "in", "range", "(", "1", ",", "self", ".", ...
Attempt to connect to the Slack API. Retry on failures.
[ "Attempt", "to", "connect", "to", "the", "Slack", "API", ".", "Retry", "on", "failures", "." ]
a146c47f2558e66bb51cf708d39909b93eaea7f4
https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L78-L94
train
Attempts to connect to the Slack API. Retry on failures.
reillysiemens/layabout
layabout.py
_SlackClientWrapper.fetch_events
def fetch_events(self) -> List[dict]: """ Fetch new RTM events from the API. """ try: return self.inner.rtm_read() # TODO: The TimeoutError could be more elegantly resolved by making # a PR to the websocket-client library and letting them coerce that # exception to a...
python
def fetch_events(self) -> List[dict]: """ Fetch new RTM events from the API. """ try: return self.inner.rtm_read() # TODO: The TimeoutError could be more elegantly resolved by making # a PR to the websocket-client library and letting them coerce that # exception to a...
[ "def", "fetch_events", "(", "self", ")", "->", "List", "[", "dict", "]", ":", "try", ":", "return", "self", ".", "inner", ".", "rtm_read", "(", ")", "# TODO: The TimeoutError could be more elegantly resolved by making", "# a PR to the websocket-client library and letting ...
Fetch new RTM events from the API.
[ "Fetch", "new", "RTM", "events", "from", "the", "API", "." ]
a146c47f2558e66bb51cf708d39909b93eaea7f4
https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L96-L109
train
Fetch RTM events from the API.
reillysiemens/layabout
layabout.py
Layabout.handle
def handle(self, type: str, *, kwargs: dict = None) -> Callable: """ Register an event handler with the :obj:`Layabout` instance. Args: type: The name of a Slack RTM API event to be handled. As a special case, although it is not a proper RTM event, ``*`` may ...
python
def handle(self, type: str, *, kwargs: dict = None) -> Callable: """ Register an event handler with the :obj:`Layabout` instance. Args: type: The name of a Slack RTM API event to be handled. As a special case, although it is not a proper RTM event, ``*`` may ...
[ "def", "handle", "(", "self", ",", "type", ":", "str", ",", "*", ",", "kwargs", ":", "dict", "=", "None", ")", "->", "Callable", ":", "def", "decorator", "(", "fn", ":", "Callable", ")", "->", "Callable", ":", "# Validate that the wrapped callable is a sui...
Register an event handler with the :obj:`Layabout` instance. Args: type: The name of a Slack RTM API event to be handled. As a special case, although it is not a proper RTM event, ``*`` may be provided to handle all events. For more information about ...
[ "Register", "an", "event", "handler", "with", "the", ":", "obj", ":", "Layabout", "instance", "." ]
a146c47f2558e66bb51cf708d39909b93eaea7f4
https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L143-L175
train
Decorator that registers a callable as a suitable event handler.
reillysiemens/layabout
layabout.py
Layabout._ensure_slack
def _ensure_slack(self, connector: Any, retries: int, backoff: Callable[[int], float]) -> None: """ Ensure we have a SlackClient. """ connector = self._env_var if connector is None else connector slack: SlackClient = _create_slack(connector) self._slack = _SlackClie...
python
def _ensure_slack(self, connector: Any, retries: int, backoff: Callable[[int], float]) -> None: """ Ensure we have a SlackClient. """ connector = self._env_var if connector is None else connector slack: SlackClient = _create_slack(connector) self._slack = _SlackClie...
[ "def", "_ensure_slack", "(", "self", ",", "connector", ":", "Any", ",", "retries", ":", "int", ",", "backoff", ":", "Callable", "[", "[", "int", "]", ",", "float", "]", ")", "->", "None", ":", "connector", "=", "self", ".", "_env_var", "if", "connect...
Ensure we have a SlackClient.
[ "Ensure", "we", "have", "a", "SlackClient", "." ]
a146c47f2558e66bb51cf708d39909b93eaea7f4
https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L177-L186
train
Ensure we have a SlackClient.
reillysiemens/layabout
layabout.py
Layabout.run
def run(self, *, connector: Union[EnvVar, Token, SlackClient, None] = None, interval: float = 0.5, retries: int = 16, backoff: Callable[[int], float] = None, until: Callable[[List[dict]], bool] = None) -> None: """ Connect to the Slack API and run the even...
python
def run(self, *, connector: Union[EnvVar, Token, SlackClient, None] = None, interval: float = 0.5, retries: int = 16, backoff: Callable[[int], float] = None, until: Callable[[List[dict]], bool] = None) -> None: """ Connect to the Slack API and run the even...
[ "def", "run", "(", "self", ",", "*", ",", "connector", ":", "Union", "[", "EnvVar", ",", "Token", ",", "SlackClient", ",", "None", "]", "=", "None", ",", "interval", ":", "float", "=", "0.5", ",", "retries", ":", "int", "=", "16", ",", "backoff", ...
Connect to the Slack API and run the event handler loop. Args: connector: A means of connecting to the Slack API. This can be an API :obj:`Token`, an :obj:`EnvVar` from which a token can be retrieved, or an established :obj:`SlackClient` instance. If ...
[ "Connect", "to", "the", "Slack", "API", "and", "run", "the", "event", "handler", "loop", "." ]
a146c47f2558e66bb51cf708d39909b93eaea7f4
https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/layabout.py#L188-L249
train
Runs the event handler loop.
cozy/python_cozy_management
cozy_management/weboob.py
install
def install(): ''' Install weboob system-wide ''' tmp_weboob_dir = '/tmp/weboob' # Check that the directory does not already exists while (os.path.exists(tmp_weboob_dir)): tmp_weboob_dir += '1' # Clone the repository print 'Fetching sources in temporary dir {}'.format(tmp_w...
python
def install(): ''' Install weboob system-wide ''' tmp_weboob_dir = '/tmp/weboob' # Check that the directory does not already exists while (os.path.exists(tmp_weboob_dir)): tmp_weboob_dir += '1' # Clone the repository print 'Fetching sources in temporary dir {}'.format(tmp_w...
[ "def", "install", "(", ")", ":", "tmp_weboob_dir", "=", "'/tmp/weboob'", "# Check that the directory does not already exists", "while", "(", "os", ".", "path", ".", "exists", "(", "tmp_weboob_dir", ")", ")", ":", "tmp_weboob_dir", "+=", "'1'", "# Clone the repository"...
Install weboob system-wide
[ "Install", "weboob", "system", "-", "wide" ]
820cea58458ae3e067fa8cc2da38edbda4681dac
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/weboob.py#L32-L72
train
Installs the weboob system - wide wevables in a temporary directory.
uogbuji/versa
tools/py/driver/memory.py
connection.copy
def copy(self, contents=True): '''Create a copy of this model, optionally without contents (i.e. just configuration)''' cp = connection(self._baseiri, self._attr_cls, self._logger) if contents: cp.add_many(self._relationships) return cp
python
def copy(self, contents=True): '''Create a copy of this model, optionally without contents (i.e. just configuration)''' cp = connection(self._baseiri, self._attr_cls, self._logger) if contents: cp.add_many(self._relationships) return cp
[ "def", "copy", "(", "self", ",", "contents", "=", "True", ")", ":", "cp", "=", "connection", "(", "self", ".", "_baseiri", ",", "self", ".", "_attr_cls", ",", "self", ".", "_logger", ")", "if", "contents", ":", "cp", ".", "add_many", "(", "self", "...
Create a copy of this model, optionally without contents (i.e. just configuration)
[ "Create", "a", "copy", "of", "this", "model", "optionally", "without", "contents", "(", "i", ".", "e", ".", "just", "configuration", ")" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/memory.py#L36-L41
train
Create a copy of this model optionally without contents ( i. e. just configuration )
uogbuji/versa
tools/py/driver/memory.py
connection.match
def match(self, origin=None, rel=None, target=None, attrs=None, include_ids=False): ''' Iterator over relationship IDs that match a pattern of components origin - (optional) origin of the relationship (similar to an RDF subject). If omitted any origin will be matched. rel - (optional) t...
python
def match(self, origin=None, rel=None, target=None, attrs=None, include_ids=False): ''' Iterator over relationship IDs that match a pattern of components origin - (optional) origin of the relationship (similar to an RDF subject). If omitted any origin will be matched. rel - (optional) t...
[ "def", "match", "(", "self", ",", "origin", "=", "None", ",", "rel", "=", "None", ",", "target", "=", "None", ",", "attrs", "=", "None", ",", "include_ids", "=", "False", ")", ":", "#Can't use items or we risk client side RuntimeError: dictionary changed size duri...
Iterator over relationship IDs that match a pattern of components origin - (optional) origin of the relationship (similar to an RDF subject). If omitted any origin will be matched. rel - (optional) type IRI of the relationship (similar to an RDF predicate). If omitted any relationship will be matched. ...
[ "Iterator", "over", "relationship", "IDs", "that", "match", "a", "pattern", "of", "components" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/memory.py#L67-L98
train
Yields the set of identifiers that match a pattern of components of components.
uogbuji/versa
tools/py/driver/memory.py
connection.add
def add(self, origin, rel, target, attrs=None, index=None): ''' Add one relationship to the extent origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an ...
python
def add(self, origin, rel, target, attrs=None, index=None): ''' Add one relationship to the extent origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an ...
[ "def", "add", "(", "self", ",", "origin", ",", "rel", ",", "target", ",", "attrs", "=", "None", ",", "index", "=", "None", ")", ":", "#FIXME: return an ID (IRI) for the resulting relationship?", "if", "not", "origin", ":", "raise", "ValueError", "(", "'Relatio...
Add one relationship to the extent origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an RDF object), a boolean, floating point or unicode object attrs - optiona...
[ "Add", "one", "relationship", "to", "the", "extent" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/memory.py#L135-L166
train
Add one relationship to the extent
uogbuji/versa
tools/py/driver/memory.py
connection.add_many
def add_many(self, rels): ''' Add a list of relationships to the extent rels - a list of 0 or more relationship tuples, e.g.: [ (origin, rel, target, {attrname1: attrval1, attrname2: attrval2}), ] origin - origin of the relationship (similar to an RDF subjec...
python
def add_many(self, rels): ''' Add a list of relationships to the extent rels - a list of 0 or more relationship tuples, e.g.: [ (origin, rel, target, {attrname1: attrval1, attrname2: attrval2}), ] origin - origin of the relationship (similar to an RDF subjec...
[ "def", "add_many", "(", "self", ",", "rels", ")", ":", "for", "curr_rel", "in", "rels", ":", "attrs", "=", "self", ".", "_attr_cls", "(", ")", "if", "len", "(", "curr_rel", ")", "==", "2", ":", "# handle __iter__ output for copy()", "origin", ",", "rel",...
Add a list of relationships to the extent rels - a list of 0 or more relationship tuples, e.g.: [ (origin, rel, target, {attrname1: attrval1, attrname2: attrval2}), ] origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship ...
[ "Add", "a", "list", "of", "relationships", "to", "the", "extent" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/memory.py#L168-L196
train
Add a list of relationships to the extent.
TUNE-Archive/freight_forwarder
freight_forwarder/cli/quality_control.py
QualityControlCommand._quality_control
def _quality_control(self, args, **extra_args): """ Export is the entry point for exporting docker images. """ if not isinstance(args, argparse.Namespace): raise Exception("args should of an instance of argparse.Namespace") # create new freight forwarder object ...
python
def _quality_control(self, args, **extra_args): """ Export is the entry point for exporting docker images. """ if not isinstance(args, argparse.Namespace): raise Exception("args should of an instance of argparse.Namespace") # create new freight forwarder object ...
[ "def", "_quality_control", "(", "self", ",", "args", ",", "*", "*", "extra_args", ")", ":", "if", "not", "isinstance", "(", "args", ",", "argparse", ".", "Namespace", ")", ":", "raise", "Exception", "(", "\"args should of an instance of argparse.Namespace\"", ")...
Export is the entry point for exporting docker images.
[ "Export", "is", "the", "entry", "point", "for", "exporting", "docker", "images", "." ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/cli/quality_control.py#L96-L130
train
This function is called by the daemon to export docker images.
ronhanson/python-tbx
tbx/process.py
restart_program
def restart_program(): """ Restarts the current program. Note: this function does not return. Any cleanup action (like saving data) must be done before calling this function. """ logging.debug("Restarting program...") python = sys.executable os.execl(python, python, * sys.argv)
python
def restart_program(): """ Restarts the current program. Note: this function does not return. Any cleanup action (like saving data) must be done before calling this function. """ logging.debug("Restarting program...") python = sys.executable os.execl(python, python, * sys.argv)
[ "def", "restart_program", "(", ")", ":", "logging", ".", "debug", "(", "\"Restarting program...\"", ")", "python", "=", "sys", ".", "executable", "os", ".", "execl", "(", "python", ",", "python", ",", "*", "sys", ".", "argv", ")" ]
Restarts the current program. Note: this function does not return. Any cleanup action (like saving data) must be done before calling this function.
[ "Restarts", "the", "current", "program", ".", "Note", ":", "this", "function", "does", "not", "return", ".", "Any", "cleanup", "action", "(", "like", "saving", "data", ")", "must", "be", "done", "before", "calling", "this", "function", "." ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/process.py#L27-L35
train
Restarts the current program.
ronhanson/python-tbx
tbx/process.py
synchronized
def synchronized(lock): """ Synchronization decorator; provide thread-safe locking on a function http://code.activestate.com/recipes/465057/ """ def wrap(f): def synchronize(*args, **kw): lock.acquire() try: return f(*args, **kw) finally: ...
python
def synchronized(lock): """ Synchronization decorator; provide thread-safe locking on a function http://code.activestate.com/recipes/465057/ """ def wrap(f): def synchronize(*args, **kw): lock.acquire() try: return f(*args, **kw) finally: ...
[ "def", "synchronized", "(", "lock", ")", ":", "def", "wrap", "(", "f", ")", ":", "def", "synchronize", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "lock", ".", "acquire", "(", ")", "try", ":", "return", "f", "(", "*", "args", ",", "*", "...
Synchronization decorator; provide thread-safe locking on a function http://code.activestate.com/recipes/465057/
[ "Synchronization", "decorator", ";", "provide", "thread", "-", "safe", "locking", "on", "a", "function", "http", ":", "//", "code", ".", "activestate", ".", "com", "/", "recipes", "/", "465057", "/" ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/process.py#L38-L51
train
A synchronization decorator that provides thread - safe locking on a function .
ronhanson/python-tbx
tbx/process.py
call_repeatedly
def call_repeatedly(func, interval, *args, **kwargs): """ Call a function at interval Returns both the thread object and the loop stopper Event. """ main_thead = threading.current_thread() stopped = threading.Event() def loop(): while not stopped.wait(interval) and main_thead.is_ali...
python
def call_repeatedly(func, interval, *args, **kwargs): """ Call a function at interval Returns both the thread object and the loop stopper Event. """ main_thead = threading.current_thread() stopped = threading.Event() def loop(): while not stopped.wait(interval) and main_thead.is_ali...
[ "def", "call_repeatedly", "(", "func", ",", "interval", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "main_thead", "=", "threading", ".", "current_thread", "(", ")", "stopped", "=", "threading", ".", "Event", "(", ")", "def", "loop", "(", ")", ...
Call a function at interval Returns both the thread object and the loop stopper Event.
[ "Call", "a", "function", "at", "interval", "Returns", "both", "the", "thread", "object", "and", "the", "loop", "stopper", "Event", "." ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/process.py#L54-L73
train
Call a function at interval returns a thread object and the loop stopper Event.
ronhanson/python-tbx
tbx/process.py
synchronized_limit
def synchronized_limit(lock): """ Synchronization decorator; provide thread-safe locking on a function http://code.activestate.com/recipes/465057/ """ def wrap(f): def synchronize(*args, **kw): if lock[1] < 10: lock[1] += 1 lock[0].acquire() ...
python
def synchronized_limit(lock): """ Synchronization decorator; provide thread-safe locking on a function http://code.activestate.com/recipes/465057/ """ def wrap(f): def synchronize(*args, **kw): if lock[1] < 10: lock[1] += 1 lock[0].acquire() ...
[ "def", "synchronized_limit", "(", "lock", ")", ":", "def", "wrap", "(", "f", ")", ":", "def", "synchronize", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "lock", "[", "1", "]", "<", "10", ":", "lock", "[", "1", "]", "+=", "1", "lock...
Synchronization decorator; provide thread-safe locking on a function http://code.activestate.com/recipes/465057/
[ "Synchronization", "decorator", ";", "provide", "thread", "-", "safe", "locking", "on", "a", "function", "http", ":", "//", "code", ".", "activestate", ".", "com", "/", "recipes", "/", "465057", "/" ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/process.py#L76-L94
train
Decorator that provides thread - safe locking on a function
ronhanson/python-tbx
tbx/process.py
execute
def execute(command, return_output=True, log_file=None, log_settings=None, error_logfile=None, timeout=None, line_function=None, poll_timing = 0.01, logger=None, working_folder=None, env=None): """ Execute a program and logs standard output into a file. :param return_output: returns the STDOUT...
python
def execute(command, return_output=True, log_file=None, log_settings=None, error_logfile=None, timeout=None, line_function=None, poll_timing = 0.01, logger=None, working_folder=None, env=None): """ Execute a program and logs standard output into a file. :param return_output: returns the STDOUT...
[ "def", "execute", "(", "command", ",", "return_output", "=", "True", ",", "log_file", "=", "None", ",", "log_settings", "=", "None", ",", "error_logfile", "=", "None", ",", "timeout", "=", "None", ",", "line_function", "=", "None", ",", "poll_timing", "=",...
Execute a program and logs standard output into a file. :param return_output: returns the STDOUT value if True or returns the return code :param logfile: path where log file should be written ( displayed on STDOUT if not set) :param error_logfile: path where error log file ...
[ "Execute", "a", "program", "and", "logs", "standard", "output", "into", "a", "file", "." ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/process.py#L97-L195
train
Execute a command and return the return code.
ronhanson/python-tbx
tbx/process.py
daemonize
def daemonize(umask=0, work_dir="/", max_fd=1024, redirect="/dev/null"): """ When this function is called, the process is daemonized (by forking + killing its parent). It becomes a background task. It is useful to release the console. """ if not redirect: redirect = "/dev/null" if h...
python
def daemonize(umask=0, work_dir="/", max_fd=1024, redirect="/dev/null"): """ When this function is called, the process is daemonized (by forking + killing its parent). It becomes a background task. It is useful to release the console. """ if not redirect: redirect = "/dev/null" if h...
[ "def", "daemonize", "(", "umask", "=", "0", ",", "work_dir", "=", "\"/\"", ",", "max_fd", "=", "1024", ",", "redirect", "=", "\"/dev/null\"", ")", ":", "if", "not", "redirect", ":", "redirect", "=", "\"/dev/null\"", "if", "hasattr", "(", "os", ",", "\"...
When this function is called, the process is daemonized (by forking + killing its parent). It becomes a background task. It is useful to release the console.
[ "When", "this", "function", "is", "called", "the", "process", "is", "daemonized", "(", "by", "forking", "+", "killing", "its", "parent", ")", ".", "It", "becomes", "a", "background", "task", ".", "It", "is", "useful", "to", "release", "the", "console", "...
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/process.py#L198-L256
train
Daemonize the current process.
Kortemme-Lab/klab
klab/stats/dataframe.py
DatasetDataFrame.log
def log(self, msg, lvl = 0): '''Log messages according to the logging level (0 is highest priority).''' if self.log_level >= lvl: self.log_fn(msg)
python
def log(self, msg, lvl = 0): '''Log messages according to the logging level (0 is highest priority).''' if self.log_level >= lvl: self.log_fn(msg)
[ "def", "log", "(", "self", ",", "msg", ",", "lvl", "=", "0", ")", ":", "if", "self", ".", "log_level", ">=", "lvl", ":", "self", ".", "log_fn", "(", "msg", ")" ]
Log messages according to the logging level (0 is highest priority).
[ "Log", "messages", "according", "to", "the", "logging", "level", "(", "0", "is", "highest", "priority", ")", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/stats/dataframe.py#L230-L233
train
Log messages according to the logging level.
Kortemme-Lab/klab
klab/stats/dataframe.py
DatasetDataFrame.get_series_names
def get_series_names(self, column_indices = [], column_names = []): '''Returns the series' names corresponding to column_indices and column_names. "names" here are: - strings for single-indexed dataframes; or - tuples for multi-indexed dataframes. If both param...
python
def get_series_names(self, column_indices = [], column_names = []): '''Returns the series' names corresponding to column_indices and column_names. "names" here are: - strings for single-indexed dataframes; or - tuples for multi-indexed dataframes. If both param...
[ "def", "get_series_names", "(", "self", ",", "column_indices", "=", "[", "]", ",", "column_names", "=", "[", "]", ")", ":", "n", "=", "[", "]", "if", "not", "column_indices", "and", "not", "column_names", ":", "for", "k", ",", "v", "in", "sorted", "(...
Returns the series' names corresponding to column_indices and column_names. "names" here are: - strings for single-indexed dataframes; or - tuples for multi-indexed dataframes. If both parameters are empty then all column names are returned.
[ "Returns", "the", "series", "names", "corresponding", "to", "column_indices", "and", "column_names", ".", "names", "here", "are", ":", "-", "strings", "for", "single", "-", "indexed", "dataframes", ";", "or", "-", "tuples", "for", "multi", "-", "indexed", "d...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/stats/dataframe.py#L236-L255
train
Returns the series names corresponding to column_indices and column_names.
Kortemme-Lab/klab
klab/stats/dataframe.py
DatasetDataFrame._analyze
def _analyze(self): '''Run-once function to generate analysis over all series, considering both full and partial data. Initializes the self.analysis dict which maps: (non-reference) column/series -> 'full' and/or 'partial' -> stats dict returned by get_xy_dataset_statistics '''...
python
def _analyze(self): '''Run-once function to generate analysis over all series, considering both full and partial data. Initializes the self.analysis dict which maps: (non-reference) column/series -> 'full' and/or 'partial' -> stats dict returned by get_xy_dataset_statistics '''...
[ "def", "_analyze", "(", "self", ")", ":", "if", "not", "self", ".", "analysis", ":", "for", "dseries", "in", "self", ".", "data_series", ":", "# Count number of non-NaN rows", "dseries_count", "=", "self", ".", "df", "[", "dseries", "]", ".", "count", "(",...
Run-once function to generate analysis over all series, considering both full and partial data. Initializes the self.analysis dict which maps: (non-reference) column/series -> 'full' and/or 'partial' -> stats dict returned by get_xy_dataset_statistics
[ "Run", "-", "once", "function", "to", "generate", "analysis", "over", "all", "series", "considering", "both", "full", "and", "partial", "data", ".", "Initializes", "the", "self", ".", "analysis", "dict", "which", "maps", ":", "(", "non", "-", "reference", ...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/stats/dataframe.py#L258-L297
train
Run - once function to generate analysis over all series and store the results for the common records in the self. analysis dictionary.
Kortemme-Lab/klab
klab/stats/dataframe.py
DatasetDataFrame.tabulate
def tabulate(self, restricted_predicted_column_indices = [], restricted_predicted_column_names = [], dataset_name = None): '''Returns summary analysis from the dataframe as a DataTable object. DataTables are wrapped pandas dataframes which can be combined if the have the same width. This is useful fo...
python
def tabulate(self, restricted_predicted_column_indices = [], restricted_predicted_column_names = [], dataset_name = None): '''Returns summary analysis from the dataframe as a DataTable object. DataTables are wrapped pandas dataframes which can be combined if the have the same width. This is useful fo...
[ "def", "tabulate", "(", "self", ",", "restricted_predicted_column_indices", "=", "[", "]", ",", "restricted_predicted_column_names", "=", "[", "]", ",", "dataset_name", "=", "None", ")", ":", "self", ".", "_analyze", "(", ")", "data_series", "=", "self", ".", ...
Returns summary analysis from the dataframe as a DataTable object. DataTables are wrapped pandas dataframes which can be combined if the have the same width. This is useful for combining multiple analyses. DataTables can be printed to terminal as a tabular string using their representation functio...
[ "Returns", "summary", "analysis", "from", "the", "dataframe", "as", "a", "DataTable", "object", ".", "DataTables", "are", "wrapped", "pandas", "dataframes", "which", "can", "be", "combined", "if", "the", "have", "the", "same", "width", ".", "This", "is", "us...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/stats/dataframe.py#L372-L425
train
Returns summary analysis from the dataframe as a DataTable object.
safarijv/sbo-sphinx
sbo_sphinx/conf.py
update_configuration
def update_configuration(app): """Update parameters which are dependent on information from the project-specific conf.py (including its location on the filesystem)""" config = app.config project = config.project config_dir = app.env.srcdir sys.path.insert(0, os.path.join(config_dir, '..')) ...
python
def update_configuration(app): """Update parameters which are dependent on information from the project-specific conf.py (including its location on the filesystem)""" config = app.config project = config.project config_dir = app.env.srcdir sys.path.insert(0, os.path.join(config_dir, '..')) ...
[ "def", "update_configuration", "(", "app", ")", ":", "config", "=", "app", ".", "config", "project", "=", "config", ".", "project", "config_dir", "=", "app", ".", "env", ".", "srcdir", "sys", ".", "path", ".", "insert", "(", "0", ",", "os", ".", "pat...
Update parameters which are dependent on information from the project-specific conf.py (including its location on the filesystem)
[ "Update", "parameters", "which", "are", "dependent", "on", "information", "from", "the", "project", "-", "specific", "conf", ".", "py", "(", "including", "its", "location", "on", "the", "filesystem", ")" ]
7a8efb7c49488131c90c19ef1a1563f595630a36
https://github.com/safarijv/sbo-sphinx/blob/7a8efb7c49488131c90c19ef1a1563f595630a36/sbo_sphinx/conf.py#L369-L421
train
Update the configuration of the current project with the information from the conf. py.
projectshift/shift-boiler
boiler/user/role_service.py
RoleService.save
def save(self, role, commit=True): """ Persist role model """ self.is_instance(role) schema = RoleSchema() valid = schema.process(role) if not valid: return valid db.session.add(role) if commit: db.session.commit() events.role_sa...
python
def save(self, role, commit=True): """ Persist role model """ self.is_instance(role) schema = RoleSchema() valid = schema.process(role) if not valid: return valid db.session.add(role) if commit: db.session.commit() events.role_sa...
[ "def", "save", "(", "self", ",", "role", ",", "commit", "=", "True", ")", ":", "self", ".", "is_instance", "(", "role", ")", "schema", "=", "RoleSchema", "(", ")", "valid", "=", "schema", ".", "process", "(", "role", ")", "if", "not", "valid", ":",...
Persist role model
[ "Persist", "role", "model" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/role_service.py#L14-L28
train
Persist role model
projectshift/shift-boiler
boiler/user/role_service.py
RoleService.create
def create(self, handle, title=None, description=None): """ Create a role """ role = Role(handle=handle, title=title, description=description) schema = RoleSchema() valid = schema.process(role) if not valid: return valid db.session.add(role) db.sessio...
python
def create(self, handle, title=None, description=None): """ Create a role """ role = Role(handle=handle, title=title, description=description) schema = RoleSchema() valid = schema.process(role) if not valid: return valid db.session.add(role) db.sessio...
[ "def", "create", "(", "self", ",", "handle", ",", "title", "=", "None", ",", "description", "=", "None", ")", ":", "role", "=", "Role", "(", "handle", "=", "handle", ",", "title", "=", "title", ",", "description", "=", "description", ")", "schema", "...
Create a role
[ "Create", "a", "role" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/role_service.py#L30-L42
train
Create a role
projectshift/shift-boiler
boiler/user/role_service.py
RoleService.delete
def delete(self, role, commit=True): """ Delete a role """ events.role_deleted_event.send(role) return super().delete(role, commit)
python
def delete(self, role, commit=True): """ Delete a role """ events.role_deleted_event.send(role) return super().delete(role, commit)
[ "def", "delete", "(", "self", ",", "role", ",", "commit", "=", "True", ")", ":", "events", ".", "role_deleted_event", ".", "send", "(", "role", ")", "return", "super", "(", ")", ".", "delete", "(", "role", ",", "commit", ")" ]
Delete a role
[ "Delete", "a", "role" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/role_service.py#L44-L47
train
Delete a role from the cache.
adaptive-learning/proso-apps
proso/models/prediction.py
PredictiveModel.update_phase
def update_phase(self, environment, data, prediction, user, item, correct, time, answer_id, **kwargs): """ After the prediction update the environment and persist some information for the predictive model. Args: environment (proso.models.environment.Environment): ...
python
def update_phase(self, environment, data, prediction, user, item, correct, time, answer_id, **kwargs): """ After the prediction update the environment and persist some information for the predictive model. Args: environment (proso.models.environment.Environment): ...
[ "def", "update_phase", "(", "self", ",", "environment", ",", "data", ",", "prediction", ",", "user", ",", "item", ",", "correct", ",", "time", ",", "answer_id", ",", "*", "*", "kwargs", ")", ":", "pass" ]
After the prediction update the environment and persist some information for the predictive model. Args: environment (proso.models.environment.Environment): environment where all the important data are persist data (object): data from the prepare ...
[ "After", "the", "prediction", "update", "the", "environment", "and", "persist", "some", "information", "for", "the", "predictive", "model", "." ]
8278c72e498d6ef8d392cc47b48473f4ec037142
https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso/models/prediction.py#L91-L108
train
After the prediction update the environment and persist some information for the predictive model.
TUNE-Archive/freight_forwarder
freight_forwarder/cli/export.py
ExportCommand._build_arguments
def _build_arguments(self): """ build arguments for command. """ self._parser.add_argument( '--clean', type=bool, required=False, default=False, help="clean up everything that was created by freight forwarder at the end." ...
python
def _build_arguments(self): """ build arguments for command. """ self._parser.add_argument( '--clean', type=bool, required=False, default=False, help="clean up everything that was created by freight forwarder at the end." ...
[ "def", "_build_arguments", "(", "self", ")", ":", "self", ".", "_parser", ".", "add_argument", "(", "'--clean'", ",", "type", "=", "bool", ",", "required", "=", "False", ",", "default", "=", "False", ",", "help", "=", "\"clean up everything that was created by...
build arguments for command.
[ "build", "arguments", "for", "command", "." ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/cli/export.py#L71-L137
train
Build the command line arguments for the freight forwarder command.
TUNE-Archive/freight_forwarder
freight_forwarder/cli/export.py
ExportCommand._export
def _export(self, args, **extra_args): """ Export is the entry point for exporting docker images. """ if not isinstance(args, argparse.Namespace): raise TypeError(logger.error("args should of an instance of argparse.Namespace")) # Warn the consumer about unsafe Docke...
python
def _export(self, args, **extra_args): """ Export is the entry point for exporting docker images. """ if not isinstance(args, argparse.Namespace): raise TypeError(logger.error("args should of an instance of argparse.Namespace")) # Warn the consumer about unsafe Docke...
[ "def", "_export", "(", "self", ",", "args", ",", "*", "*", "extra_args", ")", ":", "if", "not", "isinstance", "(", "args", ",", "argparse", ".", "Namespace", ")", ":", "raise", "TypeError", "(", "logger", ".", "error", "(", "\"args should of an instance of...
Export is the entry point for exporting docker images.
[ "Export", "is", "the", "entry", "point", "for", "exporting", "docker", "images", "." ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/cli/export.py#L139-L191
train
This function is the entry point for the export command.
reillysiemens/layabout
setup.py
get_version
def get_version(string): """ Retrieve the ``__version__`` attribute for Layabout. """ flags = re.S pattern = r".*__version__ = '(.*?)'" match = re.match(pattern=pattern, string=string, flags=flags) if match: return match.group(1) raise RuntimeError('No version string could be matched')
python
def get_version(string): """ Retrieve the ``__version__`` attribute for Layabout. """ flags = re.S pattern = r".*__version__ = '(.*?)'" match = re.match(pattern=pattern, string=string, flags=flags) if match: return match.group(1) raise RuntimeError('No version string could be matched')
[ "def", "get_version", "(", "string", ")", ":", "flags", "=", "re", ".", "S", "pattern", "=", "r\".*__version__ = '(.*?)'\"", "match", "=", "re", ".", "match", "(", "pattern", "=", "pattern", ",", "string", "=", "string", ",", "flags", "=", "flags", ")", ...
Retrieve the ``__version__`` attribute for Layabout.
[ "Retrieve", "the", "__version__", "attribute", "for", "Layabout", "." ]
a146c47f2558e66bb51cf708d39909b93eaea7f4
https://github.com/reillysiemens/layabout/blob/a146c47f2558e66bb51cf708d39909b93eaea7f4/setup.py#L13-L22
train
Retrieve the version attribute for Layabout.
PBR/MQ2
MQ2/mapchart.py
_extrac_qtl
def _extrac_qtl(peak, block, headers): """ Given a row containing the peak of the QTL and all the rows of the linkage group of the said QTL (splitted per trait), determine the QTL interval and find the start and stop marker of the said interval. The interval is a LOD 2 interval. The approach is ...
python
def _extrac_qtl(peak, block, headers): """ Given a row containing the peak of the QTL and all the rows of the linkage group of the said QTL (splitted per trait), determine the QTL interval and find the start and stop marker of the said interval. The interval is a LOD 2 interval. The approach is ...
[ "def", "_extrac_qtl", "(", "peak", ",", "block", ",", "headers", ")", ":", "qtls", "=", "[", "]", "if", "not", "peak", ":", "return", "qtls", "threshold", "=", "2", "for", "trait", "in", "peak", ":", "blockcnt", "=", "headers", ".", "index", "(", "...
Given a row containing the peak of the QTL and all the rows of the linkage group of the said QTL (splitted per trait), determine the QTL interval and find the start and stop marker of the said interval. The interval is a LOD 2 interval. The approach is conservative in the way it takes the first and ...
[ "Given", "a", "row", "containing", "the", "peak", "of", "the", "QTL", "and", "all", "the", "rows", "of", "the", "linkage", "group", "of", "the", "said", "QTL", "(", "splitted", "per", "trait", ")", "determine", "the", "QTL", "interval", "and", "find", ...
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/mapchart.py#L40-L99
train
This function extracts the start and stop markers from the QTL and returns the interval of the first and last marker of the QTL.
PBR/MQ2
MQ2/mapchart.py
generate_map_chart_file
def generate_map_chart_file(qtl_matrix, lod_threshold, map_chart_file='MapChart.map'): """ This function converts our QTL matrix file into a MapChart input file. :arg qtl_matrix: the path to the QTL matrix file generated by the plugin. :arg lod_threshold: threshold u...
python
def generate_map_chart_file(qtl_matrix, lod_threshold, map_chart_file='MapChart.map'): """ This function converts our QTL matrix file into a MapChart input file. :arg qtl_matrix: the path to the QTL matrix file generated by the plugin. :arg lod_threshold: threshold u...
[ "def", "generate_map_chart_file", "(", "qtl_matrix", ",", "lod_threshold", ",", "map_chart_file", "=", "'MapChart.map'", ")", ":", "qtl_matrix", "=", "read_input_file", "(", "qtl_matrix", ",", "sep", "=", "','", ")", "tmp_dic", "=", "{", "}", "cnt", "=", "1", ...
This function converts our QTL matrix file into a MapChart input file. :arg qtl_matrix: the path to the QTL matrix file generated by the plugin. :arg lod_threshold: threshold used to determine if a given LOD value is reflective the presence of a QTL. :kwarg map_chart_file: name of the o...
[ "This", "function", "converts", "our", "QTL", "matrix", "file", "into", "a", "MapChart", "input", "file", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/mapchart.py#L124-L228
train
This function converts our QTL matrix file into a MapChart file.
PBR/MQ2
MQ2/mapchart.py
append_flanking_markers
def append_flanking_markers(qtls_mk_file, flanking_markers): """ Append the flanking markers extracted in the process of generating the MapChart to the QTL list file. """ matrix = read_input_file(qtls_mk_file, sep=',') output = [] cnt = 0 for row in matrix: if cnt == 0: m...
python
def append_flanking_markers(qtls_mk_file, flanking_markers): """ Append the flanking markers extracted in the process of generating the MapChart to the QTL list file. """ matrix = read_input_file(qtls_mk_file, sep=',') output = [] cnt = 0 for row in matrix: if cnt == 0: m...
[ "def", "append_flanking_markers", "(", "qtls_mk_file", ",", "flanking_markers", ")", ":", "matrix", "=", "read_input_file", "(", "qtls_mk_file", ",", "sep", "=", "','", ")", "output", "=", "[", "]", "cnt", "=", "0", "for", "row", "in", "matrix", ":", "if",...
Append the flanking markers extracted in the process of generating the MapChart to the QTL list file.
[ "Append", "the", "flanking", "markers", "extracted", "in", "the", "process", "of", "generating", "the", "MapChart", "to", "the", "QTL", "list", "file", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/mapchart.py#L231-L248
train
Append the flanking markers extracted in the process of generating the MapChart to the QTL list file.
Kortemme-Lab/klab
klab/biblio/doi.py
DOI.get_info
def get_info(self): 'Retrieve the data from CrossRef.' escaped_doi = urllib2.quote(self.doi, '') html = get_resource("www.crossref.org", '/guestquery?queryType=doi&restype=unixref&doi=%s&doi_search=Search' % escaped_doi) xml_matches = [] for m in re.finditer('(<doi_records>.*?</...
python
def get_info(self): 'Retrieve the data from CrossRef.' escaped_doi = urllib2.quote(self.doi, '') html = get_resource("www.crossref.org", '/guestquery?queryType=doi&restype=unixref&doi=%s&doi_search=Search' % escaped_doi) xml_matches = [] for m in re.finditer('(<doi_records>.*?</...
[ "def", "get_info", "(", "self", ")", ":", "escaped_doi", "=", "urllib2", ".", "quote", "(", "self", ".", "doi", ",", "''", ")", "html", "=", "get_resource", "(", "\"www.crossref.org\"", ",", "'/guestquery?queryType=doi&restype=unixref&doi=%s&doi_search=Search'", "%"...
Retrieve the data from CrossRef.
[ "Retrieve", "the", "data", "from", "CrossRef", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/biblio/doi.py#L103-L117
train
Retrieve the data from CrossRef.
Kortemme-Lab/klab
klab/biblio/doi.py
DOI.to_dict
def to_dict(self): '''A representation of that publication data that matches the schema we use in our databases.''' if not self.record_type == 'journal': # todo: it may be worthwhile creating subclasses for each entry type (journal, conference, etc.) with a common # API e.g. to_j...
python
def to_dict(self): '''A representation of that publication data that matches the schema we use in our databases.''' if not self.record_type == 'journal': # todo: it may be worthwhile creating subclasses for each entry type (journal, conference, etc.) with a common # API e.g. to_j...
[ "def", "to_dict", "(", "self", ")", ":", "if", "not", "self", ".", "record_type", "==", "'journal'", ":", "# todo: it may be worthwhile creating subclasses for each entry type (journal, conference, etc.) with a common", "# API e.g. to_json which creates output appropriately", "raise"...
A representation of that publication data that matches the schema we use in our databases.
[ "A", "representation", "of", "that", "publication", "data", "that", "matches", "the", "schema", "we", "use", "in", "our", "databases", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/biblio/doi.py#L398-L441
train
A representation of that publication data that matches the schema we use in our databases.
MacHu-GWU/sqlalchemy_mate-project
sqlalchemy_mate/utils.py
ensure_session
def ensure_session(engine_or_session): """ If it is an engine, then create a session from it. And indicate that this session should be closed after the job done. :type engine_or_session: Union[Engine, Session] :rtype: Tuple[Session, bool] """ if isinstance(engine_or_session, Engine): ...
python
def ensure_session(engine_or_session): """ If it is an engine, then create a session from it. And indicate that this session should be closed after the job done. :type engine_or_session: Union[Engine, Session] :rtype: Tuple[Session, bool] """ if isinstance(engine_or_session, Engine): ...
[ "def", "ensure_session", "(", "engine_or_session", ")", ":", "if", "isinstance", "(", "engine_or_session", ",", "Engine", ")", ":", "engine_id", "=", "id", "(", "engine_or_session", ")", "if", "id", "(", "engine_id", ")", "in", "session_klass_cache", ":", "# p...
If it is an engine, then create a session from it. And indicate that this session should be closed after the job done. :type engine_or_session: Union[Engine, Session] :rtype: Tuple[Session, bool]
[ "If", "it", "is", "an", "engine", "then", "create", "a", "session", "from", "it", ".", "And", "indicate", "that", "this", "session", "should", "be", "closed", "after", "the", "job", "done", "." ]
946754744c8870f083fd7b4339fca15d1d6128b2
https://github.com/MacHu-GWU/sqlalchemy_mate-project/blob/946754744c8870f083fd7b4339fca15d1d6128b2/sqlalchemy_mate/utils.py#L61-L81
train
Ensures that a session is created from the given engine or session.
Kortemme-Lab/klab
klab/bio/spackle.py
Spackler.add_backbone_atoms_linearly_from_loop_filepaths
def add_backbone_atoms_linearly_from_loop_filepaths(self, loop_json_filepath, fasta_filepath, residue_ids): '''A utility wrapper around add_backbone_atoms_linearly. Adds backbone atoms in a straight line from the first to the last residue of residue_ids. loop_json_filepath is a path to a ...
python
def add_backbone_atoms_linearly_from_loop_filepaths(self, loop_json_filepath, fasta_filepath, residue_ids): '''A utility wrapper around add_backbone_atoms_linearly. Adds backbone atoms in a straight line from the first to the last residue of residue_ids. loop_json_filepath is a path to a ...
[ "def", "add_backbone_atoms_linearly_from_loop_filepaths", "(", "self", ",", "loop_json_filepath", ",", "fasta_filepath", ",", "residue_ids", ")", ":", "# Parse the loop file", "loop_def", "=", "json", ".", "loads", "(", "read_file", "(", "loop_json_filepath", ")", ")", ...
A utility wrapper around add_backbone_atoms_linearly. Adds backbone atoms in a straight line from the first to the last residue of residue_ids. loop_json_filepath is a path to a JSON file using the JSON format for Rosetta loops files. This file identifies the insertion points of the se...
[ "A", "utility", "wrapper", "around", "add_backbone_atoms_linearly", ".", "Adds", "backbone", "atoms", "in", "a", "straight", "line", "from", "the", "first", "to", "the", "last", "residue", "of", "residue_ids", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/spackle.py#L46-L106
train
This function is a utility wrapper around add_backbone_atoms_linearly. It is used to add backbone atoms in a straight line from the first and last residue of residue_ids.
Kortemme-Lab/klab
klab/bio/spackle.py
Spackler.add_backbone_atoms_linearly
def add_backbone_atoms_linearly(self, start_residue, end_residue, insertion_residues, insertion_residue_map): '''This function returns the PDB content for a structure with the missing backbone atoms - i.e. it adds the N, Ca, C atoms spaced evenly between the last existing backbone atom of start_resid...
python
def add_backbone_atoms_linearly(self, start_residue, end_residue, insertion_residues, insertion_residue_map): '''This function returns the PDB content for a structure with the missing backbone atoms - i.e. it adds the N, Ca, C atoms spaced evenly between the last existing backbone atom of start_resid...
[ "def", "add_backbone_atoms_linearly", "(", "self", ",", "start_residue", ",", "end_residue", ",", "insertion_residues", ",", "insertion_residue_map", ")", ":", "assert", "(", "sorted", "(", "insertion_residues", ")", "==", "sorted", "(", "insertion_residue_map", ".", ...
This function returns the PDB content for a structure with the missing backbone atoms - i.e. it adds the N, Ca, C atoms spaced evenly between the last existing backbone atom of start_residue and the first existing backbone atom of end_residue. O-atoms are not currently added although we could arbi...
[ "This", "function", "returns", "the", "PDB", "content", "for", "a", "structure", "with", "the", "missing", "backbone", "atoms", "-", "i", ".", "e", ".", "it", "adds", "the", "N", "Ca", "C", "atoms", "spaced", "evenly", "between", "the", "last", "existing...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/spackle.py#L109-L219
train
This function returns the PDB content for a structure with the missing backbone atoms - i. e. it adds the backbone atoms for start_residue and end_residue.
Kortemme-Lab/klab
klab/bio/spackle.py
Spackler.add_atoms_linearly
def add_atoms_linearly(self, start_atom, end_atom, new_atoms, jitterbug = 0.2): '''A low-level function which adds new_atoms between start_atom and end_atom. This function does not validate the input i.e. the calling functions are responsible for ensuring that the insertion makes sense. R...
python
def add_atoms_linearly(self, start_atom, end_atom, new_atoms, jitterbug = 0.2): '''A low-level function which adds new_atoms between start_atom and end_atom. This function does not validate the input i.e. the calling functions are responsible for ensuring that the insertion makes sense. R...
[ "def", "add_atoms_linearly", "(", "self", ",", "start_atom", ",", "end_atom", ",", "new_atoms", ",", "jitterbug", "=", "0.2", ")", ":", "atom_name_map", "=", "{", "'CA'", ":", "' CA '", ",", "'C'", ":", "' C '", ",", "'N'", ":", "' N '", ",", "'O'", ...
A low-level function which adds new_atoms between start_atom and end_atom. This function does not validate the input i.e. the calling functions are responsible for ensuring that the insertion makes sense. Returns the PDB file content with the new atoms added. These atoms are given fresh serial nu...
[ "A", "low", "-", "level", "function", "which", "adds", "new_atoms", "between", "start_atom", "and", "end_atom", ".", "This", "function", "does", "not", "validate", "the", "input", "i", ".", "e", ".", "the", "calling", "functions", "are", "responsible", "for"...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/spackle.py#L222-L291
train
A low - level function which adds new_atoms between start_atom and end_atom. This function is used to add new_atoms to the PDB file content.
PBR/MQ2
MQ2/qtl.py
QTL.to_string
def to_string(self): """ Return the string as it should be presented in a MapChart input file. """ return '%s %s %s %s %s' % ( self.trait, self.start_position, self.peak_start_position, self.peak_stop_position, self.stop_position)
python
def to_string(self): """ Return the string as it should be presented in a MapChart input file. """ return '%s %s %s %s %s' % ( self.trait, self.start_position, self.peak_start_position, self.peak_stop_position, self.stop_position)
[ "def", "to_string", "(", "self", ")", ":", "return", "'%s %s %s %s %s'", "%", "(", "self", ".", "trait", ",", "self", ".", "start_position", ",", "self", ".", "peak_start_position", ",", "self", ".", "peak_stop_position", ",", "self", ".", "stop_position", ...
Return the string as it should be presented in a MapChart input file.
[ "Return", "the", "string", "as", "it", "should", "be", "presented", "in", "a", "MapChart", "input", "file", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/qtl.py#L50-L57
train
Return the string representation of the object as it should be presented in a MapChart input file.
tech-pi/doufo
src/python/doufo/tensor/vector.py
Vector.one_hot
def one_hot(cls, n, l): """ n: position of "hot" l: lenght of vector """ v = [0.0] * l v[n] = 1.0 return Vector(v)
python
def one_hot(cls, n, l): """ n: position of "hot" l: lenght of vector """ v = [0.0] * l v[n] = 1.0 return Vector(v)
[ "def", "one_hot", "(", "cls", ",", "n", ",", "l", ")", ":", "v", "=", "[", "0.0", "]", "*", "l", "v", "[", "n", "]", "=", "1.0", "return", "Vector", "(", "v", ")" ]
n: position of "hot" l: lenght of vector
[ "n", ":", "position", "of", "hot", "l", ":", "lenght", "of", "vector" ]
3d375fef30670597768a6eef809b75b4b1b5a3fd
https://github.com/tech-pi/doufo/blob/3d375fef30670597768a6eef809b75b4b1b5a3fd/src/python/doufo/tensor/vector.py#L34-L41
train
returns vector of one hot
aacanakin/glim
glim/cli.py
main
def main(): """ The single entry point to glim command line interface.Main method is called from pypi console_scripts key or by glim.py on root.This function initializes a new app given the glim commands and app commands if app exists. Usage ----- $ python glim/cli.py start $ py...
python
def main(): """ The single entry point to glim command line interface.Main method is called from pypi console_scripts key or by glim.py on root.This function initializes a new app given the glim commands and app commands if app exists. Usage ----- $ python glim/cli.py start $ py...
[ "def", "main", "(", ")", ":", "# register the global parser", "preparser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "description", ",", "add_help", "=", "False", ")", "preparser", ".", "add_argument", "(", "'--env'", ",", "'-e'", ",", "...
The single entry point to glim command line interface.Main method is called from pypi console_scripts key or by glim.py on root.This function initializes a new app given the glim commands and app commands if app exists. Usage ----- $ python glim/cli.py start $ python glim.py start (on r...
[ "The", "single", "entry", "point", "to", "glim", "command", "line", "interface", ".", "Main", "method", "is", "called", "from", "pypi", "console_scripts", "key", "or", "by", "glim", ".", "py", "on", "root", ".", "This", "function", "initializes", "a", "new...
71a20ac149a1292c0d6c1dc7414985ea51854f7a
https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/cli.py#L35-L96
train
This function is called by pypi console_scripts key or by glim. py on root folder.
aacanakin/glim
glim/cli.py
make_app
def make_app(env, commandadapter=None): """ Function creates an app given environment """ mconfig = import_module('app.config.%s' % env, pass_errors=True) if mconfig is None and paths.app_exists(): print(colored('Configuration for "%s" environment is not found' % env, 'red')) return ...
python
def make_app(env, commandadapter=None): """ Function creates an app given environment """ mconfig = import_module('app.config.%s' % env, pass_errors=True) if mconfig is None and paths.app_exists(): print(colored('Configuration for "%s" environment is not found' % env, 'red')) return ...
[ "def", "make_app", "(", "env", ",", "commandadapter", "=", "None", ")", ":", "mconfig", "=", "import_module", "(", "'app.config.%s'", "%", "env", ",", "pass_errors", "=", "True", ")", "if", "mconfig", "is", "None", "and", "paths", ".", "app_exists", "(", ...
Function creates an app given environment
[ "Function", "creates", "an", "app", "given", "environment" ]
71a20ac149a1292c0d6c1dc7414985ea51854f7a
https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/cli.py#L98-L111
train
Function creates an app given an environment
projectshift/shift-boiler
boiler/user/views_social.py
BaseSocial.callback
def callback(self): """ Generate callback url for provider """ next = request.args.get('next') or None endpoint = 'social.{}.handle'.format(self.provider) return url_for(endpoint, _external=True, next=next)
python
def callback(self): """ Generate callback url for provider """ next = request.args.get('next') or None endpoint = 'social.{}.handle'.format(self.provider) return url_for(endpoint, _external=True, next=next)
[ "def", "callback", "(", "self", ")", ":", "next", "=", "request", ".", "args", ".", "get", "(", "'next'", ")", "or", "None", "endpoint", "=", "'social.{}.handle'", ".", "format", "(", "self", ".", "provider", ")", "return", "url_for", "(", "endpoint", ...
Generate callback url for provider
[ "Generate", "callback", "url", "for", "provider" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/views_social.py#L48-L52
train
Generate the url for the callback for this provider
projectshift/shift-boiler
boiler/user/views_social.py
BaseSocial.next
def next(self): """ Where to redirect after authorization """ next = request.args.get('next') if next is None: params = self.default_redirect_params next = url_for(self.default_redirect_endpoint, **params) return next
python
def next(self): """ Where to redirect after authorization """ next = request.args.get('next') if next is None: params = self.default_redirect_params next = url_for(self.default_redirect_endpoint, **params) return next
[ "def", "next", "(", "self", ")", ":", "next", "=", "request", ".", "args", ".", "get", "(", "'next'", ")", "if", "next", "is", "None", ":", "params", "=", "self", ".", "default_redirect_params", "next", "=", "url_for", "(", "self", ".", "default_redire...
Where to redirect after authorization
[ "Where", "to", "redirect", "after", "authorization" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/views_social.py#L60-L66
train
Where to redirect after authorization
projectshift/shift-boiler
boiler/user/views_social.py
BaseHandle.dispatch_request
def dispatch_request(self): """ Handle redirect back from provider """ if current_user.is_authenticated: return redirect(self.next) # clear previous! if 'social_data' in session: del session['social_data'] res = self.app.authorized_response() if ...
python
def dispatch_request(self): """ Handle redirect back from provider """ if current_user.is_authenticated: return redirect(self.next) # clear previous! if 'social_data' in session: del session['social_data'] res = self.app.authorized_response() if ...
[ "def", "dispatch_request", "(", "self", ")", ":", "if", "current_user", ".", "is_authenticated", ":", "return", "redirect", "(", "self", ".", "next", ")", "# clear previous!", "if", "'social_data'", "in", "session", ":", "del", "session", "[", "'social_data'", ...
Handle redirect back from provider
[ "Handle", "redirect", "back", "from", "provider" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/views_social.py#L106-L176
train
Dispatches the request to the provider and returns the response.
projectshift/shift-boiler
boiler/user/views_social.py
FacebookHandle.get_profile_data
def get_profile_data(self, auth_response): """ Retrieve profile data from provider """ res = auth_response token = res.get('access_token') expires = res.get('expires_in') expires = datetime.utcnow() + timedelta(seconds=int(expires)) session[self.session_key] = (token, ex...
python
def get_profile_data(self, auth_response): """ Retrieve profile data from provider """ res = auth_response token = res.get('access_token') expires = res.get('expires_in') expires = datetime.utcnow() + timedelta(seconds=int(expires)) session[self.session_key] = (token, ex...
[ "def", "get_profile_data", "(", "self", ",", "auth_response", ")", ":", "res", "=", "auth_response", "token", "=", "res", ".", "get", "(", "'access_token'", ")", "expires", "=", "res", ".", "get", "(", "'expires_in'", ")", "expires", "=", "datetime", ".", ...
Retrieve profile data from provider
[ "Retrieve", "profile", "data", "from", "provider" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/views_social.py#L194-L221
train
Retrieve profile data from provider
projectshift/shift-boiler
boiler/user/views_social.py
InstagramHandle.get_profile_data
def get_profile_data(self, auth_response): """ Retrieve profile data from provider """ res = auth_response token = res.get('access_token') me = res.get('user') if not me.get('id'): raise x.UserException('Instagram must return a user id') data = dict( ...
python
def get_profile_data(self, auth_response): """ Retrieve profile data from provider """ res = auth_response token = res.get('access_token') me = res.get('user') if not me.get('id'): raise x.UserException('Instagram must return a user id') data = dict( ...
[ "def", "get_profile_data", "(", "self", ",", "auth_response", ")", ":", "res", "=", "auth_response", "token", "=", "res", ".", "get", "(", "'access_token'", ")", "me", "=", "res", ".", "get", "(", "'user'", ")", "if", "not", "me", ".", "get", "(", "'...
Retrieve profile data from provider
[ "Retrieve", "profile", "data", "from", "provider" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/views_social.py#L331-L346
train
Retrieve profile data from provider
tech-pi/doufo
src/python/doufo/tensor/binary.py
project
def project(v, n): """ Project Vector v onto plane with normal vector n. """ return v - matmul(v, n) * n / (norm(n) ** 2.0)
python
def project(v, n): """ Project Vector v onto plane with normal vector n. """ return v - matmul(v, n) * n / (norm(n) ** 2.0)
[ "def", "project", "(", "v", ",", "n", ")", ":", "return", "v", "-", "matmul", "(", "v", ",", "n", ")", "*", "n", "/", "(", "norm", "(", "n", ")", "**", "2.0", ")" ]
Project Vector v onto plane with normal vector n.
[ "Project", "Vector", "v", "onto", "plane", "with", "normal", "vector", "n", "." ]
3d375fef30670597768a6eef809b75b4b1b5a3fd
https://github.com/tech-pi/doufo/blob/3d375fef30670597768a6eef809b75b4b1b5a3fd/src/python/doufo/tensor/binary.py#L36-L40
train
Project vector v onto plane with normal vector n.
46elks/elkme
elkme/main.py
main
def main(): """Executed on run""" args = parse_args() if args.version: from .__init__ import __version__, __release_date__ print('elkme %s (release date %s)' % (__version__, __release_date__)) print('(c) 2015-2017 46elks AB <hello@46elks.com>') print(small_elk) exit(...
python
def main(): """Executed on run""" args = parse_args() if args.version: from .__init__ import __version__, __release_date__ print('elkme %s (release date %s)' % (__version__, __release_date__)) print('(c) 2015-2017 46elks AB <hello@46elks.com>') print(small_elk) exit(...
[ "def", "main", "(", ")", ":", "args", "=", "parse_args", "(", ")", "if", "args", ".", "version", ":", "from", ".", "__init__", "import", "__version__", ",", "__release_date__", "print", "(", "'elkme %s (release date %s)'", "%", "(", "__version__", ",", "__re...
Executed on run
[ "Executed", "on", "run" ]
6ebdce6f8ac852fc6f714d1f1b836f2777fece4e
https://github.com/46elks/elkme/blob/6ebdce6f8ac852fc6f714d1f1b836f2777fece4e/elkme/main.py#L48-L93
train
Execute on run
46elks/elkme
elkme/main.py
parse_args
def parse_args(): """Parse the arguments to the application""" parser = argparse.ArgumentParser( description=HELPTEXT, epilog="This application is powered by elks with superpowers!") parser.add_argument('--version', action='store_true', help="Display elkme version and...
python
def parse_args(): """Parse the arguments to the application""" parser = argparse.ArgumentParser( description=HELPTEXT, epilog="This application is powered by elks with superpowers!") parser.add_argument('--version', action='store_true', help="Display elkme version and...
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "HELPTEXT", ",", "epilog", "=", "\"This application is powered by elks with superpowers!\"", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "...
Parse the arguments to the application
[ "Parse", "the", "arguments", "to", "the", "application" ]
6ebdce6f8ac852fc6f714d1f1b836f2777fece4e
https://github.com/46elks/elkme/blob/6ebdce6f8ac852fc6f714d1f1b836f2777fece4e/elkme/main.py#L95-L132
train
Parse the command line arguments to the application.
clement-alexandre/TotemBionet
totembionet/src/ggea/ggea.py
Graph._build_graph
def _build_graph(self) -> nx.DiGraph: """ Private method to build the graph from the model. """ digraph = nx.DiGraph() for state in self.model.all_states(): self._number_of_states += 1 for next_state in self.model.available_state(state): self._number_of_tr...
python
def _build_graph(self) -> nx.DiGraph: """ Private method to build the graph from the model. """ digraph = nx.DiGraph() for state in self.model.all_states(): self._number_of_states += 1 for next_state in self.model.available_state(state): self._number_of_tr...
[ "def", "_build_graph", "(", "self", ")", "->", "nx", ".", "DiGraph", ":", "digraph", "=", "nx", ".", "DiGraph", "(", ")", "for", "state", "in", "self", ".", "model", ".", "all_states", "(", ")", ":", "self", ".", "_number_of_states", "+=", "1", "for"...
Private method to build the graph from the model.
[ "Private", "method", "to", "build", "the", "graph", "from", "the", "model", "." ]
f37a2f9358c1ce49f21c4a868b904da5dcd4614f
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L22-L33
train
Private method to build the graph from the model.
clement-alexandre/TotemBionet
totembionet/src/ggea/ggea.py
Graph._transform_state_to_string
def _transform_state_to_string(self, state: State) -> str: """ Private method which transform a state to a string. Examples -------- The model contains 2 genes: operon = {0, 1, 2} mucuB = {0, 1} >>> graph._transform_state_to_string({...
python
def _transform_state_to_string(self, state: State) -> str: """ Private method which transform a state to a string. Examples -------- The model contains 2 genes: operon = {0, 1, 2} mucuB = {0, 1} >>> graph._transform_state_to_string({...
[ "def", "_transform_state_to_string", "(", "self", ",", "state", ":", "State", ")", "->", "str", ":", "return", "''", ".", "join", "(", "str", "(", "state", "[", "gene", "]", ")", "for", "gene", "in", "self", ".", "model", ".", "genes", ")" ]
Private method which transform a state to a string. Examples -------- The model contains 2 genes: operon = {0, 1, 2} mucuB = {0, 1} >>> graph._transform_state_to_string({operon: 1, mucuB: 0}) "10" >>> graph._transform_state_to_string...
[ "Private", "method", "which", "transform", "a", "state", "to", "a", "string", "." ]
f37a2f9358c1ce49f21c4a868b904da5dcd4614f
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L35-L51
train
Private method which transform a state to a string.
clement-alexandre/TotemBionet
totembionet/src/ggea/ggea.py
Graph.as_dot
def as_dot(self) -> str: """ Return as a string the dot version of the graph. """ return nx.drawing.nx_pydot.to_pydot(self._graph).to_string()
python
def as_dot(self) -> str: """ Return as a string the dot version of the graph. """ return nx.drawing.nx_pydot.to_pydot(self._graph).to_string()
[ "def", "as_dot", "(", "self", ")", "->", "str", ":", "return", "nx", ".", "drawing", ".", "nx_pydot", ".", "to_pydot", "(", "self", ".", "_graph", ")", ".", "to_string", "(", ")" ]
Return as a string the dot version of the graph.
[ "Return", "as", "a", "string", "the", "dot", "version", "of", "the", "graph", "." ]
f37a2f9358c1ce49f21c4a868b904da5dcd4614f
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L65-L67
train
Return the dot version of the graph.
clement-alexandre/TotemBionet
totembionet/src/ggea/ggea.py
Graph.export_to_dot
def export_to_dot(self, filename: str = 'output') -> None: """ Export the graph to the dot file "filename.dot". """ with open(filename + '.dot', 'w') as output: output.write(self.as_dot())
python
def export_to_dot(self, filename: str = 'output') -> None: """ Export the graph to the dot file "filename.dot". """ with open(filename + '.dot', 'w') as output: output.write(self.as_dot())
[ "def", "export_to_dot", "(", "self", ",", "filename", ":", "str", "=", "'output'", ")", "->", "None", ":", "with", "open", "(", "filename", "+", "'.dot'", ",", "'w'", ")", "as", "output", ":", "output", ".", "write", "(", "self", ".", "as_dot", "(", ...
Export the graph to the dot file "filename.dot".
[ "Export", "the", "graph", "to", "the", "dot", "file", "filename", ".", "dot", "." ]
f37a2f9358c1ce49f21c4a868b904da5dcd4614f
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/ggea/ggea.py#L69-L72
train
Export the current node to the dot file filename. dot.
speechinformaticslab/vfclust
vfclust/vfclust.py
get_duration_measures
def get_duration_measures(source_file_path, output_path=None, phonemic=False, semantic=False, quiet=False, similarity_file = None, threshold = None): """Parses ...
python
def get_duration_measures(source_file_path, output_path=None, phonemic=False, semantic=False, quiet=False, similarity_file = None, threshold = None): """Parses ...
[ "def", "get_duration_measures", "(", "source_file_path", ",", "output_path", "=", "None", ",", "phonemic", "=", "False", ",", "semantic", "=", "False", ",", "quiet", "=", "False", ",", "similarity_file", "=", "None", ",", "threshold", "=", "None", ")", ":", ...
Parses input arguments and runs clustering algorithm. :param source_file_path: Required. Location of the .csv or .TextGrid file to be analyzed. :param output_path: Path to which to write the resultant csv file. If left None, path will be set to the source_file_path. If set to False, no file wi...
[ "Parses", "input", "arguments", "and", "runs", "clustering", "algorithm", "." ]
7ca733dea4782c828024765726cce65de095d33c
https://github.com/speechinformaticslab/vfclust/blob/7ca733dea4782c828024765726cce65de095d33c/vfclust/vfclust.py#L1597-L1666
train
Parses the input file path and runs the duration measure algorithm.
speechinformaticslab/vfclust
vfclust/vfclust.py
validate_arguments
def validate_arguments(args): """Makes sure arguments are valid, specified files exist, etc.""" #check arguments print print "Checking input...", semantic_tests = ["animals", "custom"] phonemic_tests = ["a", "p", "s", "f"] if args.similarity_file: print print "Custom simila...
python
def validate_arguments(args): """Makes sure arguments are valid, specified files exist, etc.""" #check arguments print print "Checking input...", semantic_tests = ["animals", "custom"] phonemic_tests = ["a", "p", "s", "f"] if args.similarity_file: print print "Custom simila...
[ "def", "validate_arguments", "(", "args", ")", ":", "#check arguments", "print", "print", "\"Checking input...\"", ",", "semantic_tests", "=", "[", "\"animals\"", ",", "\"custom\"", "]", "phonemic_tests", "=", "[", "\"a\"", ",", "\"p\"", ",", "\"s\"", ",", "\"f\...
Makes sure arguments are valid, specified files exist, etc.
[ "Makes", "sure", "arguments", "are", "valid", "specified", "files", "exist", "etc", "." ]
7ca733dea4782c828024765726cce65de095d33c
https://github.com/speechinformaticslab/vfclust/blob/7ca733dea4782c828024765726cce65de095d33c/vfclust/vfclust.py#L1669-L1761
train
Makes sure arguments are valid.
speechinformaticslab/vfclust
vfclust/vfclust.py
ParsedResponse.create_from_csv
def create_from_csv(self,token_list): """ Fills the ParsedResponse object with a list of words/tokens originally from a .csv file. :param list token_list: List of strings corresponding to words in the subject response. Modifies: - self.timing_included: csv files do not include timi...
python
def create_from_csv(self,token_list): """ Fills the ParsedResponse object with a list of words/tokens originally from a .csv file. :param list token_list: List of strings corresponding to words in the subject response. Modifies: - self.timing_included: csv files do not include timi...
[ "def", "create_from_csv", "(", "self", ",", "token_list", ")", ":", "self", ".", "timing_included", "=", "False", "for", "entry", "in", "token_list", ":", "self", ".", "unit_list", ".", "append", "(", "Unit", "(", "entry", ",", "format", "=", "\"csv\"", ...
Fills the ParsedResponse object with a list of words/tokens originally from a .csv file. :param list token_list: List of strings corresponding to words in the subject response. Modifies: - self.timing_included: csv files do not include timing information - self.unit_list: fills...
[ "Fills", "the", "ParsedResponse", "object", "with", "a", "list", "of", "words", "/", "tokens", "originally", "from", "a", ".", "csv", "file", "." ]
7ca733dea4782c828024765726cce65de095d33c
https://github.com/speechinformaticslab/vfclust/blob/7ca733dea4782c828024765726cce65de095d33c/vfclust/vfclust.py#L171-L189
train
Creates a ParsedResponse object from a list of words and tokens in a. csv file.
speechinformaticslab/vfclust
vfclust/vfclust.py
ParsedResponse.create_from_textgrid
def create_from_textgrid(self,word_list): """ Fills the ParsedResponse object with a list of TextGrid.Word objects originally from a .TextGrid file. :param list word_list: List of TextGrid.Word objects corresponding to words/tokens in the subject response. Modifies: - self.timing_i...
python
def create_from_textgrid(self,word_list): """ Fills the ParsedResponse object with a list of TextGrid.Word objects originally from a .TextGrid file. :param list word_list: List of TextGrid.Word objects corresponding to words/tokens in the subject response. Modifies: - self.timing_i...
[ "def", "create_from_textgrid", "(", "self", ",", "word_list", ")", ":", "self", ".", "timing_included", "=", "True", "for", "i", ",", "entry", "in", "enumerate", "(", "word_list", ")", ":", "self", ".", "unit_list", ".", "append", "(", "Unit", "(", "entr...
Fills the ParsedResponse object with a list of TextGrid.Word objects originally from a .TextGrid file. :param list word_list: List of TextGrid.Word objects corresponding to words/tokens in the subject response. Modifies: - self.timing_included: TextGrid files include timing information ...
[ "Fills", "the", "ParsedResponse", "object", "with", "a", "list", "of", "TextGrid", ".", "Word", "objects", "originally", "from", "a", ".", "TextGrid", "file", "." ]
7ca733dea4782c828024765726cce65de095d33c
https://github.com/speechinformaticslab/vfclust/blob/7ca733dea4782c828024765726cce65de095d33c/vfclust/vfclust.py#L191-L211
train
Creates a ParsedResponse object from a list of TextGrid. Word objects generated from the words in the subject response.
speechinformaticslab/vfclust
vfclust/vfclust.py
ParsedResponse.lemmatize
def lemmatize(self): """Lemmatize all Units in self.unit_list. Modifies: - self.unit_list: converts the .text property into its lemmatized form. This method lemmatizes all inflected variants of permissible words to those words' respective canonical forms. This is done to en...
python
def lemmatize(self): """Lemmatize all Units in self.unit_list. Modifies: - self.unit_list: converts the .text property into its lemmatized form. This method lemmatizes all inflected variants of permissible words to those words' respective canonical forms. This is done to en...
[ "def", "lemmatize", "(", "self", ")", ":", "for", "unit", "in", "self", ".", "unit_list", ":", "if", "lemmatizer", ".", "lemmatize", "(", "unit", ".", "text", ")", "in", "self", ".", "lemmas", ":", "unit", ".", "text", "=", "lemmatizer", ".", "lemmat...
Lemmatize all Units in self.unit_list. Modifies: - self.unit_list: converts the .text property into its lemmatized form. This method lemmatizes all inflected variants of permissible words to those words' respective canonical forms. This is done to ensure that each instance ...
[ "Lemmatize", "all", "Units", "in", "self", ".", "unit_list", "." ]
7ca733dea4782c828024765726cce65de095d33c
https://github.com/speechinformaticslab/vfclust/blob/7ca733dea4782c828024765726cce65de095d33c/vfclust/vfclust.py#L213-L229
train
Lemmatize all Units in self. unit_list.
speechinformaticslab/vfclust
vfclust/vfclust.py
ParsedResponse.tokenize
def tokenize(self): """Tokenizes all multiword names in the list of Units. Modifies: - (indirectly) self.unit_list, by combining words into compound words. This is done because many names may be composed of multiple words, e.g., 'grizzly bear'. In order to count the number ...
python
def tokenize(self): """Tokenizes all multiword names in the list of Units. Modifies: - (indirectly) self.unit_list, by combining words into compound words. This is done because many names may be composed of multiple words, e.g., 'grizzly bear'. In order to count the number ...
[ "def", "tokenize", "(", "self", ")", ":", "if", "not", "self", ".", "quiet", ":", "print", "print", "\"Finding compound words...\"", "# lists of animal names containing 2-5 separate words", "compound_word_dict", "=", "{", "}", "for", "compound_length", "in", "range", ...
Tokenizes all multiword names in the list of Units. Modifies: - (indirectly) self.unit_list, by combining words into compound words. This is done because many names may be composed of multiple words, e.g., 'grizzly bear'. In order to count the number of permissible words ge...
[ "Tokenizes", "all", "multiword", "names", "in", "the", "list", "of", "Units", "." ]
7ca733dea4782c828024765726cce65de095d33c
https://github.com/speechinformaticslab/vfclust/blob/7ca733dea4782c828024765726cce65de095d33c/vfclust/vfclust.py#L232-L273
train
Tokenizes all multiword names in the list of Units.
speechinformaticslab/vfclust
vfclust/vfclust.py
ParsedResponse.make_compound_word
def make_compound_word(self, start_index, how_many): """Combines two Units in self.unit_list to make a compound word token. :param int start_index: Index of first Unit in self.unit_list to be combined :param int how_many: Index of how many Units in self.unit_list to be combined. Modifi...
python
def make_compound_word(self, start_index, how_many): """Combines two Units in self.unit_list to make a compound word token. :param int start_index: Index of first Unit in self.unit_list to be combined :param int how_many: Index of how many Units in self.unit_list to be combined. Modifi...
[ "def", "make_compound_word", "(", "self", ",", "start_index", ",", "how_many", ")", ":", "if", "not", "self", ".", "quiet", ":", "compound_word", "=", "\"\"", "for", "word", "in", "self", ".", "unit_list", "[", "start_index", ":", "start_index", "+", "how_...
Combines two Units in self.unit_list to make a compound word token. :param int start_index: Index of first Unit in self.unit_list to be combined :param int how_many: Index of how many Units in self.unit_list to be combined. Modifies: - self.unit_list: Modifies the Unit correspo...
[ "Combines", "two", "Units", "in", "self", ".", "unit_list", "to", "make", "a", "compound", "word", "token", "." ]
7ca733dea4782c828024765726cce65de095d33c
https://github.com/speechinformaticslab/vfclust/blob/7ca733dea4782c828024765726cce65de095d33c/vfclust/vfclust.py#L275-L310
train
Combines two Units in self. unit_list to make a compound word token.
speechinformaticslab/vfclust
vfclust/vfclust.py
ParsedResponse.remove_unit
def remove_unit(self, index): '''Removes the unit at the given index in self.unit_list. Does not modify any other units.''' if not self.quiet: print "Removing", self.unit_list[index].text self.unit_list.pop(index)
python
def remove_unit(self, index): '''Removes the unit at the given index in self.unit_list. Does not modify any other units.''' if not self.quiet: print "Removing", self.unit_list[index].text self.unit_list.pop(index)
[ "def", "remove_unit", "(", "self", ",", "index", ")", ":", "if", "not", "self", ".", "quiet", ":", "print", "\"Removing\"", ",", "self", ".", "unit_list", "[", "index", "]", ".", "text", "self", ".", "unit_list", ".", "pop", "(", "index", ")" ]
Removes the unit at the given index in self.unit_list. Does not modify any other units.
[ "Removes", "the", "unit", "at", "the", "given", "index", "in", "self", ".", "unit_list", ".", "Does", "not", "modify", "any", "other", "units", "." ]
7ca733dea4782c828024765726cce65de095d33c
https://github.com/speechinformaticslab/vfclust/blob/7ca733dea4782c828024765726cce65de095d33c/vfclust/vfclust.py#L312-L316
train
Removes the unit at the given index in self. unit_list. Does not modify any other units.