repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
saltstack/salt
salt/thorium/reg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/reg.py#L95-L133
def mean(name, add, match): ''' Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped USAGE: .. code-block:: yaml foo: reg.mean: - add: data_field ...
[ "def", "mean", "(", "name", ",", "add", ",", "match", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'result'", ":", "True", "}", "if", "name", "not", "in", "__reg__", ":", ...
Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped USAGE: .. code-block:: yaml foo: reg.mean: - add: data_field - match: my/custom/event
[ "Accept", "a", "numeric", "value", "from", "the", "matched", "events", "and", "store", "a", "running", "average", "of", "the", "values", "in", "the", "given", "register", ".", "If", "the", "specified", "value", "is", "not", "numeric", "it", "will", "be", ...
python
train
KenjiTakahashi/td
td/model.py
https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/model.py#L361-L371
def setOptions(self, glob=False, **kwargs): """Set option(s). :glob: If True, stores specified options globally. :kwargs: Dictionary of options and values to set. """ if glob: self.globalOptions.update(kwargs) else: self.options.update(kwargs)
[ "def", "setOptions", "(", "self", ",", "glob", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "glob", ":", "self", ".", "globalOptions", ".", "update", "(", "kwargs", ")", "else", ":", "self", ".", "options", ".", "update", "(", "kwargs", "...
Set option(s). :glob: If True, stores specified options globally. :kwargs: Dictionary of options and values to set.
[ "Set", "option", "(", "s", ")", "." ]
python
train
klahnakoski/pyLibrary
jx_python/flat_list.py
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_python/flat_list.py#L124-L138
def _select1(data, field, depth, output): """ SELECT A SINGLE FIELD """ for d in data: for i, f in enumerate(field[depth:]): d = d[f] if d == None: output.append(None) break elif is_list(d): _select1(d, field, i ...
[ "def", "_select1", "(", "data", ",", "field", ",", "depth", ",", "output", ")", ":", "for", "d", "in", "data", ":", "for", "i", ",", "f", "in", "enumerate", "(", "field", "[", "depth", ":", "]", ")", ":", "d", "=", "d", "[", "f", "]", "if", ...
SELECT A SINGLE FIELD
[ "SELECT", "A", "SINGLE", "FIELD" ]
python
train
Clinical-Genomics/scout
scout/adapter/mongo/index.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/adapter/mongo/index.py#L54-L72
def update_indexes(self): """Update the indexes If there are any indexes that are not added to the database, add those. """ LOG.info("Updating indexes...") nr_updated = 0 for collection_name in INDEXES: existing_indexes = self.indexes(collection_name...
[ "def", "update_indexes", "(", "self", ")", ":", "LOG", ".", "info", "(", "\"Updating indexes...\"", ")", "nr_updated", "=", "0", "for", "collection_name", "in", "INDEXES", ":", "existing_indexes", "=", "self", ".", "indexes", "(", "collection_name", ")", "inde...
Update the indexes If there are any indexes that are not added to the database, add those.
[ "Update", "the", "indexes", "If", "there", "are", "any", "indexes", "that", "are", "not", "added", "to", "the", "database", "add", "those", "." ]
python
test
coleifer/peewee
playhouse/sqlite_ext.py
https://github.com/coleifer/peewee/blob/ea9403b01acb039adb3a2472186d795c796b77a0/playhouse/sqlite_ext.py#L719-L807
def ClosureTable(model_class, foreign_key=None, referencing_class=None, referencing_key=None): """Model factory for the transitive closure extension.""" if referencing_class is None: referencing_class = model_class if foreign_key is None: for field_obj in model_class._meta....
[ "def", "ClosureTable", "(", "model_class", ",", "foreign_key", "=", "None", ",", "referencing_class", "=", "None", ",", "referencing_key", "=", "None", ")", ":", "if", "referencing_class", "is", "None", ":", "referencing_class", "=", "model_class", "if", "foreig...
Model factory for the transitive closure extension.
[ "Model", "factory", "for", "the", "transitive", "closure", "extension", "." ]
python
train
StackStorm/pybind
pybind/nos/v7_2_0/isns/isns_vrf/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/isns/isns_vrf/__init__.py#L143-L166
def _set_isns_ipaddress(self, v, load=False): """ Setter method for isns_ipaddress, mapped from YANG variable /isns/isns_vrf/isns_ipaddress (inet:ip-address) If this variable is read-only (config: false) in the source YANG file, then _set_isns_ipaddress is considered as a private method. Backends lo...
[ "def", "_set_isns_ipaddress", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
Setter method for isns_ipaddress, mapped from YANG variable /isns/isns_vrf/isns_ipaddress (inet:ip-address) If this variable is read-only (config: false) in the source YANG file, then _set_isns_ipaddress is considered as a private method. Backends looking to populate this variable should do so via calli...
[ "Setter", "method", "for", "isns_ipaddress", "mapped", "from", "YANG", "variable", "/", "isns", "/", "isns_vrf", "/", "isns_ipaddress", "(", "inet", ":", "ip", "-", "address", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", ...
python
train
sods/ods
pods/notebook.py
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/notebook.py#L68-L98
def code_toggle(start_show=False, message=None): """Toggling on and off code in a notebook. :param start_show: Whether to display the code or not on first load (default is False). :type start_show: bool :param message: the message used to toggle display of the code. :type message: string The t...
[ "def", "code_toggle", "(", "start_show", "=", "False", ",", "message", "=", "None", ")", ":", "html", "=", "'<script>\\n'", "if", "message", "is", "None", ":", "message", "=", "u'The raw code for this jupyter notebook can be hidden for easier reading.'", "if", "start_...
Toggling on and off code in a notebook. :param start_show: Whether to display the code or not on first load (default is False). :type start_show: bool :param message: the message used to toggle display of the code. :type message: string The tip that this idea is based on is from Damian Kao (ht...
[ "Toggling", "on", "and", "off", "code", "in", "a", "notebook", ".", ":", "param", "start_show", ":", "Whether", "to", "display", "the", "code", "or", "not", "on", "first", "load", "(", "default", "is", "False", ")", ".", ":", "type", "start_show", ":",...
python
train
GeospatialPython/pyshp
shapefile.py
https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L1303-L1335
def __dbfHeader(self): """Writes the dbf header and field descriptors.""" f = self.__getFileObj(self.dbf) f.seek(0) version = 3 year, month, day = time.localtime()[:3] year -= 1900 # Remove deletion flag placeholder from fields for field in self.fi...
[ "def", "__dbfHeader", "(", "self", ")", ":", "f", "=", "self", ".", "__getFileObj", "(", "self", ".", "dbf", ")", "f", ".", "seek", "(", "0", ")", "version", "=", "3", "year", ",", "month", ",", "day", "=", "time", ".", "localtime", "(", ")", "...
Writes the dbf header and field descriptors.
[ "Writes", "the", "dbf", "header", "and", "field", "descriptors", "." ]
python
train
theislab/scanpy
scanpy/neighbors/__init__.py
https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/neighbors/__init__.py#L862-L870
def _compute_Lp_matrix(self): """See Fouss et al. (2006) and von Luxburg et al. (2007). See Proposition 6 in von Luxburg (2007) and the inline equations right in the text above. """ self.Lp = sum([1/self.eigen_values[i] * np.outer(self.eigen_basis[:, i], se...
[ "def", "_compute_Lp_matrix", "(", "self", ")", ":", "self", ".", "Lp", "=", "sum", "(", "[", "1", "/", "self", ".", "eigen_values", "[", "i", "]", "*", "np", ".", "outer", "(", "self", ".", "eigen_basis", "[", ":", ",", "i", "]", ",", "self", "...
See Fouss et al. (2006) and von Luxburg et al. (2007). See Proposition 6 in von Luxburg (2007) and the inline equations right in the text above.
[ "See", "Fouss", "et", "al", ".", "(", "2006", ")", "and", "von", "Luxburg", "et", "al", ".", "(", "2007", ")", "." ]
python
train
clalancette/pycdlib
pycdlib/headervd.py
https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/headervd.py#L83-L195
def parse(self, vd, extent_loc): # type: (bytes, int) -> None ''' Parse a Volume Descriptor out of a string. Parameters: vd - The string containing the Volume Descriptor. extent_loc - The location on the ISO of this Volume Descriptor. Returns: Nothing....
[ "def", "parse", "(", "self", ",", "vd", ",", "extent_loc", ")", ":", "# type: (bytes, int) -> None", "################ PVD VERSION ######################", "(", "descriptor_type", ",", "identifier", ",", "self", ".", "version", ",", "self", ".", "flags", ",", "self"...
Parse a Volume Descriptor out of a string. Parameters: vd - The string containing the Volume Descriptor. extent_loc - The location on the ISO of this Volume Descriptor. Returns: Nothing.
[ "Parse", "a", "Volume", "Descriptor", "out", "of", "a", "string", "." ]
python
train
garethr/django-timelog
src/timelog/lib.py
https://github.com/garethr/django-timelog/blob/84c7015248a82faccb9d3fe4e6014645cc9ec103/src/timelog/lib.py#L72-L132
def analyze_log_file(logfile, pattern, reverse_paths=True, progress=True): "Given a log file and regex group and extract the performance data" if progress: lines = count_lines_in(logfile) pbar = ProgressBar(widgets=[Percentage(), Bar()], maxval=lines+1).start() counter = 0 data ...
[ "def", "analyze_log_file", "(", "logfile", ",", "pattern", ",", "reverse_paths", "=", "True", ",", "progress", "=", "True", ")", ":", "if", "progress", ":", "lines", "=", "count_lines_in", "(", "logfile", ")", "pbar", "=", "ProgressBar", "(", "widgets", "=...
Given a log file and regex group and extract the performance data
[ "Given", "a", "log", "file", "and", "regex", "group", "and", "extract", "the", "performance", "data" ]
python
train
Gandi/gandi.cli
gandi/cli/modules/forward.py
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/forward.py#L28-L34
def create(cls, domain, source, destinations): """Create a domain mail forward.""" cls.echo('Creating mail forward %s@%s' % (source, domain)) options = {'destinations': list(destinations)} result = cls.call('domain.forward.create', domain, source, options) return result
[ "def", "create", "(", "cls", ",", "domain", ",", "source", ",", "destinations", ")", ":", "cls", ".", "echo", "(", "'Creating mail forward %s@%s'", "%", "(", "source", ",", "domain", ")", ")", "options", "=", "{", "'destinations'", ":", "list", "(", "des...
Create a domain mail forward.
[ "Create", "a", "domain", "mail", "forward", "." ]
python
train
LordDarkula/chess_py
chess_py/core/algebraic/converter.py
https://github.com/LordDarkula/chess_py/blob/14bebc2f8c49ae25c59375cc83d0b38d8ff7281d/chess_py/core/algebraic/converter.py#L308-L330
def make_legal(move, position): """ Converts an incomplete move (initial ``Location`` not specified) and the corresponding position into the a complete move with the most likely starting point specified. If no moves match, ``None`` is returned. :type: move: Move :type: position: Board :...
[ "def", "make_legal", "(", "move", ",", "position", ")", ":", "assert", "isinstance", "(", "move", ",", "Move", ")", "for", "legal_move", "in", "position", ".", "all_possible_moves", "(", "move", ".", "color", ")", ":", "if", "move", ".", "status", "==", ...
Converts an incomplete move (initial ``Location`` not specified) and the corresponding position into the a complete move with the most likely starting point specified. If no moves match, ``None`` is returned. :type: move: Move :type: position: Board :rtype: Move
[ "Converts", "an", "incomplete", "move", "(", "initial", "Location", "not", "specified", ")", "and", "the", "corresponding", "position", "into", "the", "a", "complete", "move", "with", "the", "most", "likely", "starting", "point", "specified", ".", "If", "no", ...
python
train
henzk/django-productline
django_productline/tasks.py
https://github.com/henzk/django-productline/blob/24ff156924c1a8c07b99cbb8a1de0a42b8d81f60/django_productline/tasks.py#L260-L266
def export_context(target_zip): """ Append context.json to target_zip """ from django_productline import utils context_file = tasks.get_context_path() return utils.create_or_append_to_zip(context_file, target_zip, 'context.json')
[ "def", "export_context", "(", "target_zip", ")", ":", "from", "django_productline", "import", "utils", "context_file", "=", "tasks", ".", "get_context_path", "(", ")", "return", "utils", ".", "create_or_append_to_zip", "(", "context_file", ",", "target_zip", ",", ...
Append context.json to target_zip
[ "Append", "context", ".", "json", "to", "target_zip" ]
python
train
noxdafox/clipspy
clips/facts.py
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/facts.py#L438-L441
def multifield(self): """True if the slot is a multifield slot.""" return bool(lib.EnvDeftemplateSlotMultiP( self._env, self._tpl, self._name))
[ "def", "multifield", "(", "self", ")", ":", "return", "bool", "(", "lib", ".", "EnvDeftemplateSlotMultiP", "(", "self", ".", "_env", ",", "self", ".", "_tpl", ",", "self", ".", "_name", ")", ")" ]
True if the slot is a multifield slot.
[ "True", "if", "the", "slot", "is", "a", "multifield", "slot", "." ]
python
train
pyQode/pyqode.core
pyqode/core/managers/backend.py
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/managers/backend.py#L161-L194
def send_request(self, worker_class_or_function, args, on_receive=None): """ Requests some work to be done by the backend. You can get notified of the work results by passing a callback (on_receive). :param worker_class_or_function: Worker class or function :param args: worker a...
[ "def", "send_request", "(", "self", ",", "worker_class_or_function", ",", "args", ",", "on_receive", "=", "None", ")", ":", "if", "not", "self", ".", "running", ":", "try", ":", "# try to restart the backend if it crashed.", "self", ".", "start", "(", "self", ...
Requests some work to be done by the backend. You can get notified of the work results by passing a callback (on_receive). :param worker_class_or_function: Worker class or function :param args: worker args, any Json serializable objects :param on_receive: an optional callback executed w...
[ "Requests", "some", "work", "to", "be", "done", "by", "the", "backend", ".", "You", "can", "get", "notified", "of", "the", "work", "results", "by", "passing", "a", "callback", "(", "on_receive", ")", "." ]
python
train
MDAnalysis/GridDataFormats
gridData/OpenDX.py
https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/OpenDX.py#L353-L393
def write(self, file): """Write the *class array* section. Parameters ---------- file : file Raises ------ ValueError If the `dxtype` is not a valid type, :exc:`ValueError` is raised. """ if self.type not in self.dx_typ...
[ "def", "write", "(", "self", ",", "file", ")", ":", "if", "self", ".", "type", "not", "in", "self", ".", "dx_types", ":", "raise", "ValueError", "(", "(", "\"DX type {} is not supported in the DX format. \\n\"", "\"Supported valus are: {}\\n\"", "\"Use the type=<type>...
Write the *class array* section. Parameters ---------- file : file Raises ------ ValueError If the `dxtype` is not a valid type, :exc:`ValueError` is raised.
[ "Write", "the", "*", "class", "array", "*", "section", "." ]
python
valid
tehmaze/natural
natural/phone.py
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/phone.py#L123-L142
def enum(number, zone='e164.arpa'): ''' Printable DNS ENUM (telephone number mapping) record. :param number: string :param zone: string >>> print(enum('+31 20 5423 1567')) 7.6.5.1.3.2.4.5.0.2.1.3.e164.arpa. >>> print(enum('+31 97 99 6642', zone='e164.spacephone.org')) 2.4.6.6.9.9.7.9....
[ "def", "enum", "(", "number", ",", "zone", "=", "'e164.arpa'", ")", ":", "number", "=", "e164", "(", "number", ")", ".", "lstrip", "(", "'+'", ")", "return", "u'.'", ".", "join", "(", "[", "u'.'", ".", "join", "(", "number", "[", ":", ":", "-", ...
Printable DNS ENUM (telephone number mapping) record. :param number: string :param zone: string >>> print(enum('+31 20 5423 1567')) 7.6.5.1.3.2.4.5.0.2.1.3.e164.arpa. >>> print(enum('+31 97 99 6642', zone='e164.spacephone.org')) 2.4.6.6.9.9.7.9.1.3.e164.spacephone.org.
[ "Printable", "DNS", "ENUM", "(", "telephone", "number", "mapping", ")", "record", "." ]
python
train
danilobellini/dose
dose/_legacy.py
https://github.com/danilobellini/dose/blob/141f48322f7812b7d32e3d5f065d4473a11102a4/dose/_legacy.py#L497-L510
def call_after(lag): """ Parametrized decorator for calling a function after a time ``lag`` given in milliseconds. This cancels simultaneous calls. """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): wrapper.timer.cancel() # Debounce wrapper.timer = threading.Timer(lag, fun...
[ "def", "call_after", "(", "lag", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "wrapper", ".", "timer", ".", "cancel", "(", ")", "# Debo...
Parametrized decorator for calling a function after a time ``lag`` given in milliseconds. This cancels simultaneous calls.
[ "Parametrized", "decorator", "for", "calling", "a", "function", "after", "a", "time", "lag", "given", "in", "milliseconds", ".", "This", "cancels", "simultaneous", "calls", "." ]
python
train
cqparts/cqparts
src/cqparts/search.py
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts/search.py#L89-L117
def search(**criteria): """ Search registered *component* classes matching the given criteria. :param criteria: search criteria of the form: ``a='1', b='x'`` :return: parts registered with the given criteria :rtype: :class:`set` Will return an empty :class:`set` if nothing is found. :: ...
[ "def", "search", "(", "*", "*", "criteria", ")", ":", "# Find all parts that match the given criteria", "results", "=", "copy", "(", "class_list", ")", "# start with full list", "for", "(", "category", ",", "value", ")", "in", "criteria", ".", "items", "(", ")",...
Search registered *component* classes matching the given criteria. :param criteria: search criteria of the form: ``a='1', b='x'`` :return: parts registered with the given criteria :rtype: :class:`set` Will return an empty :class:`set` if nothing is found. :: from cqparts.search import se...
[ "Search", "registered", "*", "component", "*", "classes", "matching", "the", "given", "criteria", "." ]
python
train
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/status.py
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/status.py#L242-L262
def get_mapreduce_yaml(parse=parse_mapreduce_yaml): """Locates mapreduce.yaml, loads and parses its info. Args: parse: Used for testing. Returns: MapReduceYaml object. Raises: errors.BadYamlError: when contents is not a valid mapreduce.yaml file or the file is missing. """ mr_yaml_path = ...
[ "def", "get_mapreduce_yaml", "(", "parse", "=", "parse_mapreduce_yaml", ")", ":", "mr_yaml_path", "=", "find_mapreduce_yaml", "(", ")", "if", "not", "mr_yaml_path", ":", "raise", "errors", ".", "MissingYamlError", "(", ")", "mr_yaml_file", "=", "open", "(", "mr_...
Locates mapreduce.yaml, loads and parses its info. Args: parse: Used for testing. Returns: MapReduceYaml object. Raises: errors.BadYamlError: when contents is not a valid mapreduce.yaml file or the file is missing.
[ "Locates", "mapreduce", ".", "yaml", "loads", "and", "parses", "its", "info", "." ]
python
train
guaix-ucm/numina
numina/array/cosmetics.py
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/cosmetics.py#L225-L268
def cosmetics(flat1, flat2 = None, mask=None, lowercut=6.0, uppercut=6.0, siglev=2.0): """Find cosmetic defects in a detector using two flat field images. Two arrays representing flat fields of different exposure times are required. Cosmetic defects are selected as points that deviate significantly of ...
[ "def", "cosmetics", "(", "flat1", ",", "flat2", "=", "None", ",", "mask", "=", "None", ",", "lowercut", "=", "6.0", ",", "uppercut", "=", "6.0", ",", "siglev", "=", "2.0", ")", ":", "if", "flat2", "is", "None", ":", "flat1", ",", "flat2", "=", "f...
Find cosmetic defects in a detector using two flat field images. Two arrays representing flat fields of different exposure times are required. Cosmetic defects are selected as points that deviate significantly of the expected normal distribution of pixels in the ratio between `flat2` and `flat1`. ...
[ "Find", "cosmetic", "defects", "in", "a", "detector", "using", "two", "flat", "field", "images", "." ]
python
train
wmayner/pyphi
pyphi/models/fmt.py
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/models/fmt.py#L376-L398
def fmt_sia(sia, ces=True): """Format a |SystemIrreducibilityAnalysis|.""" if ces: body = ( '{ces}' '{partitioned_ces}'.format( ces=fmt_ces( sia.ces, 'Cause-effect structure'), partitioned_ces=fmt_ces( ...
[ "def", "fmt_sia", "(", "sia", ",", "ces", "=", "True", ")", ":", "if", "ces", ":", "body", "=", "(", "'{ces}'", "'{partitioned_ces}'", ".", "format", "(", "ces", "=", "fmt_ces", "(", "sia", ".", "ces", ",", "'Cause-effect structure'", ")", ",", "partit...
Format a |SystemIrreducibilityAnalysis|.
[ "Format", "a", "|SystemIrreducibilityAnalysis|", "." ]
python
train
Oneiroe/PySimpleAutomata
PySimpleAutomata/NFA.py
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/NFA.py#L232-L265
def nfa_nonemptiness_check(nfa: dict) -> bool: """ Checks if the input NFA reads any language other than the empty one, returning True/False. The language L(A) recognized by the automaton A is nonempty iff there are states :math:`s ∈ S_0` and :math:`t ∈ F` such that t is connected to s. Thus, a...
[ "def", "nfa_nonemptiness_check", "(", "nfa", ":", "dict", ")", "->", "bool", ":", "# BFS", "queue", "=", "list", "(", ")", "visited", "=", "set", "(", ")", "for", "state", "in", "nfa", "[", "'initial_states'", "]", ":", "visited", ".", "add", "(", "s...
Checks if the input NFA reads any language other than the empty one, returning True/False. The language L(A) recognized by the automaton A is nonempty iff there are states :math:`s ∈ S_0` and :math:`t ∈ F` such that t is connected to s. Thus, automata nonemptiness is equivalent to graph reachabilit...
[ "Checks", "if", "the", "input", "NFA", "reads", "any", "language", "other", "than", "the", "empty", "one", "returning", "True", "/", "False", "." ]
python
train
jbasko/configmanager
configmanager/items.py
https://github.com/jbasko/configmanager/blob/1d7229ce367143c7210d8e5f0782de03945a1721/configmanager/items.py#L315-L327
def get_path(self): """ Calculate item's path in configuration tree. Use this sparingly -- path is calculated by going up the configuration tree. For a large number of items, it is more efficient to use iterators that return paths as keys. Path value is stable only once ...
[ "def", "get_path", "(", "self", ")", ":", "if", "self", ".", "section", ":", "return", "self", ".", "section", ".", "get_path", "(", ")", "+", "(", "self", ".", "name", ",", ")", "else", ":", "return", "self", ".", "name", "," ]
Calculate item's path in configuration tree. Use this sparingly -- path is calculated by going up the configuration tree. For a large number of items, it is more efficient to use iterators that return paths as keys. Path value is stable only once the configuration tree is completely ini...
[ "Calculate", "item", "s", "path", "in", "configuration", "tree", ".", "Use", "this", "sparingly", "--", "path", "is", "calculated", "by", "going", "up", "the", "configuration", "tree", ".", "For", "a", "large", "number", "of", "items", "it", "is", "more", ...
python
train
belbio/bel
bel/lang/completion.py
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/completion.py#L494-L582
def add_completions( replace_list: list, belstr: str, replace_span: Span, completion_text: str ) -> List[Mapping[str, Any]]: """Create completions to return given replacement list Args: replace_list: list of completion replacement values belstr: BEL String replace_span: start, stop ...
[ "def", "add_completions", "(", "replace_list", ":", "list", ",", "belstr", ":", "str", ",", "replace_span", ":", "Span", ",", "completion_text", ":", "str", ")", "->", "List", "[", "Mapping", "[", "str", ",", "Any", "]", "]", ":", "completions", "=", "...
Create completions to return given replacement list Args: replace_list: list of completion replacement values belstr: BEL String replace_span: start, stop of belstr to replace completion_text: text to use for completion - used for creating highlight Returns: [{ ...
[ "Create", "completions", "to", "return", "given", "replacement", "list" ]
python
train
PGower/PyCanvas
pycanvas/apis/calendar_events.py
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/calendar_events.py#L321-L396
def update_calendar_event(self, id, calendar_event_child_event_data_X_context_code=None, calendar_event_child_event_data_X_end_at=None, calendar_event_child_event_data_X_start_at=None, calendar_event_context_code=None, calendar_event_description=None, calendar_event_end_at=None, calendar_event_location_address=None, ca...
[ "def", "update_calendar_event", "(", "self", ",", "id", ",", "calendar_event_child_event_data_X_context_code", "=", "None", ",", "calendar_event_child_event_data_X_end_at", "=", "None", ",", "calendar_event_child_event_data_X_start_at", "=", "None", ",", "calendar_event_context...
Update a calendar event. Update and return a calendar event
[ "Update", "a", "calendar", "event", ".", "Update", "and", "return", "a", "calendar", "event" ]
python
train
kplindegaard/smbus2
smbus2/smbus2.py
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L409-L427
def read_word_data(self, i2c_addr, register, force=None): """ Read a single word (2 bytes) from a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to read :type register: int :param force: :type force: Boolean ...
[ "def", "read_word_data", "(", "self", ",", "i2c_addr", ",", "register", ",", "force", "=", "None", ")", ":", "self", ".", "_set_address", "(", "i2c_addr", ",", "force", "=", "force", ")", "msg", "=", "i2c_smbus_ioctl_data", ".", "create", "(", "read_write"...
Read a single word (2 bytes) from a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to read :type register: int :param force: :type force: Boolean :return: 2-byte word :rtype: int
[ "Read", "a", "single", "word", "(", "2", "bytes", ")", "from", "a", "given", "register", "." ]
python
train
Kozea/wdb
client/wdb/__init__.py
https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L813-L876
def interaction( self, frame, tb=None, exception='Wdb', exception_description='Stepping', init=None, shell=False, shell_vars=None, source=None, iframe_mode=False, timeout=None, ...
[ "def", "interaction", "(", "self", ",", "frame", ",", "tb", "=", "None", ",", "exception", "=", "'Wdb'", ",", "exception_description", "=", "'Stepping'", ",", "init", "=", "None", ",", "shell", "=", "False", ",", "shell_vars", "=", "None", ",", "source",...
User interaction handling blocking on socket receive
[ "User", "interaction", "handling", "blocking", "on", "socket", "receive" ]
python
train
phn/lineid_plot
lineid_plot/lineid_plot.py
https://github.com/phn/lineid_plot/blob/7c7a1af53fe439b3a7c5a57f01680575837fb978/lineid_plot/lineid_plot.py#L124-L219
def adjust_boxes(line_wave, box_widths, left_edge, right_edge, max_iter=1000, adjust_factor=0.35, factor_decrement=3.0, fd_p=0.75): """Ajdust given boxes so that they don't overlap. Parameters ---------- line_wave: list or array of floats Line wave lengths. The...
[ "def", "adjust_boxes", "(", "line_wave", ",", "box_widths", ",", "left_edge", ",", "right_edge", ",", "max_iter", "=", "1000", ",", "adjust_factor", "=", "0.35", ",", "factor_decrement", "=", "3.0", ",", "fd_p", "=", "0.75", ")", ":", "# Adjust positions.", ...
Ajdust given boxes so that they don't overlap. Parameters ---------- line_wave: list or array of floats Line wave lengths. These are assumed to be the initial y (wave length) location of the boxes. box_widths: list or array of floats Width of box containing labels for each line ...
[ "Ajdust", "given", "boxes", "so", "that", "they", "don", "t", "overlap", "." ]
python
train
iLampard/x-utils
xutils/config_utils.py
https://github.com/iLampard/x-utils/blob/291d92832ee0e0c89bc22e10ecf2f44445e0d300/xutils/config_utils.py#L38-L73
def merge_configs(to_be_merged, default): """Merges two configuration dictionaries by overwriting values with same keys, with the priority on values given on the 'left' side, so the to_be_merged dict. Notice that with lists in the configuration, it skips from the default (right side) the tuples in t...
[ "def", "merge_configs", "(", "to_be_merged", ",", "default", ")", ":", "if", "isinstance", "(", "to_be_merged", ",", "dict", ")", "and", "isinstance", "(", "default", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "default", ".", "items", "(", ")",...
Merges two configuration dictionaries by overwriting values with same keys, with the priority on values given on the 'left' side, so the to_be_merged dict. Notice that with lists in the configuration, it skips from the default (right side) the tuples in that which already exist in the left side to_b...
[ "Merges", "two", "configuration", "dictionaries", "by", "overwriting", "values", "with", "same", "keys", "with", "the", "priority", "on", "values", "given", "on", "the", "left", "side", "so", "the", "to_be_merged", "dict", ".", "Notice", "that", "with", "lists...
python
train
senaite/senaite.core
bika/lims/content/analysisprofile.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/analysisprofile.py#L212-L235
def remove_service(self, service): """Removes the service passed in from the services offered by the current Profile. If the Analysis Service passed in is not assigned to this Analysis Profile, returns False. :param service: the service to be removed from this Analysis Profile :t...
[ "def", "remove_service", "(", "self", ",", "service", ")", ":", "obj", "=", "api", ".", "get_object", "(", "service", ")", "uid", "=", "api", ".", "get_uid", "(", "obj", ")", "# Remove the service from the referenced services", "services", "=", "self", ".", ...
Removes the service passed in from the services offered by the current Profile. If the Analysis Service passed in is not assigned to this Analysis Profile, returns False. :param service: the service to be removed from this Analysis Profile :type service: AnalysisService :return: ...
[ "Removes", "the", "service", "passed", "in", "from", "the", "services", "offered", "by", "the", "current", "Profile", ".", "If", "the", "Analysis", "Service", "passed", "in", "is", "not", "assigned", "to", "this", "Analysis", "Profile", "returns", "False", "...
python
train
maas/python-libmaas
maas/client/viscera/block_devices.py
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/block_devices.py#L130-L133
async def unformat(self): """Unformat this block device.""" self._data = await self._handler.unformat( system_id=self.node.system_id, id=self.id)
[ "async", "def", "unformat", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "unformat", "(", "system_id", "=", "self", ".", "node", ".", "system_id", ",", "id", "=", "self", ".", "id", ")" ]
Unformat this block device.
[ "Unformat", "this", "block", "device", "." ]
python
train
tmux-python/tmuxp
tmuxp/cli.py
https://github.com/tmux-python/tmuxp/blob/f4aa2e26589a4311131898d2e4a85cb1876b5c9b/tmuxp/cli.py#L66-L84
def get_tmuxinator_dir(): """ Return tmuxinator configuration directory. Checks for ``TMUXINATOR_CONFIG`` environmental variable. Returns ------- str : absolute path to tmuxinator config directory See Also -------- :meth:`tmuxp.config.import_tmuxinator` """ if 'TMU...
[ "def", "get_tmuxinator_dir", "(", ")", ":", "if", "'TMUXINATOR_CONFIG'", "in", "os", ".", "environ", ":", "return", "os", ".", "path", ".", "expanduser", "(", "os", ".", "environ", "[", "'TMUXINATOR_CONFIG'", "]", ")", "return", "os", ".", "path", ".", "...
Return tmuxinator configuration directory. Checks for ``TMUXINATOR_CONFIG`` environmental variable. Returns ------- str : absolute path to tmuxinator config directory See Also -------- :meth:`tmuxp.config.import_tmuxinator`
[ "Return", "tmuxinator", "configuration", "directory", "." ]
python
train
readbeyond/aeneas
aeneas/diagnostics.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L195-L209
def check_cdtw(cls): """ Check whether Python C extension ``cdtw`` can be imported. Return ``True`` on failure and ``False`` on success. :rtype: bool """ if gf.can_run_c_extension("cdtw"): gf.print_success(u"aeneas.cdtw AVAILABLE") return Fals...
[ "def", "check_cdtw", "(", "cls", ")", ":", "if", "gf", ".", "can_run_c_extension", "(", "\"cdtw\"", ")", ":", "gf", ".", "print_success", "(", "u\"aeneas.cdtw AVAILABLE\"", ")", "return", "False", "gf", ".", "print_warning", "(", "u\"aeneas.cdtw NOT AVAILABL...
Check whether Python C extension ``cdtw`` can be imported. Return ``True`` on failure and ``False`` on success. :rtype: bool
[ "Check", "whether", "Python", "C", "extension", "cdtw", "can", "be", "imported", "." ]
python
train
magrathealabs/feito
feito/prospector.py
https://github.com/magrathealabs/feito/blob/4179e40233ccf6e5a6c9892e528595690ce9ef43/feito/prospector.py#L10-L16
def run(self): """ Runs prospector in the input files and returns a json with the analysis """ arg_prospector = f'prospector --output-format json {self.repo.diff_files()}' analysis = subprocess.run(arg_prospector, stdout=subprocess.PIPE, shell=True) return json.loads(anal...
[ "def", "run", "(", "self", ")", ":", "arg_prospector", "=", "f'prospector --output-format json {self.repo.diff_files()}'", "analysis", "=", "subprocess", ".", "run", "(", "arg_prospector", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "True", "...
Runs prospector in the input files and returns a json with the analysis
[ "Runs", "prospector", "in", "the", "input", "files", "and", "returns", "a", "json", "with", "the", "analysis" ]
python
train
diffeo/yakonfig
yakonfig/toplevel.py
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/toplevel.py#L414-L441
def fill_in_arguments(config, modules, args): """Fill in configuration fields from command-line arguments. `config` is a dictionary holding the initial configuration, probably the result of :func:`assemble_default_config`. It reads through `modules`, and for each, fills in any configuration values ...
[ "def", "fill_in_arguments", "(", "config", ",", "modules", ",", "args", ")", ":", "def", "work_in", "(", "config", ",", "module", ",", "name", ")", ":", "rkeys", "=", "getattr", "(", "module", ",", "'runtime_keys'", ",", "{", "}", ")", "for", "(", "a...
Fill in configuration fields from command-line arguments. `config` is a dictionary holding the initial configuration, probably the result of :func:`assemble_default_config`. It reads through `modules`, and for each, fills in any configuration values that are provided in `args`. `config` is modifi...
[ "Fill", "in", "configuration", "fields", "from", "command", "-", "line", "arguments", "." ]
python
train
Opentrons/opentrons
api/src/opentrons/protocol_api/contexts.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/contexts.py#L1063-L1082
def distribute(self, volume: float, source: Well, dest: List[Well], *args, **kwargs) -> 'InstrumentContext': """ Move a volume of liquid from one source to multiple destinations. :param volume: The amount of volume to d...
[ "def", "distribute", "(", "self", ",", "volume", ":", "float", ",", "source", ":", "Well", ",", "dest", ":", "List", "[", "Well", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "'InstrumentContext'", ":", "self", ".", "_log", ".", "debu...
Move a volume of liquid from one source to multiple destinations. :param volume: The amount of volume to distribute to each destination well. :param source: A single well from where liquid will be aspirated. :param dest: List of Wells where liquid will be dispensed to. ...
[ "Move", "a", "volume", "of", "liquid", "from", "one", "source", "to", "multiple", "destinations", "." ]
python
train
saltstack/salt
salt/modules/ldap3.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ldap3.py#L109-L306
def connect(connect_spec=None): '''Connect and optionally bind to an LDAP server. :param connect_spec: This can be an LDAP connection object returned by a previous call to :py:func:`connect` (in which case the argument is simply returned), ``None`` (in which case an empty dict is ...
[ "def", "connect", "(", "connect_spec", "=", "None", ")", ":", "if", "isinstance", "(", "connect_spec", ",", "_connect_ctx", ")", ":", "return", "connect_spec", "if", "connect_spec", "is", "None", ":", "connect_spec", "=", "{", "}", "backend_name", "=", "conn...
Connect and optionally bind to an LDAP server. :param connect_spec: This can be an LDAP connection object returned by a previous call to :py:func:`connect` (in which case the argument is simply returned), ``None`` (in which case an empty dict is used), or a dict with the following k...
[ "Connect", "and", "optionally", "bind", "to", "an", "LDAP", "server", "." ]
python
train
callowayproject/Transmogrify
transmogrify/images2gif.py
https://github.com/callowayproject/Transmogrify/blob/f1f891b8b923b3a1ede5eac7f60531c1c472379e/transmogrify/images2gif.py#L977-L991
def palette_image(self): """ PIL weird interface for making a paletted image: create an image which already has the palette, and use that in Image.quantize. This function returns this palette image. """ if self.pimage is None: palette = [] for i in range(s...
[ "def", "palette_image", "(", "self", ")", ":", "if", "self", ".", "pimage", "is", "None", ":", "palette", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "NETSIZE", ")", ":", "palette", ".", "extend", "(", "self", ".", "colormap", "[", ...
PIL weird interface for making a paletted image: create an image which already has the palette, and use that in Image.quantize. This function returns this palette image.
[ "PIL", "weird", "interface", "for", "making", "a", "paletted", "image", ":", "create", "an", "image", "which", "already", "has", "the", "palette", "and", "use", "that", "in", "Image", ".", "quantize", ".", "This", "function", "returns", "this", "palette", ...
python
train
timdiels/pytil
pytil/algorithms.py
https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/algorithms.py#L43-L71
def multi_way_partitioning(items, bin_count): #TODO rename bin_count -> bins ''' Greedily divide weighted items equally across bins. This approximately solves a multi-way partition problem, minimising the difference between the largest and smallest sum of weights in a bin. Parameters ---------...
[ "def", "multi_way_partitioning", "(", "items", ",", "bin_count", ")", ":", "#TODO rename bin_count -> bins", "bins", "=", "[", "_Bin", "(", ")", "for", "_", "in", "range", "(", "bin_count", ")", "]", "for", "item", ",", "weight", "in", "sorted", "(", "item...
Greedily divide weighted items equally across bins. This approximately solves a multi-way partition problem, minimising the difference between the largest and smallest sum of weights in a bin. Parameters ---------- items : ~typing.Iterable[~typing.Tuple[~typing.Any, float]] Weighted items ...
[ "Greedily", "divide", "weighted", "items", "equally", "across", "bins", "." ]
python
train
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/thread.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1172-L1232
def __get_stack_trace_manually(self, depth = 16, bUseLabels = True, bMakePretty = True): """ Tries to get a stack trace for the current function. Only works for functions with standard prologue and epilogue. @type depth: int ...
[ "def", "__get_stack_trace_manually", "(", "self", ",", "depth", "=", "16", ",", "bUseLabels", "=", "True", ",", "bMakePretty", "=", "True", ")", ":", "aProcess", "=", "self", ".", "get_process", "(", ")", "st", ",", "sb", "=", "self", ".", "get_stack_ran...
Tries to get a stack trace for the current function. Only works for functions with standard prologue and epilogue. @type depth: int @param depth: Maximum depth of stack trace. @type bUseLabels: bool @param bUseLabels: C{True} to use labels, C{False} to use addresses. ...
[ "Tries", "to", "get", "a", "stack", "trace", "for", "the", "current", "function", ".", "Only", "works", "for", "functions", "with", "standard", "prologue", "and", "epilogue", "." ]
python
train
sebdah/dynamic-dynamodb
dynamic_dynamodb/core/circuit_breaker.py
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/circuit_breaker.py#L13-L97
def is_open(table_name=None, table_key=None, gsi_name=None, gsi_key=None): """ Checks whether the circuit breaker is open :param table_name: Name of the table being checked :param table_key: Configuration key for table :param gsi_name: Name of the GSI being checked :param gsi_key: Configuration key...
[ "def", "is_open", "(", "table_name", "=", "None", ",", "table_key", "=", "None", ",", "gsi_name", "=", "None", ",", "gsi_key", "=", "None", ")", ":", "logger", ".", "debug", "(", "'Checking circuit breaker status'", ")", "# Parse the URL to make sure it is OK", ...
Checks whether the circuit breaker is open :param table_name: Name of the table being checked :param table_key: Configuration key for table :param gsi_name: Name of the GSI being checked :param gsi_key: Configuration key for the GSI :returns: bool -- True if the circuit is open
[ "Checks", "whether", "the", "circuit", "breaker", "is", "open" ]
python
train
tanghaibao/jcvi
jcvi/formats/gff.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/gff.py#L663-L697
def sizes(args): """ %prog sizes gffile Given a gff file of features, calculate the sizes of chosen parent feature based on summation of sizes of child features. For example, for parent 'mRNA' and child 'CDS' feature types, calcuate sizes of mRNA by summing the sizes of the disjoint CDS parts....
[ "def", "sizes", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "sizes", ".", "__doc__", ")", "p", ".", "set_outfile", "(", ")", "p", ".", "add_option", "(", "\"--parents\"", ",", "dest", "=", "\"parents\"", ",", "default", "=", "\"mRNA\"", ",", ...
%prog sizes gffile Given a gff file of features, calculate the sizes of chosen parent feature based on summation of sizes of child features. For example, for parent 'mRNA' and child 'CDS' feature types, calcuate sizes of mRNA by summing the sizes of the disjoint CDS parts.
[ "%prog", "sizes", "gffile" ]
python
train
noahbenson/pimms
pimms/util.py
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/util.py#L775-L793
def flatten_maps(*args, **kwargs): ''' flatten_maps(*args, **kwags) yields a tuple of the maps in the given arguments; this flattens over lists and iterables so long as all elements eventually yield True to is_map(el). The optional keyword arguments passed make up the final map. This funtion do...
[ "def", "flatten_maps", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "_recur", "(", "arg", ",", "work", ")", ":", "if", "is_map", "(", "arg", ")", ":", "work", ".", "append", "(", "arg", ")", "elif", "is_str", "(", "arg", ")", "or...
flatten_maps(*args, **kwags) yields a tuple of the maps in the given arguments; this flattens over lists and iterables so long as all elements eventually yield True to is_map(el). The optional keyword arguments passed make up the final map. This funtion does not evaluate any values of any of the maps a...
[ "flatten_maps", "(", "*", "args", "**", "kwags", ")", "yields", "a", "tuple", "of", "the", "maps", "in", "the", "given", "arguments", ";", "this", "flattens", "over", "lists", "and", "iterables", "so", "long", "as", "all", "elements", "eventually", "yield"...
python
train
jreese/dotlink
dotlink/dotlink.py
https://github.com/jreese/dotlink/blob/5e48c1493c20fc6df4ad0144e80563915ce339b6/dotlink/dotlink.py#L366-L400
def deploy_local(self, dotfiles, target_root=None): """Deploy dotfiles to a local path.""" if target_root is None: target_root = self.args.path for source_path, target_path in dotfiles.items(): source_path = path.join(self.source, source_path) target_path = p...
[ "def", "deploy_local", "(", "self", ",", "dotfiles", ",", "target_root", "=", "None", ")", ":", "if", "target_root", "is", "None", ":", "target_root", "=", "self", ".", "args", ".", "path", "for", "source_path", ",", "target_path", "in", "dotfiles", ".", ...
Deploy dotfiles to a local path.
[ "Deploy", "dotfiles", "to", "a", "local", "path", "." ]
python
train
eddiejessup/metropack
metropack/draw.py
https://github.com/eddiejessup/metropack/blob/528b47d0f2f70f39e1490e41433f2da8c8b9d63c/metropack/draw.py#L6-L37
def _unwrap_one_layer(r, L, n): """For a set of points in a 2 dimensional periodic system, extend the set of points to tile the points at a given period. Parameters ---------- r: float array, shape (:, 2). Set of points. L: float array, shape (2,) System lengths. n: integer....
[ "def", "_unwrap_one_layer", "(", "r", ",", "L", ",", "n", ")", ":", "try", ":", "L", "[", "0", "]", "except", "(", "TypeError", ",", "IndexError", ")", ":", "L", "=", "np", ".", "ones", "(", "[", "r", ".", "shape", "[", "1", "]", "]", ")", ...
For a set of points in a 2 dimensional periodic system, extend the set of points to tile the points at a given period. Parameters ---------- r: float array, shape (:, 2). Set of points. L: float array, shape (2,) System lengths. n: integer. Period to unwrap. Returns...
[ "For", "a", "set", "of", "points", "in", "a", "2", "dimensional", "periodic", "system", "extend", "the", "set", "of", "points", "to", "tile", "the", "points", "at", "a", "given", "period", "." ]
python
train
KelSolaar/Umbra
umbra/components/addons/projects_explorer/projects_explorer.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/addons/projects_explorer/projects_explorer.py#L1111-L1140
def add_new_directory(self, node): """ Adds a new directory next to given Node associated path. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Method success. :rtype: bool """ if self.__script_editor.model.is_authoring_n...
[ "def", "add_new_directory", "(", "self", ",", "node", ")", ":", "if", "self", ".", "__script_editor", ".", "model", ".", "is_authoring_node", "(", "node", ")", ":", "return", "False", "directory", ",", "state", "=", "QInputDialog", ".", "getText", "(", "se...
Adds a new directory next to given Node associated path. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Method success. :rtype: bool
[ "Adds", "a", "new", "directory", "next", "to", "given", "Node", "associated", "path", "." ]
python
train
aiidateam/aiida-codtools
aiida_codtools/workflows/cif_clean.py
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/workflows/cif_clean.py#L112-L126
def run_select_calculation(self): """Run the CifSelectCalculation on the CifData output node of the CifFilterCalculation.""" inputs = { 'cif': self.ctx.cif, 'code': self.inputs.cif_select, 'parameters': self.inputs.cif_select_parameters, 'metadata': { ...
[ "def", "run_select_calculation", "(", "self", ")", ":", "inputs", "=", "{", "'cif'", ":", "self", ".", "ctx", ".", "cif", ",", "'code'", ":", "self", ".", "inputs", ".", "cif_select", ",", "'parameters'", ":", "self", ".", "inputs", ".", "cif_select_para...
Run the CifSelectCalculation on the CifData output node of the CifFilterCalculation.
[ "Run", "the", "CifSelectCalculation", "on", "the", "CifData", "output", "node", "of", "the", "CifFilterCalculation", "." ]
python
train
saltstack/salt
salt/modules/win_lgpo.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_lgpo.py#L5637-L5695
def _checkListItem(policy_element, policy_name, policy_key, xpath_object, policy_file_data, test_items=True): ''' helper function to process an enabled/disabled/true/falseList set if test_items is True, it will determine if the policy is enabled or disabled returning True if all items are configured in...
[ "def", "_checkListItem", "(", "policy_element", ",", "policy_name", ",", "policy_key", ",", "xpath_object", ",", "policy_file_data", ",", "test_items", "=", "True", ")", ":", "xpath_string", "=", "(", "'.//*[local-name() = \"decimal\" or local-name() = \"delete\"'", "' or...
helper function to process an enabled/disabled/true/falseList set if test_items is True, it will determine if the policy is enabled or disabled returning True if all items are configured in the registry.pol file and false if they are not if test_items is False, the expected strings for the items will ...
[ "helper", "function", "to", "process", "an", "enabled", "/", "disabled", "/", "true", "/", "falseList", "set" ]
python
train
pandemicsyn/statsdpy
statsdpy/statsd.py
https://github.com/pandemicsyn/statsdpy/blob/9cfccf89121fd6a12df20f17fa3eb8f618a36455/statsdpy/statsd.py#L124-L144
def stats_flush(self): """ Periodically flush stats to graphite """ while True: try: eventlet.sleep(self.flush_interval) if self.debug: print "seen %d stats so far." % self.stats_seen print "current count...
[ "def", "stats_flush", "(", "self", ")", ":", "while", "True", ":", "try", ":", "eventlet", ".", "sleep", "(", "self", ".", "flush_interval", ")", "if", "self", ".", "debug", ":", "print", "\"seen %d stats so far.\"", "%", "self", ".", "stats_seen", "print"...
Periodically flush stats to graphite
[ "Periodically", "flush", "stats", "to", "graphite" ]
python
train
PinLin/KCOJ_api
KCOJ_api/api.py
https://github.com/PinLin/KCOJ_api/blob/64f6ef0f9e64dc1efd692cbe6d5738ee7cfb78ec/KCOJ_api/api.py#L66-L107
def get_question(self, number: str=None) -> dict: """ 取得課程中的所有題目資訊 """ try: # 取得資料 response = self.__session.get( self.__url + '/HomeworkBoard', timeout=0.5, verify=False) soup = BeautifulSoup(response.text, 'html.parser') #...
[ "def", "get_question", "(", "self", ",", "number", ":", "str", "=", "None", ")", "->", "dict", ":", "try", ":", "# 取得資料", "response", "=", "self", ".", "__session", ".", "get", "(", "self", ".", "__url", "+", "'/HomeworkBoard'", ",", "timeout", "=", ...
取得課程中的所有題目資訊
[ "取得課程中的所有題目資訊" ]
python
train
exosite-labs/pyonep
pyonep/portals/endpoints.py
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/endpoints.py#L212-L242
def add_device(self, model, serial): """ Returns 'device object' of newly created device. http://docs.exosite.com/portals/#create-device http://docs.exosite.com/portals/#device-object """ device = { 'model': model, 'vendor': se...
[ "def", "add_device", "(", "self", ",", "model", ",", "serial", ")", ":", "device", "=", "{", "'model'", ":", "model", ",", "'vendor'", ":", "self", ".", "vendor", "(", ")", ",", "'sn'", ":", "serial", ",", "'type'", ":", "'vendor'", "}", "headers", ...
Returns 'device object' of newly created device. http://docs.exosite.com/portals/#create-device http://docs.exosite.com/portals/#device-object
[ "Returns", "device", "object", "of", "newly", "created", "device", "." ]
python
train
dcramer/peek
peek/tracer.py
https://github.com/dcramer/peek/blob/da7c086660fc870c6632c4dc5ccb2ff9bfbee52e/peek/tracer.py#L237-L248
def start(self, origin): """ Start this Tracer. Return a Python function suitable for use with sys.settrace(). """ self.start_time = time.time() self.pause_until = None self.data.update(self._get_struct(origin, 'origin')) self.data_stack.append(self.data)...
[ "def", "start", "(", "self", ",", "origin", ")", ":", "self", ".", "start_time", "=", "time", ".", "time", "(", ")", "self", ".", "pause_until", "=", "None", "self", ".", "data", ".", "update", "(", "self", ".", "_get_struct", "(", "origin", ",", "...
Start this Tracer. Return a Python function suitable for use with sys.settrace().
[ "Start", "this", "Tracer", "." ]
python
train
frascoweb/frasco
frasco/expression.py
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/expression.py#L348-L368
def eval_expr(expr, context): """Recursively evaluates a compiled expression using the specified context. Dict instances can contain a "__kwargs" key which will be used to update the dict with its content """ if isinstance(expr, list): rv = [] for item in expr: rv.append(...
[ "def", "eval_expr", "(", "expr", ",", "context", ")", ":", "if", "isinstance", "(", "expr", ",", "list", ")", ":", "rv", "=", "[", "]", "for", "item", "in", "expr", ":", "rv", ".", "append", "(", "eval_expr", "(", "item", ",", "context", ")", ")"...
Recursively evaluates a compiled expression using the specified context. Dict instances can contain a "__kwargs" key which will be used to update the dict with its content
[ "Recursively", "evaluates", "a", "compiled", "expression", "using", "the", "specified", "context", ".", "Dict", "instances", "can", "contain", "a", "__kwargs", "key", "which", "will", "be", "used", "to", "update", "the", "dict", "with", "its", "content" ]
python
train
kmike/django-generic-images
generic_images/admin.py
https://github.com/kmike/django-generic-images/blob/4e45068ed219ac35396758eb6b6e1fe5306147df/generic_images/admin.py#L10-L29
def attachedimage_form_factory(lang='en', debug=False): ''' Returns ModelForm class to be used in admin. 'lang' is the language for GearsUploader (can be 'en' and 'ru' at the moment). ''' yui = '' if debug else '.yui' class _AttachedImageAdminForm(forms.ModelForm): caption = for...
[ "def", "attachedimage_form_factory", "(", "lang", "=", "'en'", ",", "debug", "=", "False", ")", ":", "yui", "=", "''", "if", "debug", "else", "'.yui'", "class", "_AttachedImageAdminForm", "(", "forms", ".", "ModelForm", ")", ":", "caption", "=", "forms", "...
Returns ModelForm class to be used in admin. 'lang' is the language for GearsUploader (can be 'en' and 'ru' at the moment).
[ "Returns", "ModelForm", "class", "to", "be", "used", "in", "admin", ".", "lang", "is", "the", "language", "for", "GearsUploader", "(", "can", "be", "en", "and", "ru", "at", "the", "moment", ")", "." ]
python
train
apache/incubator-mxnet
python/mxnet/image/image.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/image/image.py#L1409-L1428
def imdecode(self, s): """Decodes a string or byte string to an NDArray. See mx.img.imdecode for more details.""" def locate(): """Locate the image file/index if decode fails.""" if self.seq is not None: idx = self.seq[(self.cur % self.num_image) - 1] ...
[ "def", "imdecode", "(", "self", ",", "s", ")", ":", "def", "locate", "(", ")", ":", "\"\"\"Locate the image file/index if decode fails.\"\"\"", "if", "self", ".", "seq", "is", "not", "None", ":", "idx", "=", "self", ".", "seq", "[", "(", "self", ".", "cu...
Decodes a string or byte string to an NDArray. See mx.img.imdecode for more details.
[ "Decodes", "a", "string", "or", "byte", "string", "to", "an", "NDArray", ".", "See", "mx", ".", "img", ".", "imdecode", "for", "more", "details", "." ]
python
train
vberlier/nbtlib
nbtlib/literal/serializer.py
https://github.com/vberlier/nbtlib/blob/9c9d58b5c4a530b0f1ffd76dda176f00406c3547/nbtlib/literal/serializer.py#L142-L150
def serialize_list(self, tag): """Return the literal representation of a list tag.""" separator, fmt = self.comma, '[{}]' with self.depth(): if self.should_expand(tag): separator, fmt = self.expand(separator, fmt) return fmt.format(separator.join(map(sel...
[ "def", "serialize_list", "(", "self", ",", "tag", ")", ":", "separator", ",", "fmt", "=", "self", ".", "comma", ",", "'[{}]'", "with", "self", ".", "depth", "(", ")", ":", "if", "self", ".", "should_expand", "(", "tag", ")", ":", "separator", ",", ...
Return the literal representation of a list tag.
[ "Return", "the", "literal", "representation", "of", "a", "list", "tag", "." ]
python
train
amzn/ion-python
amazon/ion/reader_text.py
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L2152-L2176
def _skip_trampoline(handler): """Intercepts events from container handlers, emitting them only if they should not be skipped.""" data_event, self = (yield None) delegate = handler event = None depth = 0 while True: def pass_through(): _trans = delegate.send(Transition(data_e...
[ "def", "_skip_trampoline", "(", "handler", ")", ":", "data_event", ",", "self", "=", "(", "yield", "None", ")", "delegate", "=", "handler", "event", "=", "None", "depth", "=", "0", "while", "True", ":", "def", "pass_through", "(", ")", ":", "_trans", "...
Intercepts events from container handlers, emitting them only if they should not be skipped.
[ "Intercepts", "events", "from", "container", "handlers", "emitting", "them", "only", "if", "they", "should", "not", "be", "skipped", "." ]
python
train
jason-weirather/pythologist
pythologist/__init__.py
https://github.com/jason-weirather/pythologist/blob/6eb4082be9dffa9570e4ceaa06d97845eac4c006/pythologist/__init__.py#L223-L237
def is_uniform(self,verbose=True): """ Check to make sure phenotype calls, or scored calls are consistent across all images / samples """ uni = pd.Series(self['phenotype_calls'].apply(lambda x: json.dumps(x)).unique()).\ apply(lambda x: json.loads(x)).apply(lambda x: tuple(so...
[ "def", "is_uniform", "(", "self", ",", "verbose", "=", "True", ")", ":", "uni", "=", "pd", ".", "Series", "(", "self", "[", "'phenotype_calls'", "]", ".", "apply", "(", "lambda", "x", ":", "json", ".", "dumps", "(", "x", ")", ")", ".", "unique", ...
Check to make sure phenotype calls, or scored calls are consistent across all images / samples
[ "Check", "to", "make", "sure", "phenotype", "calls", "or", "scored", "calls", "are", "consistent", "across", "all", "images", "/", "samples" ]
python
train
secdev/scapy
scapy/contrib/isotp.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/contrib/isotp.py#L347-L370
def pop(self, identifier=None, ext_addr=None, basecls=ISOTP): """ Returns a built ISOTP message :param identifier: if not None, only return isotp messages with this destination :param ext_addr: if identifier is not None, only return isotp messages ...
[ "def", "pop", "(", "self", ",", "identifier", "=", "None", ",", "ext_addr", "=", "None", ",", "basecls", "=", "ISOTP", ")", ":", "if", "identifier", "is", "not", "None", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "ready", ")", ...
Returns a built ISOTP message :param identifier: if not None, only return isotp messages with this destination :param ext_addr: if identifier is not None, only return isotp messages with this extended address for destination :param basecls: the...
[ "Returns", "a", "built", "ISOTP", "message", ":", "param", "identifier", ":", "if", "not", "None", "only", "return", "isotp", "messages", "with", "this", "destination", ":", "param", "ext_addr", ":", "if", "identifier", "is", "not", "None", "only", "return",...
python
train
tango-controls/pytango
tango/utils.py
https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/utils.py#L1264-L1271
def insert(self, i, x): """s.insert(i, x) same as s[i:i] = [x] Raises TypeError if x isn't a string.""" if not isinstance(x, str): raise TypeError( 'Members of this object must be strings. ' 'You supplied \"%s\"' % type(x)) list.insert(self, i,...
[ "def", "insert", "(", "self", ",", "i", ",", "x", ")", ":", "if", "not", "isinstance", "(", "x", ",", "str", ")", ":", "raise", "TypeError", "(", "'Members of this object must be strings. '", "'You supplied \\\"%s\\\"'", "%", "type", "(", "x", ")", ")", "l...
s.insert(i, x) same as s[i:i] = [x] Raises TypeError if x isn't a string.
[ "s", ".", "insert", "(", "i", "x", ")", "same", "as", "s", "[", "i", ":", "i", "]", "=", "[", "x", "]", "Raises", "TypeError", "if", "x", "isn", "t", "a", "string", "." ]
python
train
tamasgal/km3pipe
km3pipe/utils/streamds.py
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/streamds.py#L165-L203
def convert_runsummary_to_json( df, comment='Uploaded via km3pipe.StreamDS', prefix='TEST_' ): """Convert a Pandas DataFrame with runsummary to JSON for DB upload""" data_field = [] comment += ", by {}".format(getpass.getuser()) for det_id, det_data in df.groupby('det_id'): runs_field = ...
[ "def", "convert_runsummary_to_json", "(", "df", ",", "comment", "=", "'Uploaded via km3pipe.StreamDS'", ",", "prefix", "=", "'TEST_'", ")", ":", "data_field", "=", "[", "]", "comment", "+=", "\", by {}\"", ".", "format", "(", "getpass", ".", "getuser", "(", ")...
Convert a Pandas DataFrame with runsummary to JSON for DB upload
[ "Convert", "a", "Pandas", "DataFrame", "with", "runsummary", "to", "JSON", "for", "DB", "upload" ]
python
train
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py#L2612-L2657
def add_resize_bilinear(self, name, input_name, output_name, target_height=1, target_width=1, mode='ALIGN_ENDPOINTS_MODE'): """ Add resize bilinear layer to the model. A layer that resizes the input to a given spatial size using bilinear interpolation. Parameters ...
[ "def", "add_resize_bilinear", "(", "self", ",", "name", ",", "input_name", ",", "output_name", ",", "target_height", "=", "1", ",", "target_width", "=", "1", ",", "mode", "=", "'ALIGN_ENDPOINTS_MODE'", ")", ":", "spec", "=", "self", ".", "spec", "nn_spec", ...
Add resize bilinear layer to the model. A layer that resizes the input to a given spatial size using bilinear interpolation. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str ...
[ "Add", "resize", "bilinear", "layer", "to", "the", "model", ".", "A", "layer", "that", "resizes", "the", "input", "to", "a", "given", "spatial", "size", "using", "bilinear", "interpolation", "." ]
python
train
sio2project/filetracker
filetracker/client/data_store.py
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/data_store.py#L80-L98
def get_file(self, name, filename): """Saves the content of file named ``name`` to ``filename``. Works like :meth:`get_stream`, but ``filename`` is the name of a file which will be created (or overwritten). Returns the full versioned name of the retrieved file. """ ...
[ "def", "get_file", "(", "self", ",", "name", ",", "filename", ")", ":", "stream", ",", "vname", "=", "self", ".", "get_stream", "(", "name", ")", "path", ",", "version", "=", "split_name", "(", "vname", ")", "dir_path", "=", "os", ".", "path", ".", ...
Saves the content of file named ``name`` to ``filename``. Works like :meth:`get_stream`, but ``filename`` is the name of a file which will be created (or overwritten). Returns the full versioned name of the retrieved file.
[ "Saves", "the", "content", "of", "file", "named", "name", "to", "filename", "." ]
python
train
google/grr
grr/core/grr_response_core/lib/parsers/linux_file_parser.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/parsers/linux_file_parser.py#L679-L711
def ParseFileset(self, fileset=None): """Process linux system login files. Orchestrates collection of account entries from /etc/passwd and /etc/shadow. The passwd and shadow entries are reconciled and group memberships are mapped to the account. Args: fileset: A dict of files mapped from pa...
[ "def", "ParseFileset", "(", "self", ",", "fileset", "=", "None", ")", ":", "self", ".", "AddPassword", "(", "fileset", ")", "self", ".", "AddShadow", "(", "fileset", ")", "self", ".", "ReconcileShadow", "(", "self", ".", "shadow_store", ")", "# Get group m...
Process linux system login files. Orchestrates collection of account entries from /etc/passwd and /etc/shadow. The passwd and shadow entries are reconciled and group memberships are mapped to the account. Args: fileset: A dict of files mapped from path to an open file. Yields: - A se...
[ "Process", "linux", "system", "login", "files", "." ]
python
train
Autodesk/aomi
aomi/model/context.py
https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L155-L159
def thaw(self, tmp_dir): """Will thaw every secret into an appropriate temporary location""" for resource in self.resources(): if resource.present: resource.thaw(tmp_dir)
[ "def", "thaw", "(", "self", ",", "tmp_dir", ")", ":", "for", "resource", "in", "self", ".", "resources", "(", ")", ":", "if", "resource", ".", "present", ":", "resource", ".", "thaw", "(", "tmp_dir", ")" ]
Will thaw every secret into an appropriate temporary location
[ "Will", "thaw", "every", "secret", "into", "an", "appropriate", "temporary", "location" ]
python
train
bwohlberg/sporco
sporco/linalg.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/linalg.py#L1379-L1413
def rfl2norm2(xf, xs, axis=(0, 1)): r""" Compute the squared :math:`\ell_2` norm in the DFT domain, taking into account the unnormalised DFT scaling, i.e. given the DFT of a multi-dimensional array computed via :func:`rfftn`, return the squared :math:`\ell_2` norm of the original array. Paramet...
[ "def", "rfl2norm2", "(", "xf", ",", "xs", ",", "axis", "=", "(", "0", ",", "1", ")", ")", ":", "scl", "=", "1.0", "/", "np", ".", "prod", "(", "np", ".", "array", "(", "[", "xs", "[", "k", "]", "for", "k", "in", "axis", "]", ")", ")", "...
r""" Compute the squared :math:`\ell_2` norm in the DFT domain, taking into account the unnormalised DFT scaling, i.e. given the DFT of a multi-dimensional array computed via :func:`rfftn`, return the squared :math:`\ell_2` norm of the original array. Parameters ---------- xf : array_like ...
[ "r", "Compute", "the", "squared", ":", "math", ":", "\\", "ell_2", "norm", "in", "the", "DFT", "domain", "taking", "into", "account", "the", "unnormalised", "DFT", "scaling", "i", ".", "e", ".", "given", "the", "DFT", "of", "a", "multi", "-", "dimensio...
python
train
iotile/coretools
transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L163-L215
def _probe_services(self, handle): """Probe for all primary services and characteristics in those services Args: handle (int): the connection handle to probe """ code = 0x2800 def event_filter_func(event): if (event.command_class == 4 and event.command ...
[ "def", "_probe_services", "(", "self", ",", "handle", ")", ":", "code", "=", "0x2800", "def", "event_filter_func", "(", "event", ")", ":", "if", "(", "event", ".", "command_class", "==", "4", "and", "event", ".", "command", "==", "2", ")", ":", "event_...
Probe for all primary services and characteristics in those services Args: handle (int): the connection handle to probe
[ "Probe", "for", "all", "primary", "services", "and", "characteristics", "in", "those", "services" ]
python
train
datadesk/django-bakery
bakery/management/commands/publish.py
https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/publish.py#L313-L319
def get_md5(self, filename): """ Returns the md5 checksum of the provided file name. """ with open(filename, 'rb') as f: m = hashlib.md5(f.read()) return m.hexdigest()
[ "def", "get_md5", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "m", "=", "hashlib", ".", "md5", "(", "f", ".", "read", "(", ")", ")", "return", "m", ".", "hexdigest", "(", ")" ]
Returns the md5 checksum of the provided file name.
[ "Returns", "the", "md5", "checksum", "of", "the", "provided", "file", "name", "." ]
python
train
markovmodel/PyEMMA
pyemma/coordinates/pipelines.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/pipelines.py#L74-L90
def add_element(self, e): r""" Appends a pipeline stage. Appends the given element to the end of the current chain. """ if not isinstance(e, Iterable): raise TypeError("given element {} is not iterable in terms of " "PyEMMAs coordinate pipeline."....
[ "def", "add_element", "(", "self", ",", "e", ")", ":", "if", "not", "isinstance", "(", "e", ",", "Iterable", ")", ":", "raise", "TypeError", "(", "\"given element {} is not iterable in terms of \"", "\"PyEMMAs coordinate pipeline.\"", ".", "format", "(", "e", ")",...
r""" Appends a pipeline stage. Appends the given element to the end of the current chain.
[ "r", "Appends", "a", "pipeline", "stage", "." ]
python
train
vsoch/helpme
helpme/action/submit.py
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/action/submit.py#L24-L64
def upload_asciinema(filename): '''a wrapper around generation of an asciinema.api.Api to call the upload command given an already existing asciinema file. Parameters ========== filename: the asciinema file to upload, can be generated with function record_asciinema i...
[ "def", "upload_asciinema", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "import", "asciinema", ".", "config", "as", "aconfig", "from", "asciinema", ".", "api", "import", "Api", "# Load the API class", "cfg", ...
a wrapper around generation of an asciinema.api.Api to call the upload command given an already existing asciinema file. Parameters ========== filename: the asciinema file to upload, can be generated with function record_asciinema in record.py
[ "a", "wrapper", "around", "generation", "of", "an", "asciinema", ".", "api", ".", "Api", "to", "call", "the", "upload", "command", "given", "an", "already", "existing", "asciinema", "file", "." ]
python
train
barrust/pyspellchecker
spellchecker/spellchecker.py
https://github.com/barrust/pyspellchecker/blob/fa96024c0cdeba99e10e11060d5fd7aba796b271/spellchecker/spellchecker.py#L398-L404
def load_words(self, words): """ Load a list of words from which to generate a word frequency list Args: words (list): The list of words to be loaded """ self._dictionary.update([word.lower() for word in words]) self._update_dictionary()
[ "def", "load_words", "(", "self", ",", "words", ")", ":", "self", ".", "_dictionary", ".", "update", "(", "[", "word", ".", "lower", "(", ")", "for", "word", "in", "words", "]", ")", "self", ".", "_update_dictionary", "(", ")" ]
Load a list of words from which to generate a word frequency list Args: words (list): The list of words to be loaded
[ "Load", "a", "list", "of", "words", "from", "which", "to", "generate", "a", "word", "frequency", "list" ]
python
train
suds-community/suds
suds/client.py
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/client.py#L852-L868
def __headers(self): """ Get HTTP headers for a HTTP/HTTPS SOAP request. @return: A dictionary of header/values. @rtype: dict """ action = self.method.soap.action if isinstance(action, unicode): action = action.encode("utf-8") result = { ...
[ "def", "__headers", "(", "self", ")", ":", "action", "=", "self", ".", "method", ".", "soap", ".", "action", "if", "isinstance", "(", "action", ",", "unicode", ")", ":", "action", "=", "action", ".", "encode", "(", "\"utf-8\"", ")", "result", "=", "{...
Get HTTP headers for a HTTP/HTTPS SOAP request. @return: A dictionary of header/values. @rtype: dict
[ "Get", "HTTP", "headers", "for", "a", "HTTP", "/", "HTTPS", "SOAP", "request", "." ]
python
train
ntucllab/libact
libact/base/dataset.py
https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/base/dataset.py#L104-L119
def update(self, entry_id, new_label): """ Updates an entry with entry_id with the given label Parameters ---------- entry_id : int entry id of the sample to update. label : {int, None} Label of the sample to be update. """ self.d...
[ "def", "update", "(", "self", ",", "entry_id", ",", "new_label", ")", ":", "self", ".", "data", "[", "entry_id", "]", "=", "(", "self", ".", "data", "[", "entry_id", "]", "[", "0", "]", ",", "new_label", ")", "self", ".", "modified", "=", "True", ...
Updates an entry with entry_id with the given label Parameters ---------- entry_id : int entry id of the sample to update. label : {int, None} Label of the sample to be update.
[ "Updates", "an", "entry", "with", "entry_id", "with", "the", "given", "label" ]
python
train
jgorset/facebook
facebook/user.py
https://github.com/jgorset/facebook/blob/90f035ae1828e4eeb7af428964fedf0ee99ec2ad/facebook/user.py#L85-L106
def work(self): """ A list of :class:`Employment` instances describing the user's work history. Each structure has attributes ``employer``, ``position``, ``started_at`` and ``ended_at``. ``employer`` and ``position`` reference ``Page`` instances, while ``started_at`` and ``ended_at`` ...
[ "def", "work", "(", "self", ")", ":", "employments", "=", "[", "]", "for", "work", "in", "self", ".", "cache", "[", "'work'", "]", ":", "employment", "=", "Employment", "(", "employer", "=", "work", ".", "get", "(", "'employer'", ")", ",", "position"...
A list of :class:`Employment` instances describing the user's work history. Each structure has attributes ``employer``, ``position``, ``started_at`` and ``ended_at``. ``employer`` and ``position`` reference ``Page`` instances, while ``started_at`` and ``ended_at`` are datetime objects.
[ "A", "list", "of", ":", "class", ":", "Employment", "instances", "describing", "the", "user", "s", "work", "history", "." ]
python
train
realitix/vulkan
generator/generate.py
https://github.com/realitix/vulkan/blob/07285387092aaa61d2d71fa2913d60a73f022cbe/generator/generate.py#L325-L445
def model_functions(vk, model): """Fill the model with functions""" def get_vk_extension_functions(): names = set() for extension in get_extensions_filtered(vk): for req in extension['require']: if 'command' not in req: continue fo...
[ "def", "model_functions", "(", "vk", ",", "model", ")", ":", "def", "get_vk_extension_functions", "(", ")", ":", "names", "=", "set", "(", ")", "for", "extension", "in", "get_extensions_filtered", "(", "vk", ")", ":", "for", "req", "in", "extension", "[", ...
Fill the model with functions
[ "Fill", "the", "model", "with", "functions" ]
python
train
quantopian/zipline
zipline/finance/commission.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/commission.py#L364-L369
def calculate(self, order, transaction): """ Pay commission based on dollar value of shares. """ cost_per_share = transaction.price * self.cost_per_dollar return abs(transaction.amount) * cost_per_share
[ "def", "calculate", "(", "self", ",", "order", ",", "transaction", ")", ":", "cost_per_share", "=", "transaction", ".", "price", "*", "self", ".", "cost_per_dollar", "return", "abs", "(", "transaction", ".", "amount", ")", "*", "cost_per_share" ]
Pay commission based on dollar value of shares.
[ "Pay", "commission", "based", "on", "dollar", "value", "of", "shares", "." ]
python
train
zxylvlp/PingPHP
pingphp/grammar.py
https://github.com/zxylvlp/PingPHP/blob/2e9a5f1ef4b5b13310e3f8ff350fa91032357bc5/pingphp/grammar.py#L1095-L1103
def p_InterfaceDefList(p): ''' InterfaceDefList : InterfaceDef | InterfaceDefList InterfaceDef ''' if len(p) < 3: p[0] = InterfaceDefList(None, p[1]) else: p[0] = InterfaceDefList(p[1], p[2])
[ "def", "p_InterfaceDefList", "(", "p", ")", ":", "if", "len", "(", "p", ")", "<", "3", ":", "p", "[", "0", "]", "=", "InterfaceDefList", "(", "None", ",", "p", "[", "1", "]", ")", "else", ":", "p", "[", "0", "]", "=", "InterfaceDefList", "(", ...
InterfaceDefList : InterfaceDef | InterfaceDefList InterfaceDef
[ "InterfaceDefList", ":", "InterfaceDef", "|", "InterfaceDefList", "InterfaceDef" ]
python
train
astropy/astropy-healpix
astropy_healpix/high_level.py
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/high_level.py#L272-L298
def healpix_to_skycoord(self, healpix_index, dx=None, dy=None): """ Convert HEALPix indices (optionally with offsets) to celestial coordinates. Note that this method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, y...
[ "def", "healpix_to_skycoord", "(", "self", ",", "healpix_index", ",", "dx", "=", "None", ",", "dy", "=", "None", ")", ":", "if", "self", ".", "frame", "is", "None", ":", "raise", "NoFrameError", "(", "\"healpix_to_skycoord\"", ")", "lon", ",", "lat", "="...
Convert HEALPix indices (optionally with offsets) to celestial coordinates. Note that this method requires that a celestial frame was specified when initializing HEALPix. If you don't know or need the celestial frame, you can instead use :meth:`~astropy_healpix.HEALPix.healpix_to_lonlat`. ...
[ "Convert", "HEALPix", "indices", "(", "optionally", "with", "offsets", ")", "to", "celestial", "coordinates", "." ]
python
train
obriencj/python-javatools
javatools/__init__.py
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L2226-L2277
def _pretty_type(s, offset=0): # pylint: disable=R0911, R0912 # too many returns, too many branches. Not converting this to a # dict lookup. Waiving instead. """ returns the pretty version of a type code """ tc = s[offset] if tc == "V": return "void" elif tc == "Z": ...
[ "def", "_pretty_type", "(", "s", ",", "offset", "=", "0", ")", ":", "# pylint: disable=R0911, R0912", "# too many returns, too many branches. Not converting this to a", "# dict lookup. Waiving instead.", "tc", "=", "s", "[", "offset", "]", "if", "tc", "==", "\"V\"", ":"...
returns the pretty version of a type code
[ "returns", "the", "pretty", "version", "of", "a", "type", "code" ]
python
train
theonion/django-bulbs
bulbs/api/views.py
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/api/views.py#L204-L216
def status(self, request, **kwargs): """This endpoint returns a status text, currently one of: - "Draft" (If no publish date is set, and no item exists in the editor queue) - "Waiting for Editor" (If no publish date is set, and an item exists in the editor queue) - "Published" (The...
[ "def", "status", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "content", "=", "self", ".", "get_object", "(", ")", "return", "Response", "(", "{", "\"status\"", ":", "content", ".", "get_status", "(", ")", "}", ")" ]
This endpoint returns a status text, currently one of: - "Draft" (If no publish date is set, and no item exists in the editor queue) - "Waiting for Editor" (If no publish date is set, and an item exists in the editor queue) - "Published" (The published date is in the past) - "Sch...
[ "This", "endpoint", "returns", "a", "status", "text", "currently", "one", "of", ":", "-", "Draft", "(", "If", "no", "publish", "date", "is", "set", "and", "no", "item", "exists", "in", "the", "editor", "queue", ")", "-", "Waiting", "for", "Editor", "("...
python
train
timothydmorton/isochrones
isochrones/observation.py
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/observation.py#L827-L856
def save_hdf(self, filename, path='', overwrite=False, append=False): """ Writes all info necessary to recreate object to HDF file Saves table of photometry in DataFrame Saves model specification, spectroscopy, parallax to attrs """ if os.path.exists(filename): ...
[ "def", "save_hdf", "(", "self", ",", "filename", ",", "path", "=", "''", ",", "overwrite", "=", "False", ",", "append", "=", "False", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "store", "=", "pd", ".", "HDFStore", ...
Writes all info necessary to recreate object to HDF file Saves table of photometry in DataFrame Saves model specification, spectroscopy, parallax to attrs
[ "Writes", "all", "info", "necessary", "to", "recreate", "object", "to", "HDF", "file" ]
python
train
satellogic/telluric
telluric/georaster.py
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L838-L934
def save(self, filename, tags=None, **kwargs): """ Save GeoRaster to a file. :param filename: url :param tags: tags to add to default namespace optional parameters: * GDAL_TIFF_INTERNAL_MASK: specifies whether mask is within image file, or additional .msk * ove...
[ "def", "save", "(", "self", ",", "filename", ",", "tags", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "filename", ".", "startswith", "(", "\"/vsi\"", ")", ":", "folder", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "pa...
Save GeoRaster to a file. :param filename: url :param tags: tags to add to default namespace optional parameters: * GDAL_TIFF_INTERNAL_MASK: specifies whether mask is within image file, or additional .msk * overviews: if True, will save with previews. default: True * f...
[ "Save", "GeoRaster", "to", "a", "file", "." ]
python
train
saltstack/salt
salt/utils/cache.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cache.py#L244-L248
def put_cache(self, minions): ''' published the given minions to the ConCache ''' self.cupd_out.send(self.serial.dumps(minions))
[ "def", "put_cache", "(", "self", ",", "minions", ")", ":", "self", ".", "cupd_out", ".", "send", "(", "self", ".", "serial", ".", "dumps", "(", "minions", ")", ")" ]
published the given minions to the ConCache
[ "published", "the", "given", "minions", "to", "the", "ConCache" ]
python
train
openvax/pepdata
pepdata/iedb/alleles.py
https://github.com/openvax/pepdata/blob/2f1bad79f8084545227f4a7f895bbf08a6fb6fdc/pepdata/iedb/alleles.py#L25-L31
def local_path(force_download=False): """Downloads allele database from IEDB, returns local path to XML file.""" return cache.fetch( filename=ALLELE_XML_FILENAME, url=ALLELE_XML_URL, decompress=ALLELE_XML_DECOMPRESS, force=force_download)
[ "def", "local_path", "(", "force_download", "=", "False", ")", ":", "return", "cache", ".", "fetch", "(", "filename", "=", "ALLELE_XML_FILENAME", ",", "url", "=", "ALLELE_XML_URL", ",", "decompress", "=", "ALLELE_XML_DECOMPRESS", ",", "force", "=", "force_downlo...
Downloads allele database from IEDB, returns local path to XML file.
[ "Downloads", "allele", "database", "from", "IEDB", "returns", "local", "path", "to", "XML", "file", "." ]
python
train
petl-developers/petl
petl/util/vis.py
https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/util/vis.py#L155-L162
def lookstr(table, limit=0, **kwargs): """Like :func:`petl.util.vis.look` but use str() rather than repr() for data values. """ kwargs['vrepr'] = str return look(table, limit=limit, **kwargs)
[ "def", "lookstr", "(", "table", ",", "limit", "=", "0", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'vrepr'", "]", "=", "str", "return", "look", "(", "table", ",", "limit", "=", "limit", ",", "*", "*", "kwargs", ")" ]
Like :func:`petl.util.vis.look` but use str() rather than repr() for data values.
[ "Like", ":", "func", ":", "petl", ".", "util", ".", "vis", ".", "look", "but", "use", "str", "()", "rather", "than", "repr", "()", "for", "data", "values", "." ]
python
train
yandex/yandex-tank
yandextank/common/interfaces.py
https://github.com/yandex/yandex-tank/blob/d71d63b6ab5de8b8a5ea2b728b6ab9ac0b1ba71b/yandextank/common/interfaces.py#L98-L102
def publish(self, key, value): """publish value to status""" self.log.debug( "Publishing status: %s/%s: %s", self.__class__.__name__, key, value) self.core.publish(self.__class__.__name__, key, value)
[ "def", "publish", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Publishing status: %s/%s: %s\"", ",", "self", ".", "__class__", ".", "__name__", ",", "key", ",", "value", ")", "self", ".", "core", ".", "publ...
publish value to status
[ "publish", "value", "to", "status" ]
python
test
rosenbrockc/fortpy
fortpy/msg.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/msg.py#L27-L40
def printer(text, color=None, **kwargs): """Prints using color or standard print() depending on the value of 'nocolor'. """ if nocolor: # import sys # sys.stdout.write(text + "" if ("end" in kwargs and kwargs["end"] == "") else '\n') # sys.stdout.flush() print(text, **kwa...
[ "def", "printer", "(", "text", ",", "color", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "nocolor", ":", "# import sys", "# sys.stdout.write(text + \"\" if (\"end\" in kwargs and kwargs[\"end\"] == \"\") else '\\n')", "# sys.stdout.flush()", "print", "(", "text"...
Prints using color or standard print() depending on the value of 'nocolor'.
[ "Prints", "using", "color", "or", "standard", "print", "()", "depending", "on", "the", "value", "of", "nocolor", "." ]
python
train
xapple/plumbing
plumbing/slurm/job.py
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/job.py#L121-L136
def set_paths(self, base_dir, script_path): """Set the directory, the script path and the outfile path""" # Make absolute paths # if 'change_dir' in self.kwargs: self.kwargs['change_dir'] = DirectoryPath(os.path.abspath(self.kwargs['change_dir'])) if 'out_file' in self.kwargs...
[ "def", "set_paths", "(", "self", ",", "base_dir", ",", "script_path", ")", ":", "# Make absolute paths #", "if", "'change_dir'", "in", "self", ".", "kwargs", ":", "self", ".", "kwargs", "[", "'change_dir'", "]", "=", "DirectoryPath", "(", "os", ".", "path", ...
Set the directory, the script path and the outfile path
[ "Set", "the", "directory", "the", "script", "path", "and", "the", "outfile", "path" ]
python
train
MacHu-GWU/uszipcode-project
uszipcode/search.py
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/search.py#L616-L631
def by_state(self, state, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.zipcode.name, ascending=True, returns=DEFAULT_LIMIT): """ Search zipcode information by fuzzy State name. My engine use fuzzy m...
[ "def", "by_state", "(", "self", ",", "state", ",", "zipcode_type", "=", "ZipcodeType", ".", "Standard", ",", "sort_by", "=", "SimpleZipcode", ".", "zipcode", ".", "name", ",", "ascending", "=", "True", ",", "returns", "=", "DEFAULT_LIMIT", ")", ":", "retur...
Search zipcode information by fuzzy State name. My engine use fuzzy match and guess what is the state you want.
[ "Search", "zipcode", "information", "by", "fuzzy", "State", "name", "." ]
python
train
fhamborg/news-please
newsplease/helper_classes/url_extractor.py
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/helper_classes/url_extractor.py#L68-L107
def get_sitemap_url(url, allow_subdomains): """ Determines the domain's robot.txt :param str url: the url to work on :param bool allow_subdomains: Determines if the robot.txt may be the subdomain's :return: the robot.txt's address :r...
[ "def", "get_sitemap_url", "(", "url", ",", "allow_subdomains", ")", ":", "if", "allow_subdomains", ":", "redirect", "=", "UrlExtractor", ".", "follow_redirects", "(", "\"http://\"", "+", "UrlExtractor", ".", "get_allowed_domain", "(", "url", ")", ")", "else", ":...
Determines the domain's robot.txt :param str url: the url to work on :param bool allow_subdomains: Determines if the robot.txt may be the subdomain's :return: the robot.txt's address :raises Exception: if there's no robot.txt on the site's domain
[ "Determines", "the", "domain", "s", "robot", ".", "txt" ]
python
train
openstack/networking-cisco
networking_cisco/plugins/cisco/device_manager/config.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/config.py#L148-L199
def verify_resource_dict(res_dict, is_create, attr_info): """Verifies required attributes are in resource dictionary, res_dict. Also checking that an attribute is only specified if it is allowed for the given operation (create/update). Attribute with default values are considered to be optional. ...
[ "def", "verify_resource_dict", "(", "res_dict", ",", "is_create", ",", "attr_info", ")", ":", "if", "(", "(", "bc", ".", "NEUTRON_VERSION", ">=", "bc", ".", "NEUTRON_NEWTON_VERSION", ")", "and", "'tenant_id'", "in", "res_dict", ")", ":", "res_dict", "[", "'p...
Verifies required attributes are in resource dictionary, res_dict. Also checking that an attribute is only specified if it is allowed for the given operation (create/update). Attribute with default values are considered to be optional. This function contains code taken from function 'prepare_request_...
[ "Verifies", "required", "attributes", "are", "in", "resource", "dictionary", "res_dict", "." ]
python
train
mlperf/training
object_detection/pytorch/maskrcnn_benchmark/structures/boxlist_ops.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/structures/boxlist_ops.py#L102-L128
def cat_boxlist(bboxes): """ Concatenates a list of BoxList (having the same image size) into a single BoxList Arguments: bboxes (list[BoxList]) """ assert isinstance(bboxes, (list, tuple)) assert all(isinstance(bbox, BoxList) for bbox in bboxes) size = bboxes[0].size asser...
[ "def", "cat_boxlist", "(", "bboxes", ")", ":", "assert", "isinstance", "(", "bboxes", ",", "(", "list", ",", "tuple", ")", ")", "assert", "all", "(", "isinstance", "(", "bbox", ",", "BoxList", ")", "for", "bbox", "in", "bboxes", ")", "size", "=", "bb...
Concatenates a list of BoxList (having the same image size) into a single BoxList Arguments: bboxes (list[BoxList])
[ "Concatenates", "a", "list", "of", "BoxList", "(", "having", "the", "same", "image", "size", ")", "into", "a", "single", "BoxList" ]
python
train
globality-corp/microcosm-postgres
microcosm_postgres/store.py
https://github.com/globality-corp/microcosm-postgres/blob/43dd793b1fc9b84e4056700f350e79e0df5ff501/microcosm_postgres/store.py#L211-L217
def _filter(self, query, **kwargs): """ Filter a query with user-supplied arguments. """ query = self._auto_filter(query, **kwargs) return query
[ "def", "_filter", "(", "self", ",", "query", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_auto_filter", "(", "query", ",", "*", "*", "kwargs", ")", "return", "query" ]
Filter a query with user-supplied arguments.
[ "Filter", "a", "query", "with", "user", "-", "supplied", "arguments", "." ]
python
train
Cadasta/django-tutelary
tutelary/models.py
https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/models.py#L363-L377
def assign_user_policies(user, *policies_roles): """Assign a sequence of policies to a user (or the anonymous user is ``user`` is ``None``). (Also installed as ``assign_policies`` method on ``User`` model. """ clear_user_policies(user) pset = PermissionSet.objects.by_policies_and_roles(policie...
[ "def", "assign_user_policies", "(", "user", ",", "*", "policies_roles", ")", ":", "clear_user_policies", "(", "user", ")", "pset", "=", "PermissionSet", ".", "objects", ".", "by_policies_and_roles", "(", "policies_roles", ")", "pset", ".", "refresh", "(", ")", ...
Assign a sequence of policies to a user (or the anonymous user is ``user`` is ``None``). (Also installed as ``assign_policies`` method on ``User`` model.
[ "Assign", "a", "sequence", "of", "policies", "to", "a", "user", "(", "or", "the", "anonymous", "user", "is", "user", "is", "None", ")", ".", "(", "Also", "installed", "as", "assign_policies", "method", "on", "User", "model", "." ]
python
train
materialsproject/pymatgen
pymatgen/io/abinit/pseudos.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/pseudos.py#L1786-L1797
def print_table(self, stream=sys.stdout, filter_function=None): """ A pretty ASCII printer for the periodic table, based on some filter_function. Args: stream: file-like object filter_function: A filtering function that take a Pseudo as input and returns ...
[ "def", "print_table", "(", "self", ",", "stream", "=", "sys", ".", "stdout", ",", "filter_function", "=", "None", ")", ":", "print", "(", "self", ".", "to_table", "(", "filter_function", "=", "filter_function", ")", ",", "file", "=", "stream", ")" ]
A pretty ASCII printer for the periodic table, based on some filter_function. Args: stream: file-like object filter_function: A filtering function that take a Pseudo as input and returns a boolean. For example, setting filter_function = lambda p: p.Z_val ...
[ "A", "pretty", "ASCII", "printer", "for", "the", "periodic", "table", "based", "on", "some", "filter_function", "." ]
python
train
dmlc/xgboost
python-package/xgboost/core.py
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1072-L1087
def set_param(self, params, value=None): """Set parameters into the Booster. Parameters ---------- params: dict/list/str list of key,value pairs, dict of key to value or simply str key value: optional value of the specified parameter, when params is str key...
[ "def", "set_param", "(", "self", ",", "params", ",", "value", "=", "None", ")", ":", "if", "isinstance", "(", "params", ",", "Mapping", ")", ":", "params", "=", "params", ".", "items", "(", ")", "elif", "isinstance", "(", "params", ",", "STRING_TYPES",...
Set parameters into the Booster. Parameters ---------- params: dict/list/str list of key,value pairs, dict of key to value or simply str key value: optional value of the specified parameter, when params is str key
[ "Set", "parameters", "into", "the", "Booster", "." ]
python
train
akfullfo/taskforce
taskforce/utils.py
https://github.com/akfullfo/taskforce/blob/bc6dd744bd33546447d085dbd18a350532220193/taskforce/utils.py#L282-L307
def module_description(module__name__, module__doc__, module__file__): """ Return formatted text that lists the module-level and class-level embedded documentation. The function should be called exactly as: taskforce.utils.module_description(__name__, __doc__, __file__) The most common us...
[ "def", "module_description", "(", "module__name__", ",", "module__doc__", ",", "module__file__", ")", ":", "mod_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "module__file__", ")", ")", "[", "0", "]", "mod_de...
Return formatted text that lists the module-level and class-level embedded documentation. The function should be called exactly as: taskforce.utils.module_description(__name__, __doc__, __file__) The most common use for this function is to produce the help message for test code in a library m...
[ "Return", "formatted", "text", "that", "lists", "the", "module", "-", "level", "and", "class", "-", "level", "embedded", "documentation", ".", "The", "function", "should", "be", "called", "exactly", "as", ":" ]
python
train
EliotBerriot/django-dynamic-preferences
dynamic_preferences/managers.py
https://github.com/EliotBerriot/django-dynamic-preferences/blob/12eab4f17b960290525b215d954d1b5fb91199df/dynamic_preferences/managers.py#L47-L49
def by_name(self): """Return a dictionary with preferences identifiers and values, but without the section name in the identifier""" return {key.split(preferences_settings.SECTION_KEY_SEPARATOR)[-1]: value for key, value in self.all().items()}
[ "def", "by_name", "(", "self", ")", ":", "return", "{", "key", ".", "split", "(", "preferences_settings", ".", "SECTION_KEY_SEPARATOR", ")", "[", "-", "1", "]", ":", "value", "for", "key", ",", "value", "in", "self", ".", "all", "(", ")", ".", "items...
Return a dictionary with preferences identifiers and values, but without the section name in the identifier
[ "Return", "a", "dictionary", "with", "preferences", "identifiers", "and", "values", "but", "without", "the", "section", "name", "in", "the", "identifier" ]
python
train