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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/sax/xmlreader.py | python | IncrementalParser.prepareParser | (self, source) | This method is called by the parse implementation to allow
the SAX 2.0 driver to prepare itself for parsing. | This method is called by the parse implementation to allow
the SAX 2.0 driver to prepare itself for parsing. | [
"This",
"method",
"is",
"called",
"by",
"the",
"parse",
"implementation",
"to",
"allow",
"the",
"SAX",
"2",
".",
"0",
"driver",
"to",
"prepare",
"itself",
"for",
"parsing",
"."
] | def prepareParser(self, source):
"""This method is called by the parse implementation to allow
the SAX 2.0 driver to prepare itself for parsing."""
raise NotImplementedError("prepareParser must be overridden!") | [
"def",
"prepareParser",
"(",
"self",
",",
"source",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"prepareParser must be overridden!\"",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/sax/xmlreader.py#L136-L139 | ||
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py | python | xmlDoc.isRef | (self, elem, attr) | return ret | Determine whether an attribute is of type Ref. In case we
have DTD(s) then this is simple, otherwise we use an
heuristic: name Ref (upper or lowercase). | Determine whether an attribute is of type Ref. In case we
have DTD(s) then this is simple, otherwise we use an
heuristic: name Ref (upper or lowercase). | [
"Determine",
"whether",
"an",
"attribute",
"is",
"of",
"type",
"Ref",
".",
"In",
"case",
"we",
"have",
"DTD",
"(",
"s",
")",
"then",
"this",
"is",
"simple",
"otherwise",
"we",
"use",
"an",
"heuristic",
":",
"name",
"Ref",
"(",
"upper",
"or",
"lowercase... | def isRef(self, elem, attr):
"""Determine whether an attribute is of type Ref. In case we
have DTD(s) then this is simple, otherwise we use an
heuristic: name Ref (upper or lowercase). """
if elem is None: elem__o = None
else: elem__o = elem._o
if attr is None: attr__o = None
else: attr__o = attr._o
ret = libxml2mod.xmlIsRef(self._o, elem__o, attr__o)
return ret | [
"def",
"isRef",
"(",
"self",
",",
"elem",
",",
"attr",
")",
":",
"if",
"elem",
"is",
"None",
":",
"elem__o",
"=",
"None",
"else",
":",
"elem__o",
"=",
"elem",
".",
"_o",
"if",
"attr",
"is",
"None",
":",
"attr__o",
"=",
"None",
"else",
":",
"attr_... | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L4562-L4571 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | v8_5_1/tools/grokdump.py | python | InspectionShell.do_sh | (self, none) | Search for the V8 Heap object in all available memory regions. You
might get lucky and find this rare treasure full of invaluable
information. | Search for the V8 Heap object in all available memory regions. You
might get lucky and find this rare treasure full of invaluable
information. | [
"Search",
"for",
"the",
"V8",
"Heap",
"object",
"in",
"all",
"available",
"memory",
"regions",
".",
"You",
"might",
"get",
"lucky",
"and",
"find",
"this",
"rare",
"treasure",
"full",
"of",
"invaluable",
"information",
"."
] | def do_sh(self, none):
"""
Search for the V8 Heap object in all available memory regions. You
might get lucky and find this rare treasure full of invaluable
information.
"""
raise NotImplementedError | [
"def",
"do_sh",
"(",
"self",
",",
"none",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/v8_5_1/tools/grokdump.py#L3060-L3066 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pydoc.py | python | HTMLDoc.formatvalue | (self, object) | return self.grey('=' + self.repr(object)) | Format an argument default value as text. | Format an argument default value as text. | [
"Format",
"an",
"argument",
"default",
"value",
"as",
"text",
"."
] | def formatvalue(self, object):
"""Format an argument default value as text."""
return self.grey('=' + self.repr(object)) | [
"def",
"formatvalue",
"(",
"self",
",",
"object",
")",
":",
"return",
"self",
".",
"grey",
"(",
"'='",
"+",
"self",
".",
"repr",
"(",
"object",
")",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pydoc.py#L859-L861 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/models/alert_group.py | python | _FetchAlertGroups | (max_start_revision) | return groups | Fetches AlertGroup entities up to a given revision. | Fetches AlertGroup entities up to a given revision. | [
"Fetches",
"AlertGroup",
"entities",
"up",
"to",
"a",
"given",
"revision",
"."
] | def _FetchAlertGroups(max_start_revision):
"""Fetches AlertGroup entities up to a given revision."""
query = AlertGroup.query(AlertGroup.start_revision <= max_start_revision)
query = query.order(-AlertGroup.start_revision)
groups = query.fetch(limit=_MAX_GROUPS_TO_FETCH)
return groups | [
"def",
"_FetchAlertGroups",
"(",
"max_start_revision",
")",
":",
"query",
"=",
"AlertGroup",
".",
"query",
"(",
"AlertGroup",
".",
"start_revision",
"<=",
"max_start_revision",
")",
"query",
"=",
"query",
".",
"order",
"(",
"-",
"AlertGroup",
".",
"start_revisio... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/models/alert_group.py#L74-L80 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/genpy/src/genpy/generate_struct.py | python | pack | (pattern, vars) | return serialize("_struct_%s.pack(%s)"%(pattern, vars)) | create struct.pack call for when pattern is a string pattern
:param pattern: pattern for pack, ``str``
:param vars: name of variables to pack, ``str`` | create struct.pack call for when pattern is a string pattern
:param pattern: pattern for pack, ``str``
:param vars: name of variables to pack, ``str`` | [
"create",
"struct",
".",
"pack",
"call",
"for",
"when",
"pattern",
"is",
"a",
"string",
"pattern",
":",
"param",
"pattern",
":",
"pattern",
"for",
"pack",
"str",
":",
"param",
"vars",
":",
"name",
"of",
"variables",
"to",
"pack",
"str"
] | def pack(pattern, vars):
"""
create struct.pack call for when pattern is a string pattern
:param pattern: pattern for pack, ``str``
:param vars: name of variables to pack, ``str``
"""
# - store pattern in context
pattern = reduce_pattern(pattern)
add_pattern(pattern)
return serialize("_struct_%s.pack(%s)"%(pattern, vars)) | [
"def",
"pack",
"(",
"pattern",
",",
"vars",
")",
":",
"# - store pattern in context",
"pattern",
"=",
"reduce_pattern",
"(",
"pattern",
")",
"add_pattern",
"(",
"pattern",
")",
"return",
"serialize",
"(",
"\"_struct_%s.pack(%s)\"",
"%",
"(",
"pattern",
",",
"var... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/genpy/src/genpy/generate_struct.py#L114-L123 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/handlers.py | python | SMTPHandler.getSubject | (self, record) | return self.subject | Determine the subject for the email.
If you want to specify a subject line which is record-dependent,
override this method. | Determine the subject for the email. | [
"Determine",
"the",
"subject",
"for",
"the",
"email",
"."
] | def getSubject(self, record):
"""
Determine the subject for the email.
If you want to specify a subject line which is record-dependent,
override this method.
"""
return self.subject | [
"def",
"getSubject",
"(",
"self",
",",
"record",
")",
":",
"return",
"self",
".",
"subject"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/logging/handlers.py#L907-L914 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/util/tf_export.py | python | get_v2_names | (symbol) | return names_v2 | Get a list of TF 2.0 names for this symbol.
Args:
symbol: symbol to get API names for.
Returns:
List of all API names for this symbol including TensorFlow and
Estimator names. | Get a list of TF 2.0 names for this symbol. | [
"Get",
"a",
"list",
"of",
"TF",
"2",
".",
"0",
"names",
"for",
"this",
"symbol",
"."
] | def get_v2_names(symbol):
"""Get a list of TF 2.0 names for this symbol.
Args:
symbol: symbol to get API names for.
Returns:
List of all API names for this symbol including TensorFlow and
Estimator names.
"""
names_v2 = []
tensorflow_api_attr = API_ATTRS[TENSORFLOW_API_NAME].names
estimator_api_attr = API_ATTRS[ESTIMATOR_API_NAME].names
keras_api_attr = API_ATTRS[KERAS_API_NAME].names
if not hasattr(symbol, '__dict__'):
return names_v2
if tensorflow_api_attr in symbol.__dict__:
names_v2.extend(getattr(symbol, tensorflow_api_attr))
if estimator_api_attr in symbol.__dict__:
names_v2.extend(getattr(symbol, estimator_api_attr))
if keras_api_attr in symbol.__dict__:
names_v2.extend(getattr(symbol, keras_api_attr))
return names_v2 | [
"def",
"get_v2_names",
"(",
"symbol",
")",
":",
"names_v2",
"=",
"[",
"]",
"tensorflow_api_attr",
"=",
"API_ATTRS",
"[",
"TENSORFLOW_API_NAME",
"]",
".",
"names",
"estimator_api_attr",
"=",
"API_ATTRS",
"[",
"ESTIMATOR_API_NAME",
"]",
".",
"names",
"keras_api_attr... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/util/tf_export.py#L184-L207 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | lldb/third_party/Python/module/pexpect-4.6/pexpect/expect.py | python | searcher_re.__init__ | (self, patterns) | This creates an instance that searches for 'patterns' Where
'patterns' may be a list or other sequence of compiled regular
expressions, or the EOF or TIMEOUT types. | This creates an instance that searches for 'patterns' Where
'patterns' may be a list or other sequence of compiled regular
expressions, or the EOF or TIMEOUT types. | [
"This",
"creates",
"an",
"instance",
"that",
"searches",
"for",
"patterns",
"Where",
"patterns",
"may",
"be",
"a",
"list",
"or",
"other",
"sequence",
"of",
"compiled",
"regular",
"expressions",
"or",
"the",
"EOF",
"or",
"TIMEOUT",
"types",
"."
] | def __init__(self, patterns):
'''This creates an instance that searches for 'patterns' Where
'patterns' may be a list or other sequence of compiled regular
expressions, or the EOF or TIMEOUT types.'''
self.eof_index = -1
self.timeout_index = -1
self._searches = []
for n, s in zip(list(range(len(patterns))), patterns):
if s is EOF:
self.eof_index = n
continue
if s is TIMEOUT:
self.timeout_index = n
continue
self._searches.append((n, s)) | [
"def",
"__init__",
"(",
"self",
",",
"patterns",
")",
":",
"self",
".",
"eof_index",
"=",
"-",
"1",
"self",
".",
"timeout_index",
"=",
"-",
"1",
"self",
".",
"_searches",
"=",
"[",
"]",
"for",
"n",
",",
"s",
"in",
"zip",
"(",
"list",
"(",
"range"... | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/pexpect-4.6/pexpect/expect.py#L239-L254 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatnotebook.py | python | FNBRendererRibbonTabs.CalcTabWidth | (self, pageContainer, tabIdx, tabHeight) | return tabWidth | Calculates the width of the input tab.
:param `pageContainer`: an instance of :class:`FlatNotebook`;
:param `tabIdx`: the index of the input tab;
:param `tabHeight`: the height of the tab. | Calculates the width of the input tab. | [
"Calculates",
"the",
"width",
"of",
"the",
"input",
"tab",
"."
] | def CalcTabWidth(self, pageContainer, tabIdx, tabHeight):
"""
Calculates the width of the input tab.
:param `pageContainer`: an instance of :class:`FlatNotebook`;
:param `tabIdx`: the index of the input tab;
:param `tabHeight`: the height of the tab.
"""
pc = pageContainer
dc = wx.MemoryDC()
dc.SelectObject(wx.EmptyBitmap(1,1))
font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
if pc.IsDefaultTabs():
shapePoints = int(tabHeight*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi))
dc.SetFont(font)
width, pom = dc.GetTextExtent(pc.GetPageText(tabIdx))
# Set a minimum size to a tab
if width < 20:
width = 20
tabWidth = 2*pc._pParent.GetPadding() + width
# Style to add a small 'x' button on the top right
# of the tab
if pc.HasAGWFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection():
# The xpm image that contains the 'x' button is 9 pixels
spacer = 9
if pc.HasAGWFlag(FNB_VC8):
spacer = 4
tabWidth += pc._pParent.GetPadding() + spacer
if pc.IsDefaultTabs():
# Default style
tabWidth += 2*shapePoints
hasImage = pc._ImageList != None and pc._pagesInfoVec[tabIdx].GetImageIndex() != -1
# For VC71 style, we only add the icon size (16 pixels)
if hasImage:
if not pc.IsDefaultTabs():
tabWidth += 16 + pc._pParent.GetPadding()
else:
# Default style
tabWidth += 16 + pc._pParent.GetPadding() + shapePoints/2
return tabWidth | [
"def",
"CalcTabWidth",
"(",
"self",
",",
"pageContainer",
",",
"tabIdx",
",",
"tabHeight",
")",
":",
"pc",
"=",
"pageContainer",
"dc",
"=",
"wx",
".",
"MemoryDC",
"(",
")",
"dc",
".",
"SelectObject",
"(",
"wx",
".",
"EmptyBitmap",
"(",
"1",
",",
"1",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatnotebook.py#L3619-L3671 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/intelhex/__init__.py | python | Record.extended_segment_address | (usba) | return Record._from_bytes(b) | Return Extended Segment Address Record.
@param usba Upper Segment Base Address.
@return String representation of Intel Hex USBA record. | Return Extended Segment Address Record.
@param usba Upper Segment Base Address. | [
"Return",
"Extended",
"Segment",
"Address",
"Record",
".",
"@param",
"usba",
"Upper",
"Segment",
"Base",
"Address",
"."
] | def extended_segment_address(usba):
"""Return Extended Segment Address Record.
@param usba Upper Segment Base Address.
@return String representation of Intel Hex USBA record.
"""
b = [2, 0, 0, 0x02, (usba>>8)&0x0FF, usba&0x0FF]
return Record._from_bytes(b) | [
"def",
"extended_segment_address",
"(",
"usba",
")",
":",
"b",
"=",
"[",
"2",
",",
"0",
",",
"0",
",",
"0x02",
",",
"(",
"usba",
">>",
"8",
")",
"&",
"0x0FF",
",",
"usba",
"&",
"0x0FF",
"]",
"return",
"Record",
".",
"_from_bytes",
"(",
"b",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/intelhex/__init__.py#L1178-L1185 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_parser.py | python | p_sort_lcb_names_rcb | (p) | sort : LCB names RCB | sort : LCB names RCB | [
"sort",
":",
"LCB",
"names",
"RCB"
] | def p_sort_lcb_names_rcb(p):
'sort : LCB names RCB'
p[0] = EnumeratedSort(*[Atom(n) for n in p[2]]) | [
"def",
"p_sort_lcb_names_rcb",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"EnumeratedSort",
"(",
"*",
"[",
"Atom",
"(",
"n",
")",
"for",
"n",
"in",
"p",
"[",
"2",
"]",
"]",
")"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L1438-L1440 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/logging/config.py | python | BaseConfigurator.convert | (self, value) | return value | Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do. | Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do. | [
"Convert",
"values",
"to",
"an",
"appropriate",
"type",
".",
"dicts",
"lists",
"and",
"tuples",
"are",
"replaced",
"by",
"their",
"converting",
"alternatives",
".",
"Strings",
"are",
"checked",
"to",
"see",
"if",
"they",
"have",
"a",
"conversion",
"format",
... | def convert(self, value):
"""
Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do.
"""
if not isinstance(value, ConvertingDict) and isinstance(value, dict):
value = ConvertingDict(value)
value.configurator = self
elif not isinstance(value, ConvertingList) and isinstance(value, list):
value = ConvertingList(value)
value.configurator = self
elif not isinstance(value, ConvertingTuple) and\
isinstance(value, tuple):
value = ConvertingTuple(value)
value.configurator = self
elif isinstance(value, basestring): # str for py3k
m = self.CONVERT_PATTERN.match(value)
if m:
d = m.groupdict()
prefix = d['prefix']
converter = self.value_converters.get(prefix, None)
if converter:
suffix = d['suffix']
converter = getattr(self, converter)
value = converter(suffix)
return value | [
"def",
"convert",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"ConvertingDict",
")",
"and",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"value",
"=",
"ConvertingDict",
"(",
"value",
")",
"value",
".",
"conf... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/logging/config.py#L450-L476 | |
ppizarro/coursera | b39847928df4d9d5986b801085c025e8e9122b6a | Learn to Program: Crafting Quality Code/assignment 1/a1-buggy3.py | python | num_buses | (n) | (int) -> int
Precondition: n >= 0
Return the minimum number of buses required to transport n people.
Each bus can hold 50 people.
>>> num_buses(75)
2 | (int) -> int | [
"(",
"int",
")",
"-",
">",
"int"
] | def num_buses(n):
""" (int) -> int
Precondition: n >= 0
Return the minimum number of buses required to transport n people.
Each bus can hold 50 people.
>>> num_buses(75)
2
"""
if n!= 0 and n < 50 :
# covers children less than 50 and not equal to zero
return 1
if (n%50)== 0 :
# covers zero and divisibles of 50
return int(n/50)
else :
## covers all the odd number of children example 51,103,etc
return n// 50 + 1 | [
"def",
"num_buses",
"(",
"n",
")",
":",
"if",
"n",
"!=",
"0",
"and",
"n",
"<",
"50",
":",
"# covers children less than 50 and not equal to zero",
"return",
"1",
"if",
"(",
"n",
"%",
"50",
")",
"==",
"0",
":",
"# covers zero and divisibles of 50",
"return",
... | https://github.com/ppizarro/coursera/blob/b39847928df4d9d5986b801085c025e8e9122b6a/Learn to Program: Crafting Quality Code/assignment 1/a1-buggy3.py#L1-L21 | ||
larroy/clearskies_core | 3574ddf0edc8555454c7044126e786a6c29444dc | tools/gyp/pylib/gyp/MSVSVersion.py | python | VisualStudioVersion.ProjectExtension | (self) | return self.uses_vcxproj and '.vcxproj' or '.vcproj' | Returns the file extension for the project. | Returns the file extension for the project. | [
"Returns",
"the",
"file",
"extension",
"for",
"the",
"project",
"."
] | def ProjectExtension(self):
"""Returns the file extension for the project."""
return self.uses_vcxproj and '.vcxproj' or '.vcproj' | [
"def",
"ProjectExtension",
"(",
"self",
")",
":",
"return",
"self",
".",
"uses_vcxproj",
"and",
"'.vcxproj'",
"or",
"'.vcproj'"
] | https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/MSVSVersion.py#L54-L56 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | SplitterWindow.GetSashGravity | (*args, **kwargs) | return _windows_.SplitterWindow_GetSashGravity(*args, **kwargs) | GetSashGravity(self) -> double
Gets the sash gravity.
:see: `SetSashGravity` | GetSashGravity(self) -> double | [
"GetSashGravity",
"(",
"self",
")",
"-",
">",
"double"
] | def GetSashGravity(*args, **kwargs):
"""
GetSashGravity(self) -> double
Gets the sash gravity.
:see: `SetSashGravity`
"""
return _windows_.SplitterWindow_GetSashGravity(*args, **kwargs) | [
"def",
"GetSashGravity",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"SplitterWindow_GetSashGravity",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L1585-L1594 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Scanner/Dir.py | python | scan_on_disk | (node, env, path=()) | return scan_in_memory(node, env, path) | Scans a directory for on-disk files and directories therein.
Looking up the entries will add these to the in-memory Node tree
representation of the file system, so all we have to do is just
that and then call the in-memory scanning function. | Scans a directory for on-disk files and directories therein. | [
"Scans",
"a",
"directory",
"for",
"on",
"-",
"disk",
"files",
"and",
"directories",
"therein",
"."
] | def scan_on_disk(node, env, path=()):
"""
Scans a directory for on-disk files and directories therein.
Looking up the entries will add these to the in-memory Node tree
representation of the file system, so all we have to do is just
that and then call the in-memory scanning function.
"""
try:
flist = node.fs.listdir(node.get_abspath())
except (IOError, OSError):
return []
e = node.Entry
for f in filter(do_not_scan, flist):
# Add ./ to the beginning of the file name so if it begins with a
# '#' we don't look it up relative to the top-level directory.
e('./' + f)
return scan_in_memory(node, env, path) | [
"def",
"scan_on_disk",
"(",
"node",
",",
"env",
",",
"path",
"=",
"(",
")",
")",
":",
"try",
":",
"flist",
"=",
"node",
".",
"fs",
".",
"listdir",
"(",
"node",
".",
"get_abspath",
"(",
")",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
":",... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Scanner/Dir.py#L71-L88 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | IncrementalSelfTestResponse.toTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def toTpm(self, buf):
""" TpmMarshaller method """
buf.writeValArr(self.toDoList, 2) | [
"def",
"toTpm",
"(",
"self",
",",
"buf",
")",
":",
"buf",
".",
"writeValArr",
"(",
"self",
".",
"toDoList",
",",
"2",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L9202-L9204 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/RecoTau/python/ValidationUtils.py | python | SpawnPSet | (lArgument, subPset) | return ret | SpawnPSet(lArgument, subPset) --> cms.PSet\n
lArgument is a list containing a list of three strings/values:\n
1-name to give to the spawned pset\n
2-variable(s) to be changed\n
3-value(s) of the variable(s): SAME LENGTH OF 2-!\n
Supported types: int string float(converted to double) | SpawnPSet(lArgument, subPset) --> cms.PSet\n
lArgument is a list containing a list of three strings/values:\n
1-name to give to the spawned pset\n
2-variable(s) to be changed\n
3-value(s) of the variable(s): SAME LENGTH OF 2-!\n
Supported types: int string float(converted to double) | [
"SpawnPSet",
"(",
"lArgument",
"subPset",
")",
"--",
">",
"cms",
".",
"PSet",
"\\",
"n",
"lArgument",
"is",
"a",
"list",
"containing",
"a",
"list",
"of",
"three",
"strings",
"/",
"values",
":",
"\\",
"n",
"1",
"-",
"name",
"to",
"give",
"to",
"the",
... | def SpawnPSet(lArgument, subPset):
"""SpawnPSet(lArgument, subPset) --> cms.PSet\n
lArgument is a list containing a list of three strings/values:\n
1-name to give to the spawned pset\n
2-variable(s) to be changed\n
3-value(s) of the variable(s): SAME LENGTH OF 2-!\n
Supported types: int string float(converted to double)"""
ret = cms.PSet()
for spawn in lArgument:
if len(spawn) != 3:
print("ERROR! SpawnPSet uses argument of three data\n")
print(self.__doc__)
return None
if len(spawn[1]) != len(spawn[2]):
print("ERROR! Lists of arguments to replace must have the same length")
print(self.__doc__)
return None
spawnArg = copy.deepcopy(subPset)
for par, val in zip(spawn[1],spawn[2]):
if isinstance(val, str) :
setattr(spawnArg,par,cms.string(val))
elif isinstance(val, int) :
setattr(spawnArg,par,cms.int32(val))
elif isinstance(val, float) :
setattr(spawnArg,par,cms.double(val))
setattr(ret,spawn[0],spawnArg)
return ret | [
"def",
"SpawnPSet",
"(",
"lArgument",
",",
"subPset",
")",
":",
"ret",
"=",
"cms",
".",
"PSet",
"(",
")",
"for",
"spawn",
"in",
"lArgument",
":",
"if",
"len",
"(",
"spawn",
")",
"!=",
"3",
":",
"print",
"(",
"\"ERROR! SpawnPSet uses argument of three data\... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTau/python/ValidationUtils.py#L134-L160 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/fuzzbunch/fuzzbunch.py | python | Fuzzbunch.do_show | (self, input) | Show plugin info | Show plugin info | [
"Show",
"plugin",
"info"
] | def do_show(self, input):
"""Show plugin info"""
argc, argv = util.parseinput(input, 2)
if argc == 0:
self.io.print_module_types({'modules' : self.get_active_plugin_names()})
elif argc == 1:
plugins = [ (plugin.getName(), plugin.getVersion())
for plugin in self.get_manager(argv[0]).get_plugins() ]
args = {'module' : argv[0],
'plugins' : plugins}
self.io.print_module_lists(args)
elif argc == 2:
self.get_manager(argv[0]).print_info(argv[1]) | [
"def",
"do_show",
"(",
"self",
",",
"input",
")",
":",
"argc",
",",
"argv",
"=",
"util",
".",
"parseinput",
"(",
"input",
",",
"2",
")",
"if",
"argc",
"==",
"0",
":",
"self",
".",
"io",
".",
"print_module_types",
"(",
"{",
"'modules'",
":",
"self",... | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/fuzzbunch.py#L553-L566 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/saved_model/signature_def_utils_impl.py | python | load_op_from_signature_def | (signature_def, key, import_scope=None) | Load an Op from a SignatureDef created by op_signature_def().
Args:
signature_def: a SignatureDef proto
key: string key to op in the SignatureDef outputs.
import_scope: Scope used to import the op
Returns:
Op (or possibly Tensor) in the graph with the same name as saved in the
SignatureDef.
Raises:
NotFoundError: If the op could not be found in the graph. | Load an Op from a SignatureDef created by op_signature_def(). | [
"Load",
"an",
"Op",
"from",
"a",
"SignatureDef",
"created",
"by",
"op_signature_def",
"()",
"."
] | def load_op_from_signature_def(signature_def, key, import_scope=None):
"""Load an Op from a SignatureDef created by op_signature_def().
Args:
signature_def: a SignatureDef proto
key: string key to op in the SignatureDef outputs.
import_scope: Scope used to import the op
Returns:
Op (or possibly Tensor) in the graph with the same name as saved in the
SignatureDef.
Raises:
NotFoundError: If the op could not be found in the graph.
"""
tensor_info = signature_def.outputs[key]
try:
# The init and train ops are not strictly enforced to be operations, so
# retrieve any graph element (can be either op or tensor).
return utils.get_element_from_tensor_info(
tensor_info, import_scope=import_scope)
except KeyError:
raise errors.NotFoundError(
None, None,
f'The key "{key}" could not be found in the graph. Please make sure the'
' SavedModel was created by the internal _SavedModelBuilder. If you '
'are using the public API, please make sure the SignatureDef in the '
f'SavedModel does not contain the key "{key}".') | [
"def",
"load_op_from_signature_def",
"(",
"signature_def",
",",
"key",
",",
"import_scope",
"=",
"None",
")",
":",
"tensor_info",
"=",
"signature_def",
".",
"outputs",
"[",
"key",
"]",
"try",
":",
"# The init and train ops are not strictly enforced to be operations, so",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/signature_def_utils_impl.py#L373-L400 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/rnn.py | python | state_saving_rnn | (cell, inputs, state_saver, state_name,
sequence_length=None, scope=None) | return (outputs, state) | RNN that accepts a state saver for time-truncated RNN calculation.
Args:
cell: An instance of `RNNCell`.
inputs: A length T list of inputs, each a `Tensor` of shape
`[batch_size, input_size]`.
state_saver: A state saver object with methods `state` and `save_state`.
state_name: Python string or tuple of strings. The name to use with the
state_saver. If the cell returns tuples of states (i.e.,
`cell.state_size` is a tuple) then `state_name` should be a tuple of
strings having the same length as `cell.state_size`. Otherwise it should
be a single string.
sequence_length: (optional) An int32/int64 vector size [batch_size].
See the documentation for rnn() for more details about sequence_length.
scope: VariableScope for the created subgraph; defaults to "RNN".
Returns:
A pair (outputs, state) where:
outputs is a length T list of outputs (one for each input)
states is the final state
Raises:
TypeError: If `cell` is not an instance of RNNCell.
ValueError: If `inputs` is `None` or an empty list, or if the arity and
type of `state_name` does not match that of `cell.state_size`. | RNN that accepts a state saver for time-truncated RNN calculation. | [
"RNN",
"that",
"accepts",
"a",
"state",
"saver",
"for",
"time",
"-",
"truncated",
"RNN",
"calculation",
"."
] | def state_saving_rnn(cell, inputs, state_saver, state_name,
sequence_length=None, scope=None):
"""RNN that accepts a state saver for time-truncated RNN calculation.
Args:
cell: An instance of `RNNCell`.
inputs: A length T list of inputs, each a `Tensor` of shape
`[batch_size, input_size]`.
state_saver: A state saver object with methods `state` and `save_state`.
state_name: Python string or tuple of strings. The name to use with the
state_saver. If the cell returns tuples of states (i.e.,
`cell.state_size` is a tuple) then `state_name` should be a tuple of
strings having the same length as `cell.state_size`. Otherwise it should
be a single string.
sequence_length: (optional) An int32/int64 vector size [batch_size].
See the documentation for rnn() for more details about sequence_length.
scope: VariableScope for the created subgraph; defaults to "RNN".
Returns:
A pair (outputs, state) where:
outputs is a length T list of outputs (one for each input)
states is the final state
Raises:
TypeError: If `cell` is not an instance of RNNCell.
ValueError: If `inputs` is `None` or an empty list, or if the arity and
type of `state_name` does not match that of `cell.state_size`.
"""
state_size = cell.state_size
state_is_tuple = nest.is_sequence(state_size)
state_name_tuple = nest.is_sequence(state_name)
if state_is_tuple != state_name_tuple:
raise ValueError(
"state_name should be the same type as cell.state_size. "
"state_name: %s, cell.state_size: %s"
% (str(state_name), str(state_size)))
if state_is_tuple:
state_name_flat = nest.flatten(state_name)
state_size_flat = nest.flatten(state_size)
if len(state_name_flat) != len(state_size_flat):
raise ValueError("#elems(state_name) != #elems(state_size): %d vs. %d"
% (len(state_name_flat), len(state_size_flat)))
initial_state = nest.pack_sequence_as(
structure=state_size,
flat_sequence=[state_saver.state(s) for s in state_name_flat])
else:
initial_state = state_saver.state(state_name)
(outputs, state) = rnn(cell, inputs, initial_state=initial_state,
sequence_length=sequence_length, scope=scope)
if state_is_tuple:
flat_state = nest.flatten(state)
state_name = nest.flatten(state_name)
save_state = [state_saver.save_state(name, substate)
for name, substate in zip(state_name, flat_state)]
else:
save_state = [state_saver.save_state(state_name, state)]
with ops.control_dependencies(save_state):
last_output = outputs[-1]
flat_last_output = nest.flatten(last_output)
flat_last_output = [
array_ops.identity(output) for output in flat_last_output]
outputs[-1] = nest.pack_sequence_as(structure=last_output,
flat_sequence=flat_last_output)
return (outputs, state) | [
"def",
"state_saving_rnn",
"(",
"cell",
",",
"inputs",
",",
"state_saver",
",",
"state_name",
",",
"sequence_length",
"=",
"None",
",",
"scope",
"=",
"None",
")",
":",
"state_size",
"=",
"cell",
".",
"state_size",
"state_is_tuple",
"=",
"nest",
".",
"is_sequ... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/rnn.py#L233-L304 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/SocketServer.py | python | BaseServer.finish_request | (self, request, client_address) | Finish one request by instantiating RequestHandlerClass. | Finish one request by instantiating RequestHandlerClass. | [
"Finish",
"one",
"request",
"by",
"instantiating",
"RequestHandlerClass",
"."
] | def finish_request(self, request, client_address):
"""Finish one request by instantiating RequestHandlerClass."""
self.RequestHandlerClass(request, client_address, self) | [
"def",
"finish_request",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"self",
".",
"RequestHandlerClass",
"(",
"request",
",",
"client_address",
",",
"self",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/SocketServer.py#L332-L334 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py | python | obj_header.get_capi_translations | (self) | return map | Return a dictionary that maps C++ terminology to C API terminology. | Return a dictionary that maps C++ terminology to C API terminology. | [
"Return",
"a",
"dictionary",
"that",
"maps",
"C",
"++",
"terminology",
"to",
"C",
"API",
"terminology",
"."
] | def get_capi_translations(self):
""" Return a dictionary that maps C++ terminology to C API terminology.
"""
# strings that will be changed in C++ comments
map = {
'class' : 'structure',
'Class' : 'Structure',
'interface' : 'structure',
'Interface' : 'Structure',
'true' : 'true (1)',
'false' : 'false (0)',
'empty' : 'NULL',
'method' : 'function'
}
# add mappings for all classes and functions
funcs = self.get_funcs()
for func in funcs:
map[func.get_name()+'()'] = func.get_capi_name()+'()'
classes = self.get_classes()
for cls in classes:
map[cls.get_name()] = cls.get_capi_name()
funcs = cls.get_virtual_funcs()
for func in funcs:
map[func.get_name()+'()'] = func.get_capi_name()+'()'
funcs = cls.get_static_funcs()
for func in funcs:
map[func.get_name()+'()'] = func.get_capi_name()+'()'
return map | [
"def",
"get_capi_translations",
"(",
"self",
")",
":",
"# strings that will be changed in C++ comments",
"map",
"=",
"{",
"'class'",
":",
"'structure'",
",",
"'Class'",
":",
"'Structure'",
",",
"'interface'",
":",
"'structure'",
",",
"'Interface'",
":",
"'Structure'",... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py#L720-L752 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/xml/dom/expatbuilder.py | python | Namespaces.start_namespace_decl_handler | (self, prefix, uri) | Push this namespace declaration on our storage. | Push this namespace declaration on our storage. | [
"Push",
"this",
"namespace",
"declaration",
"on",
"our",
"storage",
"."
] | def start_namespace_decl_handler(self, prefix, uri):
"""Push this namespace declaration on our storage."""
self._ns_ordered_prefixes.append((prefix, uri)) | [
"def",
"start_namespace_decl_handler",
"(",
"self",
",",
"prefix",
",",
"uri",
")",
":",
"self",
".",
"_ns_ordered_prefixes",
".",
"append",
"(",
"(",
"prefix",
",",
"uri",
")",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/xml/dom/expatbuilder.py#L739-L741 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/parsing_ops.py | python | _parse_single_sequence_example_raw | (serialized,
context_sparse_keys=None,
context_sparse_types=None,
context_dense_keys=None,
context_dense_types=None,
context_dense_defaults=None,
context_dense_shapes=None,
feature_list_sparse_keys=None,
feature_list_sparse_types=None,
feature_list_dense_keys=None,
feature_list_dense_types=None,
feature_list_dense_shapes=None,
feature_list_dense_defaults=None,
debug_name=None,
name=None) | Parses a single `SequenceExample` proto.
Args:
serialized: A scalar (0-D Tensor) of type string, a single binary
serialized `SequenceExample` proto.
context_sparse_keys: A list of string keys in the `SequenceExample`'s
features. The results for these keys will be returned as
`SparseTensor` objects.
context_sparse_types: A list of `DTypes`, the same length as `sparse_keys`.
Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),
and `tf.string` (`BytesList`) are supported.
context_dense_keys: A list of string keys in the examples' features.
The results for these keys will be returned as `Tensor`s
context_dense_types: A list of DTypes, same length as `context_dense_keys`.
Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),
and `tf.string` (`BytesList`) are supported.
context_dense_defaults: A dict mapping string keys to `Tensor`s.
The keys of the dict must match the context_dense_keys of the feature.
context_dense_shapes: A list of tuples, same length as `context_dense_keys`.
The shape of the data for each context_dense feature referenced by
`context_dense_keys`. Required for any input tensors identified by
`context_dense_keys` whose shapes are anything other than `[]` or `[1]`.
feature_list_sparse_keys: A list of string keys in the `SequenceExample`'s
feature_lists. The results for these keys will be returned as
`SparseTensor` objects.
feature_list_sparse_types: A list of `DTypes`, same length as `sparse_keys`.
Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),
and `tf.string` (`BytesList`) are supported.
feature_list_dense_keys: A list of string keys in the `SequenceExample`'s
features_lists. The results for these keys will be returned as `Tensor`s.
feature_list_dense_types: A list of `DTypes`, same length as
`feature_list_dense_keys`. Only `tf.float32` (`FloatList`),
`tf.int64` (`Int64List`), and `tf.string` (`BytesList`) are supported.
feature_list_dense_shapes: A list of tuples, same length as
`feature_list_dense_keys`. The shape of the data for each
`FeatureList` feature referenced by `feature_list_dense_keys`.
feature_list_dense_defaults: A dict mapping key strings to values.
The only currently allowed value is `None`. Any key appearing
in this dict with value `None` is allowed to be missing from the
`SequenceExample`. If missing, the key is treated as zero-length.
debug_name: A scalar (0-D Tensor) of strings (optional), the name of
the serialized proto.
name: A name for this operation (optional).
Returns:
A tuple of two `dict`s, each mapping keys to `Tensor`s and `SparseTensor`s.
The first dict contains the context key/values.
The second dict contains the feature_list key/values.
Raises:
ValueError: If context_sparse and context_dense key sets intersect,
if input lengths do not match up, or if a value in
feature_list_dense_defaults is not None.
TypeError: if feature_list_dense_defaults is not either None or a dict. | Parses a single `SequenceExample` proto. | [
"Parses",
"a",
"single",
"SequenceExample",
"proto",
"."
] | def _parse_single_sequence_example_raw(serialized,
context_sparse_keys=None,
context_sparse_types=None,
context_dense_keys=None,
context_dense_types=None,
context_dense_defaults=None,
context_dense_shapes=None,
feature_list_sparse_keys=None,
feature_list_sparse_types=None,
feature_list_dense_keys=None,
feature_list_dense_types=None,
feature_list_dense_shapes=None,
feature_list_dense_defaults=None,
debug_name=None,
name=None):
"""Parses a single `SequenceExample` proto.
Args:
serialized: A scalar (0-D Tensor) of type string, a single binary
serialized `SequenceExample` proto.
context_sparse_keys: A list of string keys in the `SequenceExample`'s
features. The results for these keys will be returned as
`SparseTensor` objects.
context_sparse_types: A list of `DTypes`, the same length as `sparse_keys`.
Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),
and `tf.string` (`BytesList`) are supported.
context_dense_keys: A list of string keys in the examples' features.
The results for these keys will be returned as `Tensor`s
context_dense_types: A list of DTypes, same length as `context_dense_keys`.
Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),
and `tf.string` (`BytesList`) are supported.
context_dense_defaults: A dict mapping string keys to `Tensor`s.
The keys of the dict must match the context_dense_keys of the feature.
context_dense_shapes: A list of tuples, same length as `context_dense_keys`.
The shape of the data for each context_dense feature referenced by
`context_dense_keys`. Required for any input tensors identified by
`context_dense_keys` whose shapes are anything other than `[]` or `[1]`.
feature_list_sparse_keys: A list of string keys in the `SequenceExample`'s
feature_lists. The results for these keys will be returned as
`SparseTensor` objects.
feature_list_sparse_types: A list of `DTypes`, same length as `sparse_keys`.
Only `tf.float32` (`FloatList`), `tf.int64` (`Int64List`),
and `tf.string` (`BytesList`) are supported.
feature_list_dense_keys: A list of string keys in the `SequenceExample`'s
features_lists. The results for these keys will be returned as `Tensor`s.
feature_list_dense_types: A list of `DTypes`, same length as
`feature_list_dense_keys`. Only `tf.float32` (`FloatList`),
`tf.int64` (`Int64List`), and `tf.string` (`BytesList`) are supported.
feature_list_dense_shapes: A list of tuples, same length as
`feature_list_dense_keys`. The shape of the data for each
`FeatureList` feature referenced by `feature_list_dense_keys`.
feature_list_dense_defaults: A dict mapping key strings to values.
The only currently allowed value is `None`. Any key appearing
in this dict with value `None` is allowed to be missing from the
`SequenceExample`. If missing, the key is treated as zero-length.
debug_name: A scalar (0-D Tensor) of strings (optional), the name of
the serialized proto.
name: A name for this operation (optional).
Returns:
A tuple of two `dict`s, each mapping keys to `Tensor`s and `SparseTensor`s.
The first dict contains the context key/values.
The second dict contains the feature_list key/values.
Raises:
ValueError: If context_sparse and context_dense key sets intersect,
if input lengths do not match up, or if a value in
feature_list_dense_defaults is not None.
TypeError: if feature_list_dense_defaults is not either None or a dict.
"""
with ops.name_scope(name, "ParseSingleSequenceExample", [serialized]):
context_dense_defaults = (
{} if context_dense_defaults is None else context_dense_defaults)
context_sparse_keys = (
[] if context_sparse_keys is None else context_sparse_keys)
context_sparse_types = (
[] if context_sparse_types is None else context_sparse_types)
context_dense_keys = (
[] if context_dense_keys is None else context_dense_keys)
context_dense_types = (
[] if context_dense_types is None else context_dense_types)
context_dense_shapes = (
[[]] * len(context_dense_keys)
if context_dense_shapes is None else context_dense_shapes)
feature_list_sparse_keys = (
[] if feature_list_sparse_keys is None else feature_list_sparse_keys)
feature_list_sparse_types = (
[] if feature_list_sparse_types is None else feature_list_sparse_types)
feature_list_dense_keys = (
[] if feature_list_dense_keys is None else feature_list_dense_keys)
feature_list_dense_types = (
[] if feature_list_dense_types is None else feature_list_dense_types)
feature_list_dense_shapes = (
[[]] * len(feature_list_dense_keys)
if feature_list_dense_shapes is None else feature_list_dense_shapes)
feature_list_dense_defaults = (
dict() if feature_list_dense_defaults is None
else feature_list_dense_defaults)
debug_name = "" if debug_name is None else debug_name
# Internal
feature_list_dense_missing_assumed_empty = []
num_context_dense = len(context_dense_keys)
num_feature_list_dense = len(feature_list_dense_keys)
num_context_sparse = len(context_sparse_keys)
num_feature_list_sparse = len(feature_list_sparse_keys)
if len(context_dense_shapes) != num_context_dense:
raise ValueError(
"len(context_dense_shapes) != len(context_dense_keys): %d vs. %d"
% (len(context_dense_shapes), num_context_dense))
if len(context_dense_types) != num_context_dense:
raise ValueError(
"len(context_dense_types) != len(num_context_dense): %d vs. %d"
% (len(context_dense_types), num_context_dense))
if len(feature_list_dense_shapes) != num_feature_list_dense:
raise ValueError(
"len(feature_list_dense_shapes) != len(feature_list_dense_keys): "
"%d vs. %d" % (len(feature_list_dense_shapes),
num_feature_list_dense))
if len(feature_list_dense_types) != num_feature_list_dense:
raise ValueError(
"len(feature_list_dense_types) != len(num_feature_list_dense):"
"%d vs. %d" % (len(feature_list_dense_types), num_feature_list_dense))
if len(context_sparse_types) != num_context_sparse:
raise ValueError(
"len(context_sparse_types) != len(context_sparse_keys): %d vs. %d"
% (len(context_sparse_types), num_context_sparse))
if len(feature_list_sparse_types) != num_feature_list_sparse:
raise ValueError(
"len(feature_list_sparse_types) != len(feature_list_sparse_keys): "
"%d vs. %d"
% (len(feature_list_sparse_types), num_feature_list_sparse))
if (num_context_dense + num_context_sparse
+ num_feature_list_dense + num_feature_list_sparse) == 0:
raise ValueError(
"Must provide at least one context_sparse key, context_dense key, "
", feature_list_sparse key, or feature_list_dense key")
if not set(context_dense_keys).isdisjoint(set(context_sparse_keys)):
raise ValueError(
"context_dense and context_sparse keys must not intersect; "
"intersection: %s" %
set(context_dense_keys).intersection(set(context_sparse_keys)))
if not set(feature_list_dense_keys).isdisjoint(
set(feature_list_sparse_keys)):
raise ValueError(
"feature_list_dense and feature_list_sparse keys must not intersect; "
"intersection: %s" %
set(feature_list_dense_keys).intersection(
set(feature_list_sparse_keys)))
if not isinstance(feature_list_dense_defaults, dict):
raise TypeError("feature_list_dense_defaults must be a dict")
for k, v in feature_list_dense_defaults.items():
if v is not None:
raise ValueError("Value feature_list_dense_defaults[%s] must be None"
% k)
feature_list_dense_missing_assumed_empty.append(k)
context_dense_defaults_vec = []
for i, key in enumerate(context_dense_keys):
default_value = context_dense_defaults.get(key)
if default_value is None:
default_value = constant_op.constant([], dtype=context_dense_types[i])
elif not isinstance(default_value, ops.Tensor):
key_name = "key_" + re.sub("[^A-Za-z0-9_.\\-/]", "_", key)
default_value = ops.convert_to_tensor(
default_value, dtype=context_dense_types[i], name=key_name)
default_value = array_ops.reshape(
default_value, context_dense_shapes[i])
context_dense_defaults_vec.append(default_value)
context_dense_shapes = [tensor_shape.as_shape(shape).as_proto()
for shape in context_dense_shapes]
feature_list_dense_shapes = [tensor_shape.as_shape(shape).as_proto()
for shape in feature_list_dense_shapes]
# pylint: disable=protected-access
outputs = gen_parsing_ops._parse_single_sequence_example(
serialized=serialized,
debug_name=debug_name,
context_dense_defaults=context_dense_defaults_vec,
context_sparse_keys=context_sparse_keys,
context_sparse_types=context_sparse_types,
context_dense_keys=context_dense_keys,
context_dense_shapes=context_dense_shapes,
feature_list_sparse_keys=feature_list_sparse_keys,
feature_list_sparse_types=feature_list_sparse_types,
feature_list_dense_keys=feature_list_dense_keys,
feature_list_dense_types=feature_list_dense_types,
feature_list_dense_shapes=feature_list_dense_shapes,
feature_list_dense_missing_assumed_empty=(
feature_list_dense_missing_assumed_empty),
name=name)
# pylint: enable=protected-access
(context_sparse_indices, context_sparse_values,
context_sparse_shapes, context_dense_values,
feature_list_sparse_indices, feature_list_sparse_values,
feature_list_sparse_shapes, feature_list_dense_values) = outputs
context_sparse_tensors = [
sparse_tensor.SparseTensor(ix, val, shape) for (ix, val, shape)
in zip(context_sparse_indices,
context_sparse_values,
context_sparse_shapes)]
feature_list_sparse_tensors = [
sparse_tensor.SparseTensor(ix, val, shape) for (ix, val, shape)
in zip(feature_list_sparse_indices,
feature_list_sparse_values,
feature_list_sparse_shapes)]
context_output = dict(
zip(context_sparse_keys + context_dense_keys,
context_sparse_tensors + context_dense_values))
feature_list_output = dict(
zip(feature_list_sparse_keys + feature_list_dense_keys,
feature_list_sparse_tensors + feature_list_dense_values))
return (context_output, feature_list_output) | [
"def",
"_parse_single_sequence_example_raw",
"(",
"serialized",
",",
"context_sparse_keys",
"=",
"None",
",",
"context_sparse_types",
"=",
"None",
",",
"context_dense_keys",
"=",
"None",
",",
"context_dense_types",
"=",
"None",
",",
"context_dense_defaults",
"=",
"None"... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/parsing_ops.py#L947-L1168 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Tk.destroy | (self) | Destroy this and all descendants widgets. This will
end the application of this Tcl interpreter. | Destroy this and all descendants widgets. This will
end the application of this Tcl interpreter. | [
"Destroy",
"this",
"and",
"all",
"descendants",
"widgets",
".",
"This",
"will",
"end",
"the",
"application",
"of",
"this",
"Tcl",
"interpreter",
"."
] | def destroy(self):
"""Destroy this and all descendants widgets. This will
end the application of this Tcl interpreter."""
for c in self.children.values(): c.destroy()
self.tk.call('destroy', self._w)
Misc.destroy(self)
global _default_root
if _support_default_root and _default_root is self:
_default_root = None | [
"def",
"destroy",
"(",
"self",
")",
":",
"for",
"c",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
":",
"c",
".",
"destroy",
"(",
")",
"self",
".",
"tk",
".",
"call",
"(",
"'destroy'",
",",
"self",
".",
"_w",
")",
"Misc",
".",
"destro... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1786-L1794 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py | python | NDFrame.rename | (
self: FrameOrSeries,
mapper: Optional[Renamer] = None,
*,
index: Optional[Renamer] = None,
columns: Optional[Renamer] = None,
axis: Optional[Axis] = None,
copy: bool = True,
inplace: bool = False,
level: Optional[Level] = None,
errors: str = "ignore",
) | Alter axes input function or functions. Function / dict values must be
unique (1-to-1). Labels not contained in a dict / Series will be left
as-is. Extra labels listed don't throw an error. Alternatively, change
``Series.name`` with a scalar value (Series only).
Parameters
----------
%(axes)s : scalar, list-like, dict-like or function, optional
Scalar or list-like will alter the ``Series.name`` attribute,
and raise on DataFrame.
dict-like or functions are transformations to apply to
that axis' values
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Whether to return a new %(klass)s. If True then value of copy is
ignored.
level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified
level.
errors : {'ignore', 'raise'}, default 'ignore'
If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
or `columns` contains labels that are not present in the Index
being transformed.
If 'ignore', existing keys will be renamed and extra keys will be
ignored.
Returns
-------
renamed : %(klass)s (new object)
Raises
------
KeyError
If any of the labels is not found in the selected axis and
"errors='raise'".
See Also
--------
NDFrame.rename_axis
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
dtype: int64
>>> s.rename("my_name") # scalar, changes Series.name
0 1
1 2
2 3
Name: my_name, dtype: int64
>>> s.rename(lambda x: x ** 2) # function, changes labels
0 1
1 2
4 3
dtype: int64
>>> s.rename({1: 3, 2: 5}) # mapping, changes labels
0 1
3 2
5 3
dtype: int64
Since ``DataFrame`` doesn't have a ``.name`` attribute,
only mapping-type arguments are allowed.
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(2)
Traceback (most recent call last):
...
TypeError: 'int' object is not callable
``DataFrame.rename`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
We *highly* recommend using keyword arguments to clarify your
intent.
>>> df.rename(index=str, columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6
>>> df.rename(index=str, columns={"A": "a", "C": "c"})
a B
0 1 4
1 2 5
2 3 6
Using axis-style parameters
>>> df.rename(str.lower, axis='columns')
a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2, 2: 4}, axis='index')
A B
0 1 4
2 2 5
4 3 6
See the :ref:`user guide <basics.rename>` for more. | Alter axes input function or functions. Function / dict values must be
unique (1-to-1). Labels not contained in a dict / Series will be left
as-is. Extra labels listed don't throw an error. Alternatively, change
``Series.name`` with a scalar value (Series only). | [
"Alter",
"axes",
"input",
"function",
"or",
"functions",
".",
"Function",
"/",
"dict",
"values",
"must",
"be",
"unique",
"(",
"1",
"-",
"to",
"-",
"1",
")",
".",
"Labels",
"not",
"contained",
"in",
"a",
"dict",
"/",
"Series",
"will",
"be",
"left",
"a... | def rename(
self: FrameOrSeries,
mapper: Optional[Renamer] = None,
*,
index: Optional[Renamer] = None,
columns: Optional[Renamer] = None,
axis: Optional[Axis] = None,
copy: bool = True,
inplace: bool = False,
level: Optional[Level] = None,
errors: str = "ignore",
) -> Optional[FrameOrSeries]:
"""
Alter axes input function or functions. Function / dict values must be
unique (1-to-1). Labels not contained in a dict / Series will be left
as-is. Extra labels listed don't throw an error. Alternatively, change
``Series.name`` with a scalar value (Series only).
Parameters
----------
%(axes)s : scalar, list-like, dict-like or function, optional
Scalar or list-like will alter the ``Series.name`` attribute,
and raise on DataFrame.
dict-like or functions are transformations to apply to
that axis' values
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Whether to return a new %(klass)s. If True then value of copy is
ignored.
level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified
level.
errors : {'ignore', 'raise'}, default 'ignore'
If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
or `columns` contains labels that are not present in the Index
being transformed.
If 'ignore', existing keys will be renamed and extra keys will be
ignored.
Returns
-------
renamed : %(klass)s (new object)
Raises
------
KeyError
If any of the labels is not found in the selected axis and
"errors='raise'".
See Also
--------
NDFrame.rename_axis
Examples
--------
>>> s = pd.Series([1, 2, 3])
>>> s
0 1
1 2
2 3
dtype: int64
>>> s.rename("my_name") # scalar, changes Series.name
0 1
1 2
2 3
Name: my_name, dtype: int64
>>> s.rename(lambda x: x ** 2) # function, changes labels
0 1
1 2
4 3
dtype: int64
>>> s.rename({1: 3, 2: 5}) # mapping, changes labels
0 1
3 2
5 3
dtype: int64
Since ``DataFrame`` doesn't have a ``.name`` attribute,
only mapping-type arguments are allowed.
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(2)
Traceback (most recent call last):
...
TypeError: 'int' object is not callable
``DataFrame.rename`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
We *highly* recommend using keyword arguments to clarify your
intent.
>>> df.rename(index=str, columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6
>>> df.rename(index=str, columns={"A": "a", "C": "c"})
a B
0 1 4
1 2 5
2 3 6
Using axis-style parameters
>>> df.rename(str.lower, axis='columns')
a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2, 2: 4}, axis='index')
A B
0 1 4
2 2 5
4 3 6
See the :ref:`user guide <basics.rename>` for more.
"""
if mapper is None and index is None and columns is None:
raise TypeError("must pass an index to rename")
if index is not None or columns is not None:
if axis is not None:
raise TypeError(
"Cannot specify both 'axis' and any of 'index' or 'columns'"
)
elif mapper is not None:
raise TypeError(
"Cannot specify both 'mapper' and any of 'index' or 'columns'"
)
else:
# use the mapper argument
if axis and self._get_axis_number(axis) == 1:
columns = mapper
else:
index = mapper
result = self if inplace else self.copy(deep=copy)
for axis_no, replacements in enumerate((index, columns)):
if replacements is None:
continue
ax = self._get_axis(axis_no)
baxis = self._get_block_manager_axis(axis_no)
f = com.get_rename_function(replacements)
if level is not None:
level = ax._get_level_number(level)
# GH 13473
if not callable(replacements):
indexer = ax.get_indexer_for(replacements)
if errors == "raise" and len(indexer[indexer == -1]):
missing_labels = [
label
for index, label in enumerate(replacements)
if indexer[index] == -1
]
raise KeyError(f"{missing_labels} not found in axis")
result._data = result._data.rename_axis(
f, axis=baxis, copy=copy, level=level
)
result._clear_item_cache()
if inplace:
self._update_inplace(result._data)
return None
else:
return result.__finalize__(self) | [
"def",
"rename",
"(",
"self",
":",
"FrameOrSeries",
",",
"mapper",
":",
"Optional",
"[",
"Renamer",
"]",
"=",
"None",
",",
"*",
",",
"index",
":",
"Optional",
"[",
"Renamer",
"]",
"=",
"None",
",",
"columns",
":",
"Optional",
"[",
"Renamer",
"]",
"="... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py#L932-L1108 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/callback.py | python | do_checkpoint | (prefix, period=1) | return _callback | A callback that saves a model checkpoint every few epochs.
Each checkpoint is made up of a couple of binary files: a model description file and a
parameters (weights and biases) file. The model description file is named
`prefix`--symbol.json and the parameters file is named `prefix`-`epoch_number`.params
Parameters
----------
prefix : str
Prefix for the checkpoint filenames.
period : int, optional
Interval (number of epochs) between checkpoints. Default `period` is 1.
Returns
-------
callback : function
A callback function that can be passed as `epoch_end_callback` to fit.
Example
-------
>>> module.fit(iterator, num_epoch=n_epoch,
... epoch_end_callback = mx.callback.do_checkpoint("mymodel", 1))
Start training with [cpu(0)]
Epoch[0] Resetting Data Iterator
Epoch[0] Time cost=0.100
Saved checkpoint to "mymodel-0001.params"
Epoch[1] Resetting Data Iterator
Epoch[1] Time cost=0.060
Saved checkpoint to "mymodel-0002.params" | A callback that saves a model checkpoint every few epochs.
Each checkpoint is made up of a couple of binary files: a model description file and a
parameters (weights and biases) file. The model description file is named
`prefix`--symbol.json and the parameters file is named `prefix`-`epoch_number`.params | [
"A",
"callback",
"that",
"saves",
"a",
"model",
"checkpoint",
"every",
"few",
"epochs",
".",
"Each",
"checkpoint",
"is",
"made",
"up",
"of",
"a",
"couple",
"of",
"binary",
"files",
":",
"a",
"model",
"description",
"file",
"and",
"a",
"parameters",
"(",
... | def do_checkpoint(prefix, period=1):
"""A callback that saves a model checkpoint every few epochs.
Each checkpoint is made up of a couple of binary files: a model description file and a
parameters (weights and biases) file. The model description file is named
`prefix`--symbol.json and the parameters file is named `prefix`-`epoch_number`.params
Parameters
----------
prefix : str
Prefix for the checkpoint filenames.
period : int, optional
Interval (number of epochs) between checkpoints. Default `period` is 1.
Returns
-------
callback : function
A callback function that can be passed as `epoch_end_callback` to fit.
Example
-------
>>> module.fit(iterator, num_epoch=n_epoch,
... epoch_end_callback = mx.callback.do_checkpoint("mymodel", 1))
Start training with [cpu(0)]
Epoch[0] Resetting Data Iterator
Epoch[0] Time cost=0.100
Saved checkpoint to "mymodel-0001.params"
Epoch[1] Resetting Data Iterator
Epoch[1] Time cost=0.060
Saved checkpoint to "mymodel-0002.params"
"""
period = int(max(1, period))
def _callback(iter_no, sym, arg, aux):
"""The checkpoint function."""
if (iter_no + 1) % period == 0:
save_checkpoint(prefix, iter_no + 1, sym, arg, aux)
return _callback | [
"def",
"do_checkpoint",
"(",
"prefix",
",",
"period",
"=",
"1",
")",
":",
"period",
"=",
"int",
"(",
"max",
"(",
"1",
",",
"period",
")",
")",
"def",
"_callback",
"(",
"iter_no",
",",
"sym",
",",
"arg",
",",
"aux",
")",
":",
"\"\"\"The checkpoint fun... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/callback.py#L55-L90 | |
GXYM/DRRG | 9e074fa9052de8d131f55ca1f6ae6673c1bfeca4 | dataset/ctw1500/Evaluation_Protocol/voc_eval_polygon.py | python | voc_ap | (rec, prec, use_07_metric=False) | return ap | ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False). | ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False). | [
"ap",
"=",
"voc_ap",
"(",
"rec",
"prec",
"[",
"use_07_metric",
"]",
")",
"Compute",
"VOC",
"AP",
"given",
"precision",
"and",
"recall",
".",
"If",
"use_07_metric",
"is",
"true",
"uses",
"the",
"VOC",
"07",
"11",
"point",
"method",
"(",
"default",
":",
... | def voc_ap(rec, prec, use_07_metric=False):
""" ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False).
"""
if use_07_metric:
# 11 point metric
ap = 0.
for t in np.arange(0., 1.1, 0.1):
if np.sum(rec >= t) == 0:
p = 0
else:
p = np.max(prec[rec >= t])
ap = ap + p / 11.
else:
# correct AP calculation
# first append sentinel values at the end
mrec = np.concatenate(([0.], rec, [1.]))
mpre = np.concatenate(([0.], prec, [0.]))
# compute the precision envelope
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# to calculate area under PR curve, look for points
# where X axis (recall) changes value
i = np.where(mrec[1:] != mrec[:-1])[0]
# and sum (\Delta recall) * prec
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap | [
"def",
"voc_ap",
"(",
"rec",
",",
"prec",
",",
"use_07_metric",
"=",
"False",
")",
":",
"if",
"use_07_metric",
":",
"# 11 point metric",
"ap",
"=",
"0.",
"for",
"t",
"in",
"np",
".",
"arange",
"(",
"0.",
",",
"1.1",
",",
"0.1",
")",
":",
"if",
"np"... | https://github.com/GXYM/DRRG/blob/9e074fa9052de8d131f55ca1f6ae6673c1bfeca4/dataset/ctw1500/Evaluation_Protocol/voc_eval_polygon.py#L52-L83 | |
dlunion/CC4.0 | 6fb51e494b6a88f0987b9dd99117ec21766e3aee | python/caffe/io.py | python | array_to_datum | (arr, label=None) | return datum | Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format. | Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format. | [
"Converts",
"a",
"3",
"-",
"dimensional",
"array",
"to",
"datum",
".",
"If",
"the",
"array",
"has",
"dtype",
"uint8",
"the",
"output",
"data",
"will",
"be",
"encoded",
"as",
"a",
"string",
".",
"Otherwise",
"the",
"output",
"data",
"will",
"be",
"stored"... | def array_to_datum(arr, label=None):
"""Converts a 3-dimensional array to datum. If the array has dtype uint8,
the output data will be encoded as a string. Otherwise, the output data
will be stored in float format.
"""
if arr.ndim != 3:
raise ValueError('Incorrect array shape.')
datum = caffe_pb2.Datum()
datum.channels, datum.height, datum.width = arr.shape
if arr.dtype == np.uint8:
datum.data = arr.tostring()
else:
datum.float_data.extend(arr.flat)
if label is not None:
datum.label = label
return datum | [
"def",
"array_to_datum",
"(",
"arr",
",",
"label",
"=",
"None",
")",
":",
"if",
"arr",
".",
"ndim",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'Incorrect array shape.'",
")",
"datum",
"=",
"caffe_pb2",
".",
"Datum",
"(",
")",
"datum",
".",
"channels",
... | https://github.com/dlunion/CC4.0/blob/6fb51e494b6a88f0987b9dd99117ec21766e3aee/python/caffe/io.py#L66-L81 | |
ucbrise/clipper | 9f25e3fc7f8edc891615e81c5b80d3d8aed72608 | clipper_admin/clipper_admin/clipper_admin.py | python | ClipperConnection.deploy_model | (self,
name,
version,
input_type,
image,
labels=None,
num_replicas=1,
batch_size=-1) | Deploys the model in the provided Docker image to Clipper.
Deploying a model to Clipper does a few things.
1. It starts a set of Docker model containers running the model packaged
in the ``image`` Docker image. The number of containers it will start is dictated
by the ``num_replicas`` argument, but the way that these containers get started
depends on your choice of ``ContainerManager`` implementation.
2. It registers the model and version with Clipper and sets the current version of the
model to this version by internally calling
:py:meth:`clipper_admin.ClipperConnection.register_model`.
Notes
-----
If you want to deploy a model in some other way (e.g. a model that cannot run in a Docker
container for some reason), you can start the model manually or with an external tool and
call ``register_model`` directly.
Parameters
----------
name : str
The name of the deployed model
version : str
The version to assign this model. Versions must be unique on a per-model
basis, but may be re-used across different models.
input_type : str
The type of the request data this endpoint can process. Input type can be
one of "integers", "floats", "doubles", "bytes", or "strings". See the
`User Guide <http://clipper.ai/user_guide/#input-types>`_ for more details
on picking the right input type for your application.
image : str
The fully specified Docker image to deploy. If using a custom
registry, the registry name must be prepended to the image. For example,
if your Docker image is stored in the quay.io registry, you should specify
the image argument as
"quay.io/my_namespace/image_name:tag". The image name and tag are independent of
the ``name`` and ``version`` arguments, and can be set to whatever you want.
labels : list(str), optional
A list of strings annotating the model. These are ignored by Clipper
and used purely for user annotations.
num_replicas : int, optional
The number of replicas of the model to create. The number of replicas
for a model can be changed at any time with
:py:meth:`clipper.ClipperConnection.set_num_replicas`.
batch_size : int, optional
The user-defined query batch size for the model. Replicas of the model will attempt
to process at most `batch_size` queries simultaneously. They may process smaller
batches if `batch_size` queries are not immediately available.
If the default value of -1 is used, Clipper will adaptively calculate the batch size for
individual replicas of this model.
Raises
------
:py:exc:`clipper.UnconnectedException`
:py:exc:`clipper.ClipperException`
Note
----
Both the model name and version must be valid DNS-1123 subdomains. Each must consist of
lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric
character (e.g. 'example.com', regex used for validation is
'[a-z0-9]([-a-z0-9]*[a-z0-9])?\Z'. | Deploys the model in the provided Docker image to Clipper. | [
"Deploys",
"the",
"model",
"in",
"the",
"provided",
"Docker",
"image",
"to",
"Clipper",
"."
] | def deploy_model(self,
name,
version,
input_type,
image,
labels=None,
num_replicas=1,
batch_size=-1):
"""Deploys the model in the provided Docker image to Clipper.
Deploying a model to Clipper does a few things.
1. It starts a set of Docker model containers running the model packaged
in the ``image`` Docker image. The number of containers it will start is dictated
by the ``num_replicas`` argument, but the way that these containers get started
depends on your choice of ``ContainerManager`` implementation.
2. It registers the model and version with Clipper and sets the current version of the
model to this version by internally calling
:py:meth:`clipper_admin.ClipperConnection.register_model`.
Notes
-----
If you want to deploy a model in some other way (e.g. a model that cannot run in a Docker
container for some reason), you can start the model manually or with an external tool and
call ``register_model`` directly.
Parameters
----------
name : str
The name of the deployed model
version : str
The version to assign this model. Versions must be unique on a per-model
basis, but may be re-used across different models.
input_type : str
The type of the request data this endpoint can process. Input type can be
one of "integers", "floats", "doubles", "bytes", or "strings". See the
`User Guide <http://clipper.ai/user_guide/#input-types>`_ for more details
on picking the right input type for your application.
image : str
The fully specified Docker image to deploy. If using a custom
registry, the registry name must be prepended to the image. For example,
if your Docker image is stored in the quay.io registry, you should specify
the image argument as
"quay.io/my_namespace/image_name:tag". The image name and tag are independent of
the ``name`` and ``version`` arguments, and can be set to whatever you want.
labels : list(str), optional
A list of strings annotating the model. These are ignored by Clipper
and used purely for user annotations.
num_replicas : int, optional
The number of replicas of the model to create. The number of replicas
for a model can be changed at any time with
:py:meth:`clipper.ClipperConnection.set_num_replicas`.
batch_size : int, optional
The user-defined query batch size for the model. Replicas of the model will attempt
to process at most `batch_size` queries simultaneously. They may process smaller
batches if `batch_size` queries are not immediately available.
If the default value of -1 is used, Clipper will adaptively calculate the batch size for
individual replicas of this model.
Raises
------
:py:exc:`clipper.UnconnectedException`
:py:exc:`clipper.ClipperException`
Note
----
Both the model name and version must be valid DNS-1123 subdomains. Each must consist of
lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric
character (e.g. 'example.com', regex used for validation is
'[a-z0-9]([-a-z0-9]*[a-z0-9])?\Z'.
"""
if not self.connected:
raise UnconnectedException()
version = str(version)
_validate_versioned_model_name(name, version)
self.cm.deploy_model(
name=name,
version=version,
input_type=input_type,
image=image,
num_replicas=num_replicas)
self.register_model(
name,
version,
input_type,
image=image,
labels=labels,
batch_size=batch_size)
self.logger.info("Done deploying model {name}:{version}.".format(
name=name, version=version)) | [
"def",
"deploy_model",
"(",
"self",
",",
"name",
",",
"version",
",",
"input_type",
",",
"image",
",",
"labels",
"=",
"None",
",",
"num_replicas",
"=",
"1",
",",
"batch_size",
"=",
"-",
"1",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"rais... | https://github.com/ucbrise/clipper/blob/9f25e3fc7f8edc891615e81c5b80d3d8aed72608/clipper_admin/clipper_admin/clipper_admin.py#L552-L642 | ||
sonyxperiadev/WebGL | 0299b38196f78c6d5f74bcf6fa312a3daee6de60 | Tools/Scripts/webkitpy/python24/versioning.py | python | compare_version | (sysmodule=None, target_version=None) | return (comparison, current_version, target_version) | Compare the current Python version with a target version.
Args:
sysmodule: An object with version and version_info data attributes
used to detect the current Python version. The attributes
should have the same semantics as sys.version and
sys.version_info. This parameter should only be used
for unit testing. Defaults to sys.
target_version: A string representing the Python version to compare
the current version against. The string should have
one of the following three forms: 2, 2.5, or 2.5.3.
Defaults to the minimum version that the webkitpy
package supports.
Returns:
A triple of (comparison, current_version, target_version).
comparison: An integer representing the result of comparing the
current version with the target version. A positive
number means the current version is greater than the
target, 0 means they are the same, and a negative number
means the current version is less than the target.
This method compares version information only up
to the precision of the given target version. For
example, if the target version is 2.6 and the current
version is 2.5.3, this method uses 2.5 for the purposes
of comparing with the target.
current_version: A string representing the current Python version, for
example 2.5.3.
target_version: A string representing the version that the current
version was compared against, for example 2.5. | Compare the current Python version with a target version. | [
"Compare",
"the",
"current",
"Python",
"version",
"with",
"a",
"target",
"version",
"."
] | def compare_version(sysmodule=None, target_version=None):
"""Compare the current Python version with a target version.
Args:
sysmodule: An object with version and version_info data attributes
used to detect the current Python version. The attributes
should have the same semantics as sys.version and
sys.version_info. This parameter should only be used
for unit testing. Defaults to sys.
target_version: A string representing the Python version to compare
the current version against. The string should have
one of the following three forms: 2, 2.5, or 2.5.3.
Defaults to the minimum version that the webkitpy
package supports.
Returns:
A triple of (comparison, current_version, target_version).
comparison: An integer representing the result of comparing the
current version with the target version. A positive
number means the current version is greater than the
target, 0 means they are the same, and a negative number
means the current version is less than the target.
This method compares version information only up
to the precision of the given target version. For
example, if the target version is 2.6 and the current
version is 2.5.3, this method uses 2.5 for the purposes
of comparing with the target.
current_version: A string representing the current Python version, for
example 2.5.3.
target_version: A string representing the version that the current
version was compared against, for example 2.5.
"""
if sysmodule is None:
sysmodule = sys
if target_version is None:
target_version = _MINIMUM_SUPPORTED_PYTHON_VERSION
# The number of version parts to compare.
precision = len(target_version.split("."))
# We use sys.version_info rather than sys.version since its first
# three elements are guaranteed to be integers.
current_version_info_to_compare = sysmodule.version_info[:precision]
# Convert integers to strings.
current_version_info_to_compare = map(str, current_version_info_to_compare)
current_version_to_compare = ".".join(current_version_info_to_compare)
# Compare version strings lexicographically.
if current_version_to_compare > target_version:
comparison = 1
elif current_version_to_compare == target_version:
comparison = 0
else:
comparison = -1
# The version number portion of the current version string, for
# example "2.6.4".
current_version = sysmodule.version.split()[0]
return (comparison, current_version, target_version) | [
"def",
"compare_version",
"(",
"sysmodule",
"=",
"None",
",",
"target_version",
"=",
"None",
")",
":",
"if",
"sysmodule",
"is",
"None",
":",
"sysmodule",
"=",
"sys",
"if",
"target_version",
"is",
"None",
":",
"target_version",
"=",
"_MINIMUM_SUPPORTED_PYTHON_VER... | https://github.com/sonyxperiadev/WebGL/blob/0299b38196f78c6d5f74bcf6fa312a3daee6de60/Tools/Scripts/webkitpy/python24/versioning.py#L34-L95 | |
Alexhuszagh/rust-lexical | 01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0 | lexical-parse-float/etc/limits.py | python | exponent_limit | (radix, mantissa_size, max_exp) | Calculate the exponent limit for a float, for a given
float type, where `radix` is the numerical base
for the float type, and mantissa size is the length
of the mantissa in bits. max_exp is the maximum
binary exponent, where all exponent bits except the lowest
are set (or, `2**(exponent_size - 1) - 1`). | Calculate the exponent limit for a float, for a given
float type, where `radix` is the numerical base
for the float type, and mantissa size is the length
of the mantissa in bits. max_exp is the maximum
binary exponent, where all exponent bits except the lowest
are set (or, `2**(exponent_size - 1) - 1`). | [
"Calculate",
"the",
"exponent",
"limit",
"for",
"a",
"float",
"for",
"a",
"given",
"float",
"type",
"where",
"radix",
"is",
"the",
"numerical",
"base",
"for",
"the",
"float",
"type",
"and",
"mantissa",
"size",
"is",
"the",
"length",
"of",
"the",
"mantissa"... | def exponent_limit(radix, mantissa_size, max_exp):
'''
Calculate the exponent limit for a float, for a given
float type, where `radix` is the numerical base
for the float type, and mantissa size is the length
of the mantissa in bits. max_exp is the maximum
binary exponent, where all exponent bits except the lowest
are set (or, `2**(exponent_size - 1) - 1`).
'''
if is_pow2(radix):
# Can always be exactly represented. We can't handle
# denormal floats, however.
scaled = int(max_exp / math.log2(radix))
return (-scaled, scaled)
else:
# Positive and negative should be the same,
# since we need to find the maximum digit
# representable with mantissa digits.
# We first need to remove the highest power-of-
# two from the radix, since these will be represented
# with exponent digits.
base = remove_pow2(radix)
precision = mantissa_size + 1
exp_limit = int(precision / math.log2(base))
return (-exp_limit, exp_limit) | [
"def",
"exponent_limit",
"(",
"radix",
",",
"mantissa_size",
",",
"max_exp",
")",
":",
"if",
"is_pow2",
"(",
"radix",
")",
":",
"# Can always be exactly represented. We can't handle",
"# denormal floats, however.",
"scaled",
"=",
"int",
"(",
"max_exp",
"/",
"math",
... | https://github.com/Alexhuszagh/rust-lexical/blob/01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0/lexical-parse-float/etc/limits.py#L36-L61 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/beautifulsoup4/bs4/element.py | python | PageElement.format_string | (self, s, formatter='minimal') | return output | Format the given string using the given formatter. | Format the given string using the given formatter. | [
"Format",
"the",
"given",
"string",
"using",
"the",
"given",
"formatter",
"."
] | def format_string(self, s, formatter='minimal'):
"""Format the given string using the given formatter."""
if not callable(formatter):
formatter = self._formatter_for_name(formatter)
if formatter is None:
output = s
else:
output = formatter(s)
return output | [
"def",
"format_string",
"(",
"self",
",",
"s",
",",
"formatter",
"=",
"'minimal'",
")",
":",
"if",
"not",
"callable",
"(",
"formatter",
")",
":",
"formatter",
"=",
"self",
".",
"_formatter_for_name",
"(",
"formatter",
")",
"if",
"formatter",
"is",
"None",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/beautifulsoup4/bs4/element.py#L153-L161 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/shutil.py | python | _make_tarball | (base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
owner=None, group=None, logger=None) | return archive_name | Create a (possibly compressed) tar file from all the files under
'base_dir'.
'compress' must be "gzip" (the default), "bzip2", or None.
'owner' and 'group' can be used to define an owner and a group for the
archive that is being built. If not provided, the current owner and group
will be used.
The output tar file will be named 'base_name' + ".tar", possibly plus
the appropriate compression extension (".gz", or ".bz2").
Returns the output filename. | Create a (possibly compressed) tar file from all the files under
'base_dir'. | [
"Create",
"a",
"(",
"possibly",
"compressed",
")",
"tar",
"file",
"from",
"all",
"the",
"files",
"under",
"base_dir",
"."
] | def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
owner=None, group=None, logger=None):
"""Create a (possibly compressed) tar file from all the files under
'base_dir'.
'compress' must be "gzip" (the default), "bzip2", or None.
'owner' and 'group' can be used to define an owner and a group for the
archive that is being built. If not provided, the current owner and group
will be used.
The output tar file will be named 'base_name' + ".tar", possibly plus
the appropriate compression extension (".gz", or ".bz2").
Returns the output filename.
"""
if compress is None:
tar_compression = ''
elif _ZLIB_SUPPORTED and compress == 'gzip':
tar_compression = 'gz'
elif _BZ2_SUPPORTED and compress == 'bzip2':
tar_compression = 'bz2'
else:
raise ValueError("bad value for 'compress', or compression format not "
"supported : {0}".format(compress))
compress_ext = '.' + tar_compression if compress else ''
archive_name = base_name + '.tar' + compress_ext
archive_dir = os.path.dirname(archive_name)
if archive_dir and not os.path.exists(archive_dir):
if logger is not None:
logger.info("creating %s", archive_dir)
if not dry_run:
os.makedirs(archive_dir)
# creating the tarball
import tarfile # late import so Python build itself doesn't break
if logger is not None:
logger.info('Creating tar archive')
uid = _get_uid(owner)
gid = _get_gid(group)
def _set_uid_gid(tarinfo):
if gid is not None:
tarinfo.gid = gid
tarinfo.gname = group
if uid is not None:
tarinfo.uid = uid
tarinfo.uname = owner
return tarinfo
if not dry_run:
tar = tarfile.open(archive_name, 'w|%s' % tar_compression)
try:
tar.add(base_dir, filter=_set_uid_gid)
finally:
tar.close()
return archive_name | [
"def",
"_make_tarball",
"(",
"base_name",
",",
"base_dir",
",",
"compress",
"=",
"\"gzip\"",
",",
"verbose",
"=",
"0",
",",
"dry_run",
"=",
"0",
",",
"owner",
"=",
"None",
",",
"group",
"=",
"None",
",",
"logger",
"=",
"None",
")",
":",
"if",
"compre... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/shutil.py#L361-L423 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py | python | IResourceProvider.resource_listdir | (resource_name) | List of resource names in the directory (like ``os.listdir()``) | List of resource names in the directory (like ``os.listdir()``) | [
"List",
"of",
"resource",
"names",
"in",
"the",
"directory",
"(",
"like",
"os",
".",
"listdir",
"()",
")"
] | def resource_listdir(resource_name):
"""List of resource names in the directory (like ``os.listdir()``)""" | [
"def",
"resource_listdir",
"(",
"resource_name",
")",
":"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py#L550-L551 | ||
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/ogr.py | python | Layer.CreateFeature | (self, *args) | return _ogr.Layer_CreateFeature(self, *args) | r"""
CreateFeature(Layer self, Feature feature) -> OGRErr
OGRErr
OGR_L_CreateFeature(OGRLayerH hLayer, OGRFeatureH hFeat)
Create and write a new feature within a layer.
The passed feature is written to the layer as a new feature, rather
than overwriting an existing one. If the feature has a feature id
other than OGRNullFID, then the native implementation may use that as
the feature id of the new feature, but not necessarily. Upon
successful return the passed feature will have been updated with the
new feature id.
This function is the same as the C++ method OGRLayer::CreateFeature().
Parameters:
-----------
hLayer: handle to the layer to write the feature to.
hFeat: the handle of the feature to write to disk.
OGRERR_NONE on success. | r"""
CreateFeature(Layer self, Feature feature) -> OGRErr
OGRErr
OGR_L_CreateFeature(OGRLayerH hLayer, OGRFeatureH hFeat) | [
"r",
"CreateFeature",
"(",
"Layer",
"self",
"Feature",
"feature",
")",
"-",
">",
"OGRErr",
"OGRErr",
"OGR_L_CreateFeature",
"(",
"OGRLayerH",
"hLayer",
"OGRFeatureH",
"hFeat",
")"
] | def CreateFeature(self, *args):
r"""
CreateFeature(Layer self, Feature feature) -> OGRErr
OGRErr
OGR_L_CreateFeature(OGRLayerH hLayer, OGRFeatureH hFeat)
Create and write a new feature within a layer.
The passed feature is written to the layer as a new feature, rather
than overwriting an existing one. If the feature has a feature id
other than OGRNullFID, then the native implementation may use that as
the feature id of the new feature, but not necessarily. Upon
successful return the passed feature will have been updated with the
new feature id.
This function is the same as the C++ method OGRLayer::CreateFeature().
Parameters:
-----------
hLayer: handle to the layer to write the feature to.
hFeat: the handle of the feature to write to disk.
OGRERR_NONE on success.
"""
return _ogr.Layer_CreateFeature(self, *args) | [
"def",
"CreateFeature",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_ogr",
".",
"Layer_CreateFeature",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L1454-L1480 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ConfigParser.py | python | Error._set_message | (self, value) | Setter for 'message'; needed only to override deprecation in
BaseException. | Setter for 'message'; needed only to override deprecation in
BaseException. | [
"Setter",
"for",
"message",
";",
"needed",
"only",
"to",
"override",
"deprecation",
"in",
"BaseException",
"."
] | def _set_message(self, value):
"""Setter for 'message'; needed only to override deprecation in
BaseException."""
self.__message = value | [
"def",
"_set_message",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"__message",
"=",
"value"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ConfigParser.py#L120-L123 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/_parseaddr.py | python | AddrlistClass.getrouteaddr | (self) | return adlist | Parse a route address (Return-path value).
This method just skips all the route stuff and returns the addrspec. | Parse a route address (Return-path value). | [
"Parse",
"a",
"route",
"address",
"(",
"Return",
"-",
"path",
"value",
")",
"."
] | def getrouteaddr(self):
"""Parse a route address (Return-path value).
This method just skips all the route stuff and returns the addrspec.
"""
if self.field[self.pos] != '<':
return
expectroute = False
self.pos += 1
self.gotonext()
adlist = ''
while self.pos < len(self.field):
if expectroute:
self.getdomain()
expectroute = False
elif self.field[self.pos] == '>':
self.pos += 1
break
elif self.field[self.pos] == '@':
self.pos += 1
expectroute = True
elif self.field[self.pos] == ':':
self.pos += 1
else:
adlist = self.getaddrspec()
self.pos += 1
break
self.gotonext()
return adlist | [
"def",
"getrouteaddr",
"(",
"self",
")",
":",
"if",
"self",
".",
"field",
"[",
"self",
".",
"pos",
"]",
"!=",
"'<'",
":",
"return",
"expectroute",
"=",
"False",
"self",
".",
"pos",
"+=",
"1",
"self",
".",
"gotonext",
"(",
")",
"adlist",
"=",
"''",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/_parseaddr.py#L284-L314 | |
microsoft/LightGBM | 904b2d5158703c4900b68008617951dd2f9ff21b | python-package/lightgbm/basic.py | python | Dataset.__init_from_seqs | (self, seqs: List[Sequence], ref_dataset: Optional['Dataset'] = None) | return self | Initialize data from list of Sequence objects.
Sequence: Generic Data Access Object
Supports random access and access by batch if properly defined by user
Data scheme uniformity are trusted, not checked | Initialize data from list of Sequence objects. | [
"Initialize",
"data",
"from",
"list",
"of",
"Sequence",
"objects",
"."
] | def __init_from_seqs(self, seqs: List[Sequence], ref_dataset: Optional['Dataset'] = None):
"""
Initialize data from list of Sequence objects.
Sequence: Generic Data Access Object
Supports random access and access by batch if properly defined by user
Data scheme uniformity are trusted, not checked
"""
total_nrow = sum(len(seq) for seq in seqs)
# create validation dataset from ref_dataset
if ref_dataset is not None:
self._init_from_ref_dataset(total_nrow, ref_dataset)
else:
param_str = param_dict_to_str(self.get_params())
sample_cnt = _get_sample_count(total_nrow, param_str)
sample_data, col_indices = self.__sample(seqs, total_nrow)
self._init_from_sample(sample_data, col_indices, sample_cnt, total_nrow)
for seq in seqs:
nrow = len(seq)
batch_size = getattr(seq, 'batch_size', None) or Sequence.batch_size
for start in range(0, nrow, batch_size):
end = min(start + batch_size, nrow)
self._push_rows(seq[start:end])
return self | [
"def",
"__init_from_seqs",
"(",
"self",
",",
"seqs",
":",
"List",
"[",
"Sequence",
"]",
",",
"ref_dataset",
":",
"Optional",
"[",
"'Dataset'",
"]",
"=",
"None",
")",
":",
"total_nrow",
"=",
"sum",
"(",
"len",
"(",
"seq",
")",
"for",
"seq",
"in",
"seq... | https://github.com/microsoft/LightGBM/blob/904b2d5158703c4900b68008617951dd2f9ff21b/python-package/lightgbm/basic.py#L1560-L1587 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGridManager.GetColumnCount | (*args, **kwargs) | return _propgrid.PropertyGridManager_GetColumnCount(*args, **kwargs) | GetColumnCount(self, int page=-1) -> int | GetColumnCount(self, int page=-1) -> int | [
"GetColumnCount",
"(",
"self",
"int",
"page",
"=",
"-",
"1",
")",
"-",
">",
"int"
] | def GetColumnCount(*args, **kwargs):
"""GetColumnCount(self, int page=-1) -> int"""
return _propgrid.PropertyGridManager_GetColumnCount(*args, **kwargs) | [
"def",
"GetColumnCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridManager_GetColumnCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L3454-L3456 | |
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/fixpy2.py | python | subst | (*k) | return do_subst | register a substitution function | register a substitution function | [
"register",
"a",
"substitution",
"function"
] | def subst(*k):
"""register a substitution function"""
def do_subst(fun):
for x in k:
try:
all_modifs[x].append(fun)
except KeyError:
all_modifs[x] = [fun]
return fun
return do_subst | [
"def",
"subst",
"(",
"*",
"k",
")",
":",
"def",
"do_subst",
"(",
"fun",
")",
":",
"for",
"x",
"in",
"k",
":",
"try",
":",
"all_modifs",
"[",
"x",
"]",
".",
"append",
"(",
"fun",
")",
"except",
"KeyError",
":",
"all_modifs",
"[",
"x",
"]",
"=",
... | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/fixpy2.py#L38-L47 | |
wesnoth/wesnoth | 6ccac5a5e8ff75303c9190c0da60580925cb32c0 | data/tools/wesnoth/wmltools3.py | python | Forest.neighbors | (self, fn1, fn2) | return self.clique[fn1] == self.clique[fn2] | Are two files from the same tree? | Are two files from the same tree? | [
"Are",
"two",
"files",
"from",
"the",
"same",
"tree?"
] | def neighbors(self, fn1, fn2):
"Are two files from the same tree?"
return self.clique[fn1] == self.clique[fn2] | [
"def",
"neighbors",
"(",
"self",
",",
"fn1",
",",
"fn2",
")",
":",
"return",
"self",
".",
"clique",
"[",
"fn1",
"]",
"==",
"self",
".",
"clique",
"[",
"fn2",
"]"
] | https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmltools3.py#L248-L250 | |
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | shell/pkg_resources.py | python | get_distribution | (dist) | return dist | Return a current distribution object for a Requirement or string | Return a current distribution object for a Requirement or string | [
"Return",
"a",
"current",
"distribution",
"object",
"for",
"a",
"Requirement",
"or",
"string"
] | def get_distribution(dist):
"""Return a current distribution object for a Requirement or string"""
if isinstance(dist,basestring): dist = Requirement.parse(dist)
if isinstance(dist,Requirement): dist = get_provider(dist)
if not isinstance(dist,Distribution):
raise TypeError("Expected string, Requirement, or Distribution", dist)
return dist | [
"def",
"get_distribution",
"(",
"dist",
")",
":",
"if",
"isinstance",
"(",
"dist",
",",
"basestring",
")",
":",
"dist",
"=",
"Requirement",
".",
"parse",
"(",
"dist",
")",
"if",
"isinstance",
"(",
"dist",
",",
"Requirement",
")",
":",
"dist",
"=",
"get... | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/shell/pkg_resources.py#L302-L308 | |
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/containers.py | python | BaseContainer.__getitem__ | (self, key) | return self._values[key] | Retrieves item by the specified key. | Retrieves item by the specified key. | [
"Retrieves",
"item",
"by",
"the",
"specified",
"key",
"."
] | def __getitem__(self, key):
"""Retrieves item by the specified key."""
return self._values[key] | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"_values",
"[",
"key",
"]"
] | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/containers.py#L65-L67 | |
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/otci/otci/otci.py | python | OTCI.set_router_selection_jitter | (self, jitter) | Set the ROUTER_SELECTION_JITTER value. | Set the ROUTER_SELECTION_JITTER value. | [
"Set",
"the",
"ROUTER_SELECTION_JITTER",
"value",
"."
] | def set_router_selection_jitter(self, jitter):
"""Set the ROUTER_SELECTION_JITTER value."""
self.execute_command(f'routerselectionjitter {jitter}') | [
"def",
"set_router_selection_jitter",
"(",
"self",
",",
"jitter",
")",
":",
"self",
".",
"execute_command",
"(",
"f'routerselectionjitter {jitter}'",
")"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/otci.py#L594-L596 | ||
CNugteren/CLBlast | 4500a03440e2cc54998c0edab366babf5e504d67 | scripts/generator/generator/routine.py | python | Routine.arguments_half | (self) | return (self.options_list() + self.sizes_list() +
list(chain(*[self.buffer_bis(b) for b in self.scalar_buffers_first()])) +
self.scalar_half_to_float("alpha") +
list(chain(*[self.buffer_bis(b) for b in self.buffers_first()])) +
self.scalar_half_to_float("beta") +
list(chain(*[self.buffer_bis(b) for b in self.buffers_second()])) +
list(chain(*[self.buffer_bis(b) for b in self.scalar_buffers_second()])) +
list(chain(*[self.scalar(s) for s in self.other_scalars()]))) | As above, but with conversions from half to float | As above, but with conversions from half to float | [
"As",
"above",
"but",
"with",
"conversions",
"from",
"half",
"to",
"float"
] | def arguments_half(self):
"""As above, but with conversions from half to float"""
return (self.options_list() + self.sizes_list() +
list(chain(*[self.buffer_bis(b) for b in self.scalar_buffers_first()])) +
self.scalar_half_to_float("alpha") +
list(chain(*[self.buffer_bis(b) for b in self.buffers_first()])) +
self.scalar_half_to_float("beta") +
list(chain(*[self.buffer_bis(b) for b in self.buffers_second()])) +
list(chain(*[self.buffer_bis(b) for b in self.scalar_buffers_second()])) +
list(chain(*[self.scalar(s) for s in self.other_scalars()]))) | [
"def",
"arguments_half",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"options_list",
"(",
")",
"+",
"self",
".",
"sizes_list",
"(",
")",
"+",
"list",
"(",
"chain",
"(",
"*",
"[",
"self",
".",
"buffer_bis",
"(",
"b",
")",
"for",
"b",
"in",
... | https://github.com/CNugteren/CLBlast/blob/4500a03440e2cc54998c0edab366babf5e504d67/scripts/generator/generator/routine.py#L651-L660 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | GridBagSizer.FindItem | (*args) | return _core_.GridBagSizer_FindItem(*args) | FindItem(self, item) -> GBSizerItem
Find the sizer item for the given window or subsizer, returns None if
not found. (non-recursive) | FindItem(self, item) -> GBSizerItem | [
"FindItem",
"(",
"self",
"item",
")",
"-",
">",
"GBSizerItem"
] | def FindItem(*args):
"""
FindItem(self, item) -> GBSizerItem
Find the sizer item for the given window or subsizer, returns None if
not found. (non-recursive)
"""
return _core_.GridBagSizer_FindItem(*args) | [
"def",
"FindItem",
"(",
"*",
"args",
")",
":",
"return",
"_core_",
".",
"GridBagSizer_FindItem",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L16019-L16026 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/_shard/sharded_tensor/__init__.py | python | empty | (sharding_spec: ShardingSpec,
*size,
dtype=None,
layout=torch.strided,
requires_grad=False,
pin_memory=False,
memory_format=torch.contiguous_format,
process_group=None,
init_rrefs=False) | return ShardedTensor(
sharding_spec,
*size,
dtype=dtype,
layout=layout,
requires_grad=requires_grad,
pin_memory=pin_memory,
memory_format=memory_format,
process_group=process_group,
init_rrefs=init_rrefs,
) | Returns a :class:`ShardedTensor` filled with uninitialized data.
Needs to be called on all ranks in an SPMD fashion.
Args:
sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
describing how to shard the Tensor.
size (int...): a sequence of integers defining the shape of the output
tensor. Can be a variable number of arguments or a collection like a list or tuple.
Keyword args:
dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
Default: if ``None``, uses a global default (see :func:`torch.set_default_tensor_type`).
layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
Default: ``torch.strided``.
requires_grad (bool, optional): If autograd should record operations on the
returned tensor. Default: ``False``.
pin_memory (bool, optional): If set, returned tensor would be allocated in
the pinned memory. Works only for CPU tensors. Default: ``False``.
memory_format (:class:`torch.memory_format`, optional): the desired memory format of
returned Tensor. Default: ``torch.contiguous_format``.
process_group (ProcessGroup, optional): The process group to work on. If None,
the default process group will be used.
init_rrefs (bool, optional): Whether or not to initialize
:class:`torch.distributed.rpc.RRef`s pointing to remote shards.
Need to initialize the RPC Framework if specified as ``True``.
Default: ``False``.
Returns:
A :class:`ShardedTensor` object on each rank | Returns a :class:`ShardedTensor` filled with uninitialized data.
Needs to be called on all ranks in an SPMD fashion. | [
"Returns",
"a",
":",
"class",
":",
"ShardedTensor",
"filled",
"with",
"uninitialized",
"data",
".",
"Needs",
"to",
"be",
"called",
"on",
"all",
"ranks",
"in",
"an",
"SPMD",
"fashion",
"."
] | def empty(sharding_spec: ShardingSpec,
*size,
dtype=None,
layout=torch.strided,
requires_grad=False,
pin_memory=False,
memory_format=torch.contiguous_format,
process_group=None,
init_rrefs=False) -> ShardedTensor:
"""
Returns a :class:`ShardedTensor` filled with uninitialized data.
Needs to be called on all ranks in an SPMD fashion.
Args:
sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
describing how to shard the Tensor.
size (int...): a sequence of integers defining the shape of the output
tensor. Can be a variable number of arguments or a collection like a list or tuple.
Keyword args:
dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
Default: if ``None``, uses a global default (see :func:`torch.set_default_tensor_type`).
layout (:class:`torch.layout`, optional): the desired layout of returned Tensor.
Default: ``torch.strided``.
requires_grad (bool, optional): If autograd should record operations on the
returned tensor. Default: ``False``.
pin_memory (bool, optional): If set, returned tensor would be allocated in
the pinned memory. Works only for CPU tensors. Default: ``False``.
memory_format (:class:`torch.memory_format`, optional): the desired memory format of
returned Tensor. Default: ``torch.contiguous_format``.
process_group (ProcessGroup, optional): The process group to work on. If None,
the default process group will be used.
init_rrefs (bool, optional): Whether or not to initialize
:class:`torch.distributed.rpc.RRef`s pointing to remote shards.
Need to initialize the RPC Framework if specified as ``True``.
Default: ``False``.
Returns:
A :class:`ShardedTensor` object on each rank
"""
return ShardedTensor(
sharding_spec,
*size,
dtype=dtype,
layout=layout,
requires_grad=requires_grad,
pin_memory=pin_memory,
memory_format=memory_format,
process_group=process_group,
init_rrefs=init_rrefs,
) | [
"def",
"empty",
"(",
"sharding_spec",
":",
"ShardingSpec",
",",
"*",
"size",
",",
"dtype",
"=",
"None",
",",
"layout",
"=",
"torch",
".",
"strided",
",",
"requires_grad",
"=",
"False",
",",
"pin_memory",
"=",
"False",
",",
"memory_format",
"=",
"torch",
... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/_shard/sharded_tensor/__init__.py#L30-L80 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Window.SetHelpText | (*args, **kwargs) | return _core_.Window_SetHelpText(*args, **kwargs) | SetHelpText(self, String text)
Sets the help text to be used as context-sensitive help for this
window. Note that the text is actually stored by the current
`wx.HelpProvider` implementation, and not in the window object itself. | SetHelpText(self, String text) | [
"SetHelpText",
"(",
"self",
"String",
"text",
")"
] | def SetHelpText(*args, **kwargs):
"""
SetHelpText(self, String text)
Sets the help text to be used as context-sensitive help for this
window. Note that the text is actually stored by the current
`wx.HelpProvider` implementation, and not in the window object itself.
"""
return _core_.Window_SetHelpText(*args, **kwargs) | [
"def",
"SetHelpText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_SetHelpText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L11337-L11345 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.LineDownExtend | (*args, **kwargs) | return _stc.StyledTextCtrl_LineDownExtend(*args, **kwargs) | LineDownExtend(self)
Move caret down one line extending selection to new caret position. | LineDownExtend(self) | [
"LineDownExtend",
"(",
"self",
")"
] | def LineDownExtend(*args, **kwargs):
"""
LineDownExtend(self)
Move caret down one line extending selection to new caret position.
"""
return _stc.StyledTextCtrl_LineDownExtend(*args, **kwargs) | [
"def",
"LineDownExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_LineDownExtend",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L4335-L4341 | |
HKUST-Aerial-Robotics/Fast-Planner | 2ddd7793eecd573dbb5b47e2c985aa06606df3cf | uav_simulator/Utils/multi_map_server/quadrotor_msgs/src/quadrotor_msgs/msg/_Serial.py | python | Serial.__init__ | (self, *args, **kwds) | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
header,channel,type,data
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields. | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments. | [
"Constructor",
".",
"Any",
"message",
"fields",
"that",
"are",
"implicitly",
"/",
"explicitly",
"set",
"to",
"None",
"will",
"be",
"assigned",
"a",
"default",
"value",
".",
"The",
"recommend",
"use",
"is",
"keyword",
"arguments",
"as",
"this",
"is",
"more",
... | def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
header,channel,type,data
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(Serial, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.header is None:
self.header = std_msgs.msg.Header()
if self.channel is None:
self.channel = 0
if self.type is None:
self.type = 0
if self.data is None:
self.data = ''
else:
self.header = std_msgs.msg.Header()
self.channel = 0
self.type = 0
self.data = '' | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"args",
"or",
"kwds",
":",
"super",
"(",
"Serial",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"#message fields cannot be ... | https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/multi_map_server/quadrotor_msgs/src/quadrotor_msgs/msg/_Serial.py#L57-L86 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py | python | _MaskedBinaryOperation.__call__ | (self, a, b, *args, **kwargs) | return masked_result | Execute the call behavior. | Execute the call behavior. | [
"Execute",
"the",
"call",
"behavior",
"."
] | def __call__(self, a, b, *args, **kwargs):
"""
Execute the call behavior.
"""
# Get the data, as ndarray
(da, db) = (getdata(a), getdata(b))
# Get the result
with np.errstate():
np.seterr(divide='ignore', invalid='ignore')
result = self.f(da, db, *args, **kwargs)
# Get the mask for the result
(ma, mb) = (getmask(a), getmask(b))
if ma is nomask:
if mb is nomask:
m = nomask
else:
m = umath.logical_or(getmaskarray(a), mb)
elif mb is nomask:
m = umath.logical_or(ma, getmaskarray(b))
else:
m = umath.logical_or(ma, mb)
# Case 1. : scalar
if not result.ndim:
if m:
return masked
return result
# Case 2. : array
# Revert result to da where masked
if m is not nomask and m.any():
# any errors, just abort; impossible to guarantee masked values
try:
np.copyto(result, da, casting='unsafe', where=m)
except Exception:
pass
# Transforms to a (subclass of) MaskedArray
masked_result = result.view(get_masked_subclass(a, b))
masked_result._mask = m
if isinstance(a, MaskedArray):
masked_result._update_from(a)
elif isinstance(b, MaskedArray):
masked_result._update_from(b)
return masked_result | [
"def",
"__call__",
"(",
"self",
",",
"a",
",",
"b",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get the data, as ndarray",
"(",
"da",
",",
"db",
")",
"=",
"(",
"getdata",
"(",
"a",
")",
",",
"getdata",
"(",
"b",
")",
")",
"# Get the r... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L1016-L1061 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/fuchsia/common.py | python | SubprocessCallWithTimeout | (command, silent=False, timeout_secs=None) | return process.returncode, out, err | Helper function for running a command.
Args:
command: The command to run.
silent: If true, stdout and stderr of the command will not be printed.
timeout_secs: Maximum amount of time allowed for the command to finish.
Returns:
A tuple of (return code, stdout, stderr) of the command. Raises
an exception if the subprocess times out. | Helper function for running a command. | [
"Helper",
"function",
"for",
"running",
"a",
"command",
"."
] | def SubprocessCallWithTimeout(command, silent=False, timeout_secs=None):
"""Helper function for running a command.
Args:
command: The command to run.
silent: If true, stdout and stderr of the command will not be printed.
timeout_secs: Maximum amount of time allowed for the command to finish.
Returns:
A tuple of (return code, stdout, stderr) of the command. Raises
an exception if the subprocess times out.
"""
if silent:
devnull = open(os.devnull, 'w')
process = subprocess.Popen(command,
stdout=devnull,
stderr=devnull,
text=True)
else:
process = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True)
timeout_timer = None
if timeout_secs:
def interrupt_process():
process.send_signal(signal.SIGKILL)
timeout_timer = threading.Timer(timeout_secs, interrupt_process)
# Ensure that keyboard interrupts are handled properly (crbug/1198113).
timeout_timer.daemon = True
timeout_timer.start()
out, err = process.communicate()
if timeout_timer:
timeout_timer.cancel()
if process.returncode == -9:
raise Exception('Timeout when executing \"%s\".' % ' '.join(command))
return process.returncode, out, err | [
"def",
"SubprocessCallWithTimeout",
"(",
"command",
",",
"silent",
"=",
"False",
",",
"timeout_secs",
"=",
"None",
")",
":",
"if",
"silent",
":",
"devnull",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"process",
"=",
"subprocess",
".",
"Pope... | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/fuchsia/common.py#L106-L150 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/email/_header_value_parser.py | python | get_obs_local_part | (value) | return obs_local_part, value | obs-local-part = word *("." word) | obs-local-part = word *("." word) | [
"obs",
"-",
"local",
"-",
"part",
"=",
"word",
"*",
"(",
".",
"word",
")"
] | def get_obs_local_part(value):
""" obs-local-part = word *("." word)
"""
obs_local_part = ObsLocalPart()
last_non_ws_was_dot = False
while value and (value[0]=='\\' or value[0] not in PHRASE_ENDS):
if value[0] == '.':
if last_non_ws_was_dot:
obs_local_part.defects.append(errors.InvalidHeaderDefect(
"invalid repeated '.'"))
obs_local_part.append(DOT)
last_non_ws_was_dot = True
value = value[1:]
continue
elif value[0]=='\\':
obs_local_part.append(ValueTerminal(value[0],
'misplaced-special'))
value = value[1:]
obs_local_part.defects.append(errors.InvalidHeaderDefect(
"'\\' character outside of quoted-string/ccontent"))
last_non_ws_was_dot = False
continue
if obs_local_part and obs_local_part[-1].token_type != 'dot':
obs_local_part.defects.append(errors.InvalidHeaderDefect(
"missing '.' between words"))
try:
token, value = get_word(value)
last_non_ws_was_dot = False
except errors.HeaderParseError:
if value[0] not in CFWS_LEADER:
raise
token, value = get_cfws(value)
obs_local_part.append(token)
if (obs_local_part[0].token_type == 'dot' or
obs_local_part[0].token_type=='cfws' and
obs_local_part[1].token_type=='dot'):
obs_local_part.defects.append(errors.InvalidHeaderDefect(
"Invalid leading '.' in local part"))
if (obs_local_part[-1].token_type == 'dot' or
obs_local_part[-1].token_type=='cfws' and
obs_local_part[-2].token_type=='dot'):
obs_local_part.defects.append(errors.InvalidHeaderDefect(
"Invalid trailing '.' in local part"))
if obs_local_part.defects:
obs_local_part.token_type = 'invalid-obs-local-part'
return obs_local_part, value | [
"def",
"get_obs_local_part",
"(",
"value",
")",
":",
"obs_local_part",
"=",
"ObsLocalPart",
"(",
")",
"last_non_ws_was_dot",
"=",
"False",
"while",
"value",
"and",
"(",
"value",
"[",
"0",
"]",
"==",
"'\\\\'",
"or",
"value",
"[",
"0",
"]",
"not",
"in",
"P... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/_header_value_parser.py#L1476-L1521 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/SimpleXMLRPCServer.py | python | SimpleXMLRPCDispatcher._marshaled_dispatch | (self, data, dispatch_method = None, path = None) | return response | Dispatches an XML-RPC method from marshalled (XML) data.
XML-RPC methods are dispatched from the marshalled (XML) data
using the _dispatch method and the result is returned as
marshalled data. For backwards compatibility, a dispatch
function can be provided as an argument (see comment in
SimpleXMLRPCRequestHandler.do_POST) but overriding the
existing method through subclassing is the preferred means
of changing method dispatch behavior. | Dispatches an XML-RPC method from marshalled (XML) data. | [
"Dispatches",
"an",
"XML",
"-",
"RPC",
"method",
"from",
"marshalled",
"(",
"XML",
")",
"data",
"."
] | def _marshaled_dispatch(self, data, dispatch_method = None, path = None):
"""Dispatches an XML-RPC method from marshalled (XML) data.
XML-RPC methods are dispatched from the marshalled (XML) data
using the _dispatch method and the result is returned as
marshalled data. For backwards compatibility, a dispatch
function can be provided as an argument (see comment in
SimpleXMLRPCRequestHandler.do_POST) but overriding the
existing method through subclassing is the preferred means
of changing method dispatch behavior.
"""
try:
params, method = xmlrpclib.loads(data)
# generate response
if dispatch_method is not None:
response = dispatch_method(method, params)
else:
response = self._dispatch(method, params)
# wrap response in a singleton tuple
response = (response,)
response = xmlrpclib.dumps(response, methodresponse=1,
allow_none=self.allow_none, encoding=self.encoding)
except Fault, fault:
response = xmlrpclib.dumps(fault, allow_none=self.allow_none,
encoding=self.encoding)
except:
# report exception back to server
exc_type, exc_value, exc_tb = sys.exc_info()
response = xmlrpclib.dumps(
xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)),
encoding=self.encoding, allow_none=self.allow_none,
)
return response | [
"def",
"_marshaled_dispatch",
"(",
"self",
",",
"data",
",",
"dispatch_method",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"try",
":",
"params",
",",
"method",
"=",
"xmlrpclib",
".",
"loads",
"(",
"data",
")",
"# generate response",
"if",
"dispatch_m... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/SimpleXMLRPCServer.py#L241-L276 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/search/plugin/poi_search_handler.py | python | POISearch.__CreateBboxFromParameters | (self, latcenter, loncenter, latspan, lonspan) | return bbox | Create a bounding box string for bounding box queries.
Args:
latcenter: latitude centre in degrees.
loncenter: longitude centre in degrees.
latspan: full latitude span in degrees.
lonspan: full longitude span in degrees.
Returns:
The bounding box string. | Create a bounding box string for bounding box queries. | [
"Create",
"a",
"bounding",
"box",
"string",
"for",
"bounding",
"box",
"queries",
"."
] | def __CreateBboxFromParameters(self, latcenter, loncenter, latspan, lonspan):
"""Create a bounding box string for bounding box queries.
Args:
latcenter: latitude centre in degrees.
loncenter: longitude centre in degrees.
latspan: full latitude span in degrees.
lonspan: full longitude span in degrees.
Returns:
The bounding box string.
"""
(xmin, xmax, ymin, ymax) = self.__GetBBoxBounds(
latcenter, loncenter, latspan, lonspan)
bbox = "ST_SetSRID('BOX3D(%s %s,%s %s)'::box3d,%s)" %(
xmin, ymin, xmax, ymax, self.srid)
return bbox | [
"def",
"__CreateBboxFromParameters",
"(",
"self",
",",
"latcenter",
",",
"loncenter",
",",
"latspan",
",",
"lonspan",
")",
":",
"(",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
")",
"=",
"self",
".",
"__GetBBoxBounds",
"(",
"latcenter",
",",
"loncenter"... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/search/plugin/poi_search_handler.py#L814-L830 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/fuzzbunch/fuzzbunch.py | python | Fuzzbunch.do_toolpaste | (self, input) | Paste and convert data from external tool output | Paste and convert data from external tool output | [
"Paste",
"and",
"convert",
"data",
"from",
"external",
"tool",
"output"
] | def do_toolpaste(self, input):
"""Paste and convert data from external tool output"""
argc, argv = util.parseinput(input, 2)
if argc in (0,1):
self.help_toolpaste()
elif argc == 2:
try:
self.conv_tools[argv[0]](argv[1])
except KeyError:
raise exception.CmdErr, "Invalid input" | [
"def",
"do_toolpaste",
"(",
"self",
",",
"input",
")",
":",
"argc",
",",
"argv",
"=",
"util",
".",
"parseinput",
"(",
"input",
",",
"2",
")",
"if",
"argc",
"in",
"(",
"0",
",",
"1",
")",
":",
"self",
".",
"help_toolpaste",
"(",
")",
"elif",
"argc... | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/fuzzbunch.py#L830-L839 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | MouseEvent.Aux2DClick | (*args, **kwargs) | return _core_.MouseEvent_Aux2DClick(*args, **kwargs) | Aux2DClick(self) -> bool
Returns true if the event was a AUX2 button double click. | Aux2DClick(self) -> bool | [
"Aux2DClick",
"(",
"self",
")",
"-",
">",
"bool"
] | def Aux2DClick(*args, **kwargs):
"""
Aux2DClick(self) -> bool
Returns true if the event was a AUX2 button double click.
"""
return _core_.MouseEvent_Aux2DClick(*args, **kwargs) | [
"def",
"Aux2DClick",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MouseEvent_Aux2DClick",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L5737-L5743 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mox3/mox3/mox.py | python | Reset | (*args) | Reset mocks.
Args:
# args is any number of mocks to be reset. | Reset mocks. | [
"Reset",
"mocks",
"."
] | def Reset(*args):
"""Reset mocks.
Args:
# args is any number of mocks to be reset.
"""
for mock in args:
mock._Reset() | [
"def",
"Reset",
"(",
"*",
"args",
")",
":",
"for",
"mock",
"in",
"args",
":",
"mock",
".",
"_Reset",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mox3/mox3/mox.py#L417-L425 | ||
Illumina/strelka | d7377443b62319f7c7bd70c241c4b2df3459e29a | src/python/lib/snoiseWorkflow.py | python | callGenome | (self,taskPrefix="",dependencies=None) | return nextStepWait | run variant caller on all genome segments | run variant caller on all genome segments | [
"run",
"variant",
"caller",
"on",
"all",
"genome",
"segments"
] | def callGenome(self,taskPrefix="",dependencies=None):
"""
run variant caller on all genome segments
"""
tmpGraphDir=self.paths.getTmpSegmentDir()
dirTask=self.addTask(preJoin(taskPrefix,"makeTmpDir"), "mkdir -p "+tmpGraphDir, dependencies=dependencies, isForceLocal=True)
graphTasks = set()
segFiles = TempSegmentFiles()
for gseg in getNextGenomeSegment(self.params) :
graphTasks |= callGenomeSegment(self, gseg, segFiles, dependencies=dirTask)
# create a checkpoint for all segments:
completeSegmentsTask = self.addTask(preJoin(taskPrefix,"completedAllGenomeSegments"),dependencies=graphTasks)
finishTasks = set()
def finishVcf(tmpList, output, label) :
assert(len(tmpList) > 0)
if len(tmpList) > 1 :
catCmd=[self.params.bgcatBin,"-o",output]
catCmd.extend(tmpList)
catCmd = " ".join(catCmd)
else :
catCmd="mv -f %s %s" % (tmpList[0],output)
catCmd += " && %s -p vcf %s" % (self.params.tabixBin, output)
finishTasks.add(self.addTask(preJoin(taskPrefix,label+"_finalizeVCF"), catCmd, dependencies=completeSegmentsTask))
finishVcf(segFiles.gvcf, self.paths.getGvcfOutputPath(),"gVCF")
cleanTask=self.addTask(preJoin(taskPrefix,"cleanTmpDir"), "rm -rf "+tmpGraphDir, dependencies=finishTasks, isForceLocal=True)
nextStepWait = finishTasks
return nextStepWait | [
"def",
"callGenome",
"(",
"self",
",",
"taskPrefix",
"=",
"\"\"",
",",
"dependencies",
"=",
"None",
")",
":",
"tmpGraphDir",
"=",
"self",
".",
"paths",
".",
"getTmpSegmentDir",
"(",
")",
"dirTask",
"=",
"self",
".",
"addTask",
"(",
"preJoin",
"(",
"taskP... | https://github.com/Illumina/strelka/blob/d7377443b62319f7c7bd70c241c4b2df3459e29a/src/python/lib/snoiseWorkflow.py#L93-L132 | |
ROCmSoftwarePlatform/hipCaffe | 4ec5d482515cce532348553b6db6d00d015675d5 | python/caffe/pycaffe.py | python | _Net_blob_loss_weights | (self) | return self._blob_loss_weights_dict | An OrderedDict (bottom to top, i.e., input to output) of network
blob loss weights indexed by name | An OrderedDict (bottom to top, i.e., input to output) of network
blob loss weights indexed by name | [
"An",
"OrderedDict",
"(",
"bottom",
"to",
"top",
"i",
".",
"e",
".",
"input",
"to",
"output",
")",
"of",
"network",
"blob",
"loss",
"weights",
"indexed",
"by",
"name"
] | def _Net_blob_loss_weights(self):
"""
An OrderedDict (bottom to top, i.e., input to output) of network
blob loss weights indexed by name
"""
if not hasattr(self, '_blobs_loss_weights_dict'):
self._blob_loss_weights_dict = OrderedDict(zip(self._blob_names,
self._blob_loss_weights))
return self._blob_loss_weights_dict | [
"def",
"_Net_blob_loss_weights",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_blobs_loss_weights_dict'",
")",
":",
"self",
".",
"_blob_loss_weights_dict",
"=",
"OrderedDict",
"(",
"zip",
"(",
"self",
".",
"_blob_names",
",",
"self",
".",... | https://github.com/ROCmSoftwarePlatform/hipCaffe/blob/4ec5d482515cce532348553b6db6d00d015675d5/python/caffe/pycaffe.py#L36-L44 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/ogr.py | python | Geometry.MakeValid | (self, *args) | return _ogr.Geometry_MakeValid(self, *args) | r"""
MakeValid(Geometry self, char ** options=None) -> Geometry
OGRGeometryH
OGR_G_MakeValid(OGRGeometryH hGeom)
Attempts to make an invalid geometry valid without losing vertices.
Already-valid geometries are cloned without further intervention.
This function is the same as the C++ method OGRGeometry::MakeValid().
This function is built on the GEOS >= 3.8 library, check it for the
definition of the geometry operation. If OGR is built without the GEOS
>= 3.8 library, this function will return a clone of the input
geometry if it is valid, or NULL if it is invalid
Parameters:
-----------
hGeom: The Geometry to make valid.
a newly allocated geometry now owned by the caller, or NULL on
failure.
GDAL 3.0 | r"""
MakeValid(Geometry self, char ** options=None) -> Geometry
OGRGeometryH
OGR_G_MakeValid(OGRGeometryH hGeom) | [
"r",
"MakeValid",
"(",
"Geometry",
"self",
"char",
"**",
"options",
"=",
"None",
")",
"-",
">",
"Geometry",
"OGRGeometryH",
"OGR_G_MakeValid",
"(",
"OGRGeometryH",
"hGeom",
")"
] | def MakeValid(self, *args):
r"""
MakeValid(Geometry self, char ** options=None) -> Geometry
OGRGeometryH
OGR_G_MakeValid(OGRGeometryH hGeom)
Attempts to make an invalid geometry valid without losing vertices.
Already-valid geometries are cloned without further intervention.
This function is the same as the C++ method OGRGeometry::MakeValid().
This function is built on the GEOS >= 3.8 library, check it for the
definition of the geometry operation. If OGR is built without the GEOS
>= 3.8 library, this function will return a clone of the input
geometry if it is valid, or NULL if it is invalid
Parameters:
-----------
hGeom: The Geometry to make valid.
a newly allocated geometry now owned by the caller, or NULL on
failure.
GDAL 3.0
"""
return _ogr.Geometry_MakeValid(self, *args) | [
"def",
"MakeValid",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_ogr",
".",
"Geometry_MakeValid",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L6237-L6264 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | Caret.GetPositionTuple | (*args, **kwargs) | return _misc_.Caret_GetPositionTuple(*args, **kwargs) | GetPositionTuple() -> (x,y) | GetPositionTuple() -> (x,y) | [
"GetPositionTuple",
"()",
"-",
">",
"(",
"x",
"y",
")"
] | def GetPositionTuple(*args, **kwargs):
"""GetPositionTuple() -> (x,y)"""
return _misc_.Caret_GetPositionTuple(*args, **kwargs) | [
"def",
"GetPositionTuple",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Caret_GetPositionTuple",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L758-L760 | |
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/rootDataModel.py | python | RootDataModel.useExtentsHint | (self, value) | Set whether whether bounding box calculations should use extents
from prims. | Set whether whether bounding box calculations should use extents
from prims. | [
"Set",
"whether",
"whether",
"bounding",
"box",
"calculations",
"should",
"use",
"extents",
"from",
"prims",
"."
] | def useExtentsHint(self, value):
"""Set whether whether bounding box calculations should use extents
from prims.
"""
if not isinstance(value, bool):
raise ValueError("useExtentsHint must be of type bool.")
if value != self._bboxCache.GetUseExtentsHint():
# Unfortunate that we must blow the entire BBoxCache, but we have no
# other alternative, currently.
purposes = self._bboxCache.GetIncludedPurposes()
self._bboxCache = UsdGeom.BBoxCache(
self._currentFrame, purposes, value) | [
"def",
"useExtentsHint",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"ValueError",
"(",
"\"useExtentsHint must be of type bool.\"",
")",
"if",
"value",
"!=",
"self",
".",
"_bboxCache",
".",
"G... | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/rootDataModel.py#L166-L179 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | bindings/experimental/distrdf/python/DistRDF/Proxy.py | python | _managed_tcontext | () | Factory function, decorated with `contextlib.contextmanager` to make it
work in a `with` context manager. It creates a `ROOT.TDirectory.TContext`
that will store the current `ROOT.gDirectory` variable. At the end of the
context, the C++ destructor of the `TContext` object will be explicitly
called, thanks to the `__destruct__` dunder method implemented in PyROOT.
This will restore the `gDirectory` variable to its initial value, allowing
changing it in the context manager without permanent effects. | Factory function, decorated with `contextlib.contextmanager` to make it
work in a `with` context manager. It creates a `ROOT.TDirectory.TContext`
that will store the current `ROOT.gDirectory` variable. At the end of the
context, the C++ destructor of the `TContext` object will be explicitly
called, thanks to the `__destruct__` dunder method implemented in PyROOT.
This will restore the `gDirectory` variable to its initial value, allowing
changing it in the context manager without permanent effects. | [
"Factory",
"function",
"decorated",
"with",
"contextlib",
".",
"contextmanager",
"to",
"make",
"it",
"work",
"in",
"a",
"with",
"context",
"manager",
".",
"It",
"creates",
"a",
"ROOT",
".",
"TDirectory",
".",
"TContext",
"that",
"will",
"store",
"the",
"curr... | def _managed_tcontext():
"""
Factory function, decorated with `contextlib.contextmanager` to make it
work in a `with` context manager. It creates a `ROOT.TDirectory.TContext`
that will store the current `ROOT.gDirectory` variable. At the end of the
context, the C++ destructor of the `TContext` object will be explicitly
called, thanks to the `__destruct__` dunder method implemented in PyROOT.
This will restore the `gDirectory` variable to its initial value, allowing
changing it in the context manager without permanent effects.
"""
try:
ctxt = ROOT.TDirectory.TContext()
yield None
finally:
ctxt.__destruct__() | [
"def",
"_managed_tcontext",
"(",
")",
":",
"try",
":",
"ctxt",
"=",
"ROOT",
".",
"TDirectory",
".",
"TContext",
"(",
")",
"yield",
"None",
"finally",
":",
"ctxt",
".",
"__destruct__",
"(",
")"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/bindings/experimental/distrdf/python/DistRDF/Proxy.py#L28-L42 | ||
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/meshtools/quality.py | python | eta | (cell) | return 4 * np.sqrt(3) * cell.size() / np.sum(_boundaryLengths(cell)**2) | r"""Return default triangle quality (eta) of a given cell.
The quality measure relates the area of the triangle (a)
to its edge lengths (l1, l2, l3).
.. math::
\eta = \frac{4\sqrt{3}a}{l_1^2 + l_2^2 + l_3^2} | r"""Return default triangle quality (eta) of a given cell. | [
"r",
"Return",
"default",
"triangle",
"quality",
"(",
"eta",
")",
"of",
"a",
"given",
"cell",
"."
] | def eta(cell):
r"""Return default triangle quality (eta) of a given cell.
The quality measure relates the area of the triangle (a)
to its edge lengths (l1, l2, l3).
.. math::
\eta = \frac{4\sqrt{3}a}{l_1^2 + l_2^2 + l_3^2}
"""
return 4 * np.sqrt(3) * cell.size() / np.sum(_boundaryLengths(cell)**2) | [
"def",
"eta",
"(",
"cell",
")",
":",
"return",
"4",
"*",
"np",
".",
"sqrt",
"(",
"3",
")",
"*",
"cell",
".",
"size",
"(",
")",
"/",
"np",
".",
"sum",
"(",
"_boundaryLengths",
"(",
"cell",
")",
"**",
"2",
")"
] | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/meshtools/quality.py#L76-L86 | |
sfzhang15/RefineDet | 52b6fe23dc1a160fe710b7734576dca509bf4fae | python/caffe/io.py | python | Transformer.preprocess | (self, in_, data) | return caffe_in | Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net | Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature | [
"Format",
"input",
"for",
"Caffe",
":",
"-",
"convert",
"to",
"single",
"-",
"resize",
"to",
"input",
"dimensions",
"(",
"preserving",
"number",
"of",
"channels",
")",
"-",
"transpose",
"dimensions",
"to",
"K",
"x",
"H",
"x",
"W",
"-",
"reorder",
"channe... | def preprocess(self, in_, data):
"""
Format input for Caffe:
- convert to single
- resize to input dimensions (preserving number of channels)
- transpose dimensions to K x H x W
- reorder channels (for instance color to BGR)
- scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models)
- subtract mean
- scale feature
Parameters
----------
in_ : name of input blob to preprocess for
data : (H' x W' x K) ndarray
Returns
-------
caffe_in : (K x H x W) ndarray for input to a Net
"""
self.__check_input(in_)
caffe_in = data.astype(np.float32, copy=False)
transpose = self.transpose.get(in_)
channel_swap = self.channel_swap.get(in_)
raw_scale = self.raw_scale.get(in_)
mean = self.mean.get(in_)
input_scale = self.input_scale.get(in_)
in_dims = self.inputs[in_][2:]
if caffe_in.shape[:2] != in_dims:
caffe_in = resize_image(caffe_in, in_dims)
if transpose is not None:
caffe_in = caffe_in.transpose(transpose)
if channel_swap is not None:
caffe_in = caffe_in[channel_swap, :, :]
if raw_scale is not None:
caffe_in *= raw_scale
if mean is not None:
caffe_in -= mean
if input_scale is not None:
caffe_in *= input_scale
return caffe_in | [
"def",
"preprocess",
"(",
"self",
",",
"in_",
",",
"data",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"caffe_in",
"=",
"data",
".",
"astype",
"(",
"np",
".",
"float32",
",",
"copy",
"=",
"False",
")",
"transpose",
"=",
"self",
".",
"t... | https://github.com/sfzhang15/RefineDet/blob/52b6fe23dc1a160fe710b7734576dca509bf4fae/python/caffe/io.py#L122-L162 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/tools/tensorflow_builder/config_detector/config_detector.py | python | get_cudnn_version | () | Retrieves the version of cuDNN library detected.
Returns:
String that is the version of cuDNN library detected.
e.g. '7.5.0' | Retrieves the version of cuDNN library detected. | [
"Retrieves",
"the",
"version",
"of",
"cuDNN",
"library",
"detected",
"."
] | def get_cudnn_version():
"""Retrieves the version of cuDNN library detected.
Returns:
String that is the version of cuDNN library detected.
e.g. '7.5.0'
"""
key = "cudnn_ver"
cmds = cmds_all[PLATFORM.lower()][key]
out, err = run_shell_cmd(cmds[0])
if err and FLAGS.debug:
print("Error in finding `cudnn.h`:\n %s" % str(err))
if len(out.split(b" ")) > 1:
cmd = cmds[0] + " | " + cmds[1]
out_re, err_re = run_shell_cmd(cmd)
if err_re and FLAGS.debug:
print("Error in detecting cuDNN version:\n %s" % str(err_re))
return out_re.strip(b"\n")
else:
return | [
"def",
"get_cudnn_version",
"(",
")",
":",
"key",
"=",
"\"cudnn_ver\"",
"cmds",
"=",
"cmds_all",
"[",
"PLATFORM",
".",
"lower",
"(",
")",
"]",
"[",
"key",
"]",
"out",
",",
"err",
"=",
"run_shell_cmd",
"(",
"cmds",
"[",
"0",
"]",
")",
"if",
"err",
"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/tools/tensorflow_builder/config_detector/config_detector.py#L398-L419 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | GridEvent.ShiftDown | (*args, **kwargs) | return _grid.GridEvent_ShiftDown(*args, **kwargs) | ShiftDown(self) -> bool | ShiftDown(self) -> bool | [
"ShiftDown",
"(",
"self",
")",
"-",
">",
"bool"
] | def ShiftDown(*args, **kwargs):
"""ShiftDown(self) -> bool"""
return _grid.GridEvent_ShiftDown(*args, **kwargs) | [
"def",
"ShiftDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridEvent_ShiftDown",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L2329-L2331 | |
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/loader/base.py | python | ILoader.fill_minibatch | () | Fills minibatch data labels and indexes according to the current
shuffle (minibatch_indices[:self.minibatch_size]). | Fills minibatch data labels and indexes according to the current
shuffle (minibatch_indices[:self.minibatch_size]). | [
"Fills",
"minibatch",
"data",
"labels",
"and",
"indexes",
"according",
"to",
"the",
"current",
"shuffle",
"(",
"minibatch_indices",
"[",
":",
"self",
".",
"minibatch_size",
"]",
")",
"."
] | def fill_minibatch():
"""Fills minibatch data labels and indexes according to the current
shuffle (minibatch_indices[:self.minibatch_size]).
""" | [
"def",
"fill_minibatch",
"(",
")",
":"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/loader/base.py#L112-L115 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/simplejson/decoder.py | python | JSONDecoder.decode | (self, s, _w=WHITESPACE.match) | return obj | Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document) | Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document) | [
"Return",
"the",
"Python",
"representation",
"of",
"s",
"(",
"a",
"str",
"or",
"unicode",
"instance",
"containing",
"a",
"JSON",
"document",
")"
] | def decode(self, s, _w=WHITESPACE.match):
"""
Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document)
"""
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
end = _w(s, end).end()
if end != len(s):
raise ValueError(errmsg("Extra data", s, end, len(s)))
return obj | [
"def",
"decode",
"(",
"self",
",",
"s",
",",
"_w",
"=",
"WHITESPACE",
".",
"match",
")",
":",
"obj",
",",
"end",
"=",
"self",
".",
"raw_decode",
"(",
"s",
",",
"idx",
"=",
"_w",
"(",
"s",
",",
"0",
")",
".",
"end",
"(",
")",
")",
"end",
"="... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/simplejson/decoder.py#L246-L255 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/while_v2_indexed_slices_rewriter.py | python | _rewrite_output_as_tensor | (body_grad_graph, grad_output_slices) | Rewrites grad_output_slices to be a Tensor output.
Args:
body_grad_graph: _WhileBodyGradFuncGraph.
grad_output_slices: IndexedSlices output of body_grad_graph. | Rewrites grad_output_slices to be a Tensor output. | [
"Rewrites",
"grad_output_slices",
"to",
"be",
"a",
"Tensor",
"output",
"."
] | def _rewrite_output_as_tensor(body_grad_graph, grad_output_slices):
"""Rewrites grad_output_slices to be a Tensor output.
Args:
body_grad_graph: _WhileBodyGradFuncGraph.
grad_output_slices: IndexedSlices output of body_grad_graph.
"""
with body_grad_graph.as_default():
new_output = ops.convert_to_tensor_v2(grad_output_slices)
idx = _get_tensor_index_in_iterable(body_grad_graph.structured_outputs,
grad_output_slices)
body_grad_graph.structured_outputs[idx] = new_output
body_grad_graph.outputs = func_graph.flatten(
body_grad_graph.structured_outputs) | [
"def",
"_rewrite_output_as_tensor",
"(",
"body_grad_graph",
",",
"grad_output_slices",
")",
":",
"with",
"body_grad_graph",
".",
"as_default",
"(",
")",
":",
"new_output",
"=",
"ops",
".",
"convert_to_tensor_v2",
"(",
"grad_output_slices",
")",
"idx",
"=",
"_get_ten... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/while_v2_indexed_slices_rewriter.py#L91-L105 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/configgenerator.py | python | ConfigGenerator.add_device_data_template | (self) | return entry | Injects device data template
This must be populated by hand with valid data | Injects device data template
This must be populated by hand with valid data | [
"Injects",
"device",
"data",
"template",
"This",
"must",
"be",
"populated",
"by",
"hand",
"with",
"valid",
"data"
] | def add_device_data_template(self):
"""
Injects device data template
This must be populated by hand with valid data
"""
# Create new entry
entry = ETree.Element("entry")
# Add type
d_type = ETree.Element("type")
d_type.text = "D_ICSP"
entry.append(d_type)
# Fetch info providers for retrieving device info
flash_info = self.device_memory_info.memory_info_by_name(MemoryNames.FLASH)
eeprom_info = self.device_memory_info.memory_info_by_name(MemoryNames.EEPROM)
user_id_info = self.device_memory_info.memory_info_by_name(MemoryNames.USER_ID)
config_word_info = self.device_memory_info.memory_info_by_name(MemoryNames.CONFIG_WORD)
device_info = self.device_memory_info.device
# Add fields
entry.append(self._add_data("PIC_FLASH_BASE_W", "0x{0:08X}".format(flash_info['address']//2)))
entry.append(self._add_data("PIC_EEPROM_BASE_W", "0x{0:08X}".format(eeprom_info['address']//2)))
entry.append(self._add_data("PIC_USER_ID_BASE_W", "0x{0:08X}".format(user_id_info['address']//2)))
entry.append(self._add_data("PIC_CONFIG_BASE_W", "0x{0:08X}".format(config_word_info['address']//2)))
entry.append(self._add_data("PIC_FLASH_SIZE_W", "0x{0:08X}".format(flash_info['size']//2)))
entry.append(self._add_data("PIC_EEPROM_SIZE_B", "0x{0:04X}".format(eeprom_info['size'])))
entry.append(self._add_data("PIC_USER_ID_SIZE_W", "{}".format(user_id_info['size']//2)))
entry.append(self._add_data("PIC_CONFIG_SIZE_W", "{}".format(config_word_info['size']//2)))
entry.append(self._add_data("PIC_FLASH_WRITE_BLOCK_B", "{}".format(flash_info['write_size'])))
entry.append(self._add_data("PIC_EEPROM_WRITE_BLOCK_B", "{}".format(eeprom_info['write_size'])))
entry.append(self._add_data("PIC_USER_ID_WRITE_BLOCK_B", "{}".format(user_id_info['write_size'])))
entry.append(self._add_data("PIC_CONFIG_WRITE_BLOCK_B", "{}".format(config_word_info['write_size'])))
entry.append(self._add_data("PIC_DEVICE_ID", "0x{0:04X}".format(device_info['device_id'])))
return entry | [
"def",
"add_device_data_template",
"(",
"self",
")",
":",
"# Create new entry",
"entry",
"=",
"ETree",
".",
"Element",
"(",
"\"entry\"",
")",
"# Add type",
"d_type",
"=",
"ETree",
".",
"Element",
"(",
"\"type\"",
")",
"d_type",
".",
"text",
"=",
"\"D_ICSP\"",
... | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/configgenerator.py#L204-L238 | |
OPAE/opae-sdk | 221124343c8275243a249eb72d69e0ea2d568d1b | python/opae.admin/opae/admin/tools/opaevfio.py | python | release_vfio | (addr, new_driver) | Release and rebind a device bound to vfio-pci.
addr - canonical PCIe address.
new_driver - name of the new driver to bind the device.
If addr is currently bound to vfio-pci, then unbind it
and rebind it to new_driver. | Release and rebind a device bound to vfio-pci. | [
"Release",
"and",
"rebind",
"a",
"device",
"bound",
"to",
"vfio",
"-",
"pci",
"."
] | def release_vfio(addr, new_driver):
"""Release and rebind a device bound to vfio-pci.
addr - canonical PCIe address.
new_driver - name of the new driver to bind the device.
If addr is currently bound to vfio-pci, then unbind it
and rebind it to new_driver.
"""
vid_did = vid_did_for_address(addr)
driver = get_bound_driver(addr)
msg = '(0x{:04x},0x{:04x}) at {}'.format(
int(vid_did[0], 16), int(vid_did[1], 16), addr)
if not driver or driver != 'vfio-pci':
print('{} is not bound to vfio-pci'.format(msg))
return
print('Releasing {} from vfio-pci'.format(msg))
unbind_driver(driver, addr)
if new_driver:
print('Rebinding {} to {}'.format(msg, new_driver))
bind_driver(new_driver, addr) | [
"def",
"release_vfio",
"(",
"addr",
",",
"new_driver",
")",
":",
"vid_did",
"=",
"vid_did_for_address",
"(",
"addr",
")",
"driver",
"=",
"get_bound_driver",
"(",
"addr",
")",
"msg",
"=",
"'(0x{:04x},0x{:04x}) at {}'",
".",
"format",
"(",
"int",
"(",
"vid_did",... | https://github.com/OPAE/opae-sdk/blob/221124343c8275243a249eb72d69e0ea2d568d1b/python/opae.admin/opae/admin/tools/opaevfio.py#L218-L242 | ||
ROCmSoftwarePlatform/hipCaffe | 4ec5d482515cce532348553b6db6d00d015675d5 | tools/extra/parse_log.py | python | save_csv_files | (logfile_path, output_dir, train_dict_list, test_dict_list,
delimiter=',', verbose=False) | Save CSV files to output_dir
If the input log file is, e.g., caffe.INFO, the names will be
caffe.INFO.train and caffe.INFO.test | Save CSV files to output_dir | [
"Save",
"CSV",
"files",
"to",
"output_dir"
] | def save_csv_files(logfile_path, output_dir, train_dict_list, test_dict_list,
delimiter=',', verbose=False):
"""Save CSV files to output_dir
If the input log file is, e.g., caffe.INFO, the names will be
caffe.INFO.train and caffe.INFO.test
"""
log_basename = os.path.basename(logfile_path)
train_filename = os.path.join(output_dir, log_basename + '.train')
write_csv(train_filename, train_dict_list, delimiter, verbose)
test_filename = os.path.join(output_dir, log_basename + '.test')
write_csv(test_filename, test_dict_list, delimiter, verbose) | [
"def",
"save_csv_files",
"(",
"logfile_path",
",",
"output_dir",
",",
"train_dict_list",
",",
"test_dict_list",
",",
"delimiter",
"=",
"','",
",",
"verbose",
"=",
"False",
")",
":",
"log_basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"logfile_path",
... | https://github.com/ROCmSoftwarePlatform/hipCaffe/blob/4ec5d482515cce532348553b6db6d00d015675d5/tools/extra/parse_log.py#L134-L147 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Compiler/Options.py | python | normalise_encoding_name | (option_name, encoding) | return encoding | >>> normalise_encoding_name('c_string_encoding', 'ascii')
'ascii'
>>> normalise_encoding_name('c_string_encoding', 'AsCIi')
'ascii'
>>> normalise_encoding_name('c_string_encoding', 'us-ascii')
'ascii'
>>> normalise_encoding_name('c_string_encoding', 'utF8')
'utf8'
>>> normalise_encoding_name('c_string_encoding', 'utF-8')
'utf8'
>>> normalise_encoding_name('c_string_encoding', 'deFAuLT')
'default'
>>> normalise_encoding_name('c_string_encoding', 'default')
'default'
>>> normalise_encoding_name('c_string_encoding', 'SeriousLyNoSuch--Encoding')
'SeriousLyNoSuch--Encoding' | >>> normalise_encoding_name('c_string_encoding', 'ascii')
'ascii'
>>> normalise_encoding_name('c_string_encoding', 'AsCIi')
'ascii'
>>> normalise_encoding_name('c_string_encoding', 'us-ascii')
'ascii'
>>> normalise_encoding_name('c_string_encoding', 'utF8')
'utf8'
>>> normalise_encoding_name('c_string_encoding', 'utF-8')
'utf8'
>>> normalise_encoding_name('c_string_encoding', 'deFAuLT')
'default'
>>> normalise_encoding_name('c_string_encoding', 'default')
'default'
>>> normalise_encoding_name('c_string_encoding', 'SeriousLyNoSuch--Encoding')
'SeriousLyNoSuch--Encoding' | [
">>>",
"normalise_encoding_name",
"(",
"c_string_encoding",
"ascii",
")",
"ascii",
">>>",
"normalise_encoding_name",
"(",
"c_string_encoding",
"AsCIi",
")",
"ascii",
">>>",
"normalise_encoding_name",
"(",
"c_string_encoding",
"us",
"-",
"ascii",
")",
"ascii",
">>>",
"... | def normalise_encoding_name(option_name, encoding):
"""
>>> normalise_encoding_name('c_string_encoding', 'ascii')
'ascii'
>>> normalise_encoding_name('c_string_encoding', 'AsCIi')
'ascii'
>>> normalise_encoding_name('c_string_encoding', 'us-ascii')
'ascii'
>>> normalise_encoding_name('c_string_encoding', 'utF8')
'utf8'
>>> normalise_encoding_name('c_string_encoding', 'utF-8')
'utf8'
>>> normalise_encoding_name('c_string_encoding', 'deFAuLT')
'default'
>>> normalise_encoding_name('c_string_encoding', 'default')
'default'
>>> normalise_encoding_name('c_string_encoding', 'SeriousLyNoSuch--Encoding')
'SeriousLyNoSuch--Encoding'
"""
if not encoding:
return ''
if encoding.lower() in ('default', 'ascii', 'utf8'):
return encoding.lower()
import codecs
try:
decoder = codecs.getdecoder(encoding)
except LookupError:
return encoding # may exists at runtime ...
for name in ('ascii', 'utf8'):
if codecs.getdecoder(name) == decoder:
return name
return encoding | [
"def",
"normalise_encoding_name",
"(",
"option_name",
",",
"encoding",
")",
":",
"if",
"not",
"encoding",
":",
"return",
"''",
"if",
"encoding",
".",
"lower",
"(",
")",
"in",
"(",
"'default'",
",",
"'ascii'",
",",
"'utf8'",
")",
":",
"return",
"encoding",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/Options.py#L267-L298 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/grid.py | python | Grid.GetColLabelValue | (*args, **kwargs) | return _grid.Grid_GetColLabelValue(*args, **kwargs) | GetColLabelValue(self, int col) -> String | GetColLabelValue(self, int col) -> String | [
"GetColLabelValue",
"(",
"self",
"int",
"col",
")",
"-",
">",
"String"
] | def GetColLabelValue(*args, **kwargs):
"""GetColLabelValue(self, int col) -> String"""
return _grid.Grid_GetColLabelValue(*args, **kwargs) | [
"def",
"GetColLabelValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_GetColLabelValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L1514-L1516 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/debug/lib/debug_gradients.py | python | GradientsDebugger.watch_gradients_by_tensors | (self, graph, tensors) | return self.watch_gradients_by_tensor_names(graph, tensor_name_regex) | Watch gradient tensors by x-tensor(s).
The side effect of this method is that when gradient tensor(s) are created
with respect to the any paths that include the `x_tensor`s, the gradient
tensor(s) with repsect to the tensor will be registered with this
this `GradientsDebugger` instance and can later be retrieved, with the
methods `gradient_tensor` and `gradient_tensors`.
Unlike the method `identify_gradient`, this method is used to retrieve
gradient tensors after the construction of the forward subgraph has
completed (but before the construction of the backward subgraph).
This method is the same as `watch_gradients_by_x_tensor_names` except that
the tensors are specified by the Python `tf.Tensor` or `tf.Variable`
objects, instead by name patterns.
Example:
```python
x = tf.Variable(1.0)
y = tf.add(x, x, name="y")
z = tf.square(debug_y)
# Create a train op under the grad_debugger context.
grad_debugger = tf_debug.GradientsDebugger()
with grad_debugger.watch_gradients_by_tensors(y):
train_op = tf.train.GradientDescentOptimizer(z)
# Now we can reflect through grad_debugger to get the gradient tensor
# with respect to y.
y_grad = grad_debugger.gradient_tensor(y)
# or
y_grad = grad_debugger.gradient_tensor("y:0")
```
Args:
graph: the `tf.Graph` to watch the gradients on.
tensors: a `tf.Tensor` or `tf.Variable` object, or a list of such objects.
Returns:
The GradientsDebugger instance itself. | Watch gradient tensors by x-tensor(s). | [
"Watch",
"gradient",
"tensors",
"by",
"x",
"-",
"tensor",
"(",
"s",
")",
"."
] | def watch_gradients_by_tensors(self, graph, tensors):
"""Watch gradient tensors by x-tensor(s).
The side effect of this method is that when gradient tensor(s) are created
with respect to the any paths that include the `x_tensor`s, the gradient
tensor(s) with repsect to the tensor will be registered with this
this `GradientsDebugger` instance and can later be retrieved, with the
methods `gradient_tensor` and `gradient_tensors`.
Unlike the method `identify_gradient`, this method is used to retrieve
gradient tensors after the construction of the forward subgraph has
completed (but before the construction of the backward subgraph).
This method is the same as `watch_gradients_by_x_tensor_names` except that
the tensors are specified by the Python `tf.Tensor` or `tf.Variable`
objects, instead by name patterns.
Example:
```python
x = tf.Variable(1.0)
y = tf.add(x, x, name="y")
z = tf.square(debug_y)
# Create a train op under the grad_debugger context.
grad_debugger = tf_debug.GradientsDebugger()
with grad_debugger.watch_gradients_by_tensors(y):
train_op = tf.train.GradientDescentOptimizer(z)
# Now we can reflect through grad_debugger to get the gradient tensor
# with respect to y.
y_grad = grad_debugger.gradient_tensor(y)
# or
y_grad = grad_debugger.gradient_tensor("y:0")
```
Args:
graph: the `tf.Graph` to watch the gradients on.
tensors: a `tf.Tensor` or `tf.Variable` object, or a list of such objects.
Returns:
The GradientsDebugger instance itself.
"""
if not isinstance(tensors, list):
tensors = [tensors]
tensor_name_regex = []
for tensor in tensors:
tensor_name_regex.append(re.escape(tensor.name) + "$")
tensor_name_regex = "(" + "|".join(tensor_name_regex) + ")"
return self.watch_gradients_by_tensor_names(graph, tensor_name_regex) | [
"def",
"watch_gradients_by_tensors",
"(",
"self",
",",
"graph",
",",
"tensors",
")",
":",
"if",
"not",
"isinstance",
"(",
"tensors",
",",
"list",
")",
":",
"tensors",
"=",
"[",
"tensors",
"]",
"tensor_name_regex",
"=",
"[",
"]",
"for",
"tensor",
"in",
"t... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/lib/debug_gradients.py#L166-L217 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/check-completeness-of-a-binary-tree.py | python | Solution2.isCompleteTree | (self, root) | return prev_level[-1][1] == count | :type root: TreeNode
:rtype: bool | :type root: TreeNode
:rtype: bool | [
":",
"type",
"root",
":",
"TreeNode",
":",
"rtype",
":",
"bool"
] | def isCompleteTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
prev_level, current = [], [(root, 1)]
count = 0
while current:
count += len(current)
next_level = []
for node, v in current:
if not node:
continue
next_level.append((node.left, 2*v))
next_level.append((node.right, 2*v+1))
prev_level, current = current, next_level
return prev_level[-1][1] == count | [
"def",
"isCompleteTree",
"(",
"self",
",",
"root",
")",
":",
"prev_level",
",",
"current",
"=",
"[",
"]",
",",
"[",
"(",
"root",
",",
"1",
")",
"]",
"count",
"=",
"0",
"while",
"current",
":",
"count",
"+=",
"len",
"(",
"current",
")",
"next_level"... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/check-completeness-of-a-binary-tree.py#L37-L53 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/util/protobuf/compare.py | python | ProtoEq | (a, b) | return True | Compares two proto2 objects for equality.
Recurses into nested messages. Uses list (not set) semantics for comparing
repeated fields, ie duplicates and order matter.
Args:
a: A proto2 message or a primitive.
b: A proto2 message or a primitive.
Returns:
`True` if the messages are equal. | Compares two proto2 objects for equality. | [
"Compares",
"two",
"proto2",
"objects",
"for",
"equality",
"."
] | def ProtoEq(a, b):
"""Compares two proto2 objects for equality.
Recurses into nested messages. Uses list (not set) semantics for comparing
repeated fields, ie duplicates and order matter.
Args:
a: A proto2 message or a primitive.
b: A proto2 message or a primitive.
Returns:
`True` if the messages are equal.
"""
def Format(pb):
"""Returns a dictionary or unchanged pb bases on its type.
Specifically, this function returns a dictionary that maps tag
number (for messages) or element index (for repeated fields) to
value, or just pb unchanged if it's neither.
Args:
pb: A proto2 message or a primitive.
Returns:
A dict or unchanged pb.
"""
if isinstance(pb, message.Message):
return dict((desc.number, value) for desc, value in pb.ListFields())
elif _IsMap(pb):
return dict(pb.items())
elif _IsRepeatedContainer(pb):
return dict(enumerate(list(pb)))
else:
return pb
a, b = Format(a), Format(b)
# Base case
if not isinstance(a, dict) or not isinstance(b, dict):
return a == b
# This list performs double duty: it compares two messages by tag value *or*
# two repeated fields by element, in order. the magic is in the format()
# function, which converts them both to the same easily comparable format.
for tag in sorted(set(a.keys()) | set(b.keys())):
if tag not in a or tag not in b:
return False
else:
# Recursive step
if not ProtoEq(a[tag], b[tag]):
return False
# Didn't find any values that differed, so they're equal!
return True | [
"def",
"ProtoEq",
"(",
"a",
",",
"b",
")",
":",
"def",
"Format",
"(",
"pb",
")",
":",
"\"\"\"Returns a dictionary or unchanged pb bases on its type.\n\n Specifically, this function returns a dictionary that maps tag\n number (for messages) or element index (for repeated fields) to\... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/util/protobuf/compare.py#L192-L244 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/lambda_max.py | python | lambda_max.sign_from_args | (self) | return (False, False) | Returns sign (is positive, is negative) of the expression. | Returns sign (is positive, is negative) of the expression. | [
"Returns",
"sign",
"(",
"is",
"positive",
"is",
"negative",
")",
"of",
"the",
"expression",
"."
] | def sign_from_args(self) -> Tuple[bool, bool]:
"""Returns sign (is positive, is negative) of the expression.
"""
return (False, False) | [
"def",
"sign_from_args",
"(",
"self",
")",
"->",
"Tuple",
"[",
"bool",
",",
"bool",
"]",
":",
"return",
"(",
"False",
",",
"False",
")"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/lambda_max.py#L76-L79 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_windows.py | python | PrintDialogData.GetPrintToFile | (*args, **kwargs) | return _windows_.PrintDialogData_GetPrintToFile(*args, **kwargs) | GetPrintToFile(self) -> bool | GetPrintToFile(self) -> bool | [
"GetPrintToFile",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetPrintToFile(*args, **kwargs):
"""GetPrintToFile(self) -> bool"""
return _windows_.PrintDialogData_GetPrintToFile(*args, **kwargs) | [
"def",
"GetPrintToFile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PrintDialogData_GetPrintToFile",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L5074-L5076 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/instruments/interface.py | python | InstrumentInterface.export | (self, file_name) | Export the content of the UI as a python script that can
be run within Mantid
@param file_name: name of the python script to be saved | Export the content of the UI as a python script that can
be run within Mantid | [
"Export",
"the",
"content",
"of",
"the",
"UI",
"as",
"a",
"python",
"script",
"that",
"can",
"be",
"run",
"within",
"Mantid"
] | def export(self, file_name):
"""
Export the content of the UI as a python script that can
be run within Mantid
@param file_name: name of the python script to be saved
"""
self.scripter.update()
try:
return self.scripter.to_script(file_name)
except RuntimeError as e:
if self._settings.debug:
msg = "The following error was encountered:\n\n%s" % unicode(traceback.format_exc())
else:
msg = "The following error was encountered:\n\n%s" % unicode(e)
log_path = os.path.join(self.ERROR_REPORT_DIR, self.ERROR_REPORT_NAME)
msg += "\n\nWhen contacting the Mantid Team, please send this file:\n%s\n" % log_path
self._warning("Reduction Parameters Incomplete", msg)
self._error_report(traceback.format_exc())
return None
except:
msg = "The following error was encountered:\n\n%s" % sys.exc_info()[0]
msg += "\n\nPlease check your reduction parameters\n"
log_path = os.path.join(self.ERROR_REPORT_DIR, self.ERROR_REPORT_NAME)
msg += "\n\nWhen contacting the Mantid Team, please send this file:\n%s\n" % log_path
self._warning("Reduction Parameters Incomplete", msg)
self._error_report(traceback.format_exc())
return None | [
"def",
"export",
"(",
"self",
",",
"file_name",
")",
":",
"self",
".",
"scripter",
".",
"update",
"(",
")",
"try",
":",
"return",
"self",
".",
"scripter",
".",
"to_script",
"(",
"file_name",
")",
"except",
"RuntimeError",
"as",
"e",
":",
"if",
"self",
... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/instruments/interface.py#L116-L142 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/inference.py | python | is_array_like | (obj) | return is_list_like(obj) and hasattr(obj, "dtype") | Check if the object is array-like.
For an object to be considered array-like, it must be list-like and
have a `dtype` attribute.
Parameters
----------
obj : The object to check
Returns
-------
is_array_like : bool
Whether `obj` has array-like properties.
Examples
--------
>>> is_array_like(np.array([1, 2, 3]))
True
>>> is_array_like(pd.Series(["a", "b"]))
True
>>> is_array_like(pd.Index(["2016-01-01"]))
True
>>> is_array_like([1, 2, 3])
False
>>> is_array_like(("a", "b"))
False | Check if the object is array-like. | [
"Check",
"if",
"the",
"object",
"is",
"array",
"-",
"like",
"."
] | def is_array_like(obj) -> bool:
"""
Check if the object is array-like.
For an object to be considered array-like, it must be list-like and
have a `dtype` attribute.
Parameters
----------
obj : The object to check
Returns
-------
is_array_like : bool
Whether `obj` has array-like properties.
Examples
--------
>>> is_array_like(np.array([1, 2, 3]))
True
>>> is_array_like(pd.Series(["a", "b"]))
True
>>> is_array_like(pd.Index(["2016-01-01"]))
True
>>> is_array_like([1, 2, 3])
False
>>> is_array_like(("a", "b"))
False
"""
return is_list_like(obj) and hasattr(obj, "dtype") | [
"def",
"is_array_like",
"(",
"obj",
")",
"->",
"bool",
":",
"return",
"is_list_like",
"(",
"obj",
")",
"and",
"hasattr",
"(",
"obj",
",",
"\"dtype\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/inference.py#L220-L250 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/finddlg.py | python | FindPanel.GetFileFilters | (self) | return self._filters.GetValue() | Get the currently set file filters
@return: string | Get the currently set file filters
@return: string | [
"Get",
"the",
"currently",
"set",
"file",
"filters",
"@return",
":",
"string"
] | def GetFileFilters(self):
"""Get the currently set file filters
@return: string
"""
return self._filters.GetValue() | [
"def",
"GetFileFilters",
"(",
"self",
")",
":",
"return",
"self",
".",
"_filters",
".",
"GetValue",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/finddlg.py#L1086-L1091 | |
CaoWGG/TensorRT-CenterNet | f949252e37b51e60f873808f46d3683f15735e79 | onnx-tensorrt/third_party/onnx/onnx/__init__.py | python | _deserialize | (s, proto) | return proto | Parse bytes into a in-memory proto
@params
s is bytes containing serialized proto
proto is a in-memory proto object
@return
The proto instance filled in by s | Parse bytes into a in-memory proto | [
"Parse",
"bytes",
"into",
"a",
"in",
"-",
"memory",
"proto"
] | def _deserialize(s, proto): # type: (bytes, _Proto) -> _Proto
'''
Parse bytes into a in-memory proto
@params
s is bytes containing serialized proto
proto is a in-memory proto object
@return
The proto instance filled in by s
'''
if not isinstance(s, bytes):
raise ValueError('Parameter s must be bytes, but got type: {}'.format(type(s)))
if not (hasattr(proto, 'ParseFromString') and callable(proto.ParseFromString)):
raise ValueError('No ParseFromString method is detected. '
'\ntype is {}'.format(type(proto)))
decoded = cast(Optional[int], proto.ParseFromString(s))
if decoded is not None and decoded != len(s):
raise google.protobuf.message.DecodeError(
"Protobuf decoding consumed too few bytes: {} out of {}".format(
decoded, len(s)))
return proto | [
"def",
"_deserialize",
"(",
"s",
",",
"proto",
")",
":",
"# type: (bytes, _Proto) -> _Proto",
"if",
"not",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"raise",
"ValueError",
"(",
"'Parameter s must be bytes, but got type: {}'",
".",
"format",
"(",
"type",
"(",... | https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/onnx/__init__.py#L63-L86 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/setup_multiversion_mongodb.py | python | MultiVersionDownloader.is_major_minor_version | (version) | return True | Returns True if the version is specified as M.m. | Returns True if the version is specified as M.m. | [
"Returns",
"True",
"if",
"the",
"version",
"is",
"specified",
"as",
"M",
".",
"m",
"."
] | def is_major_minor_version(version):
"""Returns True if the version is specified as M.m."""
if re.match(r"^\d+?\.\d+?$", version) is None:
return False
return True | [
"def",
"is_major_minor_version",
"(",
"version",
")",
":",
"if",
"re",
".",
"match",
"(",
"r\"^\\d+?\\.\\d+?$\"",
",",
"version",
")",
"is",
"None",
":",
"return",
"False",
"return",
"True"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/setup_multiversion_mongodb.py#L147-L151 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/symtable.py | python | Symbol.get_namespaces | (self) | return self.__namespaces | Return a list of namespaces bound to this name | Return a list of namespaces bound to this name | [
"Return",
"a",
"list",
"of",
"namespaces",
"bound",
"to",
"this",
"name"
] | def get_namespaces(self):
"""Return a list of namespaces bound to this name"""
return self.__namespaces | [
"def",
"get_namespaces",
"(",
"self",
")",
":",
"return",
"self",
".",
"__namespaces"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/symtable.py#L232-L234 | |
unicode-org/icu | 2f8749a026f3ddc8cf54d4622480b7c543bb7fc0 | icu4c/source/python/icutools/databuilder/filtration.py | python | LocaleFilter._locales_required | (self, tree) | Returns a generator of all required locales in the given tree. | Returns a generator of all required locales in the given tree. | [
"Returns",
"a",
"generator",
"of",
"all",
"required",
"locales",
"in",
"the",
"given",
"tree",
"."
] | def _locales_required(self, tree):
"""Returns a generator of all required locales in the given tree."""
for locale in self.locales_requested:
while locale is not None:
yield locale
locale = self._get_parent_locale(locale, tree) | [
"def",
"_locales_required",
"(",
"self",
",",
"tree",
")",
":",
"for",
"locale",
"in",
"self",
".",
"locales_requested",
":",
"while",
"locale",
"is",
"not",
"None",
":",
"yield",
"locale",
"locale",
"=",
"self",
".",
"_get_parent_locale",
"(",
"locale",
"... | https://github.com/unicode-org/icu/blob/2f8749a026f3ddc8cf54d4622480b7c543bb7fc0/icu4c/source/python/icutools/databuilder/filtration.py#L236-L241 | ||
wujian16/Cornell-MOE | df299d1be882d2af9796d7a68b3f9505cac7a53e | moe/optimal_learning/python/cpp_wrappers/covariance.py | python | SquareExponential.covariance | (self, point_one, point_two) | r"""Compute the covariance function of two points, cov(``point_one``, ``point_two``).
We do not currently expose a C++ endpoint for this call; see :mod:`moe.optimal_learning.python.interfaces.covariance_interface` for interface specification. | r"""Compute the covariance function of two points, cov(``point_one``, ``point_two``). | [
"r",
"Compute",
"the",
"covariance",
"function",
"of",
"two",
"points",
"cov",
"(",
"point_one",
"point_two",
")",
"."
] | def covariance(self, point_one, point_two):
r"""Compute the covariance function of two points, cov(``point_one``, ``point_two``).
We do not currently expose a C++ endpoint for this call; see :mod:`moe.optimal_learning.python.interfaces.covariance_interface` for interface specification.
"""
raise NotImplementedError("C++ wrapper currently does not support computing covariance quantities.") | [
"def",
"covariance",
"(",
"self",
",",
"point_one",
",",
"point_two",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"C++ wrapper currently does not support computing covariance quantities.\"",
")"
] | https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/cpp_wrappers/covariance.py#L68-L74 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/fields.py | python | RequestField.render_headers | (self) | return u"\r\n".join(lines) | Renders the headers for this request field. | Renders the headers for this request field. | [
"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/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/fields.py#L229-L246 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/math_utils.py | python | Divide | (a, b) | return a / float(b) | Returns the quotient, or NaN if the divisor is zero. | Returns the quotient, or NaN if the divisor is zero. | [
"Returns",
"the",
"quotient",
"or",
"NaN",
"if",
"the",
"divisor",
"is",
"zero",
"."
] | def Divide(a, b):
"""Returns the quotient, or NaN if the divisor is zero."""
if b == 0:
return float('nan')
return a / float(b) | [
"def",
"Divide",
"(",
"a",
",",
"b",
")",
":",
"if",
"b",
"==",
"0",
":",
"return",
"float",
"(",
"'nan'",
")",
"return",
"a",
"/",
"float",
"(",
"b",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/math_utils.py#L43-L47 | |
rism-digital/verovio | 46d53c6b0ba4b22aaca80bc02fe7be470d4429a6 | fonts/extract-bounding-boxes.py | python | write_file_content | (filepath, content) | Write content to file with path relative to the script directory. | Write content to file with path relative to the script directory. | [
"Write",
"content",
"to",
"file",
"with",
"path",
"relative",
"to",
"the",
"script",
"directory",
"."
] | def write_file_content(filepath, content):
"""Write content to file with path relative to the script directory."""
location = os.path.realpath(os.path.dirname(__file__))
file = open(os.path.join(location, filepath), "w")
file.write(content)
file.close() | [
"def",
"write_file_content",
"(",
"filepath",
",",
"content",
")",
":",
"location",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"file",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
... | https://github.com/rism-digital/verovio/blob/46d53c6b0ba4b22aaca80bc02fe7be470d4429a6/fonts/extract-bounding-boxes.py#L29-L34 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/pystache/pystache/locator.py | python | Locator.make_file_name | (self, template_name, template_extension=None) | return file_name | Generate and return the file name for the given template name.
Arguments:
template_extension: defaults to the instance's extension. | Generate and return the file name for the given template name. | [
"Generate",
"and",
"return",
"the",
"file",
"name",
"for",
"the",
"given",
"template",
"name",
"."
] | def make_file_name(self, template_name, template_extension=None):
"""
Generate and return the file name for the given template name.
Arguments:
template_extension: defaults to the instance's extension.
"""
file_name = template_name
if template_extension is None:
template_extension = self.template_extension
if template_extension is not False:
file_name += os.path.extsep + template_extension
return file_name | [
"def",
"make_file_name",
"(",
"self",
",",
"template_name",
",",
"template_extension",
"=",
"None",
")",
":",
"file_name",
"=",
"template_name",
"if",
"template_extension",
"is",
"None",
":",
"template_extension",
"=",
"self",
".",
"template_extension",
"if",
"tem... | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/pystache/pystache/locator.py#L80-L97 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/curses/textpad.py | python | Textbox.edit | (self, validate=None) | return self.gather() | Edit in the widget window and collect the results. | Edit in the widget window and collect the results. | [
"Edit",
"in",
"the",
"widget",
"window",
"and",
"collect",
"the",
"results",
"."
] | def edit(self, validate=None):
"Edit in the widget window and collect the results."
while 1:
ch = self.win.getch()
if validate:
ch = validate(ch)
if not ch:
continue
if not self.do_command(ch):
break
self.win.refresh()
return self.gather() | [
"def",
"edit",
"(",
"self",
",",
"validate",
"=",
"None",
")",
":",
"while",
"1",
":",
"ch",
"=",
"self",
".",
"win",
".",
"getch",
"(",
")",
"if",
"validate",
":",
"ch",
"=",
"validate",
"(",
"ch",
")",
"if",
"not",
"ch",
":",
"continue",
"if"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/curses/textpad.py#L177-L188 | |
apache/singa | 93fd9da72694e68bfe3fb29d0183a65263d238a1 | python/singa/model.py | python | Model.eval | (self) | Sets the model in evaluation mode. | Sets the model in evaluation mode. | [
"Sets",
"the",
"model",
"in",
"evaluation",
"mode",
"."
] | def eval(self):
"""Sets the model in evaluation mode.
"""
self.train(mode=False) | [
"def",
"eval",
"(",
"self",
")",
":",
"self",
".",
"train",
"(",
"mode",
"=",
"False",
")"
] | https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/model.py#L219-L222 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/driver_nbody.py | python | compute_nbody_components | (func, method_string, metadata) | return {
'energies': energies_dict,
'gradients': gradients_dict,
'ptype': ptype_dict,
'intermediates': intermediates_dict
} | Computes requested N-body components.
Performs requested computations for psi4::Molecule object `molecule` according to
`compute_list` with function `func` at `method_string` level of theory.
Parameters
----------
func : str
{'energy', 'gradient', 'hessian'}
Function object to be called within N-Body procedure.
method_string : str
Indicates level of theory to be passed to function `func`.
metadata : dict of str
Dictionary of N-body metadata.
Required ``'key': value`` pairs:
``'compute_list'``: dict of int: set
List of computations to perform. Keys indicate body-levels, e.g,. `compute_list[2]` is the
list of all 2-body computations required.
``'kwargs'``: dict
Arbitrary keyword arguments to be passed to function `func`.
Returns
-------
dict of str: dict
Dictionary containing computed N-body components.
Contents:
``'energies'``: dict of set: float64
Dictionary containing all energy components required for given N-body procedure.
``'ptype'``: dict of set: float64 or dict of set: psi4.Matrix
Dictionary of returned quantities from calls of function `func` during N-body computations
``'intermediates'``: dict of str: float64
Dictionary of psivars for intermediate N-body computations to be set at the end of the
N-body procedure. | Computes requested N-body components. | [
"Computes",
"requested",
"N",
"-",
"body",
"components",
"."
] | def compute_nbody_components(func, method_string, metadata):
"""Computes requested N-body components.
Performs requested computations for psi4::Molecule object `molecule` according to
`compute_list` with function `func` at `method_string` level of theory.
Parameters
----------
func : str
{'energy', 'gradient', 'hessian'}
Function object to be called within N-Body procedure.
method_string : str
Indicates level of theory to be passed to function `func`.
metadata : dict of str
Dictionary of N-body metadata.
Required ``'key': value`` pairs:
``'compute_list'``: dict of int: set
List of computations to perform. Keys indicate body-levels, e.g,. `compute_list[2]` is the
list of all 2-body computations required.
``'kwargs'``: dict
Arbitrary keyword arguments to be passed to function `func`.
Returns
-------
dict of str: dict
Dictionary containing computed N-body components.
Contents:
``'energies'``: dict of set: float64
Dictionary containing all energy components required for given N-body procedure.
``'ptype'``: dict of set: float64 or dict of set: psi4.Matrix
Dictionary of returned quantities from calls of function `func` during N-body computations
``'intermediates'``: dict of str: float64
Dictionary of psivars for intermediate N-body computations to be set at the end of the
N-body procedure.
"""
# Get required metadata
kwargs = metadata['kwargs']
molecule = metadata['molecule']
#molecule = core.get_active_molecule()
compute_list = metadata['compute_dict']['all']
# Now compute the energies
energies_dict = {}
gradients_dict = {}
ptype_dict = {}
intermediates_dict = {}
if kwargs.get('charge_method', False) and not metadata['embedding_charges']:
metadata['embedding_charges'] = driver_nbody_helper.compute_charges(kwargs['charge_method'],
kwargs.get('charge_type', 'MULLIKEN_CHARGES').upper(), molecule)
for count, n in enumerate(compute_list.keys()):
core.print_out("\n ==> N-Body: Now computing %d-body complexes <==\n\n" % n)
total = len(compute_list[n])
for num, pair in enumerate(compute_list[n]):
core.print_out(
"\n N-Body: Computing complex (%d/%d) with fragments %s in the basis of fragments %s.\n\n" %
(num + 1, total, str(pair[0]), str(pair[1])))
ghost = list(set(pair[1]) - set(pair[0]))
current_mol = molecule.extract_subsets(list(pair[0]), ghost)
current_mol.set_name("%s_%i_%i" % (current_mol.name(), count, num))
if metadata['embedding_charges']: driver_nbody_helper.electrostatic_embedding(metadata, pair=pair)
# Save energies info
ptype_dict[pair], wfn = func(method_string, molecule=current_mol, return_wfn=True, **kwargs)
core.set_global_option_python('EXTERN', None)
energies_dict[pair] = core.variable("CURRENT ENERGY")
gradients_dict[pair] = wfn.gradient()
var_key = "N-BODY (%s)@(%s) TOTAL ENERGY" % (', '.join([str(i) for i in pair[0]]), ', '.join(
[str(i) for i in pair[1]]))
intermediates_dict[var_key] = core.variable("CURRENT ENERGY")
core.print_out("\n N-Body: Complex Energy (fragments = %s, basis = %s: %20.14f)\n" % (str(
pair[0]), str(pair[1]), energies_dict[pair]))
# Flip this off for now, needs more testing
#if 'cp' in bsse_type_list and (len(bsse_type_list) == 1):
# core.set_global_option('DF_INTS_IO', 'LOAD')
core.clean()
return {
'energies': energies_dict,
'gradients': gradients_dict,
'ptype': ptype_dict,
'intermediates': intermediates_dict
} | [
"def",
"compute_nbody_components",
"(",
"func",
",",
"method_string",
",",
"metadata",
")",
":",
"# Get required metadata",
"kwargs",
"=",
"metadata",
"[",
"'kwargs'",
"]",
"molecule",
"=",
"metadata",
"[",
"'molecule'",
"]",
"#molecule = core.get_active_molecule()",
... | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/driver_nbody.py#L467-L551 | |
9miao/CrossApp | 1f5375e061bf69841eb19728598f5ae3f508d620 | tools/bindings-generator/clang/cindex.py | python | TranslationUnit.get_tokens | (self, locations=None, extent=None) | return TokenGroup.get_tokens(self, extent) | Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined. | Obtain tokens in this translation unit. | [
"Obtain",
"tokens",
"in",
"this",
"translation",
"unit",
"."
] | def get_tokens(self, locations=None, extent=None):
"""Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined.
"""
if locations is not None:
extent = SourceRange(start=locations[0], end=locations[1])
return TokenGroup.get_tokens(self, extent) | [
"def",
"get_tokens",
"(",
"self",
",",
"locations",
"=",
"None",
",",
"extent",
"=",
"None",
")",
":",
"if",
"locations",
"is",
"not",
"None",
":",
"extent",
"=",
"SourceRange",
"(",
"start",
"=",
"locations",
"[",
"0",
"]",
",",
"end",
"=",
"locatio... | https://github.com/9miao/CrossApp/blob/1f5375e061bf69841eb19728598f5ae3f508d620/tools/bindings-generator/clang/cindex.py#L2471-L2482 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.