repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
aetros/aetros-cli | aetros/utils/image.py | https://github.com/aetros/aetros-cli/blob/a2a1f38d6af1660e1e2680c7d413ec2aef45faab/aetros/utils/image.py#L274-L339 | def get_layer_vis_square(data,
allow_heatmap=True,
normalize=True,
min_img_dim=100,
max_width=1200,
channel_order='RGB',
colormap='jet',
):
"... | [
"def",
"get_layer_vis_square",
"(",
"data",
",",
"allow_heatmap",
"=",
"True",
",",
"normalize",
"=",
"True",
",",
"min_img_dim",
"=",
"100",
",",
"max_width",
"=",
"1200",
",",
"channel_order",
"=",
"'RGB'",
",",
"colormap",
"=",
"'jet'",
",",
")",
":",
... | Returns a vis_square for the given layer data
Arguments:
data -- a np.ndarray
Keyword arguments:
allow_heatmap -- if True, convert single channel images to heatmaps
normalize -- whether to normalize the data when visualizing
max_width -- maximum width for the vis_square | [
"Returns",
"a",
"vis_square",
"for",
"the",
"given",
"layer",
"data",
"Arguments",
":",
"data",
"--",
"a",
"np",
".",
"ndarray",
"Keyword",
"arguments",
":",
"allow_heatmap",
"--",
"if",
"True",
"convert",
"single",
"channel",
"images",
"to",
"heatmaps",
"no... | python | train |
saulpw/visidata | visidata/vdtui.py | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L1537-L1543 | def unselect(self, rows, status=True, progress=True):
"Unselect given rows. Don't show progress if progress=False; don't show status if status=False."
before = len(self._selectedRows)
for r in (Progress(rows, 'unselecting') if progress else rows):
self.unselectRow(r)
if statu... | [
"def",
"unselect",
"(",
"self",
",",
"rows",
",",
"status",
"=",
"True",
",",
"progress",
"=",
"True",
")",
":",
"before",
"=",
"len",
"(",
"self",
".",
"_selectedRows",
")",
"for",
"r",
"in",
"(",
"Progress",
"(",
"rows",
",",
"'unselecting'",
")",
... | Unselect given rows. Don't show progress if progress=False; don't show status if status=False. | [
"Unselect",
"given",
"rows",
".",
"Don",
"t",
"show",
"progress",
"if",
"progress",
"=",
"False",
";",
"don",
"t",
"show",
"status",
"if",
"status",
"=",
"False",
"."
] | python | train |
Nic30/hwt | hwt/hdl/transTmpl.py | https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/transTmpl.py#L162-L171 | def _loadFromUnion(self, dtype: HdlType, bitAddr: int) -> int:
"""
Parse HUnion type to this transaction template instance
:return: address of it's end
"""
for field in dtype.fields.values():
ch = TransTmpl(field.dtype, 0, parent=self, origin=field)
self.... | [
"def",
"_loadFromUnion",
"(",
"self",
",",
"dtype",
":",
"HdlType",
",",
"bitAddr",
":",
"int",
")",
"->",
"int",
":",
"for",
"field",
"in",
"dtype",
".",
"fields",
".",
"values",
"(",
")",
":",
"ch",
"=",
"TransTmpl",
"(",
"field",
".",
"dtype",
"... | Parse HUnion type to this transaction template instance
:return: address of it's end | [
"Parse",
"HUnion",
"type",
"to",
"this",
"transaction",
"template",
"instance"
] | python | test |
saltstack/salt | salt/modules/iptables.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iptables.py#L956-L974 | def flush(table='filter', chain='', family='ipv4'):
'''
Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPU... | [
"def",
"flush",
"(",
"table",
"=",
"'filter'",
",",
"chain",
"=",
"''",
",",
"family",
"=",
"'ipv4'",
")",
":",
"wait",
"=",
"'--wait'",
"if",
"_has_option",
"(",
"'--wait'",
",",
"family",
")",
"else",
"''",
"cmd",
"=",
"'{0} {1} -t {2} -F {3}'",
".",
... | Flush the chain in the specified table, flush all chains in the specified
table if not specified chain.
CLI Example:
.. code-block:: bash
salt '*' iptables.flush filter INPUT
IPv6:
salt '*' iptables.flush filter INPUT family=ipv6 | [
"Flush",
"the",
"chain",
"in",
"the",
"specified",
"table",
"flush",
"all",
"chains",
"in",
"the",
"specified",
"table",
"if",
"not",
"specified",
"chain",
"."
] | python | train |
tango-controls/pytango | tango/device_class.py | https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/device_class.py#L119-L164 | def get_device_properties(self, dev, class_prop, dev_prop):
"""
get_device_properties(self, dev, class_prop, dev_prop) -> None
Returns the device properties
Parameters :
- dev : (DeviceImpl) the device object
- class_prop ... | [
"def",
"get_device_properties",
"(",
"self",
",",
"dev",
",",
"class_prop",
",",
"dev_prop",
")",
":",
"# initialize default properties",
"if",
"dev_prop",
"==",
"{",
"}",
"or",
"not",
"Util",
".",
"_UseDb",
":",
"return",
"# Call database to get properties",
"... | get_device_properties(self, dev, class_prop, dev_prop) -> None
Returns the device properties
Parameters :
- dev : (DeviceImpl) the device object
- class_prop : (dict<str, obj>) the class properties
- dev_prop : [in,out] (d... | [
"get_device_properties",
"(",
"self",
"dev",
"class_prop",
"dev_prop",
")",
"-",
">",
"None"
] | python | train |
serkanyersen/underscore.py | src/underscore.py | https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L1202-L1210 | def isFile(self):
""" Check if the given object is a file
"""
try:
filetype = file
except NameError:
filetype = io.IOBase
return self._wrap(type(self.obj) is filetype) | [
"def",
"isFile",
"(",
"self",
")",
":",
"try",
":",
"filetype",
"=",
"file",
"except",
"NameError",
":",
"filetype",
"=",
"io",
".",
"IOBase",
"return",
"self",
".",
"_wrap",
"(",
"type",
"(",
"self",
".",
"obj",
")",
"is",
"filetype",
")"
] | Check if the given object is a file | [
"Check",
"if",
"the",
"given",
"object",
"is",
"a",
"file"
] | python | train |
mkaz/termgraph | termgraph/termgraph.py | https://github.com/mkaz/termgraph/blob/c40b86454d380d685785b98834364b111734c163/termgraph/termgraph.py#L166-L173 | def find_max_label_length(labels):
"""Return the maximum length for the labels."""
length = 0
for i in range(len(labels)):
if len(labels[i]) > length:
length = len(labels[i])
return length | [
"def",
"find_max_label_length",
"(",
"labels",
")",
":",
"length",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"labels",
")",
")",
":",
"if",
"len",
"(",
"labels",
"[",
"i",
"]",
")",
">",
"length",
":",
"length",
"=",
"len",
"(",
"labe... | Return the maximum length for the labels. | [
"Return",
"the",
"maximum",
"length",
"for",
"the",
"labels",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L192-L207 | def overlay_gateway_attach_vlan_vid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
name_ke... | [
"def",
"overlay_gateway_attach_vlan_vid",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"overlay_gateway",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"overlay-gateway\"",
",",
"xmlns",
"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
spacetelescope/stsci.tools | lib/stsci/tools/wcsutil.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/wcsutil.py#L452-L454 | def compute_pscale(self,cd11,cd21):
""" Compute the pixel scale based on active WCS values. """
return N.sqrt(N.power(cd11,2)+N.power(cd21,2)) * 3600. | [
"def",
"compute_pscale",
"(",
"self",
",",
"cd11",
",",
"cd21",
")",
":",
"return",
"N",
".",
"sqrt",
"(",
"N",
".",
"power",
"(",
"cd11",
",",
"2",
")",
"+",
"N",
".",
"power",
"(",
"cd21",
",",
"2",
")",
")",
"*",
"3600."
] | Compute the pixel scale based on active WCS values. | [
"Compute",
"the",
"pixel",
"scale",
"based",
"on",
"active",
"WCS",
"values",
"."
] | python | train |
wummel/dosage | dosagelib/loader.py | https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/dosagelib/loader.py#L73-L91 | def get_module_plugins(module, classobj):
"""Return all subclasses of a class in the module.
If the module defines __all__, only those entries will be searched,
otherwise all objects not starting with '_' will be searched.
"""
try:
names = module.__all__
except AttributeError:
na... | [
"def",
"get_module_plugins",
"(",
"module",
",",
"classobj",
")",
":",
"try",
":",
"names",
"=",
"module",
".",
"__all__",
"except",
"AttributeError",
":",
"names",
"=",
"[",
"x",
"for",
"x",
"in",
"vars",
"(",
"module",
")",
"if",
"not",
"x",
".",
"... | Return all subclasses of a class in the module.
If the module defines __all__, only those entries will be searched,
otherwise all objects not starting with '_' will be searched. | [
"Return",
"all",
"subclasses",
"of",
"a",
"class",
"in",
"the",
"module",
".",
"If",
"the",
"module",
"defines",
"__all__",
"only",
"those",
"entries",
"will",
"be",
"searched",
"otherwise",
"all",
"objects",
"not",
"starting",
"with",
"_",
"will",
"be",
"... | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/__init__.py#L14148-L14171 | def _set_cfm_state(self, v, load=False):
"""
Setter method for cfm_state, mapped from YANG variable /cfm_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cfm_state is considered as a private
method. Backends looking to populate this variable should
... | [
"def",
"_set_cfm_state",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base... | Setter method for cfm_state, mapped from YANG variable /cfm_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cfm_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_cfm_state() directl... | [
"Setter",
"method",
"for",
"cfm_state",
"mapped",
"from",
"YANG",
"variable",
"/",
"cfm_state",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
"then",
"... | python | train |
trailofbits/manticore | manticore/native/cpu/abstractcpu.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L291-L299 | def values_from(self, base):
"""
A reusable generator for increasing pointer-sized values from an address
(usually the stack).
"""
word_bytes = self._cpu.address_bit_size // 8
while True:
yield base
base += word_bytes | [
"def",
"values_from",
"(",
"self",
",",
"base",
")",
":",
"word_bytes",
"=",
"self",
".",
"_cpu",
".",
"address_bit_size",
"//",
"8",
"while",
"True",
":",
"yield",
"base",
"base",
"+=",
"word_bytes"
] | A reusable generator for increasing pointer-sized values from an address
(usually the stack). | [
"A",
"reusable",
"generator",
"for",
"increasing",
"pointer",
"-",
"sized",
"values",
"from",
"an",
"address",
"(",
"usually",
"the",
"stack",
")",
"."
] | python | valid |
Rediker-Software/doac | doac/decorators.py | https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/decorators.py#L7-L77 | def scope_required(*scopes):
"""
Test for specific scopes that the access token has been authenticated for before
processing the request and eventual response.
The scopes that are passed in determine how the decorator will respond to incoming
requests:
- If no scopes are passed in the argument... | [
"def",
"scope_required",
"(",
"*",
"scopes",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"view_func",
")",
")",
"def",
"_wrapped_view",
"(",
"request",
",",
"*",
... | Test for specific scopes that the access token has been authenticated for before
processing the request and eventual response.
The scopes that are passed in determine how the decorator will respond to incoming
requests:
- If no scopes are passed in the arguments, the decorator will test for any availa... | [
"Test",
"for",
"specific",
"scopes",
"that",
"the",
"access",
"token",
"has",
"been",
"authenticated",
"for",
"before",
"processing",
"the",
"request",
"and",
"eventual",
"response",
"."
] | python | train |
gem/oq-engine | openquake/hazardlib/geo/polygon.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/polygon.py#L249-L291 | def get_resampled_coordinates(lons, lats):
"""
Resample polygon line segments and return the coordinates of the new
vertices. This limits distortions when projecting a polygon onto a
spherical surface.
Parameters define longitudes and latitudes of a point collection in the
form of lists or nump... | [
"def",
"get_resampled_coordinates",
"(",
"lons",
",",
"lats",
")",
":",
"num_coords",
"=",
"len",
"(",
"lons",
")",
"assert",
"num_coords",
"==",
"len",
"(",
"lats",
")",
"lons1",
"=",
"numpy",
".",
"array",
"(",
"lons",
")",
"lats1",
"=",
"numpy",
"."... | Resample polygon line segments and return the coordinates of the new
vertices. This limits distortions when projecting a polygon onto a
spherical surface.
Parameters define longitudes and latitudes of a point collection in the
form of lists or numpy arrays.
:return:
A tuple of two numpy ar... | [
"Resample",
"polygon",
"line",
"segments",
"and",
"return",
"the",
"coordinates",
"of",
"the",
"new",
"vertices",
".",
"This",
"limits",
"distortions",
"when",
"projecting",
"a",
"polygon",
"onto",
"a",
"spherical",
"surface",
"."
] | python | train |
pantsbuild/pants | src/python/pants/build_graph/build_file_parser.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/build_graph/build_file_parser.py#L90-L171 | def parse_build_file(self, build_file):
"""Capture Addressable instances from parsing `build_file`.
Prepare a context for parsing, read a BUILD file from the filesystem, and return the
Addressable instances generated by executing the code.
"""
def _format_context_msg(lineno, offset, error_type, mes... | [
"def",
"parse_build_file",
"(",
"self",
",",
"build_file",
")",
":",
"def",
"_format_context_msg",
"(",
"lineno",
",",
"offset",
",",
"error_type",
",",
"message",
")",
":",
"\"\"\"Show the line of the BUILD file that has the error along with a few line of context\"\"\"",
"... | Capture Addressable instances from parsing `build_file`.
Prepare a context for parsing, read a BUILD file from the filesystem, and return the
Addressable instances generated by executing the code. | [
"Capture",
"Addressable",
"instances",
"from",
"parsing",
"build_file",
".",
"Prepare",
"a",
"context",
"for",
"parsing",
"read",
"a",
"BUILD",
"file",
"from",
"the",
"filesystem",
"and",
"return",
"the",
"Addressable",
"instances",
"generated",
"by",
"executing",... | python | train |
ucbvislab/radiotool | radiotool/composer/track.py | https://github.com/ucbvislab/radiotool/blob/01c9d878a811cf400b1482896d641d9c95e83ded/radiotool/composer/track.py#L200-L210 | def zero_crossing_after(self, n):
"""Find nearest zero crossing in waveform after frame ``n``"""
n_in_samples = int(n * self.samplerate)
search_end = n_in_samples + self.samplerate
if search_end > self.duration:
search_end = self.duration
frame = zero_crossing_first(... | [
"def",
"zero_crossing_after",
"(",
"self",
",",
"n",
")",
":",
"n_in_samples",
"=",
"int",
"(",
"n",
"*",
"self",
".",
"samplerate",
")",
"search_end",
"=",
"n_in_samples",
"+",
"self",
".",
"samplerate",
"if",
"search_end",
">",
"self",
".",
"duration",
... | Find nearest zero crossing in waveform after frame ``n`` | [
"Find",
"nearest",
"zero",
"crossing",
"in",
"waveform",
"after",
"frame",
"n"
] | python | train |
tkf/rash | rash/indexer.py | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/indexer.py#L76-L107 | def index_record(self, json_path):
"""
Import `json_path` and remove it if :attr:`keep_json` is false.
"""
self.logger.debug('Indexing record: %s', json_path)
json_path = os.path.abspath(json_path)
self.check_path(json_path, '`json_path`')
with open(json_path) as... | [
"def",
"index_record",
"(",
"self",
",",
"json_path",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Indexing record: %s'",
",",
"json_path",
")",
"json_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"json_path",
")",
"self",
".",
"check_path",... | Import `json_path` and remove it if :attr:`keep_json` is false. | [
"Import",
"json_path",
"and",
"remove",
"it",
"if",
":",
"attr",
":",
"keep_json",
"is",
"false",
"."
] | python | train |
hotdoc/hotdoc | hotdoc/utils/loggable.py | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L298-L304 | def get_issues():
"""Get actual issues in the journal."""
issues = []
for entry in Logger.journal:
if entry.level >= WARNING:
issues.append(entry)
return issues | [
"def",
"get_issues",
"(",
")",
":",
"issues",
"=",
"[",
"]",
"for",
"entry",
"in",
"Logger",
".",
"journal",
":",
"if",
"entry",
".",
"level",
">=",
"WARNING",
":",
"issues",
".",
"append",
"(",
"entry",
")",
"return",
"issues"
] | Get actual issues in the journal. | [
"Get",
"actual",
"issues",
"in",
"the",
"journal",
"."
] | python | train |
lreis2415/PyGeoC | pygeoc/raster.py | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L340-L366 | def raster_reclassify(srcfile, v_dict, dstfile, gdaltype=GDT_Float32):
"""Reclassify raster by given classifier dict.
Args:
srcfile: source raster file.
v_dict: classifier dict.
dstfile: destination file path.
gdaltype (:obj:`pygeoc.raster.GDALDataType`):... | [
"def",
"raster_reclassify",
"(",
"srcfile",
",",
"v_dict",
",",
"dstfile",
",",
"gdaltype",
"=",
"GDT_Float32",
")",
":",
"src_r",
"=",
"RasterUtilClass",
".",
"read_raster",
"(",
"srcfile",
")",
"src_data",
"=",
"src_r",
".",
"data",
"dst_data",
"=",
"numpy... | Reclassify raster by given classifier dict.
Args:
srcfile: source raster file.
v_dict: classifier dict.
dstfile: destination file path.
gdaltype (:obj:`pygeoc.raster.GDALDataType`): GDT_Float32 as default. | [
"Reclassify",
"raster",
"by",
"given",
"classifier",
"dict",
"."
] | python | train |
twilio/twilio-python | twilio/rest/api/v2010/account/usage/record/daily.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/record/daily.py#L102-L137 | def page(self, category=values.unset, start_date=values.unset,
end_date=values.unset, include_subaccounts=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of DailyInstance records from the API.
... | [
"def",
"page",
"(",
"self",
",",
"category",
"=",
"values",
".",
"unset",
",",
"start_date",
"=",
"values",
".",
"unset",
",",
"end_date",
"=",
"values",
".",
"unset",
",",
"include_subaccounts",
"=",
"values",
".",
"unset",
",",
"page_token",
"=",
"valu... | Retrieve a single page of DailyInstance records from the API.
Request is executed immediately
:param DailyInstance.Category category: The usage category of the UsageRecord resources to read
:param date start_date: Only include usage that has occurred on or after this date
:param date en... | [
"Retrieve",
"a",
"single",
"page",
"of",
"DailyInstance",
"records",
"from",
"the",
"API",
".",
"Request",
"is",
"executed",
"immediately"
] | python | train |
spyder-ide/spyder | spyder/plugins/editor/widgets/base.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/widgets/base.py#L1065-L1075 | def hide_tooltip_if_necessary(self, key):
"""Hide calltip when necessary"""
try:
calltip_char = self.get_character(self.calltip_position)
before = self.is_cursor_before(self.calltip_position,
char_offset=1)
other = key ... | [
"def",
"hide_tooltip_if_necessary",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"calltip_char",
"=",
"self",
".",
"get_character",
"(",
"self",
".",
"calltip_position",
")",
"before",
"=",
"self",
".",
"is_cursor_before",
"(",
"self",
".",
"calltip_position... | Hide calltip when necessary | [
"Hide",
"calltip",
"when",
"necessary"
] | python | train |
astraw/stdeb | stdeb/util.py | https://github.com/astraw/stdeb/blob/493ab88e8a60be053b1baef81fb39b45e17ceef5/stdeb/util.py#L595-L609 | def parse_vals(cfg,section,option):
"""parse comma separated values in debian control file style from .cfg"""
try:
vals = cfg.get(section,option)
except ConfigParser.NoSectionError as err:
if section != 'DEFAULT':
vals = cfg.get('DEFAULT',option)
else:
raise e... | [
"def",
"parse_vals",
"(",
"cfg",
",",
"section",
",",
"option",
")",
":",
"try",
":",
"vals",
"=",
"cfg",
".",
"get",
"(",
"section",
",",
"option",
")",
"except",
"ConfigParser",
".",
"NoSectionError",
"as",
"err",
":",
"if",
"section",
"!=",
"'DEFAUL... | parse comma separated values in debian control file style from .cfg | [
"parse",
"comma",
"separated",
"values",
"in",
"debian",
"control",
"file",
"style",
"from",
".",
"cfg"
] | python | train |
i3visio/deepify | deepify/zeronet.py | https://github.com/i3visio/deepify/blob/2af04e0bea3eaabe96b0565e10f7eeb29b042a2b/deepify/zeronet.py#L52-L81 | def _grabContentFromUrl(self, url):
"""
Function that abstracts capturing a URL. This method rewrites the one from Wrapper.
:param url: The URL to be processed.
:return: The response in a Json format.
"""
# Defining an empty object for the res... | [
"def",
"_grabContentFromUrl",
"(",
"self",
",",
"url",
")",
":",
"# Defining an empty object for the response",
"info",
"=",
"{",
"}",
"# This part has to be modified... ",
"try",
":",
"# Configuring the socket",
"queryURL",
"=",
"\"http://\"",
"+",
"self",
".",
... | Function that abstracts capturing a URL. This method rewrites the one from Wrapper.
:param url: The URL to be processed.
:return: The response in a Json format. | [
"Function",
"that",
"abstracts",
"capturing",
"a",
"URL",
".",
"This",
"method",
"rewrites",
"the",
"one",
"from",
"Wrapper",
".",
":",
"param",
"url",
":",
"The",
"URL",
"to",
"be",
"processed",
".",
":",
"return",
":",
"The",
"response",
"in",
"a",
"... | python | train |
stan-dev/pystan | pystan/misc.py | https://github.com/stan-dev/pystan/blob/57bdccea11888157e7aaafba083003080a934805/pystan/misc.py#L715-L740 | def _organize_inits(inits, pars, dims):
"""Obtain a list of initial values for each chain.
The parameter 'lp__' will be removed from the chains.
Parameters
----------
inits : list
list of initial values for each chain.
pars : list of str
dims : list of list of int
from (via... | [
"def",
"_organize_inits",
"(",
"inits",
",",
"pars",
",",
"dims",
")",
":",
"try",
":",
"idx_of_lp",
"=",
"pars",
".",
"index",
"(",
"'lp__'",
")",
"del",
"pars",
"[",
"idx_of_lp",
"]",
"del",
"dims",
"[",
"idx_of_lp",
"]",
"except",
"ValueError",
":",... | Obtain a list of initial values for each chain.
The parameter 'lp__' will be removed from the chains.
Parameters
----------
inits : list
list of initial values for each chain.
pars : list of str
dims : list of list of int
from (via cython conversion) vector[vector[uint]] dims
... | [
"Obtain",
"a",
"list",
"of",
"initial",
"values",
"for",
"each",
"chain",
"."
] | python | train |
tamasgal/km3pipe | km3pipe/tools.py | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/tools.py#L369-L382 | def get_jpp_revision(via_command='JPrint'):
"""Retrieves the Jpp revision number"""
try:
output = subprocess.check_output([via_command, '-v'],
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if e.returncode == 1:
outpu... | [
"def",
"get_jpp_revision",
"(",
"via_command",
"=",
"'JPrint'",
")",
":",
"try",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"via_command",
",",
"'-v'",
"]",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"except",
"subprocess",
... | Retrieves the Jpp revision number | [
"Retrieves",
"the",
"Jpp",
"revision",
"number"
] | python | train |
ask/carrot | carrot/backends/base.py | https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/backends/base.py#L31-L35 | def decode(self):
"""Deserialize the message body, returning the original
python structure sent by the publisher."""
return serialization.decode(self.body, self.content_type,
self.content_encoding) | [
"def",
"decode",
"(",
"self",
")",
":",
"return",
"serialization",
".",
"decode",
"(",
"self",
".",
"body",
",",
"self",
".",
"content_type",
",",
"self",
".",
"content_encoding",
")"
] | Deserialize the message body, returning the original
python structure sent by the publisher. | [
"Deserialize",
"the",
"message",
"body",
"returning",
"the",
"original",
"python",
"structure",
"sent",
"by",
"the",
"publisher",
"."
] | python | train |
BernardFW/bernard | src/bernard/misc/main/_base.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/main/_base.py#L58-L78 | def main():
"""
Run the appropriate main function according to the output of the parser.
"""
parser = make_parser()
args = parser.parse_args()
if not hasattr(args, 'action'):
parser.print_help()
exit(1)
if args.action == 'sheet':
from bernard.misc.sheet_sync import... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"make_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"not",
"hasattr",
"(",
"args",
",",
"'action'",
")",
":",
"parser",
".",
"print_help",
"(",
")",
"exit",
"(",
"1",
")",
... | Run the appropriate main function according to the output of the parser. | [
"Run",
"the",
"appropriate",
"main",
"function",
"according",
"to",
"the",
"output",
"of",
"the",
"parser",
"."
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/zhao_2006.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L142-L157 | def _compute_focal_depth_term(self, C, hypo_depth):
"""
Compute fourth term in equation 1, p. 901.
"""
# p. 901. "(i.e, depth is capped at 125 km)".
focal_depth = hypo_depth
if focal_depth > 125.0:
focal_depth = 125.0
# p. 902. "We used the value of 1... | [
"def",
"_compute_focal_depth_term",
"(",
"self",
",",
"C",
",",
"hypo_depth",
")",
":",
"# p. 901. \"(i.e, depth is capped at 125 km)\".",
"focal_depth",
"=",
"hypo_depth",
"if",
"focal_depth",
">",
"125.0",
":",
"focal_depth",
"=",
"125.0",
"# p. 902. \"We used the value... | Compute fourth term in equation 1, p. 901. | [
"Compute",
"fourth",
"term",
"in",
"equation",
"1",
"p",
".",
"901",
"."
] | python | train |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L128-L137 | def clear(self):
"""
Clear the cache and remove all the files from disk.
"""
self.log(u"Clearing cache...")
for file_handler, file_info in self.cache.values():
self.log([u" Removing file '%s'", file_info])
gf.delete_file(file_handler, file_info)
s... | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Clearing cache...\"",
")",
"for",
"file_handler",
",",
"file_info",
"in",
"self",
".",
"cache",
".",
"values",
"(",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\" Removing file '%s'\"",
"... | Clear the cache and remove all the files from disk. | [
"Clear",
"the",
"cache",
"and",
"remove",
"all",
"the",
"files",
"from",
"disk",
"."
] | python | train |
UpCloudLtd/upcloud-python-api | upcloud_api/server.py | https://github.com/UpCloudLtd/upcloud-python-api/blob/954b0ad7c4b932b2be31a95d88975f6b0eeac8ed/upcloud_api/server.py#L435-L437 | def get_public_ip(self, addr_family=None, *args, **kwargs):
"""Alias for get_ip('public')"""
return self.get_ip('public', addr_family, *args, **kwargs) | [
"def",
"get_public_ip",
"(",
"self",
",",
"addr_family",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get_ip",
"(",
"'public'",
",",
"addr_family",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Alias for get_ip('public') | [
"Alias",
"for",
"get_ip",
"(",
"public",
")"
] | python | train |
websauna/pyramid_notebook | pyramid_notebook/views.py | https://github.com/websauna/pyramid_notebook/blob/8a7ecfa0259810de1a818e4b415a62811a7b077a/pyramid_notebook/views.py#L155-L171 | def notebook_proxy(request, username):
"""Renders a IPython Notebook frame wrapper.
Starts or reattachs ot an existing Notebook session.
"""
security_check(request, username)
manager = get_notebook_manager(request)
notebook_info = manager.get_context(username)
if not notebook_info:
... | [
"def",
"notebook_proxy",
"(",
"request",
",",
"username",
")",
":",
"security_check",
"(",
"request",
",",
"username",
")",
"manager",
"=",
"get_notebook_manager",
"(",
"request",
")",
"notebook_info",
"=",
"manager",
".",
"get_context",
"(",
"username",
")",
... | Renders a IPython Notebook frame wrapper.
Starts or reattachs ot an existing Notebook session. | [
"Renders",
"a",
"IPython",
"Notebook",
"frame",
"wrapper",
"."
] | python | train |
eventbrite/pysoa | pysoa/common/transport/local.py | https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/common/transport/local.py#L103-L107 | def send_response_message(self, request_id, meta, body):
"""
Add the response to the deque.
"""
self.response_messages.append((request_id, meta, body)) | [
"def",
"send_response_message",
"(",
"self",
",",
"request_id",
",",
"meta",
",",
"body",
")",
":",
"self",
".",
"response_messages",
".",
"append",
"(",
"(",
"request_id",
",",
"meta",
",",
"body",
")",
")"
] | Add the response to the deque. | [
"Add",
"the",
"response",
"to",
"the",
"deque",
"."
] | python | train |
apple/turicreate | src/unity/python/turicreate/toolkits/recommender/popularity_recommender.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/recommender/popularity_recommender.py#L15-L102 | def create(observation_data,
user_id='user_id', item_id='item_id', target=None,
user_data=None, item_data=None,
random_seed=0,
verbose=True):
"""
Create a model that makes recommendations using item popularity. When no
target column is provided, the popularity is ... | [
"def",
"create",
"(",
"observation_data",
",",
"user_id",
"=",
"'user_id'",
",",
"item_id",
"=",
"'item_id'",
",",
"target",
"=",
"None",
",",
"user_data",
"=",
"None",
",",
"item_data",
"=",
"None",
",",
"random_seed",
"=",
"0",
",",
"verbose",
"=",
"Tr... | Create a model that makes recommendations using item popularity. When no
target column is provided, the popularity is determined by the number of
observations involving each item. When a target is provided, popularity
is computed using the item's mean target value. When the target column
contains rating... | [
"Create",
"a",
"model",
"that",
"makes",
"recommendations",
"using",
"item",
"popularity",
".",
"When",
"no",
"target",
"column",
"is",
"provided",
"the",
"popularity",
"is",
"determined",
"by",
"the",
"number",
"of",
"observations",
"involving",
"each",
"item",... | python | train |
kgori/treeCl | treeCl/distance_matrix.py | https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/distance_matrix.py#L126-L134 | def check_pd(matrix):
""" A symmetric matrix (M) is PD if it has a Cholesky decomposition, i.e.
M = R.T dot R, where R is upper triangular with positive diagonal entries
"""
try:
np.linalg.cholesky(matrix)
return True
except np.linalg.LinAlgError:
return False | [
"def",
"check_pd",
"(",
"matrix",
")",
":",
"try",
":",
"np",
".",
"linalg",
".",
"cholesky",
"(",
"matrix",
")",
"return",
"True",
"except",
"np",
".",
"linalg",
".",
"LinAlgError",
":",
"return",
"False"
] | A symmetric matrix (M) is PD if it has a Cholesky decomposition, i.e.
M = R.T dot R, where R is upper triangular with positive diagonal entries | [
"A",
"symmetric",
"matrix",
"(",
"M",
")",
"is",
"PD",
"if",
"it",
"has",
"a",
"Cholesky",
"decomposition",
"i",
".",
"e",
".",
"M",
"=",
"R",
".",
"T",
"dot",
"R",
"where",
"R",
"is",
"upper",
"triangular",
"with",
"positive",
"diagonal",
"entries"
... | python | train |
BreakingBytes/simkit | simkit/core/models.py | https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/models.py#L221-L233 | def load(self, modelfile, layer=None):
"""
Load or update a model or layers in a model.
:param modelfile: The name of the json file to load.
:type modelfile: str
:param layer: Optionally load only specified layer.
:type layer: str
"""
# read modelfile, co... | [
"def",
"load",
"(",
"self",
",",
"modelfile",
",",
"layer",
"=",
"None",
")",
":",
"# read modelfile, convert JSON and load/update model",
"self",
".",
"param_file",
"=",
"modelfile",
"self",
".",
"_load",
"(",
"layer",
")",
"self",
".",
"_update",
"(",
"layer... | Load or update a model or layers in a model.
:param modelfile: The name of the json file to load.
:type modelfile: str
:param layer: Optionally load only specified layer.
:type layer: str | [
"Load",
"or",
"update",
"a",
"model",
"or",
"layers",
"in",
"a",
"model",
"."
] | python | train |
openstack/networking-arista | networking_arista/ml2/arista_sync.py | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/arista_sync.py#L176-L241 | def synchronize_resources(self):
"""Synchronize worker with CVX
All database queries must occur while the sync lock is held. This
tightly couples reads with writes and ensures that an older read
does not result in the last write. Eg:
Worker 1 reads (P1 created)
Worder 2... | [
"def",
"synchronize_resources",
"(",
"self",
")",
":",
"# Grab the sync lock",
"if",
"not",
"self",
".",
"_rpc",
".",
"sync_start",
"(",
")",
":",
"LOG",
".",
"info",
"(",
"\"%(pid)s Failed to grab the sync lock\"",
",",
"{",
"'pid'",
":",
"os",
".",
"getpid",... | Synchronize worker with CVX
All database queries must occur while the sync lock is held. This
tightly couples reads with writes and ensures that an older read
does not result in the last write. Eg:
Worker 1 reads (P1 created)
Worder 2 reads (P1 deleted)
Worker 2 writes ... | [
"Synchronize",
"worker",
"with",
"CVX"
] | python | train |
har07/PySastrawi | src/Sastrawi/Stemmer/Stemmer.py | https://github.com/har07/PySastrawi/blob/01afc81c579bde14dcb41c33686b26af8afab121/src/Sastrawi/Stemmer/Stemmer.py#L31-L36 | def stem_word(self, word):
"""Stem a word to its common stem form."""
if self.is_plural(word):
return self.stem_plural_word(word)
else:
return self.stem_singular_word(word) | [
"def",
"stem_word",
"(",
"self",
",",
"word",
")",
":",
"if",
"self",
".",
"is_plural",
"(",
"word",
")",
":",
"return",
"self",
".",
"stem_plural_word",
"(",
"word",
")",
"else",
":",
"return",
"self",
".",
"stem_singular_word",
"(",
"word",
")"
] | Stem a word to its common stem form. | [
"Stem",
"a",
"word",
"to",
"its",
"common",
"stem",
"form",
"."
] | python | train |
mwickert/scikit-dsp-comm | sk_dsp_comm/fec_conv.py | https://github.com/mwickert/scikit-dsp-comm/blob/5c1353412a4d81a8d7da169057564ecf940f8b5b/sk_dsp_comm/fec_conv.py#L621-L708 | def depuncture(self,soft_bits,puncture_pattern = ('110','101'),
erase_value = 3.5):
"""
Apply de-puncturing to the soft bits coming from the channel. Erasure bits
are inserted to return the soft bit values back to a form that can be
Viterbi decoded.
:pa... | [
"def",
"depuncture",
"(",
"self",
",",
"soft_bits",
",",
"puncture_pattern",
"=",
"(",
"'110'",
",",
"'101'",
")",
",",
"erase_value",
"=",
"3.5",
")",
":",
"# Check to see that the length of soft_bits is consistent with a rate\r",
"# 1/2 code.\r",
"L_pp",
"=",
"len",... | Apply de-puncturing to the soft bits coming from the channel. Erasure bits
are inserted to return the soft bit values back to a form that can be
Viterbi decoded.
:param soft_bits:
:param puncture_pattern:
:param erase_value:
:return:
Examples
-... | [
"Apply",
"de",
"-",
"puncturing",
"to",
"the",
"soft",
"bits",
"coming",
"from",
"the",
"channel",
".",
"Erasure",
"bits",
"are",
"inserted",
"to",
"return",
"the",
"soft",
"bit",
"values",
"back",
"to",
"a",
"form",
"that",
"can",
"be",
"Viterbi",
"deco... | python | valid |
DataONEorg/d1_python | lib_client/src/d1_client/cnclient.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/cnclient.py#L836-L849 | def updateGroupResponse(self, group, vendorSpecific=None):
"""CNIdentity.addGroupMembers(session, groupName, members) → boolean
https://releases.dataone.org/online/api-
documentation-v2.0.1/apis/CN_APIs.html#CNIdentity.addGroupMembers.
Args:
group:
vendorSpecific:
... | [
"def",
"updateGroupResponse",
"(",
"self",
",",
"group",
",",
"vendorSpecific",
"=",
"None",
")",
":",
"mmp_dict",
"=",
"{",
"'group'",
":",
"(",
"'group.xml'",
",",
"group",
".",
"toxml",
"(",
"'utf-8'",
")",
")",
"}",
"return",
"self",
".",
"PUT",
"(... | CNIdentity.addGroupMembers(session, groupName, members) → boolean
https://releases.dataone.org/online/api-
documentation-v2.0.1/apis/CN_APIs.html#CNIdentity.addGroupMembers.
Args:
group:
vendorSpecific:
Returns: | [
"CNIdentity",
".",
"addGroupMembers",
"(",
"session",
"groupName",
"members",
")",
"→",
"boolean",
"https",
":",
"//",
"releases",
".",
"dataone",
".",
"org",
"/",
"online",
"/",
"api",
"-",
"documentation",
"-",
"v2",
".",
"0",
".",
"1",
"/",
"apis",
... | python | train |
marcomusy/vtkplotter | vtkplotter/actors.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1887-L1918 | def decimate(self, fraction=0.5, N=None, boundaries=False, verbose=True):
"""
Downsample the number of vertices in a mesh.
:param float fraction: the desired target of reduction.
:param int N: the desired number of final points (**fraction** is recalculated based on it).
:param ... | [
"def",
"decimate",
"(",
"self",
",",
"fraction",
"=",
"0.5",
",",
"N",
"=",
"None",
",",
"boundaries",
"=",
"False",
",",
"verbose",
"=",
"True",
")",
":",
"poly",
"=",
"self",
".",
"polydata",
"(",
"True",
")",
"if",
"N",
":",
"# N = desired number ... | Downsample the number of vertices in a mesh.
:param float fraction: the desired target of reduction.
:param int N: the desired number of final points (**fraction** is recalculated based on it).
:param bool boundaries: (True), decide whether to leave boundaries untouched or not.
.. note... | [
"Downsample",
"the",
"number",
"of",
"vertices",
"in",
"a",
"mesh",
"."
] | python | train |
tgsmith61591/pmdarima | pmdarima/datasets/wineind.py | https://github.com/tgsmith61591/pmdarima/blob/a133de78ba5bd68da9785b061f519ba28cd514cc/pmdarima/datasets/wineind.py#L19-L112 | def load_wineind(as_series=False):
"""Australian total wine sales by wine makers in bottles <= 1 litre.
This time-series records wine sales by Australian wine makers between
Jan 1980 -- Aug 1994. This dataset is found in the R ``forecast`` package.
Parameters
----------
as_series : bool, optio... | [
"def",
"load_wineind",
"(",
"as_series",
"=",
"False",
")",
":",
"rslt",
"=",
"np",
".",
"array",
"(",
"[",
"15136",
",",
"16733",
",",
"20016",
",",
"17708",
",",
"18019",
",",
"19227",
",",
"22893",
",",
"23739",
",",
"21133",
",",
"22591",
",",
... | Australian total wine sales by wine makers in bottles <= 1 litre.
This time-series records wine sales by Australian wine makers between
Jan 1980 -- Aug 1994. This dataset is found in the R ``forecast`` package.
Parameters
----------
as_series : bool, optional (default=False)
Whether to ret... | [
"Australian",
"total",
"wine",
"sales",
"by",
"wine",
"makers",
"in",
"bottles",
"<",
"=",
"1",
"litre",
"."
] | python | train |
geomet/geomet | geomet/wkt.py | https://github.com/geomet/geomet/blob/b82d7118113ab723751eba3de5df98c368423c2b/geomet/wkt.py#L334-L363 | def _load_point(tokens, string):
"""
:param tokens:
A generator of string tokens for the input WKT, begining just after the
geometry type. The geometry type is consumed before we get to here. For
example, if :func:`loads` is called with the input 'POINT(0.0 1.0)',
``tokens`` woul... | [
"def",
"_load_point",
"(",
"tokens",
",",
"string",
")",
":",
"if",
"not",
"next",
"(",
"tokens",
")",
"==",
"'('",
":",
"raise",
"ValueError",
"(",
"INVALID_WKT_FMT",
"%",
"string",
")",
"coords",
"=",
"[",
"]",
"try",
":",
"for",
"t",
"in",
"tokens... | :param tokens:
A generator of string tokens for the input WKT, begining just after the
geometry type. The geometry type is consumed before we get to here. For
example, if :func:`loads` is called with the input 'POINT(0.0 1.0)',
``tokens`` would generate the following values:
.. ... | [
":",
"param",
"tokens",
":",
"A",
"generator",
"of",
"string",
"tokens",
"for",
"the",
"input",
"WKT",
"begining",
"just",
"after",
"the",
"geometry",
"type",
".",
"The",
"geometry",
"type",
"is",
"consumed",
"before",
"we",
"get",
"to",
"here",
".",
"Fo... | python | train |
berkerpeksag/astor | astor/string_repr.py | https://github.com/berkerpeksag/astor/blob/d9e893eb49d9eb2e30779680f90cd632c30e0ba1/astor/string_repr.py#L48-L55 | def _prep_triple_quotes(s, mysplit=mysplit, replacements=replacements):
""" Split the string up and force-feed some replacements
to make sure it will round-trip OK
"""
s = mysplit(s)
s[1::2] = (replacements[x] for x in s[1::2])
return ''.join(s) | [
"def",
"_prep_triple_quotes",
"(",
"s",
",",
"mysplit",
"=",
"mysplit",
",",
"replacements",
"=",
"replacements",
")",
":",
"s",
"=",
"mysplit",
"(",
"s",
")",
"s",
"[",
"1",
":",
":",
"2",
"]",
"=",
"(",
"replacements",
"[",
"x",
"]",
"for",
"x",
... | Split the string up and force-feed some replacements
to make sure it will round-trip OK | [
"Split",
"the",
"string",
"up",
"and",
"force",
"-",
"feed",
"some",
"replacements",
"to",
"make",
"sure",
"it",
"will",
"round",
"-",
"trip",
"OK"
] | python | train |
numenta/htmresearch | htmresearch/frameworks/layers/object_machine_base.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/object_machine_base.py#L155-L204 | def objectConfusion(self):
"""
Compute overlap between each pair of objects. Computes the average number
of feature/location pairs that are identical, as well as the average number
of shared locations and features.
This function will raise an exception if two objects are identical.
Returns th... | [
"def",
"objectConfusion",
"(",
"self",
")",
":",
"objects",
"=",
"self",
".",
"getObjects",
"(",
")",
"if",
"len",
"(",
"objects",
")",
"==",
"0",
":",
"return",
"0.0",
",",
"0.0",
",",
"0.0",
"sumCommonLocations",
"=",
"0",
"sumCommonFeatures",
"=",
"... | Compute overlap between each pair of objects. Computes the average number
of feature/location pairs that are identical, as well as the average number
of shared locations and features.
This function will raise an exception if two objects are identical.
Returns the tuple:
(avg common pairs, avg c... | [
"Compute",
"overlap",
"between",
"each",
"pair",
"of",
"objects",
".",
"Computes",
"the",
"average",
"number",
"of",
"feature",
"/",
"location",
"pairs",
"that",
"are",
"identical",
"as",
"well",
"as",
"the",
"average",
"number",
"of",
"shared",
"locations",
... | python | train |
materialsproject/pymatgen | pymatgen/vis/plotters.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/vis/plotters.py#L135-L144 | def save_plot(self, filename, img_format="eps", **kwargs):
"""
Save matplotlib plot to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS.
"""
plt = self.get_plot(**kwargs)
plt.savefig(filename, format=i... | [
"def",
"save_plot",
"(",
"self",
",",
"filename",
",",
"img_format",
"=",
"\"eps\"",
",",
"*",
"*",
"kwargs",
")",
":",
"plt",
"=",
"self",
".",
"get_plot",
"(",
"*",
"*",
"kwargs",
")",
"plt",
".",
"savefig",
"(",
"filename",
",",
"format",
"=",
"... | Save matplotlib plot to a file.
Args:
filename: Filename to write to.
img_format: Image format to use. Defaults to EPS. | [
"Save",
"matplotlib",
"plot",
"to",
"a",
"file",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/tools/qcvv/fitters.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/tools/qcvv/fitters.py#L23-L26 | def exp_fit_fun(x, a, tau, c):
"""Function used to fit the exponential decay."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) + c | [
"def",
"exp_fit_fun",
"(",
"x",
",",
"a",
",",
"tau",
",",
"c",
")",
":",
"# pylint: disable=invalid-name",
"return",
"a",
"*",
"np",
".",
"exp",
"(",
"-",
"x",
"/",
"tau",
")",
"+",
"c"
] | Function used to fit the exponential decay. | [
"Function",
"used",
"to",
"fit",
"the",
"exponential",
"decay",
"."
] | python | test |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_policer.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_policer.py#L539-L554 | def policy_map_clss_span_session(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
po_name_key = ET.SubElement(policy_map, "po-name")
po_name_key.text = ... | [
"def",
"policy_map_clss_span_session",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"policy_map",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"policy-map\"",
",",
"xmlns",
"=",
"\"urn:... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
ihgazni2/elist | elist/elist.py | https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L5089-L5113 | def replace_value_seqs(ol,src_value,dst_value,seqs,**kwargs):
'''
from elist.elist import *
ol = [1,'a',3,'a',5,'a',6,'a']
id(ol)
new = replace_value_seqs(ol,'a','AAA',[0,1])
ol
new
id(ol)
id(new)
####
ol = [1,'a',3,'a',5,'a',6,'a']
... | [
"def",
"replace_value_seqs",
"(",
"ol",
",",
"src_value",
",",
"dst_value",
",",
"seqs",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"'mode'",
"in",
"kwargs",
")",
":",
"mode",
"=",
"kwargs",
"[",
"\"mode\"",
"]",
"else",
":",
"mode",
"=",
"\"new\"... | from elist.elist import *
ol = [1,'a',3,'a',5,'a',6,'a']
id(ol)
new = replace_value_seqs(ol,'a','AAA',[0,1])
ol
new
id(ol)
id(new)
####
ol = [1,'a',3,'a',5,'a',6,'a']
id(ol)
rslt = replace_value_seqs(ol,'a','AAA',[0,1],mode="origina... | [
"from",
"elist",
".",
"elist",
"import",
"*",
"ol",
"=",
"[",
"1",
"a",
"3",
"a",
"5",
"a",
"6",
"a",
"]",
"id",
"(",
"ol",
")",
"new",
"=",
"replace_value_seqs",
"(",
"ol",
"a",
"AAA",
"[",
"0",
"1",
"]",
")",
"ol",
"new",
"id",
"(",
"ol",... | python | valid |
androguard/androguard | androguard/core/bytecodes/apk.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/apk.py#L1868-L1881 | def get_certificates_der_v3(self):
"""
Return a list of DER coded X.509 certificates from the v3 signature block
"""
if self._v3_signing_data == None:
self.parse_v3_signing_block()
certs = []
for signed_data in [signer.signed_data for signer in self._v3_sign... | [
"def",
"get_certificates_der_v3",
"(",
"self",
")",
":",
"if",
"self",
".",
"_v3_signing_data",
"==",
"None",
":",
"self",
".",
"parse_v3_signing_block",
"(",
")",
"certs",
"=",
"[",
"]",
"for",
"signed_data",
"in",
"[",
"signer",
".",
"signed_data",
"for",
... | Return a list of DER coded X.509 certificates from the v3 signature block | [
"Return",
"a",
"list",
"of",
"DER",
"coded",
"X",
".",
"509",
"certificates",
"from",
"the",
"v3",
"signature",
"block"
] | python | train |
explosion/spaCy | spacy/language.py | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/language.py#L886-L894 | def restore(self):
"""Restore the pipeline to its state when DisabledPipes was created."""
current, self.nlp.pipeline = self.nlp.pipeline, self.original_pipeline
unexpected = [name for name, pipe in current if not self.nlp.has_pipe(name)]
if unexpected:
# Don't change the pip... | [
"def",
"restore",
"(",
"self",
")",
":",
"current",
",",
"self",
".",
"nlp",
".",
"pipeline",
"=",
"self",
".",
"nlp",
".",
"pipeline",
",",
"self",
".",
"original_pipeline",
"unexpected",
"=",
"[",
"name",
"for",
"name",
",",
"pipe",
"in",
"current",
... | Restore the pipeline to its state when DisabledPipes was created. | [
"Restore",
"the",
"pipeline",
"to",
"its",
"state",
"when",
"DisabledPipes",
"was",
"created",
"."
] | python | train |
Azure/azure-cli-extensions | src/alias/azext_alias/_validators.py | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/alias/azext_alias/_validators.py#L127-L144 | def _validate_pos_args_syntax(alias_name, alias_command):
"""
Check if the positional argument syntax is valid in alias name and alias command.
Args:
alias_name: The name of the alias to validate.
alias_command: The command to validate.
"""
pos_args_from_alias = get_placeholders(ali... | [
"def",
"_validate_pos_args_syntax",
"(",
"alias_name",
",",
"alias_command",
")",
":",
"pos_args_from_alias",
"=",
"get_placeholders",
"(",
"alias_name",
")",
"# Split by '|' to extract positional argument name from Jinja filter (e.g. {{ arg_name | upper }})",
"# Split by '.' to extrac... | Check if the positional argument syntax is valid in alias name and alias command.
Args:
alias_name: The name of the alias to validate.
alias_command: The command to validate. | [
"Check",
"if",
"the",
"positional",
"argument",
"syntax",
"is",
"valid",
"in",
"alias",
"name",
"and",
"alias",
"command",
"."
] | python | train |
arista-eosplus/pyeapi | pyeapi/client.py | https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/client.py#L583-L609 | def section(self, regex, config='running_config'):
"""Returns a section of the config
Args:
regex (str): A valid regular expression used to select sections
of configuration to return
config (str): The configuration to return. Valid values for config
... | [
"def",
"section",
"(",
"self",
",",
"regex",
",",
"config",
"=",
"'running_config'",
")",
":",
"if",
"config",
"in",
"[",
"'running_config'",
",",
"'startup_config'",
"]",
":",
"config",
"=",
"getattr",
"(",
"self",
",",
"config",
")",
"match",
"=",
"re"... | Returns a section of the config
Args:
regex (str): A valid regular expression used to select sections
of configuration to return
config (str): The configuration to return. Valid values for config
are "running_config" or "startup_config". The default val... | [
"Returns",
"a",
"section",
"of",
"the",
"config"
] | python | train |
StackStorm/pybind | pybind/slxos/v17r_1_01a/show/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/show/__init__.py#L334-L357 | def _set_infra(self, v, load=False):
"""
Setter method for infra, mapped from YANG variable /show/infra (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_infra is considered as a private
method. Backends looking to populate this variable should
do so vi... | [
"def",
"_set_infra",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | Setter method for infra, mapped from YANG variable /show/infra (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_infra is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_infra() directly.
YAN... | [
"Setter",
"method",
"for",
"infra",
"mapped",
"from",
"YANG",
"variable",
"/",
"show",
"/",
"infra",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
"t... | python | train |
titusjan/argos | argos/config/configtreemodel.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L167-L173 | def setExpanded(self, index, expanded):
""" Expands the model item specified by the index.
Overridden from QTreeView to make it persistent (between inspector changes).
"""
if index.isValid():
item = self.getItem(index)
item.expanded = expanded | [
"def",
"setExpanded",
"(",
"self",
",",
"index",
",",
"expanded",
")",
":",
"if",
"index",
".",
"isValid",
"(",
")",
":",
"item",
"=",
"self",
".",
"getItem",
"(",
"index",
")",
"item",
".",
"expanded",
"=",
"expanded"
] | Expands the model item specified by the index.
Overridden from QTreeView to make it persistent (between inspector changes). | [
"Expands",
"the",
"model",
"item",
"specified",
"by",
"the",
"index",
".",
"Overridden",
"from",
"QTreeView",
"to",
"make",
"it",
"persistent",
"(",
"between",
"inspector",
"changes",
")",
"."
] | python | train |
librosa/librosa | librosa/feature/rhythm.py | https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/rhythm.py#L18-L178 | def tempogram(y=None, sr=22050, onset_envelope=None, hop_length=512,
win_length=384, center=True, window='hann', norm=np.inf):
'''Compute the tempogram: local autocorrelation of the onset strength envelope. [1]_
.. [1] Grosche, Peter, Meinard Müller, and Frank Kurth.
"Cyclic tempogram - A... | [
"def",
"tempogram",
"(",
"y",
"=",
"None",
",",
"sr",
"=",
"22050",
",",
"onset_envelope",
"=",
"None",
",",
"hop_length",
"=",
"512",
",",
"win_length",
"=",
"384",
",",
"center",
"=",
"True",
",",
"window",
"=",
"'hann'",
",",
"norm",
"=",
"np",
... | Compute the tempogram: local autocorrelation of the onset strength envelope. [1]_
.. [1] Grosche, Peter, Meinard Müller, and Frank Kurth.
"Cyclic tempogram - A mid-level tempo representation for music signals."
ICASSP, 2010.
Parameters
----------
y : np.ndarray [shape=(n,)] or None
... | [
"Compute",
"the",
"tempogram",
":",
"local",
"autocorrelation",
"of",
"the",
"onset",
"strength",
"envelope",
".",
"[",
"1",
"]",
"_"
] | python | test |
iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L646-L660 | def service_info(self, name):
"""Pull descriptive info of a service by name.
Information returned includes the service's user friendly
name and whether it was preregistered or added dynamically.
Returns:
dict: A dictionary of service information with the following keys
... | [
"def",
"service_info",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"_loop",
".",
"run_coroutine",
"(",
"self",
".",
"_client",
".",
"service_info",
"(",
"name",
")",
")"
] | Pull descriptive info of a service by name.
Information returned includes the service's user friendly
name and whether it was preregistered or added dynamically.
Returns:
dict: A dictionary of service information with the following keys
set:
long_nam... | [
"Pull",
"descriptive",
"info",
"of",
"a",
"service",
"by",
"name",
"."
] | python | train |
jaegertracing/jaeger-client-python | jaeger_client/throttler.py | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/throttler.py#L81-L87 | def _set_client_id(self, client_id):
"""
Method for tracer to set client ID of throttler.
"""
with self.lock:
if self.client_id is None:
self.client_id = client_id | [
"def",
"_set_client_id",
"(",
"self",
",",
"client_id",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"client_id",
"is",
"None",
":",
"self",
".",
"client_id",
"=",
"client_id"
] | Method for tracer to set client ID of throttler. | [
"Method",
"for",
"tracer",
"to",
"set",
"client",
"ID",
"of",
"throttler",
"."
] | python | train |
saltstack/salt | salt/runners/asam.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/asam.py#L77-L121 | def _get_asam_configuration(driver_url=''):
'''
Return the configuration read from the master configuration
file or directory
'''
asam_config = __opts__['asam'] if 'asam' in __opts__ else None
if asam_config:
try:
for asam_server, service_config in six.iteritems(asam_config)... | [
"def",
"_get_asam_configuration",
"(",
"driver_url",
"=",
"''",
")",
":",
"asam_config",
"=",
"__opts__",
"[",
"'asam'",
"]",
"if",
"'asam'",
"in",
"__opts__",
"else",
"None",
"if",
"asam_config",
":",
"try",
":",
"for",
"asam_server",
",",
"service_config",
... | Return the configuration read from the master configuration
file or directory | [
"Return",
"the",
"configuration",
"read",
"from",
"the",
"master",
"configuration",
"file",
"or",
"directory"
] | python | train |
signalfx/signalfx-python | signalfx/pyformance/registry.py | https://github.com/signalfx/signalfx-python/blob/650eb9a2b301bcc795e4e3a8c031574ade69849d/signalfx/pyformance/registry.py#L43-L46 | def meter(self, key, **dims):
"""Adds meter with dimensions to the registry"""
return super(MetricsRegistry, self).meter(
self.metadata.register(key, **dims)) | [
"def",
"meter",
"(",
"self",
",",
"key",
",",
"*",
"*",
"dims",
")",
":",
"return",
"super",
"(",
"MetricsRegistry",
",",
"self",
")",
".",
"meter",
"(",
"self",
".",
"metadata",
".",
"register",
"(",
"key",
",",
"*",
"*",
"dims",
")",
")"
] | Adds meter with dimensions to the registry | [
"Adds",
"meter",
"with",
"dimensions",
"to",
"the",
"registry"
] | python | train |
Autodesk/aomi | aomi/helpers.py | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/helpers.py#L214-L218 | def ensure_dir(path):
"""Ensures a directory exists"""
if not (os.path.exists(path) and
os.path.isdir(path)):
os.mkdir(path) | [
"def",
"ensure_dir",
"(",
"path",
")",
":",
"if",
"not",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
")",
":",
"os",
".",
"mkdir",
"(",
"path",
")"
] | Ensures a directory exists | [
"Ensures",
"a",
"directory",
"exists"
] | python | train |
eng-tools/sfsimodels | sfsimodels/files.py | https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/files.py#L33-L51 | def loads_json(p_str, custom=None, meta=False, verbose=0):
"""
Given a json string it creates a dictionary of sfsi objects
:param ffp: str, Full file path to json file
:param custom: dict, used to load custom objects, {model type: custom object}
:param meta: bool, if true then also return all ecp m... | [
"def",
"loads_json",
"(",
"p_str",
",",
"custom",
"=",
"None",
",",
"meta",
"=",
"False",
",",
"verbose",
"=",
"0",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"p_str",
")",
"if",
"meta",
":",
"md",
"=",
"{",
"}",
"for",
"item",
"in",
"da... | Given a json string it creates a dictionary of sfsi objects
:param ffp: str, Full file path to json file
:param custom: dict, used to load custom objects, {model type: custom object}
:param meta: bool, if true then also return all ecp meta data in separate dict
:param verbose: int, console output
:... | [
"Given",
"a",
"json",
"string",
"it",
"creates",
"a",
"dictionary",
"of",
"sfsi",
"objects"
] | python | train |
reingart/gui2py | gui/controls/listview.py | https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/controls/listview.py#L72-L81 | def FindPyData(self, start, py_data):
"Do a reverse look up for an item containing the requested data"
# first, look at our internal dict:
wx_data = self._wx_data_map[py_data]
# do the real search at the wx control:
if wx.VERSION < (3, 0, 0) or 'classic' in wx.version():
... | [
"def",
"FindPyData",
"(",
"self",
",",
"start",
",",
"py_data",
")",
":",
"# first, look at our internal dict:\r",
"wx_data",
"=",
"self",
".",
"_wx_data_map",
"[",
"py_data",
"]",
"# do the real search at the wx control:\r",
"if",
"wx",
".",
"VERSION",
"<",
"(",
... | Do a reverse look up for an item containing the requested data | [
"Do",
"a",
"reverse",
"look",
"up",
"for",
"an",
"item",
"containing",
"the",
"requested",
"data"
] | python | test |
jbittel/django-mama-cas | mama_cas/cas.py | https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/cas.py#L18-L38 | def validate_service_ticket(service, ticket, pgturl=None, renew=False, require_https=False):
"""
Validate a service ticket string. Return a triplet containing a
``ServiceTicket`` and an optional ``ProxyGrantingTicket``, or a
``ValidationError`` if ticket validation failed.
"""
logger.debug("Serv... | [
"def",
"validate_service_ticket",
"(",
"service",
",",
"ticket",
",",
"pgturl",
"=",
"None",
",",
"renew",
"=",
"False",
",",
"require_https",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"Service validation request received for %s\"",
"%",
"ticket",
"... | Validate a service ticket string. Return a triplet containing a
``ServiceTicket`` and an optional ``ProxyGrantingTicket``, or a
``ValidationError`` if ticket validation failed. | [
"Validate",
"a",
"service",
"ticket",
"string",
".",
"Return",
"a",
"triplet",
"containing",
"a",
"ServiceTicket",
"and",
"an",
"optional",
"ProxyGrantingTicket",
"or",
"a",
"ValidationError",
"if",
"ticket",
"validation",
"failed",
"."
] | python | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1737-L1755 | def get_snaps_install_info_from_origin(snaps, src, mode='classic'):
"""Generate a dictionary of snap install information from origin
@param snaps: List of snaps
@param src: String of openstack-origin or source of the form
snap:track/channel
@param mode: String classic, devmode or jailmode
@... | [
"def",
"get_snaps_install_info_from_origin",
"(",
"snaps",
",",
"src",
",",
"mode",
"=",
"'classic'",
")",
":",
"if",
"not",
"src",
".",
"startswith",
"(",
"'snap:'",
")",
":",
"juju_log",
"(",
"\"Snap source is not a snap origin\"",
",",
"'WARN'",
")",
"return"... | Generate a dictionary of snap install information from origin
@param snaps: List of snaps
@param src: String of openstack-origin or source of the form
snap:track/channel
@param mode: String classic, devmode or jailmode
@returns: Dictionary of snaps with channels and modes | [
"Generate",
"a",
"dictionary",
"of",
"snap",
"install",
"information",
"from",
"origin"
] | python | train |
MycroftAI/adapt | adapt/engine.py | https://github.com/MycroftAI/adapt/blob/334f23248b8e09fb9d84a88398424ec5bd3bae4c/adapt/engine.py#L315-L327 | def register_regex_entity(self, regex_str, domain=0):
"""
A regular expression making use of python named group expressions.
Example: (?P<Artist>.*)
Args:
regex_str(str): a string representing a regular expression as defined above
domain(str): a string represent... | [
"def",
"register_regex_entity",
"(",
"self",
",",
"regex_str",
",",
"domain",
"=",
"0",
")",
":",
"if",
"domain",
"not",
"in",
"self",
".",
"domains",
":",
"self",
".",
"register_domain",
"(",
"domain",
"=",
"domain",
")",
"self",
".",
"domains",
"[",
... | A regular expression making use of python named group expressions.
Example: (?P<Artist>.*)
Args:
regex_str(str): a string representing a regular expression as defined above
domain(str): a string representing the domain you wish to add the entity to | [
"A",
"regular",
"expression",
"making",
"use",
"of",
"python",
"named",
"group",
"expressions",
"."
] | python | train |
ponty/pyavrutils | pyavrutils/avrgcc.py | https://github.com/ponty/pyavrutils/blob/7a396a25b3ac076ede07b5cd5cbd416ebb578a28/pyavrutils/avrgcc.py#L140-L188 | def command_list(self, sources, _opt=False):
'''command line as list'''
def abspath(x):
x = Path(x).abspath()
if not x.exists():
raise ValueError('file not found! ' + x)
return x
self.f_cpu = int(self.f_cpu)
self.mcu = str(self.mcu)
#... | [
"def",
"command_list",
"(",
"self",
",",
"sources",
",",
"_opt",
"=",
"False",
")",
":",
"def",
"abspath",
"(",
"x",
")",
":",
"x",
"=",
"Path",
"(",
"x",
")",
".",
"abspath",
"(",
")",
"if",
"not",
"x",
".",
"exists",
"(",
")",
":",
"raise",
... | command line as list | [
"command",
"line",
"as",
"list"
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/nhs.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/nhs.py#L116-L128 | def generate_random_nhs_number() -> int:
"""
Returns a random valid NHS number, as an ``int``.
"""
check_digit = 10 # NHS numbers with this check digit are all invalid
while check_digit == 10:
digits = [random.randint(1, 9)] # don't start with a zero
digits.extend([random.randint(0... | [
"def",
"generate_random_nhs_number",
"(",
")",
"->",
"int",
":",
"check_digit",
"=",
"10",
"# NHS numbers with this check digit are all invalid",
"while",
"check_digit",
"==",
"10",
":",
"digits",
"=",
"[",
"random",
".",
"randint",
"(",
"1",
",",
"9",
")",
"]",... | Returns a random valid NHS number, as an ``int``. | [
"Returns",
"a",
"random",
"valid",
"NHS",
"number",
"as",
"an",
"int",
"."
] | python | train |
bwhite/hadoopy | hadoopy/_runner.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_runner.py#L66-L70 | def _listeq_to_dict(jobconfs):
"""Convert iterators of 'key=val' into a dictionary with later values taking priority."""
if not isinstance(jobconfs, dict):
jobconfs = dict(x.split('=', 1) for x in jobconfs)
return dict((str(k), str(v)) for k, v in jobconfs.items()) | [
"def",
"_listeq_to_dict",
"(",
"jobconfs",
")",
":",
"if",
"not",
"isinstance",
"(",
"jobconfs",
",",
"dict",
")",
":",
"jobconfs",
"=",
"dict",
"(",
"x",
".",
"split",
"(",
"'='",
",",
"1",
")",
"for",
"x",
"in",
"jobconfs",
")",
"return",
"dict",
... | Convert iterators of 'key=val' into a dictionary with later values taking priority. | [
"Convert",
"iterators",
"of",
"key",
"=",
"val",
"into",
"a",
"dictionary",
"with",
"later",
"values",
"taking",
"priority",
"."
] | python | train |
androguard/androguard | androguard/decompiler/dad/util.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/decompiler/dad/util.py#L202-L213 | def create_png(cls_name, meth_name, graph, dir_name='graphs2'):
"""
Creates a PNG from a given :class:`~androguard.decompiler.dad.graph.Graph`.
:param str cls_name: name of the class
:param str meth_name: name of the method
:param androguard.decompiler.dad.graph.Graph graph:
:param str dir_name... | [
"def",
"create_png",
"(",
"cls_name",
",",
"meth_name",
",",
"graph",
",",
"dir_name",
"=",
"'graphs2'",
")",
":",
"m_name",
"=",
"''",
".",
"join",
"(",
"x",
"for",
"x",
"in",
"meth_name",
"if",
"x",
".",
"isalnum",
"(",
")",
")",
"name",
"=",
"''... | Creates a PNG from a given :class:`~androguard.decompiler.dad.graph.Graph`.
:param str cls_name: name of the class
:param str meth_name: name of the method
:param androguard.decompiler.dad.graph.Graph graph:
:param str dir_name: output directory | [
"Creates",
"a",
"PNG",
"from",
"a",
"given",
":",
"class",
":",
"~androguard",
".",
"decompiler",
".",
"dad",
".",
"graph",
".",
"Graph",
"."
] | python | train |
mlperf/training | image_classification/tensorflow/official/resnet/imagenet_preprocessing.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/imagenet_preprocessing.py#L254-L291 | def preprocess_image(image_buffer, output_height, output_width,
num_channels, is_training=False):
"""Preprocesses the given image.
Preprocessing includes decoding, cropping, and resizing for both training
and eval images. Training preprocessing, however, introduces some random
distortion o... | [
"def",
"preprocess_image",
"(",
"image_buffer",
",",
"output_height",
",",
"output_width",
",",
"num_channels",
",",
"is_training",
"=",
"False",
")",
":",
"if",
"is_training",
":",
"# For training, we want to randomize some of the distortions.",
"image",
"=",
"_decode_cr... | Preprocesses the given image.
Preprocessing includes decoding, cropping, and resizing for both training
and eval images. Training preprocessing, however, introduces some random
distortion of the image to improve accuracy.
Args:
image_buffer: scalar string Tensor representing the raw JPEG image buffer.
... | [
"Preprocesses",
"the",
"given",
"image",
"."
] | python | train |
aparo/pyes | performance/utils.py | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/performance/utils.py#L16-L31 | def generate_dataset(number_items=1000):
"""
Generate a dataset with number_items elements.
"""
data = []
names = get_names()
totalnames = len(names)
#init random seeder
random.seed()
#calculate items
# names = random.sample(names, number_items)
for i in range(number_items):
... | [
"def",
"generate_dataset",
"(",
"number_items",
"=",
"1000",
")",
":",
"data",
"=",
"[",
"]",
"names",
"=",
"get_names",
"(",
")",
"totalnames",
"=",
"len",
"(",
"names",
")",
"#init random seeder",
"random",
".",
"seed",
"(",
")",
"#calculate items",
"# ... | Generate a dataset with number_items elements. | [
"Generate",
"a",
"dataset",
"with",
"number_items",
"elements",
"."
] | python | train |
load-tools/netort | netort/data_processing.py | https://github.com/load-tools/netort/blob/b5233a70cea74108857ea24ba5c37975057ca00f/netort/data_processing.py#L10-L18 | def get_nowait_from_queue(queue):
""" Collect all immediately available items from a queue """
data = []
for _ in range(queue.qsize()):
try:
data.append(queue.get_nowait())
except q.Empty:
break
return data | [
"def",
"get_nowait_from_queue",
"(",
"queue",
")",
":",
"data",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"queue",
".",
"qsize",
"(",
")",
")",
":",
"try",
":",
"data",
".",
"append",
"(",
"queue",
".",
"get_nowait",
"(",
")",
")",
"except",
... | Collect all immediately available items from a queue | [
"Collect",
"all",
"immediately",
"available",
"items",
"from",
"a",
"queue"
] | python | train |
ihgazni2/elist | elist/elist.py | https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L6647-L6686 | def get_next_char_level_in_j_str(curr_lv,curr_seq,j_str,block_op_pairs_dict=get_block_op_pairs("{}[]()")):
''' the first-char is level-1
when current is non-op, next-char-level = curr-level
when current is lop, non-paired-rop-next-char-level = lop-level+1;
when current is lop, paired-ro... | [
"def",
"get_next_char_level_in_j_str",
"(",
"curr_lv",
",",
"curr_seq",
",",
"j_str",
",",
"block_op_pairs_dict",
"=",
"get_block_op_pairs",
"(",
"\"{}[]()\"",
")",
")",
":",
"curr_ch",
"=",
"j_str",
"[",
"curr_seq",
"]",
"next_ch",
"=",
"j_str",
"[",
"curr_seq"... | the first-char is level-1
when current is non-op, next-char-level = curr-level
when current is lop, non-paired-rop-next-char-level = lop-level+1;
when current is lop, paired-rop-next-char-level = lop-level
when current is rop, next-char-level = rop-level - 1
# {"key_4_UF0a... | [
"the",
"first",
"-",
"char",
"is",
"level",
"-",
"1",
"when",
"current",
"is",
"non",
"-",
"op",
"next",
"-",
"char",
"-",
"level",
"=",
"curr",
"-",
"level",
"when",
"current",
"is",
"lop",
"non",
"-",
"paired",
"-",
"rop",
"-",
"next",
"-",
"ch... | python | valid |
tanghaibao/goatools | goatools/grouper/grprobj.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L108-L114 | def get_section2usrnts(self):
"""Get dict section2usrnts."""
sec_nts = []
for section_name, _ in self.get_sections_2d():
usrgos = self.get_usrgos_g_section(section_name)
sec_nts.append((section_name, [self.go2nt.get(u) for u in usrgos]))
return cx.OrderedDict(sec_... | [
"def",
"get_section2usrnts",
"(",
"self",
")",
":",
"sec_nts",
"=",
"[",
"]",
"for",
"section_name",
",",
"_",
"in",
"self",
".",
"get_sections_2d",
"(",
")",
":",
"usrgos",
"=",
"self",
".",
"get_usrgos_g_section",
"(",
"section_name",
")",
"sec_nts",
"."... | Get dict section2usrnts. | [
"Get",
"dict",
"section2usrnts",
"."
] | python | train |
uogbuji/versa | tools/py/writer/md.py | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/writer/md.py#L42-L79 | def write(models, out=None, base=None, propertybase=None, shorteners=None, logger=logging):
'''
models - input Versa models from which output is generated. Must be a sequence
object, not an iterator
'''
assert out is not None #Output stream required
if not isinstance(models, list): m... | [
"def",
"write",
"(",
"models",
",",
"out",
"=",
"None",
",",
"base",
"=",
"None",
",",
"propertybase",
"=",
"None",
",",
"shorteners",
"=",
"None",
",",
"logger",
"=",
"logging",
")",
":",
"assert",
"out",
"is",
"not",
"None",
"#Output stream required",
... | models - input Versa models from which output is generated. Must be a sequence
object, not an iterator | [
"models",
"-",
"input",
"Versa",
"models",
"from",
"which",
"output",
"is",
"generated",
".",
"Must",
"be",
"a",
"sequence",
"object",
"not",
"an",
"iterator"
] | python | train |
saltstack/salt | salt/modules/system_profiler.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system_profiler.py#L34-L55 | def _call_system_profiler(datatype):
'''
Call out to system_profiler. Return a dictionary
of the stuff we are interested in.
'''
p = subprocess.Popen(
[PROFILER_BINARY, '-detailLevel', 'full',
'-xml', datatype], stdout=subprocess.PIPE)
(sysprofresults, sysprof_stderr) = p.comm... | [
"def",
"_call_system_profiler",
"(",
"datatype",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"PROFILER_BINARY",
",",
"'-detailLevel'",
",",
"'full'",
",",
"'-xml'",
",",
"datatype",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"("... | Call out to system_profiler. Return a dictionary
of the stuff we are interested in. | [
"Call",
"out",
"to",
"system_profiler",
".",
"Return",
"a",
"dictionary",
"of",
"the",
"stuff",
"we",
"are",
"interested",
"in",
"."
] | python | train |
PyCQA/pylint | pylint/checkers/imports.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/imports.py#L791-L813 | def _check_relative_import(
self, modnode, importnode, importedmodnode, importedasname
):
"""check relative import. node is either an Import or From node, modname
the imported module name.
"""
if not self.linter.is_message_enabled("relative-import"):
return None
... | [
"def",
"_check_relative_import",
"(",
"self",
",",
"modnode",
",",
"importnode",
",",
"importedmodnode",
",",
"importedasname",
")",
":",
"if",
"not",
"self",
".",
"linter",
".",
"is_message_enabled",
"(",
"\"relative-import\"",
")",
":",
"return",
"None",
"if",... | check relative import. node is either an Import or From node, modname
the imported module name. | [
"check",
"relative",
"import",
".",
"node",
"is",
"either",
"an",
"Import",
"or",
"From",
"node",
"modname",
"the",
"imported",
"module",
"name",
"."
] | python | test |
zomux/deepy | deepy/dataset/basic.py | https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/dataset/basic.py#L30-L40 | def map(self, func):
"""
Process all data with given function.
The scheme of function should be x,y -> x,y.
"""
if self._train_set:
self._train_set = map(func, self._train_set)
if self._valid_set:
self._valid_set = map(func, self._valid_set)
... | [
"def",
"map",
"(",
"self",
",",
"func",
")",
":",
"if",
"self",
".",
"_train_set",
":",
"self",
".",
"_train_set",
"=",
"map",
"(",
"func",
",",
"self",
".",
"_train_set",
")",
"if",
"self",
".",
"_valid_set",
":",
"self",
".",
"_valid_set",
"=",
"... | Process all data with given function.
The scheme of function should be x,y -> x,y. | [
"Process",
"all",
"data",
"with",
"given",
"function",
".",
"The",
"scheme",
"of",
"function",
"should",
"be",
"x",
"y",
"-",
">",
"x",
"y",
"."
] | python | test |
edx/edx-celeryutils | celery_utils/persist_on_failure.py | https://github.com/edx/edx-celeryutils/blob/d8745f5f0929ad154fad779a19fbefe7f51e9498/celery_utils/persist_on_failure.py#L22-L34 | def on_failure(self, exc, task_id, args, kwargs, einfo):
"""
If the task fails, persist a record of the task.
"""
if not FailedTask.objects.filter(task_id=task_id, datetime_resolved=None).exists():
FailedTask.objects.create(
task_name=_truncate_to_field(Failed... | [
"def",
"on_failure",
"(",
"self",
",",
"exc",
",",
"task_id",
",",
"args",
",",
"kwargs",
",",
"einfo",
")",
":",
"if",
"not",
"FailedTask",
".",
"objects",
".",
"filter",
"(",
"task_id",
"=",
"task_id",
",",
"datetime_resolved",
"=",
"None",
")",
".",... | If the task fails, persist a record of the task. | [
"If",
"the",
"task",
"fails",
"persist",
"a",
"record",
"of",
"the",
"task",
"."
] | python | train |
JarryShaw/PyPCAPKit | src/protocols/internet/internet.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/internet.py#L113-L170 | def _import_next_layer(self, proto, length=None, *, version=4, extension=False):
"""Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Keyword Arguments:
* version -- int, I... | [
"def",
"_import_next_layer",
"(",
"self",
",",
"proto",
",",
"length",
"=",
"None",
",",
"*",
",",
"version",
"=",
"4",
",",
"extension",
"=",
"False",
")",
":",
"if",
"length",
"==",
"0",
":",
"from",
"pcapkit",
".",
"protocols",
".",
"null",
"impor... | Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Keyword Arguments:
* version -- int, IP version (4 in default)
<keyword> 4 / 6
* extension... | [
"Import",
"next",
"layer",
"extractor",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/resource/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/resource/sessions.py#L3075-L3094 | def is_descendant_of_bin(self, id_, bin_id):
"""Tests if an ``Id`` is a descendant of a bin.
arg: id (osid.id.Id): an ``Id``
arg: bin_id (osid.id.Id): the ``Id`` of a bin
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``bin_id,`` ``false`` other... | [
"def",
"is_descendant_of_bin",
"(",
"self",
",",
"id_",
",",
"bin_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.is_descendant_of_bin",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_cata... | Tests if an ``Id`` is a descendant of a bin.
arg: id (osid.id.Id): an ``Id``
arg: bin_id (osid.id.Id): the ``Id`` of a bin
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``bin_id,`` ``false`` otherwise
raise: NotFound - ``bin_id`` is not found
... | [
"Tests",
"if",
"an",
"Id",
"is",
"a",
"descendant",
"of",
"a",
"bin",
"."
] | python | train |
saltstack/salt | salt/returners/pgjsonb.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pgjsonb.py#L325-L337 | def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
with _get_serv(commit=True) as cur:
try:
cur.execute(PG_SAVE_LOAD_SQL,
{'jid': jid, 'load': psycopg2.extras.Json(load)})
except psycopg2.IntegrityError:
#... | [
"def",
"save_load",
"(",
"jid",
",",
"load",
",",
"minions",
"=",
"None",
")",
":",
"with",
"_get_serv",
"(",
"commit",
"=",
"True",
")",
"as",
"cur",
":",
"try",
":",
"cur",
".",
"execute",
"(",
"PG_SAVE_LOAD_SQL",
",",
"{",
"'jid'",
":",
"jid",
"... | Save the load to the specified jid id | [
"Save",
"the",
"load",
"to",
"the",
"specified",
"jid",
"id"
] | python | train |
tanghaibao/jcvi | jcvi/variation/str.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L876-L907 | def mergecsv(args):
"""
%prog mergecsv *.csv
Combine CSV into binary array.
"""
p = OptionParser(mergecsv.__doc__)
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
csvfiles = args
arrays = []
samplekeys = []
for csvfile in csvfiles:
... | [
"def",
"mergecsv",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mergecsv",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"sys",
".",
"exit",
"(",
... | %prog mergecsv *.csv
Combine CSV into binary array. | [
"%prog",
"mergecsv",
"*",
".",
"csv"
] | python | train |
cltk/cltk | cltk/prosody/old_norse/verse.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/old_norse/verse.py#L227-L247 | def find_alliterations(self):
"""
Alliterations is the repetition of a same sound pattern (usually the first sound) of important words.
This usually excludes stop words.
:return:
"""
self.n_alliterations = 0
self.alliterations = []
for j, sound1 in enumera... | [
"def",
"find_alliterations",
"(",
"self",
")",
":",
"self",
".",
"n_alliterations",
"=",
"0",
"self",
".",
"alliterations",
"=",
"[",
"]",
"for",
"j",
",",
"sound1",
"in",
"enumerate",
"(",
"self",
".",
"first_sounds",
")",
":",
"word1",
"=",
"normalize"... | Alliterations is the repetition of a same sound pattern (usually the first sound) of important words.
This usually excludes stop words.
:return: | [
"Alliterations",
"is",
"the",
"repetition",
"of",
"a",
"same",
"sound",
"pattern",
"(",
"usually",
"the",
"first",
"sound",
")",
"of",
"important",
"words",
".",
"This",
"usually",
"excludes",
"stop",
"words",
".",
":",
"return",
":"
] | python | train |
mwouts/jupytext | jupytext/cell_to_text.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_to_text.py#L136-L151 | def code_to_text(self):
"""Return the text representation of a code cell"""
source = copy(self.source)
comment_magic(source, self.language, self.comment_magics)
options = []
if self.cell_type == 'code' and self.language:
options.append(self.language)
filtere... | [
"def",
"code_to_text",
"(",
"self",
")",
":",
"source",
"=",
"copy",
"(",
"self",
".",
"source",
")",
"comment_magic",
"(",
"source",
",",
"self",
".",
"language",
",",
"self",
".",
"comment_magics",
")",
"options",
"=",
"[",
"]",
"if",
"self",
".",
... | Return the text representation of a code cell | [
"Return",
"the",
"text",
"representation",
"of",
"a",
"code",
"cell"
] | python | train |
Phyks/libbmc | libbmc/citations/pdf.py | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/citations/pdf.py#L21-L87 | def cermine(pdf_file, force_api=False, override_local=None):
"""
Run `CERMINE <https://github.com/CeON/CERMINE>`_ to extract metadata from \
the given PDF file, to retrieve citations (and more) from the \
provided PDF file. This function returns the raw output of \
CERMINE ca... | [
"def",
"cermine",
"(",
"pdf_file",
",",
"force_api",
"=",
"False",
",",
"override_local",
"=",
"None",
")",
":",
"try",
":",
"# Check if we want to load the local JAR from a specific path",
"local",
"=",
"override_local",
"# Else, try to stat the JAR file at the expected loca... | Run `CERMINE <https://github.com/CeON/CERMINE>`_ to extract metadata from \
the given PDF file, to retrieve citations (and more) from the \
provided PDF file. This function returns the raw output of \
CERMINE call.
.. note::
Try to use a local CERMINE JAR file, and fall... | [
"Run",
"CERMINE",
"<https",
":",
"//",
"github",
".",
"com",
"/",
"CeON",
"/",
"CERMINE",
">",
"_",
"to",
"extract",
"metadata",
"from",
"\\",
"the",
"given",
"PDF",
"file",
"to",
"retrieve",
"citations",
"(",
"and",
"more",
")",
"from",
"the",
"\\",
... | python | train |
tensorflow/tensorboard | tensorboard/plugins/text/summary.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/text/summary.py#L79-L116 | def pb(name, data, display_name=None, description=None):
"""Create a legacy text summary protobuf.
Arguments:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
data: A Python bytestring (of type bytes), or Unicode string. Or a numpy
data array of those types.... | [
"def",
"pb",
"(",
"name",
",",
"data",
",",
"display_name",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"# TODO(nickfelt): remove on-demand imports once dep situation is fixed.",
"import",
"tensorflow",
".",
"compat",
".",
"v1",
"as",
"tf",
"try",
":",... | Create a legacy text summary protobuf.
Arguments:
name: A name for the generated node. Will also serve as a series name in
TensorBoard.
data: A Python bytestring (of type bytes), or Unicode string. Or a numpy
data array of those types.
display_name: Optional name for this summary in TensorBoa... | [
"Create",
"a",
"legacy",
"text",
"summary",
"protobuf",
"."
] | python | train |
hyperledger/indy-node | indy_node/server/domain_req_handler.py | https://github.com/hyperledger/indy-node/blob/8fabd364eaf7d940a56df2911d9215b1e512a2de/indy_node/server/domain_req_handler.py#L86-L114 | def gen_txn_path(self, txn):
"""Return path to state as 'str' type or None"""
txn_type = get_type(txn)
if txn_type not in self.state_update_handlers:
logger.error('Cannot generate id for txn of type {}'.format(txn_type))
return None
if txn_type == NYM:
... | [
"def",
"gen_txn_path",
"(",
"self",
",",
"txn",
")",
":",
"txn_type",
"=",
"get_type",
"(",
"txn",
")",
"if",
"txn_type",
"not",
"in",
"self",
".",
"state_update_handlers",
":",
"logger",
".",
"error",
"(",
"'Cannot generate id for txn of type {}'",
".",
"form... | Return path to state as 'str' type or None | [
"Return",
"path",
"to",
"state",
"as",
"str",
"type",
"or",
"None"
] | python | train |
oauthlib/oauthlib | oauthlib/oauth1/rfc5849/endpoints/access_token.py | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/access_token.py#L34-L54 | def create_access_token(self, request, credentials):
"""Create and save a new access token.
Similar to OAuth 2, indication of granted scopes will be included as a
space separated list in ``oauth_authorized_realms``.
:param request: OAuthlib request.
:type request: oauthlib.comm... | [
"def",
"create_access_token",
"(",
"self",
",",
"request",
",",
"credentials",
")",
":",
"request",
".",
"realms",
"=",
"self",
".",
"request_validator",
".",
"get_realms",
"(",
"request",
".",
"resource_owner_key",
",",
"request",
")",
"token",
"=",
"{",
"'... | Create and save a new access token.
Similar to OAuth 2, indication of granted scopes will be included as a
space separated list in ``oauth_authorized_realms``.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:returns: The token as an urlencoded string. | [
"Create",
"and",
"save",
"a",
"new",
"access",
"token",
"."
] | python | train |
wuher/devil | devil/resource.py | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L135-L171 | def _process_response(self, response, request):
""" Process the response.
If the response is ``HttpResponse``, does nothing. Otherwise,
serializes, formats and validates the response.
:param response: resource's response. This can be
- ``None``,
- django's ``HttpR... | [
"def",
"_process_response",
"(",
"self",
",",
"response",
",",
"request",
")",
":",
"def",
"coerce_response",
"(",
")",
":",
"\"\"\" Coerce the response object into devil structure. \"\"\"",
"if",
"not",
"isinstance",
"(",
"response",
",",
"Response",
")",
":",
"ret... | Process the response.
If the response is ``HttpResponse``, does nothing. Otherwise,
serializes, formats and validates the response.
:param response: resource's response. This can be
- ``None``,
- django's ``HttpResponse``
- devil's ``Response``
- dic... | [
"Process",
"the",
"response",
"."
] | python | train |
robertpeteuil/multi-cloud-control | mcc/cldcnct.py | https://github.com/robertpeteuil/multi-cloud-control/blob/f1565af1c0b6ed465ff312d3ccc592ba0609f4a2/mcc/cldcnct.py#L159-L169 | def adj_nodes_aws(aws_nodes):
"""Adjust details specific to AWS."""
for node in aws_nodes:
node.cloud = "aws"
node.cloud_disp = "AWS"
node.private_ips = ip_to_str(node.private_ips)
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra['availability']
... | [
"def",
"adj_nodes_aws",
"(",
"aws_nodes",
")",
":",
"for",
"node",
"in",
"aws_nodes",
":",
"node",
".",
"cloud",
"=",
"\"aws\"",
"node",
".",
"cloud_disp",
"=",
"\"AWS\"",
"node",
".",
"private_ips",
"=",
"ip_to_str",
"(",
"node",
".",
"private_ips",
")",
... | Adjust details specific to AWS. | [
"Adjust",
"details",
"specific",
"to",
"AWS",
"."
] | python | train |
getsentry/raven-python | raven/base.py | https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L806-L826 | def captureException(self, exc_info=None, **kwargs):
"""
Creates an event from an exception.
>>> try:
>>> exc_info = sys.exc_info()
>>> client.captureException(exc_info)
>>> finally:
>>> del exc_info
If exc_info is not provided, or is set to ... | [
"def",
"captureException",
"(",
"self",
",",
"exc_info",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"exc_info",
"is",
"None",
"or",
"exc_info",
"is",
"True",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"return",
"self",
".",
"c... | Creates an event from an exception.
>>> try:
>>> exc_info = sys.exc_info()
>>> client.captureException(exc_info)
>>> finally:
>>> del exc_info
If exc_info is not provided, or is set to True, then this method will
perform the ``exc_info = sys.exc_info... | [
"Creates",
"an",
"event",
"from",
"an",
"exception",
"."
] | python | train |
PMEAL/OpenPNM | openpnm/materials/VoronoiFibers.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/materials/VoronoiFibers.py#L441-L496 | def inhull(self, xyz, pore, tol=1e-7):
r"""
Tests whether points lie within a convex hull or not.
Computes a tesselation of the hull works out the normals of the facets.
Then tests whether dot(x.normals) < dot(a.normals) where a is the the
first vertex of the facets
"""
... | [
"def",
"inhull",
"(",
"self",
",",
"xyz",
",",
"pore",
",",
"tol",
"=",
"1e-7",
")",
":",
"xyz",
"=",
"np",
".",
"around",
"(",
"xyz",
",",
"10",
")",
"# Work out range to span over for pore hull",
"xmin",
"=",
"xyz",
"[",
":",
",",
"0",
"]",
".",
... | r"""
Tests whether points lie within a convex hull or not.
Computes a tesselation of the hull works out the normals of the facets.
Then tests whether dot(x.normals) < dot(a.normals) where a is the the
first vertex of the facets | [
"r",
"Tests",
"whether",
"points",
"lie",
"within",
"a",
"convex",
"hull",
"or",
"not",
".",
"Computes",
"a",
"tesselation",
"of",
"the",
"hull",
"works",
"out",
"the",
"normals",
"of",
"the",
"facets",
".",
"Then",
"tests",
"whether",
"dot",
"(",
"x",
... | python | train |
facebook/pyre-check | sapp/sapp/interactive.py | https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L411-L420 | def show(self):
""" More details about the selected issue or trace frame.
"""
self._verify_entrypoint_selected()
if self.current_issue_instance_id != -1:
self._show_current_issue_instance()
return
self._show_current_trace_frame() | [
"def",
"show",
"(",
"self",
")",
":",
"self",
".",
"_verify_entrypoint_selected",
"(",
")",
"if",
"self",
".",
"current_issue_instance_id",
"!=",
"-",
"1",
":",
"self",
".",
"_show_current_issue_instance",
"(",
")",
"return",
"self",
".",
"_show_current_trace_fr... | More details about the selected issue or trace frame. | [
"More",
"details",
"about",
"the",
"selected",
"issue",
"or",
"trace",
"frame",
"."
] | python | train |
kennedyshead/aioasuswrt | aioasuswrt/connection.py | https://github.com/kennedyshead/aioasuswrt/blob/0c4336433727abbb7b324ee29e4c5382be9aaa2b/aioasuswrt/connection.py#L92-L118 | async def async_run_command(self, command, first_try=True):
"""Run a command through a Telnet connection.
Connect to the Telnet server if not currently connected, otherwise
use the existing connection.
"""
await self.async_connect()
try:
with (await self._io_l... | [
"async",
"def",
"async_run_command",
"(",
"self",
",",
"command",
",",
"first_try",
"=",
"True",
")",
":",
"await",
"self",
".",
"async_connect",
"(",
")",
"try",
":",
"with",
"(",
"await",
"self",
".",
"_io_lock",
")",
":",
"self",
".",
"_writer",
"."... | Run a command through a Telnet connection.
Connect to the Telnet server if not currently connected, otherwise
use the existing connection. | [
"Run",
"a",
"command",
"through",
"a",
"Telnet",
"connection",
".",
"Connect",
"to",
"the",
"Telnet",
"server",
"if",
"not",
"currently",
"connected",
"otherwise",
"use",
"the",
"existing",
"connection",
"."
] | python | train |
druids/django-chamber | chamber/utils/__init__.py | https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/utils/__init__.py#L17-L28 | def get_class_method(cls_or_inst, method_name):
"""
Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with
properties and cached properties.
"""
cls = cls_or_inst if isinstance(cls_or_inst, type) else cls_or_inst.__class__
meth = geta... | [
"def",
"get_class_method",
"(",
"cls_or_inst",
",",
"method_name",
")",
":",
"cls",
"=",
"cls_or_inst",
"if",
"isinstance",
"(",
"cls_or_inst",
",",
"type",
")",
"else",
"cls_or_inst",
".",
"__class__",
"meth",
"=",
"getattr",
"(",
"cls",
",",
"method_name",
... | Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with
properties and cached properties. | [
"Returns",
"a",
"method",
"from",
"a",
"given",
"class",
"or",
"instance",
".",
"When",
"the",
"method",
"doest",
"not",
"exist",
"it",
"returns",
"None",
".",
"Also",
"works",
"with",
"properties",
"and",
"cached",
"properties",
"."
] | python | train |
AlecAivazis/graphql-over-kafka | nautilus/management/scripts/events/publish.py | https://github.com/AlecAivazis/graphql-over-kafka/blob/70e2acef27a2f87355590be1a6ca60ce3ab4d09c/nautilus/management/scripts/events/publish.py#L15-L38 | def publish(type, payload):
"""
Publish a message with the specified action_type and payload over the
event system. Useful for debugging.
"""
async def _produce():
# fire an action with the given values
await producer.send(action_type=type, payload=payload)
# notify t... | [
"def",
"publish",
"(",
"type",
",",
"payload",
")",
":",
"async",
"def",
"_produce",
"(",
")",
":",
"# fire an action with the given values",
"await",
"producer",
".",
"send",
"(",
"action_type",
"=",
"type",
",",
"payload",
"=",
"payload",
")",
"# notify the ... | Publish a message with the specified action_type and payload over the
event system. Useful for debugging. | [
"Publish",
"a",
"message",
"with",
"the",
"specified",
"action_type",
"and",
"payload",
"over",
"the",
"event",
"system",
".",
"Useful",
"for",
"debugging",
"."
] | python | train |
vertexproject/synapse | synapse/lib/cli.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/cli.py#L310-L316 | def addCmdClass(self, ctor, **opts):
'''
Add a Cmd subclass to this cli.
'''
item = ctor(self, **opts)
name = item.getCmdName()
self.cmds[name] = item | [
"def",
"addCmdClass",
"(",
"self",
",",
"ctor",
",",
"*",
"*",
"opts",
")",
":",
"item",
"=",
"ctor",
"(",
"self",
",",
"*",
"*",
"opts",
")",
"name",
"=",
"item",
".",
"getCmdName",
"(",
")",
"self",
".",
"cmds",
"[",
"name",
"]",
"=",
"item"
... | Add a Cmd subclass to this cli. | [
"Add",
"a",
"Cmd",
"subclass",
"to",
"this",
"cli",
"."
] | python | train |
christian-oudard/htmltreediff | htmltreediff/diff_core.py | https://github.com/christian-oudard/htmltreediff/blob/0e28f56492ae7e69bb0f74f9a79a8909a5ad588d/htmltreediff/diff_core.py#L246-L253 | def match_blocks(hash_func, old_children, new_children):
"""Use difflib to find matching blocks."""
sm = difflib.SequenceMatcher(
_is_junk,
a=[hash_func(c) for c in old_children],
b=[hash_func(c) for c in new_children],
)
return sm | [
"def",
"match_blocks",
"(",
"hash_func",
",",
"old_children",
",",
"new_children",
")",
":",
"sm",
"=",
"difflib",
".",
"SequenceMatcher",
"(",
"_is_junk",
",",
"a",
"=",
"[",
"hash_func",
"(",
"c",
")",
"for",
"c",
"in",
"old_children",
"]",
",",
"b",
... | Use difflib to find matching blocks. | [
"Use",
"difflib",
"to",
"find",
"matching",
"blocks",
"."
] | python | train |
sentinel-hub/eo-learn | core/eolearn/core/utilities.py | https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/core/eolearn/core/utilities.py#L325-L337 | def get_common_timestamps(source, target):
"""Return indices of timestamps from source that are also found in target.
:param source: timestamps from source
:type source: list of datetime objects
:param target: timestamps from target
:type target: list of datetime objects
:return: indices... | [
"def",
"get_common_timestamps",
"(",
"source",
",",
"target",
")",
":",
"remove_from_source",
"=",
"set",
"(",
"source",
")",
".",
"difference",
"(",
"target",
")",
"remove_from_source_idxs",
"=",
"[",
"source",
".",
"index",
"(",
"rm_date",
")",
"for",
"rm_... | Return indices of timestamps from source that are also found in target.
:param source: timestamps from source
:type source: list of datetime objects
:param target: timestamps from target
:type target: list of datetime objects
:return: indices of timestamps from source that are also found in t... | [
"Return",
"indices",
"of",
"timestamps",
"from",
"source",
"that",
"are",
"also",
"found",
"in",
"target",
".",
":",
"param",
"source",
":",
"timestamps",
"from",
"source",
":",
"type",
"source",
":",
"list",
"of",
"datetime",
"objects",
":",
"param",
"tar... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.