repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
Prev/shaman
shamanld/shaman.py
https://github.com/Prev/shaman/blob/82891c17c6302f7f9881a215789856d460a85f9c/shamanld/shaman.py#L115-L144
def _remove_strings(code) : """ Remove strings in code """ removed_string = "" is_string_now = None for i in range(0, len(code)-1) : append_this_turn = False if code[i] == "'" and (i == 0 or code[i-1] != '\\') : if is_string_now == "'" : is_string_now = None elif is_string_now == None ...
[ "def", "_remove_strings", "(", "code", ")", ":", "removed_string", "=", "\"\"", "is_string_now", "=", "None", "for", "i", "in", "range", "(", "0", ",", "len", "(", "code", ")", "-", "1", ")", ":", "append_this_turn", "=", "False", "if", "code", "[", ...
Remove strings in code
[ "Remove", "strings", "in", "code" ]
python
train
22.166667
thespacedoctor/sherlock
sherlock/transient_catalogue_crossmatch.py
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/transient_catalogue_crossmatch.py#L264-L512
def angular_crossmatch_against_catalogue( self, objectList, searchPara={}, search_name="", brightnessFilter=False, physicalSearch=False, classificationType=False ): """*perform an angular separation crossmatch against a given catalogue in the database ...
[ "def", "angular_crossmatch_against_catalogue", "(", "self", ",", "objectList", ",", "searchPara", "=", "{", "}", ",", "search_name", "=", "\"\"", ",", "brightnessFilter", "=", "False", ",", "physicalSearch", "=", "False", ",", "classificationType", "=", "False", ...
*perform an angular separation crossmatch against a given catalogue in the database and annotate the crossmatch with some value added parameters (distances, physical separations, sub-type of transient etc)* **Key Arguments:** - ``objectList`` -- the list of transient locations to match against the ...
[ "*", "perform", "an", "angular", "separation", "crossmatch", "against", "a", "given", "catalogue", "in", "the", "database", "and", "annotate", "the", "crossmatch", "with", "some", "value", "added", "parameters", "(", "distances", "physical", "separations", "sub", ...
python
train
39.232932
cytomine/Cytomine-python-client
cytomine/cytomine_job.py
https://github.com/cytomine/Cytomine-python-client/blob/bac19722b900dd32c6cfd6bdb9354fc784d33bc4/cytomine/cytomine_job.py#L80-L108
def _software_params_to_argparse(parameters): """ Converts a SoftwareParameterCollection into an ArgumentParser object. Parameters ---------- parameters: SoftwareParameterCollection The software parameters Returns ------- argparse: ArgumentParser An initialized argument ...
[ "def", "_software_params_to_argparse", "(", "parameters", ")", ":", "# Check software parameters", "argparse", "=", "ArgumentParser", "(", ")", "boolean_defaults", "=", "{", "}", "for", "parameter", "in", "parameters", ":", "arg_desc", "=", "{", "\"dest\"", ":", "...
Converts a SoftwareParameterCollection into an ArgumentParser object. Parameters ---------- parameters: SoftwareParameterCollection The software parameters Returns ------- argparse: ArgumentParser An initialized argument parser
[ "Converts", "a", "SoftwareParameterCollection", "into", "an", "ArgumentParser", "object", "." ]
python
train
40.206897
DLR-RM/RAFCON
source/rafcon/gui/controllers/graphical_editor_gaphas.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L834-L852
def add_transition_view_for_model(self, transition_m, parent_state_m): """Creates a `TransitionView` and adds it to the canvas The method creates a`TransitionView` from the given `TransitionModel `transition_m` and adds it to the canvas. :param TransitionModel transition_m: The transition for ...
[ "def", "add_transition_view_for_model", "(", "self", ",", "transition_m", ",", "parent_state_m", ")", ":", "parent_state_v", "=", "self", ".", "canvas", ".", "get_view_for_model", "(", "parent_state_m", ")", "hierarchy_level", "=", "parent_state_v", ".", "hierarchy_le...
Creates a `TransitionView` and adds it to the canvas The method creates a`TransitionView` from the given `TransitionModel `transition_m` and adds it to the canvas. :param TransitionModel transition_m: The transition for which a view is to be created :param ContainerStateModel parent_state_m: ...
[ "Creates", "a", "TransitionView", "and", "adds", "it", "to", "the", "canvas" ]
python
train
47.052632
apache/spark
python/pyspark/sql/types.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/types.py#L1463-L1492
def asDict(self, recursive=False): """ Return as an dict :param recursive: turns the nested Row as dict (default: False). >>> Row(name="Alice", age=11).asDict() == {'name': 'Alice', 'age': 11} True >>> row = Row(key=1, value=Row(name='a', age=2)) >>> row.asDict(...
[ "def", "asDict", "(", "self", ",", "recursive", "=", "False", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"__fields__\"", ")", ":", "raise", "TypeError", "(", "\"Cannot convert a Row class into dict\"", ")", "if", "recursive", ":", "def", "conv", "...
Return as an dict :param recursive: turns the nested Row as dict (default: False). >>> Row(name="Alice", age=11).asDict() == {'name': 'Alice', 'age': 11} True >>> row = Row(key=1, value=Row(name='a', age=2)) >>> row.asDict() == {'key': 1, 'value': Row(age=2, name='a')} ...
[ "Return", "as", "an", "dict" ]
python
train
36.566667
openstack/networking-cisco
networking_cisco/apps/saf/common/utils.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/common/utils.py#L144-L158
def is_valid_mac(addr): """Check the syntax of a given mac address. The acceptable format is xx:xx:xx:xx:xx:xx """ addrs = addr.split(':') if len(addrs) != 6: return False for m in addrs: try: if int(m, 16) > 255: return False except ValueErro...
[ "def", "is_valid_mac", "(", "addr", ")", ":", "addrs", "=", "addr", ".", "split", "(", "':'", ")", "if", "len", "(", "addrs", ")", "!=", "6", ":", "return", "False", "for", "m", "in", "addrs", ":", "try", ":", "if", "int", "(", "m", ",", "16", ...
Check the syntax of a given mac address. The acceptable format is xx:xx:xx:xx:xx:xx
[ "Check", "the", "syntax", "of", "a", "given", "mac", "address", "." ]
python
train
23.266667
allenai/allennlp
allennlp/training/metrics/metric.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/metric.py#L29-L33
def get_metric(self, reset: bool) -> Union[float, Tuple[float, ...], Dict[str, float], Dict[str, List[float]]]: """ Compute and return the metric. Optionally also call :func:`self.reset`. """ raise NotImplementedError
[ "def", "get_metric", "(", "self", ",", "reset", ":", "bool", ")", "->", "Union", "[", "float", ",", "Tuple", "[", "float", ",", "...", "]", ",", "Dict", "[", "str", ",", "float", "]", ",", "Dict", "[", "str", ",", "List", "[", "float", "]", "]"...
Compute and return the metric. Optionally also call :func:`self.reset`.
[ "Compute", "and", "return", "the", "metric", ".", "Optionally", "also", "call", ":", "func", ":", "self", ".", "reset", "." ]
python
train
49
pandas-dev/pandas
pandas/core/panel.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/panel.py#L515-L541
def set_value(self, *args, **kwargs): """ Quickly set single value at (item, major, minor) location. .. deprecated:: 0.21.0 Please use .at[] or .iat[] accessors. Parameters ---------- item : item label (panel item) major : major axis label (panel item r...
[ "def", "set_value", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"set_value is deprecated and will be removed \"", "\"in a future release. Please use \"", "\".at[] or .iat[] accessors instead\"", ",", "FutureWarning", "...
Quickly set single value at (item, major, minor) location. .. deprecated:: 0.21.0 Please use .at[] or .iat[] accessors. Parameters ---------- item : item label (panel item) major : major axis label (panel item row) minor : minor axis label (panel item column) ...
[ "Quickly", "set", "single", "value", "at", "(", "item", "major", "minor", ")", "location", "." ]
python
train
33.740741
YavorPaunov/time2words
time2words/__init__.py
https://github.com/YavorPaunov/time2words/blob/f0bb059f8f5a81e1215071c5ab6a5f7ad022b719/time2words/__init__.py#L10-L40
def relative_time_to_text(l10n=locales.get(_default), **kwargs): """ Return an aproximate textual representation of the provioded duration of time. Examples: relative_time_to_text(hours=6, minutes=34) -> "six and a half hours" relative_time_to_text(years=5, months=8, days=5) -> "less than six y...
[ "def", "relative_time_to_text", "(", "l10n", "=", "locales", ".", "get", "(", "_default", ")", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "_normalize", "(", "*", "*", "kwargs", ")", "cor", "=", "_Chain", "(", ")", "cor", ".", "add", "(", "_L...
Return an aproximate textual representation of the provioded duration of time. Examples: relative_time_to_text(hours=6, minutes=34) -> "six and a half hours" relative_time_to_text(years=5, months=8, days=5) -> "less than six years" Keyword arguments: l10n -- The locale of the language for the ...
[ "Return", "an", "aproximate", "textual", "representation", "of", "the", "provioded", "duration", "of", "time", "." ]
python
train
28.645161
HPENetworking/PYHPEIMC
archived/pyhpimc.py
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L598-L617
def set_inteface_down(devid, ifindex): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie d interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interfa...
[ "def", "set_inteface_down", "(", "devid", ",", "ifindex", ")", ":", "if", "auth", "is", "None", "or", "url", "is", "None", ":", "# checks to see if the imc credentials are already available", "set_imc_creds", "(", ")", "set_int_down_url", "=", "\"/imcrs/plat/res/device/...
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie d interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values...
[ "function", "takest", "devid", "and", "ifindex", "of", "specific", "device", "and", "interface", "and", "issues", "a", "RESTFUL", "call", "to", "shut", "the", "specifie", "d", "interface", "on", "the", "target", "device", ".", ":", "param", "devid", ":", "...
python
train
45.5
bokeh/bokeh
bokeh/server/views/ws.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L147-L191
def _async_open(self, session_id, proto_version): ''' Perform the specific steps needed to open a connection to a Bokeh session Specifically, this method coordinates: * Getting a session for a session ID (creating a new one if needed) * Creating a protocol receiver and hander *...
[ "def", "_async_open", "(", "self", ",", "session_id", ",", "proto_version", ")", ":", "try", ":", "yield", "self", ".", "application_context", ".", "create_session_if_needed", "(", "session_id", ",", "self", ".", "request", ")", "session", "=", "self", ".", ...
Perform the specific steps needed to open a connection to a Bokeh session Specifically, this method coordinates: * Getting a session for a session ID (creating a new one if needed) * Creating a protocol receiver and hander * Opening a new ServerConnection and sending it an ACK ...
[ "Perform", "the", "specific", "steps", "needed", "to", "open", "a", "connection", "to", "a", "Bokeh", "session" ]
python
train
34.577778
frmdstryr/enamlx
enamlx/qt/qt_graphics_view.py
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_graphics_view.py#L258-L266
def hook_focus_events(self): """ Install the hooks for focus events. This method may be overridden by subclasses as needed. """ widget = self.widget widget.focusInEvent = self.focusInEvent widget.focusOutEvent = self.focusOutEvent
[ "def", "hook_focus_events", "(", "self", ")", ":", "widget", "=", "self", ".", "widget", "widget", ".", "focusInEvent", "=", "self", ".", "focusInEvent", "widget", ".", "focusOutEvent", "=", "self", ".", "focusOutEvent" ]
Install the hooks for focus events. This method may be overridden by subclasses as needed.
[ "Install", "the", "hooks", "for", "focus", "events", "." ]
python
train
30.222222
thiagopbueno/pyrddl
pyrddl/expr.py
https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/expr.py#L141-L156
def __expr_str(cls, expr, level): '''Returns string representing the expression.''' ident = ' ' * level * 4 if isinstance(expr, tuple): return '{}{}'.format(ident, str(expr)) if expr.etype[0] in ['pvar', 'constant']: return '{}Expression(etype={}, args={})'.form...
[ "def", "__expr_str", "(", "cls", ",", "expr", ",", "level", ")", ":", "ident", "=", "' '", "*", "level", "*", "4", "if", "isinstance", "(", "expr", ",", "tuple", ")", ":", "return", "'{}{}'", ".", "format", "(", "ident", ",", "str", "(", "expr", ...
Returns string representing the expression.
[ "Returns", "string", "representing", "the", "expression", "." ]
python
train
38.875
inasafe/inasafe
safe/gui/tools/multi_exposure_dialog.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_exposure_dialog.py#L277-L295
def _list_selection_changed(self): """Selection has changed in the list.""" items = self.list_layers_in_map_report.selectedItems() self.remove_layer.setEnabled(len(items) >= 1) if len(items) == 1 and self.list_layers_in_map_report.count() >= 2: index = self.list_layers_in_map...
[ "def", "_list_selection_changed", "(", "self", ")", ":", "items", "=", "self", ".", "list_layers_in_map_report", ".", "selectedItems", "(", ")", "self", ".", "remove_layer", ".", "setEnabled", "(", "len", "(", "items", ")", ">=", "1", ")", "if", "len", "("...
Selection has changed in the list.
[ "Selection", "has", "changed", "in", "the", "list", "." ]
python
train
45.578947
quantopian/pgcontents
pgcontents/hybridmanager.py
https://github.com/quantopian/pgcontents/blob/ed36268b7917332d16868208e1e565742a8753e1/pgcontents/hybridmanager.py#L61-L82
def _apply_prefix(prefix, model): """ Prefix all path entries in model with the given prefix. """ if not isinstance(model, dict): raise TypeError("Expected dict for model, got %s" % type(model)) # We get unwanted leading/trailing slashes if prefix or model['path'] are # '', both of whic...
[ "def", "_apply_prefix", "(", "prefix", ",", "model", ")", ":", "if", "not", "isinstance", "(", "model", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"Expected dict for model, got %s\"", "%", "type", "(", "model", ")", ")", "# We get unwanted leading/trail...
Prefix all path entries in model with the given prefix.
[ "Prefix", "all", "path", "entries", "in", "model", "with", "the", "given", "prefix", "." ]
python
test
32.727273
SBRG/ssbio
ssbio/core/protein.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/core/protein.py#L183-L189
def structure_dir(self): """str: Directory where structure related files are stored""" if self.root_dir: return op.join(self.protein_dir, 'structures') else: log.debug('Root directory not set') return None
[ "def", "structure_dir", "(", "self", ")", ":", "if", "self", ".", "root_dir", ":", "return", "op", ".", "join", "(", "self", ".", "protein_dir", ",", "'structures'", ")", "else", ":", "log", ".", "debug", "(", "'Root directory not set'", ")", "return", "...
str: Directory where structure related files are stored
[ "str", ":", "Directory", "where", "structure", "related", "files", "are", "stored" ]
python
train
37
croach/django-simple-rest
simple_rest/auth/signature.py
https://github.com/croach/django-simple-rest/blob/5f5904969d170ef3803a9fb735f814ef76f79427/simple_rest/auth/signature.py#L6-L20
def calculate_signature(key, data, timestamp=None): """ Calculates the signature for the given request data. """ # Create a timestamp if one was not given if timestamp is None: timestamp = int(time.time()) # Construct the message from the timestamp and the data in the request messag...
[ "def", "calculate_signature", "(", "key", ",", "data", ",", "timestamp", "=", "None", ")", ":", "# Create a timestamp if one was not given", "if", "timestamp", "is", "None", ":", "timestamp", "=", "int", "(", "time", ".", "time", "(", ")", ")", "# Construct th...
Calculates the signature for the given request data.
[ "Calculates", "the", "signature", "for", "the", "given", "request", "data", "." ]
python
train
36.266667
sosy-lab/benchexec
benchexec/baseexecutor.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/baseexecutor.py#L68-L78
def _kill_process(self, pid, sig=signal.SIGKILL): """Try to send signal to given process.""" try: os.kill(pid, sig) except OSError as e: if e.errno == errno.ESRCH: # process itself returned and exited before killing logging.debug("Failure %s while killing ...
[ "def", "_kill_process", "(", "self", ",", "pid", ",", "sig", "=", "signal", ".", "SIGKILL", ")", ":", "try", ":", "os", ".", "kill", "(", "pid", ",", "sig", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", ...
Try to send signal to given process.
[ "Try", "to", "send", "signal", "to", "given", "process", "." ]
python
train
52.090909
mvantellingen/wsgi-basic-auth
src/wsgi_basic_auth.py
https://github.com/mvantellingen/wsgi-basic-auth/blob/4e829bff21526f587f8d1a8592b63e1abd862a74/src/wsgi_basic_auth.py#L76-L89
def _is_request_in_include_path(self, request): """Check if the request path is in the `_include_paths` list. If no specific include paths are given then we assume that authentication is required for all paths. """ if self._include_paths: for path in self._include_p...
[ "def", "_is_request_in_include_path", "(", "self", ",", "request", ")", ":", "if", "self", ".", "_include_paths", ":", "for", "path", "in", "self", ".", "_include_paths", ":", "if", "request", ".", "path", ".", "startswith", "(", "path", ")", ":", "return"...
Check if the request path is in the `_include_paths` list. If no specific include paths are given then we assume that authentication is required for all paths.
[ "Check", "if", "the", "request", "path", "is", "in", "the", "_include_paths", "list", "." ]
python
train
32.642857
doanguyen/lasotuvi
lasotuvi/Lich_HND.py
https://github.com/doanguyen/lasotuvi/blob/98383a3056f0a0633d6937d364c37eb788661c0d/lasotuvi/Lich_HND.py#L226-L250
def L2S(lunarD, lunarM, lunarY, lunarLeap, tZ=7): '''def L2S(lunarD, lunarM, lunarY, lunarLeap, tZ = 7): Convert a lunar date to the corresponding solar date.''' if (lunarM < 11): a11 = getLunarMonth11(lunarY - 1, tZ) b11 = getLunarMonth11(lunarY, tZ) else: a11 = getLunarMonth11(...
[ "def", "L2S", "(", "lunarD", ",", "lunarM", ",", "lunarY", ",", "lunarLeap", ",", "tZ", "=", "7", ")", ":", "if", "(", "lunarM", "<", "11", ")", ":", "a11", "=", "getLunarMonth11", "(", "lunarY", "-", "1", ",", "tZ", ")", "b11", "=", "getLunarMon...
def L2S(lunarD, lunarM, lunarY, lunarLeap, tZ = 7): Convert a lunar date to the corresponding solar date.
[ "def", "L2S", "(", "lunarD", "lunarM", "lunarY", "lunarLeap", "tZ", "=", "7", ")", ":", "Convert", "a", "lunar", "date", "to", "the", "corresponding", "solar", "date", "." ]
python
train
34.72
akfullfo/taskforce
taskforce/utils.py
https://github.com/akfullfo/taskforce/blob/bc6dd744bd33546447d085dbd18a350532220193/taskforce/utils.py#L269-L280
def appname(path=None): """ Return a useful application name based on the program argument. A special case maps 'mod_wsgi' to a more appropriate name so web applications show up as our own. """ if path is None: path = sys.argv[0] name = os.path.basename(os.path.splitext(path)[0]) if name == 'mod...
[ "def", "appname", "(", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "sys", ".", "argv", "[", "0", "]", "name", "=", "os", ".", "path", ".", "basename", "(", "os", ".", "path", ".", "splitext", "(", "path", ")", ...
Return a useful application name based on the program argument. A special case maps 'mod_wsgi' to a more appropriate name so web applications show up as our own.
[ "Return", "a", "useful", "application", "name", "based", "on", "the", "program", "argument", ".", "A", "special", "case", "maps", "mod_wsgi", "to", "a", "more", "appropriate", "name", "so", "web", "applications", "show", "up", "as", "our", "own", "." ]
python
train
37.25
project-rig/rig
rig/place_and_route/place/rcm.py
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/place/rcm.py#L45-L60
def _get_connected_subgraphs(vertices, vertices_neighbours): """Break a graph containing unconnected subgraphs into a list of connected subgraphs. Returns ------- [set([vertex, ...]), ...] """ remaining_vertices = set(vertices) subgraphs = [] while remaining_vertices: subgra...
[ "def", "_get_connected_subgraphs", "(", "vertices", ",", "vertices_neighbours", ")", ":", "remaining_vertices", "=", "set", "(", "vertices", ")", "subgraphs", "=", "[", "]", "while", "remaining_vertices", ":", "subgraph", "=", "set", "(", "_dfs", "(", "remaining...
Break a graph containing unconnected subgraphs into a list of connected subgraphs. Returns ------- [set([vertex, ...]), ...]
[ "Break", "a", "graph", "containing", "unconnected", "subgraphs", "into", "a", "list", "of", "connected", "subgraphs", "." ]
python
train
29.875
Fantomas42/django-blog-zinnia
zinnia/views/categories.py
https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/views/categories.py#L42-L48
def get_queryset(self): """ Retrieve the category by his path and build a queryset of her published entries. """ self.category = get_category_or_404(self.kwargs['path']) return self.category.entries_published()
[ "def", "get_queryset", "(", "self", ")", ":", "self", ".", "category", "=", "get_category_or_404", "(", "self", ".", "kwargs", "[", "'path'", "]", ")", "return", "self", ".", "category", ".", "entries_published", "(", ")" ]
Retrieve the category by his path and build a queryset of her published entries.
[ "Retrieve", "the", "category", "by", "his", "path", "and", "build", "a", "queryset", "of", "her", "published", "entries", "." ]
python
train
36
fossasia/knittingpattern
knittingpattern/Parser.py
https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/Parser.py#L231-L241
def _get_type(self, values): """:return: the type of a knitting pattern set.""" if TYPE not in values: self._error("No pattern type given but should be " "\"{}\"".format(KNITTING_PATTERN_TYPE)) type_ = values[TYPE] if type_ != KNITTING_PATTERN_TYPE: ...
[ "def", "_get_type", "(", "self", ",", "values", ")", ":", "if", "TYPE", "not", "in", "values", ":", "self", ".", "_error", "(", "\"No pattern type given but should be \"", "\"\\\"{}\\\"\"", ".", "format", "(", "KNITTING_PATTERN_TYPE", ")", ")", "type_", "=", "...
:return: the type of a knitting pattern set.
[ ":", "return", ":", "the", "type", "of", "a", "knitting", "pattern", "set", "." ]
python
valid
45.636364
twilio/authy-python
authy/api/resources.py
https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L362-L375
def verification_check(self, phone_number, country_code, verification_code): """ :param phone_number: :param country_code: :param verification_code: :return: """ options = { 'phone_number': phone_number, 'country_code': country_code, ...
[ "def", "verification_check", "(", "self", ",", "phone_number", ",", "country_code", ",", "verification_code", ")", ":", "options", "=", "{", "'phone_number'", ":", "phone_number", ",", "'country_code'", ":", "country_code", ",", "'verification_code'", ":", "verifica...
:param phone_number: :param country_code: :param verification_code: :return:
[ ":", "param", "phone_number", ":", ":", "param", "country_code", ":", ":", "param", "verification_code", ":", ":", "return", ":" ]
python
train
33.714286
tanghaibao/goatools
goatools/gosubdag/plot/goea_results.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/plot/goea_results.py#L55-L66
def set_goid2color_pval(self, goid2color): """Fill missing colors based on p-value of an enriched GO term.""" alpha2col = self.alpha2col if self.pval_name is not None: pval_name = self.pval_name for goid, res in self.go2res.items(): pval = getattr(res, pva...
[ "def", "set_goid2color_pval", "(", "self", ",", "goid2color", ")", ":", "alpha2col", "=", "self", ".", "alpha2col", "if", "self", ".", "pval_name", "is", "not", "None", ":", "pval_name", "=", "self", ".", "pval_name", "for", "goid", ",", "res", "in", "se...
Fill missing colors based on p-value of an enriched GO term.
[ "Fill", "missing", "colors", "based", "on", "p", "-", "value", "of", "an", "enriched", "GO", "term", "." ]
python
train
49.75
sixty-north/added-value
source/added_value/multisort.py
https://github.com/sixty-north/added-value/blob/7ae75b56712822b074fc874612d6058bb7d16a1e/source/added_value/multisort.py#L62-L81
def tuplesorted(items, *keys): """Sort by tuples with a different key for each item. Args: items: An iterable series of sequences (typically tuples) *keys: Key objects which transform individual elements of each tuple into sort keys. The zeroth object transforms the zerot...
[ "def", "tuplesorted", "(", "items", ",", "*", "keys", ")", ":", "# Transform the keys so each works on one item of the tuple", "tuple_keys", "=", "[", "Key", "(", "func", "=", "lambda", "t", ",", "i", "=", "index", ",", "k", "=", "key", ":", "k", ".", "fun...
Sort by tuples with a different key for each item. Args: items: An iterable series of sequences (typically tuples) *keys: Key objects which transform individual elements of each tuple into sort keys. The zeroth object transforms the zeroth element of each tuple, the first ...
[ "Sort", "by", "tuples", "with", "a", "different", "key", "for", "each", "item", "." ]
python
train
37.3
gwastro/pycbc
pycbc/workflow/jobsetup.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/jobsetup.py#L558-L572
def get_valid_times_for_job_legacy(self, num_job): """ Get the times for which the job num_job will be valid, using the method use in inspiral hipe. """ # All of this should be integers, so no rounding factors needed. shift_dur = self.curr_seg[0] + int(self.job_time_shift * num_j...
[ "def", "get_valid_times_for_job_legacy", "(", "self", ",", "num_job", ")", ":", "# All of this should be integers, so no rounding factors needed.", "shift_dur", "=", "self", ".", "curr_seg", "[", "0", "]", "+", "int", "(", "self", ".", "job_time_shift", "*", "num_job"...
Get the times for which the job num_job will be valid, using the method use in inspiral hipe.
[ "Get", "the", "times", "for", "which", "the", "job", "num_job", "will", "be", "valid", "using", "the", "method", "use", "in", "inspiral", "hipe", "." ]
python
train
46.866667
slundberg/shap
shap/benchmark/metrics.py
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/metrics.py#L279-L286
def keep_negative_impute(X, y, model_generator, method_name, num_fcounts=11): """ Keep Negative (impute) xlabel = "Max fraction of features kept" ylabel = "Negative mean model output" transform = "negate" sort_order = 17 """ return __run_measure(measures.keep_impute, X, y, model_generator, m...
[ "def", "keep_negative_impute", "(", "X", ",", "y", ",", "model_generator", ",", "method_name", ",", "num_fcounts", "=", "11", ")", ":", "return", "__run_measure", "(", "measures", ".", "keep_impute", ",", "X", ",", "y", ",", "model_generator", ",", "method_n...
Keep Negative (impute) xlabel = "Max fraction of features kept" ylabel = "Negative mean model output" transform = "negate" sort_order = 17
[ "Keep", "Negative", "(", "impute", ")", "xlabel", "=", "Max", "fraction", "of", "features", "kept", "ylabel", "=", "Negative", "mean", "model", "output", "transform", "=", "negate", "sort_order", "=", "17" ]
python
train
44.25
pysathq/pysat
examples/lsu.py
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/lsu.py#L139-L164
def _init(self, formula): """ SAT oracle initialization. The method creates a new SAT oracle and feeds it with the formula's hard clauses. Afterwards, all soft clauses of the formula are augmented with selector literals and also added to the solver. The list of al...
[ "def", "_init", "(", "self", ",", "formula", ")", ":", "self", ".", "oracle", "=", "Solver", "(", "name", "=", "self", ".", "solver", ",", "bootstrap_with", "=", "formula", ".", "hard", ",", "incr", "=", "True", ",", "use_timer", "=", "True", ")", ...
SAT oracle initialization. The method creates a new SAT oracle and feeds it with the formula's hard clauses. Afterwards, all soft clauses of the formula are augmented with selector literals and also added to the solver. The list of all introduced selectors is stored in va...
[ "SAT", "oracle", "initialization", ".", "The", "method", "creates", "a", "new", "SAT", "oracle", "and", "feeds", "it", "with", "the", "formula", "s", "hard", "clauses", ".", "Afterwards", "all", "soft", "clauses", "of", "the", "formula", "are", "augmented", ...
python
train
41.923077
rbarrois/aionotify
aionotify/aioutils.py
https://github.com/rbarrois/aionotify/blob/6cfa35b26a2660f77f29a92d3efb7d1dde685b43/aionotify/aioutils.py#L94-L102
def _call_connection_lost(self, error): """Finalize closing.""" try: self._protocol.connection_lost(error) finally: os.close(self._fileno) self._fileno = None self._protocol = None self._loop = None
[ "def", "_call_connection_lost", "(", "self", ",", "error", ")", ":", "try", ":", "self", ".", "_protocol", ".", "connection_lost", "(", "error", ")", "finally", ":", "os", ".", "close", "(", "self", ".", "_fileno", ")", "self", ".", "_fileno", "=", "No...
Finalize closing.
[ "Finalize", "closing", "." ]
python
test
30.444444
openfisca/openfisca-france-indirect-taxation
openfisca_france_indirect_taxation/build_survey_data/step_2_homogeneisation_vehicules.py
https://github.com/openfisca/openfisca-france-indirect-taxation/blob/b4bc7da90a1126ebfc3af2c3ec61de5a2b70bb2e/openfisca_france_indirect_taxation/build_survey_data/step_2_homogeneisation_vehicules.py#L55-L109
def build_homogeneisation_vehicules(temporary_store = None, year = None): assert temporary_store is not None """Compute vehicule numbers by type""" assert year is not None # Load data bdf_survey_collection = SurveyCollection.load( collection = 'budget_des_familles', config_files_directory =...
[ "def", "build_homogeneisation_vehicules", "(", "temporary_store", "=", "None", ",", "year", "=", "None", ")", ":", "assert", "temporary_store", "is", "not", "None", "assert", "year", "is", "not", "None", "# Load data", "bdf_survey_collection", "=", "SurveyCollection...
Compute vehicule numbers by type
[ "Compute", "vehicule", "numbers", "by", "type" ]
python
train
44.981818
StackStorm/pybind
pybind/slxos/v17s_1_02/protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mep/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mep/__init__.py#L97-L123
def _set_mep_id(self, v, load=False): """ Setter method for mep_id, mapped from YANG variable /protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mep/mep_id (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_mep_id is considered as a private method. Backends ...
[ "def", "_set_mep_id", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "parent", "=", "getattr", "(", "self", ",", "\"_parent\"", ",", "None", ")", "if", "parent", "is", "not", "None", "and", "load", "is", "False", ":", "raise", "Attribute...
Setter method for mep_id, mapped from YANG variable /protocol/cfm/domain_name/ma_name/cfm_ma_sub_commands/mep/mep_id (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_mep_id is considered as a private method. Backends looking to populate this variable should do so...
[ "Setter", "method", "for", "mep_id", "mapped", "from", "YANG", "variable", "/", "protocol", "/", "cfm", "/", "domain_name", "/", "ma_name", "/", "cfm_ma_sub_commands", "/", "mep", "/", "mep_id", "(", "uint32", ")", "If", "this", "variable", "is", "read", "...
python
train
82.851852
rosshamish/hexgrid
hexgrid.py
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L371-L383
def nodes_touching_tile(tile_id): """ Get a list of node coordinates touching the given tile. :param tile_id: tile identifier, Tile.tile_id :return: list of node coordinates touching the given tile, list(int) """ coord = tile_id_to_coord(tile_id) nodes = [] for offset in _tile_node_offs...
[ "def", "nodes_touching_tile", "(", "tile_id", ")", ":", "coord", "=", "tile_id_to_coord", "(", "tile_id", ")", "nodes", "=", "[", "]", "for", "offset", "in", "_tile_node_offsets", ".", "keys", "(", ")", ":", "nodes", ".", "append", "(", "coord", "+", "of...
Get a list of node coordinates touching the given tile. :param tile_id: tile identifier, Tile.tile_id :return: list of node coordinates touching the given tile, list(int)
[ "Get", "a", "list", "of", "node", "coordinates", "touching", "the", "given", "tile", "." ]
python
train
34.538462
idmillington/layout
layout/cairo_utils.py
https://github.com/idmillington/layout/blob/c452d1d7a74c9a74f7639c1b49e2a41c4e354bb5/layout/cairo_utils.py#L140-L158
def draw_polygon( self, *pts, close_path=True, stroke=None, stroke_width=1, stroke_dash=None, fill=None ) -> None: """Draws the given polygon.""" c = self.c c.save() c.new_path() for x...
[ "def", "draw_polygon", "(", "self", ",", "*", "pts", ",", "close_path", "=", "True", ",", "stroke", "=", "None", ",", "stroke_width", "=", "1", ",", "stroke_dash", "=", "None", ",", "fill", "=", "None", ")", "->", "None", ":", "c", "=", "self", "."...
Draws the given polygon.
[ "Draws", "the", "given", "polygon", "." ]
python
train
26.157895
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_1/work_item_tracking/work_item_tracking_client.py
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/work_item_tracking/work_item_tracking_client.py#L722-L746
def get_queries(self, project, expand=None, depth=None, include_deleted=None): """GetQueries. [Preview API] Gets the root queries and their children :param str project: Project ID or project name :param str expand: Include the query string (wiql), clauses, query result columns, and sort ...
[ "def", "get_queries", "(", "self", ",", "project", ",", "expand", "=", "None", ",", "depth", "=", "None", ",", "include_deleted", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'pr...
GetQueries. [Preview API] Gets the root queries and their children :param str project: Project ID or project name :param str expand: Include the query string (wiql), clauses, query result columns, and sort options in the results. :param int depth: In the folder of queries, return child q...
[ "GetQueries", ".", "[", "Preview", "API", "]", "Gets", "the", "root", "queries", "and", "their", "children", ":", "param", "str", "project", ":", "Project", "ID", "or", "project", "name", ":", "param", "str", "expand", ":", "Include", "the", "query", "st...
python
train
60.24
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/DFReader.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/DFReader.py#L204-L208
def find_time_base(self, gps, first_ms_stamp): '''work out time basis for the log - new style''' t = self._gpsTimeToTime(gps.Week, gps.TimeMS) self.set_timebase(t - gps.T*0.001) self.timestamp = self.timebase + first_ms_stamp*0.001
[ "def", "find_time_base", "(", "self", ",", "gps", ",", "first_ms_stamp", ")", ":", "t", "=", "self", ".", "_gpsTimeToTime", "(", "gps", ".", "Week", ",", "gps", ".", "TimeMS", ")", "self", ".", "set_timebase", "(", "t", "-", "gps", ".", "T", "*", "...
work out time basis for the log - new style
[ "work", "out", "time", "basis", "for", "the", "log", "-", "new", "style" ]
python
train
51.8
KnowledgeLinks/rdfframework
rdfframework/rml/rmlmanager.py
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/rmlmanager.py#L133-L152
def make_processor(self, name, mappings, processor_type, **kwargs): """ Instantiates a RmlProcessor and registers it in the manager Args: ----- name: the name to register the processor mappings: the list RML mapping definitions to use processor_type: ...
[ "def", "make_processor", "(", "self", ",", "name", ",", "mappings", ",", "processor_type", ",", "*", "*", "kwargs", ")", ":", "from", ".", "processor", "import", "Processor", "if", "self", ".", "processors", ".", "get", "(", "name", ")", ":", "raise", ...
Instantiates a RmlProcessor and registers it in the manager Args: ----- name: the name to register the processor mappings: the list RML mapping definitions to use processor_type: the name of the RML processor to use
[ "Instantiates", "a", "RmlProcessor", "and", "registers", "it", "in", "the", "manager" ]
python
train
40.95
alecthomas/voluptuous
voluptuous/validators.py
https://github.com/alecthomas/voluptuous/blob/36c8c11e2b7eb402c24866fa558473661ede9403/voluptuous/validators.py#L366-L388
def Email(v): """Verify that the value is an Email or not. >>> s = Schema(Email()) >>> with raises(MultipleInvalid, 'expected an Email'): ... s("a.com") >>> with raises(MultipleInvalid, 'expected an Email'): ... s("a@.com") >>> with raises(MultipleInvalid, 'expected an Email'): ... ...
[ "def", "Email", "(", "v", ")", ":", "try", ":", "if", "not", "v", "or", "\"@\"", "not", "in", "v", ":", "raise", "EmailInvalid", "(", "\"Invalid Email\"", ")", "user_part", ",", "domain_part", "=", "v", ".", "rsplit", "(", "'@'", ",", "1", ")", "if...
Verify that the value is an Email or not. >>> s = Schema(Email()) >>> with raises(MultipleInvalid, 'expected an Email'): ... s("a.com") >>> with raises(MultipleInvalid, 'expected an Email'): ... s("a@.com") >>> with raises(MultipleInvalid, 'expected an Email'): ... s("a@.com") >>>...
[ "Verify", "that", "the", "value", "is", "an", "Email", "or", "not", "." ]
python
train
29.565217
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L2625-L2653
def smoothing_cross_entropy_factored_grad(op, dy): """Gradient function for smoothing_cross_entropy_factored.""" a = op.inputs[0] b = op.inputs[1] labels = op.inputs[2] confidence = op.inputs[3] num_splits = 16 vocab_size = shape_list(b)[0] labels = approximate_split(labels, num_splits) a = approximat...
[ "def", "smoothing_cross_entropy_factored_grad", "(", "op", ",", "dy", ")", ":", "a", "=", "op", ".", "inputs", "[", "0", "]", "b", "=", "op", ".", "inputs", "[", "1", "]", "labels", "=", "op", ".", "inputs", "[", "2", "]", "confidence", "=", "op", ...
Gradient function for smoothing_cross_entropy_factored.
[ "Gradient", "function", "for", "smoothing_cross_entropy_factored", "." ]
python
train
35
pybel/pybel
src/pybel/struct/summary/edge_summary.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/summary/edge_summary.py#L135-L147
def get_unused_list_annotation_values(graph) -> Mapping[str, Set[str]]: """Get all of the unused values for list annotations. :param pybel.BELGraph graph: A BEL graph :return: A dictionary of {str annotation: set of str values that aren't used} """ result = {} for annotation, values in graph.an...
[ "def", "get_unused_list_annotation_values", "(", "graph", ")", "->", "Mapping", "[", "str", ",", "Set", "[", "str", "]", "]", ":", "result", "=", "{", "}", "for", "annotation", ",", "values", "in", "graph", ".", "annotation_list", ".", "items", "(", ")",...
Get all of the unused values for list annotations. :param pybel.BELGraph graph: A BEL graph :return: A dictionary of {str annotation: set of str values that aren't used}
[ "Get", "all", "of", "the", "unused", "values", "for", "list", "annotations", "." ]
python
train
43.076923
numenta/htmresearch
htmresearch/algorithms/union_temporal_pooler.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/union_temporal_pooler.py#L283-L304
def _getMostActiveCells(self): """ Gets the most active cells in the Union SDR having at least non-zero activation in sorted order. @return: a list of cell indices """ poolingActivation = self._poolingActivation nonZeroCells = numpy.argwhere(poolingActivation > 0)[:,0] # include a tie-b...
[ "def", "_getMostActiveCells", "(", "self", ")", ":", "poolingActivation", "=", "self", ".", "_poolingActivation", "nonZeroCells", "=", "numpy", ".", "argwhere", "(", "poolingActivation", ">", "0", ")", "[", ":", ",", "0", "]", "# include a tie-breaker before sorti...
Gets the most active cells in the Union SDR having at least non-zero activation in sorted order. @return: a list of cell indices
[ "Gets", "the", "most", "active", "cells", "in", "the", "Union", "SDR", "having", "at", "least", "non", "-", "zero", "activation", "in", "sorted", "order", "." ]
python
train
35.636364
JDongian/python-jamo
jamo/jamo.py
https://github.com/JDongian/python-jamo/blob/d087a9f5f52f066fb933ad1da8e9915703374c9a/jamo/jamo.py#L54-L71
def _hangul_char_to_jamo(syllable): """Return a 3-tuple of lead, vowel, and tail jamo characters. Note: Non-Hangul characters are echoed back. """ if is_hangul_char(syllable): rem = ord(syllable) - _JAMO_OFFSET tail = rem % 28 vowel = 1 + ((rem - tail) % 588) // 28 lead =...
[ "def", "_hangul_char_to_jamo", "(", "syllable", ")", ":", "if", "is_hangul_char", "(", "syllable", ")", ":", "rem", "=", "ord", "(", "syllable", ")", "-", "_JAMO_OFFSET", "tail", "=", "rem", "%", "28", "vowel", "=", "1", "+", "(", "(", "rem", "-", "t...
Return a 3-tuple of lead, vowel, and tail jamo characters. Note: Non-Hangul characters are echoed back.
[ "Return", "a", "3", "-", "tuple", "of", "lead", "vowel", "and", "tail", "jamo", "characters", ".", "Note", ":", "Non", "-", "Hangul", "characters", "are", "echoed", "back", "." ]
python
train
35.666667
numenta/nupic
src/nupic/swarming/exp_generator/experiment_generator.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L233-L247
def _isInt(x, precision = 0.0001): """ Return (isInt, intValue) for a given floating point number. Parameters: ---------------------------------------------------------------------- x: floating point number to evaluate precision: desired precision retval: (isInt, intValue) isInt: True if x...
[ "def", "_isInt", "(", "x", ",", "precision", "=", "0.0001", ")", ":", "xInt", "=", "int", "(", "round", "(", "x", ")", ")", "return", "(", "abs", "(", "x", "-", "xInt", ")", "<", "precision", "*", "x", ",", "xInt", ")" ]
Return (isInt, intValue) for a given floating point number. Parameters: ---------------------------------------------------------------------- x: floating point number to evaluate precision: desired precision retval: (isInt, intValue) isInt: True if x is close enough to an integer value ...
[ "Return", "(", "isInt", "intValue", ")", "for", "a", "given", "floating", "point", "number", "." ]
python
valid
30.466667
google/grr
grr/server/grr_response_server/databases/mysql_users.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_users.py#L106-L116
def ReadGRRUser(self, username, cursor=None): """Reads a user object corresponding to a given name.""" cursor.execute( "SELECT username, password, ui_mode, canary_mode, user_type " "FROM grr_users WHERE username_hash = %s", [mysql_utils.Hash(username)]) row = cursor.fetchone() if row is...
[ "def", "ReadGRRUser", "(", "self", ",", "username", ",", "cursor", "=", "None", ")", ":", "cursor", ".", "execute", "(", "\"SELECT username, password, ui_mode, canary_mode, user_type \"", "\"FROM grr_users WHERE username_hash = %s\"", ",", "[", "mysql_utils", ".", "Hash",...
Reads a user object corresponding to a given name.
[ "Reads", "a", "user", "object", "corresponding", "to", "a", "given", "name", "." ]
python
train
36.090909
os/slacker
slacker/__init__.py
https://github.com/os/slacker/blob/133596971b44a7b3bd07d11afb37745a67f0ec46/slacker/__init__.py#L1168-L1177
def post(self, data): """ Posts message with payload formatted in accordance with this documentation https://api.slack.com/incoming-webhooks """ if not self.url: raise Error('URL for incoming webhook is undefined') return requests.post(self.url, data=json.dum...
[ "def", "post", "(", "self", ",", "data", ")", ":", "if", "not", "self", ".", "url", ":", "raise", "Error", "(", "'URL for incoming webhook is undefined'", ")", "return", "requests", ".", "post", "(", "self", ".", "url", ",", "data", "=", "json", ".", "...
Posts message with payload formatted in accordance with this documentation https://api.slack.com/incoming-webhooks
[ "Posts", "message", "with", "payload", "formatted", "in", "accordance", "with", "this", "documentation", "https", ":", "//", "api", ".", "slack", ".", "com", "/", "incoming", "-", "webhooks" ]
python
train
39.3
google/grr
api_client/python/grr_api_client/client.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/api_client/python/grr_api_client/client.py#L170-L177
def Approval(self, username, approval_id): """Returns a reference to an approval.""" return ClientApprovalRef( client_id=self.client_id, username=username, approval_id=approval_id, context=self._context)
[ "def", "Approval", "(", "self", ",", "username", ",", "approval_id", ")", ":", "return", "ClientApprovalRef", "(", "client_id", "=", "self", ".", "client_id", ",", "username", "=", "username", ",", "approval_id", "=", "approval_id", ",", "context", "=", "sel...
Returns a reference to an approval.
[ "Returns", "a", "reference", "to", "an", "approval", "." ]
python
train
29.625
cburgmer/upsidedown
upsidedown.py
https://github.com/cburgmer/upsidedown/blob/0bc80421d197cbda0f824a44ceed5c4fcb5cf8ba/upsidedown.py#L126-L139
def main(): """Main method for running upsidedown.py from the command line.""" import sys output = [] line = sys.stdin.readline() while line: line = line.strip("\n") output.append(transform(line)) line = sys.stdin.readline() output.reverse() print("\n".join(output)...
[ "def", "main", "(", ")", ":", "import", "sys", "output", "=", "[", "]", "line", "=", "sys", ".", "stdin", ".", "readline", "(", ")", "while", "line", ":", "line", "=", "line", ".", "strip", "(", "\"\\n\"", ")", "output", ".", "append", "(", "tran...
Main method for running upsidedown.py from the command line.
[ "Main", "method", "for", "running", "upsidedown", ".", "py", "from", "the", "command", "line", "." ]
python
train
22
dw/mitogen
mitogen/select.py
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/select.py#L288-L333
def get_event(self, timeout=None, block=True): """ Fetch the next available :class:`Event` from any source, or raise :class:`mitogen.core.TimeoutError` if no value is available within `timeout` seconds. On success, the message's :attr:`receiver <mitogen.core.Message.rece...
[ "def", "get_event", "(", "self", ",", "timeout", "=", "None", ",", "block", "=", "True", ")", ":", "if", "not", "self", ".", "_receivers", ":", "raise", "Error", "(", "self", ".", "empty_msg", ")", "event", "=", "Event", "(", ")", "while", "True", ...
Fetch the next available :class:`Event` from any source, or raise :class:`mitogen.core.TimeoutError` if no value is available within `timeout` seconds. On success, the message's :attr:`receiver <mitogen.core.Message.receiver>` attribute is set to the receiver. :param float time...
[ "Fetch", "the", "next", "available", ":", "class", ":", "Event", "from", "any", "source", "or", "raise", ":", "class", ":", "mitogen", ".", "core", ".", "TimeoutError", "if", "no", "value", "is", "available", "within", "timeout", "seconds", "." ]
python
train
39.565217
cuihantao/andes
andes/models/base.py
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1443-L1460
def elem_find(self, field, value): """ Return the indices of elements whose field first satisfies the given values ``value`` should be unique in self.field. This function does not check the uniqueness. :param field: name of the supplied field :param value: value of fiel...
[ "def", "elem_find", "(", "self", ",", "field", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "int", ",", "float", ",", "str", ")", ")", ":", "value", "=", "[", "value", "]", "f", "=", "list", "(", "self", ".", "__dict__", ...
Return the indices of elements whose field first satisfies the given values ``value`` should be unique in self.field. This function does not check the uniqueness. :param field: name of the supplied field :param value: value of field of the elemtn to find :return: idx of the ele...
[ "Return", "the", "indices", "of", "elements", "whose", "field", "first", "satisfies", "the", "given", "values" ]
python
train
33.666667
CityOfZion/neo-python-rpc
neorpc/Client.py
https://github.com/CityOfZion/neo-python-rpc/blob/89d22c4043654b2941bf26b15a1c09082901d9ef/neorpc/Client.py#L66-L77
def get_balance(self, asset_hash, id=None, endpoint=None): """ Get balance by asset hash Args: asset_hash: (str) asset to lookup, example would be 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b' id: (int, optional) id to use for response tracking ...
[ "def", "get_balance", "(", "self", ",", "asset_hash", ",", "id", "=", "None", ",", "endpoint", "=", "None", ")", ":", "return", "self", ".", "_call_endpoint", "(", "GET_BALANCE", ",", "params", "=", "[", "asset_hash", "]", ",", "id", "=", "id", ",", ...
Get balance by asset hash Args: asset_hash: (str) asset to lookup, example would be 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b' id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Ret...
[ "Get", "balance", "by", "asset", "hash", "Args", ":", "asset_hash", ":", "(", "str", ")", "asset", "to", "lookup", "example", "would", "be", "c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b", "id", ":", "(", "int", "optional", ")", "id", "to", "...
python
train
48.25
aiogram/aiogram
aiogram/dispatcher/webhook.py
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L524-L533
def write(self, *text, sep=' '): """ Write text to response :param text: :param sep: :return: """ self.text += markdown.text(*text, sep) return self
[ "def", "write", "(", "self", ",", "*", "text", ",", "sep", "=", "' '", ")", ":", "self", ".", "text", "+=", "markdown", ".", "text", "(", "*", "text", ",", "sep", ")", "return", "self" ]
Write text to response :param text: :param sep: :return:
[ "Write", "text", "to", "response" ]
python
train
20.4
tensorflow/hub
tensorflow_hub/module.py
https://github.com/tensorflow/hub/blob/09f45963f6787322967b6fec61459f3ac56fbb27/tensorflow_hub/module.py#L388-L421
def _prepare_dict_inputs(inputs, tensor_info_map): """Converts inputs to a dict of inputs and checks extra/missing args. Args: inputs: inputs fed to Module.__call__(). tensor_info_map: A map from string to `tensor_info.ParsedTensorInfo` describing the signature inputs. Returns: A dict of value...
[ "def", "_prepare_dict_inputs", "(", "inputs", ",", "tensor_info_map", ")", ":", "if", "inputs", "is", "None", ":", "dict_inputs", "=", "{", "}", "elif", "isinstance", "(", "inputs", ",", "dict", ")", ":", "dict_inputs", "=", "inputs", "elif", "len", "(", ...
Converts inputs to a dict of inputs and checks extra/missing args. Args: inputs: inputs fed to Module.__call__(). tensor_info_map: A map from string to `tensor_info.ParsedTensorInfo` describing the signature inputs. Returns: A dict of values with the same keys as tensor_info_map. Raises: ...
[ "Converts", "inputs", "to", "a", "dict", "of", "inputs", "and", "checks", "extra", "/", "missing", "args", "." ]
python
train
35.882353
DolphDev/ezurl
ezurl/__init__.py
https://github.com/DolphDev/ezurl/blob/deaa755db2c0532c237f9eb4192aa51c7e928a07/ezurl/__init__.py#L102-L109
def _page_gen(self): """ Generates The String for pages """ track = "" for page in self.__pages__: track += "/{page}".format(page=page) return track
[ "def", "_page_gen", "(", "self", ")", ":", "track", "=", "\"\"", "for", "page", "in", "self", ".", "__pages__", ":", "track", "+=", "\"/{page}\"", ".", "format", "(", "page", "=", "page", ")", "return", "track" ]
Generates The String for pages
[ "Generates", "The", "String", "for", "pages" ]
python
train
25.125
jingw/pyhdfs
pyhdfs.py
https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L616-L626
def set_xattr(self, path, xattr_name, xattr_value, flag, **kwargs): """Set an xattr of a file or directory. :param xattr_name: The name must be prefixed with the namespace followed by ``.``. For example, ``user.attr``. :param flag: ``CREATE`` or ``REPLACE`` """ kwarg...
[ "def", "set_xattr", "(", "self", ",", "path", ",", "xattr_name", ",", "xattr_value", ",", "flag", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'xattr.name'", "]", "=", "xattr_name", "kwargs", "[", "'xattr.value'", "]", "=", "xattr_value", "response",...
Set an xattr of a file or directory. :param xattr_name: The name must be prefixed with the namespace followed by ``.``. For example, ``user.attr``. :param flag: ``CREATE`` or ``REPLACE``
[ "Set", "an", "xattr", "of", "a", "file", "or", "directory", "." ]
python
train
44.181818
numenta/nupic
src/nupic/swarming/utils.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/utils.py#L218-L277
def filterResults(allResults, reportKeys, optimizeKey=None): """ Given the complete set of results generated by an experiment (passed in 'results'), filter out and return only the ones the caller wants, as specified through 'reportKeys' and 'optimizeKey'. A report key is a string of key names separated by colo...
[ "def", "filterResults", "(", "allResults", ",", "reportKeys", ",", "optimizeKey", "=", "None", ")", ":", "# Init return values", "optimizeDict", "=", "dict", "(", ")", "# Get all available report key names for this experiment", "allReportKeys", "=", "set", "(", ")", "...
Given the complete set of results generated by an experiment (passed in 'results'), filter out and return only the ones the caller wants, as specified through 'reportKeys' and 'optimizeKey'. A report key is a string of key names separated by colons, each key being one level deeper into the experiment results d...
[ "Given", "the", "complete", "set", "of", "results", "generated", "by", "an", "experiment", "(", "passed", "in", "results", ")", "filter", "out", "and", "return", "only", "the", "ones", "the", "caller", "wants", "as", "specified", "through", "reportKeys", "an...
python
valid
41.7
ansible/tower-cli
tower_cli/cli/resource.py
https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/resource.py#L97-L124
def _echo_method(self, method): """Given a method, return a method that runs the internal method and echos the result. """ @functools.wraps(method) def func(*args, **kwargs): # Echo warning if this method is deprecated. if getattr(method, 'deprecated', Fal...
[ "def", "_echo_method", "(", "self", ",", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Echo warning if this method is deprecated.", "if", "getattr", "(", "meth...
Given a method, return a method that runs the internal method and echos the result.
[ "Given", "a", "method", "return", "a", "method", "that", "runs", "the", "internal", "method", "and", "echos", "the", "result", "." ]
python
valid
39.642857
iotile/coretools
iotilesensorgraph/iotile/sg/optimizer/passes/convert_to_always.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/optimizer/passes/convert_to_always.py#L32-L67
def run(self, sensor_graph, model): """Run this optimization pass on the sensor graph If necessary, information on the device model being targeted can be found in the associated model argument. Args: sensor_graph (SensorGraph): The sensor graph to optimize model...
[ "def", "run", "(", "self", ",", "sensor_graph", ",", "model", ")", ":", "# This check can be done if there is 1 input and it is count == 1", "# and the stream type is input or unbuffered", "for", "node", ",", "inputs", ",", "outputs", "in", "sensor_graph", ".", "iterate_bfs...
Run this optimization pass on the sensor graph If necessary, information on the device model being targeted can be found in the associated model argument. Args: sensor_graph (SensorGraph): The sensor graph to optimize model (DeviceModel): The device model we're using
[ "Run", "this", "optimization", "pass", "on", "the", "sensor", "graph" ]
python
train
32.861111
fabioz/PyDev.Debugger
_pydev_bundle/pydev_localhost.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_bundle/pydev_localhost.py#L8-L33
def get_localhost(): ''' Should return 127.0.0.1 in ipv4 and ::1 in ipv6 localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work properly and takes a lot of time (had this issue on the pyunit server). Using the IP directly solves the problem. ...
[ "def", "get_localhost", "(", ")", ":", "# TODO: Needs better investigation!", "global", "_cache", "if", "_cache", "is", "None", ":", "try", ":", "for", "addr_info", "in", "socket", ".", "getaddrinfo", "(", "\"localhost\"", ",", "80", ",", "0", ",", "0", ",",...
Should return 127.0.0.1 in ipv4 and ::1 in ipv6 localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work properly and takes a lot of time (had this issue on the pyunit server). Using the IP directly solves the problem.
[ "Should", "return", "127", ".", "0", ".", "0", ".", "1", "in", "ipv4", "and", "::", "1", "in", "ipv6" ]
python
train
33.769231
pgmpy/pgmpy
pgmpy/readwrite/UAI.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/UAI.py#L98-L119
def get_variables(self): """ Returns a list of variables. Each variable is represented by an index of list. For example if the no of variables are 4 then the list will be [var_0, var_1, var_2, var_3] Returns ------- list: list of variables Exampl...
[ "def", "get_variables", "(", "self", ")", ":", "variables", "=", "[", "]", "for", "var", "in", "range", "(", "0", ",", "self", ".", "no_variables", ")", ":", "var_name", "=", "\"var_\"", "+", "str", "(", "var", ")", "variables", ".", "append", "(", ...
Returns a list of variables. Each variable is represented by an index of list. For example if the no of variables are 4 then the list will be [var_0, var_1, var_2, var_3] Returns ------- list: list of variables Example ------- >>> reader = UAIRea...
[ "Returns", "a", "list", "of", "variables", ".", "Each", "variable", "is", "represented", "by", "an", "index", "of", "list", ".", "For", "example", "if", "the", "no", "of", "variables", "are", "4", "then", "the", "list", "will", "be", "[", "var_0", "var...
python
train
28.227273
Terrance/SkPy
skpy/conn.py
https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L507-L518
def checkUser(self, user): """ Query a username or email address to see if a corresponding Microsoft account exists. Args: user (str): username or email address of an account Returns: bool: whether the account exists """ return not self.conn("POS...
[ "def", "checkUser", "(", "self", ",", "user", ")", ":", "return", "not", "self", ".", "conn", "(", "\"POST\"", ",", "\"{0}/GetCredentialType.srf\"", ".", "format", "(", "SkypeConnection", ".", "API_MSACC", ")", ",", "json", "=", "{", "\"username\"", ":", "...
Query a username or email address to see if a corresponding Microsoft account exists. Args: user (str): username or email address of an account Returns: bool: whether the account exists
[ "Query", "a", "username", "or", "email", "address", "to", "see", "if", "a", "corresponding", "Microsoft", "account", "exists", "." ]
python
test
38.166667
iclab/centinel
centinel/primitives/headless_browser.py
https://github.com/iclab/centinel/blob/9a25dcf30c6a1db3c046f7ccb8ab8873e455c1a4/centinel/primitives/headless_browser.py#L160-L202
def get(self, host, files_count, path="/", ssl=False, external=None): """ Send get request to a url and wrap the results :param host (str): the host name of the url :param path (str): the path of the url (start with "/") :return (dict): the result of the test url """ ...
[ "def", "get", "(", "self", ",", "host", ",", "files_count", ",", "path", "=", "\"/\"", ",", "ssl", "=", "False", ",", "external", "=", "None", ")", ":", "theme", "=", "\"https\"", "if", "ssl", "else", "\"http\"", "url", "=", "host", "+", "path", "h...
Send get request to a url and wrap the results :param host (str): the host name of the url :param path (str): the path of the url (start with "/") :return (dict): the result of the test url
[ "Send", "get", "request", "to", "a", "url", "and", "wrap", "the", "results", ":", "param", "host", "(", "str", ")", ":", "the", "host", "name", "of", "the", "url", ":", "param", "path", "(", "str", ")", ":", "the", "path", "of", "the", "url", "("...
python
train
31.046512
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L229-L291
def list_datasets( self, project=None, include_all=False, filter=None, max_results=None, page_token=None, retry=DEFAULT_RETRY, ): """List datasets for the project associated with this client. See https://cloud.google.com/bigquery/docs/...
[ "def", "list_datasets", "(", "self", ",", "project", "=", "None", ",", "include_all", "=", "False", ",", "filter", "=", "None", ",", "max_results", "=", "None", ",", "page_token", "=", "None", ",", "retry", "=", "DEFAULT_RETRY", ",", ")", ":", "extra_par...
List datasets for the project associated with this client. See https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list Args: project (str): Optional. Project ID to use for retreiving datasets. Defaults to the client's project. ...
[ "List", "datasets", "for", "the", "project", "associated", "with", "this", "client", "." ]
python
train
38.539683
linkedin/naarad
src/naarad/metrics/proczoneinfo_metric.py
https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/metrics/proczoneinfo_metric.py#L63-L129
def parse(self): """ Parse the vmstat file :return: status of the metric parse """ file_status = True for input_file in self.infile_list: file_status = file_status and naarad.utils.is_valid_file(input_file) if not file_status: return False status = True cur_zone = No...
[ "def", "parse", "(", "self", ")", ":", "file_status", "=", "True", "for", "input_file", "in", "self", ".", "infile_list", ":", "file_status", "=", "file_status", "and", "naarad", ".", "utils", ".", "is_valid_file", "(", "input_file", ")", "if", "not", "fil...
Parse the vmstat file :return: status of the metric parse
[ "Parse", "the", "vmstat", "file", ":", "return", ":", "status", "of", "the", "metric", "parse" ]
python
valid
40.507463
fitnr/twitter_bot_utils
twitter_bot_utils/helpers.py
https://github.com/fitnr/twitter_bot_utils/blob/21f35afa5048cd3efa54db8cb87d405f69a78a62/twitter_bot_utils/helpers.py#L140-L159
def shorten(string, length=140, ellipsis=None): ''' Shorten a string to 140 characters without breaking words. Optionally add an ellipsis character: '…' if ellipsis=True, or a given string e.g. ellipsis=' (cut)' ''' string = string.strip() if len(string) > length: if ellipsis is Tru...
[ "def", "shorten", "(", "string", ",", "length", "=", "140", ",", "ellipsis", "=", "None", ")", ":", "string", "=", "string", ".", "strip", "(", ")", "if", "len", "(", "string", ")", ">", "length", ":", "if", "ellipsis", "is", "True", ":", "ellipsis...
Shorten a string to 140 characters without breaking words. Optionally add an ellipsis character: '…' if ellipsis=True, or a given string e.g. ellipsis=' (cut)'
[ "Shorten", "a", "string", "to", "140", "characters", "without", "breaking", "words", ".", "Optionally", "add", "an", "ellipsis", "character", ":", "…", "if", "ellipsis", "=", "True", "or", "a", "given", "string", "e", ".", "g", ".", "ellipsis", "=", "(",...
python
train
26.45
olsoneric/pedemath
pedemath/vec3.py
https://github.com/olsoneric/pedemath/blob/4bffcfe7089e421d603eb0a9708b84789c2d16be/pedemath/vec3.py#L120-L125
def cross_v3(vec_a, vec_b): """Return the crossproduct between vec_a and vec_b.""" return Vec3(vec_a.y * vec_b.z - vec_a.z * vec_b.y, vec_a.z * vec_b.x - vec_a.x * vec_b.z, vec_a.x * vec_b.y - vec_a.y * vec_b.x)
[ "def", "cross_v3", "(", "vec_a", ",", "vec_b", ")", ":", "return", "Vec3", "(", "vec_a", ".", "y", "*", "vec_b", ".", "z", "-", "vec_a", ".", "z", "*", "vec_b", ".", "y", ",", "vec_a", ".", "z", "*", "vec_b", ".", "x", "-", "vec_a", ".", "x",...
Return the crossproduct between vec_a and vec_b.
[ "Return", "the", "crossproduct", "between", "vec_a", "and", "vec_b", "." ]
python
train
41.166667
wsmith323/namedspace
namedspace/__init__.py
https://github.com/wsmith323/namedspace/blob/b9c5b22eee1e845eeca7b7e803fc4e79a61c2491/namedspace/__init__.py#L13-L396
def namedspace(typename, required_fields=(), optional_fields=(), mutable_fields=(), default_values=frozendict(), default_value_factories=frozendict(), return_none=False): """Builds a new class that encapsulates a namespace and provides various ways to access it. The typename argument is re...
[ "def", "namedspace", "(", "typename", ",", "required_fields", "=", "(", ")", ",", "optional_fields", "=", "(", ")", ",", "mutable_fields", "=", "(", ")", ",", "default_values", "=", "frozendict", "(", ")", ",", "default_value_factories", "=", "frozendict", "...
Builds a new class that encapsulates a namespace and provides various ways to access it. The typename argument is required and is the name of the namedspace class that will be generated. The required_fields and optional_fields arguments can be a string or sequence of strings and together specify ...
[ "Builds", "a", "new", "class", "that", "encapsulates", "a", "namespace", "and", "provides", "various", "ways", "to", "access", "it", "." ]
python
train
36.528646
PyCQA/astroid
astroid/rebuilder.py
https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/rebuilder.py#L658-L666
def visit_ifexp(self, node, parent): """visit a IfExp node by returning a fresh instance of it""" newnode = nodes.IfExp(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.test, newnode), self.visit(node.body, newnode), self.visit(node.orel...
[ "def", "visit_ifexp", "(", "self", ",", "node", ",", "parent", ")", ":", "newnode", "=", "nodes", ".", "IfExp", "(", "node", ".", "lineno", ",", "node", ".", "col_offset", ",", "parent", ")", "newnode", ".", "postinit", "(", "self", ".", "visit", "("...
visit a IfExp node by returning a fresh instance of it
[ "visit", "a", "IfExp", "node", "by", "returning", "a", "fresh", "instance", "of", "it" ]
python
train
39.777778
abourget/gevent-socketio
socketio/namespace.py
https://github.com/abourget/gevent-socketio/blob/1cdb1594a315326987a17ce0924ea448a82fab01/socketio/namespace.py#L380-L409
def send(self, message, json=False, callback=None): """Use send to send a simple string message. If ``json`` is True, the message will be encoded as a JSON object on the wire, and decoded on the other side. This is mostly for backwards compatibility. ``emit()`` is more fun. :...
[ "def", "send", "(", "self", ",", "message", ",", "json", "=", "False", ",", "callback", "=", "None", ")", ":", "pkt", "=", "dict", "(", "type", "=", "\"message\"", ",", "data", "=", "message", ",", "endpoint", "=", "self", ".", "ns_name", ")", "if"...
Use send to send a simple string message. If ``json`` is True, the message will be encoded as a JSON object on the wire, and decoded on the other side. This is mostly for backwards compatibility. ``emit()`` is more fun. :param callback: This is a callback function that will be ...
[ "Use", "send", "to", "send", "a", "simple", "string", "message", "." ]
python
valid
44.466667
MacHu-GWU/uszipcode-project
uszipcode/pkg/sqlalchemy_mate/orm/extended_declarative_base.py
https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/orm/extended_declarative_base.py#L153-L167
def absorb(self, other): """ For attributes of others that value is not None, assign it to self. **中文文档** 将另一个文档中的数据更新到本条文档。当且仅当数据值不为None时。 """ if not isinstance(other, self.__class__): raise TypeError("`other` has to be a instance of %s!" % ...
[ "def", "absorb", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "raise", "TypeError", "(", "\"`other` has to be a instance of %s!\"", "%", "self", ".", "__class__", ")", "for", "attr", ...
For attributes of others that value is not None, assign it to self. **中文文档** 将另一个文档中的数据更新到本条文档。当且仅当数据值不为None时。
[ "For", "attributes", "of", "others", "that", "value", "is", "not", "None", "assign", "it", "to", "self", "." ]
python
train
30.866667
spyder-ide/spyder
spyder/plugins/findinfiles/widgets.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/findinfiles/widgets.py#L353-L366
def set_project_path(self, path): """ Sets the project path and disables the project search in the combobox if the value of path is None. """ if path is None: self.project_path = None self.model().item(PROJECT, 0).setEnabled(False) if s...
[ "def", "set_project_path", "(", "self", ",", "path", ")", ":", "if", "path", "is", "None", ":", "self", ".", "project_path", "=", "None", "self", ".", "model", "(", ")", ".", "item", "(", "PROJECT", ",", "0", ")", ".", "setEnabled", "(", "False", "...
Sets the project path and disables the project search in the combobox if the value of path is None.
[ "Sets", "the", "project", "path", "and", "disables", "the", "project", "search", "in", "the", "combobox", "if", "the", "value", "of", "path", "is", "None", "." ]
python
train
37.928571
hapyak/flask-peewee-swagger
flask_peewee_swagger/swagger.py
https://github.com/hapyak/flask-peewee-swagger/blob/1b7dd54a5e823401b80e04ac421ee15c9fab3f06/flask_peewee_swagger/swagger.py#L93-L110
def model_resource(self, resource_name): """ Details of a specific model resource. """ resource = first( [resource for resource in self.api._registry.values() if resource.get_api_name() == resource_name]) data = { 'apiVersion': '0.1', 'swaggerVe...
[ "def", "model_resource", "(", "self", ",", "resource_name", ")", ":", "resource", "=", "first", "(", "[", "resource", "for", "resource", "in", "self", ".", "api", ".", "_registry", ".", "values", "(", ")", "if", "resource", ".", "get_api_name", "(", ")",...
Details of a specific model resource.
[ "Details", "of", "a", "specific", "model", "resource", "." ]
python
train
37.777778
yyuu/botornado
boto/ec2/connection.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/ec2/connection.py#L166-L188
def get_all_kernels(self, kernel_ids=None, owners=None): """ Retrieve all the EC2 kernels available on your account. Constructs a filter to allow the processing to happen server side. :type kernel_ids: list :param kernel_ids: A list of strings with the image IDs wanted ...
[ "def", "get_all_kernels", "(", "self", ",", "kernel_ids", "=", "None", ",", "owners", "=", "None", ")", ":", "params", "=", "{", "}", "if", "kernel_ids", ":", "self", ".", "build_list_params", "(", "params", ",", "kernel_ids", ",", "'ImageId'", ")", "if"...
Retrieve all the EC2 kernels available on your account. Constructs a filter to allow the processing to happen server side. :type kernel_ids: list :param kernel_ids: A list of strings with the image IDs wanted :type owners: list :param owners: A list of owner IDs :rtype...
[ "Retrieve", "all", "the", "EC2", "kernels", "available", "on", "your", "account", ".", "Constructs", "a", "filter", "to", "allow", "the", "processing", "to", "happen", "server", "side", "." ]
python
train
36.782609
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_0/tfvc/tfvc_client.py
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/tfvc/tfvc_client.py#L423-L455
def get_items(self, project=None, scope_path=None, recursion_level=None, include_links=None, version_descriptor=None): """GetItems. Get a list of Tfvc items :param str project: Project ID or project name :param str scope_path: Version control path of a folder to return multiple items. ...
[ "def", "get_items", "(", "self", ",", "project", "=", "None", ",", "scope_path", "=", "None", ",", "recursion_level", "=", "None", ",", "include_links", "=", "None", ",", "version_descriptor", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "...
GetItems. Get a list of Tfvc items :param str project: Project ID or project name :param str scope_path: Version control path of a folder to return multiple items. :param str recursion_level: None (just the item), or OneLevel (contents of a folder). :param bool include_links: Tru...
[ "GetItems", ".", "Get", "a", "list", "of", "Tfvc", "items", ":", "param", "str", "project", ":", "Project", "ID", "or", "project", "name", ":", "param", "str", "scope_path", ":", "Version", "control", "path", "of", "a", "folder", "to", "return", "multipl...
python
train
63.666667
Roguelazer/muttdown
muttdown/main.py
https://github.com/Roguelazer/muttdown/blob/5aeb514ba5c4eac00db8dc3690daba60f778076c/muttdown/main.py#L138-L151
def smtp_connection(c): """Create an SMTP connection from a Config object""" if c.smtp_ssl: klass = smtplib.SMTP_SSL else: klass = smtplib.SMTP conn = klass(c.smtp_host, c.smtp_port, timeout=c.smtp_timeout) if not c.smtp_ssl: conn.ehlo() conn.starttls() conn.e...
[ "def", "smtp_connection", "(", "c", ")", ":", "if", "c", ".", "smtp_ssl", ":", "klass", "=", "smtplib", ".", "SMTP_SSL", "else", ":", "klass", "=", "smtplib", ".", "SMTP", "conn", "=", "klass", "(", "c", ".", "smtp_host", ",", "c", ".", "smtp_port", ...
Create an SMTP connection from a Config object
[ "Create", "an", "SMTP", "connection", "from", "a", "Config", "object" ]
python
train
28.928571
Rapptz/discord.py
discord/ext/commands/core.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1549-L1564
def is_owner(): """A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.Bot.is_owner`. This check raises a special exception, :exc:`.NotOwner` that is derived from :exc:`.CheckFailure`. """ async def predicate(ctx): i...
[ "def", "is_owner", "(", ")", ":", "async", "def", "predicate", "(", "ctx", ")", ":", "if", "not", "await", "ctx", ".", "bot", ".", "is_owner", "(", "ctx", ".", "author", ")", ":", "raise", "NotOwner", "(", "'You do not own this bot.'", ")", "return", "...
A :func:`.check` that checks if the person invoking this command is the owner of the bot. This is powered by :meth:`.Bot.is_owner`. This check raises a special exception, :exc:`.NotOwner` that is derived from :exc:`.CheckFailure`.
[ "A", ":", "func", ":", ".", "check", "that", "checks", "if", "the", "person", "invoking", "this", "command", "is", "the", "owner", "of", "the", "bot", "." ]
python
train
28.125
apache/airflow
airflow/www/security.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/security.py#L294-L301
def _has_role(self, role_name_or_list): """ Whether the user has this role name """ if not isinstance(role_name_or_list, list): role_name_or_list = [role_name_or_list] return any( [r.name in role_name_or_list for r in self.get_user_roles()])
[ "def", "_has_role", "(", "self", ",", "role_name_or_list", ")", ":", "if", "not", "isinstance", "(", "role_name_or_list", ",", "list", ")", ":", "role_name_or_list", "=", "[", "role_name_or_list", "]", "return", "any", "(", "[", "r", ".", "name", "in", "ro...
Whether the user has this role name
[ "Whether", "the", "user", "has", "this", "role", "name" ]
python
test
37.25
maweigert/gputools
gputools/noise/perlin.py
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/noise/perlin.py#L12-L21
def abspath(myPath): import sys, os """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS return os.path.join(base_path, os.path.basename(myPath)) except Exception: ...
[ "def", "abspath", "(", "myPath", ")", ":", "import", "sys", ",", "os", "try", ":", "# PyInstaller creates a temp folder and stores path in _MEIPASS", "base_path", "=", "sys", ".", "_MEIPASS", "return", "os", ".", "path", ".", "join", "(", "base_path", ",", "os",...
Get absolute path to resource, works for dev and for PyInstaller
[ "Get", "absolute", "path", "to", "resource", "works", "for", "dev", "and", "for", "PyInstaller" ]
python
train
41.8
prometheus/client_python
prometheus_client/decorator.py
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/decorator.py#L242-L265
def decorator(caller, _func=None): """decorator(caller) converts a caller function into a decorator""" if _func is not None: # return a decorated function # this is obsolete behavior; you should use decorate instead return decorate(_func, caller) # else return a decorator function if in...
[ "def", "decorator", "(", "caller", ",", "_func", "=", "None", ")", ":", "if", "_func", "is", "not", "None", ":", "# return a decorated function", "# this is obsolete behavior; you should use decorate instead", "return", "decorate", "(", "_func", ",", "caller", ")", ...
decorator(caller) converts a caller function into a decorator
[ "decorator", "(", "caller", ")", "converts", "a", "caller", "function", "into", "a", "decorator" ]
python
train
44.666667
leancloud/python-sdk
leancloud/query.py
https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/query.py#L474-L487
def matches_key_in_query(self, key, query_key, query): """ 增加查询条件,限制查询结果对象指定字段的值,与另外一个查询对象的返回结果指定的值相同。 :param key: 查询条件字段名 :param query_key: 查询对象返回结果的字段名 :param query: 查询对象 :type query: Query :rtype: Query """ dumped = query.dump() dumped[...
[ "def", "matches_key_in_query", "(", "self", ",", "key", ",", "query_key", ",", "query", ")", ":", "dumped", "=", "query", ".", "dump", "(", ")", "dumped", "[", "'className'", "]", "=", "query", ".", "_query_class", ".", "_class_name", "self", ".", "_add_...
增加查询条件,限制查询结果对象指定字段的值,与另外一个查询对象的返回结果指定的值相同。 :param key: 查询条件字段名 :param query_key: 查询对象返回结果的字段名 :param query: 查询对象 :type query: Query :rtype: Query
[ "增加查询条件,限制查询结果对象指定字段的值,与另外一个查询对象的返回结果指定的值相同。" ]
python
train
32.357143
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L2846-L2880
def _fake_referencenames(self, namespace, **params): """ Implements a mock WBEM server responder for :meth:`~pywbem.WBEMConnection.ReferenceNames` """ assert params['ResultClass'] is None or \ isinstance(params['ResultClass'], CIMClassName) rc = None if param...
[ "def", "_fake_referencenames", "(", "self", ",", "namespace", ",", "*", "*", "params", ")", ":", "assert", "params", "[", "'ResultClass'", "]", "is", "None", "or", "isinstance", "(", "params", "[", "'ResultClass'", "]", ",", "CIMClassName", ")", "rc", "=",...
Implements a mock WBEM server responder for :meth:`~pywbem.WBEMConnection.ReferenceNames`
[ "Implements", "a", "mock", "WBEM", "server", "responder", "for", ":", "meth", ":", "~pywbem", ".", "WBEMConnection", ".", "ReferenceNames" ]
python
train
39.028571
faucamp/python-gsmmodem
tools/gsmtermlib/terminal.py
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L533-L568
def _doCommandCompletion(self): """ Command-completion method """ prefix = ''.join(self.inputBuffer).strip().upper() matches = self.completion.keys(prefix) matchLen = len(matches) if matchLen == 0 and prefix[-1] == '=': try: ...
[ "def", "_doCommandCompletion", "(", "self", ")", ":", "prefix", "=", "''", ".", "join", "(", "self", ".", "inputBuffer", ")", ".", "strip", "(", ")", ".", "upper", "(", ")", "matches", "=", "self", ".", "completion", ".", "keys", "(", "prefix", ")", ...
Command-completion method
[ "Command", "-", "completion", "method" ]
python
train
44.805556
jaraco/jaraco.mongodb
jaraco/mongodb/oplog.py
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/oplog.py#L30-L154
def parse_args(*args, **kwargs): """ Parse the args for the command. It should be possible for one to specify '--ns', '-x', and '--rename' multiple times: >>> args = parse_args(['--ns', 'foo', 'bar', '--ns', 'baz']) >>> args.ns ['foo', 'bar', 'baz'] >>> parse_args(['-x', '--exclude'])...
[ "def", "parse_args", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "parser", ".", "add_argument", "(", "\"--help\"", ",", "help", "=", "\"show usage information\"", ...
Parse the args for the command. It should be possible for one to specify '--ns', '-x', and '--rename' multiple times: >>> args = parse_args(['--ns', 'foo', 'bar', '--ns', 'baz']) >>> args.ns ['foo', 'bar', 'baz'] >>> parse_args(['-x', '--exclude']).exclude [] >>> renames = parse_args...
[ "Parse", "the", "args", "for", "the", "command", "." ]
python
train
27.536
singularityhub/sregistry-cli
sregistry/main/docker/api.py
https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/docker/api.py#L234-L299
def get_digests(self): '''return a list of layers from a manifest. The function is intended to work with both version 1 and 2 of the schema. All layers (including redundant) are returned. By default, we try version 2 first, then fall back to version 1. For version 1 manifests: ex...
[ "def", "get_digests", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'manifests'", ")", ":", "bot", ".", "error", "(", "'Please retrieve manifests for an image first.'", ")", "sys", ".", "exit", "(", "1", ")", "digests", "=", "[", "]", ...
return a list of layers from a manifest. The function is intended to work with both version 1 and 2 of the schema. All layers (including redundant) are returned. By default, we try version 2 first, then fall back to version 1. For version 1 manifests: extraction is reversed P...
[ "return", "a", "list", "of", "layers", "from", "a", "manifest", ".", "The", "function", "is", "intended", "to", "work", "with", "both", "version", "1", "and", "2", "of", "the", "schema", ".", "All", "layers", "(", "including", "redundant", ")", "are", ...
python
test
29
Vagrants/blackbird
blackbird/utils/configread.py
https://github.com/Vagrants/blackbird/blob/3b38cd5650caae362e0668dbd38bf8f88233e079/blackbird/utils/configread.py#L631-L732
def is_log(value): """ This function checks whether file path that is specified at "log_file" option exists, whether write permission to the file path. Return the following value: case1: exists path and write permission is_log('/tmp') '/tmp/hogehoge.log' case2: non-exis...
[ "def", "is_log", "(", "value", ")", ":", "if", "value", ".", "lower", "(", ")", "==", "'syslog'", ":", "return", "'syslog'", "value", "=", "os", ".", "path", ".", "expanduser", "(", "value", ")", "value", "=", "os", ".", "path", ".", "expandvars", ...
This function checks whether file path that is specified at "log_file" option exists, whether write permission to the file path. Return the following value: case1: exists path and write permission is_log('/tmp') '/tmp/hogehoge.log' case2: non-exists path and write permission ...
[ "This", "function", "checks", "whether", "file", "path", "that", "is", "specified", "at", "log_file", "option", "exists", "whether", "write", "permission", "to", "the", "file", "path", "." ]
python
train
29.921569
dw/mitogen
ansible_mitogen/mixins.py
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/mixins.py#L125-L150
def fake_shell(self, func, stdout=False): """ Execute a function and decorate its return value in the style of _low_level_execute_command(). This produces a return value that looks like some shell command was run, when really func() was implemented entirely in Python. If...
[ "def", "fake_shell", "(", "self", ",", "func", ",", "stdout", "=", "False", ")", ":", "dct", "=", "self", ".", "COMMAND_RESULT", ".", "copy", "(", ")", "try", ":", "rc", "=", "func", "(", ")", "if", "stdout", ":", "dct", "[", "'stdout'", "]", "="...
Execute a function and decorate its return value in the style of _low_level_execute_command(). This produces a return value that looks like some shell command was run, when really func() was implemented entirely in Python. If the function raises :py:class:`mitogen.core.CallError`, this ...
[ "Execute", "a", "function", "and", "decorate", "its", "return", "value", "in", "the", "style", "of", "_low_level_execute_command", "()", ".", "This", "produces", "a", "return", "value", "that", "looks", "like", "some", "shell", "command", "was", "run", "when",...
python
train
35.230769
resync/resync
resync/dump.py
https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/dump.py#L59-L87
def write_zip(self, resources=None, dumpfile=None): """Write a ZIP format dump file. Writes a ZIP file containing the resources in the iterable resources along with a manifest file manifest.xml (written first). No checks on the size of files or total size are performed, this is expected...
[ "def", "write_zip", "(", "self", ",", "resources", "=", "None", ",", "dumpfile", "=", "None", ")", ":", "compression", "=", "(", "ZIP_DEFLATED", "if", "self", ".", "compress", "else", "ZIP_STORED", ")", "zf", "=", "ZipFile", "(", "dumpfile", ",", "mode",...
Write a ZIP format dump file. Writes a ZIP file containing the resources in the iterable resources along with a manifest file manifest.xml (written first). No checks on the size of files or total size are performed, this is expected to have been done beforehand.
[ "Write", "a", "ZIP", "format", "dump", "file", "." ]
python
train
41.758621
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L104-L106
def Reverse(self, y): """Looks up y and returns the corresponding value of x.""" return self._Bisect(y, self.ys, self.xs)
[ "def", "Reverse", "(", "self", ",", "y", ")", ":", "return", "self", ".", "_Bisect", "(", "y", ",", "self", ".", "ys", ",", "self", ".", "xs", ")" ]
Looks up y and returns the corresponding value of x.
[ "Looks", "up", "y", "and", "returns", "the", "corresponding", "value", "of", "x", "." ]
python
train
45
codeinthehole/django-async-messages
async_messages/__init__.py
https://github.com/codeinthehole/django-async-messages/blob/292cb2fc517521dabc67b90e7ca5b1617f59e214/async_messages/__init__.py#L33-L44
def get_messages(user): """ Fetch messages for given user. Returns None if no such message exists. :param user: User instance """ key = _user_key(user) result = cache.get(key) if result: cache.delete(key) return result return None
[ "def", "get_messages", "(", "user", ")", ":", "key", "=", "_user_key", "(", "user", ")", "result", "=", "cache", ".", "get", "(", "key", ")", "if", "result", ":", "cache", ".", "delete", "(", "key", ")", "return", "result", "return", "None" ]
Fetch messages for given user. Returns None if no such message exists. :param user: User instance
[ "Fetch", "messages", "for", "given", "user", ".", "Returns", "None", "if", "no", "such", "message", "exists", "." ]
python
test
22.416667
openstack/horizon
openstack_auth/utils.py
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/utils.py#L323-L330
def clean_up_auth_url(auth_url): """Clean up the auth url to extract the exact Keystone URL""" # NOTE(mnaser): This drops the query and fragment because we're only # trying to extract the Keystone URL. scheme, netloc, path, query, fragment = urlparse.urlsplit(auth_url) return urlparse...
[ "def", "clean_up_auth_url", "(", "auth_url", ")", ":", "# NOTE(mnaser): This drops the query and fragment because we're only", "# trying to extract the Keystone URL.", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urlparse", ".", "ur...
Clean up the auth url to extract the exact Keystone URL
[ "Clean", "up", "the", "auth", "url", "to", "extract", "the", "exact", "Keystone", "URL" ]
python
train
48.625
viatoriche/microservices
microservices/queues/runners.py
https://github.com/viatoriche/microservices/blob/3510563edd15dc6131b8a948d6062856cd904ac7/microservices/queues/runners.py#L1-L22
def gevent_run(app, monkey_patch=True, start=True, debug=False, **kwargs): # pragma: no cover """Run your app in gevent.spawn, run simple loop if start == True :param app: queues.Microservice instance :param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules,...
[ "def", "gevent_run", "(", "app", ",", "monkey_patch", "=", "True", ",", "start", "=", "True", ",", "debug", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "if", "monkey_patch", ":", "from", "gevent", "import", "monkey", "monkey", ...
Run your app in gevent.spawn, run simple loop if start == True :param app: queues.Microservice instance :param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: True :param start: boolean, if True, server will be start (simple loop) :param kwargs: other params...
[ "Run", "your", "app", "in", "gevent", ".", "spawn", "run", "simple", "loop", "if", "start", "==", "True" ]
python
train
31.681818
rocky/python3-trepan
trepan/lib/stack.py
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/stack.py#L31-L37
def count_frames(frame, count_start=0): "Return a count of the number of frames" count = -count_start while frame: count += 1 frame = frame.f_back return count
[ "def", "count_frames", "(", "frame", ",", "count_start", "=", "0", ")", ":", "count", "=", "-", "count_start", "while", "frame", ":", "count", "+=", "1", "frame", "=", "frame", ".", "f_back", "return", "count" ]
Return a count of the number of frames
[ "Return", "a", "count", "of", "the", "number", "of", "frames" ]
python
test
26.428571
arviz-devs/arviz
arviz/data/io_cmdstan.py
https://github.com/arviz-devs/arviz/blob/d04d8da07f029fd2931f48d2f7f324cf393e5277/arviz/data/io_cmdstan.py#L288-L307
def sample_stats_prior_to_xarray(self): """Extract sample_stats from fit.""" dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64} # copy dims and coords dims = deepcopy(self.dims) if self.dims is not None else {} coords = deepcopy(self.coords) if sel...
[ "def", "sample_stats_prior_to_xarray", "(", "self", ")", ":", "dtypes", "=", "{", "\"divergent__\"", ":", "bool", ",", "\"n_leapfrog__\"", ":", "np", ".", "int64", ",", "\"treedepth__\"", ":", "np", ".", "int64", "}", "# copy dims and coords", "dims", "=", "de...
Extract sample_stats from fit.
[ "Extract", "sample_stats", "from", "fit", "." ]
python
train
49.1
agoragames/chai
chai/expectation.py
https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/expectation.py#L265-L270
def match(self, *args, **kwargs): """ Check the if these args match this expectation. """ return self._any_args or \ self._arguments_rule.validate(*args, **kwargs)
[ "def", "match", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_any_args", "or", "self", ".", "_arguments_rule", ".", "validate", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Check the if these args match this expectation.
[ "Check", "the", "if", "these", "args", "match", "this", "expectation", "." ]
python
train
33.666667
PythonCharmers/python-future
src/future/backports/email/utils.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L259-L264
def decode_rfc2231(s): """Decode string according to RFC 2231""" parts = s.split(TICK, 2) if len(parts) <= 2: return None, None, s return parts
[ "def", "decode_rfc2231", "(", "s", ")", ":", "parts", "=", "s", ".", "split", "(", "TICK", ",", "2", ")", "if", "len", "(", "parts", ")", "<=", "2", ":", "return", "None", ",", "None", ",", "s", "return", "parts" ]
Decode string according to RFC 2231
[ "Decode", "string", "according", "to", "RFC", "2231" ]
python
train
27
infoxchange/supervisor-logging
supervisor_logging/__init__.py
https://github.com/infoxchange/supervisor-logging/blob/2d4411378fb52799bc506a68f1a914cbe671b13b/supervisor_logging/__init__.py#L74-L81
def eventdata(payload): """ Parse a Supervisor event. """ headerinfo, data = payload.split('\n', 1) headers = get_headers(headerinfo) return headers, data
[ "def", "eventdata", "(", "payload", ")", ":", "headerinfo", ",", "data", "=", "payload", ".", "split", "(", "'\\n'", ",", "1", ")", "headers", "=", "get_headers", "(", "headerinfo", ")", "return", "headers", ",", "data" ]
Parse a Supervisor event.
[ "Parse", "a", "Supervisor", "event", "." ]
python
train
21.5
boronine/discipline
discipline/models.py
https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/discipline/models.py#L808-L821
def html_state(self): """Display state in HTML format for the admin form.""" ret = "" state = json.loads(self.state) for (app, appstate) in state.items(): for (model, modelstate) in appstate.items(): ret += "<p>%s.models.%s</p>" % (app, model,) ...
[ "def", "html_state", "(", "self", ")", ":", "ret", "=", "\"\"", "state", "=", "json", ".", "loads", "(", "self", ".", "state", ")", "for", "(", "app", ",", "appstate", ")", "in", "state", ".", "items", "(", ")", ":", "for", "(", "model", ",", "...
Display state in HTML format for the admin form.
[ "Display", "state", "in", "HTML", "format", "for", "the", "admin", "form", "." ]
python
train
42.428571
aio-libs/aiohttp
aiohttp/web_urldispatcher.py
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/web_urldispatcher.py#L843-L845
def url_for(self, *args: str, **kwargs: str) -> URL: """Construct url for route with additional params.""" return self._resource.url_for(*args, **kwargs)
[ "def", "url_for", "(", "self", ",", "*", "args", ":", "str", ",", "*", "*", "kwargs", ":", "str", ")", "->", "URL", ":", "return", "self", ".", "_resource", ".", "url_for", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Construct url for route with additional params.
[ "Construct", "url", "for", "route", "with", "additional", "params", "." ]
python
train
55.666667
GiulioRossetti/ndlib
ndlib/models/epidemics/KerteszThresholdModel.py
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/epidemics/KerteszThresholdModel.py#L62-L136
def iteration(self, node_status=True): """ Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status) """ self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future...
[ "def", "iteration", "(", "self", ",", "node_status", "=", "True", ")", ":", "self", ".", "clean_initial_status", "(", "self", ".", "available_statuses", ".", "values", "(", ")", ")", "actual_status", "=", "{", "node", ":", "nstatus", "for", "node", ",", ...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
[ "Execute", "a", "single", "model", "iteration" ]
python
train
42.253333
kgori/treeCl
treeCl/distance_matrix.py
https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/distance_matrix.py#L291-L304
def eigen(matrix): """ Calculates the eigenvalues and eigenvectors of the input matrix. Returns a tuple of (eigenvalues, eigenvectors, cumulative percentage of variance explained). Eigenvalues and eigenvectors are sorted in order of eigenvalue magnitude, high to low """ (vals, vecs) = np.linalg.eig...
[ "def", "eigen", "(", "matrix", ")", ":", "(", "vals", ",", "vecs", ")", "=", "np", ".", "linalg", ".", "eigh", "(", "matrix", ")", "ind", "=", "vals", ".", "argsort", "(", ")", "[", ":", ":", "-", "1", "]", "vals", "=", "vals", "[", "ind", ...
Calculates the eigenvalues and eigenvectors of the input matrix. Returns a tuple of (eigenvalues, eigenvectors, cumulative percentage of variance explained). Eigenvalues and eigenvectors are sorted in order of eigenvalue magnitude, high to low
[ "Calculates", "the", "eigenvalues", "and", "eigenvectors", "of", "the", "input", "matrix", ".", "Returns", "a", "tuple", "of", "(", "eigenvalues", "eigenvectors", "cumulative", "percentage", "of", "variance", "explained", ")", ".", "Eigenvalues", "and", "eigenvect...
python
train
39.214286