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 |
|---|---|---|---|---|---|---|---|---|---|
haifengat/hf_ctp_py_proxy | generate/generate_enum_cs.py | https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/generate/generate_enum_cs.py#L127-L145 | def process_typedef(self, line):
"""处理类型申明"""
content = line.split(' ')
type_ = self.type_dict[content[1]]
if type_ == 'c_char' and '[' in line:
# type_ = 'string'
type_ = '%s*%s' % (type_, line[line.index('[') + 1:line.index(']')])
keyword = content[2]
... | [
"def",
"process_typedef",
"(",
"self",
",",
"line",
")",
":",
"content",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"type_",
"=",
"self",
".",
"type_dict",
"[",
"content",
"[",
"1",
"]",
"]",
"if",
"type_",
"==",
"'c_char'",
"and",
"'['",
"in",
"l... | 处理类型申明 | [
"处理类型申明"
] | python | train | 29.526316 |
cmbruns/pyopenvr | src/openvr/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L2718-L2746 | def getOutputDevice(self, textureType):
"""
* Returns platform- and texture-type specific adapter identification so that applications and the
compositor are creating textures and swap chains on the same GPU. If an error occurs the device
will be set to 0.
pInstance is an optional... | [
"def",
"getOutputDevice",
"(",
"self",
",",
"textureType",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getOutputDevice",
"pnDevice",
"=",
"c_uint64",
"(",
")",
"pInstance",
"=",
"VkInstance_T",
"(",
")",
"fn",
"(",
"byref",
"(",
"pnDevice",
"... | * Returns platform- and texture-type specific adapter identification so that applications and the
compositor are creating textures and swap chains on the same GPU. If an error occurs the device
will be set to 0.
pInstance is an optional parameter that is required only when textureType is Texture... | [
"*",
"Returns",
"platform",
"-",
"and",
"texture",
"-",
"type",
"specific",
"adapter",
"identification",
"so",
"that",
"applications",
"and",
"the",
"compositor",
"are",
"creating",
"textures",
"and",
"swap",
"chains",
"on",
"the",
"same",
"GPU",
".",
"If",
... | python | train | 66.827586 |
chrisjrn/registrasion | registrasion/forms.py | https://github.com/chrisjrn/registrasion/blob/461d5846c6f9f3b7099322a94f5d9911564448e4/registrasion/forms.py#L367-L379 | def initial_data(cls, product_quantities):
''' Prepares initial data for an instance of this form.
product_quantities is a sequence of (product,quantity) tuples '''
f = [
{
_ItemQuantityProductsForm.CHOICE_FIELD: product.id,
_ItemQuantityProductsForm.... | [
"def",
"initial_data",
"(",
"cls",
",",
"product_quantities",
")",
":",
"f",
"=",
"[",
"{",
"_ItemQuantityProductsForm",
".",
"CHOICE_FIELD",
":",
"product",
".",
"id",
",",
"_ItemQuantityProductsForm",
".",
"QUANTITY_FIELD",
":",
"quantity",
",",
"}",
"for",
... | Prepares initial data for an instance of this form.
product_quantities is a sequence of (product,quantity) tuples | [
"Prepares",
"initial",
"data",
"for",
"an",
"instance",
"of",
"this",
"form",
".",
"product_quantities",
"is",
"a",
"sequence",
"of",
"(",
"product",
"quantity",
")",
"tuples"
] | python | test | 35.230769 |
arista-eosplus/pyeapi | pyeapi/api/interfaces.py | https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/api/interfaces.py#L790-L806 | def set_lacp_timeout(self, name, value=None):
"""Configures the Port-Channel LACP fallback timeout
The fallback timeout configures the period an interface in
fallback mode remains in LACP mode without receiving a PDU.
Args:
name(str): The Port-Channel interface name
... | [
"def",
"set_lacp_timeout",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
")",
":",
"commands",
"=",
"[",
"'interface %s'",
"%",
"name",
"]",
"string",
"=",
"'port-channel lacp fallback timeout'",
"commands",
".",
"append",
"(",
"self",
".",
"command_bui... | Configures the Port-Channel LACP fallback timeout
The fallback timeout configures the period an interface in
fallback mode remains in LACP mode without receiving a PDU.
Args:
name(str): The Port-Channel interface name
value(int): port-channel lacp fallback timeout... | [
"Configures",
"the",
"Port",
"-",
"Channel",
"LACP",
"fallback",
"timeout",
"The",
"fallback",
"timeout",
"configures",
"the",
"period",
"an",
"interface",
"in",
"fallback",
"mode",
"remains",
"in",
"LACP",
"mode",
"without",
"receiving",
"a",
"PDU",
"."
] | python | train | 39.823529 |
wavycloud/pyboto3 | pyboto3/cognitoidentityprovider.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/cognitoidentityprovider.py#L3948-L4095 | def update_user_pool_client(UserPoolId=None, ClientId=None, ClientName=None, RefreshTokenValidity=None, ReadAttributes=None, WriteAttributes=None, ExplicitAuthFlows=None, SupportedIdentityProviders=None, CallbackURLs=None, LogoutURLs=None, DefaultRedirectURI=None, AllowedOAuthFlows=None, AllowedOAuthScopes=None, Allowe... | [
"def",
"update_user_pool_client",
"(",
"UserPoolId",
"=",
"None",
",",
"ClientId",
"=",
"None",
",",
"ClientName",
"=",
"None",
",",
"RefreshTokenValidity",
"=",
"None",
",",
"ReadAttributes",
"=",
"None",
",",
"WriteAttributes",
"=",
"None",
",",
"ExplicitAuthF... | Allows the developer to update the specified user pool client and password policy.
See also: AWS API Documentation
:example: response = client.update_user_pool_client(
UserPoolId='string',
ClientId='string',
ClientName='string',
RefreshTokenValidity=123,
ReadAtt... | [
"Allows",
"the",
"developer",
"to",
"update",
"the",
"specified",
"user",
"pool",
"client",
"and",
"password",
"policy",
".",
"See",
"also",
":",
"AWS",
"API",
"Documentation",
":",
"example",
":",
"response",
"=",
"client",
".",
"update_user_pool_client",
"("... | python | train | 32.587838 |
xoolive/traffic | traffic/core/flight.py | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/flight.py#L205-L216 | def flight_id(self) -> Optional[str]:
"""Returns the unique flight_id value(s) of the DataFrame.
If you know how to split flights, you may want to append such a column
in the DataFrame.
"""
if "flight_id" not in self.data.columns:
return None
tmp = set(self.d... | [
"def",
"flight_id",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"\"flight_id\"",
"not",
"in",
"self",
".",
"data",
".",
"columns",
":",
"return",
"None",
"tmp",
"=",
"set",
"(",
"self",
".",
"data",
".",
"flight_id",
")",
"if",
... | Returns the unique flight_id value(s) of the DataFrame.
If you know how to split flights, you may want to append such a column
in the DataFrame. | [
"Returns",
"the",
"unique",
"flight_id",
"value",
"(",
"s",
")",
"of",
"the",
"DataFrame",
"."
] | python | train | 37.416667 |
opennode/waldur-core | waldur_core/server/admin/dashboard.py | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/server/admin/dashboard.py#L56-L65 | def _get_app_config(self, app_name):
"""
Returns an app config for the given name, not by label.
"""
matches = [app_config for app_config in apps.get_app_configs()
if app_config.name == app_name]
if not matches:
return
return matches[0] | [
"def",
"_get_app_config",
"(",
"self",
",",
"app_name",
")",
":",
"matches",
"=",
"[",
"app_config",
"for",
"app_config",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
"if",
"app_config",
".",
"name",
"==",
"app_name",
"]",
"if",
"not",
"matches",
":",
... | Returns an app config for the given name, not by label. | [
"Returns",
"an",
"app",
"config",
"for",
"the",
"given",
"name",
"not",
"by",
"label",
"."
] | python | train | 30.7 |
hydpy-dev/hydpy | hydpy/models/dam/dam_model.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/dam/dam_model.py#L296-L379 | def calc_requiredremotesupply_v1(self):
"""Calculate the required maximum supply from another location
that can be discharged into the dam.
Required control parameters:
|HighestRemoteSupply|
|WaterLevelSupplyThreshold|
Required derived parameter:
|WaterLevelSupplySmoothPar|
Requ... | [
"def",
"calc_requiredremotesupply_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fl... | Calculate the required maximum supply from another location
that can be discharged into the dam.
Required control parameters:
|HighestRemoteSupply|
|WaterLevelSupplyThreshold|
Required derived parameter:
|WaterLevelSupplySmoothPar|
Required aide sequence:
|WaterLevel|
Cal... | [
"Calculate",
"the",
"required",
"maximum",
"supply",
"from",
"another",
"location",
"that",
"can",
"be",
"discharged",
"into",
"the",
"dam",
"."
] | python | train | 40.464286 |
project-rig/rig | rig/place_and_route/route/ner.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/place_and_route/route/ner.py#L436-L514 | def avoid_dead_links(root, machine, wrap_around=False):
"""Modify a RoutingTree to route-around dead links in a Machine.
Uses A* to reconnect disconnected branches of the tree (due to dead links
in the machine).
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingT... | [
"def",
"avoid_dead_links",
"(",
"root",
",",
"machine",
",",
"wrap_around",
"=",
"False",
")",
":",
"# Make a copy of the RoutingTree with all broken parts disconnected",
"root",
",",
"lookup",
",",
"broken_links",
"=",
"copy_and_disconnect_tree",
"(",
"root",
",",
"mac... | Modify a RoutingTree to route-around dead links in a Machine.
Uses A* to reconnect disconnected branches of the tree (due to dead links
in the machine).
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingTree`
The root of the RoutingTree which contains nothing... | [
"Modify",
"a",
"RoutingTree",
"to",
"route",
"-",
"around",
"dead",
"links",
"in",
"a",
"Machine",
"."
] | python | train | 45.35443 |
inveniosoftware/invenio-communities | invenio_communities/receivers.py | https://github.com/inveniosoftware/invenio-communities/blob/5c4de6783724d276ae1b6dd13a399a9e22fadc7a/invenio_communities/receivers.py#L36-L39 | def new_request(sender, request=None, notify=True, **kwargs):
"""New request for inclusion."""
if current_app.config['COMMUNITIES_MAIL_ENABLED'] and notify:
send_community_request_email(request) | [
"def",
"new_request",
"(",
"sender",
",",
"request",
"=",
"None",
",",
"notify",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"current_app",
".",
"config",
"[",
"'COMMUNITIES_MAIL_ENABLED'",
"]",
"and",
"notify",
":",
"send_community_request_email",
... | New request for inclusion. | [
"New",
"request",
"for",
"inclusion",
"."
] | python | train | 51.75 |
pylast/pylast | src/pylast/__init__.py | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1266-L1293 | def get_weekly_charts(self, chart_kind, from_date=None, to_date=None):
"""
Returns the weekly charts for the week starting from the
from_date value to the to_date value.
chart_kind should be one of "album", "artist" or "track"
"""
method = ".getWeekly" + chart_kind.title(... | [
"def",
"get_weekly_charts",
"(",
"self",
",",
"chart_kind",
",",
"from_date",
"=",
"None",
",",
"to_date",
"=",
"None",
")",
":",
"method",
"=",
"\".getWeekly\"",
"+",
"chart_kind",
".",
"title",
"(",
")",
"+",
"\"Chart\"",
"chart_type",
"=",
"eval",
"(",
... | Returns the weekly charts for the week starting from the
from_date value to the to_date value.
chart_kind should be one of "album", "artist" or "track" | [
"Returns",
"the",
"weekly",
"charts",
"for",
"the",
"week",
"starting",
"from",
"the",
"from_date",
"value",
"to",
"the",
"to_date",
"value",
".",
"chart_kind",
"should",
"be",
"one",
"of",
"album",
"artist",
"or",
"track"
] | python | train | 37.642857 |
ResidentMario/geoplot | geoplot/geoplot.py | https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2377-L2428 | def _discrete_colorize(categorical, hue, scheme, k, cmap, vmin, vmax):
"""
Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical
ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we
assume ... | [
"def",
"_discrete_colorize",
"(",
"categorical",
",",
"hue",
",",
"scheme",
",",
"k",
",",
"cmap",
",",
"vmin",
",",
"vmax",
")",
":",
"if",
"not",
"categorical",
":",
"binning",
"=",
"_mapclassify_choro",
"(",
"hue",
",",
"scheme",
",",
"k",
"=",
"k",... | Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical
ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we
assume that the input data is categorical.
This code makes extensive use of ``geopand... | [
"Creates",
"a",
"discrete",
"colormap",
"either",
"using",
"an",
"already",
"-",
"categorical",
"data",
"variable",
"or",
"by",
"bucketing",
"a",
"non",
"-",
"categorical",
"ordinal",
"one",
".",
"If",
"a",
"scheme",
"is",
"provided",
"we",
"compute",
"a",
... | python | train | 53.173077 |
jreese/tasky | tasky/tasks/task.py | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/tasks/task.py#L71-L77 | async def sleep(self, duration: float=0.0) -> None:
'''Simple wrapper around `asyncio.sleep()`.'''
duration = max(0, duration)
if duration > 0:
Log.debug('sleeping task %s for %.1f seconds', self.name, duration)
await asyncio.sleep(duration) | [
"async",
"def",
"sleep",
"(",
"self",
",",
"duration",
":",
"float",
"=",
"0.0",
")",
"->",
"None",
":",
"duration",
"=",
"max",
"(",
"0",
",",
"duration",
")",
"if",
"duration",
">",
"0",
":",
"Log",
".",
"debug",
"(",
"'sleeping task %s for %.1f seco... | Simple wrapper around `asyncio.sleep()`. | [
"Simple",
"wrapper",
"around",
"asyncio",
".",
"sleep",
"()",
"."
] | python | train | 40.571429 |
softlayer/softlayer-python | SoftLayer/CLI/dedicatedhost/create_options.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/create_options.py#L22-L61 | def cli(env, **kwargs):
"""host order options for a given dedicated host.
To get a list of available backend routers see example:
slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB
"""
mgr = SoftLayer.DedicatedHostManager(env.client)
tables = []
if not kwargs[... | [
"def",
"cli",
"(",
"env",
",",
"*",
"*",
"kwargs",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"DedicatedHostManager",
"(",
"env",
".",
"client",
")",
"tables",
"=",
"[",
"]",
"if",
"not",
"kwargs",
"[",
"'flavor'",
"]",
"and",
"not",
"kwargs",
"[",
"'... | host order options for a given dedicated host.
To get a list of available backend routers see example:
slcli dh create-options --datacenter dal05 --flavor 56_CORES_X_242_RAM_X_1_4_TB | [
"host",
"order",
"options",
"for",
"a",
"given",
"dedicated",
"host",
"."
] | python | train | 41.4 |
pandas-dev/pandas | pandas/core/arrays/timedeltas.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/timedeltas.py#L990-L1023 | def objects_to_td64ns(data, unit="ns", errors="raise"):
"""
Convert a object-dtyped or string-dtyped array into an
timedelta64[ns]-dtyped array.
Parameters
----------
data : ndarray or Index
unit : str, default "ns"
The timedelta unit to treat integers as multiples of.
errors : ... | [
"def",
"objects_to_td64ns",
"(",
"data",
",",
"unit",
"=",
"\"ns\"",
",",
"errors",
"=",
"\"raise\"",
")",
":",
"# coerce Index to np.ndarray, converting string-dtype if necessary",
"values",
"=",
"np",
".",
"array",
"(",
"data",
",",
"dtype",
"=",
"np",
".",
"o... | Convert a object-dtyped or string-dtyped array into an
timedelta64[ns]-dtyped array.
Parameters
----------
data : ndarray or Index
unit : str, default "ns"
The timedelta unit to treat integers as multiples of.
errors : {"raise", "coerce", "ignore"}, default "raise"
How to handle... | [
"Convert",
"a",
"object",
"-",
"dtyped",
"or",
"string",
"-",
"dtyped",
"array",
"into",
"an",
"timedelta64",
"[",
"ns",
"]",
"-",
"dtyped",
"array",
"."
] | python | train | 32.323529 |
bitcraft/pyscroll | pyscroll/data.py | https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/pyscroll/data.py#L370-L404 | def get_tile_images_by_rect(self, rect):
""" Speed up data access
More efficient because data is accessed and cached locally
"""
def rev(seq, start, stop):
if start < 0:
start = 0
return enumerate(seq[start:stop + 1], start)
x1, y1, x2, ... | [
"def",
"get_tile_images_by_rect",
"(",
"self",
",",
"rect",
")",
":",
"def",
"rev",
"(",
"seq",
",",
"start",
",",
"stop",
")",
":",
"if",
"start",
"<",
"0",
":",
"start",
"=",
"0",
"return",
"enumerate",
"(",
"seq",
"[",
"start",
":",
"stop",
"+",... | Speed up data access
More efficient because data is accessed and cached locally | [
"Speed",
"up",
"data",
"access"
] | python | train | 36.4 |
pallets/werkzeug | src/werkzeug/datastructures.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2120-L2131 | def as_set(self, preserve_casing=False):
"""Return the set as real python set type. When calling this, all
the items are converted to lowercase and the ordering is lost.
:param preserve_casing: if set to `True` the items in the set returned
will have the origina... | [
"def",
"as_set",
"(",
"self",
",",
"preserve_casing",
"=",
"False",
")",
":",
"if",
"preserve_casing",
":",
"return",
"set",
"(",
"self",
".",
"_headers",
")",
"return",
"set",
"(",
"self",
".",
"_set",
")"
] | Return the set as real python set type. When calling this, all
the items are converted to lowercase and the ordering is lost.
:param preserve_casing: if set to `True` the items in the set returned
will have the original case like in the
:... | [
"Return",
"the",
"set",
"as",
"real",
"python",
"set",
"type",
".",
"When",
"calling",
"this",
"all",
"the",
"items",
"are",
"converted",
"to",
"lowercase",
"and",
"the",
"ordering",
"is",
"lost",
"."
] | python | train | 46.083333 |
yougov/motivation | motivation/commands.py | https://github.com/yougov/motivation/blob/6239c750ef2180b7d89fcbf9867e87a1ee33af16/motivation/commands.py#L100-L108 | def danke(client, event, channel, nick, rest):
'Danke schön!'
if rest:
rest = rest.strip()
Karma.store.change(rest, 1)
rcpt = rest
else:
rcpt = channel
return f'Danke schön, {rcpt}! Danke schön!' | [
"def",
"danke",
"(",
"client",
",",
"event",
",",
"channel",
",",
"nick",
",",
"rest",
")",
":",
"if",
"rest",
":",
"rest",
"=",
"rest",
".",
"strip",
"(",
")",
"Karma",
".",
"store",
".",
"change",
"(",
"rest",
",",
"1",
")",
"rcpt",
"=",
"res... | Danke schön! | [
"Danke",
"schön!"
] | python | test | 26.111111 |
FulcrumTechnologies/pyconfluence | pyconfluence/actions.py | https://github.com/FulcrumTechnologies/pyconfluence/blob/a999726dbc1cbdd3d9062234698eeae799ce84ce/pyconfluence/actions.py#L133-L139 | def get_page_content(id):
"""Return XHTML content of a page.
Parameters:
- id: id of a Confluence page.
"""
data = _json.loads(_api.rest("/" + str(id) + "?expand=body.storage"))
return data["body"]["storage"]["value"] | [
"def",
"get_page_content",
"(",
"id",
")",
":",
"data",
"=",
"_json",
".",
"loads",
"(",
"_api",
".",
"rest",
"(",
"\"/\"",
"+",
"str",
"(",
"id",
")",
"+",
"\"?expand=body.storage\"",
")",
")",
"return",
"data",
"[",
"\"body\"",
"]",
"[",
"\"storage\"... | Return XHTML content of a page.
Parameters:
- id: id of a Confluence page. | [
"Return",
"XHTML",
"content",
"of",
"a",
"page",
".",
"Parameters",
":",
"-",
"id",
":",
"id",
"of",
"a",
"Confluence",
"page",
"."
] | python | train | 33.571429 |
wonambi-python/wonambi | wonambi/trans/select.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/select.py#L179-L267 | def select(data, trial=None, invert=False, **axes_to_select):
"""Define the selection of trials, using ranges or actual values.
Parameters
----------
data : instance of Data
data to select from.
trial : list of int or ndarray (dtype='i'), optional
index of trials of interest
**a... | [
"def",
"select",
"(",
"data",
",",
"trial",
"=",
"None",
",",
"invert",
"=",
"False",
",",
"*",
"*",
"axes_to_select",
")",
":",
"if",
"trial",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"trial",
",",
"Iterable",
")",
":",
"raise",
"TypeEr... | Define the selection of trials, using ranges or actual values.
Parameters
----------
data : instance of Data
data to select from.
trial : list of int or ndarray (dtype='i'), optional
index of trials of interest
**axes_to_select, optional
Values need to be tuple or list. If t... | [
"Define",
"the",
"selection",
"of",
"trials",
"using",
"ranges",
"or",
"actual",
"values",
"."
] | python | train | 37.910112 |
zhmcclient/python-zhmcclient | zhmcclient/_user_role.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_user_role.py#L276-L349 | def add_permission(self, permitted_object, include_members=False,
view_only=True):
"""
Add permission for the specified permitted object(s) to this User Role,
thereby granting that permission to all users that have this User Role.
The granted permission depends on... | [
"def",
"add_permission",
"(",
"self",
",",
"permitted_object",
",",
"include_members",
"=",
"False",
",",
"view_only",
"=",
"True",
")",
":",
"# noqa: E501",
"if",
"isinstance",
"(",
"permitted_object",
",",
"BaseResource",
")",
":",
"perm_obj",
"=",
"permitted_... | Add permission for the specified permitted object(s) to this User Role,
thereby granting that permission to all users that have this User Role.
The granted permission depends on the resource class of the permitted
object(s):
* For Task resources, the granted permission is task permissi... | [
"Add",
"permission",
"for",
"the",
"specified",
"permitted",
"object",
"(",
"s",
")",
"to",
"this",
"User",
"Role",
"thereby",
"granting",
"that",
"permission",
"to",
"all",
"users",
"that",
"have",
"this",
"User",
"Role",
"."
] | python | train | 37.432432 |
aio-libs/aioredis | aioredis/pool.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/pool.py#L276-L287 | async def select(self, db):
"""Changes db index for all free connections.
All previously acquired connections will be closed when released.
"""
res = True
async with self._cond:
for i in range(self.freesize):
res = res and (await self._pool[i].select(... | [
"async",
"def",
"select",
"(",
"self",
",",
"db",
")",
":",
"res",
"=",
"True",
"async",
"with",
"self",
".",
"_cond",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"freesize",
")",
":",
"res",
"=",
"res",
"and",
"(",
"await",
"self",
".",
... | Changes db index for all free connections.
All previously acquired connections will be closed when released. | [
"Changes",
"db",
"index",
"for",
"all",
"free",
"connections",
"."
] | python | train | 31.666667 |
SoCo/SoCo | soco/core.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L798-L810 | def night_mode(self):
"""bool: The speaker's night mode.
True if on, False if off, None if not supported.
"""
if not self.is_soundbar:
return None
response = self.renderingControl.GetEQ([
('InstanceID', 0),
('EQType', 'NightMode')
])
... | [
"def",
"night_mode",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_soundbar",
":",
"return",
"None",
"response",
"=",
"self",
".",
"renderingControl",
".",
"GetEQ",
"(",
"[",
"(",
"'InstanceID'",
",",
"0",
")",
",",
"(",
"'EQType'",
",",
"'Night... | bool: The speaker's night mode.
True if on, False if off, None if not supported. | [
"bool",
":",
"The",
"speaker",
"s",
"night",
"mode",
"."
] | python | train | 27.538462 |
EntilZha/PyFunctional | functional/transformations.py | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/transformations.py#L23-L32 | def name(function):
"""
Retrieve a pretty name for the function
:param function: function to get name from
:return: pretty name
"""
if isinstance(function, types.FunctionType):
return function.__name__
else:
return str(function) | [
"def",
"name",
"(",
"function",
")",
":",
"if",
"isinstance",
"(",
"function",
",",
"types",
".",
"FunctionType",
")",
":",
"return",
"function",
".",
"__name__",
"else",
":",
"return",
"str",
"(",
"function",
")"
] | Retrieve a pretty name for the function
:param function: function to get name from
:return: pretty name | [
"Retrieve",
"a",
"pretty",
"name",
"for",
"the",
"function",
":",
"param",
"function",
":",
"function",
"to",
"get",
"name",
"from",
":",
"return",
":",
"pretty",
"name"
] | python | train | 26.3 |
boriel/zxbasic | arch/zx48k/translator.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/translator.py#L89-L99 | def add_string_label(self, str_):
""" Maps ("folds") the given string, returning an unique label ID.
This allows several constant labels to be initialized to the same address
thus saving memory space.
:param str_: the string to map
:return: the unique label ID
"""
... | [
"def",
"add_string_label",
"(",
"self",
",",
"str_",
")",
":",
"if",
"self",
".",
"STRING_LABELS",
".",
"get",
"(",
"str_",
",",
"None",
")",
"is",
"None",
":",
"self",
".",
"STRING_LABELS",
"[",
"str_",
"]",
"=",
"backend",
".",
"tmp_label",
"(",
")... | Maps ("folds") the given string, returning an unique label ID.
This allows several constant labels to be initialized to the same address
thus saving memory space.
:param str_: the string to map
:return: the unique label ID | [
"Maps",
"(",
"folds",
")",
"the",
"given",
"string",
"returning",
"an",
"unique",
"label",
"ID",
".",
"This",
"allows",
"several",
"constant",
"labels",
"to",
"be",
"initialized",
"to",
"the",
"same",
"address",
"thus",
"saving",
"memory",
"space",
".",
":... | python | train | 41.545455 |
genicam/harvesters | src/harvesters/core.py | https://github.com/genicam/harvesters/blob/c3314a7f9d320bbf943e599aabac02521cd8e80b/src/harvesters/core.py#L651-L662 | def width(self):
"""
:return: The width of the data component in the buffer in number of pixels.
"""
try:
if self._part:
value = self._part.width
else:
value = self._buffer.width
except InvalidParameterException:
... | [
"def",
"width",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"_part",
":",
"value",
"=",
"self",
".",
"_part",
".",
"width",
"else",
":",
"value",
"=",
"self",
".",
"_buffer",
".",
"width",
"except",
"InvalidParameterException",
":",
"value",
... | :return: The width of the data component in the buffer in number of pixels. | [
":",
"return",
":",
"The",
"width",
"of",
"the",
"data",
"component",
"in",
"the",
"buffer",
"in",
"number",
"of",
"pixels",
"."
] | python | valid | 30.416667 |
fboender/ansible-cmdb | lib/jsonxs.py | https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/jsonxs.py#L130-L174 | def jsonxs(data, expr, action=ACTION_GET, value=None, default=None):
"""
Get, set, delete values in a JSON structure. `expr` is a JSONpath-like
expression pointing to the desired value. `action` determines the action to
perform. See the module-level `ACTION_*` constants. `value` should be given
if a... | [
"def",
"jsonxs",
"(",
"data",
",",
"expr",
",",
"action",
"=",
"ACTION_GET",
",",
"value",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"tokens",
"=",
"tokenize",
"(",
"expr",
")",
"# Walk through the list of tokens to reach the correct path in the data",
... | Get, set, delete values in a JSON structure. `expr` is a JSONpath-like
expression pointing to the desired value. `action` determines the action to
perform. See the module-level `ACTION_*` constants. `value` should be given
if action is `ACTION_SET`. If `default` is set and `expr` isn't found,
return `de... | [
"Get",
"set",
"delete",
"values",
"in",
"a",
"JSON",
"structure",
".",
"expr",
"is",
"a",
"JSONpath",
"-",
"like",
"expression",
"pointing",
"to",
"the",
"desired",
"value",
".",
"action",
"determines",
"the",
"action",
"to",
"perform",
".",
"See",
"the",
... | python | train | 36 |
paramiko/paramiko | paramiko/channel.py | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L286-L309 | def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0):
"""
Resize the pseudo-terminal. This can be used to change the width and
height of the terminal emulation created in a previous `get_pty` call.
:param int width: new width (in characters) of the terminal screen... | [
"def",
"resize_pty",
"(",
"self",
",",
"width",
"=",
"80",
",",
"height",
"=",
"24",
",",
"width_pixels",
"=",
"0",
",",
"height_pixels",
"=",
"0",
")",
":",
"m",
"=",
"Message",
"(",
")",
"m",
".",
"add_byte",
"(",
"cMSG_CHANNEL_REQUEST",
")",
"m",
... | Resize the pseudo-terminal. This can be used to change the width and
height of the terminal emulation created in a previous `get_pty` call.
:param int width: new width (in characters) of the terminal screen
:param int height: new height (in characters) of the terminal screen
:param int... | [
"Resize",
"the",
"pseudo",
"-",
"terminal",
".",
"This",
"can",
"be",
"used",
"to",
"change",
"the",
"width",
"and",
"height",
"of",
"the",
"terminal",
"emulation",
"created",
"in",
"a",
"previous",
"get_pty",
"call",
"."
] | python | train | 41.166667 |
stevearc/dynamo3 | dynamo3/result.py | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L233-L251 | def _update_capacity(self, data):
""" Update the consumed capacity metrics """
if 'ConsumedCapacity' in data:
# This is all for backwards compatibility
consumed = data['ConsumedCapacity']
if not isinstance(consumed, list):
consumed = [consumed]
... | [
"def",
"_update_capacity",
"(",
"self",
",",
"data",
")",
":",
"if",
"'ConsumedCapacity'",
"in",
"data",
":",
"# This is all for backwards compatibility",
"consumed",
"=",
"data",
"[",
"'ConsumedCapacity'",
"]",
"if",
"not",
"isinstance",
"(",
"consumed",
",",
"li... | Update the consumed capacity metrics | [
"Update",
"the",
"consumed",
"capacity",
"metrics"
] | python | train | 52.947368 |
chaoss/grimoirelab-cereslib | cereslib/enrich/enrich.py | https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L429-L445 | def enrich(self, column):
""" This enricher returns the same dataframe
with a new column named 'domain'.
That column is the result of splitting the
email address of another column. If there is
not a proper email address an 'unknown'
domain is returned.
:param col... | [
"def",
"enrich",
"(",
"self",
",",
"column",
")",
":",
"if",
"column",
"not",
"in",
"self",
".",
"data",
".",
"columns",
":",
"return",
"self",
".",
"data",
"self",
".",
"data",
"[",
"'domain'",
"]",
"=",
"self",
".",
"data",
"[",
"column",
"]",
... | This enricher returns the same dataframe
with a new column named 'domain'.
That column is the result of splitting the
email address of another column. If there is
not a proper email address an 'unknown'
domain is returned.
:param column: column where the text to analyze ... | [
"This",
"enricher",
"returns",
"the",
"same",
"dataframe",
"with",
"a",
"new",
"column",
"named",
"domain",
".",
"That",
"column",
"is",
"the",
"result",
"of",
"splitting",
"the",
"email",
"address",
"of",
"another",
"column",
".",
"If",
"there",
"is",
"no... | python | train | 33.882353 |
niklasf/python-chess | chess/__init__.py | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L782-L786 | def is_pinned(self, color: Color, square: Square) -> bool:
"""
Detects if the given square is pinned to the king of the given color.
"""
return self.pin_mask(color, square) != BB_ALL | [
"def",
"is_pinned",
"(",
"self",
",",
"color",
":",
"Color",
",",
"square",
":",
"Square",
")",
"->",
"bool",
":",
"return",
"self",
".",
"pin_mask",
"(",
"color",
",",
"square",
")",
"!=",
"BB_ALL"
] | Detects if the given square is pinned to the king of the given color. | [
"Detects",
"if",
"the",
"given",
"square",
"is",
"pinned",
"to",
"the",
"king",
"of",
"the",
"given",
"color",
"."
] | python | train | 42 |
aliyun/aliyun-odps-python-sdk | odps/tunnel/pb/output_stream.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/tunnel/pb/output_stream.py#L74-L80 | def append_var_uint32(self, value):
"""Appends an unsigned 32-bit integer to the internal buffer,
encoded as a varint.
"""
if not 0 <= value <= wire_format.UINT32_MAX:
raise errors.EncodeError('Value out of range: %d' % value)
self.append_var_uint64(value) | [
"def",
"append_var_uint32",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"0",
"<=",
"value",
"<=",
"wire_format",
".",
"UINT32_MAX",
":",
"raise",
"errors",
".",
"EncodeError",
"(",
"'Value out of range: %d'",
"%",
"value",
")",
"self",
".",
"append_var... | Appends an unsigned 32-bit integer to the internal buffer,
encoded as a varint. | [
"Appends",
"an",
"unsigned",
"32",
"-",
"bit",
"integer",
"to",
"the",
"internal",
"buffer",
"encoded",
"as",
"a",
"varint",
"."
] | python | train | 43.142857 |
trailofbits/protofuzz | protofuzz/values.py | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/values.py#L39-L63 | def _fuzzdb_get_strings(max_len=0):
'Helper to get all the strings from fuzzdb'
ignored = ['integer-overflow']
for subdir in pkg_resources.resource_listdir('protofuzz', BASE_PATH):
if subdir in ignored:
continue
path = '{}/{}'.format(BASE_PATH, subdir)
listing = pkg_re... | [
"def",
"_fuzzdb_get_strings",
"(",
"max_len",
"=",
"0",
")",
":",
"ignored",
"=",
"[",
"'integer-overflow'",
"]",
"for",
"subdir",
"in",
"pkg_resources",
".",
"resource_listdir",
"(",
"'protofuzz'",
",",
"BASE_PATH",
")",
":",
"if",
"subdir",
"in",
"ignored",
... | Helper to get all the strings from fuzzdb | [
"Helper",
"to",
"get",
"all",
"the",
"strings",
"from",
"fuzzdb"
] | python | train | 33.72 |
radjkarl/fancyTools | fancytools/os/runAsAdmin.py | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/os/runAsAdmin.py#L9-L61 | def runAsAdmin(cmdLine=None, target_dir='', wait=True):
"""
run [cmdLine] as admin
specify the location from where the code is executed through [target_dir]
"""
if os.name != 'nt':
raise RuntimeError("This function is only implemented on Windows.")
# import win32api,
import win32con
... | [
"def",
"runAsAdmin",
"(",
"cmdLine",
"=",
"None",
",",
"target_dir",
"=",
"''",
",",
"wait",
"=",
"True",
")",
":",
"if",
"os",
".",
"name",
"!=",
"'nt'",
":",
"raise",
"RuntimeError",
"(",
"\"This function is only implemented on Windows.\"",
")",
"# import wi... | run [cmdLine] as admin
specify the location from where the code is executed through [target_dir] | [
"run",
"[",
"cmdLine",
"]",
"as",
"admin",
"specify",
"the",
"location",
"from",
"where",
"the",
"code",
"is",
"executed",
"through",
"[",
"target_dir",
"]"
] | python | train | 35.981132 |
Groundworkstech/pybfd | pybfd/bfd.py | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L564-L572 | def has_gap_in_elf_shndx(self):
"""Return the has gap in elf shndx attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.HAS_GAP_IN_ELF_SHNDX) | [
"def",
"has_gap_in_elf_shndx",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"HAS_GAP... | Return the has gap in elf shndx attribute of the BFD file being
processed. | [
"Return",
"the",
"has",
"gap",
"in",
"elf",
"shndx",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | python | train | 34.222222 |
googledatalab/pydatalab | datalab/storage/_api.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_api.py#L165-L180 | def objects_copy(self, source_bucket, source_key, target_bucket, target_key):
"""Updates the metadata associated with an object.
Args:
source_bucket: the name of the bucket containing the source object.
source_key: the key of the source object being copied.
target_bucket: the name of the buck... | [
"def",
"objects_copy",
"(",
"self",
",",
"source_bucket",
",",
"source_key",
",",
"target_bucket",
",",
"target_key",
")",
":",
"url",
"=",
"Api",
".",
"_ENDPOINT",
"+",
"(",
"Api",
".",
"_OBJECT_COPY_PATH",
"%",
"(",
"source_bucket",
",",
"Api",
".",
"_es... | Updates the metadata associated with an object.
Args:
source_bucket: the name of the bucket containing the source object.
source_key: the key of the source object being copied.
target_bucket: the name of the bucket that will contain the copied object.
target_key: the key of the copied objec... | [
"Updates",
"the",
"metadata",
"associated",
"with",
"an",
"object",
"."
] | python | train | 51 |
facelessuser/soupsieve | soupsieve/util.py | https://github.com/facelessuser/soupsieve/blob/24859cc3e756ebf46b75547d49c6b4a7bf35ee82/soupsieve/util.py#L178-L213 | def warn_quirks(message, recommend, pattern, index):
"""Warn quirks."""
import traceback
import bs4 # noqa: F401
# Acquire source code line context
paths = (MODULE, sys.modules['bs4'].__path__[0])
tb = traceback.extract_stack()
previous = None
filename = None
lineno = None
for... | [
"def",
"warn_quirks",
"(",
"message",
",",
"recommend",
",",
"pattern",
",",
"index",
")",
":",
"import",
"traceback",
"import",
"bs4",
"# noqa: F401",
"# Acquire source code line context",
"paths",
"=",
"(",
"MODULE",
",",
"sys",
".",
"modules",
"[",
"'bs4'",
... | Warn quirks. | [
"Warn",
"quirks",
"."
] | python | train | 35.805556 |
gwastro/pycbc | pycbc/workflow/coincidence.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/coincidence.py#L549-L592 | def setup_interval_coinc(workflow, hdfbank, trig_files, stat_files,
veto_files, veto_names, out_dir, tags=None):
"""
This function sets up exact match coincidence and background estimation
using a folded interval technique.
"""
if tags is None:
tags = []
make_an... | [
"def",
"setup_interval_coinc",
"(",
"workflow",
",",
"hdfbank",
",",
"trig_files",
",",
"stat_files",
",",
"veto_files",
",",
"veto_names",
",",
"out_dir",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"make_... | This function sets up exact match coincidence and background estimation
using a folded interval technique. | [
"This",
"function",
"sets",
"up",
"exact",
"match",
"coincidence",
"and",
"background",
"estimation"
] | python | train | 40.772727 |
mongodb/mongo-python-driver | pymongo/uri_parser.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/uri_parser.py#L237-L253 | def _handle_option_deprecations(options):
"""Issue appropriate warnings when deprecated options are present in the
options dictionary. Removes deprecated option key, value pairs if the
options dictionary is found to also have the renamed option."""
undeprecated_options = _CaseInsensitiveDictionary()
... | [
"def",
"_handle_option_deprecations",
"(",
"options",
")",
":",
"undeprecated_options",
"=",
"_CaseInsensitiveDictionary",
"(",
")",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"options",
")",
":",
"optname",
"=",
"str",
"(",
"key",
")",
".",
"lower",
... | Issue appropriate warnings when deprecated options are present in the
options dictionary. Removes deprecated option key, value pairs if the
options dictionary is found to also have the renamed option. | [
"Issue",
"appropriate",
"warnings",
"when",
"deprecated",
"options",
"are",
"present",
"in",
"the",
"options",
"dictionary",
".",
"Removes",
"deprecated",
"option",
"key",
"value",
"pairs",
"if",
"the",
"options",
"dictionary",
"is",
"found",
"to",
"also",
"have... | python | train | 53.529412 |
saltstack/salt | salt/cloud/clouds/digitalocean.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L206-L226 | def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image)
for image in image... | [
"def",
"get_image",
"(",
"vm_",
")",
":",
"images",
"=",
"avail_images",
"(",
")",
"vm_image",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'image'",
",",
"vm_",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
"if",
"not",
"isinstance",
"(... | Return the image object to use | [
"Return",
"the",
"image",
"object",
"to",
"use"
] | python | train | 33 |
graphistry/pygraphistry | demos/demos_databases_apis/alienvault/unimatrix.py | https://github.com/graphistry/pygraphistry/blob/3dfc50e60232c6f5fedd6e5fa9d3048b606944b8/demos/demos_databases_apis/alienvault/unimatrix.py#L175-L186 | def get_alarms_list(self, num_items=100, params=None):
"""
Get alarms as list of dictionaries
:param int num_items: Max items to retrieve
:param dict params: Additional params dictionary according to:
https://www.alienvault.com/documentation/api/usm-anywhere-api.htm#/alarms
... | [
"def",
"get_alarms_list",
"(",
"self",
",",
"num_items",
"=",
"100",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"and",
"set",
"(",
"params",
".",
"keys",
"(",
")",
")",
"-",
"VALID_ALARM_PARAMS",
":",
"self",
".",
"log",
".",
"error",
"(",... | Get alarms as list of dictionaries
:param int num_items: Max items to retrieve
:param dict params: Additional params dictionary according to:
https://www.alienvault.com/documentation/api/usm-anywhere-api.htm#/alarms
:returns list: list of alarms | [
"Get",
"alarms",
"as",
"list",
"of",
"dictionaries",
":",
"param",
"int",
"num_items",
":",
"Max",
"items",
"to",
"retrieve",
":",
"param",
"dict",
"params",
":",
"Additional",
"params",
"dictionary",
"according",
"to",
":",
"https",
":",
"//",
"www",
".",... | python | train | 53.333333 |
mlperf/training | reinforcement/tensorflow/minigo/rl_loop/train_and_validate.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/train_and_validate.py#L106-L121 | def validate_holdout_selfplay():
"""Validate on held-out selfplay data."""
holdout_dirs = (os.path.join(fsdb.holdout_dir(), d)
for d in reversed(gfile.ListDirectory(fsdb.holdout_dir()))
if gfile.IsDirectory(os.path.join(fsdb.holdout_dir(), d))
for f in... | [
"def",
"validate_holdout_selfplay",
"(",
")",
":",
"holdout_dirs",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"fsdb",
".",
"holdout_dir",
"(",
")",
",",
"d",
")",
"for",
"d",
"in",
"reversed",
"(",
"gfile",
".",
"ListDirectory",
"(",
"fsdb",
".",
... | Validate on held-out selfplay data. | [
"Validate",
"on",
"held",
"-",
"out",
"selfplay",
"data",
"."
] | python | train | 49.8125 |
Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L34-L65 | def deeper_conv_block(conv_layer, kernel_size, weighted=True):
'''deeper conv layer.
'''
n_dim = get_n_dim(conv_layer)
filter_shape = (kernel_size,) * 2
n_filters = conv_layer.filters
weight = np.zeros((n_filters, n_filters) + filter_shape)
center = tuple(map(lambda x: int((x - 1) / 2), filt... | [
"def",
"deeper_conv_block",
"(",
"conv_layer",
",",
"kernel_size",
",",
"weighted",
"=",
"True",
")",
":",
"n_dim",
"=",
"get_n_dim",
"(",
"conv_layer",
")",
"filter_shape",
"=",
"(",
"kernel_size",
",",
")",
"*",
"2",
"n_filters",
"=",
"conv_layer",
".",
... | deeper conv layer. | [
"deeper",
"conv",
"layer",
"."
] | python | train | 39.625 |
chimera0/accel-brain-code | Binaural-Beat-and-Monaural-Beat-with-python/AccelBrainBeat/brain_beat.py | https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Binaural-Beat-and-Monaural-Beat-with-python/AccelBrainBeat/brain_beat.py#L149-L165 | def __create_chunk(self, frequency, play_time, sample_rate):
'''
チャンクを生成する
Args:
frequency: 周波数
play_time: 再生時間(秒)
sample_rate: サンプルレート
Returns:
チャンクのnumpy配列
'''
chunks = []
wave_form = se... | [
"def",
"__create_chunk",
"(",
"self",
",",
"frequency",
",",
"play_time",
",",
"sample_rate",
")",
":",
"chunks",
"=",
"[",
"]",
"wave_form",
"=",
"self",
".",
"wave_form",
".",
"create",
"(",
"frequency",
",",
"play_time",
",",
"sample_rate",
")",
"chunks... | チャンクを生成する
Args:
frequency: 周波数
play_time: 再生時間(秒)
sample_rate: サンプルレート
Returns:
チャンクのnumpy配列 | [
"チャンクを生成する",
"Args",
":",
"frequency",
":",
"周波数",
"play_time",
":",
"再生時間(秒)",
"sample_rate",
":",
"サンプルレート",
"Returns",
":",
"チャンクのnumpy配列"
] | python | train | 26.882353 |
chaoss/grimoirelab-perceval | perceval/backends/core/mediawiki.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/mediawiki.py#L183-L191 | def __get_max_date(self, reviews):
""""Get the max date in unixtime format from reviews."""
max_ts = 0
for review in reviews:
ts = str_to_datetime(review['timestamp'])
ts = datetime_to_utc(ts)
if ts.timestamp() > max_ts:
max_ts = ts.timestamp()... | [
"def",
"__get_max_date",
"(",
"self",
",",
"reviews",
")",
":",
"max_ts",
"=",
"0",
"for",
"review",
"in",
"reviews",
":",
"ts",
"=",
"str_to_datetime",
"(",
"review",
"[",
"'timestamp'",
"]",
")",
"ts",
"=",
"datetime_to_utc",
"(",
"ts",
")",
"if",
"t... | Get the max date in unixtime format from reviews. | [
"Get",
"the",
"max",
"date",
"in",
"unixtime",
"format",
"from",
"reviews",
"."
] | python | test | 37.111111 |
nitely/django-djconfig | djconfig/admin.py | https://github.com/nitely/django-djconfig/blob/5e79a048ef5c9529075cad947b0c309115035d7e/djconfig/admin.py#L130-L156 | def register(conf, conf_admin, **options):
"""
Register a new admin section.
:param conf: A subclass of ``djconfig.admin.Config``
:param conf_admin: A subclass of ``djconfig.admin.ConfigAdmin``
:param options: Extra options passed to ``django.contrib.admin.site.register``
"""
assert issubcl... | [
"def",
"register",
"(",
"conf",
",",
"conf_admin",
",",
"*",
"*",
"options",
")",
":",
"assert",
"issubclass",
"(",
"conf_admin",
",",
"ConfigAdmin",
")",
",",
"(",
"'conf_admin is not a ConfigAdmin subclass'",
")",
"assert",
"issubclass",
"(",
"getattr",
"(",
... | Register a new admin section.
:param conf: A subclass of ``djconfig.admin.Config``
:param conf_admin: A subclass of ``djconfig.admin.ConfigAdmin``
:param options: Extra options passed to ``django.contrib.admin.site.register`` | [
"Register",
"a",
"new",
"admin",
"section",
"."
] | python | train | 43.444444 |
diffeo/rejester | rejester/_registry.py | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L186-L216 | def lock(self, atime=30, ltime=5, identifier=None):
'''Context manager to acquire the namespace global lock.
This is typically used for multi-step registry operations,
such as a read-modify-write sequence::
with registry.lock() as session:
d = session.get('dict', 'k... | [
"def",
"lock",
"(",
"self",
",",
"atime",
"=",
"30",
",",
"ltime",
"=",
"5",
",",
"identifier",
"=",
"None",
")",
":",
"if",
"identifier",
"is",
"None",
":",
"identifier",
"=",
"nice_identifier",
"(",
")",
"if",
"self",
".",
"_acquire_lock",
"(",
"id... | Context manager to acquire the namespace global lock.
This is typically used for multi-step registry operations,
such as a read-modify-write sequence::
with registry.lock() as session:
d = session.get('dict', 'key')
del d['traceback']
session... | [
"Context",
"manager",
"to",
"acquire",
"the",
"namespace",
"global",
"lock",
"."
] | python | train | 39.580645 |
tweekmonster/moult | moult/utils.py | https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/utils.py#L134-L160 | def find_package(name, installed, package=False):
'''Finds a package in the installed list.
If `package` is true, match package names, otherwise, match import paths.
'''
if package:
name = name.lower()
tests = (
lambda x: x.user and name == x.name.lower(),
lambda... | [
"def",
"find_package",
"(",
"name",
",",
"installed",
",",
"package",
"=",
"False",
")",
":",
"if",
"package",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"tests",
"=",
"(",
"lambda",
"x",
":",
"x",
".",
"user",
"and",
"name",
"==",
"x",
".... | Finds a package in the installed list.
If `package` is true, match package names, otherwise, match import paths. | [
"Finds",
"a",
"package",
"in",
"the",
"installed",
"list",
"."
] | python | train | 30.037037 |
s0md3v/Photon | core/utils.py | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L15-L23 | def regxy(pattern, response, supress_regex, custom):
"""Extract a string based on regex pattern supplied by user."""
try:
matches = re.findall(r'%s' % pattern, response)
for match in matches:
verb('Custom regex', match)
custom.add(match)
except:
supress_regex ... | [
"def",
"regxy",
"(",
"pattern",
",",
"response",
",",
"supress_regex",
",",
"custom",
")",
":",
"try",
":",
"matches",
"=",
"re",
".",
"findall",
"(",
"r'%s'",
"%",
"pattern",
",",
"response",
")",
"for",
"match",
"in",
"matches",
":",
"verb",
"(",
"... | Extract a string based on regex pattern supplied by user. | [
"Extract",
"a",
"string",
"based",
"on",
"regex",
"pattern",
"supplied",
"by",
"user",
"."
] | python | train | 35.333333 |
pytorch/vision | torchvision/models/squeezenet.py | https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/models/squeezenet.py#L117-L129 | def squeezenet1_1(pretrained=False, **kwargs):
r"""SqueezeNet 1.1 model from the `official SqueezeNet repo
<https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_.
SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters
than SqueezeNet 1.0, without sacrificing accuracy.
... | [
"def",
"squeezenet1_1",
"(",
"pretrained",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"model",
"=",
"SqueezeNet",
"(",
"version",
"=",
"1.1",
",",
"*",
"*",
"kwargs",
")",
"if",
"pretrained",
":",
"model",
".",
"load_state_dict",
"(",
"model_zoo",
... | r"""SqueezeNet 1.1 model from the `official SqueezeNet repo
<https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_.
SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters
than SqueezeNet 1.0, without sacrificing accuracy.
Args:
pretrained (bool): If True, return... | [
"r",
"SqueezeNet",
"1",
".",
"1",
"model",
"from",
"the",
"official",
"SqueezeNet",
"repo",
"<https",
":",
"//",
"github",
".",
"com",
"/",
"DeepScale",
"/",
"SqueezeNet",
"/",
"tree",
"/",
"master",
"/",
"SqueezeNet_v1",
".",
"1",
">",
"_",
".",
"Sque... | python | test | 43.153846 |
gebn/nibble | nibble/__main__.py | https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/__main__.py#L41-L68 | def main(args):
"""
Nibble's entry point.
:param args: Command-line arguments, with the program in position 0.
"""
args = _parse_args(args)
# sort out logging output and level
level = util.log_level_from_vebosity(args.verbosity)
root = logging.getLogger()
root.setLevel(level)
... | [
"def",
"main",
"(",
"args",
")",
":",
"args",
"=",
"_parse_args",
"(",
"args",
")",
"# sort out logging output and level",
"level",
"=",
"util",
".",
"log_level_from_vebosity",
"(",
"args",
".",
"verbosity",
")",
"root",
"=",
"logging",
".",
"getLogger",
"(",
... | Nibble's entry point.
:param args: Command-line arguments, with the program in position 0. | [
"Nibble",
"s",
"entry",
"point",
"."
] | python | train | 24.607143 |
specialunderwear/django-easymode | easymode/management/commands/easy_locale.py | https://github.com/specialunderwear/django-easymode/blob/92f674b91fb8c54d6e379e2664e2000872d9c95e/easymode/management/commands/easy_locale.py#L30-L48 | def handle(self, targetdir, app=None, **options):
""" command execution """
translation.activate(settings.LANGUAGE_CODE)
if app:
unpack = app.split('.')
if len(unpack) == 2:
models = [get_model(unpack[0], unpack[1])]
elif len(unpack) == 1:
... | [
"def",
"handle",
"(",
"self",
",",
"targetdir",
",",
"app",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"translation",
".",
"activate",
"(",
"settings",
".",
"LANGUAGE_CODE",
")",
"if",
"app",
":",
"unpack",
"=",
"app",
".",
"split",
"(",
"'.'",... | command execution | [
"command",
"execution"
] | python | train | 34.105263 |
houluy/chessboard | chessboard/__init__.py | https://github.com/houluy/chessboard/blob/b834819d93d71b492f27780a58dfbb3a107d7e85/chessboard/__init__.py#L314-L325 | def handle_input(self, input_str, place=True, check=False):
'''Transfer user input to valid chess position'''
user = self.get_player()
pos = self.validate_input(input_str)
if pos[0] == 'u':
self.undo(pos[1])
return pos
if place:
result = self.s... | [
"def",
"handle_input",
"(",
"self",
",",
"input_str",
",",
"place",
"=",
"True",
",",
"check",
"=",
"False",
")",
":",
"user",
"=",
"self",
".",
"get_player",
"(",
")",
"pos",
"=",
"self",
".",
"validate_input",
"(",
"input_str",
")",
"if",
"pos",
"[... | Transfer user input to valid chess position | [
"Transfer",
"user",
"input",
"to",
"valid",
"chess",
"position"
] | python | train | 32.5 |
UDST/urbansim | urbansim/models/regression.py | https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/models/regression.py#L157-L175 | def predict(self, data):
"""
Predict new values by running data through the fit model.
Parameters
----------
data : pandas.DataFrame
Table with columns corresponding to the RHS of `model_expression`.
Returns
-------
predicted : ndarray
... | [
"def",
"predict",
"(",
"self",
",",
"data",
")",
":",
"with",
"log_start_finish",
"(",
"'_FakeRegressionResults prediction'",
",",
"logger",
")",
":",
"model_design",
"=",
"dmatrix",
"(",
"self",
".",
"_rhs",
",",
"data",
"=",
"data",
",",
"return_type",
"="... | Predict new values by running data through the fit model.
Parameters
----------
data : pandas.DataFrame
Table with columns corresponding to the RHS of `model_expression`.
Returns
-------
predicted : ndarray
Array of predicted values. | [
"Predict",
"new",
"values",
"by",
"running",
"data",
"through",
"the",
"fit",
"model",
"."
] | python | train | 30.421053 |
Erotemic/utool | utool/util_list.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1332-L1349 | def iflag_unique_items(list_):
"""
Returns a list of flags corresponding to the first time an item is seen
Args:
list_ (list): list of items
Returns:
flag_iter
"""
seen = set()
def unseen(item):
if item in seen:
return False
seen.add(item)
... | [
"def",
"iflag_unique_items",
"(",
"list_",
")",
":",
"seen",
"=",
"set",
"(",
")",
"def",
"unseen",
"(",
"item",
")",
":",
"if",
"item",
"in",
"seen",
":",
"return",
"False",
"seen",
".",
"add",
"(",
"item",
")",
"return",
"True",
"flag_iter",
"=",
... | Returns a list of flags corresponding to the first time an item is seen
Args:
list_ (list): list of items
Returns:
flag_iter | [
"Returns",
"a",
"list",
"of",
"flags",
"corresponding",
"to",
"the",
"first",
"time",
"an",
"item",
"is",
"seen"
] | python | train | 21.444444 |
mwouts/jupytext | jupytext/formats.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/formats.py#L302-L333 | def check_file_version(notebook, source_path, outputs_path):
"""Raise if file version in source file would override outputs"""
if not insert_or_test_version_number():
return
_, ext = os.path.splitext(source_path)
if ext.endswith('.ipynb'):
return
version = notebook.metadata.get('jup... | [
"def",
"check_file_version",
"(",
"notebook",
",",
"source_path",
",",
"outputs_path",
")",
":",
"if",
"not",
"insert_or_test_version_number",
"(",
")",
":",
"return",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"source_path",
")",
"if",
... | Raise if file version in source file would override outputs | [
"Raise",
"if",
"file",
"version",
"in",
"source",
"file",
"would",
"override",
"outputs"
] | python | train | 41.5625 |
nicolargo/glances | glances/stats.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/stats.py#L212-L226 | def update(self):
"""Wrapper method to update the stats."""
# For standalone and server modes
# For each plugins, call the update method
for p in self._plugins:
if self._plugins[p].is_disable():
# If current plugin is disable
# then continue to... | [
"def",
"update",
"(",
"self",
")",
":",
"# For standalone and server modes",
"# For each plugins, call the update method",
"for",
"p",
"in",
"self",
".",
"_plugins",
":",
"if",
"self",
".",
"_plugins",
"[",
"p",
"]",
".",
"is_disable",
"(",
")",
":",
"# If curre... | Wrapper method to update the stats. | [
"Wrapper",
"method",
"to",
"update",
"the",
"stats",
"."
] | python | train | 38.2 |
asciimoo/searx | searx/utils.py | https://github.com/asciimoo/searx/blob/a84caa22cf947e973c10aa968d35fb2bdda6d048/searx/utils.py#L190-L195 | def get_themes(templates_path):
"""Returns available themes list."""
themes = os.listdir(templates_path)
if '__common__' in themes:
themes.remove('__common__')
return themes | [
"def",
"get_themes",
"(",
"templates_path",
")",
":",
"themes",
"=",
"os",
".",
"listdir",
"(",
"templates_path",
")",
"if",
"'__common__'",
"in",
"themes",
":",
"themes",
".",
"remove",
"(",
"'__common__'",
")",
"return",
"themes"
] | Returns available themes list. | [
"Returns",
"available",
"themes",
"list",
"."
] | python | test | 32 |
networks-lab/metaknowledge | metaknowledge/recordCollection.py | https://github.com/networks-lab/metaknowledge/blob/8162bf95e66bb6f9916081338e6e2a6132faff75/metaknowledge/recordCollection.py#L1709-L1760 | def makeNodeTuple(citation, idVal, nodeInfo, fullInfo, nodeType, count, coreCitesDict, coreValues, detailedValues, addCR):
"""Makes a tuple of idVal and a dict of the selected attributes"""
d = {}
if nodeInfo:
if nodeType == 'full':
if coreValues:
if citation in coreCites... | [
"def",
"makeNodeTuple",
"(",
"citation",
",",
"idVal",
",",
"nodeInfo",
",",
"fullInfo",
",",
"nodeType",
",",
"count",
",",
"coreCitesDict",
",",
"coreValues",
",",
"detailedValues",
",",
"addCR",
")",
":",
"d",
"=",
"{",
"}",
"if",
"nodeInfo",
":",
"if... | Makes a tuple of idVal and a dict of the selected attributes | [
"Makes",
"a",
"tuple",
"of",
"idVal",
"and",
"a",
"dict",
"of",
"the",
"selected",
"attributes"
] | python | train | 40.634615 |
EnigmaBridge/client.py | ebclient/eb_create_uo.py | https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L488-L509 | def get_best_import_key(self, import_keys):
"""
Picks best RSA key for import from the import keys arrays.
:param import_keys:
:return:
"""
rsa2048 = None
rsa1024 = None
for c_key in import_keys:
if c_key is None \
or 'type... | [
"def",
"get_best_import_key",
"(",
"self",
",",
"import_keys",
")",
":",
"rsa2048",
"=",
"None",
"rsa1024",
"=",
"None",
"for",
"c_key",
"in",
"import_keys",
":",
"if",
"c_key",
"is",
"None",
"or",
"'type'",
"not",
"in",
"c_key",
"or",
"c_key",
"[",
"'ty... | Picks best RSA key for import from the import keys arrays.
:param import_keys:
:return: | [
"Picks",
"best",
"RSA",
"key",
"for",
"import",
"from",
"the",
"import",
"keys",
"arrays",
".",
":",
"param",
"import_keys",
":",
":",
"return",
":"
] | python | train | 31.409091 |
pennlabs/penn-sdk-python | penn/registrar.py | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/registrar.py#L80-L91 | def section(self, dept, course_number, sect_number):
"""Return a single section object for the given section. All arguments
should be strings. Throws a `ValueError` if the section is not found.
>>> lgst101_bfs = r.course('lgst', '101', '301')
"""
section_id = dept + course_numbe... | [
"def",
"section",
"(",
"self",
",",
"dept",
",",
"course_number",
",",
"sect_number",
")",
":",
"section_id",
"=",
"dept",
"+",
"course_number",
"+",
"sect_number",
"sections",
"=",
"self",
".",
"search",
"(",
"{",
"'course_id'",
":",
"section_id",
"}",
")... | Return a single section object for the given section. All arguments
should be strings. Throws a `ValueError` if the section is not found.
>>> lgst101_bfs = r.course('lgst', '101', '301') | [
"Return",
"a",
"single",
"section",
"object",
"for",
"the",
"given",
"section",
".",
"All",
"arguments",
"should",
"be",
"strings",
".",
"Throws",
"a",
"ValueError",
"if",
"the",
"section",
"is",
"not",
"found",
"."
] | python | train | 43.75 |
pylast/pylast | src/pylast/__init__.py | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2692-L2708 | def get_next_page(self):
"""Returns the next page of results as a sequence of Album objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("album"):
seq.append(
Album(
_extract(node, "ar... | [
"def",
"get_next_page",
"(",
"self",
")",
":",
"master_node",
"=",
"self",
".",
"_retrieve_next_page",
"(",
")",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"master_node",
".",
"getElementsByTagName",
"(",
"\"album\"",
")",
":",
"seq",
".",
"append",
"(",
... | Returns the next page of results as a sequence of Album objects. | [
"Returns",
"the",
"next",
"page",
"of",
"results",
"as",
"a",
"sequence",
"of",
"Album",
"objects",
"."
] | python | train | 29.764706 |
Microsoft/ApplicationInsights-Python | applicationinsights/channel/contracts/ExceptionDetails.py | https://github.com/Microsoft/ApplicationInsights-Python/blob/8452ab7126f9bb6964637d4aa1258c2af17563d6/applicationinsights/channel/contracts/ExceptionDetails.py#L145-L154 | def stack(self, value):
"""The stack property.
Args:
value (string). the property value.
"""
if value == self._defaults['stack'] and 'stack' in self._values:
del self._values['stack']
else:
self._values['stack'] = value | [
"def",
"stack",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"_defaults",
"[",
"'stack'",
"]",
"and",
"'stack'",
"in",
"self",
".",
"_values",
":",
"del",
"self",
".",
"_values",
"[",
"'stack'",
"]",
"else",
":",
"self",
"... | The stack property.
Args:
value (string). the property value. | [
"The",
"stack",
"property",
".",
"Args",
":",
"value",
"(",
"string",
")",
".",
"the",
"property",
"value",
"."
] | python | train | 29.5 |
CityOfZion/neo-python | neo/Core/State/StorageItem.py | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/StorageItem.py#L79-L87 | def Serialize(self, writer):
"""
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
"""
super(StorageItem, self).Serialize(writer)
writer.WriteVarBytes(self.Value) | [
"def",
"Serialize",
"(",
"self",
",",
"writer",
")",
":",
"super",
"(",
"StorageItem",
",",
"self",
")",
".",
"Serialize",
"(",
"writer",
")",
"writer",
".",
"WriteVarBytes",
"(",
"self",
".",
"Value",
")"
] | Serialize full object.
Args:
writer (neo.IO.BinaryWriter): | [
"Serialize",
"full",
"object",
"."
] | python | train | 24.888889 |
Netflix-Skunkworks/historical | historical/security_group/differ.py | https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/security_group/differ.py#L23-L34 | def handler(event, context): # pylint: disable=W0613
"""
Historical security group event differ.
Listens to the Historical current table and determines if there are differences that need to be persisted in the
historical record.
"""
# De-serialize the records:
records = deserialize_records... | [
"def",
"handler",
"(",
"event",
",",
"context",
")",
":",
"# pylint: disable=W0613",
"# De-serialize the records:",
"records",
"=",
"deserialize_records",
"(",
"event",
"[",
"'Records'",
"]",
")",
"for",
"record",
"in",
"records",
":",
"process_dynamodb_differ_record"... | Historical security group event differ.
Listens to the Historical current table and determines if there are differences that need to be persisted in the
historical record. | [
"Historical",
"security",
"group",
"event",
"differ",
"."
] | python | train | 38 |
Becksteinlab/GromacsWrapper | gromacs/setup.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/setup.py#L964-L1061 | def MD_restrained(dirname='MD_POSRES', **kwargs):
"""Set up MD with position restraints.
Additional itp files should be in the same directory as the top file.
Many of the keyword arguments below already have sensible values. Note that
setting *mainselection* = ``None`` will disable many of the automat... | [
"def",
"MD_restrained",
"(",
"dirname",
"=",
"'MD_POSRES'",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"info",
"(",
"\"[{dirname!s}] Setting up MD with position restraints...\"",
".",
"format",
"(",
"*",
"*",
"vars",
"(",
")",
")",
")",
"kwargs",
".",
... | Set up MD with position restraints.
Additional itp files should be in the same directory as the top file.
Many of the keyword arguments below already have sensible values. Note that
setting *mainselection* = ``None`` will disable many of the automated
choices and is often recommended when using your o... | [
"Set",
"up",
"MD",
"with",
"position",
"restraints",
"."
] | python | valid | 43.244898 |
jazzband/python-geojson | geojson/examples.py | https://github.com/jazzband/python-geojson/blob/14abb31ba73a9f3cdb81d81c56656ea736f3c865/geojson/examples.py#L47-L70 | def create_simple_web_feature(o):
"""
Create an instance of SimpleWebFeature from a dict, o. If o does not
match a Python feature object, simply return o. This function serves as a
json decoder hook. See coding.load().
:param o: A dict to create the SimpleWebFeature from.
:type o: dict
:ret... | [
"def",
"create_simple_web_feature",
"(",
"o",
")",
":",
"try",
":",
"id",
"=",
"o",
"[",
"'id'",
"]",
"g",
"=",
"o",
"[",
"'geometry'",
"]",
"p",
"=",
"o",
"[",
"'properties'",
"]",
"return",
"SimpleWebFeature",
"(",
"str",
"(",
"id",
")",
",",
"{"... | Create an instance of SimpleWebFeature from a dict, o. If o does not
match a Python feature object, simply return o. This function serves as a
json decoder hook. See coding.load().
:param o: A dict to create the SimpleWebFeature from.
:type o: dict
:return: A SimpleWebFeature from the dict provided... | [
"Create",
"an",
"instance",
"of",
"SimpleWebFeature",
"from",
"a",
"dict",
"o",
".",
"If",
"o",
"does",
"not",
"match",
"a",
"Python",
"feature",
"object",
"simply",
"return",
"o",
".",
"This",
"function",
"serves",
"as",
"a",
"json",
"decoder",
"hook",
... | python | train | 32.125 |
iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L99-L124 | def _query_systemstate(self):
"""Query the maximum number of connections supported by this adapter
"""
def status_filter_func(event):
if event.command_class == 3 and event.command == 0:
return True
return False
try:
response = self._... | [
"def",
"_query_systemstate",
"(",
"self",
")",
":",
"def",
"status_filter_func",
"(",
"event",
")",
":",
"if",
"event",
".",
"command_class",
"==",
"3",
"and",
"event",
".",
"command",
"==",
"0",
":",
"return",
"True",
"return",
"False",
"try",
":",
"res... | Query the maximum number of connections supported by this adapter | [
"Query",
"the",
"maximum",
"number",
"of",
"connections",
"supported",
"by",
"this",
"adapter"
] | python | train | 33.692308 |
astropy/astropy-helpers | astropy_helpers/commands/build_sphinx.py | https://github.com/astropy/astropy-helpers/blob/f5a27d3f84a98ea0eebb85e0cf3e7214c6bc0d09/astropy_helpers/commands/build_sphinx.py#L40-L89 | def ensure_sphinx_astropy_installed():
"""
Make sure that sphinx-astropy is available, installing it temporarily if not.
This returns the available version of sphinx-astropy as well as any
paths that should be added to sys.path for sphinx-astropy to be available.
"""
# We've split out the Sphin... | [
"def",
"ensure_sphinx_astropy_installed",
"(",
")",
":",
"# We've split out the Sphinx part of astropy-helpers into sphinx-astropy",
"# but we want it to be auto-installed seamlessly for anyone using",
"# build_docs. We check if it's already installed, and if not, we install",
"# it to a local .eggs... | Make sure that sphinx-astropy is available, installing it temporarily if not.
This returns the available version of sphinx-astropy as well as any
paths that should be added to sys.path for sphinx-astropy to be available. | [
"Make",
"sure",
"that",
"sphinx",
"-",
"astropy",
"is",
"available",
"installing",
"it",
"temporarily",
"if",
"not",
"."
] | python | train | 43.24 |
secdev/scapy | scapy/packet.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/packet.py#L488-L494 | def clear_cache(self):
"""Clear the raw packet cache for the field and all its subfields"""
self.raw_packet_cache = None
for _, fval in six.iteritems(self.fields):
if isinstance(fval, Packet):
fval.clear_cache()
self.payload.clear_cache() | [
"def",
"clear_cache",
"(",
"self",
")",
":",
"self",
".",
"raw_packet_cache",
"=",
"None",
"for",
"_",
",",
"fval",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"fields",
")",
":",
"if",
"isinstance",
"(",
"fval",
",",
"Packet",
")",
":",
"fval",... | Clear the raw packet cache for the field and all its subfields | [
"Clear",
"the",
"raw",
"packet",
"cache",
"for",
"the",
"field",
"and",
"all",
"its",
"subfields"
] | python | train | 41.714286 |
PostmonAPI/postmon-python | postmon.py | https://github.com/PostmonAPI/postmon-python/blob/bfd3a38a8aec5e069536a0bc36440946d1981e37/postmon.py#L44-L59 | def buscar(self):
"""Faz a busca das informações do objeto no Postmon.
Retorna um ``bool`` indicando se a busca foi bem sucedida.
"""
headers = {'User-Agent': self.user_agent}
try:
self._response = requests.get(self.url, headers=headers)
except requests.Reque... | [
"def",
"buscar",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"'User-Agent'",
":",
"self",
".",
"user_agent",
"}",
"try",
":",
"self",
".",
"_response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"url",
",",
"headers",
"=",
"headers",
")",
"except... | Faz a busca das informações do objeto no Postmon.
Retorna um ``bool`` indicando se a busca foi bem sucedida. | [
"Faz",
"a",
"busca",
"das",
"informações",
"do",
"objeto",
"no",
"Postmon",
"."
] | python | train | 36.5 |
XRDX/pyleap | pyleap/shape/ellipse.py | https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/shape/ellipse.py#L25-L34 | def update_points(self):
""" 椭圆的近似图形:72边形 """
n = max(8, min(72, int(2*sqrt(self.r_x+self.r_y))))
d = pi * 2 / n
x, y, r_x, r_y = self.x, self.y, self.r_x, self.r_y
ps = []
for i in range(n):
ps += [(x + r_x * sin(d * i)), (y + r_y * cos(d * i))]
self... | [
"def",
"update_points",
"(",
"self",
")",
":",
"n",
"=",
"max",
"(",
"8",
",",
"min",
"(",
"72",
",",
"int",
"(",
"2",
"*",
"sqrt",
"(",
"self",
".",
"r_x",
"+",
"self",
".",
"r_y",
")",
")",
")",
")",
"d",
"=",
"pi",
"*",
"2",
"/",
"n",
... | 椭圆的近似图形:72边形 | [
"椭圆的近似图形:72边形"
] | python | train | 33 |
dourvaris/nano-python | src/nano/rpc.py | https://github.com/dourvaris/nano-python/blob/f26b8bc895b997067780f925049a70e82c0c2479/src/nano/rpc.py#L658-L702 | def account_representative_set(self, wallet, account, representative, work=None):
"""
Sets the representative for **account** in **wallet**
.. enable_control required
:param wallet: Wallet to use for account
:type wallet: str
:param account: Account to set representati... | [
"def",
"account_representative_set",
"(",
"self",
",",
"wallet",
",",
"account",
",",
"representative",
",",
"work",
"=",
"None",
")",
":",
"wallet",
"=",
"self",
".",
"_process_value",
"(",
"wallet",
",",
"'wallet'",
")",
"account",
"=",
"self",
".",
"_pr... | Sets the representative for **account** in **wallet**
.. enable_control required
:param wallet: Wallet to use for account
:type wallet: str
:param account: Account to set representative for
:type account: str
:param representative: Representative to set to
:ty... | [
"Sets",
"the",
"representative",
"for",
"**",
"account",
"**",
"in",
"**",
"wallet",
"**"
] | python | train | 32.888889 |
alimanfoo/csvvalidator | csvvalidator.py | https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L958-L971 | def search_pattern(regex):
"""
Return a value check function which raises a ValueError if the supplied
regular expression does not match anywhere in the value, see also
`re.search`.
"""
prog = re.compile(regex)
def checker(v):
result = prog.search(v)
if result is None:
... | [
"def",
"search_pattern",
"(",
"regex",
")",
":",
"prog",
"=",
"re",
".",
"compile",
"(",
"regex",
")",
"def",
"checker",
"(",
"v",
")",
":",
"result",
"=",
"prog",
".",
"search",
"(",
"v",
")",
"if",
"result",
"is",
"None",
":",
"raise",
"ValueErro... | Return a value check function which raises a ValueError if the supplied
regular expression does not match anywhere in the value, see also
`re.search`. | [
"Return",
"a",
"value",
"check",
"function",
"which",
"raises",
"a",
"ValueError",
"if",
"the",
"supplied",
"regular",
"expression",
"does",
"not",
"match",
"anywhere",
"in",
"the",
"value",
"see",
"also",
"re",
".",
"search",
"."
] | python | valid | 25.214286 |
CalebBell/thermo | thermo/interface.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/interface.py#L226-L284 | def Brock_Bird(T, Tb, Tc, Pc):
r'''Calculates air-water surface tension using the [1]_
emperical method. Old and tested.
.. math::
\sigma = P_c^{2/3}T_c^{1/3}Q(1-T_r)^{11/9}
Q = 0.1196 \left[ 1 + \frac{T_{br}\ln (P_c/1.01325)}{1-T_{br}}\right]-0.279
Parameters
----------
T : ... | [
"def",
"Brock_Bird",
"(",
"T",
",",
"Tb",
",",
"Tc",
",",
"Pc",
")",
":",
"Tbr",
"=",
"Tb",
"/",
"Tc",
"Tr",
"=",
"T",
"/",
"Tc",
"Pc",
"=",
"Pc",
"/",
"1E5",
"# Convert to bar",
"Q",
"=",
"0.1196",
"*",
"(",
"1",
"+",
"Tbr",
"*",
"log",
"(... | r'''Calculates air-water surface tension using the [1]_
emperical method. Old and tested.
.. math::
\sigma = P_c^{2/3}T_c^{1/3}Q(1-T_r)^{11/9}
Q = 0.1196 \left[ 1 + \frac{T_{br}\ln (P_c/1.01325)}{1-T_{br}}\right]-0.279
Parameters
----------
T : float
Temperature of fluid ... | [
"r",
"Calculates",
"air",
"-",
"water",
"surface",
"tension",
"using",
"the",
"[",
"1",
"]",
"_",
"emperical",
"method",
".",
"Old",
"and",
"tested",
"."
] | python | valid | 28.355932 |
totalgood/nlpia | src/nlpia/loaders.py | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L570-L584 | def endswith_strip(s, endswith='.txt', ignorecase=True):
""" Strip a suffix from the end of a string
>>> endswith_strip('http://TotalGood.com', '.COM')
'http://TotalGood'
>>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False)
'http://TotalGood.com'
"""
if ignorecase:
... | [
"def",
"endswith_strip",
"(",
"s",
",",
"endswith",
"=",
"'.txt'",
",",
"ignorecase",
"=",
"True",
")",
":",
"if",
"ignorecase",
":",
"if",
"s",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"endswith",
".",
"lower",
"(",
")",
")",
":",
"return",
"... | Strip a suffix from the end of a string
>>> endswith_strip('http://TotalGood.com', '.COM')
'http://TotalGood'
>>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False)
'http://TotalGood.com' | [
"Strip",
"a",
"suffix",
"from",
"the",
"end",
"of",
"a",
"string"
] | python | train | 32.4 |
linuxsoftware/ls.joyous | ls/joyous/models/calendar.py | https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L506-L508 | def _getEventsByWeek(self, request, year, month):
"""Return my child events for the given month grouped by week."""
return getAllEventsByWeek(request, year, month, home=self) | [
"def",
"_getEventsByWeek",
"(",
"self",
",",
"request",
",",
"year",
",",
"month",
")",
":",
"return",
"getAllEventsByWeek",
"(",
"request",
",",
"year",
",",
"month",
",",
"home",
"=",
"self",
")"
] | Return my child events for the given month grouped by week. | [
"Return",
"my",
"child",
"events",
"for",
"the",
"given",
"month",
"grouped",
"by",
"week",
"."
] | python | train | 62.666667 |
saltstack/salt | salt/states/lvm.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lvm.py#L43-L74 | def pv_present(name, **kwargs):
'''
Set a Physical Device to be used as an LVM Physical Volume
name
The device name to initialize.
kwargs
Any supported options to pvcreate. See
:mod:`linux_lvm <salt.modules.linux_lvm>` for more details.
'''
ret = {'changes': {},
... | [
"def",
"pv_present",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
"}",
"if",
"__salt__",
"[",
"'lvm.pvdisplay'",
... | Set a Physical Device to be used as an LVM Physical Volume
name
The device name to initialize.
kwargs
Any supported options to pvcreate. See
:mod:`linux_lvm <salt.modules.linux_lvm>` for more details. | [
"Set",
"a",
"Physical",
"Device",
"to",
"be",
"used",
"as",
"an",
"LVM",
"Physical",
"Volume"
] | python | train | 31.9375 |
ranaroussi/qtpylib | qtpylib/indicators.py | https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L512-L517 | def roc(series, window=14):
"""
compute rate of change
"""
res = (series - series.shift(window)) / series.shift(window)
return pd.Series(index=series.index, data=res) | [
"def",
"roc",
"(",
"series",
",",
"window",
"=",
"14",
")",
":",
"res",
"=",
"(",
"series",
"-",
"series",
".",
"shift",
"(",
"window",
")",
")",
"/",
"series",
".",
"shift",
"(",
"window",
")",
"return",
"pd",
".",
"Series",
"(",
"index",
"=",
... | compute rate of change | [
"compute",
"rate",
"of",
"change"
] | python | train | 30.166667 |
ilevkivskyi/typing_inspect | typing_inspect.py | https://github.com/ilevkivskyi/typing_inspect/blob/fd81278cc440b6003f8298bcb22d5bc0f82ee3cd/typing_inspect.py#L203-L225 | def get_origin(tp):
"""Get the unsubscripted version of a type. Supports generic types, Union,
Callable, and Tuple. Returns None for unsupported types. Examples::
get_origin(int) == None
get_origin(ClassVar[int]) == None
get_origin(Generic) == Generic
get_origin(Generic[T]) == G... | [
"def",
"get_origin",
"(",
"tp",
")",
":",
"if",
"NEW_TYPING",
":",
"if",
"isinstance",
"(",
"tp",
",",
"_GenericAlias",
")",
":",
"return",
"tp",
".",
"__origin__",
"if",
"tp",
".",
"__origin__",
"is",
"not",
"ClassVar",
"else",
"None",
"if",
"tp",
"is... | Get the unsubscripted version of a type. Supports generic types, Union,
Callable, and Tuple. Returns None for unsupported types. Examples::
get_origin(int) == None
get_origin(ClassVar[int]) == None
get_origin(Generic) == Generic
get_origin(Generic[T]) == Generic
get_origin(U... | [
"Get",
"the",
"unsubscripted",
"version",
"of",
"a",
"type",
".",
"Supports",
"generic",
"types",
"Union",
"Callable",
"and",
"Tuple",
".",
"Returns",
"None",
"for",
"unsupported",
"types",
".",
"Examples",
"::"
] | python | train | 33.434783 |
django-salesforce/django-salesforce | salesforce/backend/introspection.py | https://github.com/django-salesforce/django-salesforce/blob/6fd5643dba69d49c5881de50875cf90204a8f808/salesforce/backend/introspection.py#L124-L166 | def get_table_description(self, cursor, table_name):
"Returns a description of the table, with the DB-API cursor.description interface."
# pylint:disable=too-many-locals,unused-argument
result = []
for field in self.table_description_cache(table_name)['fields']:
params = Orde... | [
"def",
"get_table_description",
"(",
"self",
",",
"cursor",
",",
"table_name",
")",
":",
"# pylint:disable=too-many-locals,unused-argument",
"result",
"=",
"[",
"]",
"for",
"field",
"in",
"self",
".",
"table_description_cache",
"(",
"table_name",
")",
"[",
"'fields'... | Returns a description of the table, with the DB-API cursor.description interface. | [
"Returns",
"a",
"description",
"of",
"the",
"table",
"with",
"the",
"DB",
"-",
"API",
"cursor",
".",
"description",
"interface",
"."
] | python | train | 58.627907 |
ethereum/py-evm | eth/vm/state.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/state.py#L259-L278 | def get_ancestor_hash(self, block_number: int) -> Hash32:
"""
Return the hash for the ancestor block with number ``block_number``.
Return the empty bytestring ``b''`` if the block number is outside of the
range of available block numbers (typically the last 255 blocks).
"""
... | [
"def",
"get_ancestor_hash",
"(",
"self",
",",
"block_number",
":",
"int",
")",
"->",
"Hash32",
":",
"ancestor_depth",
"=",
"self",
".",
"block_number",
"-",
"block_number",
"-",
"1",
"is_ancestor_depth_out_of_range",
"=",
"(",
"ancestor_depth",
">=",
"MAX_PREV_HEA... | Return the hash for the ancestor block with number ``block_number``.
Return the empty bytestring ``b''`` if the block number is outside of the
range of available block numbers (typically the last 255 blocks). | [
"Return",
"the",
"hash",
"for",
"the",
"ancestor",
"block",
"with",
"number",
"block_number",
".",
"Return",
"the",
"empty",
"bytestring",
"b",
"if",
"the",
"block",
"number",
"is",
"outside",
"of",
"the",
"range",
"of",
"available",
"block",
"numbers",
"(",... | python | train | 40.4 |
delfick/gitmit | gitmit/repo.py | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/repo.py#L140-L176 | def differences_between(self, current_files, parent_files, changes, prefixes):
"""
yield (thing, changes, is_path)
If is_path is true, changes is None and thing is the path as a tuple.
If is_path is false, thing is the current_files and parent_files for
that changed treeentry a... | [
"def",
"differences_between",
"(",
"self",
",",
"current_files",
",",
"parent_files",
",",
"changes",
",",
"prefixes",
")",
":",
"parent_oid",
"=",
"None",
"if",
"any",
"(",
"is_tree",
"for",
"_",
",",
"is_tree",
",",
"_",
"in",
"changes",
")",
":",
"if"... | yield (thing, changes, is_path)
If is_path is true, changes is None and thing is the path as a tuple.
If is_path is false, thing is the current_files and parent_files for
that changed treeentry and changes is the difference between current_files
and parent_files.
The code here... | [
"yield",
"(",
"thing",
"changes",
"is_path",
")"
] | python | train | 41.081081 |
facelessuser/soupsieve | soupsieve/util.py | https://github.com/facelessuser/soupsieve/blob/24859cc3e756ebf46b75547d49c6b4a7bf35ee82/soupsieve/util.py#L124-L131 | def warn_deprecated(message, stacklevel=2): # pragma: no cover
"""Warn deprecated."""
warnings.warn(
message,
category=DeprecationWarning,
stacklevel=stacklevel
) | [
"def",
"warn_deprecated",
"(",
"message",
",",
"stacklevel",
"=",
"2",
")",
":",
"# pragma: no cover",
"warnings",
".",
"warn",
"(",
"message",
",",
"category",
"=",
"DeprecationWarning",
",",
"stacklevel",
"=",
"stacklevel",
")"
] | Warn deprecated. | [
"Warn",
"deprecated",
"."
] | python | train | 24.125 |
Erotemic/utool | utool/util_iter.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L68-L74 | def itake_column(list_, colx):
""" iterator version of get_list_column """
if isinstance(colx, list):
# multi select
return ([row[colx_] for colx_ in colx] for row in list_)
else:
return (row[colx] for row in list_) | [
"def",
"itake_column",
"(",
"list_",
",",
"colx",
")",
":",
"if",
"isinstance",
"(",
"colx",
",",
"list",
")",
":",
"# multi select",
"return",
"(",
"[",
"row",
"[",
"colx_",
"]",
"for",
"colx_",
"in",
"colx",
"]",
"for",
"row",
"in",
"list_",
")",
... | iterator version of get_list_column | [
"iterator",
"version",
"of",
"get_list_column"
] | python | train | 35 |
rvswift/EB | EB/builder/postanalysis/postanalysis_io.py | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis_io.py#L205-L220 | def get_boolean(self, input_string):
"""
Return boolean type user input
"""
if input_string in ('--write_roc', '--plot', '--compare'):
# was the flag set?
try:
index = self.args.index(input_string) + 1
except ValueError:
# it wasn... | [
"def",
"get_boolean",
"(",
"self",
",",
"input_string",
")",
":",
"if",
"input_string",
"in",
"(",
"'--write_roc'",
",",
"'--plot'",
",",
"'--compare'",
")",
":",
"# was the flag set?",
"try",
":",
"index",
"=",
"self",
".",
"args",
".",
"index",
"(",
"inp... | Return boolean type user input | [
"Return",
"boolean",
"type",
"user",
"input"
] | python | train | 29.125 |
saltstack/salt | salt/modules/service.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/service.py#L207-L219 | def get_all():
'''
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
if not os.path.isdir(_GRAINMAP.get(__grains__.get('os'), '/etc/init.d')):
return []
return sorted(os.listdir(_GRAINMAP.get(__grains__.get('os'), '/etc/... | [
"def",
"get_all",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"_GRAINMAP",
".",
"get",
"(",
"__grains__",
".",
"get",
"(",
"'os'",
")",
",",
"'/etc/init.d'",
")",
")",
":",
"return",
"[",
"]",
"return",
"sorted",
"(",
"os",
... | Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' service.get_all | [
"Return",
"a",
"list",
"of",
"all",
"available",
"services"
] | python | train | 24.461538 |
mozilla-releng/scriptworker | scriptworker/cot/verify.py | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/cot/verify.py#L458-L511 | def verify_docker_image_sha(chain, link):
"""Verify that built docker shas match the artifact.
Args:
chain (ChainOfTrust): the chain we're operating on.
link (LinkOfTrust): the task link we're checking.
Raises:
CoTError: on failure.
"""
cot = link.cot
task = link.task
... | [
"def",
"verify_docker_image_sha",
"(",
"chain",
",",
"link",
")",
":",
"cot",
"=",
"link",
".",
"cot",
"task",
"=",
"link",
".",
"task",
"errors",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"task",
"[",
"'payload'",
"]",
".",
"get",
"(",
"'image'",
")",... | Verify that built docker shas match the artifact.
Args:
chain (ChainOfTrust): the chain we're operating on.
link (LinkOfTrust): the task link we're checking.
Raises:
CoTError: on failure. | [
"Verify",
"that",
"built",
"docker",
"shas",
"match",
"the",
"artifact",
"."
] | python | train | 42.981481 |
SKA-ScienceDataProcessor/integration-prototype | sip/execution_control/configuration_db/sip_config_db/scheduling/workflow_definitions.py | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/configuration_db/sip_config_db/scheduling/workflow_definitions.py#L108-L123 | def get_workflows() -> dict:
"""Get dict of ALL known workflow definitions.
Returns
list[dict]
"""
keys = DB.get_keys("workflow_definitions:*")
known_workflows = dict()
for key in keys:
values = key.split(':')
if values[1] not in known_workflows:
known_workf... | [
"def",
"get_workflows",
"(",
")",
"->",
"dict",
":",
"keys",
"=",
"DB",
".",
"get_keys",
"(",
"\"workflow_definitions:*\"",
")",
"known_workflows",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"values",
"=",
"key",
".",
"split",
"(",
"':'",
... | Get dict of ALL known workflow definitions.
Returns
list[dict] | [
"Get",
"dict",
"of",
"ALL",
"known",
"workflow",
"definitions",
"."
] | python | train | 25.625 |
SUSE-Enceladus/ipa | ipa/ipa_gce.py | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_gce.py#L168-L174 | def _get_ssh_public_key(self):
"""Generate SSH public key from private key."""
key = ipa_utils.generate_public_ssh_key(self.ssh_private_key_file)
return '{user}:{key} {user}'.format(
user=self.ssh_user,
key=key.decode()
) | [
"def",
"_get_ssh_public_key",
"(",
"self",
")",
":",
"key",
"=",
"ipa_utils",
".",
"generate_public_ssh_key",
"(",
"self",
".",
"ssh_private_key_file",
")",
"return",
"'{user}:{key} {user}'",
".",
"format",
"(",
"user",
"=",
"self",
".",
"ssh_user",
",",
"key",
... | Generate SSH public key from private key. | [
"Generate",
"SSH",
"public",
"key",
"from",
"private",
"key",
"."
] | python | train | 38.714286 |
ewels/MultiQC | multiqc/modules/base_module.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/base_module.py#L273-L311 | def general_stats_addcols(self, data, headers=None, namespace=None):
""" Helper function to add to the General Statistics variable.
Adds to report.general_stats and does not return anything. Fills
in required config variables if not supplied.
:param data: A dict with the data. First key ... | [
"def",
"general_stats_addcols",
"(",
"self",
",",
"data",
",",
"headers",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"}",
"# Use the module namespace as the name if not supplied",
"if",
"namespa... | Helper function to add to the General Statistics variable.
Adds to report.general_stats and does not return anything. Fills
in required config variables if not supplied.
:param data: A dict with the data. First key should be sample name,
then the data key, then the data.
... | [
"Helper",
"function",
"to",
"add",
"to",
"the",
"General",
"Statistics",
"variable",
".",
"Adds",
"to",
"report",
".",
"general_stats",
"and",
"does",
"not",
"return",
"anything",
".",
"Fills",
"in",
"required",
"config",
"variables",
"if",
"not",
"supplied",
... | python | train | 42.589744 |
thespacedoctor/fundamentals | fundamentals/times.py | https://github.com/thespacedoctor/fundamentals/blob/1d2c007ac74442ec2eabde771cfcacdb9c1ab382/fundamentals/times.py#L42-L95 | def calculate_time_difference(startDate, endDate):
"""
*Return the time difference between two dates as a string*
**Key Arguments:**
- ``startDate`` -- the first date in YYYY-MM-DDTHH:MM:SS format
- ``endDate`` -- the final date YYYY-MM-DDTHH:MM:SS format
**Return:**
- ``relTim... | [
"def",
"calculate_time_difference",
"(",
"startDate",
",",
"endDate",
")",
":",
"################ > IMPORTS ################",
"from",
"datetime",
"import",
"datetime",
"from",
"dateutil",
"import",
"relativedelta",
"################ > VARIABLE SETTINGS ######",
"################... | *Return the time difference between two dates as a string*
**Key Arguments:**
- ``startDate`` -- the first date in YYYY-MM-DDTHH:MM:SS format
- ``endDate`` -- the final date YYYY-MM-DDTHH:MM:SS format
**Return:**
- ``relTime`` -- the difference between the two dates in Y,M,D,h,m,s (str... | [
"*",
"Return",
"the",
"time",
"difference",
"between",
"two",
"dates",
"as",
"a",
"string",
"*"
] | python | train | 30.925926 |
bitesofcode/projexui | projexui/widgets/xnodewidget/xnodescene.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L1322-L1332 | def selectedNodes( self ):
"""
Returns a list of the selected nodes in a scene.
:return <list> [ <XNode>, .. ]
"""
output = []
for item in self.selectedItems():
if ( isinstance(item, XNode) ):
output.append(item)
return out... | [
"def",
"selectedNodes",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"selectedItems",
"(",
")",
":",
"if",
"(",
"isinstance",
"(",
"item",
",",
"XNode",
")",
")",
":",
"output",
".",
"append",
"(",
"item",
")",
... | Returns a list of the selected nodes in a scene.
:return <list> [ <XNode>, .. ] | [
"Returns",
"a",
"list",
"of",
"the",
"selected",
"nodes",
"in",
"a",
"scene",
".",
":",
"return",
"<list",
">",
"[",
"<XNode",
">",
"..",
"]"
] | python | train | 28.454545 |
mojaie/chorus | chorus/molutil.py | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/molutil.py#L37-L54 | def make_Hs_implicit(original_mol, keep_stereo=True):
"""Return molecule that explicit hydrogens removed
TODO: this query function should be renamed to "explicitHs_removed"
"""
mol = clone(original_mol)
mol.descriptors.clear() # Reset descriptor
to_remove = set()
for i, nbrs in mol.neighbor... | [
"def",
"make_Hs_implicit",
"(",
"original_mol",
",",
"keep_stereo",
"=",
"True",
")",
":",
"mol",
"=",
"clone",
"(",
"original_mol",
")",
"mol",
".",
"descriptors",
".",
"clear",
"(",
")",
"# Reset descriptor",
"to_remove",
"=",
"set",
"(",
")",
"for",
"i"... | Return molecule that explicit hydrogens removed
TODO: this query function should be renamed to "explicitHs_removed" | [
"Return",
"molecule",
"that",
"explicit",
"hydrogens",
"removed",
"TODO",
":",
"this",
"query",
"function",
"should",
"be",
"renamed",
"to",
"explicitHs_removed"
] | python | train | 37.833333 |
openid/python-openid | openid/consumer/consumer.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1364-L1440 | def _extractAssociation(self, assoc_response, assoc_session):
"""Attempt to extract an association from the response, given
the association response message and the established
association session.
@param assoc_response: The association response message from
the server
... | [
"def",
"_extractAssociation",
"(",
"self",
",",
"assoc_response",
",",
"assoc_session",
")",
":",
"# Extract the common fields from the response, raising an",
"# exception if they are not found",
"assoc_type",
"=",
"assoc_response",
".",
"getArg",
"(",
"OPENID_NS",
",",
"'ass... | Attempt to extract an association from the response, given
the association response message and the established
association session.
@param assoc_response: The association response message from
the server
@type assoc_response: openid.message.Message
@param assoc_ses... | [
"Attempt",
"to",
"extract",
"an",
"association",
"from",
"the",
"response",
"given",
"the",
"association",
"response",
"message",
"and",
"the",
"established",
"association",
"session",
"."
] | python | train | 44.597403 |
rocky/python-uncompyle6 | uncompyle6/semantics/fragments.py | https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/semantics/fragments.py#L1898-L1910 | def op_at_code_loc(code, loc, opc):
"""Return the instruction name at code[loc] using
opc to look up instruction names. Returns 'got IndexError'
if code[loc] is invalid.
`code` is instruction bytecode, `loc` is an offset (integer) and
`opc` is an opcode module from `xdis`.
"""
try:
... | [
"def",
"op_at_code_loc",
"(",
"code",
",",
"loc",
",",
"opc",
")",
":",
"try",
":",
"op",
"=",
"code",
"[",
"loc",
"]",
"except",
"IndexError",
":",
"return",
"'got IndexError'",
"return",
"opc",
".",
"opname",
"[",
"op",
"]"
] | Return the instruction name at code[loc] using
opc to look up instruction names. Returns 'got IndexError'
if code[loc] is invalid.
`code` is instruction bytecode, `loc` is an offset (integer) and
`opc` is an opcode module from `xdis`. | [
"Return",
"the",
"instruction",
"name",
"at",
"code",
"[",
"loc",
"]",
"using",
"opc",
"to",
"look",
"up",
"instruction",
"names",
".",
"Returns",
"got",
"IndexError",
"if",
"code",
"[",
"loc",
"]",
"is",
"invalid",
"."
] | python | train | 31 |
gboeing/osmnx | osmnx/simplify.py | https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/simplify.py#L302-L357 | def clean_intersections(G, tolerance=15, dead_ends=False):
"""
Clean-up intersections comprising clusters of nodes by merging them and
returning their centroids.
Divided roads are represented by separate centerline edges. The intersection
of two divided roads thus creates 4 nodes, representing wher... | [
"def",
"clean_intersections",
"(",
"G",
",",
"tolerance",
"=",
"15",
",",
"dead_ends",
"=",
"False",
")",
":",
"# if dead_ends is False, discard dead-end nodes to only work with edge",
"# intersections",
"if",
"not",
"dead_ends",
":",
"if",
"'streets_per_node'",
"in",
"... | Clean-up intersections comprising clusters of nodes by merging them and
returning their centroids.
Divided roads are represented by separate centerline edges. The intersection
of two divided roads thus creates 4 nodes, representing where each edge
intersects a perpendicular edge. These 4 nodes represen... | [
"Clean",
"-",
"up",
"intersections",
"comprising",
"clusters",
"of",
"nodes",
"by",
"merging",
"them",
"and",
"returning",
"their",
"centroids",
"."
] | python | train | 39.642857 |
gboeing/osmnx | osmnx/plot.py | https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/plot.py#L488-L620 | def plot_graph_route(G, route, bbox=None, fig_height=6, fig_width=None,
margin=0.02, bgcolor='w', axis_off=True, show=True,
save=False, close=True, file_format='png', filename='temp',
dpi=300, annotate=False, node_color='#999999',
node_... | [
"def",
"plot_graph_route",
"(",
"G",
",",
"route",
",",
"bbox",
"=",
"None",
",",
"fig_height",
"=",
"6",
",",
"fig_width",
"=",
"None",
",",
"margin",
"=",
"0.02",
",",
"bgcolor",
"=",
"'w'",
",",
"axis_off",
"=",
"True",
",",
"show",
"=",
"True",
... | Plot a route along a networkx spatial graph.
Parameters
----------
G : networkx multidigraph
route : list
the route as a list of nodes
bbox : tuple
bounding box as north,south,east,west - if None will calculate from
spatial extents of data. if passing a bbox, you probably al... | [
"Plot",
"a",
"route",
"along",
"a",
"networkx",
"spatial",
"graph",
"."
] | python | train | 41.984962 |
python-useful-helpers/threaded | threaded/_threadpooled.py | https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/threaded/_threadpooled.py#L178-L184 | def threadpooled(
func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]],
*,
loop_getter: None = None,
loop_getter_need_context: bool = False,
) -> typing.Callable[..., "concurrent.futures.Future[typing.Any]"]:
"""Overload: function callable, no loop getter.""" | [
"def",
"threadpooled",
"(",
"func",
":",
"typing",
".",
"Callable",
"[",
"...",
",",
"typing",
".",
"Union",
"[",
"\"typing.Awaitable[typing.Any]\"",
",",
"typing",
".",
"Any",
"]",
"]",
",",
"*",
",",
"loop_getter",
":",
"None",
"=",
"None",
",",
"loop_... | Overload: function callable, no loop getter. | [
"Overload",
":",
"function",
"callable",
"no",
"loop",
"getter",
"."
] | python | train | 43.571429 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/plot/plotwidget.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/plot/plotwidget.py#L159-L182 | def histogram(self, data, bins=10, color='w', orientation='h'):
"""Calculate and show a histogram of data
Parameters
----------
data : array-like
Data to histogram. Currently only 1D data is supported.
bins : int | array-like
Number of bins, or bin edges.... | [
"def",
"histogram",
"(",
"self",
",",
"data",
",",
"bins",
"=",
"10",
",",
"color",
"=",
"'w'",
",",
"orientation",
"=",
"'h'",
")",
":",
"self",
".",
"_configure_2d",
"(",
")",
"hist",
"=",
"scene",
".",
"Histogram",
"(",
"data",
",",
"bins",
",",... | Calculate and show a histogram of data
Parameters
----------
data : array-like
Data to histogram. Currently only 1D data is supported.
bins : int | array-like
Number of bins, or bin edges.
color : instance of Color
Color of the histogram.
... | [
"Calculate",
"and",
"show",
"a",
"histogram",
"of",
"data"
] | python | train | 30.583333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.