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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/MSVSProject.py | python | Writer.AddFiles | (self, files) | Adds files to the project.
Args:
files: A list of Filter objects and/or relative paths to files.
This makes a copy of the file/filter tree at the time of this call. If you
later add files to a Filter object which was passed into a previous call
to AddFiles(), it will not be reflected in this project. | Adds files to the project. | [
"Adds",
"files",
"to",
"the",
"project",
"."
] | def AddFiles(self, files):
"""Adds files to the project.
Args:
files: A list of Filter objects and/or relative paths to files.
This makes a copy of the file/filter tree at the time of this call. If you
later add files to a Filter object which was passed into a previous call
to AddFiles(), it will not be reflected in this project.
"""
self._AddFilesToNode(self.files_section, files) | [
"def",
"AddFiles",
"(",
"self",
",",
"files",
")",
":",
"self",
".",
"_AddFilesToNode",
"(",
"self",
".",
"files_section",
",",
"files",
")"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/MSVSProject.py#L152-L162 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Import/App/automotive_design.py | python | item_in_context | (item,cntxt,) | return FALSE | :param item
:type item:representation_item
:param cntxt
:type cntxt:representation_context | :param item
:type item:representation_item
:param cntxt
:type cntxt:representation_context | [
":",
"param",
"item",
":",
"type",
"item",
":",
"representation_item",
":",
"param",
"cntxt",
":",
"type",
"cntxt",
":",
"representation_context"
] | def item_in_context(item,cntxt,):
'''
:param item
:type item:representation_item
:param cntxt
:type cntxt:representation_context
'''
if (SIZEOF(USEDIN(item,'AUTOMOTIVE_DESIGN.REPRESENTATION.ITEMS') * cntxt.representations_in_context) > 0):
return TRUE
else:
y = None
if (SIZEOF(y) > 0):
for i in range(1,HIINDEX(y),1):
if (item_in_context(y[i],cntxt)):
return TRUE
return FALSE | [
"def",
"item_in_context",
"(",
"item",
",",
"cntxt",
",",
")",
":",
"if",
"(",
"SIZEOF",
"(",
"USEDIN",
"(",
"item",
",",
"'AUTOMOTIVE_DESIGN.REPRESENTATION.ITEMS'",
")",
"*",
"cntxt",
".",
"representations_in_context",
")",
">",
"0",
")",
":",
"return",
"TR... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Import/App/automotive_design.py#L40659-L40674 | |
may0324/DeepCompression-caffe | 0aff6c1287bda4cfc7f378ed8a16524e1afabd8c | python/caffe/io.py | python | Transformer.set_mean | (self, in_, mean) | Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable) | Set the mean to subtract for centering the data. | [
"Set",
"the",
"mean",
"to",
"subtract",
"for",
"centering",
"the",
"data",
"."
] | def set_mean(self, in_, mean):
"""
Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable)
"""
self.__check_input(in_)
ms = mean.shape
if mean.ndim == 1:
# broadcast channels
if ms[0] != self.inputs[in_][1]:
raise ValueError('Mean channels incompatible with input.')
mean = mean[:, np.newaxis, np.newaxis]
else:
# elementwise mean
if len(ms) == 2:
ms = (1,) + ms
if len(ms) != 3:
raise ValueError('Mean shape invalid')
if ms != self.inputs[in_][1:]:
raise ValueError('Mean shape incompatible with input shape.')
self.mean[in_] = mean | [
"def",
"set_mean",
"(",
"self",
",",
"in_",
",",
"mean",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"ms",
"=",
"mean",
".",
"shape",
"if",
"mean",
".",
"ndim",
"==",
"1",
":",
"# broadcast channels",
"if",
"ms",
"[",
"0",
"]",
"!=",
... | https://github.com/may0324/DeepCompression-caffe/blob/0aff6c1287bda4cfc7f378ed8a16524e1afabd8c/python/caffe/io.py#L236-L260 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/sdist.py | python | walk_revctrl | (dirname='') | Find all files under revision control | Find all files under revision control | [
"Find",
"all",
"files",
"under",
"revision",
"control"
] | def walk_revctrl(dirname=''):
"""Find all files under revision control"""
for ep in pkg_resources.iter_entry_points('setuptools.file_finders'):
for item in ep.load()(dirname):
yield item | [
"def",
"walk_revctrl",
"(",
"dirname",
"=",
"''",
")",
":",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"'setuptools.file_finders'",
")",
":",
"for",
"item",
"in",
"ep",
".",
"load",
"(",
")",
"(",
"dirname",
")",
":",
"yield",
"it... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/sdist.py#L17-L21 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/html.py | python | HtmlHelpFrame.GetData | (*args, **kwargs) | return _html.HtmlHelpFrame_GetData(*args, **kwargs) | GetData(self) -> HtmlHelpData | GetData(self) -> HtmlHelpData | [
"GetData",
"(",
"self",
")",
"-",
">",
"HtmlHelpData"
] | def GetData(*args, **kwargs):
"""GetData(self) -> HtmlHelpData"""
return _html.HtmlHelpFrame_GetData(*args, **kwargs) | [
"def",
"GetData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlHelpFrame_GetData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L1750-L1752 | |
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/llvm/utils/benchmark/mingw.py | python | find_7zip | (log = EmptyLogger()) | return path[0] | Attempts to find 7zip for unpacking the mingw-build archives | Attempts to find 7zip for unpacking the mingw-build archives | [
"Attempts",
"to",
"find",
"7zip",
"for",
"unpacking",
"the",
"mingw",
"-",
"build",
"archives"
] | def find_7zip(log = EmptyLogger()):
'''
Attempts to find 7zip for unpacking the mingw-build archives
'''
log.info('finding 7zip')
path = find_in_path('7z')
if not path:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\7-Zip')
path, _ = winreg.QueryValueEx(key, 'Path')
path = [os.path.join(path, '7z.exe')]
log.debug('found \'%s\'', path[0])
return path[0] | [
"def",
"find_7zip",
"(",
"log",
"=",
"EmptyLogger",
"(",
")",
")",
":",
"log",
".",
"info",
"(",
"'finding 7zip'",
")",
"path",
"=",
"find_in_path",
"(",
"'7z'",
")",
"if",
"not",
"path",
":",
"key",
"=",
"winreg",
".",
"OpenKey",
"(",
"winreg",
".",... | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/llvm/utils/benchmark/mingw.py#L99-L110 | |
cmu-db/peloton | 484d76df9344cb5c153a2c361c5d5018912d4cf4 | script/helpers.py | python | find_clangformat | () | return path | Finds appropriate clang-format executable. | Finds appropriate clang-format executable. | [
"Finds",
"appropriate",
"clang",
"-",
"format",
"executable",
"."
] | def find_clangformat():
"""Finds appropriate clang-format executable."""
#check for possible clang-format versions
for exe in ["clang-format", "clang-format-3.6", "clang-format-3.7",
"clang-format-3.8"
]:
path = distutils.spawn.find_executable(exe)
if not path is None:
break
return path | [
"def",
"find_clangformat",
"(",
")",
":",
"#check for possible clang-format versions",
"for",
"exe",
"in",
"[",
"\"clang-format\"",
",",
"\"clang-format-3.6\"",
",",
"\"clang-format-3.7\"",
",",
"\"clang-format-3.8\"",
"]",
":",
"path",
"=",
"distutils",
".",
"spawn",
... | https://github.com/cmu-db/peloton/blob/484d76df9344cb5c153a2c361c5d5018912d4cf4/script/helpers.py#L37-L46 | |
OSGeo/gdal | 3748fc4ba4fba727492774b2b908a2130c864a83 | swig/python/osgeo/gnm.py | python | Network.CommitTransaction | (self, *args) | return _gnm.Network_CommitTransaction(self, *args) | r"""CommitTransaction(Network self) -> OGRErr | r"""CommitTransaction(Network self) -> OGRErr | [
"r",
"CommitTransaction",
"(",
"Network",
"self",
")",
"-",
">",
"OGRErr"
] | def CommitTransaction(self, *args):
r"""CommitTransaction(Network self) -> OGRErr"""
return _gnm.Network_CommitTransaction(self, *args) | [
"def",
"CommitTransaction",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_gnm",
".",
"Network_CommitTransaction",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gnm.py#L176-L178 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetAsmflags | (self, config) | return asmflags | Returns the flags that need to be added to ml invocations. | Returns the flags that need to be added to ml invocations. | [
"Returns",
"the",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
"ml",
"invocations",
"."
] | def GetAsmflags(self, config):
"""Returns the flags that need to be added to ml invocations."""
config = self._TargetConfig(config)
asmflags = []
safeseh = self._Setting(('MASM', 'UseSafeExceptionHandlers'), config)
if safeseh == 'true':
asmflags.append('/safeseh')
return asmflags | [
"def",
"GetAsmflags",
"(",
"self",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"asmflags",
"=",
"[",
"]",
"safeseh",
"=",
"self",
".",
"_Setting",
"(",
"(",
"'MASM'",
",",
"'UseSafeExceptionHandlers'",
")",
"... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L417-L424 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/masked/maskededit.py | python | MaskedEditMixin._adjustPos | (self, pos, key) | return pos | Checks the current insertion point position and adjusts it if
necessary to skip over non-editable characters. | Checks the current insertion point position and adjusts it if
necessary to skip over non-editable characters. | [
"Checks",
"the",
"current",
"insertion",
"point",
"position",
"and",
"adjusts",
"it",
"if",
"necessary",
"to",
"skip",
"over",
"non",
"-",
"editable",
"characters",
"."
] | def _adjustPos(self, pos, key):
"""
Checks the current insertion point position and adjusts it if
necessary to skip over non-editable characters.
"""
## dbg('_adjustPos', pos, key, indent=1)
sel_start, sel_to = self._GetSelection()
# If a numeric or decimal mask, and negatives allowed, reserve the
# first space for sign, and last one if using parens.
if( self._signOk
and ((pos == self._signpos and key in (ord('-'), ord('+'), ord(' ')) )
or (self._useParens and pos == self._masklength -1))):
## dbg('adjusted pos:', pos, indent=0)
return pos
if key not in self._nav:
field = self._FindField(pos)
## dbg('field._insertRight?', field._insertRight)
## if self._signOk: dbg('self._signpos:', self._signpos)
if field._insertRight: # if allow right-insert
start, end = field._extent
slice = self._GetValue()[start:end].strip()
field_len = end - start
if pos == end: # if cursor at right edge of field
# if not filled or supposed to stay in field, keep current position
#### dbg('pos==end')
#### dbg('len (slice):', len(slice))
#### dbg('field_len?', field_len)
#### dbg('pos==end; len (slice) < field_len?', len(slice) < field_len)
#### dbg('not field._moveOnFieldFull?', not field._moveOnFieldFull)
if( len(slice) == field_len and field._moveOnFieldFull
and (not field._stopFieldChangeIfInvalid or
field._stopFieldChangeIfInvalid and field.IsValid(slice))):
# move cursor to next field:
pos = self._findNextEntry(pos)
self._SetInsertionPoint(pos)
if pos < sel_to:
self._SetSelection(pos, sel_to) # restore selection
else:
self._SetSelection(pos, pos) # remove selection
else: # leave cursor alone
pass
else:
# if at start of control, move to right edge
if (sel_to == sel_start
and (self._isTemplateChar(pos) or (pos == start and len(slice)+ 1 < field_len))
and pos != end):
pos = end # move to right edge
## elif sel_start <= start and sel_to == end:
## # select to right edge of field - 1 (to replace char)
## pos = end - 1
## self._SetInsertionPoint(pos)
## # restore selection
## self._SetSelection(sel_start, pos)
# if selected to beginning and signed, and not changing sign explicitly:
elif self._signOk and sel_start == 0 and key not in (ord('-'), ord('+'), ord(' ')):
# adjust to past reserved sign position:
pos = self._fields[0]._extent[0]
## dbg('adjusting field to ', pos)
self._SetInsertionPoint(pos)
# but keep original selection, to allow replacement of any sign:
self._SetSelection(0, sel_to)
else:
pass # leave position/selection alone
# else make sure the user is not trying to type over a template character
# If they are, move them to the next valid entry position
elif self._isTemplateChar(pos):
if( (not field._moveOnFieldFull
and (not self._signOk
or (self._signOk and field._index == 0 and pos > 0) ) )
or (field._stopFieldChangeIfInvalid
and not field.IsValid(self._GetValue()[start:end]) ) ):
# don't move to next field without explicit cursor movement
pass
else:
# find next valid position
pos = self._findNextEntry(pos)
self._SetInsertionPoint(pos)
if pos < sel_to: # restore selection
self._SetSelection(pos, sel_to)
else:
self._SetSelection(pos, pos)
## dbg('adjusted pos:', pos, indent=0)
return pos | [
"def",
"_adjustPos",
"(",
"self",
",",
"pos",
",",
"key",
")",
":",
"## dbg('_adjustPos', pos, key, indent=1)",
"sel_start",
",",
"sel_to",
"=",
"self",
".",
"_GetSelection",
"(",
")",
"# If a numeric or decimal mask, and negatives allowed, reserve the",
"# first spa... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/masked/maskededit.py#L4325-L4413 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/plugins/prt/wxgui.py | python | WxGui.refresh_widgets | (self) | Check through mainframe what the state of the application is
and reset widgets. For exampe enable/disable widgets
dependent on the availability of data. | Check through mainframe what the state of the application is
and reset widgets. For exampe enable/disable widgets
dependent on the availability of data. | [
"Check",
"through",
"mainframe",
"what",
"the",
"state",
"of",
"the",
"application",
"is",
"and",
"reset",
"widgets",
".",
"For",
"exampe",
"enable",
"/",
"disable",
"widgets",
"dependent",
"on",
"the",
"availability",
"of",
"data",
"."
] | def refresh_widgets(self):
"""
Check through mainframe what the state of the application is
and reset widgets. For exampe enable/disable widgets
dependent on the availability of data.
"""
scenario = self.get_scenario()
print 'prtgui.refresh_widgets', self._simulation != scenario.simulation
is_refresh = False
if self._simulation != scenario.simulation:
del self._demand
del self._prtservice
del self._simulation
self._demand = scenario.demand
self._simulation = scenario.simulation
self._prtservice = self._simulation.add_simobject(ident='prtservice', SimClass=prt.PrtService)
is_refresh = True
neteditor = self.get_neteditor()
neteditor.get_toolbox().add_toolclass(AddPrtCompressorTool) | [
"def",
"refresh_widgets",
"(",
"self",
")",
":",
"scenario",
"=",
"self",
".",
"get_scenario",
"(",
")",
"print",
"'prtgui.refresh_widgets'",
",",
"self",
".",
"_simulation",
"!=",
"scenario",
".",
"simulation",
"is_refresh",
"=",
"False",
"if",
"self",
".",
... | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/prt/wxgui.py#L332-L351 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Image.SaveMimeStream | (*args, **kwargs) | return _core_.Image_SaveMimeStream(*args, **kwargs) | SaveMimeStream(self, wxOutputStream stream, String mimetype) -> bool
Saves an image in the named file. | SaveMimeStream(self, wxOutputStream stream, String mimetype) -> bool | [
"SaveMimeStream",
"(",
"self",
"wxOutputStream",
"stream",
"String",
"mimetype",
")",
"-",
">",
"bool"
] | def SaveMimeStream(*args, **kwargs):
"""
SaveMimeStream(self, wxOutputStream stream, String mimetype) -> bool
Saves an image in the named file.
"""
return _core_.Image_SaveMimeStream(*args, **kwargs) | [
"def",
"SaveMimeStream",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_SaveMimeStream",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L3219-L3225 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/msvs_emulation.py | python | EncodeRspFileList | (args) | return program + ' ' + ' '.join(QuoteForRspFile(arg) for arg in args[1:]) | Process a list of arguments using QuoteCmdExeArgument. | Process a list of arguments using QuoteCmdExeArgument. | [
"Process",
"a",
"list",
"of",
"arguments",
"using",
"QuoteCmdExeArgument",
"."
] | def EncodeRspFileList(args):
"""Process a list of arguments using QuoteCmdExeArgument."""
# Note that the first argument is assumed to be the command. Don't add
# quotes around it because then built-ins like 'echo', etc. won't work.
# Take care to normpath only the path in the case of 'call ../x.bat' because
# otherwise the whole thing is incorrectly interpreted as a path and not
# normalized correctly.
if not args: return ''
if args[0].startswith('call '):
call, program = args[0].split(' ', 1)
program = call + ' ' + os.path.normpath(program)
else:
program = os.path.normpath(args[0])
return program + ' ' + ' '.join(QuoteForRspFile(arg) for arg in args[1:]) | [
"def",
"EncodeRspFileList",
"(",
"args",
")",
":",
"# Note that the first argument is assumed to be the command. Don't add",
"# quotes around it because then built-ins like 'echo', etc. won't work.",
"# Take care to normpath only the path in the case of 'call ../x.bat' because",
"# otherwise the w... | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/msvs_emulation.py#L77-L90 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | parserCtxt.handleEntity | (self, entity) | Default handling of defined entities, when should we define
a new input stream ? When do we just handle that as a set
of chars ? OBSOLETE: to be removed at some point. | Default handling of defined entities, when should we define
a new input stream ? When do we just handle that as a set
of chars ? OBSOLETE: to be removed at some point. | [
"Default",
"handling",
"of",
"defined",
"entities",
"when",
"should",
"we",
"define",
"a",
"new",
"input",
"stream",
"?",
"When",
"do",
"we",
"just",
"handle",
"that",
"as",
"a",
"set",
"of",
"chars",
"?",
"OBSOLETE",
":",
"to",
"be",
"removed",
"at",
... | def handleEntity(self, entity):
"""Default handling of defined entities, when should we define
a new input stream ? When do we just handle that as a set
of chars ? OBSOLETE: to be removed at some point. """
if entity is None: entity__o = None
else: entity__o = entity._o
libxml2mod.xmlHandleEntity(self._o, entity__o) | [
"def",
"handleEntity",
"(",
"self",
",",
"entity",
")",
":",
"if",
"entity",
"is",
"None",
":",
"entity__o",
"=",
"None",
"else",
":",
"entity__o",
"=",
"entity",
".",
"_o",
"libxml2mod",
".",
"xmlHandleEntity",
"(",
"self",
".",
"_o",
",",
"entity__o",
... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L5141-L5147 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/multi_worker_util.py | python | should_load_checkpoint | () | return dc_context.get_current_worker_context().experimental_should_init | Returns whether the current worker should load checkpoints.
In multi-worker training, if loading checkpoint is requested by user, or
needed for fault-tolerance, the cluster should load checkpoint but not
necessarily every worker in the cluster should.
Returns:
Whether this particular worker in the cluster should load checkpoints. | Returns whether the current worker should load checkpoints. | [
"Returns",
"whether",
"the",
"current",
"worker",
"should",
"load",
"checkpoints",
"."
] | def should_load_checkpoint():
"""Returns whether the current worker should load checkpoints.
In multi-worker training, if loading checkpoint is requested by user, or
needed for fault-tolerance, the cluster should load checkpoint but not
necessarily every worker in the cluster should.
Returns:
Whether this particular worker in the cluster should load checkpoints.
"""
return dc_context.get_current_worker_context().experimental_should_init | [
"def",
"should_load_checkpoint",
"(",
")",
":",
"return",
"dc_context",
".",
"get_current_worker_context",
"(",
")",
".",
"experimental_should_init"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/multi_worker_util.py#L282-L292 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/image/image.py | python | RandomGrayAug.__call__ | (self, src) | return src | Augmenter body | Augmenter body | [
"Augmenter",
"body"
] | def __call__(self, src):
"""Augmenter body"""
if random.random() < self.p:
src = nd.dot(src, self.mat)
return src | [
"def",
"__call__",
"(",
"self",
",",
"src",
")",
":",
"if",
"random",
".",
"random",
"(",
")",
"<",
"self",
".",
"p",
":",
"src",
"=",
"nd",
".",
"dot",
"(",
"src",
",",
"self",
".",
"mat",
")",
"return",
"src"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/image/image.py#L1133-L1137 | |
openbabel/openbabel | f3ed2a9a5166dbd3b9ce386e636a176074a6c34c | scripts/python/openbabel/pybel.py | python | Molecule.addh | (self) | Add hydrogens. | Add hydrogens. | [
"Add",
"hydrogens",
"."
] | def addh(self):
"""Add hydrogens."""
self.OBMol.AddHydrogens() | [
"def",
"addh",
"(",
"self",
")",
":",
"self",
".",
"OBMol",
".",
"AddHydrogens",
"(",
")"
] | https://github.com/openbabel/openbabel/blob/f3ed2a9a5166dbd3b9ce386e636a176074a6c34c/scripts/python/openbabel/pybel.py#L608-L610 | ||
musescore/MuseScore | a817fea23e3c2be30847b7fde5b01746222c252e | thirdparty/freetype/src/tools/docmaker/docbeauty.py | python | main | ( argv ) | main program loop | main program loop | [
"main",
"program",
"loop"
] | def main( argv ):
"""main program loop"""
global output_dir
try:
opts, args = getopt.getopt( sys.argv[1:], \
"hb", \
["help", "backup"] )
except getopt.GetoptError:
usage()
sys.exit( 2 )
if args == []:
usage()
sys.exit( 1 )
# process options
#
output_dir = None
do_backup = None
for opt in opts:
if opt[0] in ( "-h", "--help" ):
usage()
sys.exit( 0 )
if opt[0] in ( "-b", "--backup" ):
do_backup = 1
# create context and processor
source_processor = SourceProcessor()
# retrieve the list of files to process
file_list = make_file_list( args )
for filename in file_list:
source_processor.parse_file( filename )
for block in source_processor.blocks:
beautify_block( block )
new_name = filename + ".new"
ok = None
try:
file = open( new_name, "wt" )
for block in source_processor.blocks:
for line in block.lines:
file.write( line )
file.write( "\n" )
file.close()
except:
ok = 0 | [
"def",
"main",
"(",
"argv",
")",
":",
"global",
"output_dir",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"\"hb\"",
",",
"[",
"\"help\"",
",",
"\"backup\"",
"]",
")",
"except",
... | https://github.com/musescore/MuseScore/blob/a817fea23e3c2be30847b7fde5b01746222c252e/thirdparty/freetype/src/tools/docmaker/docbeauty.py#L52-L104 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py | python | PythonModuleMakefile.__init__ | (self, configuration, dstdir, srcdir=None, dir=None,
makefile="Makefile", installs=None) | Initialise an instance of a parent Makefile.
dstdir is the name of the directory where the module's Python code will
be installed.
srcdir is the name of the directory (relative to the directory in which
the Makefile will be created) containing the module's Python code. It
defaults to the same directory. | Initialise an instance of a parent Makefile. | [
"Initialise",
"an",
"instance",
"of",
"a",
"parent",
"Makefile",
"."
] | def __init__(self, configuration, dstdir, srcdir=None, dir=None,
makefile="Makefile", installs=None):
"""Initialise an instance of a parent Makefile.
dstdir is the name of the directory where the module's Python code will
be installed.
srcdir is the name of the directory (relative to the directory in which
the Makefile will be created) containing the module's Python code. It
defaults to the same directory.
"""
Makefile.__init__(self, configuration, dir=dir, makefile=makefile, installs=installs)
if not srcdir:
srcdir = "."
if dir:
self._moddir = os.path.join(dir, srcdir)
else:
self._moddir = srcdir
self._srcdir = srcdir
self._dstdir = dstdir | [
"def",
"__init__",
"(",
"self",
",",
"configuration",
",",
"dstdir",
",",
"srcdir",
"=",
"None",
",",
"dir",
"=",
"None",
",",
"makefile",
"=",
"\"Makefile\"",
",",
"installs",
"=",
"None",
")",
":",
"Makefile",
".",
"__init__",
"(",
"self",
",",
"conf... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py#L1462-L1483 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/importOCA.py | python | open | (filename) | Open filename and parse.
Parameters
----------
filename : str
The path to the filename to be opened.
Returns
-------
None | Open filename and parse. | [
"Open",
"filename",
"and",
"parse",
"."
] | def open(filename):
"""Open filename and parse.
Parameters
----------
filename : str
The path to the filename to be opened.
Returns
-------
None
"""
docname = os.path.split(filename)[1]
doc = FreeCAD.newDocument(docname)
if docname[-4:] == "gcad":
doc.Label = docname[:-5]
else:
doc.Label = docname[:-4]
parse(filename, doc)
doc.recompute() | [
"def",
"open",
"(",
"filename",
")",
":",
"docname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
")",
"[",
"1",
"]",
"doc",
"=",
"FreeCAD",
".",
"newDocument",
"(",
"docname",
")",
"if",
"docname",
"[",
"-",
"4",
":",
"]",
"==",
"\"gca... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/importOCA.py#L367-L386 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | DateTime.GetYearDay | (*args, **kwargs) | return _misc_.DateTime_GetYearDay(*args, **kwargs) | GetYearDay(self, int yday) -> DateTime | GetYearDay(self, int yday) -> DateTime | [
"GetYearDay",
"(",
"self",
"int",
"yday",
")",
"-",
">",
"DateTime"
] | def GetYearDay(*args, **kwargs):
"""GetYearDay(self, int yday) -> DateTime"""
return _misc_.DateTime_GetYearDay(*args, **kwargs) | [
"def",
"GetYearDay",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_GetYearDay",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L3898-L3900 | |
WenmuZhou/PSENet.pytorch | f760c2f4938726a2d00efaf5e5b28218323c44ca | cal_recall/script.py | python | default_evaluation_params | () | return {
'IOU_CONSTRAINT': 0.5,
'AREA_PRECISION_CONSTRAINT': 0.5,
'GT_SAMPLE_NAME_2_ID': 'gt_img_([0-9]+).txt',
'DET_SAMPLE_NAME_2_ID': 'res_img_([0-9]+).txt',
'LTRB': False, # LTRB:2points(left,top,right,bottom) or 4 points(x1,y1,x2,y2,x3,y3,x4,y4)
'CRLF': False, # Lines are delimited by Windows CRLF format
'CONFIDENCES': False, # Detections must include confidence value. AP will be calculated
'PER_SAMPLE_RESULTS': True # Generate per sample results and produce data for visualization
} | default_evaluation_params: Default parameters to use for the validation and evaluation. | default_evaluation_params: Default parameters to use for the validation and evaluation. | [
"default_evaluation_params",
":",
"Default",
"parameters",
"to",
"use",
"for",
"the",
"validation",
"and",
"evaluation",
"."
] | def default_evaluation_params():
"""
default_evaluation_params: Default parameters to use for the validation and evaluation.
"""
return {
'IOU_CONSTRAINT': 0.5,
'AREA_PRECISION_CONSTRAINT': 0.5,
'GT_SAMPLE_NAME_2_ID': 'gt_img_([0-9]+).txt',
'DET_SAMPLE_NAME_2_ID': 'res_img_([0-9]+).txt',
'LTRB': False, # LTRB:2points(left,top,right,bottom) or 4 points(x1,y1,x2,y2,x3,y3,x4,y4)
'CRLF': False, # Lines are delimited by Windows CRLF format
'CONFIDENCES': False, # Detections must include confidence value. AP will be calculated
'PER_SAMPLE_RESULTS': True # Generate per sample results and produce data for visualization
} | [
"def",
"default_evaluation_params",
"(",
")",
":",
"return",
"{",
"'IOU_CONSTRAINT'",
":",
"0.5",
",",
"'AREA_PRECISION_CONSTRAINT'",
":",
"0.5",
",",
"'GT_SAMPLE_NAME_2_ID'",
":",
"'gt_img_([0-9]+).txt'",
",",
"'DET_SAMPLE_NAME_2_ID'",
":",
"'res_img_([0-9]+).txt'",
",",... | https://github.com/WenmuZhou/PSENet.pytorch/blob/f760c2f4938726a2d00efaf5e5b28218323c44ca/cal_recall/script.py#L9-L22 | |
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | mlir/python/mlir/dialects/linalg/opdsl/lang/emitter.py | python | _infer_structured_outs | (
op_config: LinalgStructuredOpConfig,
in_arg_defs: Sequence[OperandDefConfig], ins: Sequence[Value],
out_arg_defs: Sequence[OperandDefConfig],
outs: Union[Sequence[Value], OpResultList]) | Infers implicit outs and output types.
Respects existing contents of outs if not empty.
Returns:
normalized outs, output types | Infers implicit outs and output types. | [
"Infers",
"implicit",
"outs",
"and",
"output",
"types",
"."
] | def _infer_structured_outs(
op_config: LinalgStructuredOpConfig,
in_arg_defs: Sequence[OperandDefConfig], ins: Sequence[Value],
out_arg_defs: Sequence[OperandDefConfig],
outs: Union[Sequence[Value], OpResultList]) -> Tuple[ValueList, List[Type]]:
"""Infers implicit outs and output types.
Respects existing contents of outs if not empty.
Returns:
normalized outs, output types
"""
# If outs were explicitly provided, we accept them verbatim.
if outs:
return outs, [out.type for out in outs]
raise NotImplementedError(f"Output tensor inference not yet supported for "
"structured ops") | [
"def",
"_infer_structured_outs",
"(",
"op_config",
":",
"LinalgStructuredOpConfig",
",",
"in_arg_defs",
":",
"Sequence",
"[",
"OperandDefConfig",
"]",
",",
"ins",
":",
"Sequence",
"[",
"Value",
"]",
",",
"out_arg_defs",
":",
"Sequence",
"[",
"OperandDefConfig",
"]... | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/mlir/python/mlir/dialects/linalg/opdsl/lang/emitter.py#L373-L390 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/shutil.py | python | get_archive_formats | () | return formats | Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description) | Returns a list of supported formats for archiving and unarchiving. | [
"Returns",
"a",
"list",
"of",
"supported",
"formats",
"for",
"archiving",
"and",
"unarchiving",
"."
] | def get_archive_formats():
"""Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description)
"""
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
formats.sort()
return formats | [
"def",
"get_archive_formats",
"(",
")",
":",
"formats",
"=",
"[",
"(",
"name",
",",
"registry",
"[",
"2",
"]",
")",
"for",
"name",
",",
"registry",
"in",
"_ARCHIVE_FORMATS",
".",
"items",
"(",
")",
"]",
"formats",
".",
"sort",
"(",
")",
"return",
"fo... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/shutil.py#L513-L521 | |
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | thirdparty/gflags/gflags.py | python | MultiFlag.Parse | (self, arguments) | Parses one or more arguments with the installed parser.
Args:
arguments: a single argument or a list of arguments (typically a
list of default values); a single argument is converted
internally into a list containing one item. | Parses one or more arguments with the installed parser. | [
"Parses",
"one",
"or",
"more",
"arguments",
"with",
"the",
"installed",
"parser",
"."
] | def Parse(self, arguments):
"""Parses one or more arguments with the installed parser.
Args:
arguments: a single argument or a list of arguments (typically a
list of default values); a single argument is converted
internally into a list containing one item.
"""
if not isinstance(arguments, list):
# Default value may be a list of values. Most other arguments
# will not be, so convert them into a single-item list to make
# processing simpler below.
arguments = [arguments]
if self.present:
# keep a backup reference to list of previously supplied option values
values = self.value
else:
# "erase" the defaults with an empty list
values = []
for item in arguments:
# have Flag superclass parse argument, overwriting self.value reference
Flag.Parse(self, item) # also increments self.present
values.append(self.value)
# put list of option values back in the 'value' attribute
self.value = values | [
"def",
"Parse",
"(",
"self",
",",
"arguments",
")",
":",
"if",
"not",
"isinstance",
"(",
"arguments",
",",
"list",
")",
":",
"# Default value may be a list of values. Most other arguments",
"# will not be, so convert them into a single-item list to make",
"# processing simpler... | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/thirdparty/gflags/gflags.py#L2654-L2681 | ||
linyouhappy/kongkongxiyou | 7a69b2913eb29f4be77f9a62fb90cdd72c4160f1 | cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | Type.is_pod | (self) | return conf.lib.clang_isPODType(self) | Determine whether this Type represents plain old data (POD). | Determine whether this Type represents plain old data (POD). | [
"Determine",
"whether",
"this",
"Type",
"represents",
"plain",
"old",
"data",
"(",
"POD",
")",
"."
] | def is_pod(self):
"""Determine whether this Type represents plain old data (POD)."""
return conf.lib.clang_isPODType(self) | [
"def",
"is_pod",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isPODType",
"(",
"self",
")"
] | https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1770-L1772 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | chrome/common/extensions/docs/server2/new_github_file_system.py | python | _GithubZipFile.Read | (self, path) | return self._zipball.read(posixpath.join(self._name_prefix, path)) | Returns the contents of |path|. Raises a KeyError if it doesn't exist. | Returns the contents of |path|. Raises a KeyError if it doesn't exist. | [
"Returns",
"the",
"contents",
"of",
"|path|",
".",
"Raises",
"a",
"KeyError",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | def Read(self, path):
'''Returns the contents of |path|. Raises a KeyError if it doesn't exist.
'''
return self._zipball.read(posixpath.join(self._name_prefix, path)) | [
"def",
"Read",
"(",
"self",
",",
"path",
")",
":",
"return",
"self",
".",
"_zipball",
".",
"read",
"(",
"posixpath",
".",
"join",
"(",
"self",
".",
"_name_prefix",
",",
"path",
")",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/new_github_file_system.py#L89-L92 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewModel.ChangeValue | (*args, **kwargs) | return _dataview.DataViewModel_ChangeValue(*args, **kwargs) | ChangeValue(self, wxVariant variant, DataViewItem item, unsigned int col) -> bool | ChangeValue(self, wxVariant variant, DataViewItem item, unsigned int col) -> bool | [
"ChangeValue",
"(",
"self",
"wxVariant",
"variant",
"DataViewItem",
"item",
"unsigned",
"int",
"col",
")",
"-",
">",
"bool"
] | def ChangeValue(*args, **kwargs):
"""ChangeValue(self, wxVariant variant, DataViewItem item, unsigned int col) -> bool"""
return _dataview.DataViewModel_ChangeValue(*args, **kwargs) | [
"def",
"ChangeValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewModel_ChangeValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L492-L494 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | Bracket.__init__ | (self) | Create a (possibly literal) new bracket | Create a (possibly literal) new bracket | [
"Create",
"a",
"(",
"possibly",
"literal",
")",
"new",
"bracket"
] | def __init__(self):
"Create a (possibly literal) new bracket"
FormulaBit.__init__(self)
self.inner = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"FormulaBit",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"inner",
"=",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L2760-L2763 | ||
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/jinja2/environment.py | python | Environment.parse | (self, source, name=None, filename=None) | Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja2 extensions <writing-extensions>`
this gives you a good overview of the node tree generated. | Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates. | [
"Parse",
"the",
"sourcecode",
"and",
"return",
"the",
"abstract",
"syntax",
"tree",
".",
"This",
"tree",
"of",
"nodes",
"is",
"used",
"by",
"the",
"compiler",
"to",
"convert",
"the",
"template",
"into",
"executable",
"source",
"-",
"or",
"bytecode",
".",
"... | def parse(self, source, name=None, filename=None):
"""Parse the sourcecode and return the abstract syntax tree. This
tree of nodes is used by the compiler to convert the template into
executable source- or bytecode. This is useful for debugging or to
extract information from templates.
If you are :ref:`developing Jinja2 extensions <writing-extensions>`
this gives you a good overview of the node tree generated.
"""
try:
return self._parse(source, name, filename)
except TemplateSyntaxError:
exc_info = sys.exc_info()
self.handle_exception(exc_info, source_hint=source) | [
"def",
"parse",
"(",
"self",
",",
"source",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_parse",
"(",
"source",
",",
"name",
",",
"filename",
")",
"except",
"TemplateSyntaxError",
":",
"exc_info... | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/jinja2/environment.py#L381-L394 | ||
TGAC/KAT | e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216 | deps/boost/tools/build/src/build/generators.py | python | Generator.convert_to_consumable_types | (self, project, name, prop_set, sources, only_one=False) | return consumed | Attempts to convert 'source' to the types that this generator can
handle. The intention is to produce the set of targets can should be
used when generator is run.
only_one: convert 'source' to only one of source types
if there's more that one possibility, report an
error.
Returns a pair:
consumed: all targets that can be consumed. | Attempts to convert 'source' to the types that this generator can
handle. The intention is to produce the set of targets can should be
used when generator is run.
only_one: convert 'source' to only one of source types
if there's more that one possibility, report an
error. | [
"Attempts",
"to",
"convert",
"source",
"to",
"the",
"types",
"that",
"this",
"generator",
"can",
"handle",
".",
"The",
"intention",
"is",
"to",
"produce",
"the",
"set",
"of",
"targets",
"can",
"should",
"be",
"used",
"when",
"generator",
"is",
"run",
".",
... | def convert_to_consumable_types (self, project, name, prop_set, sources, only_one=False):
""" Attempts to convert 'source' to the types that this generator can
handle. The intention is to produce the set of targets can should be
used when generator is run.
only_one: convert 'source' to only one of source types
if there's more that one possibility, report an
error.
Returns a pair:
consumed: all targets that can be consumed.
"""
if __debug__:
from .targets import ProjectTarget
assert isinstance(name, basestring) or name is None
assert isinstance(project, ProjectTarget)
assert isinstance(prop_set, property_set.PropertySet)
assert is_iterable_typed(sources, virtual_target.VirtualTarget)
assert isinstance(only_one, bool)
consumed = []
missing_types = []
if len (sources) > 1:
# Don't know how to handle several sources yet. Just try
# to pass the request to other generator
missing_types = self.source_types_
else:
(c, m) = self.consume_directly (sources [0])
consumed += c
missing_types += m
# No need to search for transformation if
# some source type has consumed source and
# no more source types are needed.
if only_one and consumed:
missing_types = []
#TODO: we should check that only one source type
#if create of 'only_one' is true.
# TODO: consider if consuned/bypassed separation should
# be done by 'construct_types'.
if missing_types:
transformed = construct_types (project, name, missing_types, prop_set, sources)
# Add targets of right type to 'consumed'. Add others to
# 'bypassed'. The 'generators.construct' rule has done
# its best to convert everything to the required type.
# There's no need to rerun it on targets of different types.
# NOTE: ignoring usage requirements
for t in transformed[1]:
if t.type() in missing_types:
consumed.append(t)
consumed = unique(consumed)
return consumed | [
"def",
"convert_to_consumable_types",
"(",
"self",
",",
"project",
",",
"name",
",",
"prop_set",
",",
"sources",
",",
"only_one",
"=",
"False",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"targets",
"import",
"ProjectTarget",
"assert",
"isinstance",
"(",
... | https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/build/generators.py#L528-L585 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | clang-tools-extra/clang-include-fixer/find-all-symbols/tool/run-find-all-symbols.py | python | run_find_all_symbols | (args, tmpdir, build_path, queue) | Takes filenames out of queue and runs find-all-symbols on them. | Takes filenames out of queue and runs find-all-symbols on them. | [
"Takes",
"filenames",
"out",
"of",
"queue",
"and",
"runs",
"find",
"-",
"all",
"-",
"symbols",
"on",
"them",
"."
] | def run_find_all_symbols(args, tmpdir, build_path, queue):
"""Takes filenames out of queue and runs find-all-symbols on them."""
while True:
name = queue.get()
invocation = [args.binary, name, '-output-dir='+tmpdir, '-p='+build_path]
sys.stdout.write(' '.join(invocation) + '\n')
subprocess.call(invocation)
queue.task_done() | [
"def",
"run_find_all_symbols",
"(",
"args",
",",
"tmpdir",
",",
"build_path",
",",
"queue",
")",
":",
"while",
"True",
":",
"name",
"=",
"queue",
".",
"get",
"(",
")",
"invocation",
"=",
"[",
"args",
".",
"binary",
",",
"name",
",",
"'-output-dir='",
"... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang-tools-extra/clang-include-fixer/find-all-symbols/tool/run-find-all-symbols.py#L55-L62 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/arrayobj.py | python | _empty_nd_impl | (context, builder, arrtype, shapes) | return ary | Utility function used for allocating a new array during LLVM code
generation (lowering). Given a target context, builder, array
type, and a tuple or list of lowered dimension sizes, returns a
LLVM value pointing at a Numba runtime allocated array. | Utility function used for allocating a new array during LLVM code
generation (lowering). Given a target context, builder, array
type, and a tuple or list of lowered dimension sizes, returns a
LLVM value pointing at a Numba runtime allocated array. | [
"Utility",
"function",
"used",
"for",
"allocating",
"a",
"new",
"array",
"during",
"LLVM",
"code",
"generation",
"(",
"lowering",
")",
".",
"Given",
"a",
"target",
"context",
"builder",
"array",
"type",
"and",
"a",
"tuple",
"or",
"list",
"of",
"lowered",
"... | def _empty_nd_impl(context, builder, arrtype, shapes):
"""Utility function used for allocating a new array during LLVM code
generation (lowering). Given a target context, builder, array
type, and a tuple or list of lowered dimension sizes, returns a
LLVM value pointing at a Numba runtime allocated array.
"""
arycls = make_array(arrtype)
ary = arycls(context, builder)
datatype = context.get_data_type(arrtype.dtype)
itemsize = context.get_constant(types.intp, get_itemsize(context, arrtype))
# compute array length
arrlen = context.get_constant(types.intp, 1)
overflow = ir.Constant(ir.IntType(1), 0)
for s in shapes:
arrlen_mult = builder.smul_with_overflow(arrlen, s)
arrlen = builder.extract_value(arrlen_mult, 0)
overflow = builder.or_(
overflow, builder.extract_value(arrlen_mult, 1)
)
if arrtype.ndim == 0:
strides = ()
elif arrtype.layout == 'C':
strides = [itemsize]
for dimension_size in reversed(shapes[1:]):
strides.append(builder.mul(strides[-1], dimension_size))
strides = tuple(reversed(strides))
elif arrtype.layout == 'F':
strides = [itemsize]
for dimension_size in shapes[:-1]:
strides.append(builder.mul(strides[-1], dimension_size))
strides = tuple(strides)
else:
raise NotImplementedError(
"Don't know how to allocate array with layout '{0}'.".format(
arrtype.layout))
# Check overflow, numpy also does this after checking order
allocsize_mult = builder.smul_with_overflow(arrlen, itemsize)
allocsize = builder.extract_value(allocsize_mult, 0)
overflow = builder.or_(overflow, builder.extract_value(allocsize_mult, 1))
with builder.if_then(overflow, likely=False):
# Raise same error as numpy, see:
# https://github.com/numpy/numpy/blob/2a488fe76a0f732dc418d03b452caace161673da/numpy/core/src/multiarray/ctors.c#L1095-L1101 # noqa: E501
context.call_conv.return_user_exc(
builder, ValueError,
("array is too big; `arr.size * arr.dtype.itemsize` is larger than"
" the maximum possible size.",)
)
align = context.get_preferred_array_alignment(arrtype.dtype)
meminfo = context.nrt.meminfo_alloc_aligned(builder, size=allocsize,
align=align)
data = context.nrt.meminfo_data(builder, meminfo)
intp_t = context.get_value_type(types.intp)
shape_array = cgutils.pack_array(builder, shapes, ty=intp_t)
strides_array = cgutils.pack_array(builder, strides, ty=intp_t)
populate_array(ary,
data=builder.bitcast(data, datatype.as_pointer()),
shape=shape_array,
strides=strides_array,
itemsize=itemsize,
meminfo=meminfo)
return ary | [
"def",
"_empty_nd_impl",
"(",
"context",
",",
"builder",
",",
"arrtype",
",",
"shapes",
")",
":",
"arycls",
"=",
"make_array",
"(",
"arrtype",
")",
"ary",
"=",
"arycls",
"(",
"context",
",",
"builder",
")",
"datatype",
"=",
"context",
".",
"get_data_type",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/arrayobj.py#L3335-L3405 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowser.py | python | FitPropertyBrowser._set_peak_initial_fwhm | (self, fun, fwhm) | Overwrite fwhm if has not been set already - this is for back to back exponential type funcs
which have had the width parameter (S) as func d-spacing refined for a standard sample (coefs stored in
instrument Paramters.xml) and has already been set.
:param fun: peak function prefix
:param fwhm: estimated fwhm of peak added | Overwrite fwhm if has not been set already - this is for back to back exponential type funcs
which have had the width parameter (S) as func d-spacing refined for a standard sample (coefs stored in
instrument Paramters.xml) and has already been set.
:param fun: peak function prefix
:param fwhm: estimated fwhm of peak added | [
"Overwrite",
"fwhm",
"if",
"has",
"not",
"been",
"set",
"already",
"-",
"this",
"is",
"for",
"back",
"to",
"back",
"exponential",
"type",
"funcs",
"which",
"have",
"had",
"the",
"width",
"parameter",
"(",
"S",
")",
"as",
"func",
"d",
"-",
"spacing",
"r... | def _set_peak_initial_fwhm(self, fun, fwhm):
"""
Overwrite fwhm if has not been set already - this is for back to back exponential type funcs
which have had the width parameter (S) as func d-spacing refined for a standard sample (coefs stored in
instrument Paramters.xml) and has already been set.
:param fun: peak function prefix
:param fwhm: estimated fwhm of peak added
"""
if not self.getWidthParameterNameOf(fun) or not \
self.isParameterExplicitlySetOf(fun, self.getWidthParameterNameOf(fun)):
self.setPeakFwhmOf(fun, fwhm) | [
"def",
"_set_peak_initial_fwhm",
"(",
"self",
",",
"fun",
",",
"fwhm",
")",
":",
"if",
"not",
"self",
".",
"getWidthParameterNameOf",
"(",
"fun",
")",
"or",
"not",
"self",
".",
"isParameterExplicitlySetOf",
"(",
"fun",
",",
"self",
".",
"getWidthParameterNameO... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowser.py#L166-L176 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py3/IPython/utils/_process_win32.py | python | getoutput | (cmd) | return py3compat.decode(out) | Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str or list
A command to be executed in the system shell.
Returns
-------
stdout : str | Return standard output of executing cmd in a shell. | [
"Return",
"standard",
"output",
"of",
"executing",
"cmd",
"in",
"a",
"shell",
"."
] | def getoutput(cmd):
"""Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str or list
A command to be executed in the system shell.
Returns
-------
stdout : str
"""
with AvoidUNCPath() as path:
if path is not None:
cmd = '"pushd %s &&"%s' % (path, cmd)
out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT)
if out is None:
out = b''
return py3compat.decode(out) | [
"def",
"getoutput",
"(",
"cmd",
")",
":",
"with",
"AvoidUNCPath",
"(",
")",
"as",
"path",
":",
"if",
"path",
"is",
"not",
"None",
":",
"cmd",
"=",
"'\"pushd %s &&\"%s'",
"%",
"(",
"path",
",",
"cmd",
")",
"out",
"=",
"process_handler",
"(",
"cmd",
",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/utils/_process_win32.py#L147-L169 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/gyp/pylib/gyp/generator/msvs.py | python | _FixPaths | (paths, separator="\\") | return [_FixPath(i, separator) for i in paths] | Fix each of the paths of the list. | Fix each of the paths of the list. | [
"Fix",
"each",
"of",
"the",
"paths",
"of",
"the",
"list",
"."
] | def _FixPaths(paths, separator="\\"):
"""Fix each of the paths of the list."""
return [_FixPath(i, separator) for i in paths] | [
"def",
"_FixPaths",
"(",
"paths",
",",
"separator",
"=",
"\"\\\\\"",
")",
":",
"return",
"[",
"_FixPath",
"(",
"i",
",",
"separator",
")",
"for",
"i",
"in",
"paths",
"]"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/generator/msvs.py#L191-L193 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/arrays/categorical.py | python | Categorical._reverse_indexer | (self) | return result | Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(list('aabca'))
In [2]: c
Out[2]:
[a, a, b, c, a]
Categories (3, object): [a, b, c]
In [3]: c.categories
Out[3]: Index([u'a', u'b', u'c'], dtype='object')
In [4]: c.codes
Out[4]: array([0, 0, 1, 2, 0], dtype=int8)
In [5]: c._reverse_indexer()
Out[5]: {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])} | Compute the inverse of a categorical, returning
a dict of categories -> indexers. | [
"Compute",
"the",
"inverse",
"of",
"a",
"categorical",
"returning",
"a",
"dict",
"of",
"categories",
"-",
">",
"indexers",
"."
] | def _reverse_indexer(self):
"""
Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(list('aabca'))
In [2]: c
Out[2]:
[a, a, b, c, a]
Categories (3, object): [a, b, c]
In [3]: c.categories
Out[3]: Index([u'a', u'b', u'c'], dtype='object')
In [4]: c.codes
Out[4]: array([0, 0, 1, 2, 0], dtype=int8)
In [5]: c._reverse_indexer()
Out[5]: {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])}
"""
categories = self.categories
r, counts = libalgos.groupsort_indexer(self.codes.astype('int64'),
categories.size)
counts = counts.cumsum()
result = [r[counts[indexer]:counts[indexer + 1]]
for indexer in range(len(counts) - 1)]
result = dict(zip(categories, result))
return result | [
"def",
"_reverse_indexer",
"(",
"self",
")",
":",
"categories",
"=",
"self",
".",
"categories",
"r",
",",
"counts",
"=",
"libalgos",
".",
"groupsort_indexer",
"(",
"self",
".",
"codes",
".",
"astype",
"(",
"'int64'",
")",
",",
"categories",
".",
"size",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/categorical.py#L2128-L2165 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/signal/ltisys.py | python | place_poles | (A, B, poles, method="YT", rtol=1e-3, maxiter=30) | return full_state_feedback | Compute K such that eigenvalues (A - dot(B, K))=poles.
K is the gain matrix such as the plant described by the linear system
``AX+BU`` will have its closed-loop poles, i.e the eigenvalues ``A - B*K``,
as close as possible to those asked for in poles.
SISO, MISO and MIMO systems are supported.
Parameters
----------
A, B : ndarray
State-space representation of linear system ``AX + BU``.
poles : array_like
Desired real poles and/or complex conjugates poles.
Complex poles are only supported with ``method="YT"`` (default).
method: {'YT', 'KNV0'}, optional
Which method to choose to find the gain matrix K. One of:
- 'YT': Yang Tits
- 'KNV0': Kautsky, Nichols, Van Dooren update method 0
See References and Notes for details on the algorithms.
rtol: float, optional
After each iteration the determinant of the eigenvectors of
``A - B*K`` is compared to its previous value, when the relative
error between these two values becomes lower than `rtol` the algorithm
stops. Default is 1e-3.
maxiter: int, optional
Maximum number of iterations to compute the gain matrix.
Default is 30.
Returns
-------
full_state_feedback : Bunch object
full_state_feedback is composed of:
gain_matrix : 1-D ndarray
The closed loop matrix K such as the eigenvalues of ``A-BK``
are as close as possible to the requested poles.
computed_poles : 1-D ndarray
The poles corresponding to ``A-BK`` sorted as first the real
poles in increasing order, then the complex congugates in
lexicographic order.
requested_poles : 1-D ndarray
The poles the algorithm was asked to place sorted as above,
they may differ from what was achieved.
X : 2-D ndarray
The transfer matrix such as ``X * diag(poles) = (A - B*K)*X``
(see Notes)
rtol : float
The relative tolerance achieved on ``det(X)`` (see Notes).
`rtol` will be NaN if it is possible to solve the system
``diag(poles) = (A - B*K)``, or 0 when the optimization
algorithms can't do anything i.e when ``B.shape[1] == 1``.
nb_iter : int
The number of iterations performed before converging.
`nb_iter` will be NaN if it is possible to solve the system
``diag(poles) = (A - B*K)``, or 0 when the optimization
algorithms can't do anything i.e when ``B.shape[1] == 1``.
Notes
-----
The Tits and Yang (YT), [2]_ paper is an update of the original Kautsky et
al. (KNV) paper [1]_. KNV relies on rank-1 updates to find the transfer
matrix X such that ``X * diag(poles) = (A - B*K)*X``, whereas YT uses
rank-2 updates. This yields on average more robust solutions (see [2]_
pp 21-22), furthermore the YT algorithm supports complex poles whereas KNV
does not in its original version. Only update method 0 proposed by KNV has
been implemented here, hence the name ``'KNV0'``.
KNV extended to complex poles is used in Matlab's ``place`` function, YT is
distributed under a non-free licence by Slicot under the name ``robpole``.
It is unclear and undocumented how KNV0 has been extended to complex poles
(Tits and Yang claim on page 14 of their paper that their method can not be
used to extend KNV to complex poles), therefore only YT supports them in
this implementation.
As the solution to the problem of pole placement is not unique for MIMO
systems, both methods start with a tentative transfer matrix which is
altered in various way to increase its determinant. Both methods have been
proven to converge to a stable solution, however depending on the way the
initial transfer matrix is chosen they will converge to different
solutions and therefore there is absolutely no guarantee that using
``'KNV0'`` will yield results similar to Matlab's or any other
implementation of these algorithms.
Using the default method ``'YT'`` should be fine in most cases; ``'KNV0'``
is only provided because it is needed by ``'YT'`` in some specific cases.
Furthermore ``'YT'`` gives on average more robust results than ``'KNV0'``
when ``abs(det(X))`` is used as a robustness indicator.
[2]_ is available as a technical report on the following URL:
https://hdl.handle.net/1903/5598
References
----------
.. [1] J. Kautsky, N.K. Nichols and P. van Dooren, "Robust pole assignment
in linear state feedback", International Journal of Control, Vol. 41
pp. 1129-1155, 1985.
.. [2] A.L. Tits and Y. Yang, "Globally convergent algorithms for robust
pole assignment by state feedback, IEEE Transactions on Automatic
Control, Vol. 41, pp. 1432-1452, 1996.
Examples
--------
A simple example demonstrating real pole placement using both KNV and YT
algorithms. This is example number 1 from section 4 of the reference KNV
publication ([1]_):
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> A = np.array([[ 1.380, -0.2077, 6.715, -5.676 ],
... [-0.5814, -4.290, 0, 0.6750 ],
... [ 1.067, 4.273, -6.654, 5.893 ],
... [ 0.0480, 4.273, 1.343, -2.104 ]])
>>> B = np.array([[ 0, 5.679 ],
... [ 1.136, 1.136 ],
... [ 0, 0, ],
... [-3.146, 0 ]])
>>> P = np.array([-0.2, -0.5, -5.0566, -8.6659])
Now compute K with KNV method 0, with the default YT method and with the YT
method while forcing 100 iterations of the algorithm and print some results
after each call.
>>> fsf1 = signal.place_poles(A, B, P, method='KNV0')
>>> fsf1.gain_matrix
array([[ 0.20071427, -0.96665799, 0.24066128, -0.10279785],
[ 0.50587268, 0.57779091, 0.51795763, -0.41991442]])
>>> fsf2 = signal.place_poles(A, B, P) # uses YT method
>>> fsf2.computed_poles
array([-8.6659, -5.0566, -0.5 , -0.2 ])
>>> fsf3 = signal.place_poles(A, B, P, rtol=-1, maxiter=100)
>>> fsf3.X
array([[ 0.52072442+0.j, -0.08409372+0.j, -0.56847937+0.j, 0.74823657+0.j],
[-0.04977751+0.j, -0.80872954+0.j, 0.13566234+0.j, -0.29322906+0.j],
[-0.82266932+0.j, -0.19168026+0.j, -0.56348322+0.j, -0.43815060+0.j],
[ 0.22267347+0.j, 0.54967577+0.j, -0.58387806+0.j, -0.40271926+0.j]])
The absolute value of the determinant of X is a good indicator to check the
robustness of the results, both ``'KNV0'`` and ``'YT'`` aim at maximizing
it. Below a comparison of the robustness of the results above:
>>> abs(np.linalg.det(fsf1.X)) < abs(np.linalg.det(fsf2.X))
True
>>> abs(np.linalg.det(fsf2.X)) < abs(np.linalg.det(fsf3.X))
True
Now a simple example for complex poles:
>>> A = np.array([[ 0, 7/3., 0, 0 ],
... [ 0, 0, 0, 7/9. ],
... [ 0, 0, 0, 0 ],
... [ 0, 0, 0, 0 ]])
>>> B = np.array([[ 0, 0 ],
... [ 0, 0 ],
... [ 1, 0 ],
... [ 0, 1 ]])
>>> P = np.array([-3, -1, -2-1j, -2+1j]) / 3.
>>> fsf = signal.place_poles(A, B, P, method='YT')
We can plot the desired and computed poles in the complex plane:
>>> t = np.linspace(0, 2*np.pi, 401)
>>> plt.plot(np.cos(t), np.sin(t), 'k--') # unit circle
>>> plt.plot(fsf.requested_poles.real, fsf.requested_poles.imag,
... 'wo', label='Desired')
>>> plt.plot(fsf.computed_poles.real, fsf.computed_poles.imag, 'bx',
... label='Placed')
>>> plt.grid()
>>> plt.axis('image')
>>> plt.axis([-1.1, 1.1, -1.1, 1.1])
>>> plt.legend(bbox_to_anchor=(1.05, 1), loc=2, numpoints=1) | Compute K such that eigenvalues (A - dot(B, K))=poles. | [
"Compute",
"K",
"such",
"that",
"eigenvalues",
"(",
"A",
"-",
"dot",
"(",
"B",
"K",
"))",
"=",
"poles",
"."
] | def place_poles(A, B, poles, method="YT", rtol=1e-3, maxiter=30):
"""
Compute K such that eigenvalues (A - dot(B, K))=poles.
K is the gain matrix such as the plant described by the linear system
``AX+BU`` will have its closed-loop poles, i.e the eigenvalues ``A - B*K``,
as close as possible to those asked for in poles.
SISO, MISO and MIMO systems are supported.
Parameters
----------
A, B : ndarray
State-space representation of linear system ``AX + BU``.
poles : array_like
Desired real poles and/or complex conjugates poles.
Complex poles are only supported with ``method="YT"`` (default).
method: {'YT', 'KNV0'}, optional
Which method to choose to find the gain matrix K. One of:
- 'YT': Yang Tits
- 'KNV0': Kautsky, Nichols, Van Dooren update method 0
See References and Notes for details on the algorithms.
rtol: float, optional
After each iteration the determinant of the eigenvectors of
``A - B*K`` is compared to its previous value, when the relative
error between these two values becomes lower than `rtol` the algorithm
stops. Default is 1e-3.
maxiter: int, optional
Maximum number of iterations to compute the gain matrix.
Default is 30.
Returns
-------
full_state_feedback : Bunch object
full_state_feedback is composed of:
gain_matrix : 1-D ndarray
The closed loop matrix K such as the eigenvalues of ``A-BK``
are as close as possible to the requested poles.
computed_poles : 1-D ndarray
The poles corresponding to ``A-BK`` sorted as first the real
poles in increasing order, then the complex congugates in
lexicographic order.
requested_poles : 1-D ndarray
The poles the algorithm was asked to place sorted as above,
they may differ from what was achieved.
X : 2-D ndarray
The transfer matrix such as ``X * diag(poles) = (A - B*K)*X``
(see Notes)
rtol : float
The relative tolerance achieved on ``det(X)`` (see Notes).
`rtol` will be NaN if it is possible to solve the system
``diag(poles) = (A - B*K)``, or 0 when the optimization
algorithms can't do anything i.e when ``B.shape[1] == 1``.
nb_iter : int
The number of iterations performed before converging.
`nb_iter` will be NaN if it is possible to solve the system
``diag(poles) = (A - B*K)``, or 0 when the optimization
algorithms can't do anything i.e when ``B.shape[1] == 1``.
Notes
-----
The Tits and Yang (YT), [2]_ paper is an update of the original Kautsky et
al. (KNV) paper [1]_. KNV relies on rank-1 updates to find the transfer
matrix X such that ``X * diag(poles) = (A - B*K)*X``, whereas YT uses
rank-2 updates. This yields on average more robust solutions (see [2]_
pp 21-22), furthermore the YT algorithm supports complex poles whereas KNV
does not in its original version. Only update method 0 proposed by KNV has
been implemented here, hence the name ``'KNV0'``.
KNV extended to complex poles is used in Matlab's ``place`` function, YT is
distributed under a non-free licence by Slicot under the name ``robpole``.
It is unclear and undocumented how KNV0 has been extended to complex poles
(Tits and Yang claim on page 14 of their paper that their method can not be
used to extend KNV to complex poles), therefore only YT supports them in
this implementation.
As the solution to the problem of pole placement is not unique for MIMO
systems, both methods start with a tentative transfer matrix which is
altered in various way to increase its determinant. Both methods have been
proven to converge to a stable solution, however depending on the way the
initial transfer matrix is chosen they will converge to different
solutions and therefore there is absolutely no guarantee that using
``'KNV0'`` will yield results similar to Matlab's or any other
implementation of these algorithms.
Using the default method ``'YT'`` should be fine in most cases; ``'KNV0'``
is only provided because it is needed by ``'YT'`` in some specific cases.
Furthermore ``'YT'`` gives on average more robust results than ``'KNV0'``
when ``abs(det(X))`` is used as a robustness indicator.
[2]_ is available as a technical report on the following URL:
https://hdl.handle.net/1903/5598
References
----------
.. [1] J. Kautsky, N.K. Nichols and P. van Dooren, "Robust pole assignment
in linear state feedback", International Journal of Control, Vol. 41
pp. 1129-1155, 1985.
.. [2] A.L. Tits and Y. Yang, "Globally convergent algorithms for robust
pole assignment by state feedback, IEEE Transactions on Automatic
Control, Vol. 41, pp. 1432-1452, 1996.
Examples
--------
A simple example demonstrating real pole placement using both KNV and YT
algorithms. This is example number 1 from section 4 of the reference KNV
publication ([1]_):
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> A = np.array([[ 1.380, -0.2077, 6.715, -5.676 ],
... [-0.5814, -4.290, 0, 0.6750 ],
... [ 1.067, 4.273, -6.654, 5.893 ],
... [ 0.0480, 4.273, 1.343, -2.104 ]])
>>> B = np.array([[ 0, 5.679 ],
... [ 1.136, 1.136 ],
... [ 0, 0, ],
... [-3.146, 0 ]])
>>> P = np.array([-0.2, -0.5, -5.0566, -8.6659])
Now compute K with KNV method 0, with the default YT method and with the YT
method while forcing 100 iterations of the algorithm and print some results
after each call.
>>> fsf1 = signal.place_poles(A, B, P, method='KNV0')
>>> fsf1.gain_matrix
array([[ 0.20071427, -0.96665799, 0.24066128, -0.10279785],
[ 0.50587268, 0.57779091, 0.51795763, -0.41991442]])
>>> fsf2 = signal.place_poles(A, B, P) # uses YT method
>>> fsf2.computed_poles
array([-8.6659, -5.0566, -0.5 , -0.2 ])
>>> fsf3 = signal.place_poles(A, B, P, rtol=-1, maxiter=100)
>>> fsf3.X
array([[ 0.52072442+0.j, -0.08409372+0.j, -0.56847937+0.j, 0.74823657+0.j],
[-0.04977751+0.j, -0.80872954+0.j, 0.13566234+0.j, -0.29322906+0.j],
[-0.82266932+0.j, -0.19168026+0.j, -0.56348322+0.j, -0.43815060+0.j],
[ 0.22267347+0.j, 0.54967577+0.j, -0.58387806+0.j, -0.40271926+0.j]])
The absolute value of the determinant of X is a good indicator to check the
robustness of the results, both ``'KNV0'`` and ``'YT'`` aim at maximizing
it. Below a comparison of the robustness of the results above:
>>> abs(np.linalg.det(fsf1.X)) < abs(np.linalg.det(fsf2.X))
True
>>> abs(np.linalg.det(fsf2.X)) < abs(np.linalg.det(fsf3.X))
True
Now a simple example for complex poles:
>>> A = np.array([[ 0, 7/3., 0, 0 ],
... [ 0, 0, 0, 7/9. ],
... [ 0, 0, 0, 0 ],
... [ 0, 0, 0, 0 ]])
>>> B = np.array([[ 0, 0 ],
... [ 0, 0 ],
... [ 1, 0 ],
... [ 0, 1 ]])
>>> P = np.array([-3, -1, -2-1j, -2+1j]) / 3.
>>> fsf = signal.place_poles(A, B, P, method='YT')
We can plot the desired and computed poles in the complex plane:
>>> t = np.linspace(0, 2*np.pi, 401)
>>> plt.plot(np.cos(t), np.sin(t), 'k--') # unit circle
>>> plt.plot(fsf.requested_poles.real, fsf.requested_poles.imag,
... 'wo', label='Desired')
>>> plt.plot(fsf.computed_poles.real, fsf.computed_poles.imag, 'bx',
... label='Placed')
>>> plt.grid()
>>> plt.axis('image')
>>> plt.axis([-1.1, 1.1, -1.1, 1.1])
>>> plt.legend(bbox_to_anchor=(1.05, 1), loc=2, numpoints=1)
"""
# Move away all the inputs checking, it only adds noise to the code
update_loop, poles = _valid_inputs(A, B, poles, method, rtol, maxiter)
# The current value of the relative tolerance we achieved
cur_rtol = 0
# The number of iterations needed before converging
nb_iter = 0
# Step A: QR decomposition of B page 1132 KN
# to debug with numpy qr uncomment the line below
# u, z = np.linalg.qr(B, mode="complete")
u, z = s_qr(B, mode="full")
rankB = np.linalg.matrix_rank(B)
u0 = u[:, :rankB]
u1 = u[:, rankB:]
z = z[:rankB, :]
# If we can use the identity matrix as X the solution is obvious
if B.shape[0] == rankB:
# if B is square and full rank there is only one solution
# such as (A+BK)=inv(X)*diag(P)*X with X=eye(A.shape[0])
# i.e K=inv(B)*(diag(P)-A)
# if B has as many lines as its rank (but not square) there are many
# solutions and we can choose one using least squares
# => use lstsq in both cases.
# In both cases the transfer matrix X will be eye(A.shape[0]) and I
# can hardly think of a better one so there is nothing to optimize
#
# for complex poles we use the following trick
#
# |a -b| has for eigenvalues a+b and a-b
# |b a|
#
# |a+bi 0| has the obvious eigenvalues a+bi and a-bi
# |0 a-bi|
#
# e.g solving the first one in R gives the solution
# for the second one in C
diag_poles = np.zeros(A.shape)
idx = 0
while idx < poles.shape[0]:
p = poles[idx]
diag_poles[idx, idx] = np.real(p)
if ~np.isreal(p):
diag_poles[idx, idx+1] = -np.imag(p)
diag_poles[idx+1, idx+1] = np.real(p)
diag_poles[idx+1, idx] = np.imag(p)
idx += 1 # skip next one
idx += 1
gain_matrix = np.linalg.lstsq(B, diag_poles-A, rcond=-1)[0]
transfer_matrix = np.eye(A.shape[0])
cur_rtol = np.nan
nb_iter = np.nan
else:
# step A (p1144 KNV) and beginning of step F: decompose
# dot(U1.T, A-P[i]*I).T and build our set of transfer_matrix vectors
# in the same loop
ker_pole = []
# flag to skip the conjugate of a complex pole
skip_conjugate = False
# select orthonormal base ker_pole for each Pole and vectors for
# transfer_matrix
for j in range(B.shape[0]):
if skip_conjugate:
skip_conjugate = False
continue
pole_space_j = np.dot(u1.T, A-poles[j]*np.eye(B.shape[0])).T
# after QR Q=Q0|Q1
# only Q0 is used to reconstruct the qr'ed (dot Q, R) matrix.
# Q1 is orthogonnal to Q0 and will be multiplied by the zeros in
# R when using mode "complete". In default mode Q1 and the zeros
# in R are not computed
# To debug with numpy qr uncomment the line below
# Q, _ = np.linalg.qr(pole_space_j, mode="complete")
Q, _ = s_qr(pole_space_j, mode="full")
ker_pole_j = Q[:, pole_space_j.shape[1]:]
# We want to select one vector in ker_pole_j to build the transfer
# matrix, however qr returns sometimes vectors with zeros on the
# same line for each pole and this yields very long convergence
# times.
# Or some other times a set of vectors, one with zero imaginary
# part and one (or several) with imaginary parts. After trying
# many ways to select the best possible one (eg ditch vectors
# with zero imaginary part for complex poles) I ended up summing
# all vectors in ker_pole_j, this solves 100% of the problems and
# is a valid choice for transfer_matrix.
# This way for complex poles we are sure to have a non zero
# imaginary part that way, and the problem of lines full of zeros
# in transfer_matrix is solved too as when a vector from
# ker_pole_j has a zero the other one(s) when
# ker_pole_j.shape[1]>1) for sure won't have a zero there.
transfer_matrix_j = np.sum(ker_pole_j, axis=1)[:, np.newaxis]
transfer_matrix_j = (transfer_matrix_j /
np.linalg.norm(transfer_matrix_j))
if ~np.isreal(poles[j]): # complex pole
transfer_matrix_j = np.hstack([np.real(transfer_matrix_j),
np.imag(transfer_matrix_j)])
ker_pole.extend([ker_pole_j, ker_pole_j])
# Skip next pole as it is the conjugate
skip_conjugate = True
else: # real pole, nothing to do
ker_pole.append(ker_pole_j)
if j == 0:
transfer_matrix = transfer_matrix_j
else:
transfer_matrix = np.hstack((transfer_matrix, transfer_matrix_j))
if rankB > 1: # otherwise there is nothing we can optimize
stop, cur_rtol, nb_iter = update_loop(ker_pole, transfer_matrix,
poles, B, maxiter, rtol)
if not stop and rtol > 0:
# if rtol<=0 the user has probably done that on purpose,
# don't annoy him
err_msg = (
"Convergence was not reached after maxiter iterations.\n"
"You asked for a relative tolerance of %f we got %f" %
(rtol, cur_rtol)
)
warnings.warn(err_msg)
# reconstruct transfer_matrix to match complex conjugate pairs,
# ie transfer_matrix_j/transfer_matrix_j+1 are
# Re(Complex_pole), Im(Complex_pole) now and will be Re-Im/Re+Im after
transfer_matrix = transfer_matrix.astype(complex)
idx = 0
while idx < poles.shape[0]-1:
if ~np.isreal(poles[idx]):
rel = transfer_matrix[:, idx].copy()
img = transfer_matrix[:, idx+1]
# rel will be an array referencing a column of transfer_matrix
# if we don't copy() it will changer after the next line and
# and the line after will not yield the correct value
transfer_matrix[:, idx] = rel-1j*img
transfer_matrix[:, idx+1] = rel+1j*img
idx += 1 # skip next one
idx += 1
try:
m = np.linalg.solve(transfer_matrix.T, np.dot(np.diag(poles),
transfer_matrix.T)).T
gain_matrix = np.linalg.solve(z, np.dot(u0.T, m-A))
except np.linalg.LinAlgError:
raise ValueError("The poles you've chosen can't be placed. "
"Check the controllability matrix and try "
"another set of poles")
# Beware: Kautsky solves A+BK but the usual form is A-BK
gain_matrix = -gain_matrix
# K still contains complex with ~=0j imaginary parts, get rid of them
gain_matrix = np.real(gain_matrix)
full_state_feedback = Bunch()
full_state_feedback.gain_matrix = gain_matrix
full_state_feedback.computed_poles = _order_complex_poles(
np.linalg.eig(A - np.dot(B, gain_matrix))[0]
)
full_state_feedback.requested_poles = poles
full_state_feedback.X = transfer_matrix
full_state_feedback.rtol = cur_rtol
full_state_feedback.nb_iter = nb_iter
return full_state_feedback | [
"def",
"place_poles",
"(",
"A",
",",
"B",
",",
"poles",
",",
"method",
"=",
"\"YT\"",
",",
"rtol",
"=",
"1e-3",
",",
"maxiter",
"=",
"30",
")",
":",
"# Move away all the inputs checking, it only adds noise to the code",
"update_loop",
",",
"poles",
"=",
"_valid_... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/ltisys.py#L2880-L3228 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/dis.py | python | dis | (x=None) | Disassemble classes, methods, functions, or code.
With no argument, disassemble the last traceback. | Disassemble classes, methods, functions, or code. | [
"Disassemble",
"classes",
"methods",
"functions",
"or",
"code",
"."
] | def dis(x=None):
"""Disassemble classes, methods, functions, or code.
With no argument, disassemble the last traceback.
"""
if x is None:
distb()
return
if isinstance(x, types.InstanceType):
x = x.__class__
if hasattr(x, 'im_func'):
x = x.im_func
if hasattr(x, 'func_code'):
x = x.func_code
if hasattr(x, '__dict__'):
items = x.__dict__.items()
items.sort()
for name, x1 in items:
if isinstance(x1, _have_code):
print "Disassembly of %s:" % name
try:
dis(x1)
except TypeError, msg:
print "Sorry:", msg
print
elif hasattr(x, 'co_code'):
disassemble(x)
elif isinstance(x, str):
disassemble_string(x)
else:
raise TypeError, \
"don't know how to disassemble %s objects" % \
type(x).__name__ | [
"def",
"dis",
"(",
"x",
"=",
"None",
")",
":",
"if",
"x",
"is",
"None",
":",
"distb",
"(",
")",
"return",
"if",
"isinstance",
"(",
"x",
",",
"types",
".",
"InstanceType",
")",
":",
"x",
"=",
"x",
".",
"__class__",
"if",
"hasattr",
"(",
"x",
","... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/dis.py#L16-L49 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py | python | GraphRewriter.add_eightbit_prologue_nodes | (self, original_node) | return all_input_names | Adds input conversion nodes to handle quantizing the underlying node. | Adds input conversion nodes to handle quantizing the underlying node. | [
"Adds",
"input",
"conversion",
"nodes",
"to",
"handle",
"quantizing",
"the",
"underlying",
"node",
"."
] | def add_eightbit_prologue_nodes(self, original_node):
"""Adds input conversion nodes to handle quantizing the underlying node."""
namespace_prefix = original_node.name + "_eightbit"
reshape_dims_name, reduction_dims_name = self.add_common_quantization_nodes(
namespace_prefix)
input_names = []
min_max_names = []
for original_input_name in original_node.input:
quantize_input_name, min_input_name, max_input_name = (
self.eightbitize_input_to_node(namespace_prefix, original_input_name,
reshape_dims_name,
reduction_dims_name))
input_names.append(quantize_input_name)
min_max_names.append(min_input_name)
min_max_names.append(max_input_name)
all_input_names = []
all_input_names.extend(input_names)
all_input_names.extend(min_max_names)
return all_input_names | [
"def",
"add_eightbit_prologue_nodes",
"(",
"self",
",",
"original_node",
")",
":",
"namespace_prefix",
"=",
"original_node",
".",
"name",
"+",
"\"_eightbit\"",
"reshape_dims_name",
",",
"reduction_dims_name",
"=",
"self",
".",
"add_common_quantization_nodes",
"(",
"name... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/quantization/tools/quantize_graph.py#L480-L498 | |
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | clang/tools/scan-build-py/libscanbuild/analyze.py | python | report_failure | (opts) | Create report when analyzer failed.
The major report is the preprocessor output. The output filename generated
randomly. The compiler output also captured into '.stderr.txt' file.
And some more execution context also saved into '.info.txt' file. | Create report when analyzer failed. | [
"Create",
"report",
"when",
"analyzer",
"failed",
"."
] | def report_failure(opts):
""" Create report when analyzer failed.
The major report is the preprocessor output. The output filename generated
randomly. The compiler output also captured into '.stderr.txt' file.
And some more execution context also saved into '.info.txt' file. """
def extension():
""" Generate preprocessor file extension. """
mapping = {'objective-c++': '.mii', 'objective-c': '.mi', 'c++': '.ii'}
return mapping.get(opts['language'], '.i')
def destination():
""" Creates failures directory if not exits yet. """
failures_dir = os.path.join(opts['output_dir'], 'failures')
if not os.path.isdir(failures_dir):
os.makedirs(failures_dir)
return failures_dir
# Classify error type: when Clang terminated by a signal it's a 'Crash'.
# (python subprocess Popen.returncode is negative when child terminated
# by signal.) Everything else is 'Other Error'.
error = 'crash' if opts['exit_code'] < 0 else 'other_error'
# Create preprocessor output file name. (This is blindly following the
# Perl implementation.)
(handle, name) = tempfile.mkstemp(suffix=extension(),
prefix='clang_' + error + '_',
dir=destination())
os.close(handle)
# Execute Clang again, but run the syntax check only.
cwd = opts['directory']
cmd = [opts['clang'], '-fsyntax-only', '-E'] + opts['flags'] + \
[opts['file'], '-o', name]
try:
cmd = get_arguments(cmd, cwd)
run_command(cmd, cwd=cwd)
except subprocess.CalledProcessError:
pass
except ClangErrorException:
pass
# write general information about the crash
with open(name + '.info.txt', 'w') as handle:
handle.write(opts['file'] + os.linesep)
handle.write(error.title().replace('_', ' ') + os.linesep)
handle.write(' '.join(cmd) + os.linesep)
handle.write(' '.join(os.uname()) + os.linesep)
handle.write(get_version(opts['clang']))
handle.close()
# write the captured output too
with open(name + '.stderr.txt', 'w') as handle:
handle.writelines(opts['error_output'])
handle.close() | [
"def",
"report_failure",
"(",
"opts",
")",
":",
"def",
"extension",
"(",
")",
":",
"\"\"\" Generate preprocessor file extension. \"\"\"",
"mapping",
"=",
"{",
"'objective-c++'",
":",
"'.mii'",
",",
"'objective-c'",
":",
"'.mi'",
",",
"'c++'",
":",
"'.ii'",
"}",
... | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/tools/scan-build-py/libscanbuild/analyze.py#L461-L514 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/debug/lib/debug_events_writer.py | python | DebugEventsWriter.WriteGraphExecutionTrace | (self, graph_execution_trace) | Write a GraphExecutionTrace proto with the writer.
Args:
graph_execution_trace: A GraphExecutionTrace proto, concerning the value
of an intermediate tensor or a list of intermediate tensors that are
computed during the graph's execution. | Write a GraphExecutionTrace proto with the writer. | [
"Write",
"a",
"GraphExecutionTrace",
"proto",
"with",
"the",
"writer",
"."
] | def WriteGraphExecutionTrace(self, graph_execution_trace):
"""Write a GraphExecutionTrace proto with the writer.
Args:
graph_execution_trace: A GraphExecutionTrace proto, concerning the value
of an intermediate tensor or a list of intermediate tensors that are
computed during the graph's execution.
"""
debug_event = debug_event_pb2.DebugEvent(
graph_execution_trace=graph_execution_trace)
self._EnsureTimestampAdded(debug_event)
_pywrap_debug_events_writer.WriteGraphExecutionTrace(
self._dump_root, debug_event) | [
"def",
"WriteGraphExecutionTrace",
"(",
"self",
",",
"graph_execution_trace",
")",
":",
"debug_event",
"=",
"debug_event_pb2",
".",
"DebugEvent",
"(",
"graph_execution_trace",
"=",
"graph_execution_trace",
")",
"self",
".",
"_EnsureTimestampAdded",
"(",
"debug_event",
"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/lib/debug_events_writer.py#L117-L129 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/propgrid.py | python | PGProperty.EnableCommonValue | (*args, **kwargs) | return _propgrid.PGProperty_EnableCommonValue(*args, **kwargs) | EnableCommonValue(self, bool enable=True) | EnableCommonValue(self, bool enable=True) | [
"EnableCommonValue",
"(",
"self",
"bool",
"enable",
"=",
"True",
")"
] | def EnableCommonValue(*args, **kwargs):
"""EnableCommonValue(self, bool enable=True)"""
return _propgrid.PGProperty_EnableCommonValue(*args, **kwargs) | [
"def",
"EnableCommonValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_EnableCommonValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L453-L455 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/inspect.py | python | formatargvalues | (args, varargs, varkw, locals,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
join=joinseq) | return '(' + string.join(specs, ', ') + ')' | Format an argument spec from the 4 values returned by getargvalues.
The first four arguments are (args, varargs, varkw, locals). The
next four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional function to format the sequence of arguments. | Format an argument spec from the 4 values returned by getargvalues. | [
"Format",
"an",
"argument",
"spec",
"from",
"the",
"4",
"values",
"returned",
"by",
"getargvalues",
"."
] | def formatargvalues(args, varargs, varkw, locals,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
join=joinseq):
"""Format an argument spec from the 4 values returned by getargvalues.
The first four arguments are (args, varargs, varkw, locals). The
next four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional function to format the sequence of arguments."""
def convert(name, locals=locals,
formatarg=formatarg, formatvalue=formatvalue):
return formatarg(name) + formatvalue(locals[name])
specs = []
for i in range(len(args)):
specs.append(strseq(args[i], convert, join))
if varargs:
specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
if varkw:
specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
return '(' + string.join(specs, ', ') + ')' | [
"def",
"formatargvalues",
"(",
"args",
",",
"varargs",
",",
"varkw",
",",
"locals",
",",
"formatarg",
"=",
"str",
",",
"formatvarargs",
"=",
"lambda",
"name",
":",
"'*'",
"+",
"name",
",",
"formatvarkw",
"=",
"lambda",
"name",
":",
"'**'",
"+",
"name",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/inspect.py#L870-L892 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/tornado/tornado-6/tornado/routing.py | python | RuleRouter.__init__ | (self, rules: Optional[_RuleList] = None) | Constructs a router from an ordered list of rules::
RuleRouter([
Rule(PathMatches("/handler"), Target),
# ... more rules
])
You can also omit explicit `Rule` constructor and use tuples of arguments::
RuleRouter([
(PathMatches("/handler"), Target),
])
`PathMatches` is a default matcher, so the example above can be simplified::
RuleRouter([
("/handler", Target),
])
In the examples above, ``Target`` can be a nested `Router` instance, an instance of
`~.httputil.HTTPServerConnectionDelegate` or an old-style callable,
accepting a request argument.
:arg rules: a list of `Rule` instances or tuples of `Rule`
constructor arguments. | Constructs a router from an ordered list of rules:: | [
"Constructs",
"a",
"router",
"from",
"an",
"ordered",
"list",
"of",
"rules",
"::"
] | def __init__(self, rules: Optional[_RuleList] = None) -> None:
"""Constructs a router from an ordered list of rules::
RuleRouter([
Rule(PathMatches("/handler"), Target),
# ... more rules
])
You can also omit explicit `Rule` constructor and use tuples of arguments::
RuleRouter([
(PathMatches("/handler"), Target),
])
`PathMatches` is a default matcher, so the example above can be simplified::
RuleRouter([
("/handler", Target),
])
In the examples above, ``Target`` can be a nested `Router` instance, an instance of
`~.httputil.HTTPServerConnectionDelegate` or an old-style callable,
accepting a request argument.
:arg rules: a list of `Rule` instances or tuples of `Rule`
constructor arguments.
"""
self.rules = [] # type: List[Rule]
if rules:
self.add_rules(rules) | [
"def",
"__init__",
"(",
"self",
",",
"rules",
":",
"Optional",
"[",
"_RuleList",
"]",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"rules",
"=",
"[",
"]",
"# type: List[Rule]",
"if",
"rules",
":",
"self",
".",
"add_rules",
"(",
"rules",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/routing.py#L303-L332 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/ast.py | python | NodeVisitor.visit | (self, node) | return visitor(node) | Visit a node. | Visit a node. | [
"Visit",
"a",
"node",
"."
] | def visit(self, node):
"""Visit a node."""
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node) | [
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"method",
"=",
"'visit_'",
"+",
"node",
".",
"__class__",
".",
"__name__",
"visitor",
"=",
"getattr",
"(",
"self",
",",
"method",
",",
"self",
".",
"generic_visit",
")",
"return",
"visitor",
"(",
"nod... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/ast.py#L227-L231 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/speedmeter.py | python | SpeedMeter.SetIntervals | (self, intervals=None) | Sets the intervals for :class:`SpeedMeter` (main ticks numeric values).
:param `intervals`: a Python list of main ticks to be displayed. If defaulted
to ``None``, the list `[0, 50, 100]` is used. | Sets the intervals for :class:`SpeedMeter` (main ticks numeric values). | [
"Sets",
"the",
"intervals",
"for",
":",
"class",
":",
"SpeedMeter",
"(",
"main",
"ticks",
"numeric",
"values",
")",
"."
] | def SetIntervals(self, intervals=None):
"""
Sets the intervals for :class:`SpeedMeter` (main ticks numeric values).
:param `intervals`: a Python list of main ticks to be displayed. If defaulted
to ``None``, the list `[0, 50, 100]` is used.
"""
if intervals is None:
intervals = [0, 50, 100]
self._intervals = intervals | [
"def",
"SetIntervals",
"(",
"self",
",",
"intervals",
"=",
"None",
")",
":",
"if",
"intervals",
"is",
"None",
":",
"intervals",
"=",
"[",
"0",
",",
"50",
",",
"100",
"]",
"self",
".",
"_intervals",
"=",
"intervals"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/speedmeter.py#L1132-L1143 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/algorithms/deep_cfr_tf2.py | python | DeepCFRSolver._learn_strategy_network | (self) | return main_loss | Compute the loss over the strategy network.
Returns:
The average loss obtained on the last training batch of transitions
or `None`. | Compute the loss over the strategy network. | [
"Compute",
"the",
"loss",
"over",
"the",
"strategy",
"network",
"."
] | def _learn_strategy_network(self):
"""Compute the loss over the strategy network.
Returns:
The average loss obtained on the last training batch of transitions
or `None`.
"""
@tf.function
def train_step(info_states, action_probs, iterations, masks):
model = self._policy_network
with tf.GradientTape() as tape:
preds = model((info_states, masks), training=True)
main_loss = self._loss_policy(
action_probs, preds, sample_weight=iterations * 2 / self._iteration)
loss = tf.add_n([main_loss], model.losses)
gradients = tape.gradient(loss, model.trainable_variables)
self._optimizer_policy.apply_gradients(
zip(gradients, model.trainable_variables))
return main_loss
with tf.device(self._train_device):
data = self._get_strategy_dataset()
for d in data.take(self._policy_network_train_steps):
main_loss = train_step(*d)
return main_loss | [
"def",
"_learn_strategy_network",
"(",
"self",
")",
":",
"@",
"tf",
".",
"function",
"def",
"train_step",
"(",
"info_states",
",",
"action_probs",
",",
"iterations",
",",
"masks",
")",
":",
"model",
"=",
"self",
".",
"_policy_network",
"with",
"tf",
".",
"... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/deep_cfr_tf2.py#L709-L735 | |
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | com/win32com/server/policy.py | python | BasicWrapPolicy._query_interface_ | (self, iid) | return 0 | Called if the object does not provide the requested interface in _com_interfaces_,
and does not provide a _query_interface_ handler.
Returns a result to the COM framework indicating the interface is not supported. | Called if the object does not provide the requested interface in _com_interfaces_,
and does not provide a _query_interface_ handler. | [
"Called",
"if",
"the",
"object",
"does",
"not",
"provide",
"the",
"requested",
"interface",
"in",
"_com_interfaces_",
"and",
"does",
"not",
"provide",
"a",
"_query_interface_",
"handler",
"."
] | def _query_interface_(self, iid):
"""Called if the object does not provide the requested interface in _com_interfaces_,
and does not provide a _query_interface_ handler.
Returns a result to the COM framework indicating the interface is not supported.
"""
return 0 | [
"def",
"_query_interface_",
"(",
"self",
",",
"iid",
")",
":",
"return",
"0"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32com/server/policy.py#L281-L287 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | HelpProvider.RemoveHelp | (*args, **kwargs) | return _controls_.HelpProvider_RemoveHelp(*args, **kwargs) | RemoveHelp(self, Window window)
Removes the association between the window pointer and the help
text. This is called by the wx.Window destructor. Without this, the
table of help strings will fill up and when window pointers are
reused, the wrong help string will be found. | RemoveHelp(self, Window window) | [
"RemoveHelp",
"(",
"self",
"Window",
"window",
")"
] | def RemoveHelp(*args, **kwargs):
"""
RemoveHelp(self, Window window)
Removes the association between the window pointer and the help
text. This is called by the wx.Window destructor. Without this, the
table of help strings will fill up and when window pointers are
reused, the wrong help string will be found.
"""
return _controls_.HelpProvider_RemoveHelp(*args, **kwargs) | [
"def",
"RemoveHelp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"HelpProvider_RemoveHelp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L6294-L6303 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py | python | convert_broadcast_mul | (node, **kwargs) | return create_basic_op_node('Mul', node, kwargs) | Map MXNet's broadcast_mul operator attributes to onnx's Mul operator
and return the created node. | Map MXNet's broadcast_mul operator attributes to onnx's Mul operator
and return the created node. | [
"Map",
"MXNet",
"s",
"broadcast_mul",
"operator",
"attributes",
"to",
"onnx",
"s",
"Mul",
"operator",
"and",
"return",
"the",
"created",
"node",
"."
] | def convert_broadcast_mul(node, **kwargs):
"""Map MXNet's broadcast_mul operator attributes to onnx's Mul operator
and return the created node.
"""
return create_basic_op_node('Mul', node, kwargs) | [
"def",
"convert_broadcast_mul",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"create_basic_op_node",
"(",
"'Mul'",
",",
"node",
",",
"kwargs",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py#L1687-L1691 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetCflagsC | (self, config) | return self._GetPchFlags(config, '.c') | Returns the flags that need to be added to .c compilations. | Returns the flags that need to be added to .c compilations. | [
"Returns",
"the",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
".",
"c",
"compilations",
"."
] | def GetCflagsC(self, config):
"""Returns the flags that need to be added to .c compilations."""
config = self._TargetConfig(config)
return self._GetPchFlags(config, '.c') | [
"def",
"GetCflagsC",
"(",
"self",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"return",
"self",
".",
"_GetPchFlags",
"(",
"config",
",",
"'.c'",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/msvs_emulation.py#L511-L514 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/global_notification.py | python | GlobalNotification.ttl | (self) | return self._ttl | Gets the ttl of this GlobalNotification. # noqa: E501
:return: The ttl of this GlobalNotification. # noqa: E501
:rtype: float | Gets the ttl of this GlobalNotification. # noqa: E501 | [
"Gets",
"the",
"ttl",
"of",
"this",
"GlobalNotification",
".",
"#",
"noqa",
":",
"E501"
] | def ttl(self):
"""Gets the ttl of this GlobalNotification. # noqa: E501
:return: The ttl of this GlobalNotification. # noqa: E501
:rtype: float
"""
return self._ttl | [
"def",
"ttl",
"(",
"self",
")",
":",
"return",
"self",
".",
"_ttl"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/global_notification.py#L182-L189 | |
twtygqyy/caffe-augmentation | c76600d247e5132fa5bd89d87bb5df458341fa84 | scripts/cpp_lint.py | python | _IncludeState.IsInAlphabeticalOrder | (self, clean_lines, linenum, header_path) | return True | Check if a header is in alphabetical order with the previous header.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
header_path: Canonicalized header to be checked.
Returns:
Returns true if the header is in alphabetical order. | Check if a header is in alphabetical order with the previous header. | [
"Check",
"if",
"a",
"header",
"is",
"in",
"alphabetical",
"order",
"with",
"the",
"previous",
"header",
"."
] | def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
"""Check if a header is in alphabetical order with the previous header.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
header_path: Canonicalized header to be checked.
Returns:
Returns true if the header is in alphabetical order.
"""
# If previous section is different from current section, _last_header will
# be reset to empty string, so it's always less than current header.
#
# If previous line was a blank line, assume that the headers are
# intentionally sorted the way they are.
if (self._last_header > header_path and
not Match(r'^\s*$', clean_lines.elided[linenum - 1])):
return False
return True | [
"def",
"IsInAlphabeticalOrder",
"(",
"self",
",",
"clean_lines",
",",
"linenum",
",",
"header_path",
")",
":",
"# If previous section is different from current section, _last_header will",
"# be reset to empty string, so it's always less than current header.",
"#",
"# If previous line ... | https://github.com/twtygqyy/caffe-augmentation/blob/c76600d247e5132fa5bd89d87bb5df458341fa84/scripts/cpp_lint.py#L616-L635 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/ext.py | python | Extension.preprocess | (self, source, name, filename=None) | return source | This method is called before the actual lexing and can be used to
preprocess the source. The `filename` is optional. The return value
must be the preprocessed source. | This method is called before the actual lexing and can be used to
preprocess the source. The `filename` is optional. The return value
must be the preprocessed source. | [
"This",
"method",
"is",
"called",
"before",
"the",
"actual",
"lexing",
"and",
"can",
"be",
"used",
"to",
"preprocess",
"the",
"source",
".",
"The",
"filename",
"is",
"optional",
".",
"The",
"return",
"value",
"must",
"be",
"the",
"preprocessed",
"source",
... | def preprocess(self, source, name, filename=None):
"""This method is called before the actual lexing and can be used to
preprocess the source. The `filename` is optional. The return value
must be the preprocessed source.
"""
return source | [
"def",
"preprocess",
"(",
"self",
",",
"source",
",",
"name",
",",
"filename",
"=",
"None",
")",
":",
"return",
"source"
] | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/ext.py#L80-L85 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/scripts/analyze_dxp.py | python | has_pairs | (profile) | return len(profile) > 0 and isinstance(profile[0], list) | Returns True if the Python that produced the argument profile
was built with -DDXPAIRS. | Returns True if the Python that produced the argument profile
was built with -DDXPAIRS. | [
"Returns",
"True",
"if",
"the",
"Python",
"that",
"produced",
"the",
"argument",
"profile",
"was",
"built",
"with",
"-",
"DDXPAIRS",
"."
] | def has_pairs(profile):
"""Returns True if the Python that produced the argument profile
was built with -DDXPAIRS."""
return len(profile) > 0 and isinstance(profile[0], list) | [
"def",
"has_pairs",
"(",
"profile",
")",
":",
"return",
"len",
"(",
"profile",
")",
">",
"0",
"and",
"isinstance",
"(",
"profile",
"[",
"0",
"]",
",",
"list",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/scripts/analyze_dxp.py#L39-L43 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Point2D.GetRounded | (*args, **kwargs) | return _core_.Point2D_GetRounded(*args, **kwargs) | GetRounded() -> (x,y)
Convert to integer | GetRounded() -> (x,y) | [
"GetRounded",
"()",
"-",
">",
"(",
"x",
"y",
")"
] | def GetRounded(*args, **kwargs):
"""
GetRounded() -> (x,y)
Convert to integer
"""
return _core_.Point2D_GetRounded(*args, **kwargs) | [
"def",
"GetRounded",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Point2D_GetRounded",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L1664-L1670 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/_pyio.py | python | IOBase.tell | (self) | return self.seek(0, 1) | Return current stream position. | Return current stream position. | [
"Return",
"current",
"stream",
"position",
"."
] | def tell(self):
"""Return current stream position."""
return self.seek(0, 1) | [
"def",
"tell",
"(",
"self",
")",
":",
"return",
"self",
".",
"seek",
"(",
"0",
",",
"1",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/_pyio.py#L322-L324 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/summary/summary_iterator.py | python | SummaryWriter.close | (self) | Flushes the event file to disk and close the file.
Call this method when you do not need the summary writer anymore. | Flushes the event file to disk and close the file. | [
"Flushes",
"the",
"event",
"file",
"to",
"disk",
"and",
"close",
"the",
"file",
"."
] | def close(self):
"""Flushes the event file to disk and close the file.
Call this method when you do not need the summary writer anymore.
"""
self.flush()
self._ev_writer.Close()
self._closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"flush",
"(",
")",
"self",
".",
"_ev_writer",
".",
"Close",
"(",
")",
"self",
".",
"_closed",
"=",
"True"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/summary/summary_iterator.py#L279-L286 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/geographic_msgs/msg/_KeyValue.py | python | KeyValue.serialize | (self, buff) | serialize message into buffer
:param buff: buffer, ``StringIO`` | serialize message into buffer
:param buff: buffer, ``StringIO`` | [
"serialize",
"message",
"into",
"buffer",
":",
"param",
"buff",
":",
"buffer",
"StringIO"
] | def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self.key
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = self.value
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x)))) | [
"def",
"serialize",
"(",
"self",
",",
"buff",
")",
":",
"try",
":",
"_x",
"=",
"self",
".",
"key",
"length",
"=",
"len",
"(",
"_x",
")",
"if",
"python3",
"or",
"type",
"(",
"_x",
")",
"==",
"unicode",
":",
"_x",
"=",
"_x",
".",
"encode",
"(",
... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/geographic_msgs/msg/_KeyValue.py#L56-L81 | ||
TheImagingSource/tiscamera | baacb4cfaa7858c2e6cfb4f1a297b404c4e002f6 | tools/tcam-capture/tcam_capture/TcamView.py | python | TcamView.fire_device_lost | (self) | Notify all callback that our device is gone | Notify all callback that our device is gone | [
"Notify",
"all",
"callback",
"that",
"our",
"device",
"is",
"gone"
] | def fire_device_lost(self):
"""
Notify all callback that our device is gone
"""
for cb in self.device_lost_callbacks:
cb() | [
"def",
"fire_device_lost",
"(",
"self",
")",
":",
"for",
"cb",
"in",
"self",
".",
"device_lost_callbacks",
":",
"cb",
"(",
")"
] | https://github.com/TheImagingSource/tiscamera/blob/baacb4cfaa7858c2e6cfb4f1a297b404c4e002f6/tools/tcam-capture/tcam_capture/TcamView.py#L519-L524 | ||
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | thirdparty/gflags/gflags.py | python | FlagValues.__RenderOurModuleKeyFlags | (self, module, output_lines, prefix="") | Generates a help string for the key flags of a given module.
Args:
module: A module object or a module name (a string).
output_lines: A list of strings. The generated help message
lines will be appended to this list.
prefix: A string that is prepended to each generated help line. | Generates a help string for the key flags of a given module. | [
"Generates",
"a",
"help",
"string",
"for",
"the",
"key",
"flags",
"of",
"a",
"given",
"module",
"."
] | def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""):
"""Generates a help string for the key flags of a given module.
Args:
module: A module object or a module name (a string).
output_lines: A list of strings. The generated help message
lines will be appended to this list.
prefix: A string that is prepended to each generated help line.
"""
key_flags = self._GetKeyFlagsForModule(module)
if key_flags:
self.__RenderModuleFlags(module, key_flags, output_lines, prefix) | [
"def",
"__RenderOurModuleKeyFlags",
"(",
"self",
",",
"module",
",",
"output_lines",
",",
"prefix",
"=",
"\"\"",
")",
":",
"key_flags",
"=",
"self",
".",
"_GetKeyFlagsForModule",
"(",
"module",
")",
"if",
"key_flags",
":",
"self",
".",
"__RenderModuleFlags",
"... | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/thirdparty/gflags/gflags.py#L1335-L1346 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/runpy.py | python | _run_code | (code, run_globals, init_globals=None,
mod_name=None, mod_fname=None,
mod_loader=None, pkg_name=None) | return run_globals | Helper for _run_module_code | Helper for _run_module_code | [
"Helper",
"for",
"_run_module_code"
] | def _run_code(code, run_globals, init_globals=None,
mod_name=None, mod_fname=None,
mod_loader=None, pkg_name=None):
"""Helper for _run_module_code"""
if init_globals is not None:
run_globals.update(init_globals)
run_globals.update(__name__ = mod_name,
__file__ = mod_fname,
__loader__ = mod_loader,
__package__ = pkg_name)
exec code in run_globals
return run_globals | [
"def",
"_run_code",
"(",
"code",
",",
"run_globals",
",",
"init_globals",
"=",
"None",
",",
"mod_name",
"=",
"None",
",",
"mod_fname",
"=",
"None",
",",
"mod_loader",
"=",
"None",
",",
"pkg_name",
"=",
"None",
")",
":",
"if",
"init_globals",
"is",
"not",... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/runpy.py#L24-L35 | |
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | third_party/WebIDL.py | python | Parser.p_TypeSuffixStartingWithArrayEmpty | (self, p) | TypeSuffixStartingWithArray : | TypeSuffixStartingWithArray : | [
"TypeSuffixStartingWithArray",
":"
] | def p_TypeSuffixStartingWithArrayEmpty(self, p):
"""
TypeSuffixStartingWithArray :
"""
p[0] = [] | [
"def",
"p_TypeSuffixStartingWithArrayEmpty",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"]"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/WebIDL.py#L4816-L4820 | ||
sc0ty/subsync | be5390d00ff475b6543eb0140c7e65b34317d95b | subsync/assets/assetlist.py | python | AssetList.hasUpdate | (self) | return AssetList([ a for a in self if a.hasUpdate() ]) | Get assets that could be updated (as new `AssetList`).
These assets are available on asset server and are not installed locally
or remote version are newer than local (based on version number). | Get assets that could be updated (as new `AssetList`). | [
"Get",
"assets",
"that",
"could",
"be",
"updated",
"(",
"as",
"new",
"AssetList",
")",
"."
] | def hasUpdate(self):
"""Get assets that could be updated (as new `AssetList`).
These assets are available on asset server and are not installed locally
or remote version are newer than local (based on version number).
"""
return AssetList([ a for a in self if a.hasUpdate() ]) | [
"def",
"hasUpdate",
"(",
"self",
")",
":",
"return",
"AssetList",
"(",
"[",
"a",
"for",
"a",
"in",
"self",
"if",
"a",
".",
"hasUpdate",
"(",
")",
"]",
")"
] | https://github.com/sc0ty/subsync/blob/be5390d00ff475b6543eb0140c7e65b34317d95b/subsync/assets/assetlist.py#L20-L26 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TInt.IsEven | (*args) | return _snap.TInt_IsEven(*args) | IsEven(int const & Int) -> bool
Parameters:
Int: int const & | IsEven(int const & Int) -> bool | [
"IsEven",
"(",
"int",
"const",
"&",
"Int",
")",
"-",
">",
"bool"
] | def IsEven(*args):
"""
IsEven(int const & Int) -> bool
Parameters:
Int: int const &
"""
return _snap.TInt_IsEven(*args) | [
"def",
"IsEven",
"(",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TInt_IsEven",
"(",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L13143-L13151 | |
zhaoweicai/hwgq | ebc706bee3e2d145de1da4be446ce8de8740738f | python/caffe/pycaffe.py | python | _Net_backward | (self, diffs=None, start=None, end=None, **kwargs) | return {out: self.blobs[out].diff for out in outputs} | Backward pass: prepare diffs and run the net backward.
Parameters
----------
diffs : list of diffs to return in addition to bottom diffs.
kwargs : Keys are output blob names and values are diff ndarrays.
If None, top diffs are taken from forward loss.
start : optional name of layer at which to begin the backward pass
end : optional name of layer at which to finish the backward pass
(inclusive)
Returns
-------
outs: {blob name: diff ndarray} dict. | Backward pass: prepare diffs and run the net backward. | [
"Backward",
"pass",
":",
"prepare",
"diffs",
"and",
"run",
"the",
"net",
"backward",
"."
] | def _Net_backward(self, diffs=None, start=None, end=None, **kwargs):
"""
Backward pass: prepare diffs and run the net backward.
Parameters
----------
diffs : list of diffs to return in addition to bottom diffs.
kwargs : Keys are output blob names and values are diff ndarrays.
If None, top diffs are taken from forward loss.
start : optional name of layer at which to begin the backward pass
end : optional name of layer at which to finish the backward pass
(inclusive)
Returns
-------
outs: {blob name: diff ndarray} dict.
"""
if diffs is None:
diffs = []
if start is not None:
start_ind = list(self._layer_names).index(start)
else:
start_ind = len(self.layers) - 1
if end is not None:
end_ind = list(self._layer_names).index(end)
outputs = set([end] + diffs)
else:
end_ind = 0
outputs = set(self.inputs + diffs)
if kwargs:
if set(kwargs.keys()) != set(self.outputs):
raise Exception('Top diff arguments do not match net outputs.')
# Set top diffs according to defined shapes and make arrays single and
# C-contiguous as Caffe expects.
for top, diff in six.iteritems(kwargs):
if diff.shape[0] != self.blobs[top].shape[0]:
raise Exception('Diff is not batch sized')
self.blobs[top].diff[...] = diff
self._backward(start_ind, end_ind)
# Unpack diffs to extract
return {out: self.blobs[out].diff for out in outputs} | [
"def",
"_Net_backward",
"(",
"self",
",",
"diffs",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"diffs",
"is",
"None",
":",
"diffs",
"=",
"[",
"]",
"if",
"start",
"is",
"not",
"None",
... | https://github.com/zhaoweicai/hwgq/blob/ebc706bee3e2d145de1da4be446ce8de8740738f/python/caffe/pycaffe.py#L127-L172 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/glcanvas.py | python | GLCanvas.SwapBuffers | (*args, **kwargs) | return _glcanvas.GLCanvas_SwapBuffers(*args, **kwargs) | SwapBuffers(self) -> bool | SwapBuffers(self) -> bool | [
"SwapBuffers",
"(",
"self",
")",
"-",
">",
"bool"
] | def SwapBuffers(*args, **kwargs):
"""SwapBuffers(self) -> bool"""
return _glcanvas.GLCanvas_SwapBuffers(*args, **kwargs) | [
"def",
"SwapBuffers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_glcanvas",
".",
"GLCanvas_SwapBuffers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/glcanvas.py#L122-L124 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/engine/validators.py | python | check_to_device_send | (method) | return new_method | Check the input arguments of send function for TransferDataset. | Check the input arguments of send function for TransferDataset. | [
"Check",
"the",
"input",
"arguments",
"of",
"send",
"function",
"for",
"TransferDataset",
"."
] | def check_to_device_send(method):
"""Check the input arguments of send function for TransferDataset."""
@wraps(method)
def new_method(self, *args, **kwargs):
[num_epochs], _ = parse_user_args(method, *args, **kwargs)
if num_epochs is not None:
type_check(num_epochs, (int,), "num_epochs")
check_value(num_epochs, [-1, INT32_MAX], "num_epochs")
return method(self, *args, **kwargs)
return new_method | [
"def",
"check_to_device_send",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"new_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"[",
"num_epochs",
"]",
",",
"_",
"=",
"parse_user_args",
"(",
"method",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/validators.py#L1856-L1869 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/contrib/onnx/onnx2mx/_op_translations.py | python | greater | (attrs, inputs, proto_obj) | return 'broadcast_greater', attrs, inputs | Logical Greater operator with broadcasting. | Logical Greater operator with broadcasting. | [
"Logical",
"Greater",
"operator",
"with",
"broadcasting",
"."
] | def greater(attrs, inputs, proto_obj):
"""Logical Greater operator with broadcasting."""
return 'broadcast_greater', attrs, inputs | [
"def",
"greater",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"return",
"'broadcast_greater'",
",",
"attrs",
",",
"inputs"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L196-L198 | |
neopenx/Dragon | 0e639a7319035ddc81918bd3df059230436ee0a1 | Dragon/python/dragon/operators/activation.py | python | LRelu | (inputs, slope=0.2, **kwargs) | return output | Leaky Rectified Linear Unit function.
Parameters
----------
inputs : Tensor
The input tensor.
slope : float
The slope of negative side.
Returns
-------
Tensor
The output tensor, calculated as: |lrelu_function|. | Leaky Rectified Linear Unit function. | [
"Leaky",
"Rectified",
"Linear",
"Unit",
"function",
"."
] | def LRelu(inputs, slope=0.2, **kwargs):
"""Leaky Rectified Linear Unit function.
Parameters
----------
inputs : Tensor
The input tensor.
slope : float
The slope of negative side.
Returns
-------
Tensor
The output tensor, calculated as: |lrelu_function|.
"""
CheckInputs(inputs, 1)
arguments = ParseArguments(locals())
output = Tensor.CreateOperator(nout=1, op_type='Relu', **arguments)
if inputs.shape is not None:
output.shape = inputs.shape[:]
return output | [
"def",
"LRelu",
"(",
"inputs",
",",
"slope",
"=",
"0.2",
",",
"*",
"*",
"kwargs",
")",
":",
"CheckInputs",
"(",
"inputs",
",",
"1",
")",
"arguments",
"=",
"ParseArguments",
"(",
"locals",
"(",
")",
")",
"output",
"=",
"Tensor",
".",
"CreateOperator",
... | https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/operators/activation.py#L39-L63 | |
ucbrise/clipper | 9f25e3fc7f8edc891615e81c5b80d3d8aed72608 | clipper_admin/clipper_admin/clipper_admin.py | python | ClipperConnection.unlink_model_from_app | (self, app_name, model_name) | Prevents the model with `model_name` from being used by the app with `app_name`.
The model and app should both be registered with Clipper and a link should
already exist between them.
Parameters
----------
app_name : str
The name of the application
model_name : str
The name of the model to link to the application
Raises
------
:py:exc:`clipper.UnconnectedException`
:py:exc:`clipper.ClipperException` | Prevents the model with `model_name` from being used by the app with `app_name`.
The model and app should both be registered with Clipper and a link should
already exist between them. | [
"Prevents",
"the",
"model",
"with",
"model_name",
"from",
"being",
"used",
"by",
"the",
"app",
"with",
"app_name",
".",
"The",
"model",
"and",
"app",
"should",
"both",
"be",
"registered",
"with",
"Clipper",
"and",
"a",
"link",
"should",
"already",
"exist",
... | def unlink_model_from_app(self, app_name, model_name):
"""
Prevents the model with `model_name` from being used by the app with `app_name`.
The model and app should both be registered with Clipper and a link should
already exist between them.
Parameters
----------
app_name : str
The name of the application
model_name : str
The name of the model to link to the application
Raises
------
:py:exc:`clipper.UnconnectedException`
:py:exc:`clipper.ClipperException`
"""
if not self.connected:
raise UnconnectedException()
url = "http://{host}/admin/delete_model_links".format(
host=self.cm.get_admin_addr())
req_json = json.dumps({
"app_name": app_name,
"model_names": [model_name]
})
headers = {'Content-type': 'application/json'}
r = requests.post(url, headers=headers, data=req_json)
logger.debug(r.text)
if r.status_code != requests.codes.ok:
msg = "Received error status code: {code} and message: {msg}".format(
code=r.status_code, msg=r.text)
logger.error(msg)
raise ClipperException(msg)
else:
logger.info(
"Model {model} is now removed to application {app}".format(
model=model_name, app=app_name)) | [
"def",
"unlink_model_from_app",
"(",
"self",
",",
"app_name",
",",
"model_name",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"UnconnectedException",
"(",
")",
"url",
"=",
"\"http://{host}/admin/delete_model_links\"",
".",
"format",
"(",
"host",
... | https://github.com/ucbrise/clipper/blob/9f25e3fc7f8edc891615e81c5b80d3d8aed72608/clipper_admin/clipper_admin/clipper_admin.py#L305-L344 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Point2D.GetVectorAngle | (*args, **kwargs) | return _core_.Point2D_GetVectorAngle(*args, **kwargs) | GetVectorAngle(self) -> double | GetVectorAngle(self) -> double | [
"GetVectorAngle",
"(",
"self",
")",
"-",
">",
"double"
] | def GetVectorAngle(*args, **kwargs):
"""GetVectorAngle(self) -> double"""
return _core_.Point2D_GetVectorAngle(*args, **kwargs) | [
"def",
"GetVectorAngle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Point2D_GetVectorAngle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L1676-L1678 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Utilities/Sphinx/sphinx_apidoc.py | python | create_modules_toc_file | (modules, opts, name='modules') | Create the module's index. | Create the module's index. | [
"Create",
"the",
"module",
"s",
"index",
"."
] | def create_modules_toc_file(modules, opts, name='modules'):
"""Create the module's index."""
text = format_heading(1, '%s' % opts.header)
text += '.. toctree::\n'
text += ' :maxdepth: %s\n\n' % opts.maxdepth
modules.sort()
prev_module = ''
for module in modules:
# look if the module is a subpackage and, if yes, ignore it
if module.startswith(prev_module + '.'):
continue
prev_module = module
text += ' %s\n' % module
write_file(name, text, opts) | [
"def",
"create_modules_toc_file",
"(",
"modules",
",",
"opts",
",",
"name",
"=",
"'modules'",
")",
":",
"text",
"=",
"format_heading",
"(",
"1",
",",
"'%s'",
"%",
"opts",
".",
"header",
")",
"text",
"+=",
"'.. toctree::\\n'",
"text",
"+=",
"' :maxdepth: %s... | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Utilities/Sphinx/sphinx_apidoc.py#L241-L256 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge2.py | python | ExodusModel._merge_node_groups | (self, node_groups, suppress_warnings=False) | Merge nodes in the given node groups.
This updates node field and node set field values with the average of
the values at the merged nodes. If they differ, a warning is output in
addition.
Node sets and node set fields are updated accordingly.
Example:
>>> model._merge_node_groups({1: [2, 3], 5: [7, 8]}) | Merge nodes in the given node groups. | [
"Merge",
"nodes",
"in",
"the",
"given",
"node",
"groups",
"."
] | def _merge_node_groups(self, node_groups, suppress_warnings=False):
"""
Merge nodes in the given node groups.
This updates node field and node set field values with the average of
the values at the merged nodes. If they differ, a warning is output in
addition.
Node sets and node set fields are updated accordingly.
Example:
>>> model._merge_node_groups({1: [2, 3], 5: [7, 8]})
"""
# ensure slave nodes are not duplicated
slave_nodes_set = set()
duplicated_slave_nodes = set()
for master, slaves in node_groups.items():
for slave in slaves:
if slave in slave_nodes_set:
duplicated_slave_nodes.add(slave)
else:
slave_nodes_set.add(slave)
if duplicated_slave_nodes:
problem_groups = dict()
for master, slaves in node_groups.items():
for index in slaves:
if index in duplicated_slave_nodes:
problem_groups[master] = slaves
groups = '\n '.join(str(x) + ': ' + str(y)
for x, y in problem_groups.items())
self._bug('Invalid merged node groups.',
'Slaves nodes were found in multiple merged groups. '
'Conflicting merged node groups:\n %s' % (groups))
# ensure validity of input
# slave nodes are not repeated
# master nodes are never slave nodes
master_nodes = sorted(node_groups.keys())
slave_nodes = sorted(list(itertools.chain(*node_groups.values())))
slave_nodes_set = set(slave_nodes)
# ensure master nodes are not slave nodes
for master in master_nodes:
if master in slave_nodes_set:
self._bug('Invalid merged node groups.',
'The master node %d is also found in a slave node '
'group.' % (master))
# ensure slave nodes are not in multiple groups
if not sorted(slave_nodes_set) == slave_nodes:
self._bug('Invalid merged node groups.',
'Slave nodes are duplicated in multiple groups.')
# First, remap all nodes such that slave nodes appear at the very
# end.
next_master_index = 0
first_slave_index = len(self.nodes) - len(slave_nodes)
next_slave_index = first_slave_index
node_map = []
index = 0
for slave_node in slave_nodes:
if slave_node != index:
count = slave_node - index
assert count > 0
node_map.extend(xrange(next_master_index,
next_master_index + count))
index += count
next_master_index += count
node_map.append(next_slave_index)
next_slave_index += 1
index += 1
count = first_slave_index - next_master_index
node_map.extend(xrange(next_master_index,
next_master_index + count))
next_master_index += count
assert next_master_index == first_slave_index
assert next_slave_index == len(self.nodes)
for master, slaves in node_groups.items():
assert node_map[master] < first_slave_index
assert min([node_map[x] for x in slaves]) >= first_slave_index
# apply this node map
self._apply_node_map(node_map)
# apply the mapping to node_groups
node_groups = dict((node_map[key], [node_map[x] for x in values])
for key, values in node_groups.items())
for master, slaves in node_groups.items():
assert master < first_slave_index
assert min(slaves) >= first_slave_index
# get connectivity mapping
connectivity_map = range(len(self.nodes))
for master, slaves in node_groups.items():
for slave in slaves:
connectivity_map[slave] = master
# change connectivity in element_blocks
for element_block_id in self.get_element_block_ids():
connectivity = self.get_connectivity(element_block_id)
connectivity[:] = [connectivity_map[x] for x in connectivity]
# change self.node_fields
node_field_value_warnings = 0
for name, all_values in self.node_fields.items():
for values in all_values:
for master, slaves in node_groups.items():
master_value = values[master]
slave_values = [values[x] for x in slaves]
if not self._values_match(master_value,
slave_values):
if (not node_field_value_warnings and
not suppress_warnings):
self._warning(
'Node field values do not match.',
'Nodes are being merged but values at these '
'nodes for node field "%s" do not match. An '
'averaged value will be used.\n'
'\n'
'Future warnings of this type will be '
'suppressed.' % (name))
node_field_value_warnings += 1
values[master] = (values[master] + sum(slave_values)
) / float(1 + len(slaves))
del values[first_slave_index:]
# change self.node_sets
node_set_member_warnings = 0
node_set_value_warnings = 0
for node_set_id in self.get_node_set_ids():
members = self.get_node_set_members(node_set_id)
fields = self._get_node_set_fields(node_set_id)
members_set = set(members)
member_indices_to_delete = []
for master, slaves in node_groups.items():
master_included = master in members_set
slaves_included = []
slaves_not_included = []
for slave in slaves:
if slave in members_set:
slaves_included.append(slave)
else:
slaves_not_included.append(slave)
if not master_included and not slaves_included:
continue
# warn if not all nodes are in the set
if not master_included or slaves_not_included:
if not node_set_member_warnings and not suppress_warnings:
self._warning(
'Ambiguous merge of nodes.',
'Node are being merged, but only some of these '
'nodes belong to a given node set. The operation '
'is therefore ambiguous on whether or not to '
'include the merged node in the set. The merged '
'node will be included in the set.\n\nFuture '
'warnings of this type will be suppressed.')
node_set_member_warnings += 1
# if master node is not included, steal the position of a
# slave node
if not master_included:
members[members.index(slaves_included[0])] = master
del slaves_included[0]
master_included = True
if not slaves_included:
continue
master_index = members.index(master)
slave_indices = [members.index(x) for x in slaves_included]
# mark slaves to delete
member_indices_to_delete.extend(slave_indices)
# average values, warn if they are not the same
for name, all_values in fields.items():
for values in all_values:
slave_values = [values[x] for x in slave_indices]
if not self._values_match(values[master_index],
slave_values):
if (not node_set_value_warnings and
not suppress_warnings):
self._warning(
'Node set field values do not match.',
'Nodes are being merged but values at '
'these nodes for node set field %s do '
'not match. An averaged values will '
'be used.\n\nFuture warnings of this '
'type will be suppressed.' % (name))
node_set_value_warnings += 1
new_value = (values[master_index] + sum(slave_values)
) / float(1 + len(slave_indices))
values[master_index] = new_value
# delete slave members
for index in sorted(member_indices_to_delete, reverse=True):
del members[index]
for all_values in fields.values():
for values in all_values:
del values[index]
# delete those nodes
del self.nodes[first_slave_index:] | [
"def",
"_merge_node_groups",
"(",
"self",
",",
"node_groups",
",",
"suppress_warnings",
"=",
"False",
")",
":",
"# ensure slave nodes are not duplicated",
"slave_nodes_set",
"=",
"set",
"(",
")",
"duplicated_slave_nodes",
"=",
"set",
"(",
")",
"for",
"master",
",",
... | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge2.py#L7003-L7189 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | cmake/tribits/doc/sphinx/sphinx_rst_generator.py | python | SphinxRstGenerator.save_rst | (file_path: str, file_content: str) | Saves .rst file with given pathh and content | Saves .rst file with given pathh and content | [
"Saves",
".",
"rst",
"file",
"with",
"given",
"pathh",
"and",
"content"
] | def save_rst(file_path: str, file_content: str) -> None:
""" Saves .rst file with given pathh and content
"""
with open(file_path, 'w') as dest_file:
dest_file.write(file_content) | [
"def",
"save_rst",
"(",
"file_path",
":",
"str",
",",
"file_content",
":",
"str",
")",
"->",
"None",
":",
"with",
"open",
"(",
"file_path",
",",
"'w'",
")",
"as",
"dest_file",
":",
"dest_file",
".",
"write",
"(",
"file_content",
")"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/cmake/tribits/doc/sphinx/sphinx_rst_generator.py#L161-L165 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/idl/idl/generator.py | python | _CppSourceFileWriter.gen_string_constants_definitions | (self, struct) | Generate a StringData constant for field name in the cpp file. | Generate a StringData constant for field name in the cpp file. | [
"Generate",
"a",
"StringData",
"constant",
"for",
"field",
"name",
"in",
"the",
"cpp",
"file",
"."
] | def gen_string_constants_definitions(self, struct):
# type: (ast.Struct) -> None
# pylint: disable=invalid-name
"""Generate a StringData constant for field name in the cpp file."""
# Generate a sorted list of string constants
sorted_fields = sorted([field for field in struct.fields], key=lambda f: f.cpp_name)
for field in sorted_fields:
self._writer.write_line(
common.template_args(
'constexpr StringData ${class_name}::${constant_name};',
class_name=common.title_case(struct.name),
constant_name=_get_field_constant_name(field)))
if isinstance(struct, ast.Command):
self._writer.write_line(
common.template_args(
'constexpr StringData ${class_name}::kCommandName;',
class_name=common.title_case(struct.name))) | [
"def",
"gen_string_constants_definitions",
"(",
"self",
",",
"struct",
")",
":",
"# type: (ast.Struct) -> None",
"# pylint: disable=invalid-name",
"# Generate a sorted list of string constants",
"sorted_fields",
"=",
"sorted",
"(",
"[",
"field",
"for",
"field",
"in",
"struct"... | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/generator.py#L1334-L1354 | ||
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/decoder.py | python | _EndGroup | (buffer, pos, end) | return -1 | Skipping an END_GROUP tag returns -1 to tell the parent loop to break. | Skipping an END_GROUP tag returns -1 to tell the parent loop to break. | [
"Skipping",
"an",
"END_GROUP",
"tag",
"returns",
"-",
"1",
"to",
"tell",
"the",
"parent",
"loop",
"to",
"break",
"."
] | def _EndGroup(buffer, pos, end):
"""Skipping an END_GROUP tag returns -1 to tell the parent loop to break."""
return -1 | [
"def",
"_EndGroup",
"(",
"buffer",
",",
"pos",
",",
"end",
")",
":",
"return",
"-",
"1"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/decoder.py#L669-L672 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/execution.py | python | Execution.symbol | (self, symbol) | Sets the symbol of this Execution.
:param symbol: The symbol of this Execution. # noqa: E501
:type: str | Sets the symbol of this Execution. | [
"Sets",
"the",
"symbol",
"of",
"this",
"Execution",
"."
] | def symbol(self, symbol):
"""Sets the symbol of this Execution.
:param symbol: The symbol of this Execution. # noqa: E501
:type: str
"""
self._symbol = symbol | [
"def",
"symbol",
"(",
"self",
",",
"symbol",
")",
":",
"self",
".",
"_symbol",
"=",
"symbol"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/execution.py#L397-L405 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py | python | Grid.entrycget | (self, x, y, option) | return self.tk.call(self, 'entrycget', x, y, option) | Get the option value for cell at (x,y) | Get the option value for cell at (x,y) | [
"Get",
"the",
"option",
"value",
"for",
"cell",
"at",
"(",
"x",
"y",
")"
] | def entrycget(self, x, y, option):
"Get the option value for cell at (x,y)"
if option and option[0] != '-':
option = '-' + option
return self.tk.call(self, 'entrycget', x, y, option) | [
"def",
"entrycget",
"(",
"self",
",",
"x",
",",
"y",
",",
"option",
")",
":",
"if",
"option",
"and",
"option",
"[",
"0",
"]",
"!=",
"'-'",
":",
"option",
"=",
"'-'",
"+",
"option",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
",",
"'e... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tix.py#L1856-L1860 | |
mavlink/mavros | a32232d57a5e91abf6737e454d4199cae29b369c | mavros/mavros/param.py | python | ParamPlugin.cli_pull | (self) | return self.create_client(ParamPull, ("param", "pull")) | Client for ParamPull service. | Client for ParamPull service. | [
"Client",
"for",
"ParamPull",
"service",
"."
] | def cli_pull(self) -> rclpy.node.Client:
"""Client for ParamPull service."""
return self.create_client(ParamPull, ("param", "pull")) | [
"def",
"cli_pull",
"(",
"self",
")",
"->",
"rclpy",
".",
"node",
".",
"Client",
":",
"return",
"self",
".",
"create_client",
"(",
"ParamPull",
",",
"(",
"\"param\"",
",",
"\"pull\"",
")",
")"
] | https://github.com/mavlink/mavros/blob/a32232d57a5e91abf6737e454d4199cae29b369c/mavros/mavros/param.py#L185-L187 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/zipfile.py | python | ZipFile.testzip | (self) | Read all the files and check the CRC. | Read all the files and check the CRC. | [
"Read",
"all",
"the",
"files",
"and",
"check",
"the",
"CRC",
"."
] | def testzip(self):
"""Read all the files and check the CRC."""
chunk_size = 2 ** 20
for zinfo in self.filelist:
try:
# Read by chunks, to avoid an OverflowError or a
# MemoryError with very large embedded files.
with self.open(zinfo.filename, "r") as f:
while f.read(chunk_size): # Check CRC-32
pass
except BadZipfile:
return zinfo.filename | [
"def",
"testzip",
"(",
"self",
")",
":",
"chunk_size",
"=",
"2",
"**",
"20",
"for",
"zinfo",
"in",
"self",
".",
"filelist",
":",
"try",
":",
"# Read by chunks, to avoid an OverflowError or a",
"# MemoryError with very large embedded files.",
"with",
"self",
".",
"op... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/zipfile.py#L887-L898 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/distutils/fcompiler/pg.py | python | PGroupFlangCompiler.get_library_dirs | (self) | return opt | List of compiler library directories. | List of compiler library directories. | [
"List",
"of",
"compiler",
"library",
"directories",
"."
] | def get_library_dirs(self):
"""List of compiler library directories."""
opt = FCompiler.get_library_dirs(self)
flang_dir = dirname(self.executables['compiler_f77'][0])
opt.append(normpath(join(flang_dir, '..', 'lib')))
return opt | [
"def",
"get_library_dirs",
"(",
"self",
")",
":",
"opt",
"=",
"FCompiler",
".",
"get_library_dirs",
"(",
"self",
")",
"flang_dir",
"=",
"dirname",
"(",
"self",
".",
"executables",
"[",
"'compiler_f77'",
"]",
"[",
"0",
"]",
")",
"opt",
".",
"append",
"(",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/fcompiler/pg.py#L94-L100 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathSurface.py | python | SetupProperties | () | return [tup[1] for tup in ObjectSurface.opPropertyDefinitions(False)] | SetupProperties() ... Return list of properties required for operation. | SetupProperties() ... Return list of properties required for operation. | [
"SetupProperties",
"()",
"...",
"Return",
"list",
"of",
"properties",
"required",
"for",
"operation",
"."
] | def SetupProperties():
"""SetupProperties() ... Return list of properties required for operation."""
return [tup[1] for tup in ObjectSurface.opPropertyDefinitions(False)] | [
"def",
"SetupProperties",
"(",
")",
":",
"return",
"[",
"tup",
"[",
"1",
"]",
"for",
"tup",
"in",
"ObjectSurface",
".",
"opPropertyDefinitions",
"(",
"False",
")",
"]"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathSurface.py#L2747-L2749 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/models.py | python | Response.raise_for_status | (self) | Raises stored :class:`HTTPError`, if one occurred. | Raises stored :class:`HTTPError`, if one occurred. | [
"Raises",
"stored",
":",
"class",
":",
"HTTPError",
"if",
"one",
"occurred",
"."
] | def raise_for_status(self):
"""Raises stored :class:`HTTPError`, if one occurred."""
http_error_msg = ''
if isinstance(self.reason, bytes):
# We attempt to decode utf-8 first because some servers
# choose to localize their reason strings. If the string
# isn't utf-8, we fall back to iso-8859-1 for all other
# encodings. (See PR #3538)
try:
reason = self.reason.decode('utf-8')
except UnicodeDecodeError:
reason = self.reason.decode('iso-8859-1')
else:
reason = self.reason
if 400 <= self.status_code < 500:
http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)
elif 500 <= self.status_code < 600:
http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)
if http_error_msg:
raise HTTPError(http_error_msg, response=self) | [
"def",
"raise_for_status",
"(",
"self",
")",
":",
"http_error_msg",
"=",
"''",
"if",
"isinstance",
"(",
"self",
".",
"reason",
",",
"bytes",
")",
":",
"# We attempt to decode utf-8 first because some servers",
"# choose to localize their reason strings. If the string",
"# i... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/models.py#L918-L941 | ||
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/python_message.py | python | _BytesForNonRepeatedElement | (value, field_number, field_type) | Returns the number of bytes needed to serialize a non-repeated element.
The returned byte count includes space for tag information and any
other additional space associated with serializing value.
Args:
value: Value we're serializing.
field_number: Field number of this value. (Since the field number
is stored as part of a varint-encoded tag, this has an impact
on the total bytes required to serialize the value).
field_type: The type of the field. One of the TYPE_* constants
within FieldDescriptor. | Returns the number of bytes needed to serialize a non-repeated element.
The returned byte count includes space for tag information and any
other additional space associated with serializing value. | [
"Returns",
"the",
"number",
"of",
"bytes",
"needed",
"to",
"serialize",
"a",
"non",
"-",
"repeated",
"element",
".",
"The",
"returned",
"byte",
"count",
"includes",
"space",
"for",
"tag",
"information",
"and",
"any",
"other",
"additional",
"space",
"associated... | def _BytesForNonRepeatedElement(value, field_number, field_type):
"""Returns the number of bytes needed to serialize a non-repeated element.
The returned byte count includes space for tag information and any
other additional space associated with serializing value.
Args:
value: Value we're serializing.
field_number: Field number of this value. (Since the field number
is stored as part of a varint-encoded tag, this has an impact
on the total bytes required to serialize the value).
field_type: The type of the field. One of the TYPE_* constants
within FieldDescriptor.
"""
try:
fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type]
return fn(field_number, value)
except KeyError:
raise message_mod.EncodeError('Unrecognized field type: %d' % field_type) | [
"def",
"_BytesForNonRepeatedElement",
"(",
"value",
",",
"field_number",
",",
"field_type",
")",
":",
"try",
":",
"fn",
"=",
"type_checkers",
".",
"TYPE_TO_BYTE_SIZE_FN",
"[",
"field_type",
"]",
"return",
"fn",
"(",
"field_number",
",",
"value",
")",
"except",
... | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/python_message.py#L716-L733 | ||
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/preprocessor.py | python | Expression.__strip | (self, length) | Remove a given amount of chars from the input and update
the offset. | Remove a given amount of chars from the input and update
the offset. | [
"Remove",
"a",
"given",
"amount",
"of",
"chars",
"from",
"the",
"input",
"and",
"update",
"the",
"offset",
"."
] | def __strip(self, length):
"""
Remove a given amount of chars from the input and update
the offset.
"""
self.content = self.content[length:]
self.offset += length | [
"def",
"__strip",
"(",
"self",
",",
"length",
")",
":",
"self",
".",
"content",
"=",
"self",
".",
"content",
"[",
"length",
":",
"]",
"self",
".",
"offset",
"+=",
"length"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/preprocessor.py#L171-L177 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/platform.py | python | architecture | (executable=sys.executable, bits='', linkage='') | return bits, linkage | Queries the given executable (defaults to the Python interpreter
binary) for various architecture information.
Returns a tuple (bits, linkage) which contains information about
the bit architecture and the linkage format used for the
executable. Both values are returned as strings.
Values that cannot be determined are returned as given by the
parameter presets. If bits is given as '', the sizeof(pointer)
(or sizeof(long) on Python version < 1.5.2) is used as
indicator for the supported pointer size.
The function relies on the system's "file" command to do the
actual work. This is available on most if not all Unix
platforms. On some non-Unix platforms where the "file" command
does not exist and the executable is set to the Python interpreter
binary defaults from _default_architecture are used. | Queries the given executable (defaults to the Python interpreter
binary) for various architecture information. | [
"Queries",
"the",
"given",
"executable",
"(",
"defaults",
"to",
"the",
"Python",
"interpreter",
"binary",
")",
"for",
"various",
"architecture",
"information",
"."
] | def architecture(executable=sys.executable, bits='', linkage=''):
""" Queries the given executable (defaults to the Python interpreter
binary) for various architecture information.
Returns a tuple (bits, linkage) which contains information about
the bit architecture and the linkage format used for the
executable. Both values are returned as strings.
Values that cannot be determined are returned as given by the
parameter presets. If bits is given as '', the sizeof(pointer)
(or sizeof(long) on Python version < 1.5.2) is used as
indicator for the supported pointer size.
The function relies on the system's "file" command to do the
actual work. This is available on most if not all Unix
platforms. On some non-Unix platforms where the "file" command
does not exist and the executable is set to the Python interpreter
binary defaults from _default_architecture are used.
"""
# Use the sizeof(pointer) as default number of bits if nothing
# else is given as default.
if not bits:
import struct
size = struct.calcsize('P')
bits = str(size * 8) + 'bit'
# Get data from the 'file' system command
if executable:
fileout = _syscmd_file(executable, '')
else:
fileout = ''
if not fileout and \
executable == sys.executable:
# "file" command did not return anything; we'll try to provide
# some sensible defaults then...
if sys.platform in _default_architecture:
b, l = _default_architecture[sys.platform]
if b:
bits = b
if l:
linkage = l
return bits, linkage
if 'executable' not in fileout and 'shared object' not in fileout:
# Format not supported
return bits, linkage
# Bits
if '32-bit' in fileout:
bits = '32bit'
elif 'N32' in fileout:
# On Irix only
bits = 'n32bit'
elif '64-bit' in fileout:
bits = '64bit'
# Linkage
if 'ELF' in fileout:
linkage = 'ELF'
elif 'PE' in fileout:
# E.g. Windows uses this format
if 'Windows' in fileout:
linkage = 'WindowsPE'
else:
linkage = 'PE'
elif 'COFF' in fileout:
linkage = 'COFF'
elif 'MS-DOS' in fileout:
linkage = 'MSDOS'
else:
# XXX the A.OUT format also falls under this class...
pass
return bits, linkage | [
"def",
"architecture",
"(",
"executable",
"=",
"sys",
".",
"executable",
",",
"bits",
"=",
"''",
",",
"linkage",
"=",
"''",
")",
":",
"# Use the sizeof(pointer) as default number of bits if nothing",
"# else is given as default.",
"if",
"not",
"bits",
":",
"import",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/platform.py#L650-L726 | |
ltcmelo/psychec | 46672204681d73b40772a7bf24137dca23175e81 | cnippet/wrapper/Python/CCompilerFacade.py | python | CCompilerFacade.preprocess | (self, c_file_name, pp_file_name) | Preprocess the file. | Preprocess the file. | [
"Preprocess",
"the",
"file",
"."
] | def preprocess(self, c_file_name, pp_file_name):
"""
Preprocess the file.
"""
cmd = [self.cc,
'-E',
'-x',
'c',
c_file_name,
'-o',
pp_file_name]
cmd += CCompilerFacade.defined_macros('-D')
cmd += CCompilerFacade.undefined_macros('-U')
cmd += self.original_options()
code = execute(CCompilerFacade.ID(), cmd)
if code != 0:
sys.exit(
DiagnosticReporter.fatal(PREPROCESSING_FILE_FAILED,
c_file_name)) | [
"def",
"preprocess",
"(",
"self",
",",
"c_file_name",
",",
"pp_file_name",
")",
":",
"cmd",
"=",
"[",
"self",
".",
"cc",
",",
"'-E'",
",",
"'-x'",
",",
"'c'",
",",
"c_file_name",
",",
"'-o'",
",",
"pp_file_name",
"]",
"cmd",
"+=",
"CCompilerFacade",
".... | https://github.com/ltcmelo/psychec/blob/46672204681d73b40772a7bf24137dca23175e81/cnippet/wrapper/Python/CCompilerFacade.py#L141-L163 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBBreakpoint.SetCondition | (self, *args) | return _lldb.SBBreakpoint_SetCondition(self, *args) | SetCondition(self, str condition)
The breakpoint stops only if the condition expression evaluates to true. | SetCondition(self, str condition) | [
"SetCondition",
"(",
"self",
"str",
"condition",
")"
] | def SetCondition(self, *args):
"""
SetCondition(self, str condition)
The breakpoint stops only if the condition expression evaluates to true.
"""
return _lldb.SBBreakpoint_SetCondition(self, *args) | [
"def",
"SetCondition",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBBreakpoint_SetCondition",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L1506-L1512 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/hypertreelist.py | python | TreeListMainWindow.OnEditTimer | (self) | The timer for editing has expired. Start editing. | The timer for editing has expired. Start editing. | [
"The",
"timer",
"for",
"editing",
"has",
"expired",
".",
"Start",
"editing",
"."
] | def OnEditTimer(self):
""" The timer for editing has expired. Start editing. """
self.EditLabel(self._current, self._curColumn) | [
"def",
"OnEditTimer",
"(",
"self",
")",
":",
"self",
".",
"EditLabel",
"(",
"self",
".",
"_current",
",",
"self",
".",
"_curColumn",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L3393-L3396 | ||
OAID/Tengine | 66b2c22ad129d25e2fc6de3b22a608bb54dd90db | tools/optimize/yolov5s-opt.py | python | main | () | main function | main function | [
"main",
"function"
] | def main():
"""
main function
"""
print("---- Tengine YOLOv5 Optimize Tool ----\n")
if args == None or args.input == None:
usage_info()
return None
print("Input model : %s" % (args.input))
print("Output model : %s" % (args.output))
print("Input tensor : %s" % (args.in_tensor))
print("Output tensor : %s" % (args.out_tensor))
in_tensor = args.in_tensor.split(',')
out_tensor = args.out_tensor.split(',')
# load original onnx model, graph, nodes
print("[Quant Tools Info]: Step 0, load original onnx model from %s." % (args.input))
onnx_model = onnx.load(args.input)
onnx_model, check = simplify(onnx_model)
graph = onnx_model.graph
print(len(graph.value_info))
# create the new nodes for optimize onnx model
old_node = graph.node
new_nodes = old_node[:]
# cut the focus and postprocess nodes
if args.cut_focus:
print("[Quant Tools Info]: Step 1, Remove the focus and postprocess nodes.")
new_nodes = cut_focus_output(old_node, in_tensor, out_tensor)
# op fusion, using HardSwish replace the Sigmoid and Mul
print("[Quant Tools Info]: Step 2, Using hardswish replace the sigmoid and mul.")
new_nodes = fusion_hardswish(new_nodes)
# rebuild new model, set the input and outputs nodes
print("[Quant Tools Info]: Step 3, Rebuild onnx graph nodes.")
del onnx_model.graph.node[:]
onnx_model.graph.node.extend(new_nodes)
# get input/output tensor index of value info
in_tensor_idx = [None] * len(in_tensor)
out_tensor_idx = [None] * len(out_tensor)
value = graph.value_info
for i, v in enumerate(value):
if v.name in in_tensor:
in_tensor_idx[in_tensor.index(v.name)] = i
if v.name in out_tensor:
out_tensor_idx[out_tensor.index(v.name)] = i
print("[Quant Tools Info]: Step 4, Update input and output tensor.")
keep_or_del_elem(onnx_model.graph.input, in_tensor, True)
for i in in_tensor_idx:
if i: onnx_model.graph.input.append(value[i])
keep_or_del_elem(onnx_model.graph.output, out_tensor, True)
for i in out_tensor_idx:
if i: onnx_model.graph.output.append(value[i])
# save the new optimize onnx model
print("[Quant Tools Info]: Step 5, save the new onnx model to %s." % (args.output))
onnx.save(onnx_model, args.output)
print("\n---- Tengine YOLOv5s Optimize onnx create success, best wish for your inference has a high accuracy ...\\(^0^)/ ----") | [
"def",
"main",
"(",
")",
":",
"print",
"(",
"\"---- Tengine YOLOv5 Optimize Tool ----\\n\"",
")",
"if",
"args",
"==",
"None",
"or",
"args",
".",
"input",
"==",
"None",
":",
"usage_info",
"(",
")",
"return",
"None",
"print",
"(",
"\"Input model : %s\"",
"%... | https://github.com/OAID/Tengine/blob/66b2c22ad129d25e2fc6de3b22a608bb54dd90db/tools/optimize/yolov5s-opt.py#L153-L219 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xpathContext.functionURI | (self) | return ret | Get the current function name URI xpathContext | Get the current function name URI xpathContext | [
"Get",
"the",
"current",
"function",
"name",
"URI",
"xpathContext"
] | def functionURI(self):
"""Get the current function name URI xpathContext """
ret = libxml2mod.xmlXPathGetFunctionURI(self._o)
return ret | [
"def",
"functionURI",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlXPathGetFunctionURI",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L7286-L7289 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/third_party/Python/module/pexpect-4.6/pexpect/FSM.py | python | FSM.process | (self, input_symbol) | This is the main method that you call to process input. This may
cause the FSM to change state and call an action. This method calls
get_transition() to find the action and next_state associated with the
input_symbol and current_state. If the action is None then the action
is not called and only the current state is changed. This method
processes one complete input symbol. You can process a list of symbols
(or a string) by calling process_list(). | This is the main method that you call to process input. This may
cause the FSM to change state and call an action. This method calls
get_transition() to find the action and next_state associated with the
input_symbol and current_state. If the action is None then the action
is not called and only the current state is changed. This method
processes one complete input symbol. You can process a list of symbols
(or a string) by calling process_list(). | [
"This",
"is",
"the",
"main",
"method",
"that",
"you",
"call",
"to",
"process",
"input",
".",
"This",
"may",
"cause",
"the",
"FSM",
"to",
"change",
"state",
"and",
"call",
"an",
"action",
".",
"This",
"method",
"calls",
"get_transition",
"()",
"to",
"find... | def process (self, input_symbol):
'''This is the main method that you call to process input. This may
cause the FSM to change state and call an action. This method calls
get_transition() to find the action and next_state associated with the
input_symbol and current_state. If the action is None then the action
is not called and only the current state is changed. This method
processes one complete input symbol. You can process a list of symbols
(or a string) by calling process_list(). '''
self.input_symbol = input_symbol
(self.action, self.next_state) = self.get_transition (self.input_symbol, self.current_state)
if self.action is not None:
self.action (self)
self.current_state = self.next_state
self.next_state = None | [
"def",
"process",
"(",
"self",
",",
"input_symbol",
")",
":",
"self",
".",
"input_symbol",
"=",
"input_symbol",
"(",
"self",
".",
"action",
",",
"self",
".",
"next_state",
")",
"=",
"self",
".",
"get_transition",
"(",
"self",
".",
"input_symbol",
",",
"s... | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/pexpect-4.6/pexpect/FSM.py#L228-L243 | ||
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | docs/custom_inheritance_diagram/btd/sphinx/inheritance_diagram.py | python | try_import | (objname: str) | Import a object or module using *name* and *currentmodule*.
*name* should be a relative name from *currentmodule* or
a fully-qualified name.
Returns imported object or module. If failed, returns None value. | Import a object or module using *name* and *currentmodule*.
*name* should be a relative name from *currentmodule* or
a fully-qualified name. | [
"Import",
"a",
"object",
"or",
"module",
"using",
"*",
"name",
"*",
"and",
"*",
"currentmodule",
"*",
".",
"*",
"name",
"*",
"should",
"be",
"a",
"relative",
"name",
"from",
"*",
"currentmodule",
"*",
"or",
"a",
"fully",
"-",
"qualified",
"name",
"."
] | def try_import(objname: str) -> Any:
"""Import a object or module using *name* and *currentmodule*.
*name* should be a relative name from *currentmodule* or
a fully-qualified name.
Returns imported object or module. If failed, returns None value.
"""
try:
return import_module(objname)
except TypeError:
# Relative import
return None
except ImportError:
matched = module_sig_re.match(objname)
if not matched:
return None
modname, attrname = matched.groups()
if modname is None:
return None
try:
module = import_module(modname)
return getattr(module, attrname, None)
except ImportError:
return None | [
"def",
"try_import",
"(",
"objname",
":",
"str",
")",
"->",
"Any",
":",
"try",
":",
"return",
"import_module",
"(",
"objname",
")",
"except",
"TypeError",
":",
"# Relative import",
"return",
"None",
"except",
"ImportError",
":",
"matched",
"=",
"module_sig_re"... | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/docs/custom_inheritance_diagram/btd/sphinx/inheritance_diagram.py#L77-L103 | ||
Komnomnomnom/swigibpy | cfd307fdbfaffabc69a2dc037538d7e34a8b8daf | swigibpy.py | python | TagValueList.erase | (self, *args) | return _swigibpy.TagValueList_erase(self, *args) | erase(TagValueList self, std::vector< shared_ptr< TagValue > >::iterator pos) -> std::vector< shared_ptr< TagValue > >::iterator
erase(TagValueList self, std::vector< shared_ptr< TagValue > >::iterator first, std::vector< shared_ptr< TagValue > >::iterator last) -> std::vector< shared_ptr< TagValue > >::iterator | erase(TagValueList self, std::vector< shared_ptr< TagValue > >::iterator pos) -> std::vector< shared_ptr< TagValue > >::iterator
erase(TagValueList self, std::vector< shared_ptr< TagValue > >::iterator first, std::vector< shared_ptr< TagValue > >::iterator last) -> std::vector< shared_ptr< TagValue > >::iterator | [
"erase",
"(",
"TagValueList",
"self",
"std",
"::",
"vector<",
"shared_ptr<",
"TagValue",
">",
">",
"::",
"iterator",
"pos",
")",
"-",
">",
"std",
"::",
"vector<",
"shared_ptr<",
"TagValue",
">",
">",
"::",
"iterator",
"erase",
"(",
"TagValueList",
"self",
... | def erase(self, *args):
"""
erase(TagValueList self, std::vector< shared_ptr< TagValue > >::iterator pos) -> std::vector< shared_ptr< TagValue > >::iterator
erase(TagValueList self, std::vector< shared_ptr< TagValue > >::iterator first, std::vector< shared_ptr< TagValue > >::iterator last) -> std::vector< shared_ptr< TagValue > >::iterator
"""
return _swigibpy.TagValueList_erase(self, *args) | [
"def",
"erase",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_swigibpy",
".",
"TagValueList_erase",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L814-L819 | |
GoSSIP-SJTU/TripleDoggy | 03648d6b19c812504b14e8b98c8c7b3f443f4e54 | tools/clang/tools/scan-build-py/libscanbuild/analyze.py | python | analyze_build | () | Entry point for analyze-build command. | Entry point for analyze-build command. | [
"Entry",
"point",
"for",
"analyze",
"-",
"build",
"command",
"."
] | def analyze_build():
""" Entry point for analyze-build command. """
args = parse_args_for_analyze_build()
# will re-assign the report directory as new output
with report_directory(args.output, args.keep_empty) as args.output:
# Run the analyzer against a compilation db.
govern_analyzer_runs(args)
# Cover report generation and bug counting.
number_of_bugs = document(args)
# Set exit status as it was requested.
return number_of_bugs if args.status_bugs else 0 | [
"def",
"analyze_build",
"(",
")",
":",
"args",
"=",
"parse_args_for_analyze_build",
"(",
")",
"# will re-assign the report directory as new output",
"with",
"report_directory",
"(",
"args",
".",
"output",
",",
"args",
".",
"keep_empty",
")",
"as",
"args",
".",
"outp... | https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/tools/clang/tools/scan-build-py/libscanbuild/analyze.py#L77-L88 | ||
amd/OpenCL-caffe | 638543108517265366c18ae5821f3096cf5cf34a | python/caffe/io.py | python | Transformer.set_mean | (self, in_, mean) | Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable) | Set the mean to subtract for centering the data. | [
"Set",
"the",
"mean",
"to",
"subtract",
"for",
"centering",
"the",
"data",
"."
] | def set_mean(self, in_, mean):
"""
Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable)
"""
self.__check_input(in_)
ms = mean.shape
if mean.ndim == 1:
# broadcast channels
if ms[0] != self.inputs[in_][1]:
raise ValueError('Mean channels incompatible with input.')
mean = mean[:, np.newaxis, np.newaxis]
else:
# elementwise mean
if len(ms) == 2:
ms = (1,) + ms
if len(ms) != 3:
raise ValueError('Mean shape invalid')
if ms != self.inputs[in_][1:]:
raise ValueError('Mean shape incompatible with input shape.')
self.mean[in_] = mean | [
"def",
"set_mean",
"(",
"self",
",",
"in_",
",",
"mean",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"ms",
"=",
"mean",
".",
"shape",
"if",
"mean",
".",
"ndim",
"==",
"1",
":",
"# broadcast channels",
"if",
"ms",
"[",
"0",
"]",
"!=",
... | https://github.com/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/python/caffe/io.py#L232-L256 | ||
PaddlePaddle/PaddleOCR | b756bf5f8c90142e0d89d3db0163965c686b6ffe | ppstructure/table/table_metric/table_metric.py | python | TEDS.evaluate | (self, pred, true) | Computes TEDS score between the prediction and the ground truth of a
given sample | Computes TEDS score between the prediction and the ground truth of a
given sample | [
"Computes",
"TEDS",
"score",
"between",
"the",
"prediction",
"and",
"the",
"ground",
"truth",
"of",
"a",
"given",
"sample"
] | def evaluate(self, pred, true):
''' Computes TEDS score between the prediction and the ground truth of a
given sample
'''
if (not pred) or (not true):
return 0.0
parser = html.HTMLParser(remove_comments=True, encoding='utf-8')
pred = html.fromstring(pred, parser=parser)
true = html.fromstring(true, parser=parser)
if pred.xpath('body/table') and true.xpath('body/table'):
pred = pred.xpath('body/table')[0]
true = true.xpath('body/table')[0]
if self.ignore_nodes:
etree.strip_tags(pred, *self.ignore_nodes)
etree.strip_tags(true, *self.ignore_nodes)
n_nodes_pred = len(pred.xpath(".//*"))
n_nodes_true = len(true.xpath(".//*"))
n_nodes = max(n_nodes_pred, n_nodes_true)
tree_pred = self.load_html_tree(pred)
tree_true = self.load_html_tree(true)
distance = APTED(tree_pred, tree_true,
CustomConfig()).compute_edit_distance()
return 1.0 - (float(distance) / n_nodes)
else:
return 0.0 | [
"def",
"evaluate",
"(",
"self",
",",
"pred",
",",
"true",
")",
":",
"if",
"(",
"not",
"pred",
")",
"or",
"(",
"not",
"true",
")",
":",
"return",
"0.0",
"parser",
"=",
"html",
".",
"HTMLParser",
"(",
"remove_comments",
"=",
"True",
",",
"encoding",
... | https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppstructure/table/table_metric/table_metric.py#L176-L200 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | TimeSpan_Minutes | (*args, **kwargs) | return _misc_.TimeSpan_Minutes(*args, **kwargs) | TimeSpan_Minutes(long min) -> TimeSpan | TimeSpan_Minutes(long min) -> TimeSpan | [
"TimeSpan_Minutes",
"(",
"long",
"min",
")",
"-",
">",
"TimeSpan"
] | def TimeSpan_Minutes(*args, **kwargs):
"""TimeSpan_Minutes(long min) -> TimeSpan"""
return _misc_.TimeSpan_Minutes(*args, **kwargs) | [
"def",
"TimeSpan_Minutes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"TimeSpan_Minutes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4572-L4574 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.