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 |
|---|---|---|---|---|---|---|---|---|---|
Nekroze/partpy | partpy/sourcestring.py | https://github.com/Nekroze/partpy/blob/dbb7d2fb285464fc43d85bc31f5af46192d301f6/partpy/sourcestring.py#L347-L352 | def match_any_char(self, chars, offset=0):
"""Match and return the current SourceString char if its in chars."""
if not self.has_space(offset=offset):
return ''
current = self.string[self.pos + offset]
return current if current in chars else '' | [
"def",
"match_any_char",
"(",
"self",
",",
"chars",
",",
"offset",
"=",
"0",
")",
":",
"if",
"not",
"self",
".",
"has_space",
"(",
"offset",
"=",
"offset",
")",
":",
"return",
"''",
"current",
"=",
"self",
".",
"string",
"[",
"self",
".",
"pos",
"+... | Match and return the current SourceString char if its in chars. | [
"Match",
"and",
"return",
"the",
"current",
"SourceString",
"char",
"if",
"its",
"in",
"chars",
"."
] | python | train | 47.166667 |
humilis/humilis-lambdautils | lambdautils/state.py | https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/state.py#L227-L237 | def get_state_batch(keys, namespace=None, consistent=True):
"""Get a batch of items from the state store."""
ukeys = set(keys)
if namespace:
ns_keys = ["{}:{}".format(namespace, key) for key in ukeys]
uvalues = {k: v for k, v
in zip(ukeys, get_item_batch(ns_keys, consistent=con... | [
"def",
"get_state_batch",
"(",
"keys",
",",
"namespace",
"=",
"None",
",",
"consistent",
"=",
"True",
")",
":",
"ukeys",
"=",
"set",
"(",
"keys",
")",
"if",
"namespace",
":",
"ns_keys",
"=",
"[",
"\"{}:{}\"",
".",
"format",
"(",
"namespace",
",",
"key"... | Get a batch of items from the state store. | [
"Get",
"a",
"batch",
"of",
"items",
"from",
"the",
"state",
"store",
"."
] | python | train | 34.090909 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/extensions/autoreload.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/extensions/autoreload.py#L195-L249 | def check(self, check_all=False):
"""Check whether some modules need to be reloaded."""
if not self.enabled and not check_all:
return
if check_all or self.check_all:
modules = sys.modules.keys()
else:
modules = self.modules.keys()
for modnam... | [
"def",
"check",
"(",
"self",
",",
"check_all",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"enabled",
"and",
"not",
"check_all",
":",
"return",
"if",
"check_all",
"or",
"self",
".",
"check_all",
":",
"modules",
"=",
"sys",
".",
"modules",
".",
... | Check whether some modules need to be reloaded. | [
"Check",
"whether",
"some",
"modules",
"need",
"to",
"be",
"reloaded",
"."
] | python | test | 31.690909 |
nicferrier/md | src/mdlib/pull.py | https://github.com/nicferrier/md/blob/302ca8882dae060fb15bd5ae470d8e661fb67ec4/src/mdlib/pull.py#L96-L120 | def _list_remote(store, maildir, verbose=False):
"""List the a maildir.
store is an abstract representation of the source maildir.
maildir is the local maildir to which mail will be pulled.
This is a generator for a reason. Because of the way ssh
multi-mastering works a single open TCP connectio... | [
"def",
"_list_remote",
"(",
"store",
",",
"maildir",
",",
"verbose",
"=",
"False",
")",
":",
"# This command produces a list of all files in the maildir like:",
"# base-filename timestamp container-directory",
"command",
"=",
"\"\"\"echo {maildir}/{{cur,new}} | tr ' ' '\\\\n' | whi... | List the a maildir.
store is an abstract representation of the source maildir.
maildir is the local maildir to which mail will be pulled.
This is a generator for a reason. Because of the way ssh
multi-mastering works a single open TCP connection allows multiple
virtual ssh connections. So the en... | [
"List",
"the",
"a",
"maildir",
"."
] | python | train | 45.72 |
pandas-dev/pandas | pandas/core/internals/blocks.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/internals/blocks.py#L651-L682 | def _try_cast_result(self, result, dtype=None):
""" try to cast the result to our original type, we may have
roundtripped thru object in the mean-time
"""
if dtype is None:
dtype = self.dtype
if self.is_integer or self.is_bool or self.is_datetime:
pass
... | [
"def",
"_try_cast_result",
"(",
"self",
",",
"result",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"self",
".",
"dtype",
"if",
"self",
".",
"is_integer",
"or",
"self",
".",
"is_bool",
"or",
"self",
".",
"is_da... | try to cast the result to our original type, we may have
roundtripped thru object in the mean-time | [
"try",
"to",
"cast",
"the",
"result",
"to",
"our",
"original",
"type",
"we",
"may",
"have",
"roundtripped",
"thru",
"object",
"in",
"the",
"mean",
"-",
"time"
] | python | train | 37.6875 |
diyan/pywinrm | winrm/protocol.py | https://github.com/diyan/pywinrm/blob/ed4c2d991d9d0fe921dfc958c475c4c6a570519e/winrm/protocol.py#L274-L299 | def close_shell(self, shell_id):
"""
Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool
"""
message_id = uuid.uui... | [
"def",
"close_shell",
"(",
"self",
",",
"shell_id",
")",
":",
"message_id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
"req",
"=",
"{",
"'env:Envelope'",
":",
"self",
".",
"_get_soap_header",
"(",
"resource_uri",
"=",
"'http://schemas.microsoft.com/wbem/wsman/1/windows/... | Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool | [
"Close",
"the",
"shell"
] | python | train | 40.192308 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L149-L188 | def ifinstalled(parser, token):
"""
Old-style ``if`` tag that renders contents if the given app is
installed. The main use case is:
{% ifinstalled app_name %}
{% include "app_name/template.html" %}
{% endifinstalled %}
so we need to manually pull out all tokens if the app isn't
install... | [
"def",
"ifinstalled",
"(",
"parser",
",",
"token",
")",
":",
"try",
":",
"tag",
",",
"app",
"=",
"token",
".",
"split_contents",
"(",
")",
"except",
"ValueError",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"ifinstalled should be in the form: \"",
"\"{% ifinstalle... | Old-style ``if`` tag that renders contents if the given app is
installed. The main use case is:
{% ifinstalled app_name %}
{% include "app_name/template.html" %}
{% endifinstalled %}
so we need to manually pull out all tokens if the app isn't
installed, since if we used a normal ``if`` tag wit... | [
"Old",
"-",
"style",
"if",
"tag",
"that",
"renders",
"contents",
"if",
"the",
"given",
"app",
"is",
"installed",
".",
"The",
"main",
"use",
"case",
"is",
":"
] | python | train | 34.725 |
INM-6/hybridLFPy | hybridLFPy/helpers.py | https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/hybridLFPy/helpers.py#L1088-L1127 | def cv(data, units=False):
"""
Calculate coefficient of variation (cv) of data. Mean and standard deviation
are computed across time.
Parameters
----------
data : numpy.ndarray
1st axis unit, 2nd axis time.
units : bool
Average `cv`.
Returns
-------
numpy.ndar... | [
"def",
"cv",
"(",
"data",
",",
"units",
"=",
"False",
")",
":",
"mu",
"=",
"mean",
"(",
"data",
",",
"time",
"=",
"True",
")",
"var",
"=",
"variance",
"(",
"data",
",",
"time",
"=",
"True",
")",
"cv",
"=",
"np",
".",
"sqrt",
"(",
"var",
")",
... | Calculate coefficient of variation (cv) of data. Mean and standard deviation
are computed across time.
Parameters
----------
data : numpy.ndarray
1st axis unit, 2nd axis time.
units : bool
Average `cv`.
Returns
-------
numpy.ndarray
If units=False, series of u... | [
"Calculate",
"coefficient",
"of",
"variation",
"(",
"cv",
")",
"of",
"data",
".",
"Mean",
"and",
"standard",
"deviation",
"are",
"computed",
"across",
"time",
"."
] | python | train | 20.1 |
log2timeline/plaso | plaso/cli/status_view.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/status_view.py#L208-L221 | def _PrintAnalysisStatusUpdateLinear(self, processing_status):
"""Prints an analysis status update in linear mode.
Args:
processing_status (ProcessingStatus): processing status.
"""
for worker_status in processing_status.workers_status:
status_line = (
'{0:s} (PID: {1:d}) - events... | [
"def",
"_PrintAnalysisStatusUpdateLinear",
"(",
"self",
",",
"processing_status",
")",
":",
"for",
"worker_status",
"in",
"processing_status",
".",
"workers_status",
":",
"status_line",
"=",
"(",
"'{0:s} (PID: {1:d}) - events consumed: {2:d} - running: '",
"'{3!s}\\n'",
")",
... | Prints an analysis status update in linear mode.
Args:
processing_status (ProcessingStatus): processing status. | [
"Prints",
"an",
"analysis",
"status",
"update",
"in",
"linear",
"mode",
"."
] | python | train | 43.071429 |
ml4ai/delphi | delphi/analysis/comparison/utils.py | https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/analysis/comparison/utils.py#L6-L10 | def draw_graph(G: nx.DiGraph, filename: str):
""" Draw a networkx graph with Pygraphviz. """
A = to_agraph(G)
A.graph_attr["rankdir"] = "LR"
A.draw(filename, prog="dot") | [
"def",
"draw_graph",
"(",
"G",
":",
"nx",
".",
"DiGraph",
",",
"filename",
":",
"str",
")",
":",
"A",
"=",
"to_agraph",
"(",
"G",
")",
"A",
".",
"graph_attr",
"[",
"\"rankdir\"",
"]",
"=",
"\"LR\"",
"A",
".",
"draw",
"(",
"filename",
",",
"prog",
... | Draw a networkx graph with Pygraphviz. | [
"Draw",
"a",
"networkx",
"graph",
"with",
"Pygraphviz",
"."
] | python | train | 36.2 |
LordDarkula/chess_py | chess_py/core/algebraic/location.py | https://github.com/LordDarkula/chess_py/blob/14bebc2f8c49ae25c59375cc83d0b38d8ff7281d/chess_py/core/algebraic/location.py#L165-L174 | def shift_up(self, times=1):
"""
Finds Location shifted up by 1
:rtype: Location
"""
try:
return Location(self._rank + times, self._file)
except IndexError as e:
raise IndexError(e) | [
"def",
"shift_up",
"(",
"self",
",",
"times",
"=",
"1",
")",
":",
"try",
":",
"return",
"Location",
"(",
"self",
".",
"_rank",
"+",
"times",
",",
"self",
".",
"_file",
")",
"except",
"IndexError",
"as",
"e",
":",
"raise",
"IndexError",
"(",
"e",
")... | Finds Location shifted up by 1
:rtype: Location | [
"Finds",
"Location",
"shifted",
"up",
"by",
"1"
] | python | train | 24.5 |
flaviogrossi/sockjs-cyclone | sockjs/cyclone/session.py | https://github.com/flaviogrossi/sockjs-cyclone/blob/d3ca053ec1aa1e85f652347bff562c2319be37a2/sockjs/cyclone/session.py#L48-L64 | def set_handler(self, handler):
""" Set transport handler
@param handler: Handler, should derive from the
C{sockjs.cyclone.transports.base.BaseTransportMixin}
"""
if self.handler is not None:
raise Exception('Attempted to overwrite BaseSession handler... | [
"def",
"set_handler",
"(",
"self",
",",
"handler",
")",
":",
"if",
"self",
".",
"handler",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"'Attempted to overwrite BaseSession handler'",
")",
"self",
".",
"handler",
"=",
"handler",
"self",
".",
"transport... | Set transport handler
@param handler: Handler, should derive from the
C{sockjs.cyclone.transports.base.BaseTransportMixin} | [
"Set",
"transport",
"handler"
] | python | train | 32.588235 |
DataDog/integrations-core | datadog_checks_base/datadog_checks/base/checks/prometheus/mixins.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_base/datadog_checks/base/checks/prometheus/mixins.py#L664-L696 | def _submit_gauges_from_histogram(
self, name, metric, send_histograms_buckets=True, custom_tags=None, hostname=None
):
"""
Extracts metrics from a prometheus histogram and sends them as gauges
"""
if custom_tags is None:
custom_tags = []
# histograms do n... | [
"def",
"_submit_gauges_from_histogram",
"(",
"self",
",",
"name",
",",
"metric",
",",
"send_histograms_buckets",
"=",
"True",
",",
"custom_tags",
"=",
"None",
",",
"hostname",
"=",
"None",
")",
":",
"if",
"custom_tags",
"is",
"None",
":",
"custom_tags",
"=",
... | Extracts metrics from a prometheus histogram and sends them as gauges | [
"Extracts",
"metrics",
"from",
"a",
"prometheus",
"histogram",
"and",
"sends",
"them",
"as",
"gauges"
] | python | train | 47.242424 |
xtrementl/focus | focus/plugin/modules/sounds.py | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/sounds.py#L123-L130 | def on_taskend(self, task):
""" Play sounds at task end.
"""
key = 'timer' if task.elapsed else 'end'
filename = self.files.get(key)
if filename:
self._play_sound(filename) | [
"def",
"on_taskend",
"(",
"self",
",",
"task",
")",
":",
"key",
"=",
"'timer'",
"if",
"task",
".",
"elapsed",
"else",
"'end'",
"filename",
"=",
"self",
".",
"files",
".",
"get",
"(",
"key",
")",
"if",
"filename",
":",
"self",
".",
"_play_sound",
"(",... | Play sounds at task end. | [
"Play",
"sounds",
"at",
"task",
"end",
"."
] | python | train | 27.75 |
Lucretiel/Dispatch | dispatching.py | https://github.com/Lucretiel/Dispatch/blob/dffbce6bacb4370c4ecd11652e5ba8a6aaf2b5b4/dispatching.py#L34-L47 | def _bind_args(sig, param_matchers, args, kwargs):
'''
Attempt to bind the args to the type signature. First try to just bind
to the signature, then ensure that all arguments match the parameter
types.
'''
#Bind to signature. May throw its own TypeError
bound = si... | [
"def",
"_bind_args",
"(",
"sig",
",",
"param_matchers",
",",
"args",
",",
"kwargs",
")",
":",
"#Bind to signature. May throw its own TypeError",
"bound",
"=",
"sig",
".",
"bind",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"all",
"(",
"par... | Attempt to bind the args to the type signature. First try to just bind
to the signature, then ensure that all arguments match the parameter
types. | [
"Attempt",
"to",
"bind",
"the",
"args",
"to",
"the",
"type",
"signature",
".",
"First",
"try",
"to",
"just",
"bind",
"to",
"the",
"signature",
"then",
"ensure",
"that",
"all",
"arguments",
"match",
"the",
"parameter",
"types",
"."
] | python | valid | 36.357143 |
juju/python-libjuju | juju/model.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L197-L220 | def get_entity(
self, entity_type, entity_id, history_index=-1, connected=True):
"""Return an object instance for the given entity_type and id.
By default the object state matches the most recent state from
Juju. To get an instance of the object in an older state, pass
histo... | [
"def",
"get_entity",
"(",
"self",
",",
"entity_type",
",",
"entity_id",
",",
"history_index",
"=",
"-",
"1",
",",
"connected",
"=",
"True",
")",
":",
"if",
"history_index",
"<",
"0",
"and",
"history_index",
"!=",
"-",
"1",
":",
"history_index",
"+=",
"le... | Return an object instance for the given entity_type and id.
By default the object state matches the most recent state from
Juju. To get an instance of the object in an older state, pass
history_index, an index into the history deque for the entity. | [
"Return",
"an",
"object",
"instance",
"for",
"the",
"given",
"entity_type",
"and",
"id",
"."
] | python | train | 36.458333 |
wummel/linkchecker | linkcheck/logger/sql.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/sql.py#L77-L85 | def start_output (self):
"""
Write start of checking info as sql comment.
"""
super(SQLLogger, self).start_output()
if self.has_part("intro"):
self.write_intro()
self.writeln()
self.flush() | [
"def",
"start_output",
"(",
"self",
")",
":",
"super",
"(",
"SQLLogger",
",",
"self",
")",
".",
"start_output",
"(",
")",
"if",
"self",
".",
"has_part",
"(",
"\"intro\"",
")",
":",
"self",
".",
"write_intro",
"(",
")",
"self",
".",
"writeln",
"(",
")... | Write start of checking info as sql comment. | [
"Write",
"start",
"of",
"checking",
"info",
"as",
"sql",
"comment",
"."
] | python | train | 28.555556 |
pytorch/ignite | ignite/contrib/handlers/param_scheduler.py | https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L501-L565 | def create_lr_scheduler_with_warmup(lr_scheduler, warmup_start_value, warmup_end_value, warmup_duration,
save_history=False,
output_simulated_values=None):
"""
Helper method to create a LR scheduler with a linear warm-up.
Args:
... | [
"def",
"create_lr_scheduler_with_warmup",
"(",
"lr_scheduler",
",",
"warmup_start_value",
",",
"warmup_end_value",
",",
"warmup_duration",
",",
"save_history",
"=",
"False",
",",
"output_simulated_values",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"lr_sch... | Helper method to create a LR scheduler with a linear warm-up.
Args:
lr_scheduler (ParamScheduler or subclass of `torch.optim.lr_scheduler._LRScheduler`): LR scheduler after
the warm-up.
warmup_start_value (float): LR start value of the warm-up phase.
warmup_end_value (float): LR... | [
"Helper",
"method",
"to",
"create",
"a",
"LR",
"scheduler",
"with",
"a",
"linear",
"warm",
"-",
"up",
"."
] | python | train | 51.184615 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/geom_encoder.py | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/geom_encoder.py#L39-L48 | def coords_on_grid(self, x, y):
""" Snap coordinates on the grid with integer coordinates """
if isinstance(x, float):
x = int(self._round(x))
if isinstance(y, float):
y = int(self._round(y))
if not self._y_coord_down:
y = self._extents - y
re... | [
"def",
"coords_on_grid",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"float",
")",
":",
"x",
"=",
"int",
"(",
"self",
".",
"_round",
"(",
"x",
")",
")",
"if",
"isinstance",
"(",
"y",
",",
"float",
")",
":",
"... | Snap coordinates on the grid with integer coordinates | [
"Snap",
"coordinates",
"on",
"the",
"grid",
"with",
"integer",
"coordinates"
] | python | train | 32 |
pyca/pynacl | src/nacl/public.py | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/public.py#L99-L125 | def from_seed(cls, seed, encoder=encoding.RawEncoder):
"""
Generate a PrivateKey using a deterministic construction
starting from a caller-provided seed
.. warning:: The seed **must** be high-entropy; therefore,
its generator **must** be a cryptographic quality
r... | [
"def",
"from_seed",
"(",
"cls",
",",
"seed",
",",
"encoder",
"=",
"encoding",
".",
"RawEncoder",
")",
":",
"# decode the seed",
"seed",
"=",
"encoder",
".",
"decode",
"(",
"seed",
")",
"# Verify the given seed type and size are correct",
"if",
"not",
"(",
"isins... | Generate a PrivateKey using a deterministic construction
starting from a caller-provided seed
.. warning:: The seed **must** be high-entropy; therefore,
its generator **must** be a cryptographic quality
random function like, for example, :func:`~nacl.utils.random`.
.. w... | [
"Generate",
"a",
"PrivateKey",
"using",
"a",
"deterministic",
"construction",
"starting",
"from",
"a",
"caller",
"-",
"provided",
"seed"
] | python | train | 45.962963 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L266-L280 | def split_coords_2d(seq):
"""
:param seq: a flat list with lons and lats
:returns: a validated list of pairs (lon, lat)
>>> split_coords_2d([1.1, 2.1, 2.2, 2.3])
[(1.1, 2.1), (2.2, 2.3)]
"""
lons, lats = [], []
for i, el in enumerate(seq):
if i % 2 == 0:
lons.append(... | [
"def",
"split_coords_2d",
"(",
"seq",
")",
":",
"lons",
",",
"lats",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"i",
",",
"el",
"in",
"enumerate",
"(",
"seq",
")",
":",
"if",
"i",
"%",
"2",
"==",
"0",
":",
"lons",
".",
"append",
"(",
"valid",
".",
... | :param seq: a flat list with lons and lats
:returns: a validated list of pairs (lon, lat)
>>> split_coords_2d([1.1, 2.1, 2.2, 2.3])
[(1.1, 2.1), (2.2, 2.3)] | [
":",
"param",
"seq",
":",
"a",
"flat",
"list",
"with",
"lons",
"and",
"lats",
":",
"returns",
":",
"a",
"validated",
"list",
"of",
"pairs",
"(",
"lon",
"lat",
")"
] | python | train | 28.533333 |
lotabout/pymustache | pymustache/mustache.py | https://github.com/lotabout/pymustache/blob/d4089e49cda01fc11bab0c986d95e25150a60bac/pymustache/mustache.py#L465-L474 | def _render(self, contexts, partials):
"""render partials"""
try:
partial = partials[self.value]
except KeyError as e:
return self._escape(EMPTYSTRING)
partial = re_insert_indent.sub(r'\1' + ' '*self.indent, partial)
return inner_render(partial, contexts... | [
"def",
"_render",
"(",
"self",
",",
"contexts",
",",
"partials",
")",
":",
"try",
":",
"partial",
"=",
"partials",
"[",
"self",
".",
"value",
"]",
"except",
"KeyError",
"as",
"e",
":",
"return",
"self",
".",
"_escape",
"(",
"EMPTYSTRING",
")",
"partial... | render partials | [
"render",
"partials"
] | python | train | 33.8 |
greenbone/ospd | ospd/misc.py | https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L772-L846 | def create_args_parser(description):
""" Create a command-line arguments parser for OSPD. """
parser = argparse.ArgumentParser(description=description)
def network_port(string):
""" Check if provided string is a valid network port. """
value = int(string)
if not 0 < value <= 65535... | [
"def",
"create_args_parser",
"(",
"description",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
")",
"def",
"network_port",
"(",
"string",
")",
":",
"\"\"\" Check if provided string is a valid network port. \"\"\"",
"... | Create a command-line arguments parser for OSPD. | [
"Create",
"a",
"command",
"-",
"line",
"arguments",
"parser",
"for",
"OSPD",
"."
] | python | train | 44.586667 |
networks-lab/metaknowledge | metaknowledge/graphHelpers.py | https://github.com/networks-lab/metaknowledge/blob/8162bf95e66bb6f9916081338e6e2a6132faff75/metaknowledge/graphHelpers.py#L497-L561 | def dropEdges(grph, minWeight = - float('inf'), maxWeight = float('inf'), parameterName = 'weight', ignoreUnweighted = False, dropSelfLoops = False):
"""Modifies _grph_ by dropping edges whose weight is not within the inclusive bounds of _minWeight_ and _maxWeight_, i.e after running _grph_ will only have edges who... | [
"def",
"dropEdges",
"(",
"grph",
",",
"minWeight",
"=",
"-",
"float",
"(",
"'inf'",
")",
",",
"maxWeight",
"=",
"float",
"(",
"'inf'",
")",
",",
"parameterName",
"=",
"'weight'",
",",
"ignoreUnweighted",
"=",
"False",
",",
"dropSelfLoops",
"=",
"False",
... | Modifies _grph_ by dropping edges whose weight is not within the inclusive bounds of _minWeight_ and _maxWeight_, i.e after running _grph_ will only have edges whose weights meet the following inequality: _minWeight_ <= edge's weight <= _maxWeight_. A `Keyerror` will be raised if the graph is unweighted unless _ignoreU... | [
"Modifies",
"_grph_",
"by",
"dropping",
"edges",
"whose",
"weight",
"is",
"not",
"within",
"the",
"inclusive",
"bounds",
"of",
"_minWeight_",
"and",
"_maxWeight_",
"i",
".",
"e",
"after",
"running",
"_grph_",
"will",
"only",
"have",
"edges",
"whose",
"weights"... | python | train | 46.215385 |
sailthru/sailthru-python-client | sailthru/sailthru_client.py | https://github.com/sailthru/sailthru-python-client/blob/22aa39ba0c5bddd7b8743e24ada331128c0f4f54/sailthru/sailthru_client.py#L374-L382 | def import_contacts(self, email, password, include_name=False):
"""
Fetch email contacts from a user's address book on one of the major email websites. Currently supports AOL, Gmail, Hotmail, and Yahoo! Mail.
"""
data = {'email': email,
'password': password}
if in... | [
"def",
"import_contacts",
"(",
"self",
",",
"email",
",",
"password",
",",
"include_name",
"=",
"False",
")",
":",
"data",
"=",
"{",
"'email'",
":",
"email",
",",
"'password'",
":",
"password",
"}",
"if",
"include_name",
":",
"data",
"[",
"'names'",
"]",... | Fetch email contacts from a user's address book on one of the major email websites. Currently supports AOL, Gmail, Hotmail, and Yahoo! Mail. | [
"Fetch",
"email",
"contacts",
"from",
"a",
"user",
"s",
"address",
"book",
"on",
"one",
"of",
"the",
"major",
"email",
"websites",
".",
"Currently",
"supports",
"AOL",
"Gmail",
"Hotmail",
"and",
"Yahoo!",
"Mail",
"."
] | python | train | 44.444444 |
jobovy/galpy | galpy/potential/FerrersPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/FerrersPotential.py#L131-L148 | def _Rforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rforce
PURPOSE:T
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | [
"def",
"_Rforce",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"if",
"not",
"self",
".",
"isNonAxi",
":",
"phi",
"=",
"0.",
"self",
".",
"_compute_xyzforces",
"(",
"R",
",",
"z",
",",
"phi",
",",
"t",... | NAME:
_Rforce
PURPOSE:T
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the radial force | [
"NAME",
":",
"_Rforce",
"PURPOSE",
":",
"T",
"evaluate",
"the",
"radial",
"force",
"for",
"this",
"potential",
"INPUT",
":",
"R",
"-",
"Galactocentric",
"cylindrical",
"radius",
"z",
"-",
"vertical",
"height",
"phi",
"-",
"azimuth",
"t",
"-",
"time",
"OUTP... | python | train | 27.555556 |
portantier/habu | habu/cli/cmd_arp_ping.py | https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_arp_ping.py#L18-L43 | def cmd_arp_ping(ip, iface, verbose):
"""
Send ARP packets to check if a host it's alive in the local network.
Example:
\b
# habu.arp.ping 192.168.0.1
Ether / ARP is at a4:08:f5:19:17:a4 says 192.168.0.1 / Padding
"""
if verbose:
logging.basicConfig(level=logging.INFO, format=... | [
"def",
"cmd_arp_ping",
"(",
"ip",
",",
"iface",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"'%(message)s'",
")",
"conf",
".",
"verb",
"=",
"False",
"if",... | Send ARP packets to check if a host it's alive in the local network.
Example:
\b
# habu.arp.ping 192.168.0.1
Ether / ARP is at a4:08:f5:19:17:a4 says 192.168.0.1 / Padding | [
"Send",
"ARP",
"packets",
"to",
"check",
"if",
"a",
"host",
"it",
"s",
"alive",
"in",
"the",
"local",
"network",
"."
] | python | train | 22.038462 |
sprockets/sprockets.mixins.mediatype | sprockets/mixins/mediatype/content.py | https://github.com/sprockets/sprockets.mixins.mediatype/blob/c034e04f674201487a8d6ce9f8ce36f3f5de07d8/sprockets/mixins/mediatype/content.py#L309-L342 | def get_request_body(self):
"""
Fetch (and cache) the request body as a dictionary.
:raise web.HTTPError:
- if the content type cannot be matched, then the status code
is set to 415 Unsupported Media Type.
- if decoding the content body fails, then the stat... | [
"def",
"get_request_body",
"(",
"self",
")",
":",
"if",
"self",
".",
"_request_body",
"is",
"None",
":",
"settings",
"=",
"get_settings",
"(",
"self",
".",
"application",
",",
"force_instance",
"=",
"True",
")",
"content_type_header",
"=",
"headers",
".",
"p... | Fetch (and cache) the request body as a dictionary.
:raise web.HTTPError:
- if the content type cannot be matched, then the status code
is set to 415 Unsupported Media Type.
- if decoding the content body fails, then the status code is
set to 400 Bad Syntax. | [
"Fetch",
"(",
"and",
"cache",
")",
"the",
"request",
"body",
"as",
"a",
"dictionary",
"."
] | python | train | 44.5 |
GearPlug/payu-python | payu/tokenization.py | https://github.com/GearPlug/payu-python/blob/47ec5c9fc89f1f89a53ec0a68c84f358bbe3394e/payu/tokenization.py#L324-L348 | def remove_token(self, *, payer_id, credit_card_token_id):
"""
This feature allows you to delete a tokenized credit card register.
Args:
payer_id:
credit_card_token_id:
Returns:
"""
payload = {
"language": self.client.language.value,... | [
"def",
"remove_token",
"(",
"self",
",",
"*",
",",
"payer_id",
",",
"credit_card_token_id",
")",
":",
"payload",
"=",
"{",
"\"language\"",
":",
"self",
".",
"client",
".",
"language",
".",
"value",
",",
"\"command\"",
":",
"PaymentCommand",
".",
"REMOVE_TOKE... | This feature allows you to delete a tokenized credit card register.
Args:
payer_id:
credit_card_token_id:
Returns: | [
"This",
"feature",
"allows",
"you",
"to",
"delete",
"a",
"tokenized",
"credit",
"card",
"register",
"."
] | python | train | 29.92 |
danidee10/Staticfy | staticfy/staticfy.py | https://github.com/danidee10/Staticfy/blob/ebc555b00377394b0f714e4a173d37833fec90cb/staticfy/staticfy.py#L179-L193 | def main():
"""Main method."""
args = parse_cmd_arguments()
html_file = args.file
try:
json.loads(args.add_tags or '{}')
json.loads(args.exc_tags or '{}')
except ValueError:
print('\033[91m' + 'Invalid json string: please provide a valid json '
'string e.g {}'.... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_cmd_arguments",
"(",
")",
"html_file",
"=",
"args",
".",
"file",
"try",
":",
"json",
".",
"loads",
"(",
"args",
".",
"add_tags",
"or",
"'{}'",
")",
"json",
".",
"loads",
"(",
"args",
".",
"exc_tags",
... | Main method. | [
"Main",
"method",
"."
] | python | train | 31.533333 |
Calysto/calysto | calysto/ai/conx.py | https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/ai/conx.py#L1475-L1504 | def getData(self, pos):
"""
Returns dictionary with input and target given pos.
"""
retval = {}
if pos >= len(self.inputs):
raise IndexError('getData() pattern beyond range.', pos)
if self.verbosity >= 1: print("Getting input", pos, "...")
if len(self... | [
"def",
"getData",
"(",
"self",
",",
"pos",
")",
":",
"retval",
"=",
"{",
"}",
"if",
"pos",
">=",
"len",
"(",
"self",
".",
"inputs",
")",
":",
"raise",
"IndexError",
"(",
"'getData() pattern beyond range.'",
",",
"pos",
")",
"if",
"self",
".",
"verbosit... | Returns dictionary with input and target given pos. | [
"Returns",
"dictionary",
"with",
"input",
"and",
"target",
"given",
"pos",
"."
] | python | train | 43.533333 |
rohankapoorcom/zm-py | zoneminder/monitor.py | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L121-L140 | def is_recording(self) -> Optional[bool]:
"""Indicate if this Monitor is currently recording."""
status_response = self._client.get_state(
'api/monitors/alarm/id:{}/command:status.json'.format(
self._monitor_id
)
)
if not status_response:
... | [
"def",
"is_recording",
"(",
"self",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"status_response",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"'api/monitors/alarm/id:{}/command:status.json'",
".",
"format",
"(",
"self",
".",
"_monitor_id",
")",
")",
... | Indicate if this Monitor is currently recording. | [
"Indicate",
"if",
"this",
"Monitor",
"is",
"currently",
"recording",
"."
] | python | train | 34.55 |
knipknap/exscript | Exscript/queue.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/queue.py#L613-L632 | def run(self, hosts, function, attempts=1):
"""
Add the given function to a queue, and call it once for each host
according to the threading options.
Use decorators.bind() if you also want to pass additional
arguments to the callback function.
Returns an object that repr... | [
"def",
"run",
"(",
"self",
",",
"hosts",
",",
"function",
",",
"attempts",
"=",
"1",
")",
":",
"return",
"self",
".",
"_run",
"(",
"hosts",
",",
"function",
",",
"self",
".",
"workqueue",
".",
"enqueue",
",",
"attempts",
")"
] | Add the given function to a queue, and call it once for each host
according to the threading options.
Use decorators.bind() if you also want to pass additional
arguments to the callback function.
Returns an object that represents the queued task, and that may be
passed to is_com... | [
"Add",
"the",
"given",
"function",
"to",
"a",
"queue",
"and",
"call",
"it",
"once",
"for",
"each",
"host",
"according",
"to",
"the",
"threading",
"options",
".",
"Use",
"decorators",
".",
"bind",
"()",
"if",
"you",
"also",
"want",
"to",
"pass",
"addition... | python | train | 42.8 |
saltstack/salt | salt/utils/color.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/color.py#L18-L41 | def get_color_theme(theme):
'''
Return the color theme to use
'''
# Keep the heavy lifting out of the module space
import salt.utils.data
import salt.utils.files
import salt.utils.yaml
if not os.path.isfile(theme):
log.warning('The named theme %s if not available', theme)
tr... | [
"def",
"get_color_theme",
"(",
"theme",
")",
":",
"# Keep the heavy lifting out of the module space",
"import",
"salt",
".",
"utils",
".",
"data",
"import",
"salt",
".",
"utils",
".",
"files",
"import",
"salt",
".",
"utils",
".",
"yaml",
"if",
"not",
"os",
"."... | Return the color theme to use | [
"Return",
"the",
"color",
"theme",
"to",
"use"
] | python | train | 34.041667 |
greedo/python-xbrl | xbrl/xbrl.py | https://github.com/greedo/python-xbrl/blob/e6baa4de61333f7fcead758a1072c21943563b49/xbrl/xbrl.py#L585-L633 | def parseDEI(self,
xbrl,
ignore_errors=0):
"""
Parse DEI from our XBRL soup and return a DEI object.
"""
dei_obj = DEI()
if ignore_errors == 2:
logging.basicConfig(filename='/tmp/xbrl.log',
level=logging.ERROR,
... | [
"def",
"parseDEI",
"(",
"self",
",",
"xbrl",
",",
"ignore_errors",
"=",
"0",
")",
":",
"dei_obj",
"=",
"DEI",
"(",
")",
"if",
"ignore_errors",
"==",
"2",
":",
"logging",
".",
"basicConfig",
"(",
"filename",
"=",
"'/tmp/xbrl.log'",
",",
"level",
"=",
"l... | Parse DEI from our XBRL soup and return a DEI object. | [
"Parse",
"DEI",
"from",
"our",
"XBRL",
"soup",
"and",
"return",
"a",
"DEI",
"object",
"."
] | python | train | 41.77551 |
fakedrake/overlay_parse | overlay_parse/overlays.py | https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/overlays.py#L41-L49 | def copy(self, props=None, value=None):
"""
Copy the Overlay possibly overriding props.
"""
return Overlay(self.text,
(self.start, self.end),
props=props or self.props,
value=value or self.value) | [
"def",
"copy",
"(",
"self",
",",
"props",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"return",
"Overlay",
"(",
"self",
".",
"text",
",",
"(",
"self",
".",
"start",
",",
"self",
".",
"end",
")",
",",
"props",
"=",
"props",
"or",
"self",
"... | Copy the Overlay possibly overriding props. | [
"Copy",
"the",
"Overlay",
"possibly",
"overriding",
"props",
"."
] | python | train | 32.111111 |
spyder-ide/spyder | spyder/plugins/ipythonconsole/widgets/client.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/client.py#L558-L575 | def kernel_restarted_message(self, msg):
"""Show kernel restarted/died messages."""
if not self.is_error_shown:
# If there are kernel creation errors, jupyter_client will
# try to restart the kernel and qtconsole prints a
# message about it.
# So we ... | [
"def",
"kernel_restarted_message",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"self",
".",
"is_error_shown",
":",
"# If there are kernel creation errors, jupyter_client will\r",
"# try to restart the kernel and qtconsole prints a\r",
"# message about it.\r",
"# So we read the ... | Show kernel restarted/died messages. | [
"Show",
"kernel",
"restarted",
"/",
"died",
"messages",
"."
] | python | train | 45 |
glormph/msstitch | src/app/actions/pycolator/splitmerge.py | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/pycolator/splitmerge.py#L57-L69 | def protein_header_split_generator(elements, headers, ns):
"""Loop through proteins of each PSM/peptide. If a protein does not
match any of headers, discard PSM/peptide immediately"""
for el in elements:
header_not_matching = False
for protein in el.findall('{%s}protein_id' % ns['xmlns']):
... | [
"def",
"protein_header_split_generator",
"(",
"elements",
",",
"headers",
",",
"ns",
")",
":",
"for",
"el",
"in",
"elements",
":",
"header_not_matching",
"=",
"False",
"for",
"protein",
"in",
"el",
".",
"findall",
"(",
"'{%s}protein_id'",
"%",
"ns",
"[",
"'x... | Loop through proteins of each PSM/peptide. If a protein does not
match any of headers, discard PSM/peptide immediately | [
"Loop",
"through",
"proteins",
"of",
"each",
"PSM",
"/",
"peptide",
".",
"If",
"a",
"protein",
"does",
"not",
"match",
"any",
"of",
"headers",
"discard",
"PSM",
"/",
"peptide",
"immediately"
] | python | train | 44.461538 |
atztogo/phono3py | phono3py/phonon3/fc3.py | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/fc3.py#L290-L347 | def get_constrained_fc2(supercell,
dataset_second_atoms,
atom1,
reduced_site_sym,
symprec):
"""
dataset_second_atoms: [{'number': 7,
'displacement': [],
'delta_... | [
"def",
"get_constrained_fc2",
"(",
"supercell",
",",
"dataset_second_atoms",
",",
"atom1",
",",
"reduced_site_sym",
",",
"symprec",
")",
":",
"lattice",
"=",
"supercell",
".",
"get_cell",
"(",
")",
".",
"T",
"positions",
"=",
"supercell",
".",
"get_scaled_positi... | dataset_second_atoms: [{'number': 7,
'displacement': [],
'delta_forces': []}, ...] | [
"dataset_second_atoms",
":",
"[",
"{",
"number",
":",
"7",
"displacement",
":",
"[]",
"delta_forces",
":",
"[]",
"}",
"...",
"]"
] | python | train | 37.396552 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_sec_services.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_sec_services.py#L186-L199 | def ssh_sa_ssh_server_ssh_vrf_cont_use_vrf_use_vrf_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services")
ssh = ET.SubElement(ssh_sa, "ssh")
server = ET.Sub... | [
"def",
"ssh_sa_ssh_server_ssh_vrf_cont_use_vrf_use_vrf_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ssh_sa",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ssh-sa\"",
",",
"xmlns",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 46.785714 |
EpistasisLab/tpot | tpot/builtins/one_hot_encoder.py | https://github.com/EpistasisLab/tpot/blob/b626271e6b5896a73fb9d7d29bebc7aa9100772e/tpot/builtins/one_hot_encoder.py#L239-L267 | def _matrix_adjust(self, X):
"""Adjust all values in X to encode for NaNs and infinities in the data.
Parameters
----------
X : array-like, shape=(n_samples, n_feature)
Input array of type int.
Returns
-------
X : array-like, shape=(n_samples, n_feat... | [
"def",
"_matrix_adjust",
"(",
"self",
",",
"X",
")",
":",
"data_matrix",
"=",
"X",
".",
"data",
"if",
"sparse",
".",
"issparse",
"(",
"X",
")",
"else",
"X",
"# Shift all values to specially encode for NAN/infinity/OTHER and 0",
"# Old value New Value",
"# --... | Adjust all values in X to encode for NaNs and infinities in the data.
Parameters
----------
X : array-like, shape=(n_samples, n_feature)
Input array of type int.
Returns
-------
X : array-like, shape=(n_samples, n_feature)
Input array without any... | [
"Adjust",
"all",
"values",
"in",
"X",
"to",
"encode",
"for",
"NaNs",
"and",
"infinities",
"in",
"the",
"data",
"."
] | python | train | 32.551724 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/common.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/common.py#L149-L162 | def inverse(self):
"""
Return the inverse of the graph.
@rtype: graph
@return: Complement graph for the graph.
"""
inv = self.__class__()
inv.add_nodes(self.nodes())
inv.complete()
for each in self.edges():
if (inv.has_edge(ea... | [
"def",
"inverse",
"(",
"self",
")",
":",
"inv",
"=",
"self",
".",
"__class__",
"(",
")",
"inv",
".",
"add_nodes",
"(",
"self",
".",
"nodes",
"(",
")",
")",
"inv",
".",
"complete",
"(",
")",
"for",
"each",
"in",
"self",
".",
"edges",
"(",
")",
"... | Return the inverse of the graph.
@rtype: graph
@return: Complement graph for the graph. | [
"Return",
"the",
"inverse",
"of",
"the",
"graph",
"."
] | python | train | 26.142857 |
davidmogar/cucco | cucco/cucco.py | https://github.com/davidmogar/cucco/blob/e2a0ff3342e4a9f25a65c486206a5a2ae1a4dbd4/cucco/cucco.py#L202-L226 | def replace_characters(self, text, characters, replacement=''):
"""Remove characters from text.
Removes custom characters from input text or replaces them
with a string if specified.
Args:
text: The text to be processed.
characters: Characters that will be repla... | [
"def",
"replace_characters",
"(",
"self",
",",
"text",
",",
"characters",
",",
"replacement",
"=",
"''",
")",
":",
"if",
"not",
"characters",
":",
"return",
"text",
"characters",
"=",
"''",
".",
"join",
"(",
"sorted",
"(",
"characters",
")",
")",
"if",
... | Remove characters from text.
Removes custom characters from input text or replaces them
with a string if specified.
Args:
text: The text to be processed.
characters: Characters that will be replaced.
replacement: New text that will replace the custom charact... | [
"Remove",
"characters",
"from",
"text",
"."
] | python | train | 35.52 |
google/tangent | tangent/utils.py | https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/utils.py#L659-L675 | def pop(stack, op_id):
"""Pop a value from the stack (i.e. read it from the tape).
Args:
stack: The stack to pop from.
op_id: A unique variable that is also passed into the matching push.
Allows optimization passes to track pairs of pushes and pops.
Returns:
The last value.
"""
if __debu... | [
"def",
"pop",
"(",
"stack",
",",
"op_id",
")",
":",
"if",
"__debug__",
":",
"pushed_value",
",",
"pushed_op_id",
"=",
"stack",
".",
"pop",
"(",
")",
"assert",
"pushed_op_id",
"==",
"op_id",
",",
"'Wanted %s, got %s'",
"%",
"(",
"op_id",
",",
"pushed_op_id"... | Pop a value from the stack (i.e. read it from the tape).
Args:
stack: The stack to pop from.
op_id: A unique variable that is also passed into the matching push.
Allows optimization passes to track pairs of pushes and pops.
Returns:
The last value. | [
"Pop",
"a",
"value",
"from",
"the",
"stack",
"(",
"i",
".",
"e",
".",
"read",
"it",
"from",
"the",
"tape",
")",
"."
] | python | train | 28.941176 |
jhuapl-boss/intern | intern/remote/boss/remote.py | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L352-L366 | def list_group_maintainers(self, name):
"""
Get the maintainers of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of maintainer names.
Raises:
requests.HTTPError on failure.
"""
self.proje... | [
"def",
"list_group_maintainers",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"return",
"self",
".",
"project_service",
".",
"list_group_maintainers",
"(",
"name",
")"
] | Get the maintainers of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of maintainer names.
Raises:
requests.HTTPError on failure. | [
"Get",
"the",
"maintainers",
"of",
"a",
"group",
"."
] | python | train | 27.4 |
ddorn/GUI | GUI/buttons.py | https://github.com/ddorn/GUI/blob/e1fcb5286d24e0995f280d5180222e51895c368c/GUI/buttons.py#L42-L60 | def click(self, force_no_call=False, milis=None):
"""
Call when the button is pressed. This start the callback function in a thread
If :milis is given, will release the button after :milis miliseconds
"""
if self.clicked:
return False
if not force_no_call an... | [
"def",
"click",
"(",
"self",
",",
"force_no_call",
"=",
"False",
",",
"milis",
"=",
"None",
")",
":",
"if",
"self",
".",
"clicked",
":",
"return",
"False",
"if",
"not",
"force_no_call",
"and",
"self",
".",
"flags",
"&",
"self",
".",
"CALL_ON_PRESS",
":... | Call when the button is pressed. This start the callback function in a thread
If :milis is given, will release the button after :milis miliseconds | [
"Call",
"when",
"the",
"button",
"is",
"pressed",
".",
"This",
"start",
"the",
"callback",
"function",
"in",
"a",
"thread",
"If",
":",
"milis",
"is",
"given",
"will",
"release",
"the",
"button",
"after",
":",
"milis",
"miliseconds"
] | python | train | 31.526316 |
ClericPy/torequests | torequests/utils.py | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1460-L1499 | def find_one(cls, pattern, string, flags=0):
"""JS-like match object. Use index number to get groups, if not match or no group, will return ''.
Basic Usage::
>>> from torequests.utils import find_one
>>> string = "abcd"
>>> find_one("a.*", string)
<toreq... | [
"def",
"find_one",
"(",
"cls",
",",
"pattern",
",",
"string",
",",
"flags",
"=",
"0",
")",
":",
"item",
"=",
"re",
".",
"search",
"(",
"pattern",
",",
"string",
",",
"flags",
"=",
"flags",
")",
"return",
"cls",
"(",
"item",
")"
] | JS-like match object. Use index number to get groups, if not match or no group, will return ''.
Basic Usage::
>>> from torequests.utils import find_one
>>> string = "abcd"
>>> find_one("a.*", string)
<torequests.utils.RegMatch object at 0x0705F1D0>
>... | [
"JS",
"-",
"like",
"match",
"object",
".",
"Use",
"index",
"number",
"to",
"get",
"groups",
"if",
"not",
"match",
"or",
"no",
"group",
"will",
"return",
"."
] | python | train | 31.4 |
pycontribs/pyrax | pyrax/cloudloadbalancers.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudloadbalancers.py#L76-L85 | def get_usage(self, start=None, end=None):
"""
Return the usage records for this load balancer. You may optionally
include a start datetime or an end datetime, or both, which will limit
the records to those on or after the start time, and those before or on
the end time. These ti... | [
"def",
"get_usage",
"(",
"self",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"return",
"self",
".",
"manager",
".",
"get_usage",
"(",
"self",
",",
"start",
"=",
"start",
",",
"end",
"=",
"end",
")"
] | Return the usage records for this load balancer. You may optionally
include a start datetime or an end datetime, or both, which will limit
the records to those on or after the start time, and those before or on
the end time. These times should be Python datetime.datetime objects,
Python ... | [
"Return",
"the",
"usage",
"records",
"for",
"this",
"load",
"balancer",
".",
"You",
"may",
"optionally",
"include",
"a",
"start",
"datetime",
"or",
"an",
"end",
"datetime",
"or",
"both",
"which",
"will",
"limit",
"the",
"records",
"to",
"those",
"on",
"or"... | python | train | 54.7 |
numenta/nupic | src/nupic/datafiles/extra/secondOrder/makeDataset.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/datafiles/extra/secondOrder/makeDataset.py#L133-L257 | def _generateModel1(numCategories):
""" Generate the initial, first order, and second order transition
probabilities for 'model1'. For this model, we generate the following
set of sequences:
0-10-15 (1X)
0-11-16 (1X)
0-12-17 (1X)
0-13-18 (1X)
0-14-19 (1X)
1-10-20 (1X)
1-11-21 (1X)
1-12-22 (1X)... | [
"def",
"_generateModel1",
"(",
"numCategories",
")",
":",
"# --------------------------------------------------------------------",
"# Initial probabilities, 0 and 1 equally likely",
"initProb",
"=",
"numpy",
".",
"zeros",
"(",
"numCategories",
")",
"initProb",
"[",
"0",
"]",
... | Generate the initial, first order, and second order transition
probabilities for 'model1'. For this model, we generate the following
set of sequences:
0-10-15 (1X)
0-11-16 (1X)
0-12-17 (1X)
0-13-18 (1X)
0-14-19 (1X)
1-10-20 (1X)
1-11-21 (1X)
1-12-22 (1X)
1-13-23 (1X)
1-14-24 (1X)
Par... | [
"Generate",
"the",
"initial",
"first",
"order",
"and",
"second",
"order",
"transition",
"probabilities",
"for",
"model1",
".",
"For",
"this",
"model",
"we",
"generate",
"the",
"following",
"set",
"of",
"sequences",
":",
"0",
"-",
"10",
"-",
"15",
"(",
"1X"... | python | valid | 32.184 |
ontio/ontology-python-sdk | ontology/io/binary_reader.py | https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L71-L82 | def read_bytes(self, length) -> bytes:
"""
Read the specified number of bytes from the stream.
Args:
length (int): number of bytes to read.
Returns:
bytes: `length` number of bytes.
"""
value = self.stream.read(length)
return value | [
"def",
"read_bytes",
"(",
"self",
",",
"length",
")",
"->",
"bytes",
":",
"value",
"=",
"self",
".",
"stream",
".",
"read",
"(",
"length",
")",
"return",
"value"
] | Read the specified number of bytes from the stream.
Args:
length (int): number of bytes to read.
Returns:
bytes: `length` number of bytes. | [
"Read",
"the",
"specified",
"number",
"of",
"bytes",
"from",
"the",
"stream",
"."
] | python | train | 25.166667 |
chrisspen/dtree | dtree.py | https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L223-L230 | def best(self):
"""
Returns the element with the highest probability.
"""
b = (-1e999999, None)
for k, c in iteritems(self.counts):
b = max(b, (c, k))
return b[1] | [
"def",
"best",
"(",
"self",
")",
":",
"b",
"=",
"(",
"-",
"1e999999",
",",
"None",
")",
"for",
"k",
",",
"c",
"in",
"iteritems",
"(",
"self",
".",
"counts",
")",
":",
"b",
"=",
"max",
"(",
"b",
",",
"(",
"c",
",",
"k",
")",
")",
"return",
... | Returns the element with the highest probability. | [
"Returns",
"the",
"element",
"with",
"the",
"highest",
"probability",
"."
] | python | train | 26.875 |
oceanprotocol/squid-py | squid_py/ddo/ddo.py | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L118-L129 | def as_text(self, is_proof=True, is_pretty=False):
"""Return the DDO as a JSON text.
:param if is_proof: if False then do not include the 'proof' element.
:param is_pretty: If True return dictionary in a prettier way, bool
:return: str
"""
data = self.as_dictionary(is_pr... | [
"def",
"as_text",
"(",
"self",
",",
"is_proof",
"=",
"True",
",",
"is_pretty",
"=",
"False",
")",
":",
"data",
"=",
"self",
".",
"as_dictionary",
"(",
"is_proof",
")",
"if",
"is_pretty",
":",
"return",
"json",
".",
"dumps",
"(",
"data",
",",
"indent",
... | Return the DDO as a JSON text.
:param if is_proof: if False then do not include the 'proof' element.
:param is_pretty: If True return dictionary in a prettier way, bool
:return: str | [
"Return",
"the",
"DDO",
"as",
"a",
"JSON",
"text",
"."
] | python | train | 36.5 |
ElementAI/greensim | greensim/__init__.py | https://github.com/ElementAI/greensim/blob/f160e8b57d69f6ef469f2e991cc07b7721e08a91/greensim/__init__.py#L280-L287 | def add(self, fn_process: Callable, *args: Any, **kwargs: Any) -> 'Process':
"""
Adds a process to the simulation. The process is embodied by a function, which will be called with the given
positional and keyword parameters when the simulation runs. As a process, this function runs on a special ... | [
"def",
"add",
"(",
"self",
",",
"fn_process",
":",
"Callable",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"'Process'",
":",
"return",
"self",
".",
"add_in",
"(",
"0.0",
",",
"fn_process",
",",
"*",
"args",
",",
... | Adds a process to the simulation. The process is embodied by a function, which will be called with the given
positional and keyword parameters when the simulation runs. As a process, this function runs on a special green
thread, and thus will be able to call functions `now()`, `advance()`, `pause()` and... | [
"Adds",
"a",
"process",
"to",
"the",
"simulation",
".",
"The",
"process",
"is",
"embodied",
"by",
"a",
"function",
"which",
"will",
"be",
"called",
"with",
"the",
"given",
"positional",
"and",
"keyword",
"parameters",
"when",
"the",
"simulation",
"runs",
"."... | python | train | 73.75 |
dhylands/rshell | rshell/main.py | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1224-L1237 | def print_long(filename, stat, print_func):
"""Prints detailed information about the file passed in."""
size = stat_size(stat)
mtime = stat_mtime(stat)
file_mtime = time.localtime(mtime)
curr_time = time.time()
if mtime > (curr_time + SIX_MONTHS) or mtime < (curr_time - SIX_MONTHS):
prin... | [
"def",
"print_long",
"(",
"filename",
",",
"stat",
",",
"print_func",
")",
":",
"size",
"=",
"stat_size",
"(",
"stat",
")",
"mtime",
"=",
"stat_mtime",
"(",
"stat",
")",
"file_mtime",
"=",
"time",
".",
"localtime",
"(",
"mtime",
")",
"curr_time",
"=",
... | Prints detailed information about the file passed in. | [
"Prints",
"detailed",
"information",
"about",
"the",
"file",
"passed",
"in",
"."
] | python | train | 56.071429 |
thespacedoctor/transientNamer | transientNamer/search.py | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L489-L546 | def table(
self,
dirPath=None):
"""*Render the results as an ascii table*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `tableSources` -- the top-level transient data
... | [
"def",
"table",
"(",
"self",
",",
"dirPath",
"=",
"None",
")",
":",
"if",
"dirPath",
":",
"p",
"=",
"self",
".",
"_file_prefix",
"(",
")",
"tableSources",
"=",
"self",
".",
"sourceResults",
".",
"table",
"(",
"filepath",
"=",
"dirPath",
"+",
"\"/\"",
... | *Render the results as an ascii table*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `tableSources` -- the top-level transient data
- `tablePhot` -- all photometry associated with the tran... | [
"*",
"Render",
"the",
"results",
"as",
"an",
"ascii",
"table",
"*"
] | python | train | 66.482759 |
mwickert/scikit-dsp-comm | sk_dsp_comm/pyaudio_helper.py | https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/pyaudio_helper.py#L353-L373 | def get_LR(self,in_data):
"""
Splits incoming packed stereo data into separate left and right channels
and returns an array of left samples and an array of right samples
Parameters
----------
in_data : input data from the streaming object in the callback f... | [
"def",
"get_LR",
"(",
"self",
",",
"in_data",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"frame_length",
"*",
"2",
")",
":",
"if",
"i",
"%",
"2",
":",
"self",
".",
"right_in",
"[",
"(",
"int",
")",
"(",
"i",
"/",
"2",
... | Splits incoming packed stereo data into separate left and right channels
and returns an array of left samples and an array of right samples
Parameters
----------
in_data : input data from the streaming object in the callback function.
Returns
--... | [
"Splits",
"incoming",
"packed",
"stereo",
"data",
"into",
"separate",
"left",
"and",
"right",
"channels",
"and",
"returns",
"an",
"array",
"of",
"left",
"samples",
"and",
"an",
"array",
"of",
"right",
"samples",
"Parameters",
"----------",
"in_data",
":",
"inp... | python | valid | 35.190476 |
chaoss/grimoirelab-sigils | src/migration/to_kibana5.py | https://github.com/chaoss/grimoirelab-sigils/blob/33d395195acb316287143a535a2c6e4009bf0528/src/migration/to_kibana5.py#L107-L119 | def configure_logging(debug=False):
"""Configure logging
The function configures log messages. By default, log messages
are sent to stderr. Set the parameter `debug` to activate the
debug mode.
:param debug: set the debug mode
"""
if not debug:
logging.basicConfig(level=logging.INFO,... | [
"def",
"configure_logging",
"(",
"debug",
"=",
"False",
")",
":",
"if",
"not",
"debug",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"LOG_FORMAT",
")",
"else",
":",
"logging",
".",
"basicConfig",
"(",... | Configure logging
The function configures log messages. By default, log messages
are sent to stderr. Set the parameter `debug` to activate the
debug mode.
:param debug: set the debug mode | [
"Configure",
"logging",
"The",
"function",
"configures",
"log",
"messages",
".",
"By",
"default",
"log",
"messages",
"are",
"sent",
"to",
"stderr",
".",
"Set",
"the",
"parameter",
"debug",
"to",
"activate",
"the",
"debug",
"mode",
".",
":",
"param",
"debug",... | python | train | 35.923077 |
m32/endesive | endesive/pdf/fpdf/fpdf.py | https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L644-L658 | def text(self, x, y, txt=''):
"Output a string"
txt = self.normalize_text(txt)
if (self.unifontsubset):
txt2 = self._escape(UTF8ToUTF16BE(txt, False))
for uni in UTF8StringToArray(txt):
self.current_font['subset'].append(uni)
else:
txt2... | [
"def",
"text",
"(",
"self",
",",
"x",
",",
"y",
",",
"txt",
"=",
"''",
")",
":",
"txt",
"=",
"self",
".",
"normalize_text",
"(",
"txt",
")",
"if",
"(",
"self",
".",
"unifontsubset",
")",
":",
"txt2",
"=",
"self",
".",
"_escape",
"(",
"UTF8ToUTF16... | Output a string | [
"Output",
"a",
"string"
] | python | train | 39.266667 |
ArchiveTeam/wpull | wpull/url.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L239-L254 | def parse_host(cls, host):
'''Parse the host and return hostname and port.'''
if host.endswith(']'):
return cls.parse_hostname(host), None
else:
hostname, sep, port = host.rpartition(':')
if sep:
port = int(port)
if port < 0 or port > 6553... | [
"def",
"parse_host",
"(",
"cls",
",",
"host",
")",
":",
"if",
"host",
".",
"endswith",
"(",
"']'",
")",
":",
"return",
"cls",
".",
"parse_hostname",
"(",
"host",
")",
",",
"None",
"else",
":",
"hostname",
",",
"sep",
",",
"port",
"=",
"host",
".",
... | Parse the host and return hostname and port. | [
"Parse",
"the",
"host",
"and",
"return",
"hostname",
"and",
"port",
"."
] | python | train | 30 |
saltstack/salt | salt/modules/postgres.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/postgres.py#L1514-L1539 | def is_installed_extension(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Test if a specific extension is... | [
"def",
"is_installed_extension",
"(",
"name",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"installed_ext",
"=",
"ge... | Test if a specific extension is installed
CLI Example:
.. code-block:: bash
salt '*' postgres.is_installed_extension | [
"Test",
"if",
"a",
"specific",
"extension",
"is",
"installed"
] | python | train | 24.692308 |
zeth/inputs | inputs.py | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L115-L120 | def convert_timeval(seconds_since_epoch):
"""Convert time into C style timeval."""
frac, whole = math.modf(seconds_since_epoch)
microseconds = math.floor(frac * 1000000)
seconds = math.floor(whole)
return seconds, microseconds | [
"def",
"convert_timeval",
"(",
"seconds_since_epoch",
")",
":",
"frac",
",",
"whole",
"=",
"math",
".",
"modf",
"(",
"seconds_since_epoch",
")",
"microseconds",
"=",
"math",
".",
"floor",
"(",
"frac",
"*",
"1000000",
")",
"seconds",
"=",
"math",
".",
"floo... | Convert time into C style timeval. | [
"Convert",
"time",
"into",
"C",
"style",
"timeval",
"."
] | python | train | 40.166667 |
mar10/pyftpsync | ftpsync/pyftpsync.py | https://github.com/mar10/pyftpsync/blob/bbdc94186975cdc1cc4f678474bdce08bce7bb76/ftpsync/pyftpsync.py#L45-L271 | def run():
"""CLI main entry point."""
# Use print() instead of logging when running in CLI mode:
set_pyftpsync_logger(None)
parser = argparse.ArgumentParser(
description="Synchronize folders over FTP.",
epilog="See also https://github.com/mar10/pyftpsync",
parents=[ve... | [
"def",
"run",
"(",
")",
":",
"# Use print() instead of logging when running in CLI mode:\r",
"set_pyftpsync_logger",
"(",
"None",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Synchronize folders over FTP.\"",
",",
"epilog",
"=",
"\"Se... | CLI main entry point. | [
"CLI",
"main",
"entry",
"point",
"."
] | python | train | 31.898678 |
christophercrouzet/nani | nani.py | https://github.com/christophercrouzet/nani/blob/296ae50c0cdcfd3ed0cba23a4d2edea0d124bcb1/nani.py#L1093-L1098 | def _format_type(cls):
"""Format a type name for printing."""
if cls.__module__ == _BUILTIN_MODULE:
return cls.__name__
else:
return '%s.%s' % (cls.__module__, cls.__name__) | [
"def",
"_format_type",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__module__",
"==",
"_BUILTIN_MODULE",
":",
"return",
"cls",
".",
"__name__",
"else",
":",
"return",
"'%s.%s'",
"%",
"(",
"cls",
".",
"__module__",
",",
"cls",
".",
"__name__",
")"
] | Format a type name for printing. | [
"Format",
"a",
"type",
"name",
"for",
"printing",
"."
] | python | train | 32.666667 |
totalgood/pugnlp | src/pugnlp/tutil.py | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L299-L316 | def datetime_from_ordinal_float(days):
"""Inverse of `ordinal_float()`, converts a float number of days back to a `datetime` object
>>> dt = datetime.datetime(1970, 1, 1)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
True
>>> dt = datetime.datetime(1, 2, 3, 4, 5, 6, 7)
>>> datetime_f... | [
"def",
"datetime_from_ordinal_float",
"(",
"days",
")",
":",
"if",
"isinstance",
"(",
"days",
",",
"(",
"float",
",",
"int",
")",
")",
":",
"if",
"np",
".",
"isnan",
"(",
"days",
")",
"or",
"days",
"in",
"set",
"(",
"(",
"float",
"(",
"'nan'",
")",... | Inverse of `ordinal_float()`, converts a float number of days back to a `datetime` object
>>> dt = datetime.datetime(1970, 1, 1)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
True
>>> dt = datetime.datetime(1, 2, 3, 4, 5, 6, 7)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
... | [
"Inverse",
"of",
"ordinal_float",
"()",
"converts",
"a",
"float",
"number",
"of",
"days",
"back",
"to",
"a",
"datetime",
"object"
] | python | train | 46.722222 |
conchoecia/gloTK | gloTK/wrappers_biolite.py | https://github.com/conchoecia/gloTK/blob/58abee663fcfbbd09f4863c3ca3ae054e33184a8/gloTK/wrappers_biolite.py#L132-L171 | def version(self, flag=None, cmd=None, path=None):
"""
Generates and logs a hash to distinguish this particular installation
of the program (on a certain host, with a certain compiler, program
version, etc.)
Specify the optional 'binary' argument if the wrapper name is not
actually the program, e.g. if you... | [
"def",
"version",
"(",
"self",
",",
"flag",
"=",
"None",
",",
"cmd",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"# Setup the command to run.",
"if",
"not",
"cmd",
":",
"cmd",
"=",
"list",
"(",
"self",
".",
"cmd",
")",
"if",
"flag",
":",
"cmd"... | Generates and logs a hash to distinguish this particular installation
of the program (on a certain host, with a certain compiler, program
version, etc.)
Specify the optional 'binary' argument if the wrapper name is not
actually the program, e.g. if your program has a Perl wrapper script.
Set 'binary' to the ... | [
"Generates",
"and",
"logs",
"a",
"hash",
"to",
"distinguish",
"this",
"particular",
"installation",
"of",
"the",
"program",
"(",
"on",
"a",
"certain",
"host",
"with",
"a",
"certain",
"compiler",
"program",
"version",
"etc",
".",
")"
] | python | train | 30.375 |
GeoPyTool/GeoPyTool | geopytool/K2OSiO2.py | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/K2OSiO2.py#L122-L471 | def K2OSiO2(self, Left=35, Right=79, X0=30, X1=90, X_Gap=7, Base=0,
Top=19, Y0=1, Y1=19, Y_Gap=19, FontSize=12, xlabel=r'$SiO_2 wt\%$', ylabel=r'$K_2O wt\%$', width=12,
height=12, dpi=300):
self.setWindowTitle('K2OSiO2 diagram ')
self.axes.clear()
#self.axes.axis('off')
... | [
"def",
"K2OSiO2",
"(",
"self",
",",
"Left",
"=",
"35",
",",
"Right",
"=",
"79",
",",
"X0",
"=",
"30",
",",
"X1",
"=",
"90",
",",
"X_Gap",
"=",
"7",
",",
"Base",
"=",
"0",
",",
"Top",
"=",
"19",
",",
"Y0",
"=",
"1",
",",
"Y1",
"=",
"19",
... | self.axes.set_xticks([30,40,50,60,70,80,90])
self.axes.set_xticklabels([30,40,50,60,70,80,90])
self.axes.set_yticks([0, 5, 10, 15, 20])
self.axes.set_yticklabels([0, 5, 10, 15, 20])
self.axes.set_ylim(bottom=0) | [
"self",
".",
"axes",
".",
"set_xticks",
"(",
"[",
"30",
"40",
"50",
"60",
"70",
"80",
"90",
"]",
")",
"self",
".",
"axes",
".",
"set_xticklabels",
"(",
"[",
"30",
"40",
"50",
"60",
"70",
"80",
"90",
"]",
")"
] | python | train | 36.128571 |
MillionIntegrals/vel | vel/models/rnn/multilayer_rnn_sequence_classification.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/rnn/multilayer_rnn_sequence_classification.py#L97-L122 | def forward(self, sequence):
""" Forward propagate batch of sequences through the network, without accounting for the state """
data = self.input_block(sequence)
for idx in range(len(self.rnn_layers)):
data, _ = self.rnn_layers[idx](data)
if self.rnn_dropout_layers:
... | [
"def",
"forward",
"(",
"self",
",",
"sequence",
")",
":",
"data",
"=",
"self",
".",
"input_block",
"(",
"sequence",
")",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"rnn_layers",
")",
")",
":",
"data",
",",
"_",
"=",
"self",
".",
"... | Forward propagate batch of sequences through the network, without accounting for the state | [
"Forward",
"propagate",
"batch",
"of",
"sequences",
"through",
"the",
"network",
"without",
"accounting",
"for",
"the",
"state"
] | python | train | 36.846154 |
Azure/azure-sdk-for-python | azure-mgmt-mixedreality/azure/mgmt/mixedreality/mixed_reality_client.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-mgmt-mixedreality/azure/mgmt/mixedreality/mixed_reality_client.py#L90-L157 | def check_name_availability_local(
self, location, name, type, custom_headers=None, raw=False, **operation_config):
"""Check Name Availability for global uniqueness.
:param location: The location in which uniqueness will be verified.
:type location: str
:param name: Resource... | [
"def",
"check_name_availability_local",
"(",
"self",
",",
"location",
",",
"name",
",",
"type",
",",
"custom_headers",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"*",
"*",
"operation_config",
")",
":",
"check_name_availability",
"=",
"models",
".",
"CheckName... | Check Name Availability for global uniqueness.
:param location: The location in which uniqueness will be verified.
:type location: str
:param name: Resource Name To Verify
:type name: str
:param type: Fully qualified resource type which includes provider
namespace
... | [
"Check",
"Name",
"Availability",
"for",
"global",
"uniqueness",
"."
] | python | test | 45.970588 |
fp12/achallonge | challonge/tournament.py | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/tournament.py#L654-L674 | async def get_match(self, m_id, force_update=False) -> Match:
""" get a single match by id
|methcoro|
Args:
m_id: match id
force_update (default=False): True to force an update to the Challonge API
Returns:
Match
Raises:
APIExce... | [
"async",
"def",
"get_match",
"(",
"self",
",",
"m_id",
",",
"force_update",
"=",
"False",
")",
"->",
"Match",
":",
"found_m",
"=",
"self",
".",
"_find_match",
"(",
"m_id",
")",
"if",
"force_update",
"or",
"found_m",
"is",
"None",
":",
"await",
"self",
... | get a single match by id
|methcoro|
Args:
m_id: match id
force_update (default=False): True to force an update to the Challonge API
Returns:
Match
Raises:
APIException | [
"get",
"a",
"single",
"match",
"by",
"id"
] | python | train | 24.190476 |
vroomfonde1/basicmodem | basicmodem/basicmodem.py | https://github.com/vroomfonde1/basicmodem/blob/ea5835b0d4a05d167456f78d2ae8c74c1d636aac/basicmodem/basicmodem.py#L144-L216 | def _modem_sm(self):
"""Handle modem response state machine."""
import datetime
read_timeout = READ_IDLE_TIMEOUT
while self.ser:
try:
resp = self.read(read_timeout)
except (serial.SerialException, SystemExit, TypeError):
_LOGGER.de... | [
"def",
"_modem_sm",
"(",
"self",
")",
":",
"import",
"datetime",
"read_timeout",
"=",
"READ_IDLE_TIMEOUT",
"while",
"self",
".",
"ser",
":",
"try",
":",
"resp",
"=",
"self",
".",
"read",
"(",
"read_timeout",
")",
"except",
"(",
"serial",
".",
"SerialExcept... | Handle modem response state machine. | [
"Handle",
"modem",
"response",
"state",
"machine",
"."
] | python | train | 34.547945 |
HewlettPackard/python-hpOneView | hpOneView/resources/resource.py | https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/resource.py#L678-L697 | def do_requests_to_getall(self, uri, requested_count):
"""Helps to make http request for get_all method.
Note:
This method will be checking for the pagination URI in the response
and make request to pagination URI to get all the resources.
"""
items = []
... | [
"def",
"do_requests_to_getall",
"(",
"self",
",",
"uri",
",",
"requested_count",
")",
":",
"items",
"=",
"[",
"]",
"while",
"uri",
":",
"logger",
".",
"debug",
"(",
"'Making HTTP request to get all resources. Uri: {0}'",
".",
"format",
"(",
"uri",
")",
")",
"r... | Helps to make http request for get_all method.
Note:
This method will be checking for the pagination URI in the response
and make request to pagination URI to get all the resources. | [
"Helps",
"to",
"make",
"http",
"request",
"for",
"get_all",
"method",
"."
] | python | train | 41.15 |
saltstack/salt | salt/modules/boto_rds.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L158-L173 | def option_group_exists(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1
'''
conn = _get_conn(region=region, key=ke... | [
"def",
"option_group_exists",
"(",
"name",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
... | Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1 | [
"Check",
"to",
"see",
"if",
"an",
"RDS",
"option",
"group",
"exists",
"."
] | python | train | 33.4375 |
webadmin87/midnight | midnight_main/services.py | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/services.py#L27-L38 | def get_comment_init(request, obj):
"""
Возвращает словарь для инициализации начальных значений модели комментария
:param request: запрос
:param obj: объект к которому добавляется комментарий
:return:
"""
if request.user.is_authenticated():
init = {'obj': obj, 'username': request.use... | [
"def",
"get_comment_init",
"(",
"request",
",",
"obj",
")",
":",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"init",
"=",
"{",
"'obj'",
":",
"obj",
",",
"'username'",
":",
"request",
".",
"user",
".",
"username",
",",
"'email'... | Возвращает словарь для инициализации начальных значений модели комментария
:param request: запрос
:param obj: объект к которому добавляется комментарий
:return: | [
"Возвращает",
"словарь",
"для",
"инициализации",
"начальных",
"значений",
"модели",
"комментария",
":",
"param",
"request",
":",
"запрос",
":",
"param",
"obj",
":",
"объект",
"к",
"которому",
"добавляется",
"комментарий",
":",
"return",
":"
] | python | train | 33.583333 |
tensorpack/tensorpack | examples/FasterRCNN/utils/box_ops.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/utils/box_ops.py#L29-L47 | def pairwise_intersection(boxlist1, boxlist2):
"""Compute pairwise intersection areas between boxes.
Args:
boxlist1: Nx4 floatbox
boxlist2: Mx4
Returns:
a tensor with shape [N, M] representing pairwise intersections
"""
x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=... | [
"def",
"pairwise_intersection",
"(",
"boxlist1",
",",
"boxlist2",
")",
":",
"x_min1",
",",
"y_min1",
",",
"x_max1",
",",
"y_max1",
"=",
"tf",
".",
"split",
"(",
"boxlist1",
",",
"4",
",",
"axis",
"=",
"1",
")",
"x_min2",
",",
"y_min2",
",",
"x_max2",
... | Compute pairwise intersection areas between boxes.
Args:
boxlist1: Nx4 floatbox
boxlist2: Mx4
Returns:
a tensor with shape [N, M] representing pairwise intersections | [
"Compute",
"pairwise",
"intersection",
"areas",
"between",
"boxes",
"."
] | python | train | 44.421053 |
coinbase/coinbase-python | coinbase/wallet/client.py | https://github.com/coinbase/coinbase-python/blob/497c28158f529e8c7d0228521b4386a890baf088/coinbase/wallet/client.py#L430-L433 | def get_buys(self, account_id, **params):
"""https://developers.coinbase.com/api/v2#list-buys"""
response = self._get('v2', 'accounts', account_id, 'buys', params=params)
return self._make_api_object(response, Buy) | [
"def",
"get_buys",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"params",
")",
":",
"response",
"=",
"self",
".",
"_get",
"(",
"'v2'",
",",
"'accounts'",
",",
"account_id",
",",
"'buys'",
",",
"params",
"=",
"params",
")",
"return",
"self",
".",
"_... | https://developers.coinbase.com/api/v2#list-buys | [
"https",
":",
"//",
"developers",
".",
"coinbase",
".",
"com",
"/",
"api",
"/",
"v2#list",
"-",
"buys"
] | python | train | 58.75 |
SmileyChris/django-countries | django_countries/fields.py | https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L391-L413 | def validate(self, value, model_instance):
"""
Use custom validation for when using a multiple countries field.
"""
if not self.multiple:
return super(CountryField, self).validate(value, model_instance)
if not self.editable:
# Skip validation for non-edit... | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"model_instance",
")",
":",
"if",
"not",
"self",
".",
"multiple",
":",
"return",
"super",
"(",
"CountryField",
",",
"self",
")",
".",
"validate",
"(",
"value",
",",
"model_instance",
")",
"if",
"not",
... | Use custom validation for when using a multiple countries field. | [
"Use",
"custom",
"validation",
"for",
"when",
"using",
"a",
"multiple",
"countries",
"field",
"."
] | python | train | 39.347826 |
tjvr/kurt | kurt/scratch14/objtable.py | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/objtable.py#L300-L381 | def encode_network(root):
"""Yield ref-containing obj table entries from object network"""
orig_objects = []
objects = []
def get_ref(value, objects=objects):
"""Returns the index of the given object in the object table,
adding it if needed.
"""
value = PythonicAdapter(... | [
"def",
"encode_network",
"(",
"root",
")",
":",
"orig_objects",
"=",
"[",
"]",
"objects",
"=",
"[",
"]",
"def",
"get_ref",
"(",
"value",
",",
"objects",
"=",
"objects",
")",
":",
"\"\"\"Returns the index of the given object in the object table,\n adding it if n... | Yield ref-containing obj table entries from object network | [
"Yield",
"ref",
"-",
"containing",
"obj",
"table",
"entries",
"from",
"object",
"network"
] | python | train | 30.719512 |
PGower/PyCanvas | pycanvas/apis/courses.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L1145-L1180 | def update_courses(self, event, account_id, course_ids):
"""
Update courses.
Update multiple courses in an account. Operates asynchronously; use the {api:ProgressController#show progress endpoint}
to query the status of an operation.
The action to take on each c... | [
"def",
"update_courses",
"(",
"self",
",",
"event",
",",
"account_id",
",",
"course_ids",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - account_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"account_id\"",
"]... | Update courses.
Update multiple courses in an account. Operates asynchronously; use the {api:ProgressController#show progress endpoint}
to query the status of an operation.
The action to take on each course. Must be one of 'offer', 'conclude', 'delete', or 'undelete'.
... | [
"Update",
"courses",
".",
"Update",
"multiple",
"courses",
"in",
"an",
"account",
".",
"Operates",
"asynchronously",
";",
"use",
"the",
"{",
"api",
":",
"ProgressController#show",
"progress",
"endpoint",
"}",
"to",
"query",
"the",
"status",
"of",
"an",
"operat... | python | train | 55.638889 |
lambdamusic/Ontospy | ontospy/extras/sparqlpy.py | https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/sparqlpy.py#L197-L209 | def __getFormat(self, format):
"""
Defaults to JSON [ps: 'RDF' is the native rdflib representation]
"""
if format == "XML":
self.sparql.setReturnFormat(XML)
self.format = "XML"
elif format == "RDF":
self.sparql.setReturnFormat(RDF)
self.format = "RDF"
else:
self.sparql.setReturnFormat(JSON)
... | [
"def",
"__getFormat",
"(",
"self",
",",
"format",
")",
":",
"if",
"format",
"==",
"\"XML\"",
":",
"self",
".",
"sparql",
".",
"setReturnFormat",
"(",
"XML",
")",
"self",
".",
"format",
"=",
"\"XML\"",
"elif",
"format",
"==",
"\"RDF\"",
":",
"self",
"."... | Defaults to JSON [ps: 'RDF' is the native rdflib representation] | [
"Defaults",
"to",
"JSON",
"[",
"ps",
":",
"RDF",
"is",
"the",
"native",
"rdflib",
"representation",
"]"
] | python | train | 25.461538 |
IdentityPython/pysaml2 | src/saml2/response.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/response.py#L202-L219 | def for_me(conditions, myself):
""" Am I among the intended audiences """
if not conditions.audience_restriction: # No audience restriction
return True
for restriction in conditions.audience_restriction:
if not restriction.audience:
continue
for audience in restriction... | [
"def",
"for_me",
"(",
"conditions",
",",
"myself",
")",
":",
"if",
"not",
"conditions",
".",
"audience_restriction",
":",
"# No audience restriction",
"return",
"True",
"for",
"restriction",
"in",
"conditions",
".",
"audience_restriction",
":",
"if",
"not",
"restr... | Am I among the intended audiences | [
"Am",
"I",
"among",
"the",
"intended",
"audiences"
] | python | train | 30.333333 |
alexandrovteam/cpyMSpec | cpyMSpec/spectrum.py | https://github.com/alexandrovteam/cpyMSpec/blob/99d9ea18036d65d2d76744102e9304c5df67a1e1/cpyMSpec/spectrum.py#L207-L220 | def centroids(self, instrument, min_abundance=1e-4, points_per_fwhm=25):
"""
Estimates centroided peaks for a given instrument model.
:param instrument: instrument model
:param min_abundance: minimum abundance for including a peak
:param points_per_fwhm: grid density used for en... | [
"def",
"centroids",
"(",
"self",
",",
"instrument",
",",
"min_abundance",
"=",
"1e-4",
",",
"points_per_fwhm",
"=",
"25",
")",
":",
"assert",
"self",
".",
"ptr",
"!=",
"ffi",
".",
"NULL",
"centroids",
"=",
"ims",
".",
"spectrum_envelope_centroids",
"(",
"s... | Estimates centroided peaks for a given instrument model.
:param instrument: instrument model
:param min_abundance: minimum abundance for including a peak
:param points_per_fwhm: grid density used for envelope calculation
:returns: peaks visible with the instrument used
:rtype: T... | [
"Estimates",
"centroided",
"peaks",
"for",
"a",
"given",
"instrument",
"model",
"."
] | python | train | 49.142857 |
PGower/PyCanvas | pycanvas/apis/users.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L429-L596 | def create_user(self, account_id, pseudonym_unique_id, communication_channel_address=None, communication_channel_confirmation_url=None, communication_channel_skip_confirmation=None, communication_channel_type=None, enable_sis_reactivation=None, force_validations=None, pseudonym_authentication_provider_id=None, pseudony... | [
"def",
"create_user",
"(",
"self",
",",
"account_id",
",",
"pseudonym_unique_id",
",",
"communication_channel_address",
"=",
"None",
",",
"communication_channel_confirmation_url",
"=",
"None",
",",
"communication_channel_skip_confirmation",
"=",
"None",
",",
"communication_... | Create a user.
Create and return a new user and pseudonym for an account.
If you don't have the "Modify login details for users" permission, but
self-registration is enabled on the account, you can still use this
endpoint to register new users. Certain fields will be requ... | [
"Create",
"a",
"user",
".",
"Create",
"and",
"return",
"a",
"new",
"user",
"and",
"pseudonym",
"for",
"an",
"account",
".",
"If",
"you",
"don",
"t",
"have",
"the",
"Modify",
"login",
"details",
"for",
"users",
"permission",
"but",
"self",
"-",
"registrat... | python | train | 55.386905 |
Azure/blobxfer | blobxfer/operations/upload.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/upload.py#L619-L632 | def _set_blob_properties(self, ud):
# type: (Uploader, blobxfer.models.upload.Descriptor) -> None
"""Set blob properties (md5, cache control)
:param Uploader self: this
:param blobxfer.models.upload.Descriptor ud: upload descriptor
"""
if ud.requires_non_encrypted_md5_put... | [
"def",
"_set_blob_properties",
"(",
"self",
",",
"ud",
")",
":",
"# type: (Uploader, blobxfer.models.upload.Descriptor) -> None",
"if",
"ud",
".",
"requires_non_encrypted_md5_put",
":",
"digest",
"=",
"blobxfer",
".",
"util",
".",
"base64_encode_as_string",
"(",
"ud",
"... | Set blob properties (md5, cache control)
:param Uploader self: this
:param blobxfer.models.upload.Descriptor ud: upload descriptor | [
"Set",
"blob",
"properties",
"(",
"md5",
"cache",
"control",
")",
":",
"param",
"Uploader",
"self",
":",
"this",
":",
"param",
"blobxfer",
".",
"models",
".",
"upload",
".",
"Descriptor",
"ud",
":",
"upload",
"descriptor"
] | python | train | 49.857143 |
hammerlab/stancache | stancache/utils.py | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/utils.py#L36-L42 | def is_field_unique_by_group(df, field_col, group_col):
''' Determine if field is constant by group in df
'''
def num_unique(x):
return len(pd.unique(x))
num_distinct = df.groupby(group_col)[field_col].agg(num_unique)
return all(num_distinct == 1) | [
"def",
"is_field_unique_by_group",
"(",
"df",
",",
"field_col",
",",
"group_col",
")",
":",
"def",
"num_unique",
"(",
"x",
")",
":",
"return",
"len",
"(",
"pd",
".",
"unique",
"(",
"x",
")",
")",
"num_distinct",
"=",
"df",
".",
"groupby",
"(",
"group_c... | Determine if field is constant by group in df | [
"Determine",
"if",
"field",
"is",
"constant",
"by",
"group",
"in",
"df"
] | python | train | 38.428571 |
erdewit/ib_insync | ib_insync/util.py | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/util.py#L381-L409 | def startLoop():
"""
Use nested asyncio event loop for Jupyter notebooks.
"""
def _ipython_loop_asyncio(kernel):
'''
Use asyncio event loop for the given IPython kernel.
'''
loop = asyncio.get_event_loop()
def kernel_handler():
kernel.do_one_iteration... | [
"def",
"startLoop",
"(",
")",
":",
"def",
"_ipython_loop_asyncio",
"(",
"kernel",
")",
":",
"'''\n Use asyncio event loop for the given IPython kernel.\n '''",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"def",
"kernel_handler",
"(",
")",
":",... | Use nested asyncio event loop for Jupyter notebooks. | [
"Use",
"nested",
"asyncio",
"event",
"loop",
"for",
"Jupyter",
"notebooks",
"."
] | python | train | 30.724138 |
pypa/bandersnatch | src/bandersnatch/mirror.py | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/mirror.py#L164-L209 | def determine_packages_to_sync(self):
"""
Update the self.packages_to_sync to contain packages that need to be
synced.
"""
# In case we don't find any changes we will stay on the currently
# synced serial.
self.target_serial = self.synced_serial
self.packa... | [
"def",
"determine_packages_to_sync",
"(",
"self",
")",
":",
"# In case we don't find any changes we will stay on the currently",
"# synced serial.",
"self",
".",
"target_serial",
"=",
"self",
".",
"synced_serial",
"self",
".",
"packages_to_sync",
"=",
"{",
"}",
"logger",
... | Update the self.packages_to_sync to contain packages that need to be
synced. | [
"Update",
"the",
"self",
".",
"packages_to_sync",
"to",
"contain",
"packages",
"that",
"need",
"to",
"be",
"synced",
"."
] | python | train | 47.043478 |
fusionapp/fusion-util | fusion_util/enums.py | https://github.com/fusionapp/fusion-util/blob/089c525799926c8b8bf1117ab22ed055dc99c7e6/fusion_util/enums.py#L89-L102 | def get(self, value):
"""
Get an enumeration item for an enumeration value.
:param unicode value: Enumeration value.
:raise InvalidEnumItem: If ``value`` does not match any known
enumeration value.
:rtype: EnumItem
"""
_nothing = object()
item = s... | [
"def",
"get",
"(",
"self",
",",
"value",
")",
":",
"_nothing",
"=",
"object",
"(",
")",
"item",
"=",
"self",
".",
"_values",
".",
"get",
"(",
"value",
",",
"_nothing",
")",
"if",
"item",
"is",
"_nothing",
":",
"raise",
"InvalidEnumItem",
"(",
"value"... | Get an enumeration item for an enumeration value.
:param unicode value: Enumeration value.
:raise InvalidEnumItem: If ``value`` does not match any known
enumeration value.
:rtype: EnumItem | [
"Get",
"an",
"enumeration",
"item",
"for",
"an",
"enumeration",
"value",
"."
] | python | train | 30.642857 |
lipoja/URLExtract | urlextract/urlextract_core.py | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L196-L212 | def set_stop_chars(self, stop_chars):
"""
Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters
"""
warnings.... | [
"def",
"set_stop_chars",
"(",
"self",
",",
"stop_chars",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Method set_stop_chars is deprecated, \"",
"\"use `set_stop_chars_left` or \"",
"\"`set_stop_chars_right` instead\"",
",",
"DeprecationWarning",
")",
"self",
".",
"_stop_chars",... | Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters | [
"Set",
"stop",
"characters",
"used",
"when",
"determining",
"end",
"of",
"URL",
"."
] | python | train | 36.470588 |
gwastro/pycbc | pycbc/events/ranking.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/ranking.py#L55-L67 | def newsnr_sgveto_psdvar(snr, bchisq, sgchisq, psd_var_val):
""" Combined SNR derived from NewSNR, Sine-Gaussian Chisq and PSD
variation statistic """
nsnr = numpy.array(newsnr_sgveto(snr, bchisq, sgchisq), ndmin=1)
psd_var_val = numpy.array(psd_var_val, ndmin=1)
lgc = psd_var_val >= 1.8
nsnr[lg... | [
"def",
"newsnr_sgveto_psdvar",
"(",
"snr",
",",
"bchisq",
",",
"sgchisq",
",",
"psd_var_val",
")",
":",
"nsnr",
"=",
"numpy",
".",
"array",
"(",
"newsnr_sgveto",
"(",
"snr",
",",
"bchisq",
",",
"sgchisq",
")",
",",
"ndmin",
"=",
"1",
")",
"psd_var_val",
... | Combined SNR derived from NewSNR, Sine-Gaussian Chisq and PSD
variation statistic | [
"Combined",
"SNR",
"derived",
"from",
"NewSNR",
"Sine",
"-",
"Gaussian",
"Chisq",
"and",
"PSD",
"variation",
"statistic"
] | python | train | 39.538462 |
gouthambs/Flask-Blogging | flask_blogging/processor.py | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/processor.py#L67-L80 | def process(cls, post, render=True):
"""
This method takes the post data and renders it
:param post:
:param render:
:return:
"""
post["slug"] = cls.create_slug(post["title"])
post["editable"] = cls.is_author(post, current_user)
post["url"] = cls.co... | [
"def",
"process",
"(",
"cls",
",",
"post",
",",
"render",
"=",
"True",
")",
":",
"post",
"[",
"\"slug\"",
"]",
"=",
"cls",
".",
"create_slug",
"(",
"post",
"[",
"\"title\"",
"]",
")",
"post",
"[",
"\"editable\"",
"]",
"=",
"cls",
".",
"is_author",
... | This method takes the post data and renders it
:param post:
:param render:
:return: | [
"This",
"method",
"takes",
"the",
"post",
"data",
"and",
"renders",
"it",
":",
"param",
"post",
":",
":",
"param",
"render",
":",
":",
"return",
":"
] | python | train | 33.571429 |
senaite/senaite.jsonapi | src/senaite/jsonapi/request.py | https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/request.py#L137-L144 | def get_sort_on(allowed_indexes=None):
""" returns the 'sort_on' from the request
"""
sort_on = get("sort_on")
if allowed_indexes and sort_on not in allowed_indexes:
logger.warn("Index '{}' is not in allowed_indexes".format(sort_on))
return None
return sort_on | [
"def",
"get_sort_on",
"(",
"allowed_indexes",
"=",
"None",
")",
":",
"sort_on",
"=",
"get",
"(",
"\"sort_on\"",
")",
"if",
"allowed_indexes",
"and",
"sort_on",
"not",
"in",
"allowed_indexes",
":",
"logger",
".",
"warn",
"(",
"\"Index '{}' is not in allowed_indexes... | returns the 'sort_on' from the request | [
"returns",
"the",
"sort_on",
"from",
"the",
"request"
] | python | train | 36.125 |
dbcli/cli_helpers | cli_helpers/config.py | https://github.com/dbcli/cli_helpers/blob/3ebd891ac0c02bad061182dbcb54a47fb21980ae/cli_helpers/config.py#L145-L153 | def write(self, outfile=None, section=None):
"""Write the current config to a file (defaults to user config).
:param str outfile: The path to the file to write to.
:param None/str section: The config section to write, or :data:`None`
to write the entire config.
... | [
"def",
"write",
"(",
"self",
",",
"outfile",
"=",
"None",
",",
"section",
"=",
"None",
")",
":",
"with",
"io",
".",
"open",
"(",
"outfile",
"or",
"self",
".",
"user_config_file",
"(",
")",
",",
"'wb'",
")",
"as",
"f",
":",
"self",
".",
"data",
".... | Write the current config to a file (defaults to user config).
:param str outfile: The path to the file to write to.
:param None/str section: The config section to write, or :data:`None`
to write the entire config. | [
"Write",
"the",
"current",
"config",
"to",
"a",
"file",
"(",
"defaults",
"to",
"user",
"config",
")",
"."
] | python | test | 49.777778 |
Esri/ArcREST | src/arcrest/manageags/_data.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/_data.py#L99-L128 | def findDataItems(self, parentPath=None, ancestorPath=None,
type=None, id=None):
"""
You can use this operation to search through the various data
items registered in the server's data store.
Inputs:
parentPath - The path of the parent under w... | [
"def",
"findDataItems",
"(",
"self",
",",
"parentPath",
"=",
"None",
",",
"ancestorPath",
"=",
"None",
",",
"type",
"=",
"None",
",",
"id",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"}",
"if",
"parentPath",
"is",
"not"... | You can use this operation to search through the various data
items registered in the server's data store.
Inputs:
parentPath - The path of the parent under which to find items
ancestorPath - The path of the ancestor under which to find
item... | [
"You",
"can",
"use",
"this",
"operation",
"to",
"search",
"through",
"the",
"various",
"data",
"items",
"registered",
"in",
"the",
"server",
"s",
"data",
"store",
".",
"Inputs",
":",
"parentPath",
"-",
"The",
"path",
"of",
"the",
"parent",
"under",
"which"... | python | train | 40.366667 |
KvasirSecurity/kvasirapi-python | KvasirAPI/jsonrpc/hosts.py | https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/hosts.py#L28-L42 | def add(self, f_ipaddr, f_macaddr, f_hostname, f_netbios_name, f_engineer, f_asset_group, f_confirmed):
"""
Add a t_hosts record
:param f_ipaddr: IP address
:param f_macaddr: MAC Address
:param f_hostname: Hostname
:param f_netbios_name: NetBIOS Name
:param f_eng... | [
"def",
"add",
"(",
"self",
",",
"f_ipaddr",
",",
"f_macaddr",
",",
"f_hostname",
",",
"f_netbios_name",
",",
"f_engineer",
",",
"f_asset_group",
",",
"f_confirmed",
")",
":",
"return",
"self",
".",
"send",
".",
"host_add",
"(",
"f_ipaddr",
",",
"f_macaddr",
... | Add a t_hosts record
:param f_ipaddr: IP address
:param f_macaddr: MAC Address
:param f_hostname: Hostname
:param f_netbios_name: NetBIOS Name
:param f_engineer: Engineer username
:param f_asset_group: Asset group
:param f_confirmed: Confirmed boolean
:re... | [
"Add",
"a",
"t_hosts",
"record"
] | python | train | 43.266667 |
miquelo/resort | packages/resort/component/glassfish.py | https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/component/glassfish.py#L901-L922 | def domain(host, port, username, password, avail_timeout=240.):
"""
Endpoint domain.
:param str host:
Endpoint host.
:param int port:
Endpoint port.
:param str username:
Endpoint username.
:param str password:
Endpoint password.
:param float avail_timeout:
Availability check timeout in se... | [
"def",
"domain",
"(",
"host",
",",
"port",
",",
"username",
",",
"password",
",",
"avail_timeout",
"=",
"240.",
")",
":",
"return",
"Domain",
"(",
"Endpoint",
"(",
"host",
",",
"port",
",",
"username",
",",
"password",
")",
",",
"avail_timeout",
")"
] | Endpoint domain.
:param str host:
Endpoint host.
:param int port:
Endpoint port.
:param str username:
Endpoint username.
:param str password:
Endpoint password.
:param float avail_timeout:
Availability check timeout in seconds.
:rtype:
Domain
:return:
Domain for the given endpoint p... | [
"Endpoint",
"domain",
".",
":",
"param",
"str",
"host",
":",
"Endpoint",
"host",
".",
":",
"param",
"int",
"port",
":",
"Endpoint",
"port",
".",
":",
"param",
"str",
"username",
":",
"Endpoint",
"username",
".",
":",
"param",
"str",
"password",
":",
"E... | python | train | 20.909091 |
angr/angr | angr/analyses/bindiff.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/bindiff.py#L1171-L1205 | def _get_function_matches(attributes_a, attributes_b, filter_set_a=None, filter_set_b=None):
"""
:param attributes_a: A dict of functions to their attributes
:param attributes_b: A dict of functions to their attributes
The following parameters are optional.
:param filter_... | [
"def",
"_get_function_matches",
"(",
"attributes_a",
",",
"attributes_b",
",",
"filter_set_a",
"=",
"None",
",",
"filter_set_b",
"=",
"None",
")",
":",
"# get the attributes that are in the sets",
"if",
"filter_set_a",
"is",
"None",
":",
"filtered_attributes_a",
"=",
... | :param attributes_a: A dict of functions to their attributes
:param attributes_b: A dict of functions to their attributes
The following parameters are optional.
:param filter_set_a: A set to limit attributes_a to the functions in this set.
:param filter_set_b: A set to limi... | [
":",
"param",
"attributes_a",
":",
"A",
"dict",
"of",
"functions",
"to",
"their",
"attributes",
":",
"param",
"attributes_b",
":",
"A",
"dict",
"of",
"functions",
"to",
"their",
"attributes"
] | python | train | 44.914286 |
saltstack/salt | salt/cloud/clouds/oneandone.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/oneandone.py#L227-L242 | def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['... | [
"def",
"get_image",
"(",
"vm_",
")",
":",
"vm_image",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'image'",
",",
"vm_",
",",
"__opts__",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'salt-cloud-force-ascii'",
")",
"images",
"=",
"avail_images",
"(",
")"... | Return the image object to use | [
"Return",
"the",
"image",
"object",
"to",
"use"
] | python | train | 29.75 |
mastro35/flows | flows/Actions/InputWatchdogAction.py | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/InputWatchdogAction.py#L28-L32 | def on_any_event(self, event):
"""On any event method"""
for delegate in self.delegates:
if hasattr(delegate, "on_any_event"):
delegate.on_any_event(event) | [
"def",
"on_any_event",
"(",
"self",
",",
"event",
")",
":",
"for",
"delegate",
"in",
"self",
".",
"delegates",
":",
"if",
"hasattr",
"(",
"delegate",
",",
"\"on_any_event\"",
")",
":",
"delegate",
".",
"on_any_event",
"(",
"event",
")"
] | On any event method | [
"On",
"any",
"event",
"method"
] | python | train | 39 |
hustlzp/Flask-Boost | flask_boost/project/application/utils/helpers.py | https://github.com/hustlzp/Flask-Boost/blob/d0308408ebb248dd752b77123b845f8ec637fab2/flask_boost/project/application/utils/helpers.py#L7-L12 | def absolute_url_for(endpoint, **values):
"""Absolute url for endpoint."""
config = current_app.config
site_domain = config.get('SITE_DOMAIN')
relative_url = url_for(endpoint, **values)
return join_url(site_domain, relative_url) | [
"def",
"absolute_url_for",
"(",
"endpoint",
",",
"*",
"*",
"values",
")",
":",
"config",
"=",
"current_app",
".",
"config",
"site_domain",
"=",
"config",
".",
"get",
"(",
"'SITE_DOMAIN'",
")",
"relative_url",
"=",
"url_for",
"(",
"endpoint",
",",
"*",
"*",... | Absolute url for endpoint. | [
"Absolute",
"url",
"for",
"endpoint",
"."
] | python | test | 40.5 |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L17063-L17078 | def find_host_network_interfaces_of_type(self, type_p):
"""Searches through all host network interfaces and returns a list of interfaces of the specified type
in type_p of type :class:`HostNetworkInterfaceType`
type of the host network interfaces to search for.
return network_inter... | [
"def",
"find_host_network_interfaces_of_type",
"(",
"self",
",",
"type_p",
")",
":",
"if",
"not",
"isinstance",
"(",
"type_p",
",",
"HostNetworkInterfaceType",
")",
":",
"raise",
"TypeError",
"(",
"\"type_p can only be an instance of type HostNetworkInterfaceType\"",
")",
... | Searches through all host network interfaces and returns a list of interfaces of the specified type
in type_p of type :class:`HostNetworkInterfaceType`
type of the host network interfaces to search for.
return network_interfaces of type :class:`IHostNetworkInterface`
Found host... | [
"Searches",
"through",
"all",
"host",
"network",
"interfaces",
"and",
"returns",
"a",
"list",
"of",
"interfaces",
"of",
"the",
"specified",
"type"
] | python | train | 49.8125 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.