nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PropertyGridInterface.GetPropertyValues | (self,dict_=None, as_strings=False,
inc_attributes=False) | return dict_ | Returns values in the grid. | Returns values in the grid. | [
"Returns",
"values",
"in",
"the",
"grid",
"."
] | def GetPropertyValues(self,dict_=None, as_strings=False,
inc_attributes=False):
"Returns values in the grid."
""
"dict_: if not given, then a new one is created. dict_ can be"
" object as well, in which case it's __dict__ is used."
"as_strings: if True, then string representations of values"
" are fetched instead of native types. Useful for config and "
"such."
"inc_attributes: if True, then property attributes are added"
" as @<propname>@<attr>."
""
"Return value: dictionary with values. It is always a dictionary,"
"so if dict_ was object with __dict__ attribute, then that "
"attribute is returned."
if dict_ is None:
dict_ = {}
elif hasattr(dict_,'__dict__'):
dict_ = dict_.__dict__
if not as_strings:
getter = self.GetPropertyValue
else:
getter = self.GetPropertyValueAsString
it = self.GetVIterator(PG_ITERATE_PROPERTIES)
while not it.AtEnd():
p = it.GetProperty()
name = p.GetName()
dict_[name] = getter(p)
if inc_attributes:
attrs = p.GetAttributes()
if attrs and len(attrs):
dict_['@%s@attr'%name] = attrs
it.Next()
return dict_ | [
"def",
"GetPropertyValues",
"(",
"self",
",",
"dict_",
"=",
"None",
",",
"as_strings",
"=",
"False",
",",
"inc_attributes",
"=",
"False",
")",
":",
"\"\"",
"\"dict_: if not given, then a new one is created. dict_ can be\"",
"\" object as well, in which case it's __dict__ is ... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L1531-L1571 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/isis_instrument.py | python | ISISInstrument.set_incident_mon | (self, spectrum_number) | set the incident scattering monitor spectrum number regardless of
lock
@param spectrum_number: monitor's sectrum number | set the incident scattering monitor spectrum number regardless of
lock | [
"set",
"the",
"incident",
"scattering",
"monitor",
"spectrum",
"number",
"regardless",
"of",
"lock"
] | def set_incident_mon(self, spectrum_number):
"""
set the incident scattering monitor spectrum number regardless of
lock
@param spectrum_number: monitor's sectrum number
"""
self._incid_monitor = int(spectrum_number)
self._del_incidient_set = True | [
"def",
"set_incident_mon",
"(",
"self",
",",
"spectrum_number",
")",
":",
"self",
".",
"_incid_monitor",
"=",
"int",
"(",
"spectrum_number",
")",
"self",
".",
"_del_incidient_set",
"=",
"True"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/isis_instrument.py#L537-L544 | ||
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/GardenSnake/GardenSnake.py | python | p_trailer | (p) | trailer : LPAR arglist RPAR | trailer : LPAR arglist RPAR | [
"trailer",
":",
"LPAR",
"arglist",
"RPAR"
] | def p_trailer(p):
"trailer : LPAR arglist RPAR"
p[0] = ("CALL", p[2]) | [
"def",
"p_trailer",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"\"CALL\"",
",",
"p",
"[",
"2",
"]",
")"
] | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/GardenSnake/GardenSnake.py#L568-L570 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/packaging/msi.py | python | build_wxsfile_file_section | (root, files, NAME, VERSION, VENDOR, filename_set, id_set) | Builds the Component sections of the wxs file with their included files.
Files need to be specified in 8.3 format and in the long name format, long
filenames will be converted automatically.
Features are specficied with the 'X_MSI_FEATURE' or 'DOC' FileTag. | Builds the Component sections of the wxs file with their included files. | [
"Builds",
"the",
"Component",
"sections",
"of",
"the",
"wxs",
"file",
"with",
"their",
"included",
"files",
"."
] | def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set, id_set):
""" Builds the Component sections of the wxs file with their included files.
Files need to be specified in 8.3 format and in the long name format, long
filenames will be converted automatically.
Features are specficied with the 'X_MSI_FEATURE' or 'DOC' FileTag.
"""
root = create_default_directory_layout( root, NAME, VERSION, VENDOR, filename_set )
components = create_feature_dict( files )
factory = Document()
def get_directory( node, dir ):
""" Returns the node under the given node representing the directory.
Returns the component node if dir is None or empty.
"""
if dir == '' or not dir:
return node
Directory = node
dir_parts = dir.split(os.path.sep)
# to make sure that our directory ids are unique, the parent folders are
# consecutively added to upper_dir
upper_dir = ''
# walk down the xml tree finding parts of the directory
dir_parts = [d for d in dir_parts if d != '']
for d in dir_parts[:]:
already_created = [c for c in Directory.childNodes
if c.nodeName == 'Directory'
and c.attributes['LongName'].value == escape(d)]
if already_created != []:
Directory = already_created[0]
dir_parts.remove(d)
upper_dir += d
else:
break
for d in dir_parts:
nDirectory = factory.createElement( 'Directory' )
nDirectory.attributes['LongName'] = escape( d )
nDirectory.attributes['Name'] = escape( gen_dos_short_file_name( d, filename_set ) )
upper_dir += d
nDirectory.attributes['Id'] = convert_to_id( upper_dir, id_set )
Directory.childNodes.append( nDirectory )
Directory = nDirectory
return Directory
for file in files:
drive, path = os.path.splitdrive( file.PACKAGING_INSTALL_LOCATION )
filename = os.path.basename( path )
dirname = os.path.dirname( path )
h = {
# tagname : default value
'PACKAGING_X_MSI_VITAL' : 'yes',
'PACKAGING_X_MSI_FILEID' : convert_to_id(filename, id_set),
'PACKAGING_X_MSI_LONGNAME' : filename,
'PACKAGING_X_MSI_SHORTNAME' : gen_dos_short_file_name(filename, filename_set),
'PACKAGING_X_MSI_SOURCE' : file.get_path(),
}
# fill in the default tags given above.
for k,v in [ (k, v) for (k,v) in h.items() if not hasattr(file, k) ]:
setattr( file, k, v )
File = factory.createElement( 'File' )
File.attributes['LongName'] = escape( file.PACKAGING_X_MSI_LONGNAME )
File.attributes['Name'] = escape( file.PACKAGING_X_MSI_SHORTNAME )
File.attributes['Source'] = escape( file.PACKAGING_X_MSI_SOURCE )
File.attributes['Id'] = escape( file.PACKAGING_X_MSI_FILEID )
File.attributes['Vital'] = escape( file.PACKAGING_X_MSI_VITAL )
# create the <Component> Tag under which this file should appear
Component = factory.createElement('Component')
Component.attributes['DiskId'] = '1'
Component.attributes['Id'] = convert_to_id( filename, id_set )
# hang the component node under the root node and the file node
# under the component node.
Directory = get_directory( root, dirname )
Directory.childNodes.append( Component )
Component.childNodes.append( File ) | [
"def",
"build_wxsfile_file_section",
"(",
"root",
",",
"files",
",",
"NAME",
",",
"VERSION",
",",
"VENDOR",
",",
"filename_set",
",",
"id_set",
")",
":",
"root",
"=",
"create_default_directory_layout",
"(",
"root",
",",
"NAME",
",",
"VERSION",
",",
"VENDOR",
... | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/packaging/msi.py#L270-L357 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/framemanager.py | python | GetToolBarDockOffsets | (docks) | return top_left, bottom_right | Returns the toolbar dock offsets (top-left and bottom-right).
:param `docks`: a list of :class:`AuiDockInfo` to analyze. | Returns the toolbar dock offsets (top-left and bottom-right). | [
"Returns",
"the",
"toolbar",
"dock",
"offsets",
"(",
"top",
"-",
"left",
"and",
"bottom",
"-",
"right",
")",
"."
] | def GetToolBarDockOffsets(docks):
"""
Returns the toolbar dock offsets (top-left and bottom-right).
:param `docks`: a list of :class:`AuiDockInfo` to analyze.
"""
top_left = wx.Size(0, 0)
bottom_right = wx.Size(0, 0)
for dock in docks:
if dock.toolbar:
dock_direction = dock.dock_direction
if dock_direction == AUI_DOCK_LEFT:
top_left.x += dock.rect.width
bottom_right.x += dock.rect.width
elif dock_direction == AUI_DOCK_TOP:
top_left.y += dock.rect.height
bottom_right.y += dock.rect.height
elif dock_direction == AUI_DOCK_RIGHT:
bottom_right.x += dock.rect.width
elif dock_direction == AUI_DOCK_BOTTOM:
bottom_right.y += dock.rect.height
return top_left, bottom_right | [
"def",
"GetToolBarDockOffsets",
"(",
"docks",
")",
":",
"top_left",
"=",
"wx",
".",
"Size",
"(",
"0",
",",
"0",
")",
"bottom_right",
"=",
"wx",
".",
"Size",
"(",
"0",
",",
"0",
")",
"for",
"dock",
"in",
"docks",
":",
"if",
"dock",
".",
"toolbar",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L3717-L3744 | |
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | python/mxnet/executor_manager.py | python | DataParallelExecutorManager.update_metric | (self, metric, labels) | update metric with the current executor | update metric with the current executor | [
"update",
"metric",
"with",
"the",
"current",
"executor"
] | def update_metric(self, metric, labels):
"""update metric with the current executor"""
self.curr_execgrp.update_metric(metric, labels) | [
"def",
"update_metric",
"(",
"self",
",",
"metric",
",",
"labels",
")",
":",
"self",
".",
"curr_execgrp",
".",
"update_metric",
"(",
"metric",
",",
"labels",
")"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/mxnet/executor_manager.py#L391-L393 | ||
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | python/mxnet/ndarray.py | python | ones | (shape, ctx=None, dtype=mx_real_t) | return arr | Create a new NDArray filled with 1, with specified shape.
Parameters
----------
shape : tuple
shape of the NDArray.
ctx : Context, optional
The context of the NDArray, default to current default context.
Returns
-------
out: Array
The created NDArray. | Create a new NDArray filled with 1, with specified shape. | [
"Create",
"a",
"new",
"NDArray",
"filled",
"with",
"1",
"with",
"specified",
"shape",
"."
] | def ones(shape, ctx=None, dtype=mx_real_t):
"""Create a new NDArray filled with 1, with specified shape.
Parameters
----------
shape : tuple
shape of the NDArray.
ctx : Context, optional
The context of the NDArray, default to current default context.
Returns
-------
out: Array
The created NDArray.
"""
arr = empty(shape, ctx, dtype)
arr[:] = 1.0
return arr | [
"def",
"ones",
"(",
"shape",
",",
"ctx",
"=",
"None",
",",
"dtype",
"=",
"mx_real_t",
")",
":",
"arr",
"=",
"empty",
"(",
"shape",
",",
"ctx",
",",
"dtype",
")",
"arr",
"[",
":",
"]",
"=",
"1.0",
"return",
"arr"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/mxnet/ndarray.py#L663-L680 | |
hszhao/PSPNet | cf7e5a99ba37e46118026e96be5821a9bc63bde0 | examples/web_demo/app.py | python | embed_image_html | (image) | return 'data:image/png;base64,' + data | Creates an image embedded in HTML base64 format. | Creates an image embedded in HTML base64 format. | [
"Creates",
"an",
"image",
"embedded",
"in",
"HTML",
"base64",
"format",
"."
] | def embed_image_html(image):
"""Creates an image embedded in HTML base64 format."""
image_pil = Image.fromarray((255 * image).astype('uint8'))
image_pil = image_pil.resize((256, 256))
string_buf = StringIO.StringIO()
image_pil.save(string_buf, format='png')
data = string_buf.getvalue().encode('base64').replace('\n', '')
return 'data:image/png;base64,' + data | [
"def",
"embed_image_html",
"(",
"image",
")",
":",
"image_pil",
"=",
"Image",
".",
"fromarray",
"(",
"(",
"255",
"*",
"image",
")",
".",
"astype",
"(",
"'uint8'",
")",
")",
"image_pil",
"=",
"image_pil",
".",
"resize",
"(",
"(",
"256",
",",
"256",
")... | https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/examples/web_demo/app.py#L82-L89 | |
Evolving-AI-Lab/fooling | 66f097dd6bd2eb6794ade3e187a7adfdf1887688 | caffe/scripts/cpp_lint.py | python | _VerboseLevel | () | return _cpplint_state.verbose_level | Returns the module's verbosity setting. | Returns the module's verbosity setting. | [
"Returns",
"the",
"module",
"s",
"verbosity",
"setting",
"."
] | def _VerboseLevel():
"""Returns the module's verbosity setting."""
return _cpplint_state.verbose_level | [
"def",
"_VerboseLevel",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"verbose_level"
] | https://github.com/Evolving-AI-Lab/fooling/blob/66f097dd6bd2eb6794ade3e187a7adfdf1887688/caffe/scripts/cpp_lint.py#L776-L778 | |
scribusproject/scribus | 41ec7c775a060912cf251682a8b1437f753f80f4 | scribus/plugins/scriptplugin/scripts/Ligatursatz.py | python | StoryInterface.read_text | (self, first, count) | return scribus.getAllText(self.__identifier) | Precondition: The object with the unique identifier “textFrame”
(constructor argument) currently exists in the current document,
and it refers to a text frame. “first” and “count” are non-negative
integers. The requested range exists really.
Postcondition: Returns a value of type “unicode” that contains the
requested text range (the total number of “count” indexes, starting at
index “first”). Note that the indexes are the indexes provides by
scribus. This may not be unicode characters, but UTF16 code units, and
if you choose half a surrogate pair, scribus will silently add the
missing half surrogate pair. The indexes does not refer to the actual
text content of “textFrame”, but to the content of the underlying
“story”, that means the common text content that is shared between
this text frame and all linked text frames. Note that this function
will (likely) change the current text selection of the story. | Precondition: The object with the unique identifier “textFrame”
(constructor argument) currently exists in the current document,
and it refers to a text frame. “first” and “count” are non-negative
integers. The requested range exists really.
Postcondition: Returns a value of type “unicode” that contains the
requested text range (the total number of “count” indexes, starting at
index “first”). Note that the indexes are the indexes provides by
scribus. This may not be unicode characters, but UTF16 code units, and
if you choose half a surrogate pair, scribus will silently add the
missing half surrogate pair. The indexes does not refer to the actual
text content of “textFrame”, but to the content of the underlying
“story”, that means the common text content that is shared between
this text frame and all linked text frames. Note that this function
will (likely) change the current text selection of the story. | [
"Precondition",
":",
"The",
"object",
"with",
"the",
"unique",
"identifier",
"“textFrame”",
"(",
"constructor",
"argument",
")",
"currently",
"exists",
"in",
"the",
"current",
"document",
"and",
"it",
"refers",
"to",
"a",
"text",
"frame",
".",
"“first”",
"and"... | def read_text(self, first, count):
"""Precondition: The object with the unique identifier “textFrame”
(constructor argument) currently exists in the current document,
and it refers to a text frame. “first” and “count” are non-negative
integers. The requested range exists really.
Postcondition: Returns a value of type “unicode” that contains the
requested text range (the total number of “count” indexes, starting at
index “first”). Note that the indexes are the indexes provides by
scribus. This may not be unicode characters, but UTF16 code units, and
if you choose half a surrogate pair, scribus will silently add the
missing half surrogate pair. The indexes does not refer to the actual
text content of “textFrame”, but to the content of the underlying
“story”, that means the common text content that is shared between
this text frame and all linked text frames. Note that this function
will (likely) change the current text selection of the story."""
if (type(first) is not int) or (type(count) is not int):
raise TypeError("Both arguments, “first” and “count”, must be "
"integers, but they aren’t.")
if (first < 0) or (count < 0):
raise IndexError("Both arguments, “first” and “count”, must"
"not be negative, but they are.")
if scribus.getObjectType(self.__identifier) != "TextFrame":
raise RuntimeError("The argument “textFrame” that was given in "
"the constructor does currently not refer to "
"a text frame in the current document.")
# If count is 0, scribus.selectText will select nothing. But when
# nothing is selected, scribus.getAllText will not return an empty
# string, but the hole content of the story. That is not what we
# expect, so we have to catch this case manually.
if count == 0:
if first >= self.length():
raise IndexError("“first” is out of range.")
return u""
scribus.selectText(first, count, self.__identifier)
return scribus.getAllText(self.__identifier) | [
"def",
"read_text",
"(",
"self",
",",
"first",
",",
"count",
")",
":",
"if",
"(",
"type",
"(",
"first",
")",
"is",
"not",
"int",
")",
"or",
"(",
"type",
"(",
"count",
")",
"is",
"not",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"Both arguments, ... | https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/scribus/plugins/scriptplugin/scripts/Ligatursatz.py#L22429-L22463 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetLibtoolflags | (self, configname) | return libtoolflags | Returns flags that need to be passed to the static linker.
Args:
configname: The name of the configuration to get ld flags for. | Returns flags that need to be passed to the static linker. | [
"Returns",
"flags",
"that",
"need",
"to",
"be",
"passed",
"to",
"the",
"static",
"linker",
"."
] | def GetLibtoolflags(self, configname):
"""Returns flags that need to be passed to the static linker.
Args:
configname: The name of the configuration to get ld flags for.
"""
self.configname = configname
libtoolflags = []
for libtoolflag in self._Settings().get('OTHER_LDFLAGS', []):
libtoolflags.append(libtoolflag)
# TODO(thakis): ARCHS?
self.configname = None
return libtoolflags | [
"def",
"GetLibtoolflags",
"(",
"self",
",",
"configname",
")",
":",
"self",
".",
"configname",
"=",
"configname",
"libtoolflags",
"=",
"[",
"]",
"for",
"libtoolflag",
"in",
"self",
".",
"_Settings",
"(",
")",
".",
"get",
"(",
"'OTHER_LDFLAGS'",
",",
"[",
... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L853-L867 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/CallTips.py | python | CallTips.get_entity | (self, expression) | Return the object corresponding to expression evaluated
in a namespace spanning sys.modules and __main.dict__. | Return the object corresponding to expression evaluated
in a namespace spanning sys.modules and __main.dict__. | [
"Return",
"the",
"object",
"corresponding",
"to",
"expression",
"evaluated",
"in",
"a",
"namespace",
"spanning",
"sys",
".",
"modules",
"and",
"__main",
".",
"dict__",
"."
] | def get_entity(self, expression):
"""Return the object corresponding to expression evaluated
in a namespace spanning sys.modules and __main.dict__.
"""
if expression:
namespace = sys.modules.copy()
namespace.update(__main__.__dict__)
try:
return eval(expression, namespace)
except BaseException:
# An uncaught exception closes idle, and eval can raise any
# exception, especially if user classes are involved.
return None | [
"def",
"get_entity",
"(",
"self",
",",
"expression",
")",
":",
"if",
"expression",
":",
"namespace",
"=",
"sys",
".",
"modules",
".",
"copy",
"(",
")",
"namespace",
".",
"update",
"(",
"__main__",
".",
"__dict__",
")",
"try",
":",
"return",
"eval",
"("... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/CallTips.py#L108-L120 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/ipaddr/ipaddr.py | python | _BaseV4.is_link_local | (self) | return self in IPv4Network('169.254.0.0/16') | Test if the address is reserved for link-local.
Returns:
A boolean, True if the address is link-local per RFC 3927. | Test if the address is reserved for link-local. | [
"Test",
"if",
"the",
"address",
"is",
"reserved",
"for",
"link",
"-",
"local",
"."
] | def is_link_local(self):
"""Test if the address is reserved for link-local.
Returns:
A boolean, True if the address is link-local per RFC 3927.
"""
return self in IPv4Network('169.254.0.0/16') | [
"def",
"is_link_local",
"(",
"self",
")",
":",
"return",
"self",
"in",
"IPv4Network",
"(",
"'169.254.0.0/16'",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/ipaddr/ipaddr.py#L1161-L1168 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py | python | _dlog10 | (c, e, p) | return _div_nearest(log_tenpower+log_d, 100) | Given integers c, e and p with c > 0, p >= 0, compute an integer
approximation to 10**p * log10(c*10**e), with an absolute error of
at most 1. Assumes that c*10**e is not exactly 1. | Given integers c, e and p with c > 0, p >= 0, compute an integer
approximation to 10**p * log10(c*10**e), with an absolute error of
at most 1. Assumes that c*10**e is not exactly 1. | [
"Given",
"integers",
"c",
"e",
"and",
"p",
"with",
"c",
">",
"0",
"p",
">",
"=",
"0",
"compute",
"an",
"integer",
"approximation",
"to",
"10",
"**",
"p",
"*",
"log10",
"(",
"c",
"*",
"10",
"**",
"e",
")",
"with",
"an",
"absolute",
"error",
"of",
... | def _dlog10(c, e, p):
"""Given integers c, e and p with c > 0, p >= 0, compute an integer
approximation to 10**p * log10(c*10**e), with an absolute error of
at most 1. Assumes that c*10**e is not exactly 1."""
# increase precision by 2; compensate for this by dividing
# final result by 100
p += 2
# write c*10**e as d*10**f with either:
# f >= 0 and 1 <= d <= 10, or
# f <= 0 and 0.1 <= d <= 1.
# Thus for c*10**e close to 1, f = 0
l = len(str(c))
f = e+l - (e+l >= 1)
if p > 0:
M = 10**p
k = e+p-f
if k >= 0:
c *= 10**k
else:
c = _div_nearest(c, 10**-k)
log_d = _ilog(c, M) # error < 5 + 22 = 27
log_10 = _log10_digits(p) # error < 1
log_d = _div_nearest(log_d*M, log_10)
log_tenpower = f*M # exact
else:
log_d = 0 # error < 2.31
log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
return _div_nearest(log_tenpower+log_d, 100) | [
"def",
"_dlog10",
"(",
"c",
",",
"e",
",",
"p",
")",
":",
"# increase precision by 2; compensate for this by dividing",
"# final result by 100",
"p",
"+=",
"2",
"# write c*10**e as d*10**f with either:",
"# f >= 0 and 1 <= d <= 10, or",
"# f <= 0 and 0.1 <= d <= 1.",
"# Thus ... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py#L5774-L5806 | |
RcppCore/RcppParallel | ff49e84602a1771c06bc39fdea995447564f2b7f | src/tbb/python/tbb/pool.py | python | AbstractResultCollector._get_result | (self, idx, timeout=None) | Called by the CollectorIterator object to retrieve the
result's values one after another (order defined by the
implementation)
\param idx The index of the result we want, wrt collector's order
\param timeout integer telling how long to wait (in seconds)
for the result at index idx to be available, or None (wait
forever) | Called by the CollectorIterator object to retrieve the
result's values one after another (order defined by the
implementation)
\param idx The index of the result we want, wrt collector's order
\param timeout integer telling how long to wait (in seconds)
for the result at index idx to be available, or None (wait
forever) | [
"Called",
"by",
"the",
"CollectorIterator",
"object",
"to",
"retrieve",
"the",
"result",
"s",
"values",
"one",
"after",
"another",
"(",
"order",
"defined",
"by",
"the",
"implementation",
")",
"\\",
"param",
"idx",
"The",
"index",
"of",
"the",
"result",
"we",... | def _get_result(self, idx, timeout=None):
"""Called by the CollectorIterator object to retrieve the
result's values one after another (order defined by the
implementation)
\param idx The index of the result we want, wrt collector's order
\param timeout integer telling how long to wait (in seconds)
for the result at index idx to be available, or None (wait
forever)
"""
raise NotImplementedError("Children classes must implement it") | [
"def",
"_get_result",
"(",
"self",
",",
"idx",
",",
"timeout",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Children classes must implement it\"",
")"
] | https://github.com/RcppCore/RcppParallel/blob/ff49e84602a1771c06bc39fdea995447564f2b7f/src/tbb/python/tbb/pool.py#L435-L444 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/Blast/houdini/python2.7libs/blastExport/slice.py | python | Slice.editorEntityIconComponentId | (self, value) | :return: str | :return: str | [
":",
"return",
":",
"str"
] | def editorEntityIconComponentId(self, value):
"""
:return: str
"""
if self.__editorEntityIconComponentId == value:
return
self.__editorEntityIconComponentId = value | [
"def",
"editorEntityIconComponentId",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"__editorEntityIconComponentId",
"==",
"value",
":",
"return",
"self",
".",
"__editorEntityIconComponentId",
"=",
"value"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/houdini/python2.7libs/blastExport/slice.py#L497-L505 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/ragged/ragged_tensor_shape.py | python | RaggedTensorDynamicShape.broadcast_to_rank | (self, rank) | Adds leading size-1 dimensions to broadcast `self` to the given rank.
E.g., if `shape1` is `[3, (D2), 4]`, then `shape1.broadcast_to_rank(5)`
is `[1, 1, 3, (D2), 4]`.
Args:
rank: The rank for the returned shape.
Returns:
A RaggedTensorDynamicShape with `rank` dimensions, whose inner dimensions
have the same size as `self` and whose outer dimensions have size `1`.
Raises:
ValueError: If `self.rank` is unknown or greater than `rank`. | Adds leading size-1 dimensions to broadcast `self` to the given rank. | [
"Adds",
"leading",
"size",
"-",
"1",
"dimensions",
"to",
"broadcast",
"self",
"to",
"the",
"given",
"rank",
"."
] | def broadcast_to_rank(self, rank):
"""Adds leading size-1 dimensions to broadcast `self` to the given rank.
E.g., if `shape1` is `[3, (D2), 4]`, then `shape1.broadcast_to_rank(5)`
is `[1, 1, 3, (D2), 4]`.
Args:
rank: The rank for the returned shape.
Returns:
A RaggedTensorDynamicShape with `rank` dimensions, whose inner dimensions
have the same size as `self` and whose outer dimensions have size `1`.
Raises:
ValueError: If `self.rank` is unknown or greater than `rank`.
"""
if self.rank is None:
raise ValueError('Unable to broadcast: self.rank is unknown')
dims_to_add = rank - self.rank
if dims_to_add < 0:
raise ValueError('Unable to broadcast: rank=%d must be greater than '
'self.rank=%d.' % (rank, self.rank))
elif dims_to_add == 0:
return self
elif self._partitioned_dim_sizes:
partitioned_dims = (1,) * dims_to_add + self._partitioned_dim_sizes
return RaggedTensorDynamicShape(partitioned_dims, self.inner_dim_sizes,
self.dim_size_dtype)
else:
inner_dims = array_ops.concat(
[array_ops.ones([dims_to_add], self.dim_size_dtype),
self.inner_dim_sizes],
axis=0)
return RaggedTensorDynamicShape([], inner_dims, self.dim_size_dtype) | [
"def",
"broadcast_to_rank",
"(",
"self",
",",
"rank",
")",
":",
"if",
"self",
".",
"rank",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unable to broadcast: self.rank is unknown'",
")",
"dims_to_add",
"=",
"rank",
"-",
"self",
".",
"rank",
"if",
"dims_to_a... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/ragged/ragged_tensor_shape.py#L256-L289 | ||
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/inputs/atoms.py | python | InputAtoms.fetch | (self) | return atoms | Creates an atoms object.
Returns:
An atoms object of the appropriate type and with the appropriate
properties given the attributes of the InputAtoms object. | Creates an atoms object. | [
"Creates",
"an",
"atoms",
"object",
"."
] | def fetch(self):
"""Creates an atoms object.
Returns:
An atoms object of the appropriate type and with the appropriate
properties given the attributes of the InputAtoms object.
"""
super(InputAtoms,self).fetch()
atoms = Atoms(self.natoms.fetch())
atoms.q = self.q.fetch()
atoms.p = self.p.fetch()
atoms.m = self.m.fetch()
atoms.names = self.names.fetch()
return atoms | [
"def",
"fetch",
"(",
"self",
")",
":",
"super",
"(",
"InputAtoms",
",",
"self",
")",
".",
"fetch",
"(",
")",
"atoms",
"=",
"Atoms",
"(",
"self",
".",
"natoms",
".",
"fetch",
"(",
")",
")",
"atoms",
".",
"q",
"=",
"self",
".",
"q",
".",
"fetch",... | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/inputs/atoms.py#L93-L107 | |
turi-code/SFrame | 796b9bdfb2fa1b881d82080754643c7e68629cd2 | oss_src/unity/python/sframe/data_structures/sarray.py | python | SArray.nnz | (self) | Number of non-zero elements in the SArray.
Returns
-------
out : int
Number of non-zero elements. | Number of non-zero elements in the SArray. | [
"Number",
"of",
"non",
"-",
"zero",
"elements",
"in",
"the",
"SArray",
"."
] | def nnz(self):
"""
Number of non-zero elements in the SArray.
Returns
-------
out : int
Number of non-zero elements.
"""
with cython_context():
return self.__proxy__.nnz() | [
"def",
"nnz",
"(",
"self",
")",
":",
"with",
"cython_context",
"(",
")",
":",
"return",
"self",
".",
"__proxy__",
".",
"nnz",
"(",
")"
] | https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sarray.py#L2294-L2304 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py | python | CallWrapper.__init__ | (self, func, subst, widget) | Store FUNC, SUBST and WIDGET as members. | Store FUNC, SUBST and WIDGET as members. | [
"Store",
"FUNC",
"SUBST",
"and",
"WIDGET",
"as",
"members",
"."
] | def __init__(self, func, subst, widget):
"""Store FUNC, SUBST and WIDGET as members."""
self.func = func
self.subst = subst
self.widget = widget | [
"def",
"__init__",
"(",
"self",
",",
"func",
",",
"subst",
",",
"widget",
")",
":",
"self",
".",
"func",
"=",
"func",
"self",
".",
"subst",
"=",
"subst",
"self",
".",
"widget",
"=",
"widget"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L1695-L1699 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | tools/code_coverage/coverage_posix.py | python | Coverage.AfterRunAllTests | (self) | Do things right after running ALL tests. | Do things right after running ALL tests. | [
"Do",
"things",
"right",
"after",
"running",
"ALL",
"tests",
"."
] | def AfterRunAllTests(self):
"""Do things right after running ALL tests."""
# On POSIX we can do it all at once without running out of memory.
# This contrasts with Windows where we must do it after each test.
if self.IsPosix():
self.GenerateLcovPosix()
# Only on Linux do we have the Xvfb step.
if self.IsLinux() and self.options.xvfb:
self.StopXvfb() | [
"def",
"AfterRunAllTests",
"(",
"self",
")",
":",
"# On POSIX we can do it all at once without running out of memory.",
"# This contrasts with Windows where we must do it after each test.",
"if",
"self",
".",
"IsPosix",
"(",
")",
":",
"self",
".",
"GenerateLcovPosix",
"(",
")",... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/code_coverage/coverage_posix.py#L729-L737 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py | python | LuongAttentionV2.__init__ | (self,
units,
memory,
memory_sequence_length=None,
scale=False,
probability_fn="softmax",
dtype=None,
name="LuongAttention",
**kwargs) | Construct the AttentionMechanism mechanism.
Args:
units: The depth of the attention mechanism.
memory: The memory to query; usually the output of an RNN encoder. This
tensor should be shaped `[batch_size, max_time, ...]`.
memory_sequence_length: (optional): Sequence lengths for the batch entries
in memory. If provided, the memory tensor rows are masked with zeros
for values past the respective sequence lengths.
scale: Python boolean. Whether to scale the energy term.
probability_fn: (optional) string, the name of function to convert the
attention score to probabilities. The default is `softmax` which is
`tf.nn.softmax`. Other options is `hardmax`, which is hardmax() within
this module. Any other value will result intovalidation error. Default
to use `softmax`.
dtype: The data type for the memory layer of the attention mechanism.
name: Name to use when creating ops.
**kwargs: Dictionary that contains other common arguments for layer
creation. | Construct the AttentionMechanism mechanism. | [
"Construct",
"the",
"AttentionMechanism",
"mechanism",
"."
] | def __init__(self,
units,
memory,
memory_sequence_length=None,
scale=False,
probability_fn="softmax",
dtype=None,
name="LuongAttention",
**kwargs):
"""Construct the AttentionMechanism mechanism.
Args:
units: The depth of the attention mechanism.
memory: The memory to query; usually the output of an RNN encoder. This
tensor should be shaped `[batch_size, max_time, ...]`.
memory_sequence_length: (optional): Sequence lengths for the batch entries
in memory. If provided, the memory tensor rows are masked with zeros
for values past the respective sequence lengths.
scale: Python boolean. Whether to scale the energy term.
probability_fn: (optional) string, the name of function to convert the
attention score to probabilities. The default is `softmax` which is
`tf.nn.softmax`. Other options is `hardmax`, which is hardmax() within
this module. Any other value will result intovalidation error. Default
to use `softmax`.
dtype: The data type for the memory layer of the attention mechanism.
name: Name to use when creating ops.
**kwargs: Dictionary that contains other common arguments for layer
creation.
"""
# For LuongAttention, we only transform the memory layer; thus
# num_units **must** match expected the query depth.
self.probability_fn_name = probability_fn
probability_fn = self._process_probability_fn(self.probability_fn_name)
wrapped_probability_fn = lambda score, _: probability_fn(score)
if dtype is None:
dtype = dtypes.float32
memory_layer = kwargs.pop("memory_layer", None)
if not memory_layer:
memory_layer = layers.Dense(
units, name="memory_layer", use_bias=False, dtype=dtype)
self.units = units
self.scale = scale
self.scale_weight = None
super(LuongAttentionV2, self).__init__(
memory=memory,
memory_sequence_length=memory_sequence_length,
query_layer=None,
memory_layer=memory_layer,
probability_fn=wrapped_probability_fn,
name=name,
dtype=dtype,
**kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"units",
",",
"memory",
",",
"memory_sequence_length",
"=",
"None",
",",
"scale",
"=",
"False",
",",
"probability_fn",
"=",
"\"softmax\"",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"\"LuongAttention\"",
",",
"*",
"*"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py#L770-L821 | ||
syoyo/tinygltf | e7f1ff5c59d3ca2489923beb239bdf93d863498f | deps/cpplint.py | python | FilesBelongToSameModule | (filename_cc, filename_h) | return files_belong_to_same_module, common_path | Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to the same module here.
If the filename_cc contains a longer path than the filename_h, for example,
'/absolute/path/to/base/sysinfo.cc', and this file would include
'base/sysinfo.h', this function also produces the prefix needed to open the
header. This is used by the caller of this function to more robustly open the
header file. We don't have access to the real include paths in this context,
so we need this guesswork here.
Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
according to this implementation. Because of this, this function gives
some false positives. This should be sufficiently rare in practice.
Args:
filename_cc: is the path for the .cc file
filename_h: is the path for the header path
Returns:
Tuple with a bool and a string:
bool: True if filename_cc and filename_h belong to the same module.
string: the additional prefix needed to open the header file. | Check if these two filenames belong to the same module. | [
"Check",
"if",
"these",
"two",
"filenames",
"belong",
"to",
"the",
"same",
"module",
"."
] | def FilesBelongToSameModule(filename_cc, filename_h):
"""Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to the same module here.
If the filename_cc contains a longer path than the filename_h, for example,
'/absolute/path/to/base/sysinfo.cc', and this file would include
'base/sysinfo.h', this function also produces the prefix needed to open the
header. This is used by the caller of this function to more robustly open the
header file. We don't have access to the real include paths in this context,
so we need this guesswork here.
Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
according to this implementation. Because of this, this function gives
some false positives. This should be sufficiently rare in practice.
Args:
filename_cc: is the path for the .cc file
filename_h: is the path for the header path
Returns:
Tuple with a bool and a string:
bool: True if filename_cc and filename_h belong to the same module.
string: the additional prefix needed to open the header file.
"""
if not filename_cc.endswith('.cc'):
return (False, '')
filename_cc = filename_cc[:-len('.cc')]
if filename_cc.endswith('_unittest'):
filename_cc = filename_cc[:-len('_unittest')]
elif filename_cc.endswith('_test'):
filename_cc = filename_cc[:-len('_test')]
filename_cc = filename_cc.replace('/public/', '/')
filename_cc = filename_cc.replace('/internal/', '/')
if not filename_h.endswith('.h'):
return (False, '')
filename_h = filename_h[:-len('.h')]
if filename_h.endswith('-inl'):
filename_h = filename_h[:-len('-inl')]
filename_h = filename_h.replace('/public/', '/')
filename_h = filename_h.replace('/internal/', '/')
files_belong_to_same_module = filename_cc.endswith(filename_h)
common_path = ''
if files_belong_to_same_module:
common_path = filename_cc[:-len(filename_h)]
return files_belong_to_same_module, common_path | [
"def",
"FilesBelongToSameModule",
"(",
"filename_cc",
",",
"filename_h",
")",
":",
"if",
"not",
"filename_cc",
".",
"endswith",
"(",
"'.cc'",
")",
":",
"return",
"(",
"False",
",",
"''",
")",
"filename_cc",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
... | https://github.com/syoyo/tinygltf/blob/e7f1ff5c59d3ca2489923beb239bdf93d863498f/deps/cpplint.py#L5522-L5574 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | Grid.GetDefaultRowLabelSize | (*args, **kwargs) | return _grid.Grid_GetDefaultRowLabelSize(*args, **kwargs) | GetDefaultRowLabelSize(self) -> int | GetDefaultRowLabelSize(self) -> int | [
"GetDefaultRowLabelSize",
"(",
"self",
")",
"-",
">",
"int"
] | def GetDefaultRowLabelSize(*args, **kwargs):
"""GetDefaultRowLabelSize(self) -> int"""
return _grid.Grid_GetDefaultRowLabelSize(*args, **kwargs) | [
"def",
"GetDefaultRowLabelSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_GetDefaultRowLabelSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L1470-L1472 | |
msftguy/ssh-rd | a5f3a79daeac5844edebf01916c9613563f1c390 | _3rd/boost_1_48_0/tools/build/v2/build/targets.py | python | BasicTarget.generate | (self, ps) | return self.generated_[ps] | Determines final build properties, generates sources,
and calls 'construct'. This method should not be
overridden. | Determines final build properties, generates sources,
and calls 'construct'. This method should not be
overridden. | [
"Determines",
"final",
"build",
"properties",
"generates",
"sources",
"and",
"calls",
"construct",
".",
"This",
"method",
"should",
"not",
"be",
"overridden",
"."
] | def generate (self, ps):
""" Determines final build properties, generates sources,
and calls 'construct'. This method should not be
overridden.
"""
self.manager_.errors().push_user_context(
"Generating target " + self.full_name(), self.user_context_)
if self.manager().targets().logging():
self.manager().targets().log(
"Building target '%s'" % self.name_)
self.manager().targets().increase_indent ()
self.manager().targets().log(
"Build request: '%s'" % str (ps.raw ()))
cf = self.manager().command_line_free_features()
self.manager().targets().log(
"Command line free features: '%s'" % str (cf.raw ()))
self.manager().targets().log(
"Target requirements: %s'" % str (self.requirements().raw ()))
self.manager().targets().push_target(self)
if not self.generated_.has_key(ps):
# Apply free features form the command line. If user
# said
# define=FOO
# he most likely want this define to be set for all compiles.
ps = ps.refine(self.manager().command_line_free_features())
rproperties = self.common_properties (ps, self.requirements_)
self.manager().targets().log(
"Common properties are '%s'" % str (rproperties))
if rproperties.get("<build>") != ["no"]:
result = GenerateResult ()
properties = rproperties.non_dependency ()
(p, u) = self.generate_dependency_properties (rproperties.dependency (), rproperties)
properties += p
assert all(isinstance(p, property.Property) for p in properties)
usage_requirements = u
(source_targets, u) = self.generate_dependency_targets (self.sources_, rproperties)
usage_requirements += u
self.manager_.targets().log(
"Usage requirements for '%s' are '%s'" % (self.name_, usage_requirements))
# FIXME:
rproperties = property_set.create(properties + usage_requirements)
usage_requirements = property_set.create (usage_requirements)
self.manager_.targets().log(
"Build properties: '%s'" % str(rproperties))
source_targets += rproperties.get('<source>')
# We might get duplicate sources, for example if
# we link to two library which have the same <library> in
# usage requirements.
# Use stable sort, since for some targets the order is
# important. E.g. RUN_PY target need python source to come
# first.
source_targets = unique(source_targets, stable=True)
# FIXME: figure why this call messes up source_targets in-place
result = self.construct (self.name_, source_targets[:], rproperties)
if result:
assert len(result) == 2
gur = result [0]
result = result [1]
if self.always_:
for t in result:
t.always()
s = self.create_subvariant (
result,
self.manager().virtual_targets().recent_targets(), ps,
source_targets, rproperties, usage_requirements)
self.manager().virtual_targets().clear_recent_targets()
ur = self.compute_usage_requirements (s)
ur = ur.add (gur)
s.set_usage_requirements (ur)
self.manager_.targets().log (
"Usage requirements from '%s' are '%s'" %
(self.name(), str(rproperties)))
self.generated_[ps] = GenerateResult (ur, result)
else:
self.generated_[ps] = GenerateResult (property_set.empty(), [])
else:
# If we just see <build>no, we cannot produce any reasonable
# diagnostics. The code that adds this property is expected
# to explain why a target is not built, for example using
# the configure.log-component-configuration function.
# If this target fails to build, add <build>no to properties
# to cause any parent target to fail to build. Except that it
# - does not work now, since we check for <build>no only in
# common properties, but not in properties that came from
# dependencies
# - it's not clear if that's a good idea anyway. The alias
# target, for example, should not fail to build if a dependency
# fails.
self.generated_[ps] = GenerateResult(
property_set.create(["<build>no"]), [])
else:
self.manager().targets().log ("Already built")
self.manager().targets().pop_target()
self.manager().targets().decrease_indent()
return self.generated_[ps] | [
"def",
"generate",
"(",
"self",
",",
"ps",
")",
":",
"self",
".",
"manager_",
".",
"errors",
"(",
")",
".",
"push_user_context",
"(",
"\"Generating target \"",
"+",
"self",
".",
"full_name",
"(",
")",
",",
"self",
".",
"user_context_",
")",
"if",
"self",... | https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/targets.py#L1086-L1206 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | DC.SetFont | (*args, **kwargs) | return _gdi_.DC_SetFont(*args, **kwargs) | SetFont(self, Font font)
Sets the current font for the DC. It must be a valid font, in
particular you should not pass ``wx.NullFont`` to this method. | SetFont(self, Font font) | [
"SetFont",
"(",
"self",
"Font",
"font",
")"
] | def SetFont(*args, **kwargs):
"""
SetFont(self, Font font)
Sets the current font for the DC. It must be a valid font, in
particular you should not pass ``wx.NullFont`` to this method.
"""
return _gdi_.DC_SetFont(*args, **kwargs) | [
"def",
"SetFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_SetFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L4103-L4110 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/learn/python/learn/estimators/_sklearn.py | python | _BaseEstimator.set_params | (self, **params) | return self | Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as pipelines). The former have parameters of the form
``<component>__<parameter>`` so that it's possible to update each
component of a nested object.
Args:
**params: Parameters.
Returns:
self
Raises:
ValueError: If params contain invalid names. | Set the parameters of this estimator. | [
"Set",
"the",
"parameters",
"of",
"this",
"estimator",
"."
] | def set_params(self, **params):
"""Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as pipelines). The former have parameters of the form
``<component>__<parameter>`` so that it's possible to update each
component of a nested object.
Args:
**params: Parameters.
Returns:
self
Raises:
ValueError: If params contain invalid names.
"""
if not params:
# Simple optimisation to gain speed (inspect is slow)
return self
valid_params = self.get_params(deep=True)
for key, value in six.iteritems(params):
split = key.split('__', 1)
if len(split) > 1:
# nested objects case
name, sub_name = split
if name not in valid_params:
raise ValueError('Invalid parameter %s for estimator %s. '
'Check the list of available parameters '
'with `estimator.get_params().keys()`.' %
(name, self))
sub_object = valid_params[name]
sub_object.set_params(**{sub_name: value})
else:
# simple objects case
if key not in valid_params:
raise ValueError('Invalid parameter %s for estimator %s. '
'Check the list of available parameters '
'with `estimator.get_params().keys()`.' %
(key, self.__class__.__name__))
setattr(self, key, value)
return self | [
"def",
"set_params",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"if",
"not",
"params",
":",
"# Simple optimisation to gain speed (inspect is slow)",
"return",
"self",
"valid_params",
"=",
"self",
".",
"get_params",
"(",
"deep",
"=",
"True",
")",
"for",
"k... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/estimators/_sklearn.py#L68-L109 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/tooltip.py | python | OnHoverTooltipBase.__init__ | (self, anchor_widget, hover_delay=1000) | Create a tooltip with a mouse hover delay.
anchor_widget: the widget next to which the tooltip will be shown
hover_delay: time to delay before showing the tooltip, in milliseconds
Note that a widget will only be shown when showtip() is called,
e.g. after hovering over the anchor widget with the mouse for enough
time. | Create a tooltip with a mouse hover delay. | [
"Create",
"a",
"tooltip",
"with",
"a",
"mouse",
"hover",
"delay",
"."
] | def __init__(self, anchor_widget, hover_delay=1000):
"""Create a tooltip with a mouse hover delay.
anchor_widget: the widget next to which the tooltip will be shown
hover_delay: time to delay before showing the tooltip, in milliseconds
Note that a widget will only be shown when showtip() is called,
e.g. after hovering over the anchor widget with the mouse for enough
time.
"""
super(OnHoverTooltipBase, self).__init__(anchor_widget)
self.hover_delay = hover_delay
self._after_id = None
self._id1 = self.anchor_widget.bind("<Enter>", self._show_event)
self._id2 = self.anchor_widget.bind("<Leave>", self._hide_event)
self._id3 = self.anchor_widget.bind("<Button>", self._hide_event) | [
"def",
"__init__",
"(",
"self",
",",
"anchor_widget",
",",
"hover_delay",
"=",
"1000",
")",
":",
"super",
"(",
"OnHoverTooltipBase",
",",
"self",
")",
".",
"__init__",
"(",
"anchor_widget",
")",
"self",
".",
"hover_delay",
"=",
"hover_delay",
"self",
".",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/tooltip.py#L85-L101 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/BaseHTTPServer.py | python | BaseHTTPRequestHandler.handle | (self) | Handle multiple requests if necessary. | Handle multiple requests if necessary. | [
"Handle",
"multiple",
"requests",
"if",
"necessary",
"."
] | def handle(self):
"""Handle multiple requests if necessary."""
self.close_connection = 1
self.handle_one_request()
while not self.close_connection:
self.handle_one_request() | [
"def",
"handle",
"(",
"self",
")",
":",
"self",
".",
"close_connection",
"=",
"1",
"self",
".",
"handle_one_request",
"(",
")",
"while",
"not",
"self",
".",
"close_connection",
":",
"self",
".",
"handle_one_request",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/BaseHTTPServer.py#L336-L342 | ||
jubatus/jubatus | 1251ce551bac980488a6313728e72b3fe0b79a9f | tools/codestyle/cpplint/cpplint.py | python | _IncludeState.CheckNextIncludeOrder | (self, header_type) | return '' | Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong. | Returns a non-empty error message if the next header is out of order. | [
"Returns",
"a",
"non",
"-",
"empty",
"error",
"message",
"if",
"the",
"next",
"header",
"is",
"out",
"of",
"order",
"."
] | def CheckNextIncludeOrder(self, header_type):
"""Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong.
"""
error_message = ('Found %s after %s' %
(self._TYPE_NAMES[header_type],
self._SECTION_NAMES[self._section]))
last_section = self._section
if header_type == _C_SYS_HEADER:
if self._section <= self._C_SECTION:
self._section = self._C_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _CPP_SYS_HEADER:
if self._section <= self._CPP_SECTION:
self._section = self._CPP_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _THIRD_PARTY_SYS_HEADER:
if self._section <= self._THIRD_PARTY_SECTION:
self._section = self._THIRD_PARTY_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _LIKELY_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
self._section = self._OTHER_H_SECTION
elif header_type == _POSSIBLE_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
# This will always be the fallback because we're not sure
# enough that the header is associated with this file.
self._section = self._OTHER_H_SECTION
else:
assert header_type == _OTHER_HEADER
self._section = self._OTHER_H_SECTION
if last_section != self._section:
self._last_header = ''
return '' | [
"def",
"CheckNextIncludeOrder",
"(",
"self",
",",
"header_type",
")",
":",
"error_message",
"=",
"(",
"'Found %s after %s'",
"%",
"(",
"self",
".",
"_TYPE_NAMES",
"[",
"header_type",
"]",
",",
"self",
".",
"_SECTION_NAMES",
"[",
"self",
".",
"_section",
"]",
... | https://github.com/jubatus/jubatus/blob/1251ce551bac980488a6313728e72b3fe0b79a9f/tools/codestyle/cpplint/cpplint.py#L446-L503 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/applications/workbench/workbench/projectrecovery/recoverygui/projectrecoverymodel.py | python | ProjectRecoveryModel.recover_selected_checkpoint | (self, selected) | Recover the passed checkpoint
:param selected: String; Checkpoint name to be recovered | Recover the passed checkpoint
:param selected: String; Checkpoint name to be recovered | [
"Recover",
"the",
"passed",
"checkpoint",
":",
"param",
"selected",
":",
"String",
";",
"Checkpoint",
"name",
"to",
"be",
"recovered"
] | def recover_selected_checkpoint(self, selected):
"""
Recover the passed checkpoint
:param selected: String; Checkpoint name to be recovered
"""
# If this is a valid file then it should only be the checkpoint here
if os.path.exists(selected):
selected = os.path.basename(selected)
self.is_recovery_running = True
self.presenter.change_start_mantid_to_cancel_label()
ADS.clear()
# Recover given the checkpoint selected
pid_dir = self.project_recovery.get_pid_folder_to_load_a_checkpoint_from()
selected = selected.replace(" ", "T")
checkpoint = os.path.join(pid_dir, selected)
self.selected_checkpoint = selected
try:
self._start_recovery_of_checkpoint(checkpoint)
except Exception as e:
# Fail "Silently" by setting failed run to true, setting checkpoint to tried and closing the view.
logger.debug("Project Recovery: " + str(e))
self.has_failed_run = True
self._update_checkpoint_tried(selected)
self.presenter.close_view() | [
"def",
"recover_selected_checkpoint",
"(",
"self",
",",
"selected",
")",
":",
"# If this is a valid file then it should only be the checkpoint here",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"selected",
")",
":",
"selected",
"=",
"os",
".",
"path",
".",
"basenam... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/applications/workbench/workbench/projectrecovery/recoverygui/projectrecoverymodel.py#L77-L104 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/variables.py | python | global_variables_initializer | () | return variables_initializer(global_variables()) | Returns an Op that initializes global variables.
This is just a shortcut for `variables_initializer(global_variables())`
@compatibility(TF2)
In TF2, variables are initialized immediately when they are created. There is
no longer a need to run variable initializers before using them.
@end_compatibility
Returns:
An Op that initializes global variables in the graph. | Returns an Op that initializes global variables. | [
"Returns",
"an",
"Op",
"that",
"initializes",
"global",
"variables",
"."
] | def global_variables_initializer():
"""Returns an Op that initializes global variables.
This is just a shortcut for `variables_initializer(global_variables())`
@compatibility(TF2)
In TF2, variables are initialized immediately when they are created. There is
no longer a need to run variable initializers before using them.
@end_compatibility
Returns:
An Op that initializes global variables in the graph.
"""
if context.executing_eagerly():
return control_flow_ops.no_op(name="global_variables_initializer")
return variables_initializer(global_variables()) | [
"def",
"global_variables_initializer",
"(",
")",
":",
"if",
"context",
".",
"executing_eagerly",
"(",
")",
":",
"return",
"control_flow_ops",
".",
"no_op",
"(",
"name",
"=",
"\"global_variables_initializer\"",
")",
"return",
"variables_initializer",
"(",
"global_varia... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/variables.py#L3300-L3315 | |
hughperkins/Jinja2CppLight | 04196b080adf6edb86184824a1cf948ace310d19 | thirdparty/cogapp/cogapp/cogapp.py | python | Cog.processFile | (self, fIn, fOut, fname=None, globals=None) | Process an input file object to an output file object.
fIn and fOut can be file objects, or file names. | Process an input file object to an output file object.
fIn and fOut can be file objects, or file names. | [
"Process",
"an",
"input",
"file",
"object",
"to",
"an",
"output",
"file",
"object",
".",
"fIn",
"and",
"fOut",
"can",
"be",
"file",
"objects",
"or",
"file",
"names",
"."
] | def processFile(self, fIn, fOut, fname=None, globals=None):
""" Process an input file object to an output file object.
fIn and fOut can be file objects, or file names.
"""
sFileIn = fname or ''
sFileOut = fname or ''
fInToClose = fOutToClose = None
# Convert filenames to files.
if isinstance(fIn, string_types):
# Open the input file.
sFileIn = fIn
fIn = fInToClose = self.openInputFile(fIn)
if isinstance(fOut, string_types):
# Open the output file.
sFileOut = fOut
fOut = fOutToClose = self.openOutputFile(fOut)
try:
fIn = NumberedFileReader(fIn)
bSawCog = False
self.cogmodule.inFile = sFileIn
self.cogmodule.outFile = sFileOut
# The globals dict we'll use for this file.
if globals is None:
globals = {}
# If there are any global defines, put them in the globals.
globals.update(self.options.defines)
# loop over generator chunks
l = fIn.readline()
while l:
# Find the next spec begin
while l and not self.isBeginSpecLine(l):
if self.isEndSpecLine(l):
raise CogError("Unexpected '%s'" % self.options.sEndSpec,
file=sFileIn, line=fIn.linenumber())
if self.isEndOutputLine(l):
raise CogError("Unexpected '%s'" % self.options.sEndOutput,
file=sFileIn, line=fIn.linenumber())
fOut.write(l)
l = fIn.readline()
if not l:
break
if not self.options.bDeleteCode:
fOut.write(l)
# l is the begin spec
gen = CogGenerator()
gen.setOutput(stdout=self.stdout)
gen.parseMarker(l)
firstLineNum = fIn.linenumber()
self.cogmodule.firstLineNum = firstLineNum
# If the spec begin is also a spec end, then process the single
# line of code inside.
if self.isEndSpecLine(l):
beg = l.find(self.options.sBeginSpec)
end = l.find(self.options.sEndSpec)
if beg > end:
raise CogError("Cog code markers inverted",
file=sFileIn, line=firstLineNum)
else:
sCode = l[beg+len(self.options.sBeginSpec):end].strip()
gen.parseLine(sCode)
else:
# Deal with an ordinary code block.
l = fIn.readline()
# Get all the lines in the spec
while l and not self.isEndSpecLine(l):
if self.isBeginSpecLine(l):
raise CogError("Unexpected '%s'" % self.options.sBeginSpec,
file=sFileIn, line=fIn.linenumber())
if self.isEndOutputLine(l):
raise CogError("Unexpected '%s'" % self.options.sEndOutput,
file=sFileIn, line=fIn.linenumber())
if not self.options.bDeleteCode:
fOut.write(l)
gen.parseLine(l)
l = fIn.readline()
if not l:
raise CogError(
"Cog block begun but never ended.",
file=sFileIn, line=firstLineNum)
if not self.options.bDeleteCode:
fOut.write(l)
gen.parseMarker(l)
l = fIn.readline()
# Eat all the lines in the output section. While reading past
# them, compute the md5 hash of the old output.
previous = ""
hasher = hashlib.md5()
while l and not self.isEndOutputLine(l):
if self.isBeginSpecLine(l):
raise CogError("Unexpected '%s'" % self.options.sBeginSpec,
file=sFileIn, line=fIn.linenumber())
if self.isEndSpecLine(l):
raise CogError("Unexpected '%s'" % self.options.sEndSpec,
file=sFileIn, line=fIn.linenumber())
previous += l
hasher.update(to_bytes(l))
l = fIn.readline()
curHash = hasher.hexdigest()
if not l and not self.options.bEofCanBeEnd:
# We reached end of file before we found the end output line.
raise CogError("Missing '%s' before end of file." % self.options.sEndOutput,
file=sFileIn, line=fIn.linenumber())
# Make the previous output available to the current code
self.cogmodule.previous = previous
# Write the output of the spec to be the new output if we're
# supposed to generate code.
hasher = hashlib.md5()
if not self.options.bNoGenerate:
sFile = "%s+%d" % (sFileIn, firstLineNum)
sGen = gen.evaluate(cog=self, globals=globals, fname=sFile)
sGen = self.suffixLines(sGen)
hasher.update(to_bytes(sGen))
fOut.write(sGen)
newHash = hasher.hexdigest()
bSawCog = True
# Write the ending output line
hashMatch = self.reEndOutput.search(l)
if self.options.bHashOutput:
if hashMatch:
oldHash = hashMatch.groupdict()['hash']
if oldHash != curHash:
raise CogError("Output has been edited! Delete old checksum to unprotect.",
file=sFileIn, line=fIn.linenumber())
# Create a new end line with the correct hash.
endpieces = l.split(hashMatch.group(0), 1)
else:
# There was no old hash, but we want a new hash.
endpieces = l.split(self.options.sEndOutput, 1)
l = (self.sEndFormat % newHash).join(endpieces)
else:
# We don't want hashes output, so if there was one, get rid of
# it.
if hashMatch:
l = l.replace(hashMatch.groupdict()['hashsect'], '', 1)
if not self.options.bDeleteCode:
fOut.write(l)
l = fIn.readline()
if not bSawCog and self.options.bWarnEmpty:
self.showWarning("no cog code found in %s" % sFileIn)
finally:
if fInToClose:
fInToClose.close()
if fOutToClose:
fOutToClose.close() | [
"def",
"processFile",
"(",
"self",
",",
"fIn",
",",
"fOut",
",",
"fname",
"=",
"None",
",",
"globals",
"=",
"None",
")",
":",
"sFileIn",
"=",
"fname",
"or",
"''",
"sFileOut",
"=",
"fname",
"or",
"''",
"fInToClose",
"=",
"fOutToClose",
"=",
"None",
"#... | https://github.com/hughperkins/Jinja2CppLight/blob/04196b080adf6edb86184824a1cf948ace310d19/thirdparty/cogapp/cogapp/cogapp.py#L370-L533 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/datamodel/models.py | python | StructModel.get | (self, builder, val, pos) | return builder.extract_value(val, [pos],
name="extracted." + self._fields[pos]) | Get a field at the given position or the fieldname
Args
----
builder:
LLVM IRBuilder
val:
value to be inserted
pos: int or str
field index or field name
Returns
-------
Extracted value | Get a field at the given position or the fieldname | [
"Get",
"a",
"field",
"at",
"the",
"given",
"position",
"or",
"the",
"fieldname"
] | def get(self, builder, val, pos):
"""Get a field at the given position or the fieldname
Args
----
builder:
LLVM IRBuilder
val:
value to be inserted
pos: int or str
field index or field name
Returns
-------
Extracted value
"""
if isinstance(pos, str):
pos = self.get_field_position(pos)
return builder.extract_value(val, [pos],
name="extracted." + self._fields[pos]) | [
"def",
"get",
"(",
"self",
",",
"builder",
",",
"val",
",",
"pos",
")",
":",
"if",
"isinstance",
"(",
"pos",
",",
"str",
")",
":",
"pos",
"=",
"self",
".",
"get_field_position",
"(",
"pos",
")",
"return",
"builder",
".",
"extract_value",
"(",
"val",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/datamodel/models.py#L615-L634 | |
priyankchheda/algorithms | c361aa9071573fa9966d5b02d05e524815abcf2b | linked_list/library/linked_list.py | python | LinkedList.__init__ | (self) | initializing singly linked list with zero node | initializing singly linked list with zero node | [
"initializing",
"singly",
"linked",
"list",
"with",
"zero",
"node"
] | def __init__(self):
""" initializing singly linked list with zero node """
self.head = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"head",
"=",
"None"
] | https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/linked_list/library/linked_list.py#L42-L44 | ||
google/or-tools | 2cb85b4eead4c38e1c54b48044f92087cf165bce | examples/contrib/magic_sequence_sat.py | python | main | () | Magic sequence problem. | Magic sequence problem. | [
"Magic",
"sequence",
"problem",
"."
] | def main():
"""Magic sequence problem."""
n = 100
values = range(n)
model = cp_model.CpModel()
x = [model.NewIntVar(0, n, 'x%i' % i) for i in values]
for k in values:
tmp_array = []
for i in values:
tmp_var = model.NewBoolVar('')
model.Add(x[i] == k).OnlyEnforceIf(tmp_var)
model.Add(x[i] != k).OnlyEnforceIf(tmp_var.Not())
tmp_array.append(tmp_var)
model.Add(sum(tmp_array) == x[k])
# Redundant constraint.
model.Add(sum(x) == n)
solver = cp_model.CpSolver()
# No solution printer, this problem has only 1 solution.
solver.parameters.log_search_progress = True
solver.Solve(model)
print(solver.ResponseStats())
for k in values:
print('x[%i] = %i ' % (k, solver.Value(x[k])), end='')
print() | [
"def",
"main",
"(",
")",
":",
"n",
"=",
"100",
"values",
"=",
"range",
"(",
"n",
")",
"model",
"=",
"cp_model",
".",
"CpModel",
"(",
")",
"x",
"=",
"[",
"model",
".",
"NewIntVar",
"(",
"0",
",",
"n",
",",
"'x%i'",
"%",
"i",
")",
"for",
"i",
... | https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/examples/contrib/magic_sequence_sat.py#L19-L47 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/nodes.py | python | Element.replace_attr | (self, attr, value, force = True) | If self[attr] does not exist or force is True or omitted, set
self[attr] to value, otherwise do nothing. | If self[attr] does not exist or force is True or omitted, set
self[attr] to value, otherwise do nothing. | [
"If",
"self",
"[",
"attr",
"]",
"does",
"not",
"exist",
"or",
"force",
"is",
"True",
"or",
"omitted",
"set",
"self",
"[",
"attr",
"]",
"to",
"value",
"otherwise",
"do",
"nothing",
"."
] | def replace_attr(self, attr, value, force = True):
"""
If self[attr] does not exist or force is True or omitted, set
self[attr] to value, otherwise do nothing.
"""
# One or the other
if force or self.get(attr) is None:
self[attr] = value | [
"def",
"replace_attr",
"(",
"self",
",",
"attr",
",",
"value",
",",
"force",
"=",
"True",
")",
":",
"# One or the other",
"if",
"force",
"or",
"self",
".",
"get",
"(",
"attr",
")",
"is",
"None",
":",
"self",
"[",
"attr",
"]",
"=",
"value"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/nodes.py#L735-L742 | ||
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/plasma/Plasma.py | python | PtGetNPCByID | (npcID) | This will return the NPC with a specific ID | This will return the NPC with a specific ID | [
"This",
"will",
"return",
"the",
"NPC",
"with",
"a",
"specific",
"ID"
] | def PtGetNPCByID(npcID):
"""This will return the NPC with a specific ID"""
pass | [
"def",
"PtGetNPCByID",
"(",
"npcID",
")",
":",
"pass"
] | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/plasma/Plasma.py#L491-L493 | ||
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/generators.py | python | viable_source_types | (target_type) | return __viable_source_types_cache [target_type] | Helper rule, caches the result of '__viable_source_types_real'. | Helper rule, caches the result of '__viable_source_types_real'. | [
"Helper",
"rule",
"caches",
"the",
"result",
"of",
"__viable_source_types_real",
"."
] | def viable_source_types (target_type):
""" Helper rule, caches the result of '__viable_source_types_real'.
"""
assert isinstance(target_type, basestring)
if target_type not in __viable_source_types_cache:
__vst_cached_types.append(target_type)
__viable_source_types_cache [target_type] = __viable_source_types_real (target_type)
return __viable_source_types_cache [target_type] | [
"def",
"viable_source_types",
"(",
"target_type",
")",
":",
"assert",
"isinstance",
"(",
"target_type",
",",
"basestring",
")",
"if",
"target_type",
"not",
"in",
"__viable_source_types_cache",
":",
"__vst_cached_types",
".",
"append",
"(",
"target_type",
")",
"__via... | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/generators.py#L823-L830 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | uCSIsCatLl | (code) | return ret | Check whether the character is part of Ll UCS Category | Check whether the character is part of Ll UCS Category | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"Ll",
"UCS",
"Category"
] | def uCSIsCatLl(code):
"""Check whether the character is part of Ll UCS Category """
ret = libxml2mod.xmlUCSIsCatLl(code)
return ret | [
"def",
"uCSIsCatLl",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsCatLl",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L2274-L2277 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/lin_ops/lin_utils.py | python | hstack | (operators, shape: Tuple[int, ...]) | return lo.LinOp(lo.HSTACK, shape, operators, None) | Concatenates operators horizontally.
Parameters
----------
operator : list
The operators to stack.
shape : tuple
The (rows, cols) of the stacked operators.
Returns
-------
LinOp
LinOp representing the stacked expression. | Concatenates operators horizontally. | [
"Concatenates",
"operators",
"horizontally",
"."
] | def hstack(operators, shape: Tuple[int, ...]):
"""Concatenates operators horizontally.
Parameters
----------
operator : list
The operators to stack.
shape : tuple
The (rows, cols) of the stacked operators.
Returns
-------
LinOp
LinOp representing the stacked expression.
"""
return lo.LinOp(lo.HSTACK, shape, operators, None) | [
"def",
"hstack",
"(",
"operators",
",",
"shape",
":",
"Tuple",
"[",
"int",
",",
"...",
"]",
")",
":",
"return",
"lo",
".",
"LinOp",
"(",
"lo",
".",
"HSTACK",
",",
"shape",
",",
"operators",
",",
"None",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/lin_ops/lin_utils.py#L521-L536 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/signal/waveforms.py | python | _chirp_phase | (t, f0, t1, f1, method='linear', vertex_zero=True) | return phase | Calculate the phase used by chirp_phase to generate its output.
See `chirp_phase` for a description of the arguments. | Calculate the phase used by chirp_phase to generate its output. | [
"Calculate",
"the",
"phase",
"used",
"by",
"chirp_phase",
"to",
"generate",
"its",
"output",
"."
] | def _chirp_phase(t, f0, t1, f1, method='linear', vertex_zero=True):
"""
Calculate the phase used by chirp_phase to generate its output.
See `chirp_phase` for a description of the arguments.
"""
t = asarray(t)
f0 = float(f0)
t1 = float(t1)
f1 = float(f1)
if method in ['linear', 'lin', 'li']:
beta = (f1 - f0) / t1
phase = 2 * pi * (f0 * t + 0.5 * beta * t * t)
elif method in ['quadratic', 'quad', 'q']:
beta = (f1 - f0) / (t1 ** 2)
if vertex_zero:
phase = 2 * pi * (f0 * t + beta * t ** 3 / 3)
else:
phase = 2 * pi * (f1 * t + beta * ((t1 - t) ** 3 - t1 ** 3) / 3)
elif method in ['logarithmic', 'log', 'lo']:
if f0 * f1 <= 0.0:
raise ValueError("For a logarithmic chirp, f0 and f1 must be "
"nonzero and have the same sign.")
if f0 == f1:
phase = 2 * pi * f0 * t
else:
beta = t1 / log(f1 / f0)
phase = 2 * pi * beta * f0 * (pow(f1 / f0, t / t1) - 1.0)
elif method in ['hyperbolic', 'hyp']:
if f0 == 0 or f1 == 0:
raise ValueError("For a hyperbolic chirp, f0 and f1 must be "
"nonzero.")
if f0 == f1:
# Degenerate case: constant frequency.
phase = 2 * pi * f0 * t
else:
# Singular point: the instantaneous frequency blows up
# when t == sing.
sing = -f1 * t1 / (f0 - f1)
phase = 2 * pi * (-sing * f0) * log(np.abs(1 - t/sing))
else:
raise ValueError("method must be 'linear', 'quadratic', 'logarithmic',"
" or 'hyperbolic', but a value of %r was given."
% method)
return phase | [
"def",
"_chirp_phase",
"(",
"t",
",",
"f0",
",",
"t1",
",",
"f1",
",",
"method",
"=",
"'linear'",
",",
"vertex_zero",
"=",
"True",
")",
":",
"t",
"=",
"asarray",
"(",
"t",
")",
"f0",
"=",
"float",
"(",
"f0",
")",
"t1",
"=",
"float",
"(",
"t1",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/signal/waveforms.py#L349-L399 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/externals/joblib/format_stack.py | python | format_exc | (etype, evalue, etb, context=5, tb_offset=0) | return '%s\n%s\n%s' % (head, '\n'.join(frames), ''.join(exception[0])) | Return a nice text document describing the traceback.
Parameters
-----------
etype, evalue, etb: as returned by sys.exc_info
context: number of lines of the source file to plot
tb_offset: the number of stack frame not to use (0 = use all) | Return a nice text document describing the traceback. | [
"Return",
"a",
"nice",
"text",
"document",
"describing",
"the",
"traceback",
"."
] | def format_exc(etype, evalue, etb, context=5, tb_offset=0):
""" Return a nice text document describing the traceback.
Parameters
-----------
etype, evalue, etb: as returned by sys.exc_info
context: number of lines of the source file to plot
tb_offset: the number of stack frame not to use (0 = use all)
"""
# some locals
try:
etype = etype.__name__
except AttributeError:
pass
# Header with the exception type, python version, and date
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
date = time.ctime(time.time())
pid = 'PID: %i' % os.getpid()
head = '%s%s%s\n%s%s%s' % (
etype, ' ' * (75 - len(str(etype)) - len(date)),
date, pid, ' ' * (75 - len(str(pid)) - len(pyver)),
pyver)
# Drop topmost frames if requested
try:
records = _fixed_getframes(etb, context, tb_offset)
except:
raise
print('\nUnfortunately, your original traceback can not be '
'constructed.\n')
return ''
# Get (safely) a string form of the exception info
try:
etype_str, evalue_str = map(str, (etype, evalue))
except:
# User exception is improperly defined.
etype, evalue = str, sys.exc_info()[:2]
etype_str, evalue_str = map(str, (etype, evalue))
# ... and format it
exception = ['%s: %s' % (etype_str, evalue_str)]
frames = format_records(records)
return '%s\n%s\n%s' % (head, '\n'.join(frames), ''.join(exception[0])) | [
"def",
"format_exc",
"(",
"etype",
",",
"evalue",
",",
"etb",
",",
"context",
"=",
"5",
",",
"tb_offset",
"=",
"0",
")",
":",
"# some locals",
"try",
":",
"etype",
"=",
"etype",
".",
"__name__",
"except",
"AttributeError",
":",
"pass",
"# Header with the e... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/externals/joblib/format_stack.py#L331-L376 | |
fifengine/fifengine | 4b62c42e85bec19893cef8e63e6855927cff2c47 | engine/python/fife/extensions/serializers/xml_loader_tools.py | python | frange | (limit1, limit2 = None, increment = 1.) | return (limit1 + n*increment for n in range(count)) | Range function that accepts floats (and integers).
If only one limit is specified, assumes 0 as lower limit.
Usage:
frange(-2, 2, 0.1)
frange(10)
frange(10, increment = 0.5)
The returned value is an iterator. Use list(frange) for a list.
source: U{http://code.activestate.com/recipes/
66472-frange-a-range-function-with-float-increments/}
@type limit1: float
@param limit1: lower range limit
@type limit2: float
@param limit2: upper range limit
@type increment: float
@param increment: length of each step
@rtype generator
@return iterable over (limit2 - limit1) / increment steps | Range function that accepts floats (and integers).
If only one limit is specified, assumes 0 as lower limit. | [
"Range",
"function",
"that",
"accepts",
"floats",
"(",
"and",
"integers",
")",
".",
"If",
"only",
"one",
"limit",
"is",
"specified",
"assumes",
"0",
"as",
"lower",
"limit",
"."
] | def frange(limit1, limit2 = None, increment = 1.):
"""Range function that accepts floats (and integers).
If only one limit is specified, assumes 0 as lower limit.
Usage:
frange(-2, 2, 0.1)
frange(10)
frange(10, increment = 0.5)
The returned value is an iterator. Use list(frange) for a list.
source: U{http://code.activestate.com/recipes/
66472-frange-a-range-function-with-float-increments/}
@type limit1: float
@param limit1: lower range limit
@type limit2: float
@param limit2: upper range limit
@type increment: float
@param increment: length of each step
@rtype generator
@return iterable over (limit2 - limit1) / increment steps
"""
if limit2 is None:
limit2, limit1 = float(limit1), 0.
else:
limit1 = float(limit1)
count = int(math.ceil(old_div((limit2 - limit1),increment)))
return (limit1 + n*increment for n in range(count)) | [
"def",
"frange",
"(",
"limit1",
",",
"limit2",
"=",
"None",
",",
"increment",
"=",
"1.",
")",
":",
"if",
"limit2",
"is",
"None",
":",
"limit2",
",",
"limit1",
"=",
"float",
"(",
"limit1",
")",
",",
"0.",
"else",
":",
"limit1",
"=",
"float",
"(",
... | https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/serializers/xml_loader_tools.py#L125-L155 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | build/automationutils.py | python | ZipFileReader._getnormalizedpath | (self, path) | return path | Gets a normalized path from 'path' (or the current working directory if
'path' is None). Also asserts that the path exists. | Gets a normalized path from 'path' (or the current working directory if
'path' is None). Also asserts that the path exists. | [
"Gets",
"a",
"normalized",
"path",
"from",
"path",
"(",
"or",
"the",
"current",
"working",
"directory",
"if",
"path",
"is",
"None",
")",
".",
"Also",
"asserts",
"that",
"the",
"path",
"exists",
"."
] | def _getnormalizedpath(self, path):
"""
Gets a normalized path from 'path' (or the current working directory if
'path' is None). Also asserts that the path exists.
"""
if path is None:
path = os.curdir
path = os.path.normpath(os.path.expanduser(path))
assert os.path.isdir(path)
return path | [
"def",
"_getnormalizedpath",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"curdir",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
")",
... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/build/automationutils.py#L61-L70 | |
senlinuc/caffe_ocr | 81642f61ea8f888e360cca30e08e05b7bc6d4556 | examples/pycaffe/layers/pascal_multilabel_datalayers.py | python | check_params | (params) | A utility function to check the parameters for the data layers. | A utility function to check the parameters for the data layers. | [
"A",
"utility",
"function",
"to",
"check",
"the",
"parameters",
"for",
"the",
"data",
"layers",
"."
] | def check_params(params):
"""
A utility function to check the parameters for the data layers.
"""
assert 'split' in params.keys(
), 'Params must include split (train, val, or test).'
required = ['batch_size', 'pascal_root', 'im_shape']
for r in required:
assert r in params.keys(), 'Params must include {}'.format(r) | [
"def",
"check_params",
"(",
"params",
")",
":",
"assert",
"'split'",
"in",
"params",
".",
"keys",
"(",
")",
",",
"'Params must include split (train, val, or test).'",
"required",
"=",
"[",
"'batch_size'",
",",
"'pascal_root'",
",",
"'im_shape'",
"]",
"for",
"r",
... | https://github.com/senlinuc/caffe_ocr/blob/81642f61ea8f888e360cca30e08e05b7bc6d4556/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L196-L205 | ||
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | cpp/build-support/cpplint.py | python | ParseNolintSuppressions | (filename, raw_line, linenum, error) | Updates the global list of line error-suppressions.
Parses any NOLINT comments on the current line, updating the global
error_suppressions store. Reports an error if the NOLINT comment
was malformed.
Args:
filename: str, the name of the input file.
raw_line: str, the line of input text, with comments.
linenum: int, the number of the current line.
error: function, an error handler. | Updates the global list of line error-suppressions. | [
"Updates",
"the",
"global",
"list",
"of",
"line",
"error",
"-",
"suppressions",
"."
] | def ParseNolintSuppressions(filename, raw_line, linenum, error):
"""Updates the global list of line error-suppressions.
Parses any NOLINT comments on the current line, updating the global
error_suppressions store. Reports an error if the NOLINT comment
was malformed.
Args:
filename: str, the name of the input file.
raw_line: str, the line of input text, with comments.
linenum: int, the number of the current line.
error: function, an error handler.
"""
matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
if matched:
if matched.group(1):
suppressed_line = linenum + 1
else:
suppressed_line = linenum
category = matched.group(2)
if category in (None, '(*)'): # => "suppress all"
_error_suppressions.setdefault(None, set()).add(suppressed_line)
else:
if category.startswith('(') and category.endswith(')'):
category = category[1:-1]
if category in _ERROR_CATEGORIES:
_error_suppressions.setdefault(category, set()).add(suppressed_line)
elif category not in _LEGACY_ERROR_CATEGORIES:
error(filename, linenum, 'readability/nolint', 5,
'Unknown NOLINT error category: %s' % category) | [
"def",
"ParseNolintSuppressions",
"(",
"filename",
",",
"raw_line",
",",
"linenum",
",",
"error",
")",
":",
"matched",
"=",
"Search",
"(",
"r'\\bNOLINT(NEXTLINE)?\\b(\\([^)]+\\))?'",
",",
"raw_line",
")",
"if",
"matched",
":",
"if",
"matched",
".",
"group",
"(",... | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/cpp/build-support/cpplint.py#L683-L712 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/ensemble/_gb.py | python | BaseGradientBoosting._init_state | (self) | Initialize model state and allocate model state data structures. | Initialize model state and allocate model state data structures. | [
"Initialize",
"model",
"state",
"and",
"allocate",
"model",
"state",
"data",
"structures",
"."
] | def _init_state(self):
"""Initialize model state and allocate model state data structures. """
self.init_ = self.init
if self.init_ is None:
self.init_ = self.loss_.init_estimator()
self.estimators_ = np.empty((self.n_estimators, self.loss_.K),
dtype=np.object)
self.train_score_ = np.zeros((self.n_estimators,), dtype=np.float64)
# do oob?
if self.subsample < 1.0:
self.oob_improvement_ = np.zeros((self.n_estimators),
dtype=np.float64) | [
"def",
"_init_state",
"(",
"self",
")",
":",
"self",
".",
"init_",
"=",
"self",
".",
"init",
"if",
"self",
".",
"init_",
"is",
"None",
":",
"self",
".",
"init_",
"=",
"self",
".",
"loss_",
".",
"init_estimator",
"(",
")",
"self",
".",
"estimators_",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/ensemble/_gb.py#L1344-L1357 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py | python | pager | (text) | The first time this is called, determine what kind of pager to use. | The first time this is called, determine what kind of pager to use. | [
"The",
"first",
"time",
"this",
"is",
"called",
"determine",
"what",
"kind",
"of",
"pager",
"to",
"use",
"."
] | def pager(text):
"""The first time this is called, determine what kind of pager to use."""
global pager
pager = getpager()
pager(text) | [
"def",
"pager",
"(",
"text",
")",
":",
"global",
"pager",
"pager",
"=",
"getpager",
"(",
")",
"pager",
"(",
"text",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/pydoc.py#L1314-L1318 | ||
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | hasher-matcher-actioner/hmalib/aws_secrets.py | python | AWSSecrets._update_str_secret | (self, secret_name: str, secret_value: str) | Update secret_value as the value for secret_name only if it exists. | Update secret_value as the value for secret_name only if it exists. | [
"Update",
"secret_value",
"as",
"the",
"value",
"for",
"secret_name",
"only",
"if",
"it",
"exists",
"."
] | def _update_str_secret(self, secret_name: str, secret_value: str):
"""
Update secret_value as the value for secret_name only if it exists.
"""
self.secrets_client.update_secret(
SecretId=secret_name, SecretString=secret_value
) | [
"def",
"_update_str_secret",
"(",
"self",
",",
"secret_name",
":",
"str",
",",
"secret_value",
":",
"str",
")",
":",
"self",
".",
"secrets_client",
".",
"update_secret",
"(",
"SecretId",
"=",
"secret_name",
",",
"SecretString",
"=",
"secret_value",
")"
] | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/hasher-matcher-actioner/hmalib/aws_secrets.py#L94-L100 | ||
luliyucoordinate/Leetcode | 96afcdc54807d1d184e881a075d1dbf3371e31fb | src/0139-Word-Break/0139.py | python | Solution.wordBreak | (self, s, wordDict) | return self._wordBreak(s, set(wordDict), 0, set()) | :type s: str
:type wordDict: List[str]
:rtype: bool | :type s: str
:type wordDict: List[str]
:rtype: bool | [
":",
"type",
"s",
":",
"str",
":",
"type",
"wordDict",
":",
"List",
"[",
"str",
"]",
":",
"rtype",
":",
"bool"
] | def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
return self._wordBreak(s, set(wordDict), 0, set()) | [
"def",
"wordBreak",
"(",
"self",
",",
"s",
",",
"wordDict",
")",
":",
"return",
"self",
".",
"_wordBreak",
"(",
"s",
",",
"set",
"(",
"wordDict",
")",
",",
"0",
",",
"set",
"(",
")",
")"
] | https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0139-Word-Break/0139.py#L2-L8 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/findertools.py | python | shutdown | () | Shut the mac down | Shut the mac down | [
"Shut",
"the",
"mac",
"down"
] | def shutdown():
"""Shut the mac down"""
finder = _getfinder()
finder.shut_down() | [
"def",
"shutdown",
"(",
")",
":",
"finder",
"=",
"_getfinder",
"(",
")",
"finder",
".",
"shut_down",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/findertools.py#L86-L89 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/getopt.py | python | getopt | (args, shortopts, longopts = []) | return opts, args | getopt(args, options[, long_options]) -> opts, args
Parses command line options and parameter list. args is the
argument list to be parsed, without the leading reference to the
running program. Typically, this means "sys.argv[1:]". shortopts
is the string of option letters that the script wants to
recognize, with options that require an argument followed by a
colon (i.e., the same format that Unix getopt() uses). If
specified, longopts is a list of strings with the names of the
long options which should be supported. The leading '--'
characters should not be included in the option name. Options
which require an argument should be followed by an equal sign
('=').
The return value consists of two elements: the first is a list of
(option, value) pairs; the second is the list of program arguments
left after the option list was stripped (this is a trailing slice
of the first argument). Each option-and-value pair returned has
the option as its first element, prefixed with a hyphen (e.g.,
'-x'), and the option argument as its second element, or an empty
string if the option has no argument. The options occur in the
list in the same order in which they were found, thus allowing
multiple occurrences. Long and short options may be mixed. | getopt(args, options[, long_options]) -> opts, args | [
"getopt",
"(",
"args",
"options",
"[",
"long_options",
"]",
")",
"-",
">",
"opts",
"args"
] | def getopt(args, shortopts, longopts = []):
"""getopt(args, options[, long_options]) -> opts, args
Parses command line options and parameter list. args is the
argument list to be parsed, without the leading reference to the
running program. Typically, this means "sys.argv[1:]". shortopts
is the string of option letters that the script wants to
recognize, with options that require an argument followed by a
colon (i.e., the same format that Unix getopt() uses). If
specified, longopts is a list of strings with the names of the
long options which should be supported. The leading '--'
characters should not be included in the option name. Options
which require an argument should be followed by an equal sign
('=').
The return value consists of two elements: the first is a list of
(option, value) pairs; the second is the list of program arguments
left after the option list was stripped (this is a trailing slice
of the first argument). Each option-and-value pair returned has
the option as its first element, prefixed with a hyphen (e.g.,
'-x'), and the option argument as its second element, or an empty
string if the option has no argument. The options occur in the
list in the same order in which they were found, thus allowing
multiple occurrences. Long and short options may be mixed.
"""
opts = []
if type(longopts) == type(""):
longopts = [longopts]
else:
longopts = list(longopts)
while args and args[0].startswith('-') and args[0] != '-':
if args[0] == '--':
args = args[1:]
break
if args[0].startswith('--'):
opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
else:
opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
return opts, args | [
"def",
"getopt",
"(",
"args",
",",
"shortopts",
",",
"longopts",
"=",
"[",
"]",
")",
":",
"opts",
"=",
"[",
"]",
"if",
"type",
"(",
"longopts",
")",
"==",
"type",
"(",
"\"\"",
")",
":",
"longopts",
"=",
"[",
"longopts",
"]",
"else",
":",
"longopt... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/getopt.py#L56-L97 | |
apache/thrift | 0b29261a4f3c6882ef3b09aae47914f0012b0472 | lib/py/src/transport/TTwisted.py | python | ThriftSASLClientProtocol.__init__ | (self, client_class, iprot_factory, oprot_factory=None,
host=None, service=None, mechanism='GSSAPI', **sasl_kwargs) | host: the name of the server, from a SASL perspective
service: the name of the server's service, from a SASL perspective
mechanism: the name of the preferred mechanism to use
All other kwargs will be passed to the puresasl.client.SASLClient
constructor. | host: the name of the server, from a SASL perspective
service: the name of the server's service, from a SASL perspective
mechanism: the name of the preferred mechanism to use | [
"host",
":",
"the",
"name",
"of",
"the",
"server",
"from",
"a",
"SASL",
"perspective",
"service",
":",
"the",
"name",
"of",
"the",
"server",
"s",
"service",
"from",
"a",
"SASL",
"perspective",
"mechanism",
":",
"the",
"name",
"of",
"the",
"preferred",
"m... | def __init__(self, client_class, iprot_factory, oprot_factory=None,
host=None, service=None, mechanism='GSSAPI', **sasl_kwargs):
"""
host: the name of the server, from a SASL perspective
service: the name of the server's service, from a SASL perspective
mechanism: the name of the preferred mechanism to use
All other kwargs will be passed to the puresasl.client.SASLClient
constructor.
"""
from puresasl.client import SASLClient
self.SASLCLient = SASLClient
ThriftClientProtocol.__init__(self, client_class, iprot_factory, oprot_factory)
self._sasl_negotiation_deferred = None
self._sasl_negotiation_status = None
self.client = None
if host is not None:
self.createSASLClient(host, service, mechanism, **sasl_kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"client_class",
",",
"iprot_factory",
",",
"oprot_factory",
"=",
"None",
",",
"host",
"=",
"None",
",",
"service",
"=",
"None",
",",
"mechanism",
"=",
"'GSSAPI'",
",",
"*",
"*",
"sasl_kwargs",
")",
":",
"from",
"pures... | https://github.com/apache/thrift/blob/0b29261a4f3c6882ef3b09aae47914f0012b0472/lib/py/src/transport/TTwisted.py#L122-L143 | ||
reverbrain/elliptics | 4b4f9b8094d7616c1ec50eb8605edb059b9f228e | recovery/elliptics_recovery/utils/misc.py | python | worker_init | () | Do not catch Ctrl+C in worker | Do not catch Ctrl+C in worker | [
"Do",
"not",
"catch",
"Ctrl",
"+",
"C",
"in",
"worker"
] | def worker_init():
"""Do not catch Ctrl+C in worker"""
from signal import signal, SIGINT, SIG_IGN
signal(SIGINT, SIG_IGN) | [
"def",
"worker_init",
"(",
")",
":",
"from",
"signal",
"import",
"signal",
",",
"SIGINT",
",",
"SIG_IGN",
"signal",
"(",
"SIGINT",
",",
"SIG_IGN",
")"
] | https://github.com/reverbrain/elliptics/blob/4b4f9b8094d7616c1ec50eb8605edb059b9f228e/recovery/elliptics_recovery/utils/misc.py#L86-L89 | ||
tcpexmachina/remy | 687b5db29b81df7ae8737889c78b47e7f9788297 | scripts/plot.py | python | BaseRemyCCPerformancePlotGenerator.get_statistics | (self, remyccfilename, link_ppt) | Must be implemented by subclasses. Should, for the given RemyCC and
link speed, return a 3-tuple `(norm_score, sender_data,
link_ppt_prior)`, where `norm_score` is the normalized score,
`sender_data` is a list of `[throughput, delay] lists, and
`link_ppt_prior` is a 2-tuple `(low, high)` being the link speed range
on which the RemyCC was trained. | Must be implemented by subclasses. Should, for the given RemyCC and
link speed, return a 3-tuple `(norm_score, sender_data,
link_ppt_prior)`, where `norm_score` is the normalized score,
`sender_data` is a list of `[throughput, delay] lists, and
`link_ppt_prior` is a 2-tuple `(low, high)` being the link speed range
on which the RemyCC was trained. | [
"Must",
"be",
"implemented",
"by",
"subclasses",
".",
"Should",
"for",
"the",
"given",
"RemyCC",
"and",
"link",
"speed",
"return",
"a",
"3",
"-",
"tuple",
"(",
"norm_score",
"sender_data",
"link_ppt_prior",
")",
"where",
"norm_score",
"is",
"the",
"normalized"... | def get_statistics(self, remyccfilename, link_ppt):
"""Must be implemented by subclasses. Should, for the given RemyCC and
link speed, return a 3-tuple `(norm_score, sender_data,
link_ppt_prior)`, where `norm_score` is the normalized score,
`sender_data` is a list of `[throughput, delay] lists, and
`link_ppt_prior` is a 2-tuple `(low, high)` being the link speed range
on which the RemyCC was trained.
"""
raise NotImplementedError("subclasses of BaseRemyCCPerformancePlotGenerator must implement get_statistics") | [
"def",
"get_statistics",
"(",
"self",
",",
"remyccfilename",
",",
"link_ppt",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"subclasses of BaseRemyCCPerformancePlotGenerator must implement get_statistics\"",
")"
] | https://github.com/tcpexmachina/remy/blob/687b5db29b81df7ae8737889c78b47e7f9788297/scripts/plot.py#L65-L73 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/distributed/auto_parallel/cost_model.py | python | estimate_cost | (distributed_program, cluster, pipeline_config,
standalone_cost_data, batch_size) | return cost | Estimated cost from distributed program, cluster model and distributed settings.
Args:
distributed_program(list): list of paddle programs
cluster(Cluster): cluster model
standalone_cost_data(CostData): cost data given by paddle.core
batch_size(int): batch size of the training workload
pipeline_config(list): configuration of pipeline stage allocation | Estimated cost from distributed program, cluster model and distributed settings.
Args:
distributed_program(list): list of paddle programs
cluster(Cluster): cluster model
standalone_cost_data(CostData): cost data given by paddle.core
batch_size(int): batch size of the training workload
pipeline_config(list): configuration of pipeline stage allocation | [
"Estimated",
"cost",
"from",
"distributed",
"program",
"cluster",
"model",
"and",
"distributed",
"settings",
".",
"Args",
":",
"distributed_program",
"(",
"list",
")",
":",
"list",
"of",
"paddle",
"programs",
"cluster",
"(",
"Cluster",
")",
":",
"cluster",
"mo... | def estimate_cost(distributed_program, cluster, pipeline_config,
standalone_cost_data, batch_size):
"""
Estimated cost from distributed program, cluster model and distributed settings.
Args:
distributed_program(list): list of paddle programs
cluster(Cluster): cluster model
standalone_cost_data(CostData): cost data given by paddle.core
batch_size(int): batch size of the training workload
pipeline_config(list): configuration of pipeline stage allocation
"""
# the following line is left for now, cluster model will be involved in the future
assert cluster is None, "For now, cluster remains None"
cm_ctx = CostModel(
cluster=cluster,
batch_size=batch_size,
standalone_cost_data=standalone_cost_data,
pipeline_config=pipeline_config)
cm_ctx.init(distributed_program)
cost = cm_ctx.get_cost()
return cost | [
"def",
"estimate_cost",
"(",
"distributed_program",
",",
"cluster",
",",
"pipeline_config",
",",
"standalone_cost_data",
",",
"batch_size",
")",
":",
"# the following line is left for now, cluster model will be involved in the future",
"assert",
"cluster",
"is",
"None",
",",
... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/auto_parallel/cost_model.py#L780-L801 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/fields.py | python | RequestField.render_headers | (self) | return u"\r\n".join(lines) | Renders the headers for this request field. | [] | def render_headers(self):
"""
Renders the headers for this request field.
"""
lines = []
sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"]
for sort_key in sort_keys:
if self.headers.get(sort_key, False):
lines.append(u"%s: %s" % (sort_key, self.headers[sort_key]))
for header_name, header_value in self.headers.items():
if header_name not in sort_keys:
if header_value:
lines.append(u"%s: %s" % (header_name, header_value))
lines.append(u"\r\n")
return u"\r\n".join(lines) | [
"def",
"render_headers",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"sort_keys",
"=",
"[",
"\"Content-Disposition\"",
",",
"\"Content-Type\"",
",",
"\"Content-Location\"",
"]",
"for",
"sort_key",
"in",
"sort_keys",
":",
"if",
"self",
".",
"headers",
".",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/fields.py#L459-L493 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py | python | _FindRuleTriggerFiles | (rule, sources) | return rule.get('rule_sources', []) | Find the list of files which a particular rule applies to.
Arguments:
rule: the rule in question
sources: the set of all known source files for this project
Returns:
The list of sources that trigger a particular rule. | Find the list of files which a particular rule applies to. | [
"Find",
"the",
"list",
"of",
"files",
"which",
"a",
"particular",
"rule",
"applies",
"to",
"."
] | def _FindRuleTriggerFiles(rule, sources):
"""Find the list of files which a particular rule applies to.
Arguments:
rule: the rule in question
sources: the set of all known source files for this project
Returns:
The list of sources that trigger a particular rule.
"""
return rule.get('rule_sources', []) | [
"def",
"_FindRuleTriggerFiles",
"(",
"rule",
",",
"sources",
")",
":",
"return",
"rule",
".",
"get",
"(",
"'rule_sources'",
",",
"[",
"]",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L506-L515 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/gluon/probability/distributions/utils.py | python | digamma | () | return compute | Unified digamma interface for both scalar and tensor | Unified digamma interface for both scalar and tensor | [
"Unified",
"digamma",
"interface",
"for",
"both",
"scalar",
"and",
"tensor"
] | def digamma():
"""Unified digamma interface for both scalar and tensor
"""
def compute(value):
"""Return digamma(value)
"""
if isinstance(value, Number):
if sc is not None:
return sc.digamma(value, dtype='float32')
else:
raise ValueError('Numbers are not supported as input if scipy is not installed')
return npx.digamma(value)
return compute | [
"def",
"digamma",
"(",
")",
":",
"def",
"compute",
"(",
"value",
")",
":",
"\"\"\"Return digamma(value)\n \"\"\"",
"if",
"isinstance",
"(",
"value",
",",
"Number",
")",
":",
"if",
"sc",
"is",
"not",
"None",
":",
"return",
"sc",
".",
"digamma",
"(",
... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/probability/distributions/utils.py#L46-L58 | |
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/application.py | python | IApplication.Delete | (self) | Deletes the APP2APP application in Skype client. | Deletes the APP2APP application in Skype client. | [
"Deletes",
"the",
"APP2APP",
"application",
"in",
"Skype",
"client",
"."
] | def Delete(self):
'''Deletes the APP2APP application in Skype client.
'''
self._Skype._DoCommand('DELETE APPLICATION %s' % self._Name) | [
"def",
"Delete",
"(",
"self",
")",
":",
"self",
".",
"_Skype",
".",
"_DoCommand",
"(",
"'DELETE APPLICATION %s'",
"%",
"self",
".",
"_Name",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/application.py#L65-L68 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/more-itertools/py2/more_itertools/more.py | python | last | (iterable, default=_marker) | Return the last item of *iterable*, or *default* if *iterable* is
empty.
>>> last([0, 1, 2, 3])
3
>>> last([], 'some default')
'some default'
If *default* is not provided and there are no items in the iterable,
raise ``ValueError``. | Return the last item of *iterable*, or *default* if *iterable* is
empty. | [
"Return",
"the",
"last",
"item",
"of",
"*",
"iterable",
"*",
"or",
"*",
"default",
"*",
"if",
"*",
"iterable",
"*",
"is",
"empty",
"."
] | def last(iterable, default=_marker):
"""Return the last item of *iterable*, or *default* if *iterable* is
empty.
>>> last([0, 1, 2, 3])
3
>>> last([], 'some default')
'some default'
If *default* is not provided and there are no items in the iterable,
raise ``ValueError``.
"""
try:
try:
# Try to access the last item directly
return iterable[-1]
except (TypeError, AttributeError, KeyError):
# If not slice-able, iterate entirely using length-1 deque
return deque(iterable, maxlen=1)[0]
except IndexError: # If the iterable was empty
if default is _marker:
raise ValueError('last() was called on an empty iterable, and no '
'default value was provided.')
return default | [
"def",
"last",
"(",
"iterable",
",",
"default",
"=",
"_marker",
")",
":",
"try",
":",
"try",
":",
"# Try to access the last item directly",
"return",
"iterable",
"[",
"-",
"1",
"]",
"except",
"(",
"TypeError",
",",
"AttributeError",
",",
"KeyError",
")",
":"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/more-itertools/py2/more_itertools/more.py#L146-L169 | ||
envoyproxy/envoy | 65541accdafe255e72310b4298d646e091da2d80 | tools/api_proto_plugin/visitor.py | python | Visitor.visit_enum | (self, enum_proto, type_context) | Visit an enum definition.
Args:
enum_proto: EnumDescriptorProto for enum.
type_context: type_context.TypeContext for enum type.
Returns:
Plugin specific output. | Visit an enum definition. | [
"Visit",
"an",
"enum",
"definition",
"."
] | def visit_enum(self, enum_proto, type_context):
"""Visit an enum definition.
Args:
enum_proto: EnumDescriptorProto for enum.
type_context: type_context.TypeContext for enum type.
Returns:
Plugin specific output.
"""
pass | [
"def",
"visit_enum",
"(",
"self",
",",
"enum_proto",
",",
"type_context",
")",
":",
"pass"
] | https://github.com/envoyproxy/envoy/blob/65541accdafe255e72310b4298d646e091da2d80/tools/api_proto_plugin/visitor.py#L19-L29 | ||
CanalTP/navitia | cb84ce9859070187e708818b058e6a7e0b7f891b | source/tyr/tyr/binarisation.py | python | reload_data | (self, instance_config, job_id) | reload data on all kraken of this instance | reload data on all kraken of this instance | [
"reload",
"data",
"on",
"all",
"kraken",
"of",
"this",
"instance"
] | def reload_data(self, instance_config, job_id):
""" reload data on all kraken of this instance"""
job = models.Job.query.get(job_id)
instance = job.instance
logging.info("Unqueuing job {}, reload data of instance {}".format(job.id, instance.name))
logger = get_instance_logger(instance, task_id=job_id)
try:
task = navitiacommon.task_pb2.Task()
task.action = navitiacommon.task_pb2.RELOAD
rabbit_mq_handler = RabbitMqHandler(
current_app.config['KRAKEN_BROKER_URL'], instance_config.exchange, "topic"
)
logger.info("reload kraken")
rabbit_mq_handler.publish(task.SerializeToString(), instance.name + '.task.reload')
except:
logger.exception('')
job.state = 'failed'
models.db.session.commit()
raise | [
"def",
"reload_data",
"(",
"self",
",",
"instance_config",
",",
"job_id",
")",
":",
"job",
"=",
"models",
".",
"Job",
".",
"query",
".",
"get",
"(",
"job_id",
")",
"instance",
"=",
"job",
".",
"instance",
"logging",
".",
"info",
"(",
"\"Unqueuing job {},... | https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/tyr/tyr/binarisation.py#L563-L583 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/inspector_protocol/jinja2/filters.py | python | contextfilter | (f) | return f | Decorator for marking context dependent filters. The current
:class:`Context` will be passed as first argument. | Decorator for marking context dependent filters. The current
:class:`Context` will be passed as first argument. | [
"Decorator",
"for",
"marking",
"context",
"dependent",
"filters",
".",
"The",
"current",
":",
"class",
":",
"Context",
"will",
"be",
"passed",
"as",
"first",
"argument",
"."
] | def contextfilter(f):
"""Decorator for marking context dependent filters. The current
:class:`Context` will be passed as first argument.
"""
f.contextfilter = True
return f | [
"def",
"contextfilter",
"(",
"f",
")",
":",
"f",
".",
"contextfilter",
"=",
"True",
"return",
"f"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/filters.py#L29-L34 | |
wujixiu/helmet-detection | 8eff5c59ddfba5a29e0b76aeb48babcb49246178 | hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py | python | CheckSpacingForFunctionCall | (filename, line, linenum, error) | Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for the correctness of various spacing around function calls. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"around",
"function",
"calls",
"."
] | def CheckSpacingForFunctionCall(filename, line, linenum, error):
"""Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Since function calls often occur inside if/for/while/switch
# expressions - which have their own, more liberal conventions - we
# first see if we should be looking inside such an expression for a
# function call, to which we can apply more strict standards.
fncall = line # if there's no control flow construct, look at whole line
for pattern in (r'\bif\s*\((.*)\)\s*{',
r'\bfor\s*\((.*)\)\s*{',
r'\bwhile\s*\((.*)\)\s*[{;]',
r'\bswitch\s*\((.*)\)\s*{'):
match = Search(pattern, line)
if match:
fncall = match.group(1) # look inside the parens for function calls
break
# Except in if/for/while/switch, there should never be space
# immediately inside parens (eg "f( 3, 4 )"). We make an exception
# for nested parens ( (a+b) + c ). Likewise, there should never be
# a space before a ( when it's a function argument. I assume it's a
# function argument when the char before the whitespace is legal in
# a function name (alnum + _) and we're not starting a macro. Also ignore
# pointers and references to arrays and functions coz they're too tricky:
# we use a very simple way to recognize these:
# " (something)(maybe-something)" or
# " (something)(maybe-something," or
# " (something)[something]"
# Note that we assume the contents of [] to be short enough that
# they'll never need to wrap.
if ( # Ignore control structures.
not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
fncall) and
# Ignore pointers/references to functions.
not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
# Ignore pointers/references to arrays.
not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
error(filename, linenum, 'whitespace/parens', 4,
'Extra space after ( in function call')
elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Extra space after (')
if (Search(r'\w\s+\(', fncall) and
not Search(r'#\s*define|typedef', fncall) and
not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)):
error(filename, linenum, 'whitespace/parens', 4,
'Extra space before ( in function call')
# If the ) is followed only by a newline or a { + newline, assume it's
# part of a control statement (if/while/etc), and don't complain
if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
# If the closing parenthesis is preceded by only whitespaces,
# try to give a more descriptive error message.
if Search(r'^\s+\)', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Closing ) should be moved to the previous line')
else:
error(filename, linenum, 'whitespace/parens', 2,
'Extra space before )') | [
"def",
"CheckSpacingForFunctionCall",
"(",
"filename",
",",
"line",
",",
"linenum",
",",
"error",
")",
":",
"# Since function calls often occur inside if/for/while/switch",
"# expressions - which have their own, more liberal conventions - we",
"# first see if we should be looking inside ... | https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py#L2305-L2370 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/altgraph/altgraph/Dot.py | python | Dot.all_node_style | (self, **kwargs) | Modifies all node styles | Modifies all node styles | [
"Modifies",
"all",
"node",
"styles"
] | def all_node_style(self, **kwargs):
'''
Modifies all node styles
'''
for node in self.nodes:
self.node_style(node, **kwargs) | [
"def",
"all_node_style",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"self",
".",
"node_style",
"(",
"node",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/altgraph/altgraph/Dot.py#L199-L204 | ||
tensor-compiler/taco | d0654a84137169883973c40a951dfdb89883fd9c | python_bindings/pytaco/pytensor/taco_tensor.py | python | to_array | (t) | return np.array(t.to_dense(), copy=True) | Converts a taco tensor to a numpy array.
This always copies the tensor. To avoid the copy for dense tensors, see the notes section.
Parameters
-----------
t: tensor
A taco tensor to convert to a numpy array.
Notes
-------
Dense tensors export python's buffer interface. As a result, they can be converted to numpy arrays using
``np.array(tensor, copy=False)`` . Attempting to do this for sparse tensors throws an error. Note that as a result
of exporting the buffer interface dense tensors can also be converted to eigen or any other library supporting this
inferface.
Also it is very important to note that if requesting a numpy view of data owned by taco, taco will mark the array as
read only meaning the user cannot write to that data without using the taco reference. This is needed to avoid
raising issues with taco's delayed execution mechanism.
Examples
----------
We first look at a simple use of to_array
>>> import pytaco as pt
>>> t = pt.tensor([2, 2], [pt.dense, pt.compressed])
>>> t.insert([0, 0], 10)
>>> t.to_array()[0, 0]
10.0
One could choose to use np.array if a copy is not needed
>>> import pytaco as pt
>>> import numpy as np
>>> t = pt.tensor([2, 2], pt.dense)
>>> t.insert([0, 0], 10)
>>> a = np.array(t, copy=False)
>>> a
array([[10., 0.],
[ 0., 0.]], dtype=float32)
>>> t.insert([0, 0], 100) # Note that insert increments instead of setting!
>>> t.to_array()[0, 0]
110.0
Returns
---------
arr: numpy.array
A numpy array containing a copy of the data in the tensor object t. | Converts a taco tensor to a numpy array. | [
"Converts",
"a",
"taco",
"tensor",
"to",
"a",
"numpy",
"array",
"."
] | def to_array(t):
"""
Converts a taco tensor to a numpy array.
This always copies the tensor. To avoid the copy for dense tensors, see the notes section.
Parameters
-----------
t: tensor
A taco tensor to convert to a numpy array.
Notes
-------
Dense tensors export python's buffer interface. As a result, they can be converted to numpy arrays using
``np.array(tensor, copy=False)`` . Attempting to do this for sparse tensors throws an error. Note that as a result
of exporting the buffer interface dense tensors can also be converted to eigen or any other library supporting this
inferface.
Also it is very important to note that if requesting a numpy view of data owned by taco, taco will mark the array as
read only meaning the user cannot write to that data without using the taco reference. This is needed to avoid
raising issues with taco's delayed execution mechanism.
Examples
----------
We first look at a simple use of to_array
>>> import pytaco as pt
>>> t = pt.tensor([2, 2], [pt.dense, pt.compressed])
>>> t.insert([0, 0], 10)
>>> t.to_array()[0, 0]
10.0
One could choose to use np.array if a copy is not needed
>>> import pytaco as pt
>>> import numpy as np
>>> t = pt.tensor([2, 2], pt.dense)
>>> t.insert([0, 0], 10)
>>> a = np.array(t, copy=False)
>>> a
array([[10., 0.],
[ 0., 0.]], dtype=float32)
>>> t.insert([0, 0], 100) # Note that insert increments instead of setting!
>>> t.to_array()[0, 0]
110.0
Returns
---------
arr: numpy.array
A numpy array containing a copy of the data in the tensor object t.
"""
return np.array(t.to_dense(), copy=True) | [
"def",
"to_array",
"(",
"t",
")",
":",
"return",
"np",
".",
"array",
"(",
"t",
".",
"to_dense",
"(",
")",
",",
"copy",
"=",
"True",
")"
] | https://github.com/tensor-compiler/taco/blob/d0654a84137169883973c40a951dfdb89883fd9c/python_bindings/pytaco/pytensor/taco_tensor.py#L658-L713 | |
vslavik/poedit | f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a | deps/boost/libs/metaparse/tools/build_environment.py | python | main | () | The main function of the utility | The main function of the utility | [
"The",
"main",
"function",
"of",
"the",
"utility"
] | def main():
"""The main function of the utility"""
parser = argparse.ArgumentParser(
description='Manage the build environment of Boost.Metaparse'
)
parser.add_argument(
'--dep_json',
required=True,
help='The json file describing the dependencies'
)
parser.add_argument(
'--git',
required=False,
default='git',
help='The git command to use'
)
parser.add_argument(
'--out',
required=False,
default='boost',
help='The directory to clone into'
)
parser.add_argument(
'--action',
required=True,
choices=['update', 'checkout'],
help='The action to do with the dependencies'
)
parser.add_argument(
'--boost_repository',
required=False,
default='https://github.com/boostorg/boost.git',
help='The Boost repository to clone'
)
parser.add_argument(
'--ref',
required=False,
default='origin/master',
help='The reference to set to in update'
)
args = parser.parse_args()
build_environment(
args.dep_json,
args.out,
ChildProcess([args.git]),
args.boost_repository,
args.action,
args.ref
) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Manage the build environment of Boost.Metaparse'",
")",
"parser",
".",
"add_argument",
"(",
"'--dep_json'",
",",
"required",
"=",
"True",
",",
"help",
"=",
... | https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/libs/metaparse/tools/build_environment.py#L81-L130 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/serial/serialutil.py | python | SerialBase.xonxoff | (self) | return self._xonxoff | Get the current XON/XOFF setting. | Get the current XON/XOFF setting. | [
"Get",
"the",
"current",
"XON",
"/",
"XOFF",
"setting",
"."
] | def xonxoff(self):
"""Get the current XON/XOFF setting."""
return self._xonxoff | [
"def",
"xonxoff",
"(",
"self",
")",
":",
"return",
"self",
".",
"_xonxoff"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/serialutil.py#L411-L413 | |
libornovax/master_thesis_code | 6eca474ed3cae673afde010caef338cf7349f839 | caffe/scripts/cpp_lint.py | python | GetHeaderGuardCPPVariable | (filename) | return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' | Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file. | Returns the CPP variable that should be used as a header guard. | [
"Returns",
"the",
"CPP",
"variable",
"that",
"should",
"be",
"used",
"as",
"a",
"header",
"guard",
"."
] | def GetHeaderGuardCPPVariable(filename):
"""Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file.
"""
# Restores original filename in case that cpplint is invoked from Emacs's
# flymake.
filename = re.sub(r'_flymake\.h$', '.h', filename)
filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
fileinfo = FileInfo(filename)
file_path_from_root = fileinfo.RepositoryName()
if _root:
file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' | [
"def",
"GetHeaderGuardCPPVariable",
"(",
"filename",
")",
":",
"# Restores original filename in case that cpplint is invoked from Emacs's",
"# flymake.",
"filename",
"=",
"re",
".",
"sub",
"(",
"r'_flymake\\.h$'",
",",
"'.h'",
",",
"filename",
")",
"filename",
"=",
"re",
... | https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/caffe/scripts/cpp_lint.py#L1384-L1405 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | ShowEvent.SetShow | (*args, **kwargs) | return _core_.ShowEvent_SetShow(*args, **kwargs) | SetShow(self, bool show) | SetShow(self, bool show) | [
"SetShow",
"(",
"self",
"bool",
"show",
")"
] | def SetShow(*args, **kwargs):
"""SetShow(self, bool show)"""
return _core_.ShowEvent_SetShow(*args, **kwargs) | [
"def",
"SetShow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"ShowEvent_SetShow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L6577-L6579 | |
LLNL/blt | 4eafa66ddb99ee5a4a0f75f3d7d790679add6e01 | thirdparty_builtin/benchmark-1.5.0/tools/gbench/report.py | python | find_longest_name | (benchmark_list) | return longest_name | Return the length of the longest benchmark name in a given list of
benchmark JSON objects | Return the length of the longest benchmark name in a given list of
benchmark JSON objects | [
"Return",
"the",
"length",
"of",
"the",
"longest",
"benchmark",
"name",
"in",
"a",
"given",
"list",
"of",
"benchmark",
"JSON",
"objects"
] | def find_longest_name(benchmark_list):
"""
Return the length of the longest benchmark name in a given list of
benchmark JSON objects
"""
longest_name = 1
for bc in benchmark_list:
if len(bc['name']) > longest_name:
longest_name = len(bc['name'])
return longest_name | [
"def",
"find_longest_name",
"(",
"benchmark_list",
")",
":",
"longest_name",
"=",
"1",
"for",
"bc",
"in",
"benchmark_list",
":",
"if",
"len",
"(",
"bc",
"[",
"'name'",
"]",
")",
">",
"longest_name",
":",
"longest_name",
"=",
"len",
"(",
"bc",
"[",
"'name... | https://github.com/LLNL/blt/blob/4eafa66ddb99ee5a4a0f75f3d7d790679add6e01/thirdparty_builtin/benchmark-1.5.0/tools/gbench/report.py#L59-L68 | |
nasa/meshNetwork | ff4bd66e0ca6bd424fd8897a97252bb3925d8b3c | python/mesh/generic/nodeConfig.py | python | NodeConfig.hashPlatformConfig | (self, configHash) | Hash platform specific configuration parameters. This method should be overriden by derived classes. | Hash platform specific configuration parameters. This method should be overriden by derived classes. | [
"Hash",
"platform",
"specific",
"configuration",
"parameters",
".",
"This",
"method",
"should",
"be",
"overriden",
"by",
"derived",
"classes",
"."
] | def hashPlatformConfig(self, configHash):
'''Hash platform specific configuration parameters. This method should be overriden by derived classes.'''
pass | [
"def",
"hashPlatformConfig",
"(",
"self",
",",
"configHash",
")",
":",
"pass"
] | https://github.com/nasa/meshNetwork/blob/ff4bd66e0ca6bd424fd8897a97252bb3925d8b3c/python/mesh/generic/nodeConfig.py#L242-L244 | ||
zhaoweicai/mscnn | 534bcac5710a579d60827f192035f7eef6d8c585 | scripts/cpp_lint.py | python | _CppLintState.IncrementErrorCount | (self, category) | Bumps the module's error statistic. | Bumps the module's error statistic. | [
"Bumps",
"the",
"module",
"s",
"error",
"statistic",
"."
] | def IncrementErrorCount(self, category):
"""Bumps the module's error statistic."""
self.error_count += 1
if self.counting in ('toplevel', 'detailed'):
if self.counting != 'detailed':
category = category.split('/')[0]
if category not in self.errors_by_category:
self.errors_by_category[category] = 0
self.errors_by_category[category] += 1 | [
"def",
"IncrementErrorCount",
"(",
"self",
",",
"category",
")",
":",
"self",
".",
"error_count",
"+=",
"1",
"if",
"self",
".",
"counting",
"in",
"(",
"'toplevel'",
",",
"'detailed'",
")",
":",
"if",
"self",
".",
"counting",
"!=",
"'detailed'",
":",
"cat... | https://github.com/zhaoweicai/mscnn/blob/534bcac5710a579d60827f192035f7eef6d8c585/scripts/cpp_lint.py#L747-L755 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/symbol/symbol.py | python | Symbol.sort | (self, *args, **kwargs) | return op.sort(self, *args, **kwargs) | Convenience fluent method for :py:func:`sort`.
The arguments are the same as for :py:func:`sort`, with
this array as data. | Convenience fluent method for :py:func:`sort`. | [
"Convenience",
"fluent",
"method",
"for",
":",
"py",
":",
"func",
":",
"sort",
"."
] | def sort(self, *args, **kwargs):
"""Convenience fluent method for :py:func:`sort`.
The arguments are the same as for :py:func:`sort`, with
this array as data.
"""
return op.sort(self, *args, **kwargs) | [
"def",
"sort",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"op",
".",
"sort",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/symbol/symbol.py#L2014-L2020 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py | python | Index._validate_index_level | (self, level) | Validate index level.
For single-level Index getting level number is a no-op, but some
verification must be done like in MultiIndex. | Validate index level. | [
"Validate",
"index",
"level",
"."
] | def _validate_index_level(self, level):
"""
Validate index level.
For single-level Index getting level number is a no-op, but some
verification must be done like in MultiIndex.
"""
if isinstance(level, int):
if level < 0 and level != -1:
raise IndexError(
"Too many levels: Index has only 1 level, "
f"{level} is not a valid level number"
)
elif level > 0:
raise IndexError(
f"Too many levels: Index has only 1 level, not {level + 1}"
)
elif level != self.name:
raise KeyError(
f"Requested level ({level}) does not match index name ({self.name})"
) | [
"def",
"_validate_index_level",
"(",
"self",
",",
"level",
")",
":",
"if",
"isinstance",
"(",
"level",
",",
"int",
")",
":",
"if",
"level",
"<",
"0",
"and",
"level",
"!=",
"-",
"1",
":",
"raise",
"IndexError",
"(",
"\"Too many levels: Index has only 1 level,... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py#L1396-L1417 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/distributions/python/ops/bijectors/cholesky_outer_product_impl.py | python | CholeskyOuterProduct.__init__ | (self, event_ndims=2, validate_args=False,
name="cholesky_outer_product") | Instantiates the `CholeskyOuterProduct` bijector.
Args:
event_ndims: `constant` `int32` scalar `Tensor` indicating the number of
dimensions associated with a particular draw from the distribution. Must
be 0 or 2.
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object.
Raises:
ValueError: if event_ndims is neither 0 or 2. | Instantiates the `CholeskyOuterProduct` bijector. | [
"Instantiates",
"the",
"CholeskyOuterProduct",
"bijector",
"."
] | def __init__(self, event_ndims=2, validate_args=False,
name="cholesky_outer_product"):
"""Instantiates the `CholeskyOuterProduct` bijector.
Args:
event_ndims: `constant` `int32` scalar `Tensor` indicating the number of
dimensions associated with a particular draw from the distribution. Must
be 0 or 2.
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object.
Raises:
ValueError: if event_ndims is neither 0 or 2.
"""
self._graph_parents = []
self._name = name
with self._name_scope("init", values=[event_ndims]):
event_ndims = ops.convert_to_tensor(event_ndims, name="event_ndims")
event_ndims = tensor_util.constant_value(event_ndims)
if event_ndims is None or event_ndims not in [0, 2]:
raise ValueError("`event_ndims` must be a TF constant which is 0 or 2")
self._static_event_ndims = event_ndims
super(CholeskyOuterProduct, self).__init__(
event_ndims=event_ndims,
validate_args=validate_args,
name=name) | [
"def",
"__init__",
"(",
"self",
",",
"event_ndims",
"=",
"2",
",",
"validate_args",
"=",
"False",
",",
"name",
"=",
"\"cholesky_outer_product\"",
")",
":",
"self",
".",
"_graph_parents",
"=",
"[",
"]",
"self",
".",
"_name",
"=",
"name",
"with",
"self",
"... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/distributions/python/ops/bijectors/cholesky_outer_product_impl.py#L58-L84 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/wsgiref/util.py | python | is_hop_by_hop | (header_name) | return _hoppish(header_name.lower()) | Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header | Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header | [
"Return",
"true",
"if",
"header_name",
"is",
"an",
"HTTP",
"/",
"1",
".",
"1",
"Hop",
"-",
"by",
"-",
"Hop",
"header"
] | def is_hop_by_hop(header_name):
"""Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header"""
return _hoppish(header_name.lower()) | [
"def",
"is_hop_by_hop",
"(",
"header_name",
")",
":",
"return",
"_hoppish",
"(",
"header_name",
".",
"lower",
"(",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/wsgiref/util.py#L163-L165 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | Choice.Create | (*args, **kwargs) | return _controls_.Choice_Create(*args, **kwargs) | Create(Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
List choices=EmptyList, long style=0, Validator validator=DefaultValidator,
String name=ChoiceNameStr) -> bool
Actually create the GUI Choice control for 2-phase creation | Create(Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
List choices=EmptyList, long style=0, Validator validator=DefaultValidator,
String name=ChoiceNameStr) -> bool | [
"Create",
"(",
"Window",
"parent",
"int",
"id",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"List",
"choices",
"=",
"EmptyList",
"long",
"style",
"=",
"0",
"Validator",
"validator",
"=",
"DefaultValidator",
"String",
"name",
"="... | def Create(*args, **kwargs):
"""
Create(Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize,
List choices=EmptyList, long style=0, Validator validator=DefaultValidator,
String name=ChoiceNameStr) -> bool
Actually create the GUI Choice control for 2-phase creation
"""
return _controls_.Choice_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"Choice_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L504-L512 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py | python | GmmAlgorithm.clusters | (self) | return self._means | Returns the clusters with dimensions num_classes X 1 X num_dimensions. | Returns the clusters with dimensions num_classes X 1 X num_dimensions. | [
"Returns",
"the",
"clusters",
"with",
"dimensions",
"num_classes",
"X",
"1",
"X",
"num_dimensions",
"."
] | def clusters(self):
"""Returns the clusters with dimensions num_classes X 1 X num_dimensions."""
return self._means | [
"def",
"clusters",
"(",
"self",
")",
":",
"return",
"self",
".",
"_means"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L179-L181 | |
christinaa/LLVM-VideoCore4 | 7773c3c9e5d22b785d4b96ed0acea37c8aa9c183 | bindings/python/llvm/object.py | python | Section.get_relocations | (self, cache=False) | Obtain the relocations in this Section.
This is a generator for llvm.object.Relocation instances.
Each instance is a limited used object. See this module's documentation
on iterators for more. | Obtain the relocations in this Section. | [
"Obtain",
"the",
"relocations",
"in",
"this",
"Section",
"."
] | def get_relocations(self, cache=False):
"""Obtain the relocations in this Section.
This is a generator for llvm.object.Relocation instances.
Each instance is a limited used object. See this module's documentation
on iterators for more.
"""
if self.expired:
raise Exception('Section instance has expired.')
relocations = lib.LLVMGetRelocations(self)
last = None
while True:
if lib.LLVMIsRelocationIteratorAtEnd(self, relocations):
break
last = Relocation(relocations)
if cache:
last.cache()
yield last
lib.LLVMMoveToNextRelocation(relocations)
last.expire()
if last is not None:
last.expire()
lib.LLVMDisposeRelocationIterator(relocations) | [
"def",
"get_relocations",
"(",
"self",
",",
"cache",
"=",
"False",
")",
":",
"if",
"self",
".",
"expired",
":",
"raise",
"Exception",
"(",
"'Section instance has expired.'",
")",
"relocations",
"=",
"lib",
".",
"LLVMGetRelocations",
"(",
"self",
")",
"last",
... | https://github.com/christinaa/LLVM-VideoCore4/blob/7773c3c9e5d22b785d4b96ed0acea37c8aa9c183/bindings/python/llvm/object.py#L240-L269 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py | python | EntryPoint.parse_map | (cls, data, dist=None) | return maps | Parse a map of entry point groups | Parse a map of entry point groups | [
"Parse",
"a",
"map",
"of",
"entry",
"point",
"groups"
] | def parse_map(cls, data, dist=None):
"""Parse a map of entry point groups"""
if isinstance(data, dict):
data = data.items()
else:
data = split_sections(data)
maps = {}
for group, lines in data:
if group is None:
if not lines:
continue
raise ValueError("Entry points must be listed in groups")
group = group.strip()
if group in maps:
raise ValueError("Duplicate group name", group)
maps[group] = cls.parse_group(group, lines, dist)
return maps | [
"def",
"parse_map",
"(",
"cls",
",",
"data",
",",
"dist",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
"=",
"data",
".",
"items",
"(",
")",
"else",
":",
"data",
"=",
"split_sections",
"(",
"data",
")",
"m... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L2527-L2543 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/shortcuteditor.py | python | ShortcutEditor.CreateWidgets | (self) | Creates all the widgets needed to populate the interface, such as buttons,
texts and, most importantly, :class:`ListShortcut`. | Creates all the widgets needed to populate the interface, such as buttons,
texts and, most importantly, :class:`ListShortcut`. | [
"Creates",
"all",
"the",
"widgets",
"needed",
"to",
"populate",
"the",
"interface",
"such",
"as",
"buttons",
"texts",
"and",
"most",
"importantly",
":",
"class",
":",
"ListShortcut",
"."
] | def CreateWidgets(self):
"""
Creates all the widgets needed to populate the interface, such as buttons,
texts and, most importantly, :class:`ListShortcut`.
"""
self.topStatic = wx.StaticText(self, -1, _('&Search:'))
self.searchText = wx.TextCtrl(self, -1, '')
clearBmp = _clear.GetBitmap()
self.clearButton = wx.BitmapButton(self, wx.ID_CLEAR, clearBmp, style=wx.NO_BORDER)
self.listShortcut = ListShortcut(self)
self.hiddenText = wx.TextCtrl(self, -1, '', style=wx.BORDER_THEME)
w, h, d, e = self.hiddenText.GetFullTextExtent('Ctrl+Shift+Alt+q+g+M', self.hiddenText.GetFont())
self.hiddenText.SetMinSize((w, h+d-e+1))
defaultBmp = _default.GetBitmap()
self.defaultButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_RESET, defaultBmp,
_('Restore Defaults '), size=(-1, 29))
self.infoBitmap = wx.StaticBitmap(self, -1, _info.GetBitmap())
message = _('To edit a shortcut key, click on the corresponding row\n' \
'and type a new accelerator, or press backspace to clear.')
italicFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
italicFont.SetStyle(wx.ITALIC)
self.infoStatic = wx.StaticText(self, -1, message)
self.infoStatic.SetFont(italicFont)
okBmp = _ok.GetBitmap()
cancelBmp = _cancel.GetBitmap()
helpBmp = _help.GetBitmap()
self.okButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_OK, okBmp, _('OK'))
self.cancelButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_CANCEL, cancelBmp, _('Cancel'))
self.helpButton = buttons.ThemedGenBitmapTextButton(self, wx.ID_HELP, helpBmp, _('Help'))
self.okButton.SetDefault() | [
"def",
"CreateWidgets",
"(",
"self",
")",
":",
"self",
".",
"topStatic",
"=",
"wx",
".",
"StaticText",
"(",
"self",
",",
"-",
"1",
",",
"_",
"(",
"'&Search:'",
")",
")",
"self",
".",
"searchText",
"=",
"wx",
".",
"TextCtrl",
"(",
"self",
",",
"-",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/shortcuteditor.py#L2221-L2262 | ||
wyrover/book-code | 7f4883d9030d553bc6bcfa3da685e34789839900 | 3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py | python | Duration.ToSeconds | (self) | return self.seconds | Converts a Duration to seconds. | Converts a Duration to seconds. | [
"Converts",
"a",
"Duration",
"to",
"seconds",
"."
] | def ToSeconds(self):
"""Converts a Duration to seconds."""
return self.seconds | [
"def",
"ToSeconds",
"(",
"self",
")",
":",
"return",
"self",
".",
"seconds"
] | https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py#L315-L317 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/v8/third_party/jinja2/filters.py | python | do_replace | (eval_ctx, s, old, new, count=None) | return s.replace(soft_unicode(old), soft_unicode(new), count) | Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced:
.. sourcecode:: jinja
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh | Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced: | [
"Return",
"a",
"copy",
"of",
"the",
"value",
"with",
"all",
"occurrences",
"of",
"a",
"substring",
"replaced",
"with",
"a",
"new",
"one",
".",
"The",
"first",
"argument",
"is",
"the",
"substring",
"that",
"should",
"be",
"replaced",
"the",
"second",
"is",
... | def do_replace(eval_ctx, s, old, new, count=None):
"""Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced:
.. sourcecode:: jinja
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh
"""
if count is None:
count = -1
if not eval_ctx.autoescape:
return text_type(s).replace(text_type(old), text_type(new), count)
if hasattr(old, '__html__') or hasattr(new, '__html__') and \
not hasattr(s, '__html__'):
s = escape(s)
else:
s = soft_unicode(s)
return s.replace(soft_unicode(old), soft_unicode(new), count) | [
"def",
"do_replace",
"(",
"eval_ctx",
",",
"s",
",",
"old",
",",
"new",
",",
"count",
"=",
"None",
")",
":",
"if",
"count",
"is",
"None",
":",
"count",
"=",
"-",
"1",
"if",
"not",
"eval_ctx",
".",
"autoescape",
":",
"return",
"text_type",
"(",
"s",... | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/filters.py#L102-L126 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/move-sub-tree-of-n-ary-tree.py | python | Solution2.moveSubTree | (self, root, p, q) | return root | :type root: Node
:type p: Node
:type q: Node
:rtype: Node | :type root: Node
:type p: Node
:type q: Node
:rtype: Node | [
":",
"type",
"root",
":",
"Node",
":",
"type",
"p",
":",
"Node",
":",
"type",
"q",
":",
"Node",
":",
"rtype",
":",
"Node"
] | def moveSubTree(self, root, p, q):
"""
:type root: Node
:type p: Node
:type q: Node
:rtype: Node
"""
def iter_find_parents(node, parent, p, q, lookup):
stk = [(1, [node, None])]
while stk:
step, params = stk.pop()
if step == 1:
node, parent = params
if node in (p, q):
lookup[node] = parent
if len(lookup) == 2:
return
stk.append((2, [node, reversed(node.children)]))
else:
node, it = params
child = next(it, None)
if not child:
continue
stk.append((2, [node, it]))
stk.append((1, [child, node]))
def iter_is_ancestor(node, q):
stk = [(1, [node])]
while stk:
step, params = stk.pop()
if step == 1:
node = params[0]
stk.append((2, [reversed(node.children)]))
else:
it = params[0]
child = next(it, None)
if not child:
continue
if child == q:
return True
stk.append((2, [it]))
stk.append((1, [child]))
return False
lookup = {}
iter_find_parents(root, None, p, q, lookup)
if p in lookup and lookup[p] == q:
return root
q.children.append(p)
if not iter_is_ancestor(p, q):
lookup[p].children.remove(p)
else:
lookup[q].children.remove(q)
if p == root:
root = q
else:
lookup[p].children[lookup[p].children.index(p)] = q
return root | [
"def",
"moveSubTree",
"(",
"self",
",",
"root",
",",
"p",
",",
"q",
")",
":",
"def",
"iter_find_parents",
"(",
"node",
",",
"parent",
",",
"p",
",",
"q",
",",
"lookup",
")",
":",
"stk",
"=",
"[",
"(",
"1",
",",
"[",
"node",
",",
"None",
"]",
... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/move-sub-tree-of-n-ary-tree.py#L99-L156 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/resolver.py | python | Resolver.read_resolv_conf | (self, f) | Process f as a file in the /etc/resolv.conf format. If f is
a string, it is used as the name of the file to open; otherwise it
is treated as the file itself. | Process f as a file in the /etc/resolv.conf format. If f is
a string, it is used as the name of the file to open; otherwise it
is treated as the file itself. | [
"Process",
"f",
"as",
"a",
"file",
"in",
"the",
"/",
"etc",
"/",
"resolv",
".",
"conf",
"format",
".",
"If",
"f",
"is",
"a",
"string",
"it",
"is",
"used",
"as",
"the",
"name",
"of",
"the",
"file",
"to",
"open",
";",
"otherwise",
"it",
"is",
"trea... | def read_resolv_conf(self, f):
"""Process f as a file in the /etc/resolv.conf format. If f is
a string, it is used as the name of the file to open; otherwise it
is treated as the file itself."""
if isinstance(f, str) or isinstance(f, unicode):
try:
f = open(f, 'r')
except IOError:
# /etc/resolv.conf doesn't exist, can't be read, etc.
# We'll just use the default resolver configuration.
self.nameservers = ['127.0.0.1']
return
want_close = True
else:
want_close = False
try:
for l in f:
if len(l) == 0 or l[0] == '#' or l[0] == ';':
continue
tokens = l.split()
if len(tokens) == 0:
continue
if tokens[0] == 'nameserver':
self.nameservers.append(tokens[1])
elif tokens[0] == 'domain':
self.domain = dns.name.from_text(tokens[1])
elif tokens[0] == 'search':
for suffix in tokens[1:]:
self.search.append(dns.name.from_text(suffix))
finally:
if want_close:
f.close()
if len(self.nameservers) == 0:
self.nameservers.append('127.0.0.1') | [
"def",
"read_resolv_conf",
"(",
"self",
",",
"f",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"str",
")",
"or",
"isinstance",
"(",
"f",
",",
"unicode",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"f",
",",
"'r'",
")",
"except",
"IOError",
":",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/resolver.py#L319-L352 | ||
RcppCore/RcppParallel | ff49e84602a1771c06bc39fdea995447564f2b7f | src/tbb/python/tbb/pool.py | python | OrderedResultCollector.notify_ready | (self, apply_result) | Called by the ApplyResult object (already registered via
register_result()) that it is now ready (ie. the Job's result
is available or an exception has been raised).
\param apply_result ApplyResult object telling us that the job
has been processed | Called by the ApplyResult object (already registered via
register_result()) that it is now ready (ie. the Job's result
is available or an exception has been raised).
\param apply_result ApplyResult object telling us that the job
has been processed | [
"Called",
"by",
"the",
"ApplyResult",
"object",
"(",
"already",
"registered",
"via",
"register_result",
"()",
")",
"that",
"it",
"is",
"now",
"ready",
"(",
"ie",
".",
"the",
"Job",
"s",
"result",
"is",
"available",
"or",
"an",
"exception",
"has",
"been",
... | def notify_ready(self, apply_result):
"""Called by the ApplyResult object (already registered via
register_result()) that it is now ready (ie. the Job's result
is available or an exception has been raised).
\param apply_result ApplyResult object telling us that the job
has been processed
"""
got_first = False
got_last = False
self._lock.acquire()
try:
assert self._remaining > 0
got_first = (len(self._results) == self._remaining)
self._remaining -= 1
got_last = (self._remaining == 0)
finally:
self._lock.release()
if self._to_notify is not None:
if self._as_iterator and got_first:
self._to_notify._set_value(iter(self))
elif not self._as_iterator and got_last:
try:
lst = [r.get(0) for r in self._results]
except:
self._to_notify._set_exception()
else:
self._to_notify._set_value(lst) | [
"def",
"notify_ready",
"(",
"self",
",",
"apply_result",
")",
":",
"got_first",
"=",
"False",
"got_last",
"=",
"False",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"assert",
"self",
".",
"_remaining",
">",
"0",
"got_first",
"=",
"(",
"l... | https://github.com/RcppCore/RcppParallel/blob/ff49e84602a1771c06bc39fdea995447564f2b7f/src/tbb/python/tbb/pool.py#L604-L631 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/contrib/onnx/mx2onnx/_op_translations.py | python | convert_elementwise_sub | (node, **kwargs) | return create_basic_op_node('Sub', node, kwargs) | Map MXNet's elemwise_sub operator attributes to onnx's Sub operator
and return the created node. | Map MXNet's elemwise_sub operator attributes to onnx's Sub operator
and return the created node. | [
"Map",
"MXNet",
"s",
"elemwise_sub",
"operator",
"attributes",
"to",
"onnx",
"s",
"Sub",
"operator",
"and",
"return",
"the",
"created",
"node",
"."
] | def convert_elementwise_sub(node, **kwargs):
"""Map MXNet's elemwise_sub operator attributes to onnx's Sub operator
and return the created node.
"""
return create_basic_op_node('Sub', node, kwargs) | [
"def",
"convert_elementwise_sub",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"create_basic_op_node",
"(",
"'Sub'",
",",
"node",
",",
"kwargs",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/mx2onnx/_op_translations.py#L1343-L1347 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | WorkingSet.find | (self, req) | return dist | Find a distribution matching requirement `req`
If there is an active distribution for the requested project, this
returns it as long as it meets the version requirement specified by
`req`. But, if there is an active distribution for the project and it
does *not* meet the `req` requirement, ``VersionConflict`` is raised.
If there is no active distribution for the requested project, ``None``
is returned. | Find a distribution matching requirement `req` | [
"Find",
"a",
"distribution",
"matching",
"requirement",
"req"
] | def find(self, req):
"""Find a distribution matching requirement `req`
If there is an active distribution for the requested project, this
returns it as long as it meets the version requirement specified by
`req`. But, if there is an active distribution for the project and it
does *not* meet the `req` requirement, ``VersionConflict`` is raised.
If there is no active distribution for the requested project, ``None``
is returned.
"""
dist = self.by_key.get(req.key)
if dist is not None and dist not in req:
# XXX add more info
raise VersionConflict(dist, req)
return dist | [
"def",
"find",
"(",
"self",
",",
"req",
")",
":",
"dist",
"=",
"self",
".",
"by_key",
".",
"get",
"(",
"req",
".",
"key",
")",
"if",
"dist",
"is",
"not",
"None",
"and",
"dist",
"not",
"in",
"req",
":",
"# XXX add more info",
"raise",
"VersionConflict... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L680-L694 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py | python | LabeledScale._adjust | (self, *args) | Adjust the label position according to the scale. | Adjust the label position according to the scale. | [
"Adjust",
"the",
"label",
"position",
"according",
"to",
"the",
"scale",
"."
] | def _adjust(self, *args):
"""Adjust the label position according to the scale."""
def adjust_label():
self.update_idletasks() # "force" scale redraw
x, y = self.scale.coords()
if self._label_top:
y = self.scale.winfo_y() - self.label.winfo_reqheight()
else:
y = self.scale.winfo_reqheight() + self.label.winfo_reqheight()
self.label.place_configure(x=x, y=y)
from_ = _to_number(self.scale['from'])
to = _to_number(self.scale['to'])
if to < from_:
from_, to = to, from_
newval = self._variable.get()
if not from_ <= newval <= to:
# value outside range, set value back to the last valid one
self.value = self._last_valid
return
self._last_valid = newval
self.label['text'] = newval
self.after_idle(adjust_label) | [
"def",
"_adjust",
"(",
"self",
",",
"*",
"args",
")",
":",
"def",
"adjust_label",
"(",
")",
":",
"self",
".",
"update_idletasks",
"(",
")",
"# \"force\" scale redraw",
"x",
",",
"y",
"=",
"self",
".",
"scale",
".",
"coords",
"(",
")",
"if",
"self",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py#L1582-L1607 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/xrc.py | python | XmlResource.SetDomain | (*args, **kwargs) | return _xrc.XmlResource_SetDomain(*args, **kwargs) | SetDomain(self, String domain) | SetDomain(self, String domain) | [
"SetDomain",
"(",
"self",
"String",
"domain",
")"
] | def SetDomain(*args, **kwargs):
"""SetDomain(self, String domain)"""
return _xrc.XmlResource_SetDomain(*args, **kwargs) | [
"def",
"SetDomain",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlResource_SetDomain",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/xrc.py#L222-L224 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py | python | _AsinhGrad | (op, grad) | Returns grad * 1/cosh(y). | Returns grad * 1/cosh(y). | [
"Returns",
"grad",
"*",
"1",
"/",
"cosh",
"(",
"y",
")",
"."
] | def _AsinhGrad(op, grad):
"""Returns grad * 1/cosh(y)."""
y = op.outputs[0]
with ops.control_dependencies([grad]):
y = math_ops.conj(y)
return grad / math_ops.cosh(y) | [
"def",
"_AsinhGrad",
"(",
"op",
",",
"grad",
")",
":",
"y",
"=",
"op",
".",
"outputs",
"[",
"0",
"]",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"grad",
"]",
")",
":",
"y",
"=",
"math_ops",
".",
"conj",
"(",
"y",
")",
"return",
"grad",... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/math_grad.py#L718-L723 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cgutils.py | python | global_constant | (builder_or_module, name, value, linkage='internal') | return data | Get or create a (LLVM module-)global constant with *name* or *value*. | Get or create a (LLVM module-)global constant with *name* or *value*. | [
"Get",
"or",
"create",
"a",
"(",
"LLVM",
"module",
"-",
")",
"global",
"constant",
"with",
"*",
"name",
"*",
"or",
"*",
"value",
"*",
"."
] | def global_constant(builder_or_module, name, value, linkage='internal'):
"""
Get or create a (LLVM module-)global constant with *name* or *value*.
"""
if isinstance(builder_or_module, ir.Module):
module = builder_or_module
else:
module = builder_or_module.module
data = module.add_global_variable(value.type, name=name)
data.linkage = linkage
data.global_constant = True
data.initializer = value
return data | [
"def",
"global_constant",
"(",
"builder_or_module",
",",
"name",
",",
"value",
",",
"linkage",
"=",
"'internal'",
")",
":",
"if",
"isinstance",
"(",
"builder_or_module",
",",
"ir",
".",
"Module",
")",
":",
"module",
"=",
"builder_or_module",
"else",
":",
"mo... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cgutils.py#L911-L923 | |
usdot-fhwa-stol/carma-platform | d9d9b93f9689b2c7dd607cf5432d5296fc1000f5 | guidance_plugin_validator/src/guidance_plugin_validator/guidance_plugin_components.py | python | OptionalControlComponents.__init__ | (self) | Default constructor for OptionalControlComponents | Default constructor for OptionalControlComponents | [
"Default",
"constructor",
"for",
"OptionalControlComponents"
] | def __init__(self):
"""Default constructor for OptionalControlComponents"""
# Validation results indicating whether control plugin's node publishes optional (but commonly useful) information to the plugin_discovery topic
self.has_plugin_discovery_available = False
self.has_plugin_discovery_activated = False | [
"def",
"__init__",
"(",
"self",
")",
":",
"# Validation results indicating whether control plugin's node publishes optional (but commonly useful) information to the plugin_discovery topic",
"self",
".",
"has_plugin_discovery_available",
"=",
"False",
"self",
".",
"has_plugin_discovery_ac... | https://github.com/usdot-fhwa-stol/carma-platform/blob/d9d9b93f9689b2c7dd607cf5432d5296fc1000f5/guidance_plugin_validator/src/guidance_plugin_validator/guidance_plugin_components.py#L398-L403 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/core/formatters.py | python | format_display_data | (obj, include=None, exclude=None) | return InteractiveShell.instance().display_formatter.format(
obj,
include,
exclude
) | Return a format data dict for an object.
By default all format types will be computed.
Parameters
----------
obj : object
The Python object whose format data will be computed.
Returns
-------
format_dict : dict
A dictionary of key/value pairs, one or each format that was
generated for the object. The keys are the format types, which
will usually be MIME type strings and the values and JSON'able
data structure containing the raw data for the representation in
that format.
include : list or tuple, optional
A list of format type strings (MIME types) to include in the
format data dict. If this is set *only* the format types included
in this list will be computed.
exclude : list or tuple, optional
A list of format type string (MIME types) to exclude in the format
data dict. If this is set all format types will be computed,
except for those included in this argument. | Return a format data dict for an object. | [
"Return",
"a",
"format",
"data",
"dict",
"for",
"an",
"object",
"."
] | def format_display_data(obj, include=None, exclude=None):
"""Return a format data dict for an object.
By default all format types will be computed.
Parameters
----------
obj : object
The Python object whose format data will be computed.
Returns
-------
format_dict : dict
A dictionary of key/value pairs, one or each format that was
generated for the object. The keys are the format types, which
will usually be MIME type strings and the values and JSON'able
data structure containing the raw data for the representation in
that format.
include : list or tuple, optional
A list of format type strings (MIME types) to include in the
format data dict. If this is set *only* the format types included
in this list will be computed.
exclude : list or tuple, optional
A list of format type string (MIME types) to exclude in the format
data dict. If this is set all format types will be computed,
except for those included in this argument.
"""
from .interactiveshell import InteractiveShell
return InteractiveShell.instance().display_formatter.format(
obj,
include,
exclude
) | [
"def",
"format_display_data",
"(",
"obj",
",",
"include",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"from",
".",
"interactiveshell",
"import",
"InteractiveShell",
"return",
"InteractiveShell",
".",
"instance",
"(",
")",
".",
"display_formatter",
".",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/formatters.py#L991-L1024 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PGChoices.AddAsSorted | (*args, **kwargs) | return _propgrid.PGChoices_AddAsSorted(*args, **kwargs) | AddAsSorted(self, String label, int value=INT_MAX) | AddAsSorted(self, String label, int value=INT_MAX) | [
"AddAsSorted",
"(",
"self",
"String",
"label",
"int",
"value",
"=",
"INT_MAX",
")"
] | def AddAsSorted(*args, **kwargs):
"""AddAsSorted(self, String label, int value=INT_MAX)"""
return _propgrid.PGChoices_AddAsSorted(*args, **kwargs) | [
"def",
"AddAsSorted",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGChoices_AddAsSorted",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L242-L244 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/jpsro.py | python | _mwcce | (meta_game, per_player_repeats, ignore_repeats=False) | return dist, dict() | Maximum welfare CCE. | Maximum welfare CCE. | [
"Maximum",
"welfare",
"CCE",
"."
] | def _mwcce(meta_game, per_player_repeats, ignore_repeats=False):
"""Maximum welfare CCE."""
del ignore_repeats
num_players = len(per_player_repeats)
cost = np.ravel(np.sum(meta_game, axis=0))
a_mat, _ = _cce_constraints(
meta_game, [0.0] * num_players, remove_null=True,
zero_tolerance=1e-8)
e_vec = np.zeros([a_mat.shape[0]])
x, _ = _linear(meta_game, a_mat, e_vec, cost=cost)
dist = np.reshape(x, meta_game.shape[1:])
return dist, dict() | [
"def",
"_mwcce",
"(",
"meta_game",
",",
"per_player_repeats",
",",
"ignore_repeats",
"=",
"False",
")",
":",
"del",
"ignore_repeats",
"num_players",
"=",
"len",
"(",
"per_player_repeats",
")",
"cost",
"=",
"np",
".",
"ravel",
"(",
"np",
".",
"sum",
"(",
"m... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/jpsro.py#L970-L981 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/pylib/utils/logdog_helper.py | python | open_text | (name) | return get_logdog_client().open_text(name) | Returns a file like object which you can write to.
Args:
name: Name of the logdog stream.
Returns:
A file like object. close() file when done. | Returns a file like object which you can write to. | [
"Returns",
"a",
"file",
"like",
"object",
"which",
"you",
"can",
"write",
"to",
"."
] | def open_text(name):
"""Returns a file like object which you can write to.
Args:
name: Name of the logdog stream.
Returns:
A file like object. close() file when done.
"""
logging.info('Opening text logdog stream, %s', name)
return get_logdog_client().open_text(name) | [
"def",
"open_text",
"(",
"name",
")",
":",
"logging",
".",
"info",
"(",
"'Opening text logdog stream, %s'",
",",
"name",
")",
"return",
"get_logdog_client",
"(",
")",
".",
"open_text",
"(",
"name",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/pylib/utils/logdog_helper.py#L45-L55 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.