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 |
|---|---|---|---|---|---|---|---|---|---|
ejeschke/ginga | ginga/rv/plugins/PlotTable.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/PlotTable.py#L331-L348 | def _get_label(self, axis):
"""Return plot label for column for the given axis."""
if axis == 'x':
colname = self.x_col
else: # y
colname = self.y_col
if colname == self._idxname:
label = 'Index'
else:
col = self.tab[colname]
... | [
"def",
"_get_label",
"(",
"self",
",",
"axis",
")",
":",
"if",
"axis",
"==",
"'x'",
":",
"colname",
"=",
"self",
".",
"x_col",
"else",
":",
"# y",
"colname",
"=",
"self",
".",
"y_col",
"if",
"colname",
"==",
"self",
".",
"_idxname",
":",
"label",
"... | Return plot label for column for the given axis. | [
"Return",
"plot",
"label",
"for",
"column",
"for",
"the",
"given",
"axis",
"."
] | python | train | 25.555556 |
TomasTomecek/sen | sen/tui/ui.py | https://github.com/TomasTomecek/sen/blob/239b4868125814e8bf5527708119fc08b35f6cc0/sen/tui/ui.py#L131-L147 | def pick_and_display_buffer(self, i):
"""
pick i-th buffer from list and display it
:param i: int
:return: None
"""
if len(self.buffers) == 1:
# we don't need to display anything
# listing is already displayed
return
else:
... | [
"def",
"pick_and_display_buffer",
"(",
"self",
",",
"i",
")",
":",
"if",
"len",
"(",
"self",
".",
"buffers",
")",
"==",
"1",
":",
"# we don't need to display anything",
"# listing is already displayed",
"return",
"else",
":",
"try",
":",
"self",
".",
"display_bu... | pick i-th buffer from list and display it
:param i: int
:return: None | [
"pick",
"i",
"-",
"th",
"buffer",
"from",
"list",
"and",
"display",
"it"
] | python | train | 28.176471 |
h2oai/h2o-3 | h2o-py/h2o/model/model_base.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/model/model_base.py#L1095-L1178 | def varimp_plot(self, num_of_features=None, server=False):
"""
Plot the variable importance for a trained model.
:param num_of_features: the number of features shown in the plot (default is 10 or all if less than 10).
:param server: ?
:returns: None.
"""
assert_... | [
"def",
"varimp_plot",
"(",
"self",
",",
"num_of_features",
"=",
"None",
",",
"server",
"=",
"False",
")",
":",
"assert_is_type",
"(",
"num_of_features",
",",
"None",
",",
"int",
")",
"assert_is_type",
"(",
"server",
",",
"bool",
")",
"plt",
"=",
"_get_matp... | Plot the variable importance for a trained model.
:param num_of_features: the number of features shown in the plot (default is 10 or all if less than 10).
:param server: ?
:returns: None. | [
"Plot",
"the",
"variable",
"importance",
"for",
"a",
"trained",
"model",
"."
] | python | test | 48.107143 |
tjcsl/ion | intranet/apps/dashboard/views.py | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dashboard/views.py#L185-L254 | def find_birthdays(request):
"""Return information on user birthdays."""
today = date.today()
custom = False
yr_inc = 0
if "birthday_month" in request.GET and "birthday_day" in request.GET:
try:
mon = int(request.GET["birthday_month"])
day = int(request.GET["birthday_... | [
"def",
"find_birthdays",
"(",
"request",
")",
":",
"today",
"=",
"date",
".",
"today",
"(",
")",
"custom",
"=",
"False",
"yr_inc",
"=",
"0",
"if",
"\"birthday_month\"",
"in",
"request",
".",
"GET",
"and",
"\"birthday_day\"",
"in",
"request",
".",
"GET",
... | Return information on user birthdays. | [
"Return",
"information",
"on",
"user",
"birthdays",
"."
] | python | train | 36.085714 |
tsroten/dragonmapper | dragonmapper/hanzi.py | https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L89-L168 | def to_pinyin(s, delimiter=' ', all_readings=False, container='[]',
accented=True):
"""Convert a string's Chinese characters to Pinyin readings.
*s* is a string containing Chinese characters. *accented* is a
boolean value indicating whether to return accented or numbered Pinyin
readings.
... | [
"def",
"to_pinyin",
"(",
"s",
",",
"delimiter",
"=",
"' '",
",",
"all_readings",
"=",
"False",
",",
"container",
"=",
"'[]'",
",",
"accented",
"=",
"True",
")",
":",
"hanzi",
"=",
"s",
"pinyin",
"=",
"''",
"# Process the given string.",
"while",
"hanzi",
... | Convert a string's Chinese characters to Pinyin readings.
*s* is a string containing Chinese characters. *accented* is a
boolean value indicating whether to return accented or numbered Pinyin
readings.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differenti... | [
"Convert",
"a",
"string",
"s",
"Chinese",
"characters",
"to",
"Pinyin",
"readings",
"."
] | python | train | 37.375 |
wavefrontHQ/python-client | wavefront_api_client/api/alert_api.py | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/alert_api.py#L333-L353 | def get_alert(self, id, **kwargs): # noqa: E501
"""Get a specific alert # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_alert(id, async_req=True)
... | [
"def",
"get_alert",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"get_alert_with_htt... | Get a specific alert # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_alert(id, async_req=True)
>>> result = thread.get()
:param async_req bool
... | [
"Get",
"a",
"specific",
"alert",
"#",
"noqa",
":",
"E501"
] | python | train | 39.142857 |
openego/ding0 | ding0/core/__init__.py | https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/core/__init__.py#L1784-L1802 | def reinforce_grid(self):
""" Performs grid reinforcement measures for all MV and LV grids
Args:
Returns:
"""
# TODO: Finish method and enable LV case
for grid_district in self.mv_grid_districts():
# reinforce MV grid
grid_district.mv_grid.rein... | [
"def",
"reinforce_grid",
"(",
"self",
")",
":",
"# TODO: Finish method and enable LV case",
"for",
"grid_district",
"in",
"self",
".",
"mv_grid_districts",
"(",
")",
":",
"# reinforce MV grid",
"grid_district",
".",
"mv_grid",
".",
"reinforce_grid",
"(",
")",
"# reinf... | Performs grid reinforcement measures for all MV and LV grids
Args:
Returns: | [
"Performs",
"grid",
"reinforcement",
"measures",
"for",
"all",
"MV",
"and",
"LV",
"grids",
"Args",
":"
] | python | train | 31.894737 |
JamesPHoughton/pysd | pysd/py_backend/functions.py | https://github.com/JamesPHoughton/pysd/blob/bf1b1d03954e9ba5acac9ba4f1ada7cd93352eda/pysd/py_backend/functions.py#L615-L690 | def run(self, params=None, return_columns=None, return_timestamps=None,
initial_condition='original', reload=False):
""" Simulate the model's behavior over time.
Return a pandas dataframe with timestamps as rows,
model elements as columns.
Parameters
----------
... | [
"def",
"run",
"(",
"self",
",",
"params",
"=",
"None",
",",
"return_columns",
"=",
"None",
",",
"return_timestamps",
"=",
"None",
",",
"initial_condition",
"=",
"'original'",
",",
"reload",
"=",
"False",
")",
":",
"if",
"reload",
":",
"self",
".",
"reloa... | Simulate the model's behavior over time.
Return a pandas dataframe with timestamps as rows,
model elements as columns.
Parameters
----------
params : dictionary
Keys are strings of model component names.
Values are numeric or pandas Series.
Nu... | [
"Simulate",
"the",
"model",
"s",
"behavior",
"over",
"time",
".",
"Return",
"a",
"pandas",
"dataframe",
"with",
"timestamps",
"as",
"rows",
"model",
"elements",
"as",
"columns",
"."
] | python | train | 37.355263 |
tapilab/brandelion | brandelion/cli/collect.py | https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/collect.py#L56-L82 | def fetch_followers(account_file, outfile, limit, do_loop):
""" Fetch up to limit followers for each Twitter account in
account_file. Write results to outfile file in format:
screen_name user_id follower_id_1 follower_id_2 ..."""
print('Fetching followers for accounts in %s' % account_file)
niters ... | [
"def",
"fetch_followers",
"(",
"account_file",
",",
"outfile",
",",
"limit",
",",
"do_loop",
")",
":",
"print",
"(",
"'Fetching followers for accounts in %s'",
"%",
"account_file",
")",
"niters",
"=",
"1",
"while",
"True",
":",
"outf",
"=",
"gzip",
".",
"open"... | Fetch up to limit followers for each Twitter account in
account_file. Write results to outfile file in format:
screen_name user_id follower_id_1 follower_id_2 ... | [
"Fetch",
"up",
"to",
"limit",
"followers",
"for",
"each",
"Twitter",
"account",
"in",
"account_file",
".",
"Write",
"results",
"to",
"outfile",
"file",
"in",
"format",
":"
] | python | train | 41 |
NICTA/revrand | revrand/optimize/decorators.py | https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/decorators.py#L487-L534 | def flatten_args(shapes):
r"""
Decorator to flatten structured arguments to a function.
Examples
--------
>>> @flatten_args([(5,), ()])
... def f(w, lambda_):
... return .5 * lambda_ * w.T.dot(w)
>>> np.isclose(f(np.array([2., .5, .6, -.2, .9, .2])), .546)
True
>>> w = np.ar... | [
"def",
"flatten_args",
"(",
"shapes",
")",
":",
"def",
"flatten_args_dec",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"array1d",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"tuple",
"(",
"un... | r"""
Decorator to flatten structured arguments to a function.
Examples
--------
>>> @flatten_args([(5,), ()])
... def f(w, lambda_):
... return .5 * lambda_ * w.T.dot(w)
>>> np.isclose(f(np.array([2., .5, .6, -.2, .9, .2])), .546)
True
>>> w = np.array([2., .5, .6, -.2, .9])
... | [
"r",
"Decorator",
"to",
"flatten",
"structured",
"arguments",
"to",
"a",
"function",
"."
] | python | train | 29.270833 |
raiden-network/raiden | raiden/transfer/mediated_transfer/initiator.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator.py#L49-L84 | def events_for_unlock_lock(
initiator_state: InitiatorTransferState,
channel_state: NettingChannelState,
secret: Secret,
secrethash: SecretHash,
pseudo_random_generator: random.Random,
) -> List[Event]:
""" Unlocks the lock offchain, and emits the events for the successful pa... | [
"def",
"events_for_unlock_lock",
"(",
"initiator_state",
":",
"InitiatorTransferState",
",",
"channel_state",
":",
"NettingChannelState",
",",
"secret",
":",
"Secret",
",",
"secrethash",
":",
"SecretHash",
",",
"pseudo_random_generator",
":",
"random",
".",
"Random",
... | Unlocks the lock offchain, and emits the events for the successful payment. | [
"Unlocks",
"the",
"lock",
"offchain",
"and",
"emits",
"the",
"events",
"for",
"the",
"successful",
"payment",
"."
] | python | train | 38.833333 |
SCIP-Interfaces/PySCIPOpt | examples/finished/flp.py | https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/finished/flp.py#L49-L59 | def make_data():
"""creates example data set"""
I,d = multidict({1:80, 2:270, 3:250, 4:160, 5:180}) # demand
J,M,f = multidict({1:[500,1000], 2:[500,1000], 3:[500,1000]}) # capacity, fixed costs
c = {(1,1):4, (1,2):6, (1,3):9, # transportation costs
(2,1):5, (2,2):4, (2,3):7,
... | [
"def",
"make_data",
"(",
")",
":",
"I",
",",
"d",
"=",
"multidict",
"(",
"{",
"1",
":",
"80",
",",
"2",
":",
"270",
",",
"3",
":",
"250",
",",
"4",
":",
"160",
",",
"5",
":",
"180",
"}",
")",
"# demand",
"J",
",",
"M",
",",
"f",
"=",
"m... | creates example data set | [
"creates",
"example",
"data",
"set"
] | python | train | 41.545455 |
ActivisionGameScience/assertpy | assertpy/assertpy.py | https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L366-L374 | def is_in(self, *items):
"""Asserts that val is equal to one of the given items."""
if len(items) == 0:
raise ValueError('one or more args must be given')
else:
for i in items:
if self.val == i:
return self
self._err('Expected <... | [
"def",
"is_in",
"(",
"self",
",",
"*",
"items",
")",
":",
"if",
"len",
"(",
"items",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'one or more args must be given'",
")",
"else",
":",
"for",
"i",
"in",
"items",
":",
"if",
"self",
".",
"val",
"=="... | Asserts that val is equal to one of the given items. | [
"Asserts",
"that",
"val",
"is",
"equal",
"to",
"one",
"of",
"the",
"given",
"items",
"."
] | python | valid | 42.222222 |
bskinn/opan | opan/output.py | https://github.com/bskinn/opan/blob/0b1b21662df6abc971407a9386db21a8796fbfe5/opan/output.py#L792-L818 | def en_last(self):
""" Report the energies from the last SCF present in the output.
Returns a |dict| providing the various energy values from the
last SCF cycle performed in the output. Keys are those of
:attr:`~opan.output.OrcaOutput.p_en`.
Any energy value not relevant to the ... | [
"def",
"en_last",
"(",
"self",
")",
":",
"# Initialize the return dict",
"last_ens",
"=",
"dict",
"(",
")",
"# Iterate and store",
"for",
"(",
"k",
",",
"l",
")",
"in",
"self",
".",
"en",
".",
"items",
"(",
")",
":",
"last_ens",
".",
"update",
"(",
"{"... | Report the energies from the last SCF present in the output.
Returns a |dict| providing the various energy values from the
last SCF cycle performed in the output. Keys are those of
:attr:`~opan.output.OrcaOutput.p_en`.
Any energy value not relevant to the parsed
output is assign... | [
"Report",
"the",
"energies",
"from",
"the",
"last",
"SCF",
"present",
"in",
"the",
"output",
"."
] | python | train | 28.740741 |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network.py#L1148-L1208 | def add_padding(self, name,
left = 0, right = 0, top = 0, bottom = 0,
value = 0,
input_name = 'data', output_name = 'out',
padding_type = 'constant'):
"""
Add a padding layer to the model. Kindly refer to NeuralNetwork.proto for details.
Parameter... | [
"def",
"add_padding",
"(",
"self",
",",
"name",
",",
"left",
"=",
"0",
",",
"right",
"=",
"0",
",",
"top",
"=",
"0",
",",
"bottom",
"=",
"0",
",",
"value",
"=",
"0",
",",
"input_name",
"=",
"'data'",
",",
"output_name",
"=",
"'out'",
",",
"paddin... | Add a padding layer to the model. Kindly refer to NeuralNetwork.proto for details.
Parameters
----------
name: str
The name of this layer.
left: int
Number of elements to be padded on the left side of the input blob.
right: int
Number of eleme... | [
"Add",
"a",
"padding",
"layer",
"to",
"the",
"model",
".",
"Kindly",
"refer",
"to",
"NeuralNetwork",
".",
"proto",
"for",
"details",
"."
] | python | train | 37.196721 |
mitsei/dlkit | dlkit/services/relationship.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/relationship.py#L468-L476 | def get_family_form(self, *args, **kwargs):
"""Pass through to provider FamilyAdminSession.get_family_form_for_update"""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.get_bin_form_for_update_template
# This method might be a bit sketchy. Time will tell.
... | [
"def",
"get_family_form",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Implemented from kitosid template for -",
"# osid.resource.BinAdminSession.get_bin_form_for_update_template",
"# This method might be a bit sketchy. Time will tell.",
"if",
"isinstance",
... | Pass through to provider FamilyAdminSession.get_family_form_for_update | [
"Pass",
"through",
"to",
"provider",
"FamilyAdminSession",
".",
"get_family_form_for_update"
] | python | train | 58.777778 |
boakley/robotframework-hub | rfhub/blueprints/doc/__init__.py | https://github.com/boakley/robotframework-hub/blob/f3dc7562fe6218a7b8d7aac7b9ef234e1a573f7c/rfhub/blueprints/doc/__init__.py#L32-L43 | def index():
"""Show a list of available libraries, and resource files"""
kwdb = current_app.kwdb
libraries = get_collections(kwdb, libtype="library")
resource_files = get_collections(kwdb, libtype="resource")
return flask.render_template("libraryNames.html",
data=... | [
"def",
"index",
"(",
")",
":",
"kwdb",
"=",
"current_app",
".",
"kwdb",
"libraries",
"=",
"get_collections",
"(",
"kwdb",
",",
"libtype",
"=",
"\"library\"",
")",
"resource_files",
"=",
"get_collections",
"(",
"kwdb",
",",
"libtype",
"=",
"\"resource\"",
")"... | Show a list of available libraries, and resource files | [
"Show",
"a",
"list",
"of",
"available",
"libraries",
"and",
"resource",
"files"
] | python | train | 42.166667 |
yunojuno/elasticsearch-django | elasticsearch_django/models.py | https://github.com/yunojuno/elasticsearch-django/blob/e8d98d32bcd77f1bedb8f1a22b6523ca44ffd489/elasticsearch_django/models.py#L223-L228 | def _is_field_serializable(self, field_name):
"""Return True if the field can be serialized into a JSON doc."""
return (
self._meta.get_field(field_name).get_internal_type()
in self.SIMPLE_UPDATE_FIELD_TYPES
) | [
"def",
"_is_field_serializable",
"(",
"self",
",",
"field_name",
")",
":",
"return",
"(",
"self",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
".",
"get_internal_type",
"(",
")",
"in",
"self",
".",
"SIMPLE_UPDATE_FIELD_TYPES",
")"
] | Return True if the field can be serialized into a JSON doc. | [
"Return",
"True",
"if",
"the",
"field",
"can",
"be",
"serialized",
"into",
"a",
"JSON",
"doc",
"."
] | python | train | 42 |
bunq/sdk_python | bunq/sdk/model/generated/endpoint.py | https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L7182-L7244 | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._uuid is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._merchant_reference is not None:
... | [
"def",
"is_all_field_none",
"(",
"self",
")",
":",
"if",
"self",
".",
"_uuid",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_created",
"is",
"not",
"None",
":",
"return",
"False",
"if",
"self",
".",
"_updated",
"is",
"not",
"None",
... | :rtype: bool | [
":",
"rtype",
":",
"bool"
] | python | train | 20.920635 |
crytic/slither | slither/printers/summary/slithir.py | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/printers/summary/slithir.py#L15-L48 | def output(self, _filename):
"""
_filename is not used
Args:
_filename(string)
"""
txt = ""
for contract in self.contracts:
print('Contract {}'.format(contract.name))
for function in contract.functions:
if f... | [
"def",
"output",
"(",
"self",
",",
"_filename",
")",
":",
"txt",
"=",
"\"\"",
"for",
"contract",
"in",
"self",
".",
"contracts",
":",
"print",
"(",
"'Contract {}'",
".",
"format",
"(",
"contract",
".",
"name",
")",
")",
"for",
"function",
"in",
"contra... | _filename is not used
Args:
_filename(string) | [
"_filename",
"is",
"not",
"used",
"Args",
":",
"_filename",
"(",
"string",
")"
] | python | train | 42.970588 |
pyQode/pyqode.core | pyqode/core/widgets/splittable_tab_widget.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L215-L225 | def close_all(self):
"""
Closes all editors
"""
if self._try_close_dirty_tabs():
while self.count():
widget = self.widget(0)
self.remove_tab(0)
self.tab_closed.emit(widget)
return True
return False | [
"def",
"close_all",
"(",
"self",
")",
":",
"if",
"self",
".",
"_try_close_dirty_tabs",
"(",
")",
":",
"while",
"self",
".",
"count",
"(",
")",
":",
"widget",
"=",
"self",
".",
"widget",
"(",
"0",
")",
"self",
".",
"remove_tab",
"(",
"0",
")",
"self... | Closes all editors | [
"Closes",
"all",
"editors"
] | python | train | 27.181818 |
facelessuser/soupsieve | soupsieve/__init__.py | https://github.com/facelessuser/soupsieve/blob/24859cc3e756ebf46b75547d49c6b4a7bf35ee82/soupsieve/__init__.py#L78-L81 | def match(select, tag, namespaces=None, flags=0, **kwargs):
"""Match node."""
return compile(select, namespaces, flags, **kwargs).match(tag) | [
"def",
"match",
"(",
"select",
",",
"tag",
",",
"namespaces",
"=",
"None",
",",
"flags",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"compile",
"(",
"select",
",",
"namespaces",
",",
"flags",
",",
"*",
"*",
"kwargs",
")",
".",
"match",
... | Match node. | [
"Match",
"node",
"."
] | python | train | 36.5 |
awslabs/aws-sam-cli | samcli/commands/publish/command.py | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/publish/command.py#L55-L83 | def do_cli(ctx, template, semantic_version):
"""Publish the application based on command line inputs."""
try:
template_data = get_template_data(template)
except ValueError as ex:
click.secho("Publish Failed", fg='red')
raise UserException(str(ex))
# Override SemanticVersion in t... | [
"def",
"do_cli",
"(",
"ctx",
",",
"template",
",",
"semantic_version",
")",
":",
"try",
":",
"template_data",
"=",
"get_template_data",
"(",
"template",
")",
"except",
"ValueError",
"as",
"ex",
":",
"click",
".",
"secho",
"(",
"\"Publish Failed\"",
",",
"fg"... | Publish the application based on command line inputs. | [
"Publish",
"the",
"application",
"based",
"on",
"command",
"line",
"inputs",
"."
] | python | train | 50.241379 |
LogicalDash/LiSE | ELiDE/ELiDE/charmenu.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/charmenu.py#L140-L158 | def toggle_reciprocal(self):
"""Flip my ``reciprocal_portal`` boolean, and draw (or stop drawing)
an extra arrow on the appropriate button to indicate the
fact.
"""
self.screen.boardview.reciprocal_portal = not self.screen.boardview.reciprocal_portal
if self.screen.board... | [
"def",
"toggle_reciprocal",
"(",
"self",
")",
":",
"self",
".",
"screen",
".",
"boardview",
".",
"reciprocal_portal",
"=",
"not",
"self",
".",
"screen",
".",
"boardview",
".",
"reciprocal_portal",
"if",
"self",
".",
"screen",
".",
"boardview",
".",
"reciproc... | Flip my ``reciprocal_portal`` boolean, and draw (or stop drawing)
an extra arrow on the appropriate button to indicate the
fact. | [
"Flip",
"my",
"reciprocal_portal",
"boolean",
"and",
"draw",
"(",
"or",
"stop",
"drawing",
")",
"an",
"extra",
"arrow",
"on",
"the",
"appropriate",
"button",
"to",
"indicate",
"the",
"fact",
"."
] | python | train | 41.263158 |
apple/turicreate | deps/src/boost_1_68_0/libs/metaparse/tools/benchmark/benchmark.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/benchmark/benchmark.py#L76-L92 | def compiler_info(compiler):
"""Determine the name + version of the compiler"""
(out, err) = subprocess.Popen(
['/bin/sh', '-c', '{0} -v'.format(compiler)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate('')
gcc_clang = re.compile('(g... | [
"def",
"compiler_info",
"(",
"compiler",
")",
":",
"(",
"out",
",",
"err",
")",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'/bin/sh'",
",",
"'-c'",
",",
"'{0} -v'",
".",
"format",
"(",
"compiler",
")",
"]",
",",
"stdin",
"=",
"subprocess",
".",
"PIP... | Determine the name + version of the compiler | [
"Determine",
"the",
"name",
"+",
"version",
"of",
"the",
"compiler"
] | python | train | 30.411765 |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsHandle_Edit.py | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsHandle_Edit.py#L80-L83 | def Uri(self):
""" Constructs the connection URI from name, noSsl and port instance variables. """
return ("%s://%s%s" % (("https", "http")[self._noSsl == True], self._name, (":" + str(self._port), "")[
(((self._noSsl == False) and (self._port == 80)) or ((self._noSsl == True) and (self._port == 443)))])) | [
"def",
"Uri",
"(",
"self",
")",
":",
"return",
"(",
"\"%s://%s%s\"",
"%",
"(",
"(",
"\"https\"",
",",
"\"http\"",
")",
"[",
"self",
".",
"_noSsl",
"==",
"True",
"]",
",",
"self",
".",
"_name",
",",
"(",
"\":\"",
"+",
"str",
"(",
"self",
".",
"_po... | Constructs the connection URI from name, noSsl and port instance variables. | [
"Constructs",
"the",
"connection",
"URI",
"from",
"name",
"noSsl",
"and",
"port",
"instance",
"variables",
"."
] | python | train | 77.5 |
Bystroushaak/pyDHTMLParser | src/dhtmlparser/htmlelement/html_parser.py | https://github.com/Bystroushaak/pyDHTMLParser/blob/4756f93dd048500b038ece2323fe26e46b6bfdea/src/dhtmlparser/htmlelement/html_parser.py#L311-L336 | def isNonPairTag(self, isnonpair=None):
"""
True if element is listed in nonpair tag table (``br`` for example) or
if it ends with ``/>`` (``<hr />`` for example).
You can also change state from pair to nonpair if you use this as
setter.
Args:
isnonpair (boo... | [
"def",
"isNonPairTag",
"(",
"self",
",",
"isnonpair",
"=",
"None",
")",
":",
"if",
"isnonpair",
"is",
"None",
":",
"return",
"self",
".",
"_isnonpairtag",
"if",
"not",
"self",
".",
"_istag",
":",
"return",
"if",
"isnonpair",
":",
"self",
".",
"endtag",
... | True if element is listed in nonpair tag table (``br`` for example) or
if it ends with ``/>`` (``<hr />`` for example).
You can also change state from pair to nonpair if you use this as
setter.
Args:
isnonpair (bool, default None): If set, internal nonpair state is
... | [
"True",
"if",
"element",
"is",
"listed",
"in",
"nonpair",
"tag",
"table",
"(",
"br",
"for",
"example",
")",
"or",
"if",
"it",
"ends",
"with",
"/",
">",
"(",
"<hr",
"/",
">",
"for",
"example",
")",
"."
] | python | train | 26.461538 |
ChrisTimperley/Kaskara | python/kaskara/statements.py | https://github.com/ChrisTimperley/Kaskara/blob/3d182d95b2938508e5990eddd30321be15e2f2ef/python/kaskara/statements.py#L134-L141 | def at_line(self, line: FileLine) -> Iterator[Statement]:
"""
Returns an iterator over all of the statements located at a given line.
"""
num = line.num
for stmt in self.in_file(line.filename):
if stmt.location.start.line == num:
yield stmt | [
"def",
"at_line",
"(",
"self",
",",
"line",
":",
"FileLine",
")",
"->",
"Iterator",
"[",
"Statement",
"]",
":",
"num",
"=",
"line",
".",
"num",
"for",
"stmt",
"in",
"self",
".",
"in_file",
"(",
"line",
".",
"filename",
")",
":",
"if",
"stmt",
".",
... | Returns an iterator over all of the statements located at a given line. | [
"Returns",
"an",
"iterator",
"over",
"all",
"of",
"the",
"statements",
"located",
"at",
"a",
"given",
"line",
"."
] | python | train | 37.625 |
bokeh/bokeh | bokeh/core/has_props.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L191-L212 | def accumulate_from_superclasses(cls, propname):
''' Traverse the class hierarchy and accumulate the special sets of names
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__container_props__``,
... | [
"def",
"accumulate_from_superclasses",
"(",
"cls",
",",
"propname",
")",
":",
"cachename",
"=",
"\"__cached_all\"",
"+",
"propname",
"# we MUST use cls.__dict__ NOT hasattr(). hasattr() would also look at base",
"# classes, and the cache must be separate for each class",
"if",
"cache... | Traverse the class hierarchy and accumulate the special sets of names
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__container_props__``,
``__properties__``, ``__properties_with_refs__`` | [
"Traverse",
"the",
"class",
"hierarchy",
"and",
"accumulate",
"the",
"special",
"sets",
"of",
"names",
"MetaHasProps",
"stores",
"on",
"classes",
":"
] | python | train | 38.5 |
openstack/horizon | openstack_dashboard/dashboards/project/instances/utils.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L37-L70 | def sort_flavor_list(request, flavors, with_menu_label=True):
"""Utility method to sort a list of flavors.
By default, returns the available flavors, sorted by RAM usage (ascending).
Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict
in ``local_settings.py``.
"""
def get_key(... | [
"def",
"sort_flavor_list",
"(",
"request",
",",
"flavors",
",",
"with_menu_label",
"=",
"True",
")",
":",
"def",
"get_key",
"(",
"flavor",
",",
"sort_key",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"flavor",
",",
"sort_key",
")",
"except",
"Attribute... | Utility method to sort a list of flavors.
By default, returns the available flavors, sorted by RAM usage (ascending).
Override these behaviours with a ``CREATE_INSTANCE_FLAVOR_SORT`` dict
in ``local_settings.py``. | [
"Utility",
"method",
"to",
"sort",
"a",
"list",
"of",
"flavors",
"."
] | python | train | 38.558824 |
bitesofcode/projexui | projexui/widgets/ximageslider/ximageslider.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/ximageslider/ximageslider.py#L106-L122 | def recalculate(self):
"""
Recalcualtes the slider scene for this widget.
"""
# recalculate the scene geometry
scene = self.scene()
w = self.calculateSceneWidth()
scene.setSceneRect(0, 0, w, self.height())
# recalculate the item layout
... | [
"def",
"recalculate",
"(",
"self",
")",
":",
"# recalculate the scene geometry\r",
"scene",
"=",
"self",
".",
"scene",
"(",
")",
"w",
"=",
"self",
".",
"calculateSceneWidth",
"(",
")",
"scene",
".",
"setSceneRect",
"(",
"0",
",",
"0",
",",
"w",
",",
"sel... | Recalcualtes the slider scene for this widget. | [
"Recalcualtes",
"the",
"slider",
"scene",
"for",
"this",
"widget",
"."
] | python | train | 33.529412 |
SystemRDL/systemrdl-compiler | systemrdl/core/parameter.py | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/parameter.py#L17-L24 | def get_value(self):
"""
Evaluate self.expr to get the parameter's value
"""
if (self._value is None) and (self.expr is not None):
self._value = self.expr.get_value()
return self._value | [
"def",
"get_value",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_value",
"is",
"None",
")",
"and",
"(",
"self",
".",
"expr",
"is",
"not",
"None",
")",
":",
"self",
".",
"_value",
"=",
"self",
".",
"expr",
".",
"get_value",
"(",
")",
"return",... | Evaluate self.expr to get the parameter's value | [
"Evaluate",
"self",
".",
"expr",
"to",
"get",
"the",
"parameter",
"s",
"value"
] | python | train | 28.875 |
mitsei/dlkit | dlkit/json_/commenting/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/commenting/sessions.py#L2094-L2133 | def update_book(self, book_form):
"""Updates an existing book.
arg: book_form (osid.commenting.BookForm): the form
containing the elements to be updated
raise: IllegalState - ``book_form`` already used in an update
transaction
raise: InvalidArgument ... | [
"def",
"update_book",
"(",
"self",
",",
"book_form",
")",
":",
"# Implemented from template for",
"# osid.resource.BinAdminSession.update_bin_template",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
".",
"upd... | Updates an existing book.
arg: book_form (osid.commenting.BookForm): the form
containing the elements to be updated
raise: IllegalState - ``book_form`` already used in an update
transaction
raise: InvalidArgument - the form contains an invalid value
... | [
"Updates",
"an",
"existing",
"book",
"."
] | python | train | 52.9 |
apache/incubator-superset | superset/views/core.py | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2654-L2692 | def csv(self, client_id):
"""Download the query results as csv."""
logging.info('Exporting CSV file [{}]'.format(client_id))
query = (
db.session.query(Query)
.filter_by(client_id=client_id)
.one()
)
rejected_tables = security_manager.rejected... | [
"def",
"csv",
"(",
"self",
",",
"client_id",
")",
":",
"logging",
".",
"info",
"(",
"'Exporting CSV file [{}]'",
".",
"format",
"(",
"client_id",
")",
")",
"query",
"=",
"(",
"db",
".",
"session",
".",
"query",
"(",
"Query",
")",
".",
"filter_by",
"(",... | Download the query results as csv. | [
"Download",
"the",
"query",
"results",
"as",
"csv",
"."
] | python | train | 44.769231 |
vslutov/turingmarkov | turingmarkov/turing.py | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L125-L142 | def execute_once(self):
"""One step of execution."""
symbol = self.tape.get(self.head, self.EMPTY_SYMBOL)
index = self.alphabet.index(symbol)
rule = self.states[self.state][index]
if rule is None:
raise RuntimeError('Unexpected symbol: ' + symbol)
self.tape... | [
"def",
"execute_once",
"(",
"self",
")",
":",
"symbol",
"=",
"self",
".",
"tape",
".",
"get",
"(",
"self",
".",
"head",
",",
"self",
".",
"EMPTY_SYMBOL",
")",
"index",
"=",
"self",
".",
"alphabet",
".",
"index",
"(",
"symbol",
")",
"rule",
"=",
"se... | One step of execution. | [
"One",
"step",
"of",
"execution",
"."
] | python | train | 25.833333 |
carpedm20/ndrive | ndrive/client.py | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/ndrive/client.py#L746-L765 | def setProperty(self, full_path, protect, dummy = 7046):
"""Set property of a file.
:param full_path: The full path to get the file or directory property.
:param protect: 'Y' or 'N', 중요 표시
:return: ``True`` when success to set property or ``False``
"""
data = {'orgresou... | [
"def",
"setProperty",
"(",
"self",
",",
"full_path",
",",
"protect",
",",
"dummy",
"=",
"7046",
")",
":",
"data",
"=",
"{",
"'orgresource'",
":",
"full_path",
",",
"'protect'",
":",
"protect",
",",
"'userid'",
":",
"self",
".",
"user_id",
",",
"'useridx'... | Set property of a file.
:param full_path: The full path to get the file or directory property.
:param protect: 'Y' or 'N', 중요 표시
:return: ``True`` when success to set property or ``False`` | [
"Set",
"property",
"of",
"a",
"file",
"."
] | python | train | 31.15 |
pycontribs/pyrax | pyrax/manager.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/manager.py#L93-L96 | def head(self, item):
"""Makes a HEAD request on a specific item."""
uri = "/%s/%s" % (self.uri_base, utils.get_id(item))
return self._head(uri) | [
"def",
"head",
"(",
"self",
",",
"item",
")",
":",
"uri",
"=",
"\"/%s/%s\"",
"%",
"(",
"self",
".",
"uri_base",
",",
"utils",
".",
"get_id",
"(",
"item",
")",
")",
"return",
"self",
".",
"_head",
"(",
"uri",
")"
] | Makes a HEAD request on a specific item. | [
"Makes",
"a",
"HEAD",
"request",
"on",
"a",
"specific",
"item",
"."
] | python | train | 41.25 |
StaticCube/python-synology | SynologyDSM/SynologyDSM.py | https://github.com/StaticCube/python-synology/blob/a5446a052fc91a38f7589803dc7a654180db2566/SynologyDSM/SynologyDSM.py#L530-L538 | def utilisation(self):
"""Getter for various Utilisation variables"""
if self._utilisation is None:
api = "SYNO.Core.System.Utilization"
url = "%s/entry.cgi?api=%s&version=1&method=get" % (
self.base_url,
api)
self._utilisation =... | [
"def",
"utilisation",
"(",
"self",
")",
":",
"if",
"self",
".",
"_utilisation",
"is",
"None",
":",
"api",
"=",
"\"SYNO.Core.System.Utilization\"",
"url",
"=",
"\"%s/entry.cgi?api=%s&version=1&method=get\"",
"%",
"(",
"self",
".",
"base_url",
",",
"api",
")",
"se... | Getter for various Utilisation variables | [
"Getter",
"for",
"various",
"Utilisation",
"variables"
] | python | test | 42.444444 |
apache/spark | python/pyspark/mllib/linalg/distributed.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/linalg/distributed.py#L401-L414 | def U(self):
"""
Returns a distributed matrix whose columns are the left
singular vectors of the SingularValueDecomposition if computeU was set to be True.
"""
u = self.call("U")
if u is not None:
mat_name = u.getClass().getSimpleName()
if mat_name... | [
"def",
"U",
"(",
"self",
")",
":",
"u",
"=",
"self",
".",
"call",
"(",
"\"U\"",
")",
"if",
"u",
"is",
"not",
"None",
":",
"mat_name",
"=",
"u",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
"if",
"mat_name",
"==",
"\"RowMatrix\"",
":... | Returns a distributed matrix whose columns are the left
singular vectors of the SingularValueDecomposition if computeU was set to be True. | [
"Returns",
"a",
"distributed",
"matrix",
"whose",
"columns",
"are",
"the",
"left",
"singular",
"vectors",
"of",
"the",
"SingularValueDecomposition",
"if",
"computeU",
"was",
"set",
"to",
"be",
"True",
"."
] | python | train | 39.857143 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/init.py | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/init.py#L69-L74 | def set_api_key(config, key):
"""Configure a new API key."""
if not key and "X-Api-Key" in config.api_key:
del config.api_key["X-Api-Key"]
else:
config.api_key["X-Api-Key"] = key | [
"def",
"set_api_key",
"(",
"config",
",",
"key",
")",
":",
"if",
"not",
"key",
"and",
"\"X-Api-Key\"",
"in",
"config",
".",
"api_key",
":",
"del",
"config",
".",
"api_key",
"[",
"\"X-Api-Key\"",
"]",
"else",
":",
"config",
".",
"api_key",
"[",
"\"X-Api-K... | Configure a new API key. | [
"Configure",
"a",
"new",
"API",
"key",
"."
] | python | train | 33.5 |
SmokinCaterpillar/pypet | pypet/trajectory.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/trajectory.py#L2180-L2218 | def _merge_single_runs(self, other_trajectory, used_runs):
""" Updates the `run_information` of the current trajectory."""
count = len(self) # Variable to count the increasing new run indices and create
# new run names
run_indices = range(len(other_trajectory))
run_name_dict ... | [
"def",
"_merge_single_runs",
"(",
"self",
",",
"other_trajectory",
",",
"used_runs",
")",
":",
"count",
"=",
"len",
"(",
"self",
")",
"# Variable to count the increasing new run indices and create",
"# new run names",
"run_indices",
"=",
"range",
"(",
"len",
"(",
"oth... | Updates the `run_information` of the current trajectory. | [
"Updates",
"the",
"run_information",
"of",
"the",
"current",
"trajectory",
"."
] | python | test | 41.538462 |
AmesCornish/buttersink | buttersink/BestDiffs.py | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/BestDiffs.py#L110-L153 | def analyze(self, chunkSize, *sinks):
""" Figure out the best diffs to use to reach all our required volumes. """
measureSize = False
if self.measureSize:
for sink in sinks:
if sink.isRemote:
measureSize = True
# Use destination (already ... | [
"def",
"analyze",
"(",
"self",
",",
"chunkSize",
",",
"*",
"sinks",
")",
":",
"measureSize",
"=",
"False",
"if",
"self",
".",
"measureSize",
":",
"for",
"sink",
"in",
"sinks",
":",
"if",
"sink",
".",
"isRemote",
":",
"measureSize",
"=",
"True",
"# Use ... | Figure out the best diffs to use to reach all our required volumes. | [
"Figure",
"out",
"the",
"best",
"diffs",
"to",
"use",
"to",
"reach",
"all",
"our",
"required",
"volumes",
"."
] | python | train | 30.409091 |
anchore/anchore | anchore/cli/system.py | https://github.com/anchore/anchore/blob/8a4d5b9708e27856312d303aae3f04f3c72039d6/anchore/cli/system.py#L211-L285 | def importdb(indir):
"""Import a previously exported anchore DB"""
ecode = 0
try:
imgdir = os.path.join(indir, "images")
feeddir = os.path.join(indir, "feeds")
storedir = os.path.join(indir, "storedfiles")
for d in [indir, imgdir, feeddir, storedir]:
if not os.pa... | [
"def",
"importdb",
"(",
"indir",
")",
":",
"ecode",
"=",
"0",
"try",
":",
"imgdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"indir",
",",
"\"images\"",
")",
"feeddir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"indir",
",",
"\"feeds\"",
")",
"s... | Import a previously exported anchore DB | [
"Import",
"a",
"previously",
"exported",
"anchore",
"DB"
] | python | train | 42.333333 |
oceanprotocol/squid-py | squid_py/brizo/brizo.py | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/brizo/brizo.py#L99-L132 | def consume_service(service_agreement_id, service_endpoint, account, files,
destination_folder, index=None):
"""
Call the brizo endpoint to get access to the different files that form the asset.
:param service_agreement_id: Service Agreement Id, str
:param servic... | [
"def",
"consume_service",
"(",
"service_agreement_id",
",",
"service_endpoint",
",",
"account",
",",
"files",
",",
"destination_folder",
",",
"index",
"=",
"None",
")",
":",
"signature",
"=",
"Keeper",
".",
"get_instance",
"(",
")",
".",
"sign_hash",
"(",
"ser... | Call the brizo endpoint to get access to the different files that form the asset.
:param service_agreement_id: Service Agreement Id, str
:param service_endpoint: Url to consume, str
:param account: Account instance of the consumer signing this agreement, hex-str
:param files: List conta... | [
"Call",
"the",
"brizo",
"endpoint",
"to",
"get",
"access",
"to",
"the",
"different",
"files",
"that",
"form",
"the",
"asset",
"."
] | python | train | 62.205882 |
albu/albumentations | albumentations/augmentations/functional.py | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L35-L44 | def preserve_shape(func):
"""Preserve shape of the image."""
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
result = result.reshape(shape)
return result
return wrapped_function | [
"def",
"preserve_shape",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_function",
"(",
"img",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"shape",
"=",
"img",
".",
"shape",
"result",
"=",
"func",
"(",
"img",
",",
... | Preserve shape of the image. | [
"Preserve",
"shape",
"of",
"the",
"image",
"."
] | python | train | 28 |
FujiMakoto/AgentML | agentml/parser/trigger/condition/__init__.py | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/trigger/condition/__init__.py#L189-L242 | def evaluate(self, agentml, user=None):
"""
Evaluate the conditional statement and return its contents if a successful evaluation takes place
:param user: The active user object
:type user: agentml.User or None
:param agentml: The active AgentML instance
:type ... | [
"def",
"evaluate",
"(",
"self",
",",
"agentml",
",",
"user",
"=",
"None",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"'Evaluating conditional statement: {statement}'",
".",
"format",
"(",
"statement",
"=",
"' '",
".",
"join",
"(",
"filter",
"(",
"No... | Evaluate the conditional statement and return its contents if a successful evaluation takes place
:param user: The active user object
:type user: agentml.User or None
:param agentml: The active AgentML instance
:type agentml: AgentML
:return: Condition contents if the... | [
"Evaluate",
"the",
"conditional",
"statement",
"and",
"return",
"its",
"contents",
"if",
"a",
"successful",
"evaluation",
"takes",
"place",
":",
"param",
"user",
":",
"The",
"active",
"user",
"object",
":",
"type",
"user",
":",
"agentml",
".",
"User",
"or",
... | python | train | 37.722222 |
flaper87/python-gerrit | gerrit/filters.py | https://github.com/flaper87/python-gerrit/blob/34fcd6d98f31b35280f29c353ad8098905ba4b39/gerrit/filters.py#L20-L30 | def add_flags(self, *flags):
"""Adds one or more flags to the query.
For example:
current-patch-set -> --current-patch-set
"""
if not isinstance(flags, (list, tuple)):
flags = [str(flags)]
self.extend(["--%s" % f for f in flags])
return self | [
"def",
"add_flags",
"(",
"self",
",",
"*",
"flags",
")",
":",
"if",
"not",
"isinstance",
"(",
"flags",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"flags",
"=",
"[",
"str",
"(",
"flags",
")",
"]",
"self",
".",
"extend",
"(",
"[",
"\"--%s\"",
... | Adds one or more flags to the query.
For example:
current-patch-set -> --current-patch-set | [
"Adds",
"one",
"or",
"more",
"flags",
"to",
"the",
"query",
"."
] | python | train | 27.727273 |
Parquery/icontract | icontract/_represent.py | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L101-L109 | def visit_ListComp(self, node: ast.ListComp) -> None:
"""Represent the list comprehension by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.... | [
"def",
"visit_ListComp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"ListComp",
")",
"->",
"None",
":",
"if",
"node",
"in",
"self",
".",
"_recomputed_values",
":",
"value",
"=",
"self",
".",
"_recomputed_values",
"[",
"node",
"]",
"text",
"=",
"self",
... | Represent the list comprehension by dumping its source code. | [
"Represent",
"the",
"list",
"comprehension",
"by",
"dumping",
"its",
"source",
"code",
"."
] | python | train | 37.333333 |
bitcaster-io/bitcaster | src/bitcaster/messages.py | https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/messages.py#L54-L57 | def debug(self, request, message, extra_tags='', fail_silently=False):
"""Add a message with the ``DEBUG`` level."""
add(self.target_name, request, constants.DEBUG, message, extra_tags=extra_tags,
fail_silently=fail_silently) | [
"def",
"debug",
"(",
"self",
",",
"request",
",",
"message",
",",
"extra_tags",
"=",
"''",
",",
"fail_silently",
"=",
"False",
")",
":",
"add",
"(",
"self",
".",
"target_name",
",",
"request",
",",
"constants",
".",
"DEBUG",
",",
"message",
",",
"extra... | Add a message with the ``DEBUG`` level. | [
"Add",
"a",
"message",
"with",
"the",
"DEBUG",
"level",
"."
] | python | train | 62.5 |
wummel/linkchecker | linkcheck/checker/urlbase.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/checker/urlbase.py#L526-L535 | def add_size_info (self):
"""Set size of URL content (if any)..
Should be overridden in subclasses."""
maxbytes = self.aggregate.config["maxfilesizedownload"]
if self.size > maxbytes:
self.add_warning(
_("Content size %(size)s is larger than %(maxbytes)s.") %
... | [
"def",
"add_size_info",
"(",
"self",
")",
":",
"maxbytes",
"=",
"self",
".",
"aggregate",
".",
"config",
"[",
"\"maxfilesizedownload\"",
"]",
"if",
"self",
".",
"size",
">",
"maxbytes",
":",
"self",
".",
"add_warning",
"(",
"_",
"(",
"\"Content size %(size)s... | Set size of URL content (if any)..
Should be overridden in subclasses. | [
"Set",
"size",
"of",
"URL",
"content",
"(",
"if",
"any",
")",
"..",
"Should",
"be",
"overridden",
"in",
"subclasses",
"."
] | python | train | 48.1 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1544-L1562 | def strings(self, minSize = 4, maxSize = 1024):
"""
Extract ASCII strings from the process memory.
@type minSize: int
@param minSize: (Optional) Minimum size of the strings to search for.
@type maxSize: int
@param maxSize: (Optional) Maximum size of the strings to sea... | [
"def",
"strings",
"(",
"self",
",",
"minSize",
"=",
"4",
",",
"maxSize",
"=",
"1024",
")",
":",
"return",
"Search",
".",
"extract_ascii_strings",
"(",
"self",
",",
"minSize",
"=",
"minSize",
",",
"maxSize",
"=",
"maxSize",
")"
] | Extract ASCII strings from the process memory.
@type minSize: int
@param minSize: (Optional) Minimum size of the strings to search for.
@type maxSize: int
@param maxSize: (Optional) Maximum size of the strings to search for.
@rtype: iterator of tuple(int, int, str)
... | [
"Extract",
"ASCII",
"strings",
"from",
"the",
"process",
"memory",
"."
] | python | train | 39.894737 |
collectiveacuity/labPack | labpack/records/settings.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/settings.py#L319-L386 | def compile_settings(model_path, file_path, ignore_errors=False):
''' a method to compile configuration values from different sources
NOTE: method searches the environment variables, a local
configuration path and the default values for a jsonmodel
object for valid ... | [
"def",
"compile_settings",
"(",
"model_path",
",",
"file_path",
",",
"ignore_errors",
"=",
"False",
")",
":",
"# construct configuration model and default details\r",
"from",
"jsonmodel",
".",
"validators",
"import",
"jsonModel",
"config_model",
"=",
"jsonModel",
"(",
"... | a method to compile configuration values from different sources
NOTE: method searches the environment variables, a local
configuration path and the default values for a jsonmodel
object for valid configuration values. if an environmental
variable or key in... | [
"a",
"method",
"to",
"compile",
"configuration",
"values",
"from",
"different",
"sources",
"NOTE",
":",
"method",
"searches",
"the",
"environment",
"variables",
"a",
"local",
"configuration",
"path",
"and",
"the",
"default",
"values",
"for",
"a",
"jsonmodel",
"o... | python | train | 38.955882 |
MolSSI-BSE/basis_set_exchange | basis_set_exchange/references.py | https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/references.py#L8-L52 | def compact_references(basis_dict, ref_data):
"""
Creates a mapping of elements to reference keys
A list is returned, with each element of the list being a dictionary
with entries 'reference_info' containing data for (possibly) multiple references,
and 'elements' which is a list of element Z number... | [
"def",
"compact_references",
"(",
"basis_dict",
",",
"ref_data",
")",
":",
"element_refs",
"=",
"[",
"]",
"# Create a mapping of elements -> reference information",
"# (sort by Z first, keeping in mind Z is a string)",
"sorted_el",
"=",
"sorted",
"(",
"basis_dict",
"[",
"'ele... | Creates a mapping of elements to reference keys
A list is returned, with each element of the list being a dictionary
with entries 'reference_info' containing data for (possibly) multiple references,
and 'elements' which is a list of element Z numbers
that those references apply to
Parameters
-... | [
"Creates",
"a",
"mapping",
"of",
"elements",
"to",
"reference",
"keys"
] | python | train | 34.511111 |
IBMStreams/pypi.streamsx | streamsx/spl/toolkit.py | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/toolkit.py#L25-L36 | def add_toolkit(topology, location):
"""Add an SPL toolkit to a topology.
Args:
topology(Topology): Topology to include toolkit in.
location(str): Location of the toolkit directory.
"""
import streamsx.topology.topology
assert isinstance(topology, streamsx.topology.topology.Topology... | [
"def",
"add_toolkit",
"(",
"topology",
",",
"location",
")",
":",
"import",
"streamsx",
".",
"topology",
".",
"topology",
"assert",
"isinstance",
"(",
"topology",
",",
"streamsx",
".",
"topology",
".",
"topology",
".",
"Topology",
")",
"tkinfo",
"=",
"dict",... | Add an SPL toolkit to a topology.
Args:
topology(Topology): Topology to include toolkit in.
location(str): Location of the toolkit directory. | [
"Add",
"an",
"SPL",
"toolkit",
"to",
"a",
"topology",
"."
] | python | train | 35.416667 |
Nukesor/pueue | pueue/daemon/logger.py | https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/logger.py#L131-L152 | def remove_old(self, max_log_time):
"""Remove all logs which are older than the specified time."""
files = glob.glob('{}/queue-*'.format(self.log_dir))
files = list(map(lambda x: os.path.basename(x), files))
for log_file in files:
# Get time stamp from filename
n... | [
"def",
"remove_old",
"(",
"self",
",",
"max_log_time",
")",
":",
"files",
"=",
"glob",
".",
"glob",
"(",
"'{}/queue-*'",
".",
"format",
"(",
"self",
".",
"log_dir",
")",
")",
"files",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"os",
".",
"pa... | Remove all logs which are older than the specified time. | [
"Remove",
"all",
"logs",
"which",
"are",
"older",
"than",
"the",
"specified",
"time",
"."
] | python | train | 40.045455 |
talkincode/toughlib | toughlib/paginator.py | https://github.com/talkincode/toughlib/blob/1c2f7dde3a7f101248f1b5f5d428cc85466995cf/toughlib/paginator.py#L26-L75 | def render(self, form_id=None):
'''
动态输出html内容
'''
page_bar = self.page_bars.get(int(self.page / 10))
if page_bar is None:
return ''
_htmls = []
if form_id:
_htmls.append(u'''<script>
function goto_page(form_id,page){
... | [
"def",
"render",
"(",
"self",
",",
"form_id",
"=",
"None",
")",
":",
"page_bar",
"=",
"self",
".",
"page_bars",
".",
"get",
"(",
"int",
"(",
"self",
".",
"page",
"/",
"10",
")",
")",
"if",
"page_bar",
"is",
"None",
":",
"return",
"''",
"_htmls",
... | 动态输出html内容 | [
"动态输出html内容"
] | python | train | 42.24 |
scanny/python-pptx | pptx/shapes/autoshape.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/shapes/autoshape.py#L342-L356 | def shape_type(self):
"""
Unique integer identifying the type of this shape, like
``MSO_SHAPE_TYPE.TEXT_BOX``.
"""
if self.is_placeholder:
return MSO_SHAPE_TYPE.PLACEHOLDER
if self._sp.has_custom_geometry:
return MSO_SHAPE_TYPE.FREEFORM
if ... | [
"def",
"shape_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_placeholder",
":",
"return",
"MSO_SHAPE_TYPE",
".",
"PLACEHOLDER",
"if",
"self",
".",
"_sp",
".",
"has_custom_geometry",
":",
"return",
"MSO_SHAPE_TYPE",
".",
"FREEFORM",
"if",
"self",
".",
"... | Unique integer identifying the type of this shape, like
``MSO_SHAPE_TYPE.TEXT_BOX``. | [
"Unique",
"integer",
"identifying",
"the",
"type",
"of",
"this",
"shape",
"like",
"MSO_SHAPE_TYPE",
".",
"TEXT_BOX",
"."
] | python | train | 36.333333 |
dade-ai/snipy | snipy/flags.py | https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/flags.py#L151-L172 | def add_flag(*args, **kwargs):
"""
define a single flag.
add_flag(flagname, default_value, help='', **kwargs)
add_flag([(flagname, default_value, help), ...])
or
define flags without help message
add_flag(flagname, default_value, help='', **kwargs)
add_flag('gpu', 1, help='CUDA_VISIBLE_... | [
"def",
"add_flag",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"a",
"in",
"args",
"[",
... | define a single flag.
add_flag(flagname, default_value, help='', **kwargs)
add_flag([(flagname, default_value, help), ...])
or
define flags without help message
add_flag(flagname, default_value, help='', **kwargs)
add_flag('gpu', 1, help='CUDA_VISIBLE_DEVICES')
:param args:
:param kwarg... | [
"define",
"a",
"single",
"flag",
".",
"add_flag",
"(",
"flagname",
"default_value",
"help",
"=",
"**",
"kwargs",
")",
"add_flag",
"(",
"[",
"(",
"flagname",
"default_value",
"help",
")",
"...",
"]",
")",
"or",
"define",
"flags",
"without",
"help",
"message... | python | valid | 27.954545 |
pyviz/holoviews | holoviews/core/layout.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/layout.py#L168-L183 | def relabel(self, label=None, group=None, depth=1):
"""Clone object and apply new group and/or label.
Applies relabeling to child up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to re... | [
"def",
"relabel",
"(",
"self",
",",
"label",
"=",
"None",
",",
"group",
"=",
"None",
",",
"depth",
"=",
"1",
")",
":",
"return",
"super",
"(",
"AdjointLayout",
",",
"self",
")",
".",
"relabel",
"(",
"label",
"=",
"label",
",",
"group",
"=",
"group"... | Clone object and apply new group and/or label.
Applies relabeling to child up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to returned object
depth (int, optional): Depth to which... | [
"Clone",
"object",
"and",
"apply",
"new",
"group",
"and",
"/",
"or",
"label",
"."
] | python | train | 42.4375 |
PrefPy/prefpy | prefpy/mov.py | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mov.py#L368-L397 | def getMaximinScores(profile):
"""
Returns a dictionary that associates integer representations of each candidate with their
Copeland score.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Currently, we expect the profile to contain complete ordering over can... | [
"def",
"getMaximinScores",
"(",
"profile",
")",
":",
"# Currently, we expect the profile to contain complete ordering over candidates. Ties are",
"# allowed however.",
"elecType",
"=",
"profile",
".",
"getElecType",
"(",
")",
"if",
"elecType",
"!=",
"\"soc\"",
"and",
"elecTyp... | Returns a dictionary that associates integer representations of each candidate with their
Copeland score.
:ivar Profile profile: A Profile object that represents an election profile. | [
"Returns",
"a",
"dictionary",
"that",
"associates",
"integer",
"representations",
"of",
"each",
"candidate",
"with",
"their",
"Copeland",
"score",
"."
] | python | train | 38.066667 |
Diaoul/subliminal | subliminal/refiners/tvdb.py | https://github.com/Diaoul/subliminal/blob/a952dfb2032eb0fd6eb1eb89f04080923c11c4cf/subliminal/refiners/tvdb.py#L96-L107 | def login(self):
"""Login"""
# perform the request
data = {'apikey': self.apikey, 'username': self.username, 'password': self.password}
r = self.session.post(self.base_url + '/login', json=data)
r.raise_for_status()
# set the Authorization header
self.session.hea... | [
"def",
"login",
"(",
"self",
")",
":",
"# perform the request",
"data",
"=",
"{",
"'apikey'",
":",
"self",
".",
"apikey",
",",
"'username'",
":",
"self",
".",
"username",
",",
"'password'",
":",
"self",
".",
"password",
"}",
"r",
"=",
"self",
".",
"ses... | Login | [
"Login"
] | python | train | 36.25 |
agile-geoscience/striplog | striplog/striplog.py | https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1429-L1444 | def get_data(self, field, function=None, default=None):
"""
Get data from the striplog.
"""
f = function or utils.null
data = []
for iv in self:
d = iv.data.get(field)
if d is None:
if default is not None:
d = de... | [
"def",
"get_data",
"(",
"self",
",",
"field",
",",
"function",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"f",
"=",
"function",
"or",
"utils",
".",
"null",
"data",
"=",
"[",
"]",
"for",
"iv",
"in",
"self",
":",
"d",
"=",
"iv",
".",
"da... | Get data from the striplog. | [
"Get",
"data",
"from",
"the",
"striplog",
"."
] | python | test | 26.5 |
radical-cybertools/radical.entk | src/radical/entk/execman/base/resource_manager.py | https://github.com/radical-cybertools/radical.entk/blob/945f6c93c9a62db90ad191b306418d5c1cdd9d24/src/radical/entk/execman/base/resource_manager.py#L198-L221 | def _populate(self):
"""
**Purpose**: Populate the ResourceManager class with the validated
resource description
"""
if self._validated:
self._prof.prof('populating rmgr', uid=self._uid)
self._logger.debug('Populating resource manager ... | [
"def",
"_populate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_validated",
":",
"self",
".",
"_prof",
".",
"prof",
"(",
"'populating rmgr'",
",",
"uid",
"=",
"self",
".",
"_uid",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Populating resource mana... | **Purpose**: Populate the ResourceManager class with the validated
resource description | [
"**",
"Purpose",
"**",
":",
"Populate",
"the",
"ResourceManager",
"class",
"with",
"the",
"validated",
"resource",
"description"
] | python | train | 40.5 |
edublancas/sklearn-evaluation | sklearn_evaluation/evaluator.py | https://github.com/edublancas/sklearn-evaluation/blob/79ee6e4dfe911b5a5a9b78a5caaed7c73eef6f39/sklearn_evaluation/evaluator.py#L92-L95 | def roc(self):
"""ROC plot
"""
return plot.roc(self.y_true, self.y_score, ax=_gen_ax()) | [
"def",
"roc",
"(",
"self",
")",
":",
"return",
"plot",
".",
"roc",
"(",
"self",
".",
"y_true",
",",
"self",
".",
"y_score",
",",
"ax",
"=",
"_gen_ax",
"(",
")",
")"
] | ROC plot | [
"ROC",
"plot"
] | python | train | 27 |
radjkarl/fancyTools | fancytools/fcollections/FIFObuffer.py | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/fcollections/FIFObuffer.py#L45-L57 | def add(self, value):
"""
Add a value to the buffer.
"""
ind = int(self._ind % self.shape)
self._pos = self._ind % self.shape
self._values[ind] = value
if self._ind < self.shape:
self._ind += 1 # fast fill
else:
self._ind += self._... | [
"def",
"add",
"(",
"self",
",",
"value",
")",
":",
"ind",
"=",
"int",
"(",
"self",
".",
"_ind",
"%",
"self",
".",
"shape",
")",
"self",
".",
"_pos",
"=",
"self",
".",
"_ind",
"%",
"self",
".",
"shape",
"self",
".",
"_values",
"[",
"ind",
"]",
... | Add a value to the buffer. | [
"Add",
"a",
"value",
"to",
"the",
"buffer",
"."
] | python | train | 30.307692 |
UCL-INGI/INGInious | inginious/agent/docker_agent/_docker_interface.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/_docker_interface.py#L162-L166 | def get_logs(self, container_id):
""" Return the full stdout/stderr of a container"""
stdout = self._docker.containers.get(container_id).logs(stdout=True, stderr=False).decode('utf8')
stderr = self._docker.containers.get(container_id).logs(stdout=False, stderr=True).decode('utf8')
return... | [
"def",
"get_logs",
"(",
"self",
",",
"container_id",
")",
":",
"stdout",
"=",
"self",
".",
"_docker",
".",
"containers",
".",
"get",
"(",
"container_id",
")",
".",
"logs",
"(",
"stdout",
"=",
"True",
",",
"stderr",
"=",
"False",
")",
".",
"decode",
"... | Return the full stdout/stderr of a container | [
"Return",
"the",
"full",
"stdout",
"/",
"stderr",
"of",
"a",
"container"
] | python | train | 66.2 |
lorien/grab | grab/document.py | https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L363-L370 | def browse(self):
"""
Save response in temporary file and open it in GUI browser.
"""
_, path = tempfile.mkstemp()
self.save(path)
webbrowser.open('file://' + path) | [
"def",
"browse",
"(",
"self",
")",
":",
"_",
",",
"path",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"self",
".",
"save",
"(",
"path",
")",
"webbrowser",
".",
"open",
"(",
"'file://'",
"+",
"path",
")"
] | Save response in temporary file and open it in GUI browser. | [
"Save",
"response",
"in",
"temporary",
"file",
"and",
"open",
"it",
"in",
"GUI",
"browser",
"."
] | python | train | 25.75 |
SmokinCaterpillar/pypet | pypet/trajectory.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/trajectory.py#L1084-L1092 | def _remove_exploration(self):
""" Called if trajectory is expanded, deletes all explored parameters from disk """
for param in self._explored_parameters.values():
if param._stored:
try:
self.f_delete_item(param)
except Exception:
... | [
"def",
"_remove_exploration",
"(",
"self",
")",
":",
"for",
"param",
"in",
"self",
".",
"_explored_parameters",
".",
"values",
"(",
")",
":",
"if",
"param",
".",
"_stored",
":",
"try",
":",
"self",
".",
"f_delete_item",
"(",
"param",
")",
"except",
"Exce... | Called if trajectory is expanded, deletes all explored parameters from disk | [
"Called",
"if",
"trajectory",
"is",
"expanded",
"deletes",
"all",
"explored",
"parameters",
"from",
"disk"
] | python | test | 51.777778 |
totalgood/pugnlp | src/pugnlp/tutil.py | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L478-L500 | def clip_datetime(dt, tz=DEFAULT_TZ, is_dst=None):
"""Limit a datetime to a valid range for datetime, datetime64, and Timestamp objects
>>> from datetime import timedelta
>>> clip_datetime(MAX_DATETIME + timedelta(100)) == pd.Timestamp(MAX_DATETIME, tz='utc') == MAX_TIMESTAMP
True
>>> MAX_TIMESTAMP
... | [
"def",
"clip_datetime",
"(",
"dt",
",",
"tz",
"=",
"DEFAULT_TZ",
",",
"is_dst",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"dt",
",",
"datetime",
".",
"datetime",
")",
":",
"# TODO: this gives up a day of datetime range due to assumptions about timezone",
"# ... | Limit a datetime to a valid range for datetime, datetime64, and Timestamp objects
>>> from datetime import timedelta
>>> clip_datetime(MAX_DATETIME + timedelta(100)) == pd.Timestamp(MAX_DATETIME, tz='utc') == MAX_TIMESTAMP
True
>>> MAX_TIMESTAMP
Timestamp('2262-04-11 23:47:16.854775+0000', tz='UTC') | [
"Limit",
"a",
"datetime",
"to",
"a",
"valid",
"range",
"for",
"datetime",
"datetime64",
"and",
"Timestamp",
"objects",
">>>",
"from",
"datetime",
"import",
"timedelta",
">>>",
"clip_datetime",
"(",
"MAX_DATETIME",
"+",
"timedelta",
"(",
"100",
"))",
"==",
"pd"... | python | train | 40.956522 |
CybOXProject/mixbox | mixbox/namespaces.py | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/namespaces.py#L453-L466 | def remove_prefix(self, prefix):
"""Removes prefix from this set. This is a no-op if the prefix
doesn't exist in it.
"""
if prefix not in self.__prefix_map:
return
ni = self.__lookup_prefix(prefix)
ni.prefixes.discard(prefix)
del self.__prefix_map[pr... | [
"def",
"remove_prefix",
"(",
"self",
",",
"prefix",
")",
":",
"if",
"prefix",
"not",
"in",
"self",
".",
"__prefix_map",
":",
"return",
"ni",
"=",
"self",
".",
"__lookup_prefix",
"(",
"prefix",
")",
"ni",
".",
"prefixes",
".",
"discard",
"(",
"prefix",
... | Removes prefix from this set. This is a no-op if the prefix
doesn't exist in it. | [
"Removes",
"prefix",
"from",
"this",
"set",
".",
"This",
"is",
"a",
"no",
"-",
"op",
"if",
"the",
"prefix",
"doesn",
"t",
"exist",
"in",
"it",
"."
] | python | train | 34.357143 |
nteract/papermill | papermill/engines.py | https://github.com/nteract/papermill/blob/7423a303f3fa22ec6d03edf5fd9700d659b5a6fa/papermill/engines.py#L178-L193 | def cell_start(self, cell, cell_index=None, **kwargs):
"""
Set and save a cell's start state.
Optionally called by engines during execution to initialize the
metadata for a cell and save the notebook to the output path.
"""
if self.log_output:
ceel_num = cell... | [
"def",
"cell_start",
"(",
"self",
",",
"cell",
",",
"cell_index",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"log_output",
":",
"ceel_num",
"=",
"cell_index",
"+",
"1",
"if",
"cell_index",
"is",
"not",
"None",
"else",
"''",
"l... | Set and save a cell's start state.
Optionally called by engines during execution to initialize the
metadata for a cell and save the notebook to the output path. | [
"Set",
"and",
"save",
"a",
"cell",
"s",
"start",
"state",
"."
] | python | train | 38.6875 |
user-cont/conu | conu/backend/podman/image.py | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/image.py#L191-L203 | def _run_container(self, run_command_instance, callback):
""" this is internal method """
tmpfile = os.path.join(get_backend_tmpdir(), random_tmp_filename())
# the cid file must not exist
run_command_instance.options += ["--cidfile=%s" % tmpfile]
logger.debug("podman command: %s"... | [
"def",
"_run_container",
"(",
"self",
",",
"run_command_instance",
",",
"callback",
")",
":",
"tmpfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_backend_tmpdir",
"(",
")",
",",
"random_tmp_filename",
"(",
")",
")",
"# the cid file must not exist",
"run_co... | this is internal method | [
"this",
"is",
"internal",
"method"
] | python | train | 53 |
buildbot/buildbot | master/buildbot/changes/hgpoller.py | https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/changes/hgpoller.py#L313-L318 | def _stopOnFailure(self, f):
"utility method to stop the service when a failure occurs"
if self.running:
d = defer.maybeDeferred(self.stopService)
d.addErrback(log.err, 'while stopping broken HgPoller service')
return f | [
"def",
"_stopOnFailure",
"(",
"self",
",",
"f",
")",
":",
"if",
"self",
".",
"running",
":",
"d",
"=",
"defer",
".",
"maybeDeferred",
"(",
"self",
".",
"stopService",
")",
"d",
".",
"addErrback",
"(",
"log",
".",
"err",
",",
"'while stopping broken HgPol... | utility method to stop the service when a failure occurs | [
"utility",
"method",
"to",
"stop",
"the",
"service",
"when",
"a",
"failure",
"occurs"
] | python | train | 43.666667 |
asyrjasalo/RESTinstance | src/REST/keywords.py | https://github.com/asyrjasalo/RESTinstance/blob/9b003ffc6a89ec4b8b6f05eeb6cc8e56aad4be4e/src/REST/keywords.py#L656-L705 | def boolean(self, field, value=None, **validations):
"""*Asserts the field as JSON boolean.*
The field consists of parts separated by spaces, the parts being
object property names or array indices starting from 0, and the root
being the instance created by the last request (see `Output`... | [
"def",
"boolean",
"(",
"self",
",",
"field",
",",
"value",
"=",
"None",
",",
"*",
"*",
"validations",
")",
":",
"values",
"=",
"[",
"]",
"for",
"found",
"in",
"self",
".",
"_find_by_field",
"(",
"field",
")",
":",
"reality",
"=",
"found",
"[",
"\"r... | *Asserts the field as JSON boolean.*
The field consists of parts separated by spaces, the parts being
object property names or array indices starting from 0, and the root
being the instance created by the last request (see `Output` for it).
For asserting deeply nested properties or mul... | [
"*",
"Asserts",
"the",
"field",
"as",
"JSON",
"boolean",
".",
"*"
] | python | train | 48.08 |
openfisca/openfisca-core | openfisca_core/taxbenefitsystems.py | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/taxbenefitsystems.py#L370-L419 | def get_package_metadata(self):
"""
Gets metatada relative to the country package the tax and benefit system is built from.
:returns: Country package metadata
:rtype: dict
Example:
>>> tax_benefit_system.get_package_metadata()
>>> {
... | [
"def",
"get_package_metadata",
"(",
"self",
")",
":",
"# Handle reforms",
"if",
"self",
".",
"baseline",
":",
"return",
"self",
".",
"baseline",
".",
"get_package_metadata",
"(",
")",
"fallback_metadata",
"=",
"{",
"'name'",
":",
"self",
".",
"__class__",
".",... | Gets metatada relative to the country package the tax and benefit system is built from.
:returns: Country package metadata
:rtype: dict
Example:
>>> tax_benefit_system.get_package_metadata()
>>> {
>>> 'location': '/path/to/dir/containing/pack... | [
"Gets",
"metatada",
"relative",
"to",
"the",
"country",
"package",
"the",
"tax",
"and",
"benefit",
"system",
"is",
"built",
"from",
"."
] | python | train | 34.5 |
blockstack/blockstack-core | blockstack/blockstackd.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2066-L2076 | def stop_server(self):
"""
Stop serving
"""
if self.api_server is not None:
try:
self.api_server.socket.shutdown(socket.SHUT_RDWR)
except:
log.warning("Failed to shut down API server socket")
self.api_server.shutdown() | [
"def",
"stop_server",
"(",
"self",
")",
":",
"if",
"self",
".",
"api_server",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"api_server",
".",
"socket",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"except",
":",
"log",
".",
"warning",
... | Stop serving | [
"Stop",
"serving"
] | python | train | 28.090909 |
SUNCAT-Center/CatHub | cathub/cli.py | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cli.py#L44-L60 | def ase(dbuser, dbpassword, args, gui):
"""Connection to atomic structures on the Catalysis-Hub
server with ase db cli.
Arguments to the the ase db cli client must be enclosed in one string.
For example: <cathub ase 'formula=Ag6In6H -s energy -L 200'>.
To see possible ase db arguments ru... | [
"def",
"ase",
"(",
"dbuser",
",",
"dbpassword",
",",
"args",
",",
"gui",
")",
":",
"if",
"dbuser",
"==",
"'upload'",
":",
"dbpassword",
"=",
"'cHyuuQH0'",
"db",
"=",
"CathubPostgreSQL",
"(",
"user",
"=",
"dbuser",
",",
"password",
"=",
"dbpassword",
")",... | Connection to atomic structures on the Catalysis-Hub
server with ase db cli.
Arguments to the the ase db cli client must be enclosed in one string.
For example: <cathub ase 'formula=Ag6In6H -s energy -L 200'>.
To see possible ase db arguments run <ase db --help> | [
"Connection",
"to",
"atomic",
"structures",
"on",
"the",
"Catalysis",
"-",
"Hub",
"server",
"with",
"ase",
"db",
"cli",
".",
"Arguments",
"to",
"the",
"the",
"ase",
"db",
"cli",
"client",
"must",
"be",
"enclosed",
"in",
"one",
"string",
".",
"For",
"exam... | python | train | 41.823529 |
GNS3/gns3-server | gns3server/controller/node.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/node.py#L508-L515 | def post(self, path, data=None, **kwargs):
"""
HTTP post on the node
"""
if data:
return (yield from self._compute.post("/projects/{}/{}/nodes/{}{}".format(self._project.id, self._node_type, self._id, path), data=data, **kwargs))
else:
return (yield from s... | [
"def",
"post",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"data",
":",
"return",
"(",
"yield",
"from",
"self",
".",
"_compute",
".",
"post",
"(",
"\"/projects/{}/{}/nodes/{}{}\"",
".",
"format",
"(",
... | HTTP post on the node | [
"HTTP",
"post",
"on",
"the",
"node"
] | python | train | 53.625 |
saltstack/salt | salt/utils/win_dacl.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_dacl.py#L1047-L1090 | def get_sid(principal):
'''
Converts a username to a sid, or verifies a sid. Required for working with
the DACL.
Args:
principal(str):
The principal to lookup the sid. Can be a sid or a username.
Returns:
PySID Object: A sid
Usage:
.. code-block:: python
... | [
"def",
"get_sid",
"(",
"principal",
")",
":",
"# If None is passed, use the Universal Well-known SID \"Null SID\"",
"if",
"principal",
"is",
"None",
":",
"principal",
"=",
"'NULL SID'",
"# Test if the user passed a sid or a name",
"try",
":",
"sid",
"=",
"salt",
".",
"uti... | Converts a username to a sid, or verifies a sid. Required for working with
the DACL.
Args:
principal(str):
The principal to lookup the sid. Can be a sid or a username.
Returns:
PySID Object: A sid
Usage:
.. code-block:: python
# Get a user's sid
salt... | [
"Converts",
"a",
"username",
"to",
"a",
"sid",
"or",
"verifies",
"a",
"sid",
".",
"Required",
"for",
"working",
"with",
"the",
"DACL",
"."
] | python | train | 25.477273 |
dereneaton/ipyrad | ipyrad/assemble/write_outfiles.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/write_outfiles.py#L1862-L1881 | def write_usnps(data, sidx, pnames):
""" write the bisnp string """
## grab bis data from tmparr
tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name))
with h5py.File(tmparrs, 'r') as io5:
bisarr = io5["bisarr"]
## trim to size b/c it was made longer than actual
... | [
"def",
"write_usnps",
"(",
"data",
",",
"sidx",
",",
"pnames",
")",
":",
"## grab bis data from tmparr",
"tmparrs",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data",
".",
"dirs",
".",
"outfiles",
",",
"\"tmp-{}.h5\"",
".",
"format",
"(",
"data",
".",
"na... | write the bisnp string | [
"write",
"the",
"bisnp",
"string"
] | python | valid | 36.9 |
openego/eDisGo | edisgo/data/import_data.py | https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/data/import_data.py#L38-L115 | def import_from_ding0(file, network):
"""
Import an eDisGo grid topology from
`Ding0 data <https://github.com/openego/ding0>`_.
This import method is specifically designed to load grid topology data in
the format as `Ding0 <https://github.com/openego/ding0>`_ provides it via
pickles.
The i... | [
"def",
"import_from_ding0",
"(",
"file",
",",
"network",
")",
":",
"# when `file` is a string, it will be read by the help of pickle",
"if",
"isinstance",
"(",
"file",
",",
"str",
")",
":",
"ding0_nd",
"=",
"load_nd_from_pickle",
"(",
"filename",
"=",
"file",
")",
"... | Import an eDisGo grid topology from
`Ding0 data <https://github.com/openego/ding0>`_.
This import method is specifically designed to load grid topology data in
the format as `Ding0 <https://github.com/openego/ding0>`_ provides it via
pickles.
The import of the grid topology includes
* the... | [
"Import",
"an",
"eDisGo",
"grid",
"topology",
"from",
"Ding0",
"data",
"<https",
":",
"//",
"github",
".",
"com",
"/",
"openego",
"/",
"ding0",
">",
"_",
"."
] | python | train | 35.769231 |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAARP/QARisk.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAARP/QARisk.py#L1313-L1320 | def plot_pnlratio(self):
"""
画出pnl比率散点图
"""
plt.scatter(x=self.pnl.sell_date.apply(str), y=self.pnl.pnl_ratio)
plt.gcf().autofmt_xdate()
return plt | [
"def",
"plot_pnlratio",
"(",
"self",
")",
":",
"plt",
".",
"scatter",
"(",
"x",
"=",
"self",
".",
"pnl",
".",
"sell_date",
".",
"apply",
"(",
"str",
")",
",",
"y",
"=",
"self",
".",
"pnl",
".",
"pnl_ratio",
")",
"plt",
".",
"gcf",
"(",
")",
"."... | 画出pnl比率散点图 | [
"画出pnl比率散点图"
] | python | train | 23.625 |
thecynic/pylutron | pylutron/__init__.py | https://github.com/thecynic/pylutron/blob/4d9222c96ef7ac7ac458031c058ad93ec31cebbf/pylutron/__init__.py#L93-L109 | def _do_login_locked(self):
"""Executes the login procedure (telnet) as well as setting up some
connection defaults like turning off the prompt, etc."""
self._telnet = telnetlib.Telnet(self._host)
self._telnet.read_until(LutronConnection.USER_PROMPT)
self._telnet.write(self._user + b'\r\n')
self... | [
"def",
"_do_login_locked",
"(",
"self",
")",
":",
"self",
".",
"_telnet",
"=",
"telnetlib",
".",
"Telnet",
"(",
"self",
".",
"_host",
")",
"self",
".",
"_telnet",
".",
"read_until",
"(",
"LutronConnection",
".",
"USER_PROMPT",
")",
"self",
".",
"_telnet",
... | Executes the login procedure (telnet) as well as setting up some
connection defaults like turning off the prompt, etc. | [
"Executes",
"the",
"login",
"procedure",
"(",
"telnet",
")",
"as",
"well",
"as",
"setting",
"up",
"some",
"connection",
"defaults",
"like",
"turning",
"off",
"the",
"prompt",
"etc",
"."
] | python | train | 43.764706 |
vatlab/SoS | src/sos/parser.py | https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L1423-L1472 | def print_help(self, script_name: str):
'''print a help message from the script'''
textWidth = max(60, shutil.get_terminal_size((80, 20)).columns)
if len(script_name) > 20:
print(f'usage: sos run {script_name}')
print(
' [workflow_name | -t ... | [
"def",
"print_help",
"(",
"self",
",",
"script_name",
":",
"str",
")",
":",
"textWidth",
"=",
"max",
"(",
"60",
",",
"shutil",
".",
"get_terminal_size",
"(",
"(",
"80",
",",
"20",
")",
")",
".",
"columns",
")",
"if",
"len",
"(",
"script_name",
")",
... | print a help message from the script | [
"print",
"a",
"help",
"message",
"from",
"the",
"script"
] | python | train | 39.32 |
Neurosim-lab/netpyne | netpyne/conversion/excel.py | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/conversion/excel.py#L19-L75 | def importConnFromExcel (fileName, sheetName):
''' Import connectivity rules from Excel sheet'''
import openpyxl as xl
# set columns
colPreTags = 0 # 'A'
colPostTags = 1 # 'B'
colConnFunc = 2 # 'C'
colSyn = 3 # 'D'
colProb = 5 # 'F'
colWeight = 6 # 'G'
colAnnot = 8 # 'I'
o... | [
"def",
"importConnFromExcel",
"(",
"fileName",
",",
"sheetName",
")",
":",
"import",
"openpyxl",
"as",
"xl",
"# set columns",
"colPreTags",
"=",
"0",
"# 'A'",
"colPostTags",
"=",
"1",
"# 'B'",
"colConnFunc",
"=",
"2",
"# 'C'",
"colSyn",
"=",
"3",
"# 'D'",
"c... | Import connectivity rules from Excel sheet | [
"Import",
"connectivity",
"rules",
"from",
"Excel",
"sheet"
] | python | train | 48.368421 |
CamDavidsonPilon/lifetimes | lifetimes/plotting.py | https://github.com/CamDavidsonPilon/lifetimes/blob/f926308bc03c17c1d12fead729de43885cf13321/lifetimes/plotting.py#L480-L567 | def plot_incremental_transactions(
model,
transactions,
datetime_col,
customer_id_col,
t,
t_cal,
datetime_format=None,
freq="D",
set_index_date=False,
title="Tracking Daily Transactions",
xlabel="day",
ylabel="Transactions",
ax=None,
**kwargs
):
"""
Plot a... | [
"def",
"plot_incremental_transactions",
"(",
"model",
",",
"transactions",
",",
"datetime_col",
",",
"customer_id_col",
",",
"t",
",",
"t_cal",
",",
"datetime_format",
"=",
"None",
",",
"freq",
"=",
"\"D\"",
",",
"set_index_date",
"=",
"False",
",",
"title",
"... | Plot a figure of the predicted and actual cumulative transactions of users.
Parameters
----------
model: lifetimes model
A fitted lifetimes model
transactions: pandas DataFrame
DataFrame containing the transactions history of the customer_id
datetime_col: str
The column in t... | [
"Plot",
"a",
"figure",
"of",
"the",
"predicted",
"and",
"actual",
"cumulative",
"transactions",
"of",
"users",
"."
] | python | train | 29.045455 |
markuskiller/textblob-de | textblob_de/ext/_pattern/text/__init__.py | https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/__init__.py#L1218-L1242 | def find_prepositions(chunked):
""" The input is a list of [token, tag, chunk]-items.
The output is a list of [token, tag, chunk, preposition]-items.
PP-chunks followed by NP-chunks make up a PNP-chunk.
"""
# Tokens that are not part of a preposition just get the O-tag.
for ch in chunked... | [
"def",
"find_prepositions",
"(",
"chunked",
")",
":",
"# Tokens that are not part of a preposition just get the O-tag.",
"for",
"ch",
"in",
"chunked",
":",
"ch",
".",
"append",
"(",
"\"O\"",
")",
"for",
"i",
",",
"chunk",
"in",
"enumerate",
"(",
"chunked",
")",
... | The input is a list of [token, tag, chunk]-items.
The output is a list of [token, tag, chunk, preposition]-items.
PP-chunks followed by NP-chunks make up a PNP-chunk. | [
"The",
"input",
"is",
"a",
"list",
"of",
"[",
"token",
"tag",
"chunk",
"]",
"-",
"items",
".",
"The",
"output",
"is",
"a",
"list",
"of",
"[",
"token",
"tag",
"chunk",
"preposition",
"]",
"-",
"items",
".",
"PP",
"-",
"chunks",
"followed",
"by",
"NP... | python | train | 44.44 |
numenta/nupic | src/nupic/algorithms/backtracking_tm_cpp.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm_cpp.py#L625-L646 | def getSegmentOnCell(self, c, i, segIdx):
"""
Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentOnCell`.
"""
segList = self.cells4.getNonEmptySegList(c,i)
seg = self.cells4.getSegment(c, i, segList[segIdx])
numSyn = seg.size()
assert numSyn != 0
# Accumulate seg... | [
"def",
"getSegmentOnCell",
"(",
"self",
",",
"c",
",",
"i",
",",
"segIdx",
")",
":",
"segList",
"=",
"self",
".",
"cells4",
".",
"getNonEmptySegList",
"(",
"c",
",",
"i",
")",
"seg",
"=",
"self",
".",
"cells4",
".",
"getSegment",
"(",
"c",
",",
"i"... | Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentOnCell`. | [
"Overrides",
":",
"meth",
":",
"nupic",
".",
"algorithms",
".",
"backtracking_tm",
".",
"BacktrackingTM",
".",
"getSegmentOnCell",
"."
] | python | valid | 35.818182 |
gabstopper/smc-python | smc-monitoring/smc_monitoring/models/query.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc-monitoring/smc_monitoring/models/query.py#L309-L322 | def fetch_live(self, formatter=TableFormat):
"""
Fetch a live stream query. This is the equivalent of selecting
the "Play" option for monitoring fields within the SMC UI. Data will
be streamed back in real time.
:param formatter: Formatter type for data representation. A... | [
"def",
"fetch_live",
"(",
"self",
",",
"formatter",
"=",
"TableFormat",
")",
":",
"fmt",
"=",
"formatter",
"(",
"self",
")",
"for",
"results",
"in",
"self",
".",
"execute",
"(",
")",
":",
"if",
"'records'",
"in",
"results",
"and",
"results",
"[",
"'rec... | Fetch a live stream query. This is the equivalent of selecting
the "Play" option for monitoring fields within the SMC UI. Data will
be streamed back in real time.
:param formatter: Formatter type for data representation. Any type
in :py:mod:`smc_monitoring.models.formatters`... | [
"Fetch",
"a",
"live",
"stream",
"query",
".",
"This",
"is",
"the",
"equivalent",
"of",
"selecting",
"the",
"Play",
"option",
"for",
"monitoring",
"fields",
"within",
"the",
"SMC",
"UI",
".",
"Data",
"will",
"be",
"streamed",
"back",
"in",
"real",
"time",
... | python | train | 46.857143 |
cloudtools/troposphere | troposphere/__init__.py | https://github.com/cloudtools/troposphere/blob/f7ea5591a7c287a843adc9c184d2f56064cfc632/troposphere/__init__.py#L710-L723 | def set_parameter_label(self, parameter, label):
"""
Sets the Label used in the User Interface for the given parameter.
:type parameter: str or Parameter
:type label: str
"""
labels = self.metadata\
.setdefault("AWS::CloudFormation::Interface", {})\
... | [
"def",
"set_parameter_label",
"(",
"self",
",",
"parameter",
",",
"label",
")",
":",
"labels",
"=",
"self",
".",
"metadata",
".",
"setdefault",
"(",
"\"AWS::CloudFormation::Interface\"",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"\"ParameterLabels\"",
",",
"... | Sets the Label used in the User Interface for the given parameter.
:type parameter: str or Parameter
:type label: str | [
"Sets",
"the",
"Label",
"used",
"in",
"the",
"User",
"Interface",
"for",
"the",
"given",
"parameter",
".",
":",
"type",
"parameter",
":",
"str",
"or",
"Parameter",
":",
"type",
"label",
":",
"str"
] | python | train | 34.357143 |
dfiel/greenwavereality | greenwavereality/greenwavereality.py | https://github.com/dfiel/greenwavereality/blob/cb2c0328385eb7afda910cc483266086432fb708/greenwavereality/greenwavereality.py#L22-L37 | def set_brightness(host, did, value, token=None):
"""Set brightness of a bulb or fixture."""
urllib3.disable_warnings()
if token:
scheme = "https"
if not token:
scheme = "http"
token = "1234567890"
url = (
scheme + '://' + host + '/gwr/gop.php?cmd=DeviceSendComman... | [
"def",
"set_brightness",
"(",
"host",
",",
"did",
",",
"value",
",",
"token",
"=",
"None",
")",
":",
"urllib3",
".",
"disable_warnings",
"(",
")",
"if",
"token",
":",
"scheme",
"=",
"\"https\"",
"if",
"not",
"token",
":",
"scheme",
"=",
"\"http\"",
"to... | Set brightness of a bulb or fixture. | [
"Set",
"brightness",
"of",
"a",
"bulb",
"or",
"fixture",
"."
] | python | train | 37.4375 |
heuer/segno | segno/utils.py | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/utils.py#L214-L286 | def matrix_iter_detail(matrix, version, scale=1, border=None):
"""\
Returns an iterator / generator over the provided matrix which includes
the border and the scaling factor.
This iterator / generator returns different values for dark / light modules
and therefor the different parts (like the finde... | [
"def",
"matrix_iter_detail",
"(",
"matrix",
",",
"version",
",",
"scale",
"=",
"1",
",",
"border",
"=",
"None",
")",
":",
"from",
"segno",
"import",
"encoder",
"check_valid_border",
"(",
"border",
")",
"scale",
"=",
"int",
"(",
"scale",
")",
"check_valid_s... | \
Returns an iterator / generator over the provided matrix which includes
the border and the scaling factor.
This iterator / generator returns different values for dark / light modules
and therefor the different parts (like the finder patterns, alignment patterns etc.)
are distinguishable. If this ... | [
"\\",
"Returns",
"an",
"iterator",
"/",
"generator",
"over",
"the",
"provided",
"matrix",
"which",
"includes",
"the",
"border",
"and",
"the",
"scaling",
"factor",
"."
] | python | train | 49.931507 |
frascoweb/frasco | frasco/actions/common.py | https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/actions/common.py#L122-L129 | def incr_obj(obj, **attrs):
"""Increments context variables
"""
for name, value in attrs.iteritems():
v = getattr(obj, name, None)
if not hasattr(obj, name) or v is None:
v = 0
setattr(obj, name, v + value) | [
"def",
"incr_obj",
"(",
"obj",
",",
"*",
"*",
"attrs",
")",
":",
"for",
"name",
",",
"value",
"in",
"attrs",
".",
"iteritems",
"(",
")",
":",
"v",
"=",
"getattr",
"(",
"obj",
",",
"name",
",",
"None",
")",
"if",
"not",
"hasattr",
"(",
"obj",
",... | Increments context variables | [
"Increments",
"context",
"variables"
] | python | train | 30.875 |
jic-dtool/dtoolcore | dtoolcore/__init__.py | https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/__init__.py#L50-L69 | def generate_admin_metadata(name, creator_username=None):
"""Return admin metadata as a dictionary."""
if not dtoolcore.utils.name_is_valid(name):
raise(DtoolCoreInvalidNameError())
if creator_username is None:
creator_username = dtoolcore.utils.getuser()
datetime_obj = datetime.datet... | [
"def",
"generate_admin_metadata",
"(",
"name",
",",
"creator_username",
"=",
"None",
")",
":",
"if",
"not",
"dtoolcore",
".",
"utils",
".",
"name_is_valid",
"(",
"name",
")",
":",
"raise",
"(",
"DtoolCoreInvalidNameError",
"(",
")",
")",
"if",
"creator_usernam... | Return admin metadata as a dictionary. | [
"Return",
"admin",
"metadata",
"as",
"a",
"dictionary",
"."
] | python | train | 30.4 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L181-L220 | def get_setting(self, key, converter=None, choices=None):
'''Returns the settings value for the provided key.
If converter is str, unicode, bool or int the settings value will be
returned converted to the provided type.
If choices is an instance of list or tuple its item at position of t... | [
"def",
"get_setting",
"(",
"self",
",",
"key",
",",
"converter",
"=",
"None",
",",
"choices",
"=",
"None",
")",
":",
"#TODO: allow pickling of settings items?",
"# TODO: STUB THIS OUT ON CLI",
"value",
"=",
"self",
".",
"addon",
".",
"getSetting",
"(",
"id",
"="... | Returns the settings value for the provided key.
If converter is str, unicode, bool or int the settings value will be
returned converted to the provided type.
If choices is an instance of list or tuple its item at position of the
settings value be returned.
.. note:: It is sugges... | [
"Returns",
"the",
"settings",
"value",
"for",
"the",
"provided",
"key",
".",
"If",
"converter",
"is",
"str",
"unicode",
"bool",
"or",
"int",
"the",
"settings",
"value",
"will",
"be",
"returned",
"converted",
"to",
"the",
"provided",
"type",
".",
"If",
"cho... | python | train | 45.925 |
Onyo/jsonbender | jsonbender/core.py | https://github.com/Onyo/jsonbender/blob/df85ec444be3185d346db894402ca6eaa38dd947/jsonbender/core.py#L216-L227 | def bend(mapping, source, context=None):
"""
The main bending function.
mapping: the map of benders
source: a dict to be bent
returns a new dict according to the provided map.
"""
context = {} if context is None else context
transport = Transport(source, context)
return _bend(mappi... | [
"def",
"bend",
"(",
"mapping",
",",
"source",
",",
"context",
"=",
"None",
")",
":",
"context",
"=",
"{",
"}",
"if",
"context",
"is",
"None",
"else",
"context",
"transport",
"=",
"Transport",
"(",
"source",
",",
"context",
")",
"return",
"_bend",
"(",
... | The main bending function.
mapping: the map of benders
source: a dict to be bent
returns a new dict according to the provided map. | [
"The",
"main",
"bending",
"function",
"."
] | python | train | 26.916667 |
deep-compute/deeputil | deeputil/keep_running.py | https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/keep_running.py#L10-L171 | def keeprunning(wait_secs=0, exit_on_success=False,
on_success=None, on_error=None, on_done=None):
'''
Example 1: dosomething needs to run until completion condition
without needing to have a loop in its code. Also, when error
happens, we should NOT terminate execution
>>> from deep... | [
"def",
"keeprunning",
"(",
"wait_secs",
"=",
"0",
",",
"exit_on_success",
"=",
"False",
",",
"on_success",
"=",
"None",
",",
"on_error",
"=",
"None",
",",
"on_done",
"=",
"None",
")",
":",
"def",
"decfn",
"(",
"fn",
")",
":",
"def",
"_call_callback",
"... | Example 1: dosomething needs to run until completion condition
without needing to have a loop in its code. Also, when error
happens, we should NOT terminate execution
>>> from deeputil import AttrDict
>>> @keeprunning(wait_secs=1)
... def dosomething(state):
... state.i += 1
... pri... | [
"Example",
"1",
":",
"dosomething",
"needs",
"to",
"run",
"until",
"completion",
"condition",
"without",
"needing",
"to",
"have",
"a",
"loop",
"in",
"its",
"code",
".",
"Also",
"when",
"error",
"happens",
"we",
"should",
"NOT",
"terminate",
"execution"
] | python | train | 28.969136 |
coursera-dl/coursera-dl | coursera/network.py | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/network.py#L61-L93 | def get_page(session,
url,
json=False,
post=False,
data=None,
headers=None,
quiet=False,
**kwargs):
"""
Download an HTML page using the requests session.
@param session: Requests session.
@type session: requests.... | [
"def",
"get_page",
"(",
"session",
",",
"url",
",",
"json",
"=",
"False",
",",
"post",
"=",
"False",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"quiet",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"url",
".",
"... | Download an HTML page using the requests session.
@param session: Requests session.
@type session: requests.Session
@param url: URL pattern with optional keywords to format.
@type url: str
@param post: Flag that indicates whether POST request should be sent.
@type post: bool
@param data:... | [
"Download",
"an",
"HTML",
"page",
"using",
"the",
"requests",
"session",
"."
] | python | train | 27.272727 |
django-ldapdb/django-ldapdb | ldapdb/models/fields.py | https://github.com/django-ldapdb/django-ldapdb/blob/f3a35d3c8e42e7799d71e5d156ab97fb69e6b479/ldapdb/models/fields.py#L113-L134 | def get_db_prep_value(self, value, connection, prepared=False):
"""Prepare a value for DB interaction.
Returns:
- list(bytes) if not prepared
- list(str) if prepared
"""
if prepared:
return value
if value is None:
return []
value... | [
"def",
"get_db_prep_value",
"(",
"self",
",",
"value",
",",
"connection",
",",
"prepared",
"=",
"False",
")",
":",
"if",
"prepared",
":",
"return",
"value",
"if",
"value",
"is",
"None",
":",
"return",
"[",
"]",
"values",
"=",
"value",
"if",
"self",
"."... | Prepare a value for DB interaction.
Returns:
- list(bytes) if not prepared
- list(str) if prepared | [
"Prepare",
"a",
"value",
"for",
"DB",
"interaction",
"."
] | python | train | 33.5 |
michaeljoseph/changes | changes/prompt.py | https://github.com/michaeljoseph/changes/blob/a8beb409671c58cdf28ee913bad0a5c7d5374ade/changes/prompt.py#L8-L63 | def choose_labels(alternatives):
"""
Prompt the user select several labels from the provided alternatives.
At least one label must be selected.
:param list alternatives: Sequence of options that are available to select from
:return: Several selected labels
"""
if not alternatives:
... | [
"def",
"choose_labels",
"(",
"alternatives",
")",
":",
"if",
"not",
"alternatives",
":",
"raise",
"ValueError",
"if",
"not",
"isinstance",
"(",
"alternatives",
",",
"list",
")",
":",
"raise",
"TypeError",
"choice_map",
"=",
"OrderedDict",
"(",
"(",
"'{}'",
"... | Prompt the user select several labels from the provided alternatives.
At least one label must be selected.
:param list alternatives: Sequence of options that are available to select from
:return: Several selected labels | [
"Prompt",
"the",
"user",
"select",
"several",
"labels",
"from",
"the",
"provided",
"alternatives",
"."
] | python | train | 29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.