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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/compiler.py | python | DefaultPassBuilder.define_interpreted_pipeline | (state, name="interpreted") | return pm | Returns an interpreted mode pipeline based PassManager | Returns an interpreted mode pipeline based PassManager | [
"Returns",
"an",
"interpreted",
"mode",
"pipeline",
"based",
"PassManager"
] | def define_interpreted_pipeline(state, name="interpreted"):
"""Returns an interpreted mode pipeline based PassManager
"""
pm = PassManager(name)
pm.add_pass(CompileInterpMode,
"compiling with interpreter mode")
pm.finalize()
return pm | [
"def",
"define_interpreted_pipeline",
"(",
"state",
",",
"name",
"=",
"\"interpreted\"",
")",
":",
"pm",
"=",
"PassManager",
"(",
"name",
")",
"pm",
".",
"add_pass",
"(",
"CompileInterpMode",
",",
"\"compiling with interpreter mode\"",
")",
"pm",
".",
"finalize",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/compiler.py#L515-L522 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/search/bounds_search.py | python | MercatorBounds | (lat, lng, lod) | return {
"south": south,
"north": north,
"west": west,
"east": east
} | Return bounds of Mercator tile containing given lat/lng at given lod.
Args:
lat: (float) Latitude in degrees.
lng: (float) Longitude in degrees.
lod: (integer) Level of detail (zoom).
Returns:
Dictionary of north, west, south, east bounds. | Return bounds of Mercator tile containing given lat/lng at given lod. | [
"Return",
"bounds",
"of",
"Mercator",
"tile",
"containing",
"given",
"lat",
"/",
"lng",
"at",
"given",
"lod",
"."
] | def MercatorBounds(lat, lng, lod):
"""Return bounds of Mercator tile containing given lat/lng at given lod.
Args:
lat: (float) Latitude in degrees.
lng: (float) Longitude in degrees.
lod: (integer) Level of detail (zoom).
Returns:
Dictionary of north, west, south, east bounds.
"""
num_tiles = 1 << lod
(west, east) = LongitudinalBounds(lng, num_tiles)
# Normalize to between -90 and 90 degrees latitude.
while lat < -90.0:
lat += 180.0
while lat >= 90.0:
lat -= 180.0
y = int(ToMercPosition(lat, num_tiles))
south = ToMercDegrees(y, num_tiles)
north = ToMercDegrees(y + 1, num_tiles)
return {
"south": south,
"north": north,
"west": west,
"east": east
} | [
"def",
"MercatorBounds",
"(",
"lat",
",",
"lng",
",",
"lod",
")",
":",
"num_tiles",
"=",
"1",
"<<",
"lod",
"(",
"west",
",",
"east",
")",
"=",
"LongitudinalBounds",
"(",
"lng",
",",
"num_tiles",
")",
"# Normalize to between -90 and 90 degrees latitude.",
"whil... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/search/bounds_search.py#L95-L125 | |
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | build/unix/makepchinput.py | python | getSTLIncludes | () | return allHeadersPartContent | Here we include the list of c++11 stl headers
From http://en.cppreference.com/w/cpp/header
valarray is removed because it causes lots of compilation at startup. | Here we include the list of c++11 stl headers
From http://en.cppreference.com/w/cpp/header
valarray is removed because it causes lots of compilation at startup. | [
"Here",
"we",
"include",
"the",
"list",
"of",
"c",
"++",
"11",
"stl",
"headers",
"From",
"http",
":",
"//",
"en",
".",
"cppreference",
".",
"com",
"/",
"w",
"/",
"cpp",
"/",
"header",
"valarray",
"is",
"removed",
"because",
"it",
"causes",
"lots",
"o... | def getSTLIncludes():
"""
Here we include the list of c++11 stl headers
From http://en.cppreference.com/w/cpp/header
valarray is removed because it causes lots of compilation at startup.
"""
stlHeadersList = ("cstdlib",
"csignal",
"csetjmp",
"cstdarg",
"typeinfo",
"typeindex",
"type_traits",
"bitset",
"functional",
"utility",
"ctime",
"chrono",
"cstddef",
"initializer_list",
"tuple",
"new",
"memory",
"scoped_allocator",
"climits",
"cfloat",
"cstdint",
"cinttypes",
"limits",
"exception",
"stdexcept",
"cassert",
"system_error",
"cerrno",
"cctype",
"cwctype",
"cstring",
"cwchar",
"cuchar",
"string",
"array",
"vector",
"deque",
"list",
"forward_list",
"set",
"map",
"unordered_set",
"unordered_map",
"stack",
"queue",
"algorithm",
"iterator",
"cmath",
"complex",
# "valarray",
"random",
"numeric",
"ratio",
"cfenv",
"iosfwd",
"ios",
"istream",
"ostream",
"iostream",
"fstream",
"sstream",
"iomanip",
"streambuf",
"cstdio",
"locale",
"clocale",
"codecvt",
"atomic",
"thread",
"mutex",
"future",
"condition_variable",
"ciso646",
"ccomplex",
"ctgmath",
"regex",
"cstdbool")
allHeadersPartContent = "// STL headers\n"
for header in stlHeadersList:
allHeadersPartContent += getGuardedStlInclude(header)
# Special case for regex
allHeadersPartContent += '// treat regex separately\n' +\
'#if __has_include("regex") && !defined __APPLE__\n' +\
'#include <regex>\n' +\
'#endif\n'
# treat this deprecated headers in a special way
stlDeprecatedHeadersList=["strstream"]
allHeadersPartContent += '// STL Deprecated headers\n' +\
'#define _BACKWARD_BACKWARD_WARNING_H\n' +\
"#pragma clang diagnostic push\n" +\
'#pragma GCC diagnostic ignored "-Wdeprecated"\n'
for header in stlDeprecatedHeadersList:
allHeadersPartContent += getGuardedStlInclude(header)
allHeadersPartContent += '#pragma clang diagnostic pop\n' +\
'#undef _BACKWARD_BACKWARD_WARNING_H\n'
return allHeadersPartContent | [
"def",
"getSTLIncludes",
"(",
")",
":",
"stlHeadersList",
"=",
"(",
"\"cstdlib\"",
",",
"\"csignal\"",
",",
"\"csetjmp\"",
",",
"\"cstdarg\"",
",",
"\"typeinfo\"",
",",
"\"typeindex\"",
",",
"\"type_traits\"",
",",
"\"bitset\"",
",",
"\"functional\"",
",",
"\"util... | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/build/unix/makepchinput.py#L54-L161 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/html5lib/treewalkers/base.py | python | TreeWalker.endTag | (self, namespace, name) | return {"type": "EndTag",
"name": name,
"namespace": namespace} | Generates an EndTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:returns: EndTag token | Generates an EndTag token | [
"Generates",
"an",
"EndTag",
"token"
] | def endTag(self, namespace, name):
"""Generates an EndTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:returns: EndTag token
"""
return {"type": "EndTag",
"name": name,
"namespace": namespace} | [
"def",
"endTag",
"(",
"self",
",",
"namespace",
",",
"name",
")",
":",
"return",
"{",
"\"type\"",
":",
"\"EndTag\"",
",",
"\"name\"",
":",
"name",
",",
"\"namespace\"",
":",
"namespace",
"}"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/html5lib/treewalkers/base.py#L86-L98 | |
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | utils/vim-lldb/python-vim-lldb/vim_ui.py | python | UI.update | (self, target, status, controller, goto_file=False) | Updates debugger info panels and breakpoint/pc marks and prints
status to the vim status line. If goto_file is True, the user's
cursor is moved to the source PC location in the selected frame. | Updates debugger info panels and breakpoint/pc marks and prints
status to the vim status line. If goto_file is True, the user's
cursor is moved to the source PC location in the selected frame. | [
"Updates",
"debugger",
"info",
"panels",
"and",
"breakpoint",
"/",
"pc",
"marks",
"and",
"prints",
"status",
"to",
"the",
"vim",
"status",
"line",
".",
"If",
"goto_file",
"is",
"True",
"the",
"user",
"s",
"cursor",
"is",
"moved",
"to",
"the",
"source",
"... | def update(self, target, status, controller, goto_file=False):
""" Updates debugger info panels and breakpoint/pc marks and prints
status to the vim status line. If goto_file is True, the user's
cursor is moved to the source PC location in the selected frame.
"""
self.paneCol.update(target, controller)
self.update_breakpoints(target, self.get_user_buffers())
if target is not None and target.IsValid():
process = target.GetProcess()
if process is not None and process.IsValid():
self.update_pc(process, self.get_user_buffers, goto_file)
if status is not None and len(status) > 0:
print(status) | [
"def",
"update",
"(",
"self",
",",
"target",
",",
"status",
",",
"controller",
",",
"goto_file",
"=",
"False",
")",
":",
"self",
".",
"paneCol",
".",
"update",
"(",
"target",
",",
"controller",
")",
"self",
".",
"update_breakpoints",
"(",
"target",
",",
... | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/utils/vim-lldb/python-vim-lldb/vim_ui.py#L209-L224 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | PrintPreview.GetPrintoutForPrinting | (*args, **kwargs) | return _windows_.PrintPreview_GetPrintoutForPrinting(*args, **kwargs) | GetPrintoutForPrinting(self) -> Printout | GetPrintoutForPrinting(self) -> Printout | [
"GetPrintoutForPrinting",
"(",
"self",
")",
"-",
">",
"Printout"
] | def GetPrintoutForPrinting(*args, **kwargs):
"""GetPrintoutForPrinting(self) -> Printout"""
return _windows_.PrintPreview_GetPrintoutForPrinting(*args, **kwargs) | [
"def",
"GetPrintoutForPrinting",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PrintPreview_GetPrintoutForPrinting",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L5589-L5591 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | configure.py | python | set_gcc_host_compiler_path | (environ_cp) | Set GCC_HOST_COMPILER_PATH. | Set GCC_HOST_COMPILER_PATH. | [
"Set",
"GCC_HOST_COMPILER_PATH",
"."
] | def set_gcc_host_compiler_path(environ_cp):
"""Set GCC_HOST_COMPILER_PATH."""
default_gcc_host_compiler_path = which('gcc') or ''
cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
if os.path.islink(cuda_bin_symlink):
# os.readlink is only available in linux
default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
ask_gcc_path = (
'Please specify which gcc should be used by nvcc as the '
'host compiler. [Default is %s]: ') % default_gcc_host_compiler_path
while True:
gcc_host_compiler_path = get_from_env_or_user_or_default(
environ_cp, 'GCC_HOST_COMPILER_PATH', ask_gcc_path,
default_gcc_host_compiler_path)
if os.path.exists(gcc_host_compiler_path):
break
# Reset and retry
print('Invalid gcc path. %s cannot be found' % gcc_host_compiler_path)
environ_cp['GCC_HOST_COMPILER_PATH'] = ''
# Set GCC_HOST_COMPILER_PATH
environ_cp['GCC_HOST_COMPILER_PATH'] = gcc_host_compiler_path
write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH', gcc_host_compiler_path) | [
"def",
"set_gcc_host_compiler_path",
"(",
"environ_cp",
")",
":",
"default_gcc_host_compiler_path",
"=",
"which",
"(",
"'gcc'",
")",
"or",
"''",
"cuda_bin_symlink",
"=",
"'%s/bin/gcc'",
"%",
"environ_cp",
".",
"get",
"(",
"'CUDA_TOOLKIT_PATH'",
")",
"if",
"os",
".... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/configure.py#L558-L584 | ||
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Modules/Scripted/LabelStatistics/LabelStatistics.py | python | LabelStatisticsWidget.onApply | (self) | Calculate the label statistics | Calculate the label statistics | [
"Calculate",
"the",
"label",
"statistics"
] | def onApply(self):
"""Calculate the label statistics
"""
self.applyButton.text = "Working..."
# TODO: why doesn't processEvents alone make the label text change?
self.applyButton.repaint()
slicer.app.processEvents()
# resample the label to the space of the grayscale if needed
volumesLogic = slicer.modules.volumes.logic()
warnings = volumesLogic.CheckForLabelVolumeValidity(self.grayscaleNode, self.labelNode)
resampledLabelNode = None
if warnings != "":
if 'mismatch' in warnings:
resampledLabelNode = volumesLogic.ResampleVolumeToReferenceVolume(self.labelNode, self.grayscaleNode)
# resampledLabelNode does not have a display node, therefore the colorNode has to be passed to it
self.logic = LabelStatisticsLogic(self.grayscaleNode, resampledLabelNode, colorNode=self.labelNode.GetDisplayNode().GetColorNode(), nodeBaseName=self.labelNode.GetName())
else:
slicer.util.warnDisplay("Volumes do not have the same geometry.\n%s" % warnings, windowTitle="Label Statistics")
return
else:
self.logic = LabelStatisticsLogic(self.grayscaleNode, self.labelNode)
self.populateStats()
if resampledLabelNode:
slicer.mrmlScene.RemoveNode(resampledLabelNode)
self.chartFrame.enabled = True
self.exportToTableButton.enabled = True
self.applyButton.text = "Apply" | [
"def",
"onApply",
"(",
"self",
")",
":",
"self",
".",
"applyButton",
".",
"text",
"=",
"\"Working...\"",
"# TODO: why doesn't processEvents alone make the label text change?",
"self",
".",
"applyButton",
".",
"repaint",
"(",
")",
"slicer",
".",
"app",
".",
"processE... | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/LabelStatistics/LabelStatistics.py#L160-L187 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/device.py | python | is_cambricon_available | () | return CompNode._get_device_count(t, False) > 0 | r"""Returns whether cambricon device is available on this system. | r"""Returns whether cambricon device is available on this system. | [
"r",
"Returns",
"whether",
"cambricon",
"device",
"is",
"available",
"on",
"this",
"system",
"."
] | def is_cambricon_available() -> bool:
r"""Returns whether cambricon device is available on this system."""
t = _str2device_type("cambricon")
return CompNode._get_device_count(t, False) > 0 | [
"def",
"is_cambricon_available",
"(",
")",
"->",
"bool",
":",
"t",
"=",
"_str2device_type",
"(",
"\"cambricon\"",
")",
"return",
"CompNode",
".",
"_get_device_count",
"(",
"t",
",",
"False",
")",
">",
"0"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/device.py#L101-L104 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibar.py | python | ToolbarCommandCapture.GetCommandId | (self) | return self._last_id | Returns the event command identifier. | Returns the event command identifier. | [
"Returns",
"the",
"event",
"command",
"identifier",
"."
] | def GetCommandId(self):
""" Returns the event command identifier. """
return self._last_id | [
"def",
"GetCommandId",
"(",
"self",
")",
":",
"return",
"self",
".",
"_last_id"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibar.py#L201-L204 | |
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/plasma/Plasma.py | python | PtFadeOut | (lenTime, holdFlag, noSound=0) | Fades screen out for lenTime seconds | Fades screen out for lenTime seconds | [
"Fades",
"screen",
"out",
"for",
"lenTime",
"seconds"
] | def PtFadeOut(lenTime, holdFlag, noSound=0):
"""Fades screen out for lenTime seconds"""
pass | [
"def",
"PtFadeOut",
"(",
"lenTime",
",",
"holdFlag",
",",
"noSound",
"=",
"0",
")",
":",
"pass"
] | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/plasma/Plasma.py#L296-L298 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | Slider.SetMin | (*args, **kwargs) | return _controls_.Slider_SetMin(*args, **kwargs) | SetMin(self, int minValue) | SetMin(self, int minValue) | [
"SetMin",
"(",
"self",
"int",
"minValue",
")"
] | def SetMin(*args, **kwargs):
"""SetMin(self, int minValue)"""
return _controls_.Slider_SetMin(*args, **kwargs) | [
"def",
"SetMin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"Slider_SetMin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L2856-L2858 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | cmake/std/trilinosprhelpers/TrilinosPRConfigurationBase.py | python | TrilinosPRConfigurationBase.arg_workspace_dir | (self) | return self.args.workspace_dir | Returns the Jenkins workspace directory for the PR.
The default behavior of this property is to return the value of
the `workspace_dir` argument from the program arguments. | Returns the Jenkins workspace directory for the PR.
The default behavior of this property is to return the value of
the `workspace_dir` argument from the program arguments. | [
"Returns",
"the",
"Jenkins",
"workspace",
"directory",
"for",
"the",
"PR",
".",
"The",
"default",
"behavior",
"of",
"this",
"property",
"is",
"to",
"return",
"the",
"value",
"of",
"the",
"workspace_dir",
"argument",
"from",
"the",
"program",
"arguments",
"."
] | def arg_workspace_dir(self):
"""
Returns the Jenkins workspace directory for the PR.
The default behavior of this property is to return the value of
the `workspace_dir` argument from the program arguments.
"""
return self.args.workspace_dir | [
"def",
"arg_workspace_dir",
"(",
"self",
")",
":",
"return",
"self",
".",
"args",
".",
"workspace_dir"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/cmake/std/trilinosprhelpers/TrilinosPRConfigurationBase.py#L168-L174 | |
sccn/lsl_archived | 2ff44b7a5172b02fe845b1fc72b9ab5578a489ed | Apps/neuroPrax/lsl_server.py | python | ProtocolHandler.handle_GIP | (self) | return paramDict | handle a GIP: General Information Protocol
order of keys is fixed according to protocol
we therefore go through all keys, and store them
in a dictionary | handle a GIP: General Information Protocol
order of keys is fixed according to protocol
we therefore go through all keys, and store them
in a dictionary | [
"handle",
"a",
"GIP",
":",
"General",
"Information",
"Protocol",
"order",
"of",
"keys",
"is",
"fixed",
"according",
"to",
"protocol",
"we",
"therefore",
"go",
"through",
"all",
"keys",
"and",
"store",
"them",
"in",
"a",
"dictionary"
] | def handle_GIP(self):
'''handle a GIP: General Information Protocol
order of keys is fixed according to protocol
we therefore go through all keys, and store them
in a dictionary
'''
settingList = ['recFileName',
'recPathName',
'DB_PatName',
'DB_PatFirstName',
'DB_PatBirthDay',
'DB_PatINR',
'elecSetup',
'fs',
'selAlgorithm',
'numChannels',
'numEXGChannels'
]
chanInfoList = ['ChannelNames',
'ChannelTypes',
'ChannelUnits',
'ChannelReference']
# receive information on the generalsetting
params = self.recv_bytes(1576)
paramList = params.decode().split('$')
paramDict = {}
for key, val in zip(settingList, paramList):
if 'Channels' in key:
paramDict[key] = int(val)
elif 'fs' in key:
paramDict[key] = int(val)
else:
paramDict[key] = val
# receive information on the channels. As this depends on
# channel number, it is within a seperate block
chanInfo = self.recv_bytes(36 * paramDict['numChannels'])
infoList = chanInfo.decode('cp1252').split('$')
for idx, key in enumerate(chanInfoList):
num = paramDict['numChannels']
paramDict[key] = infoList[(num * idx) : (num * (idx + 1)) ]
# store key information in the instance, to allow transformation
# of packets to data files (see packet2cnt)
self.fs = paramDict['fs']
paramDict['ChannelNames'] = [ch.strip() for
ch in paramDict['ChannelNames']]
paramDict['ChannelTypes'] = [t.strip() for
t in paramDict['ChannelTypes']]
# lsl xdf specification requests 'microvolts' instead of 'µV'
units = []
for ch in paramDict['ChannelUnits']:
if ch.strip() == 'µV':
units.append('microvolts')
else:
units.append(ch.strip())
paramDict['ChannelUnits'] = units
self.settings = paramDict
return paramDict | [
"def",
"handle_GIP",
"(",
"self",
")",
":",
"settingList",
"=",
"[",
"'recFileName'",
",",
"'recPathName'",
",",
"'DB_PatName'",
",",
"'DB_PatFirstName'",
",",
"'DB_PatBirthDay'",
",",
"'DB_PatINR'",
",",
"'elecSetup'",
",",
"'fs'",
",",
"'selAlgorithm'",
",",
"... | https://github.com/sccn/lsl_archived/blob/2ff44b7a5172b02fe845b1fc72b9ab5578a489ed/Apps/neuroPrax/lsl_server.py#L123-L191 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/gyp/util/build_utils.py | python | DoZip | (inputs,
output,
base_dir=None,
compress_fn=None,
zip_prefix_path=None,
timestamp=None) | Creates a zip file from a list of files.
Args:
inputs: A list of paths to zip, or a list of (zip_path, fs_path) tuples.
output: Path, fileobj, or ZipFile instance to add files to.
base_dir: Prefix to strip from inputs.
compress_fn: Applied to each input to determine whether or not to compress.
By default, items will be |zipfile.ZIP_STORED|.
zip_prefix_path: Path prepended to file path in zip file.
timestamp: Unix timestamp to use for files in the archive. | Creates a zip file from a list of files. | [
"Creates",
"a",
"zip",
"file",
"from",
"a",
"list",
"of",
"files",
"."
] | def DoZip(inputs,
output,
base_dir=None,
compress_fn=None,
zip_prefix_path=None,
timestamp=None):
"""Creates a zip file from a list of files.
Args:
inputs: A list of paths to zip, or a list of (zip_path, fs_path) tuples.
output: Path, fileobj, or ZipFile instance to add files to.
base_dir: Prefix to strip from inputs.
compress_fn: Applied to each input to determine whether or not to compress.
By default, items will be |zipfile.ZIP_STORED|.
zip_prefix_path: Path prepended to file path in zip file.
timestamp: Unix timestamp to use for files in the archive.
"""
if base_dir is None:
base_dir = '.'
input_tuples = []
for tup in inputs:
if isinstance(tup, string_types):
tup = (os.path.relpath(tup, base_dir), tup)
if tup[0].startswith('..'):
raise Exception('Invalid zip_path: ' + tup[0])
input_tuples.append(tup)
# Sort by zip path to ensure stable zip ordering.
input_tuples.sort(key=lambda tup: tup[0])
out_zip = output
if not isinstance(output, zipfile.ZipFile):
out_zip = zipfile.ZipFile(output, 'w')
date_time = HermeticDateTime(timestamp)
try:
for zip_path, fs_path in input_tuples:
if zip_prefix_path:
zip_path = os.path.join(zip_prefix_path, zip_path)
compress = compress_fn(zip_path) if compress_fn else None
AddToZipHermetic(out_zip,
zip_path,
src_path=fs_path,
compress=compress,
date_time=date_time)
finally:
if output is not out_zip:
out_zip.close() | [
"def",
"DoZip",
"(",
"inputs",
",",
"output",
",",
"base_dir",
"=",
"None",
",",
"compress_fn",
"=",
"None",
",",
"zip_prefix_path",
"=",
"None",
",",
"timestamp",
"=",
"None",
")",
":",
"if",
"base_dir",
"is",
"None",
":",
"base_dir",
"=",
"'.'",
"inp... | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/util/build_utils.py#L472-L519 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/gluon/lipnet/trainer.py | python | Train.run | (self, epochs) | Description : Run training for LipNet | Description : Run training for LipNet | [
"Description",
":",
"Run",
"training",
"for",
"LipNet"
] | def run(self, epochs):
"""
Description : Run training for LipNet
"""
best_loss = sys.maxsize
for epoch in trange(epochs):
iter_no = 0
## train
sum_losses, len_losses = self.train_batch(self.train_dataloader)
if iter_no % 20 == 0:
current_loss = sum_losses / len_losses
print("[Train] epoch:{e} iter:{i} loss:{l:.4f}".format(e=epoch,
i=iter_no,
l=current_loss))
## validating
sum_val_losses, len_val_losses = self.infer_batch(self.valid_dataloader)
current_val_loss = sum_val_losses / len_val_losses
print("[Vaild] epoch:{e} iter:{i} loss:{l:.4f}".format(e=epoch,
i=iter_no,
l=current_val_loss))
if best_loss > current_val_loss:
self.save_model(epoch, current_val_loss)
best_loss = current_val_loss
iter_no += 1 | [
"def",
"run",
"(",
"self",
",",
"epochs",
")",
":",
"best_loss",
"=",
"sys",
".",
"maxsize",
"for",
"epoch",
"in",
"trange",
"(",
"epochs",
")",
":",
"iter_no",
"=",
"0",
"## train",
"sum_losses",
",",
"len_losses",
"=",
"self",
".",
"train_batch",
"("... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/gluon/lipnet/trainer.py#L203-L232 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/twodim_base.py | python | histogram2d | (x, y, bins=10, range=None, normed=None, weights=None,
density=None) | return hist, edges[0], edges[1] | Compute the bi-dimensional histogram of two data samples.
Parameters
----------
x : array_like, shape (N,)
An array containing the x coordinates of the points to be
histogrammed.
y : array_like, shape (N,)
An array containing the y coordinates of the points to be
histogrammed.
bins : int or array_like or [int, int] or [array, array], optional
The bin specification:
* If int, the number of bins for the two dimensions (nx=ny=bins).
* If array_like, the bin edges for the two dimensions
(x_edges=y_edges=bins).
* If [int, int], the number of bins in each dimension
(nx, ny = bins).
* If [array, array], the bin edges in each dimension
(x_edges, y_edges = bins).
* A combination [int, array] or [array, int], where int
is the number of bins and array is the bin edges.
range : array_like, shape(2,2), optional
The leftmost and rightmost edges of the bins along each dimension
(if not specified explicitly in the `bins` parameters):
``[[xmin, xmax], [ymin, ymax]]``. All values outside of this range
will be considered outliers and not tallied in the histogram.
density : bool, optional
If False, the default, returns the number of samples in each bin.
If True, returns the probability *density* function at the bin,
``bin_count / sample_count / bin_area``.
normed : bool, optional
An alias for the density argument that behaves identically. To avoid
confusion with the broken normed argument to `histogram`, `density`
should be preferred.
weights : array_like, shape(N,), optional
An array of values ``w_i`` weighing each sample ``(x_i, y_i)``.
Weights are normalized to 1 if `normed` is True. If `normed` is
False, the values of the returned histogram are equal to the sum of
the weights belonging to the samples falling into each bin.
Returns
-------
H : ndarray, shape(nx, ny)
The bi-dimensional histogram of samples `x` and `y`. Values in `x`
are histogrammed along the first dimension and values in `y` are
histogrammed along the second dimension.
xedges : ndarray, shape(nx+1,)
The bin edges along the first dimension.
yedges : ndarray, shape(ny+1,)
The bin edges along the second dimension.
See Also
--------
histogram : 1D histogram
histogramdd : Multidimensional histogram
Notes
-----
When `normed` is True, then the returned histogram is the sample
density, defined such that the sum over bins of the product
``bin_value * bin_area`` is 1.
Please note that the histogram does not follow the Cartesian convention
where `x` values are on the abscissa and `y` values on the ordinate
axis. Rather, `x` is histogrammed along the first dimension of the
array (vertical), and `y` along the second dimension of the array
(horizontal). This ensures compatibility with `histogramdd`.
Examples
--------
>>> from matplotlib.image import NonUniformImage
>>> import matplotlib.pyplot as plt
Construct a 2-D histogram with variable bin width. First define the bin
edges:
>>> xedges = [0, 1, 3, 5]
>>> yedges = [0, 2, 3, 4, 6]
Next we create a histogram H with random bin content:
>>> x = np.random.normal(2, 1, 100)
>>> y = np.random.normal(1, 1, 100)
>>> H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges))
>>> # Histogram does not follow Cartesian convention (see Notes),
>>> # therefore transpose H for visualization purposes.
>>> H = H.T
:func:`imshow <matplotlib.pyplot.imshow>` can only display square bins:
>>> fig = plt.figure(figsize=(7, 3))
>>> ax = fig.add_subplot(131, title='imshow: square bins')
>>> plt.imshow(H, interpolation='nearest', origin='lower',
... extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
<matplotlib.image.AxesImage object at 0x...>
:func:`pcolormesh <matplotlib.pyplot.pcolormesh>` can display actual edges:
>>> ax = fig.add_subplot(132, title='pcolormesh: actual edges',
... aspect='equal')
>>> X, Y = np.meshgrid(xedges, yedges)
>>> ax.pcolormesh(X, Y, H)
<matplotlib.collections.QuadMesh object at 0x...>
:class:`NonUniformImage <matplotlib.image.NonUniformImage>` can be used to
display actual bin edges with interpolation:
>>> ax = fig.add_subplot(133, title='NonUniformImage: interpolated',
... aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]])
>>> im = NonUniformImage(ax, interpolation='bilinear')
>>> xcenters = (xedges[:-1] + xedges[1:]) / 2
>>> ycenters = (yedges[:-1] + yedges[1:]) / 2
>>> im.set_data(xcenters, ycenters, H)
>>> ax.images.append(im)
>>> plt.show() | Compute the bi-dimensional histogram of two data samples. | [
"Compute",
"the",
"bi",
"-",
"dimensional",
"histogram",
"of",
"two",
"data",
"samples",
"."
] | def histogram2d(x, y, bins=10, range=None, normed=None, weights=None,
density=None):
"""
Compute the bi-dimensional histogram of two data samples.
Parameters
----------
x : array_like, shape (N,)
An array containing the x coordinates of the points to be
histogrammed.
y : array_like, shape (N,)
An array containing the y coordinates of the points to be
histogrammed.
bins : int or array_like or [int, int] or [array, array], optional
The bin specification:
* If int, the number of bins for the two dimensions (nx=ny=bins).
* If array_like, the bin edges for the two dimensions
(x_edges=y_edges=bins).
* If [int, int], the number of bins in each dimension
(nx, ny = bins).
* If [array, array], the bin edges in each dimension
(x_edges, y_edges = bins).
* A combination [int, array] or [array, int], where int
is the number of bins and array is the bin edges.
range : array_like, shape(2,2), optional
The leftmost and rightmost edges of the bins along each dimension
(if not specified explicitly in the `bins` parameters):
``[[xmin, xmax], [ymin, ymax]]``. All values outside of this range
will be considered outliers and not tallied in the histogram.
density : bool, optional
If False, the default, returns the number of samples in each bin.
If True, returns the probability *density* function at the bin,
``bin_count / sample_count / bin_area``.
normed : bool, optional
An alias for the density argument that behaves identically. To avoid
confusion with the broken normed argument to `histogram`, `density`
should be preferred.
weights : array_like, shape(N,), optional
An array of values ``w_i`` weighing each sample ``(x_i, y_i)``.
Weights are normalized to 1 if `normed` is True. If `normed` is
False, the values of the returned histogram are equal to the sum of
the weights belonging to the samples falling into each bin.
Returns
-------
H : ndarray, shape(nx, ny)
The bi-dimensional histogram of samples `x` and `y`. Values in `x`
are histogrammed along the first dimension and values in `y` are
histogrammed along the second dimension.
xedges : ndarray, shape(nx+1,)
The bin edges along the first dimension.
yedges : ndarray, shape(ny+1,)
The bin edges along the second dimension.
See Also
--------
histogram : 1D histogram
histogramdd : Multidimensional histogram
Notes
-----
When `normed` is True, then the returned histogram is the sample
density, defined such that the sum over bins of the product
``bin_value * bin_area`` is 1.
Please note that the histogram does not follow the Cartesian convention
where `x` values are on the abscissa and `y` values on the ordinate
axis. Rather, `x` is histogrammed along the first dimension of the
array (vertical), and `y` along the second dimension of the array
(horizontal). This ensures compatibility with `histogramdd`.
Examples
--------
>>> from matplotlib.image import NonUniformImage
>>> import matplotlib.pyplot as plt
Construct a 2-D histogram with variable bin width. First define the bin
edges:
>>> xedges = [0, 1, 3, 5]
>>> yedges = [0, 2, 3, 4, 6]
Next we create a histogram H with random bin content:
>>> x = np.random.normal(2, 1, 100)
>>> y = np.random.normal(1, 1, 100)
>>> H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges))
>>> # Histogram does not follow Cartesian convention (see Notes),
>>> # therefore transpose H for visualization purposes.
>>> H = H.T
:func:`imshow <matplotlib.pyplot.imshow>` can only display square bins:
>>> fig = plt.figure(figsize=(7, 3))
>>> ax = fig.add_subplot(131, title='imshow: square bins')
>>> plt.imshow(H, interpolation='nearest', origin='lower',
... extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
<matplotlib.image.AxesImage object at 0x...>
:func:`pcolormesh <matplotlib.pyplot.pcolormesh>` can display actual edges:
>>> ax = fig.add_subplot(132, title='pcolormesh: actual edges',
... aspect='equal')
>>> X, Y = np.meshgrid(xedges, yedges)
>>> ax.pcolormesh(X, Y, H)
<matplotlib.collections.QuadMesh object at 0x...>
:class:`NonUniformImage <matplotlib.image.NonUniformImage>` can be used to
display actual bin edges with interpolation:
>>> ax = fig.add_subplot(133, title='NonUniformImage: interpolated',
... aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]])
>>> im = NonUniformImage(ax, interpolation='bilinear')
>>> xcenters = (xedges[:-1] + xedges[1:]) / 2
>>> ycenters = (yedges[:-1] + yedges[1:]) / 2
>>> im.set_data(xcenters, ycenters, H)
>>> ax.images.append(im)
>>> plt.show()
"""
from numpy import histogramdd
try:
N = len(bins)
except TypeError:
N = 1
if N != 1 and N != 2:
xedges = yedges = asarray(bins)
bins = [xedges, yedges]
hist, edges = histogramdd([x, y], bins, range, normed, weights, density)
return hist, edges[0], edges[1] | [
"def",
"histogram2d",
"(",
"x",
",",
"y",
",",
"bins",
"=",
"10",
",",
"range",
"=",
"None",
",",
"normed",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"density",
"=",
"None",
")",
":",
"from",
"numpy",
"import",
"histogramdd",
"try",
":",
"N",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/twodim_base.py#L619-L752 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/locale.py | python | setlocale | (category, locale=None) | return _setlocale(category, locale) | Set the locale for the given category. The locale can be
a string, a locale tuple (language code, encoding), or None.
Locale tuples are converted to strings the locale aliasing
engine. Locale strings are passed directly to the C lib.
category may be given as one of the LC_* values. | Set the locale for the given category. The locale can be
a string, a locale tuple (language code, encoding), or None. | [
"Set",
"the",
"locale",
"for",
"the",
"given",
"category",
".",
"The",
"locale",
"can",
"be",
"a",
"string",
"a",
"locale",
"tuple",
"(",
"language",
"code",
"encoding",
")",
"or",
"None",
"."
] | def setlocale(category, locale=None):
""" Set the locale for the given category. The locale can be
a string, a locale tuple (language code, encoding), or None.
Locale tuples are converted to strings the locale aliasing
engine. Locale strings are passed directly to the C lib.
category may be given as one of the LC_* values.
"""
if locale and type(locale) is not type(""):
# convert to string
locale = normalize(_build_localename(locale))
return _setlocale(category, locale) | [
"def",
"setlocale",
"(",
"category",
",",
"locale",
"=",
"None",
")",
":",
"if",
"locale",
"and",
"type",
"(",
"locale",
")",
"is",
"not",
"type",
"(",
"\"\"",
")",
":",
"# convert to string",
"locale",
"=",
"normalize",
"(",
"_build_localename",
"(",
"l... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/locale.py#L499-L513 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/string.py | python | zfill | (x, width) | return x.zfill(width) | zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated. | zfill(x, width) -> string | [
"zfill",
"(",
"x",
"width",
")",
"-",
">",
"string"
] | def zfill(x, width):
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
"""
if not isinstance(x, basestring):
x = repr(x)
return x.zfill(width) | [
"def",
"zfill",
"(",
"x",
",",
"width",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"basestring",
")",
":",
"x",
"=",
"repr",
"(",
"x",
")",
"return",
"x",
".",
"zfill",
"(",
"width",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/string.py#L458-L467 | |
cinder/Cinder | e83f5bb9c01a63eec20168d02953a0879e5100f7 | docs/libs/pystache/common.py | python | is_string | (obj) | return isinstance(obj, _STRING_TYPES) | Return whether the given object is a byte string or unicode string.
This function is provided for compatibility with both Python 2 and 3
when using 2to3. | Return whether the given object is a byte string or unicode string. | [
"Return",
"whether",
"the",
"given",
"object",
"is",
"a",
"byte",
"string",
"or",
"unicode",
"string",
"."
] | def is_string(obj):
"""
Return whether the given object is a byte string or unicode string.
This function is provided for compatibility with both Python 2 and 3
when using 2to3.
"""
return isinstance(obj, _STRING_TYPES) | [
"def",
"is_string",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"_STRING_TYPES",
")"
] | https://github.com/cinder/Cinder/blob/e83f5bb9c01a63eec20168d02953a0879e5100f7/docs/libs/pystache/common.py#L24-L32 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py | python | CheckedEval | (file_contents) | return CheckNode(c3[0], []) | Return the eval of a gyp file.
The gyp file is restricted to dictionaries and lists only, and
repeated keys are not allowed.
Note that this is slower than eval() is. | Return the eval of a gyp file. | [
"Return",
"the",
"eval",
"of",
"a",
"gyp",
"file",
"."
] | def CheckedEval(file_contents):
"""Return the eval of a gyp file.
The gyp file is restricted to dictionaries and lists only, and
repeated keys are not allowed.
Note that this is slower than eval() is.
"""
ast = compiler.parse(file_contents)
assert isinstance(ast, Module)
c1 = ast.getChildren()
assert c1[0] is None
assert isinstance(c1[1], Stmt)
c2 = c1[1].getChildren()
assert isinstance(c2[0], Discard)
c3 = c2[0].getChildren()
assert len(c3) == 1
return CheckNode(c3[0], []) | [
"def",
"CheckedEval",
"(",
"file_contents",
")",
":",
"ast",
"=",
"compiler",
".",
"parse",
"(",
"file_contents",
")",
"assert",
"isinstance",
"(",
"ast",
",",
"Module",
")",
"c1",
"=",
"ast",
".",
"getChildren",
"(",
")",
"assert",
"c1",
"[",
"0",
"]"... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py#L176-L194 | |
lhmRyan/deep-supervised-hashing-DSH | 631901f82e2ab031fbac33f914a5b08ef8e21d57 | python/caffe/detector.py | python | Detector.detect_windows | (self, images_windows) | return detections | Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net.
Parameters
----------
images_windows: (image filename, window list) iterable.
context_crop: size of context border to crop in pixels.
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts. | Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net. | [
"Do",
"windowed",
"detection",
"over",
"given",
"images",
"and",
"windows",
".",
"Windows",
"are",
"extracted",
"then",
"warped",
"to",
"the",
"input",
"dimensions",
"of",
"the",
"net",
"."
] | def detect_windows(self, images_windows):
"""
Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net.
Parameters
----------
images_windows: (image filename, window list) iterable.
context_crop: size of context border to crop in pixels.
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts.
"""
# Extract windows.
window_inputs = []
for image_fname, windows in images_windows:
image = caffe.io.load_image(image_fname).astype(np.float32)
for window in windows:
window_inputs.append(self.crop(image, window))
# Run through the net (warping windows to input dimensions).
in_ = self.inputs[0]
caffe_in = np.zeros((len(window_inputs), window_inputs[0].shape[2])
+ self.blobs[in_].data.shape[2:],
dtype=np.float32)
for ix, window_in in enumerate(window_inputs):
caffe_in[ix] = self.transformer.preprocess(in_, window_in)
out = self.forward_all(**{in_: caffe_in})
predictions = out[self.outputs[0]].squeeze(axis=(2, 3))
# Package predictions with images and windows.
detections = []
ix = 0
for image_fname, windows in images_windows:
for window in windows:
detections.append({
'window': window,
'prediction': predictions[ix],
'filename': image_fname
})
ix += 1
return detections | [
"def",
"detect_windows",
"(",
"self",
",",
"images_windows",
")",
":",
"# Extract windows.",
"window_inputs",
"=",
"[",
"]",
"for",
"image_fname",
",",
"windows",
"in",
"images_windows",
":",
"image",
"=",
"caffe",
".",
"io",
".",
"load_image",
"(",
"image_fna... | https://github.com/lhmRyan/deep-supervised-hashing-DSH/blob/631901f82e2ab031fbac33f914a5b08ef8e21d57/python/caffe/detector.py#L56-L99 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/nvmpic.py | python | NvmAccessProviderCmsisDapPic.__init__ | (self, transport, device_info, packpath, options="") | :raises: ImportError if packpath is None | :raises: ImportError if packpath is None | [
":",
"raises",
":",
"ImportError",
"if",
"packpath",
"is",
"None"
] | def __init__(self, transport, device_info, packpath, options=""):
"""
:raises: ImportError if packpath is None
"""
self.pic = None
NvmAccessProviderCmsisDapTool.__init__(self, device_info)
self.options = {}
if packpath is None:
raise ImportError("No path to pack repo provided!")
# Each part pack ships its own version of the full script stack, including pyedbglib.
# pyedbglib, and other libraries, can be installed in the local python site-packages
# This path hack puts the part pack path at the front of the python import path
system_path = sys.path
sys.path = [os.path.normpath(packpath)] + sys.path
sys.path = [os.path.normpath(packpath + "//common")] + sys.path
# Create driver for scripted debuggers
self.options['skip_blank_pages'] = True
self.options['overlapped_usb_access'] = False
# This imports the debugger model from the provided packpath so the import must be late
from common.debugprovider import provide_debugger_model # pylint: disable=import-outside-toplevel, import-error
devicename = device_info[DeviceInfoKeys.NAME]
self.pic = provide_debugger_model(devicename)
# Start immediately
self.pic.setup_session(transport, self.options)
self.device_info = device_info
# Start the programming session
if 'pic24' in devicename.lower():
if 'no_pe' in options:
# Only PIC24 devices support Programming Executives
try:
# Force no Programming Executive usage by setting program_pe flag but not configure a
# PE (i.e. not calling set_program_exec)
self.pic.start_programming_operation(program_pe=options['no_pe'])
except TypeError:
# start_programming_operation does not have program_pe argument (i.e. old
# devicesupportscripts without PE support)
self.pic.start_programming_operation()
else:
self.pic.start_programming_operation(program_pe=False)
else:
self.pic.start_programming_operation()
# The stack has been built, revert path hacks
sys.path = system_path | [
"def",
"__init__",
"(",
"self",
",",
"transport",
",",
"device_info",
",",
"packpath",
",",
"options",
"=",
"\"\"",
")",
":",
"self",
".",
"pic",
"=",
"None",
"NvmAccessProviderCmsisDapTool",
".",
"__init__",
"(",
"self",
",",
"device_info",
")",
"self",
"... | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/nvmpic.py#L21-L69 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py | python | generateKScript | (filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript) | Generate a random Kaleidoscope script based on the given parameters | Generate a random Kaleidoscope script based on the given parameters | [
"Generate",
"a",
"random",
"Kaleidoscope",
"script",
"based",
"on",
"the",
"given",
"parameters"
] | def generateKScript(filename, numFuncs, elementsPerFunc, funcsBetweenExec, callWeighting, timingScript):
""" Generate a random Kaleidoscope script based on the given parameters """
print("Generating " + filename)
print(" %d functions, %d elements per function, %d functions between execution" %
(numFuncs, elementsPerFunc, funcsBetweenExec))
print(" Call weighting = %f" % callWeighting)
script = KScriptGenerator(filename)
script.setCallWeighting(callWeighting)
script.writeComment("===========================================================================")
script.writeComment("Auto-generated script")
script.writeComment(" %d functions, %d elements per function, %d functions between execution"
% (numFuncs, elementsPerFunc, funcsBetweenExec))
script.writeComment(" call weighting = %f" % callWeighting)
script.writeComment("===========================================================================")
script.writeEmptyLine()
script.writePredefinedFunctions()
funcsSinceLastExec = 0
for i in range(numFuncs):
script.writeFunction(elementsPerFunc)
funcsSinceLastExec += 1
if funcsSinceLastExec == funcsBetweenExec:
script.writeFunctionCall()
funcsSinceLastExec = 0
# Always end with a function call
if funcsSinceLastExec > 0:
script.writeFunctionCall()
script.writeEmptyLine()
script.writeFinalFunctionCounts()
funcsCalled = len(script.calledFunctions)
print(" Called %d of %d functions, %d total" % (funcsCalled, numFuncs, script.totalCallsExecuted))
timingScript.writeTimingCall(filename, numFuncs, funcsCalled, script.totalCallsExecuted) | [
"def",
"generateKScript",
"(",
"filename",
",",
"numFuncs",
",",
"elementsPerFunc",
",",
"funcsBetweenExec",
",",
"callWeighting",
",",
"timingScript",
")",
":",
"print",
"(",
"\"Generating \"",
"+",
"filename",
")",
"print",
"(",
"\" %d functions, %d elements per fu... | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py#L176-L206 | ||
PixarAnimationStudios/USD | faed18ce62c8736b02413635b584a2f637156bad | pxr/usdImaging/usdviewq/settings2.py | python | Settings._loadState | (self) | Loads and returns application state from a state file. If the file is
not found, contains invalid JSON, does not contain a dictionary, an
empty state is returned instead. | Loads and returns application state from a state file. If the file is
not found, contains invalid JSON, does not contain a dictionary, an
empty state is returned instead. | [
"Loads",
"and",
"returns",
"application",
"state",
"from",
"a",
"state",
"file",
".",
"If",
"the",
"file",
"is",
"not",
"found",
"contains",
"invalid",
"JSON",
"does",
"not",
"contain",
"a",
"dictionary",
"an",
"empty",
"state",
"is",
"returned",
"instead",
... | def _loadState(self):
"""Loads and returns application state from a state file. If the file is
not found, contains invalid JSON, does not contain a dictionary, an
empty state is returned instead.
"""
# Load the dict containing all versions of app state.
if not self._isEphemeral:
try:
with open(self._stateFilePath, "r") as fp:
self._versionsStateBuffer = json.load(fp)
except IOError as e:
if os.path.isfile(self._stateFilePath):
print("Error opening state file: " + str(e), file=sys.stderr)
else:
print("State file not found, a new one will be created.",
file=sys.stderr)
except ValueError:
print("State file contained invalid JSON. Please fix or delete " +
"it. Default settings will be used for this instance of " +
"USDView, but will not be saved.", file=sys.stderr)
self._isEphemeral = True
# Make sure JSON returned a dict.
if not isinstance(self._versionsStateBuffer, dict):
self._versionsStateBuffer = dict()
# Load the correct version of the state dict.
self._stateBuffer = self._versionsStateBuffer.get(self._version, None)
if not isinstance(self._stateBuffer, dict):
self._stateBuffer = dict()
self._versionsStateBuffer[self._version] = self._stateBuffer | [
"def",
"_loadState",
"(",
"self",
")",
":",
"# Load the dict containing all versions of app state.",
"if",
"not",
"self",
".",
"_isEphemeral",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_stateFilePath",
",",
"\"r\"",
")",
"as",
"fp",
":",
"self",
".",... | https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/settings2.py#L207-L238 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/debug/lib/stepper.py | python | NodeStepper.override_tensor | (self, tensor_name, overriding_val) | Override the value of a tensor.
Args:
tensor_name: (str) Name of the tensor to override.
overriding_val: (numpy.ndarray) Overriding tensor value.
Raises:
ValueError: If tensor_name does not correspond to a tensor in the input
tree to the fetched graph element of this stepper instance. | Override the value of a tensor. | [
"Override",
"the",
"value",
"of",
"a",
"tensor",
"."
] | def override_tensor(self, tensor_name, overriding_val):
"""Override the value of a tensor.
Args:
tensor_name: (str) Name of the tensor to override.
overriding_val: (numpy.ndarray) Overriding tensor value.
Raises:
ValueError: If tensor_name does not correspond to a tensor in the input
tree to the fetched graph element of this stepper instance.
"""
if not isinstance(tensor_name, six.string_types):
raise TypeError("Expected type str; got type %s" % type(tensor_name))
node_name = self._get_node_name(tensor_name)
if node_name not in self._transitive_closure_set:
raise ValueError(
"Cannot override tensor \"%s\" because it does not exist in the "
"input tree to the fetch \"%s\"" %
(tensor_name, repr(self._fetch_names)))
self._override_tensors[tensor_name] = overriding_val
# Invalidate cache by tracing outputs.
self._invalidate_transitively_outgoing_cache(tensor_name) | [
"def",
"override_tensor",
"(",
"self",
",",
"tensor_name",
",",
"overriding_val",
")",
":",
"if",
"not",
"isinstance",
"(",
"tensor_name",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected type str; got type %s\"",
"%",
"type",
"(... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/lib/stepper.py#L391-L416 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | samples/ide/activegrid/tool/project.py | python | ProjectFile.RelativeToAbsPath | (self, parentPath) | Used to convert path to absolute path (for any necessary disk access) | Used to convert path to absolute path (for any necessary disk access) | [
"Used",
"to",
"convert",
"path",
"to",
"absolute",
"path",
"(",
"for",
"any",
"necessary",
"disk",
"access",
")"
] | def RelativeToAbsPath(self, parentPath):
""" Used to convert path to absolute path (for any necessary disk access) """
if self.filePath.startswith("./"): # relative to project file
self.filePath = os.path.normpath(os.path.join(parentPath, self.filePath)) | [
"def",
"RelativeToAbsPath",
"(",
"self",
",",
"parentPath",
")",
":",
"if",
"self",
".",
"filePath",
".",
"startswith",
"(",
"\"./\"",
")",
":",
"# relative to project file",
"self",
".",
"filePath",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/ide/activegrid/tool/project.py#L379-L382 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | native_client_sdk/src/build_tools/sdk_tools/sdk_update.py | python | SDKConfig.AddSource | (self, string) | Add a source file to load packages from.
Args:
string: a URL to an external package manifest file. | Add a source file to load packages from. | [
"Add",
"a",
"source",
"file",
"to",
"load",
"packages",
"from",
"."
] | def AddSource(self, string):
'''Add a source file to load packages from.
Args:
string: a URL to an external package manifest file.'''
# For now whitelist only the following location for external sources:
# https://commondatastorage.googleapis.com/nativeclient-mirror/nacl/nacl_sdk
(scheme, host, path, _, _, _) = urlparse.urlparse(string)
if (host != 'commondatastorage.googleapis.com' or
scheme != 'https' or
not path.startswith('/nativeclient-mirror/nacl/nacl_sdk')):
WarningPrint('Only whitelisted sources from '
'\'https://commondatastorage.googleapis.com/nativeclient-'
'mirror/nacl/nacl_sdk\' are currently allowed.')
return
if string in self._data['sources']:
WarningPrint('source \''+string+'\' already exists in config.')
return
try:
url_stream = UrlOpen(string)
except urllib2.URLError:
WarningPrint('Unable to fetch manifest URL \'%s\'. Exiting...' % string)
return
self._data['sources'].append(string)
InfoPrint('source \''+string+'\' added to config.') | [
"def",
"AddSource",
"(",
"self",
",",
"string",
")",
":",
"# For now whitelist only the following location for external sources:",
"# https://commondatastorage.googleapis.com/nativeclient-mirror/nacl/nacl_sdk",
"(",
"scheme",
",",
"host",
",",
"path",
",",
"_",
",",
"_",
",",... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/build_tools/sdk_tools/sdk_update.py#L342-L367 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/copy_helper.py | python | _CreateDigestsFromLocalFile | (logger, algs, file_name, final_file_name,
src_obj_metadata) | return digests | Creates a base64 CRC32C and/or MD5 digest from file_name.
Args:
logger: For outputting log messages.
algs: List of algorithms to compute.
file_name: File to digest.
final_file_name: Permanent location to be used for the downloaded file
after validation (used for logging).
src_obj_metadata: Metadata of source object.
Returns:
Dict of algorithm name : base 64 encoded digest | Creates a base64 CRC32C and/or MD5 digest from file_name. | [
"Creates",
"a",
"base64",
"CRC32C",
"and",
"/",
"or",
"MD5",
"digest",
"from",
"file_name",
"."
] | def _CreateDigestsFromLocalFile(logger, algs, file_name, final_file_name,
src_obj_metadata):
"""Creates a base64 CRC32C and/or MD5 digest from file_name.
Args:
logger: For outputting log messages.
algs: List of algorithms to compute.
file_name: File to digest.
final_file_name: Permanent location to be used for the downloaded file
after validation (used for logging).
src_obj_metadata: Metadata of source object.
Returns:
Dict of algorithm name : base 64 encoded digest
"""
hash_dict = {}
if 'md5' in algs:
hash_dict['md5'] = md5()
if 'crc32c' in algs:
hash_dict['crc32c'] = crcmod.predefined.Crc('crc-32c')
with open(file_name, 'rb') as fp:
CalculateHashesFromContents(
fp, hash_dict, ProgressCallbackWithBackoff(
src_obj_metadata.size,
FileProgressCallbackHandler(
ConstructAnnounceText('Hashing', final_file_name),
logger).call))
digests = {}
for alg_name, digest in hash_dict.iteritems():
digests[alg_name] = Base64EncodeHash(digest.hexdigest())
return digests | [
"def",
"_CreateDigestsFromLocalFile",
"(",
"logger",
",",
"algs",
",",
"file_name",
",",
"final_file_name",
",",
"src_obj_metadata",
")",
":",
"hash_dict",
"=",
"{",
"}",
"if",
"'md5'",
"in",
"algs",
":",
"hash_dict",
"[",
"'md5'",
"]",
"=",
"md5",
"(",
")... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/copy_helper.py#L668-L698 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSVersion.py | python | VisualStudioVersion.SetupScript | (self, target_arch) | Returns a command (with arguments) to be used to set up the
environment. | Returns a command (with arguments) to be used to set up the
environment. | [
"Returns",
"a",
"command",
"(",
"with",
"arguments",
")",
"to",
"be",
"used",
"to",
"set",
"up",
"the",
"environment",
"."
] | def SetupScript(self, target_arch):
"""Returns a command (with arguments) to be used to set up the
environment."""
# Check if we are running in the SDK command line environment and use
# the setup script from the SDK if so. |target_arch| should be either
# 'x86' or 'x64'.
assert target_arch in ('x86', 'x64')
sdk_dir = os.environ.get('WindowsSDKDir')
if self.sdk_based and sdk_dir:
return [os.path.normpath(os.path.join(sdk_dir, 'Bin/SetEnv.Cmd')),
'/' + target_arch]
else:
# We don't use VC/vcvarsall.bat for x86 because vcvarsall calls
# vcvars32, which it can only find if VS??COMNTOOLS is set, which it
# isn't always.
if target_arch == 'x86':
return [os.path.normpath(
os.path.join(self.path, 'Common7/Tools/vsvars32.bat'))]
else:
assert target_arch == 'x64'
arg = 'x86_amd64'
if (os.environ.get('PROCESSOR_ARCHITECTURE') == 'AMD64' or
os.environ.get('PROCESSOR_ARCHITEW6432') == 'AMD64'):
# Use the 64-on-64 compiler if we can.
arg = 'amd64'
return [os.path.normpath(
os.path.join(self.path, 'VC/vcvarsall.bat')), arg] | [
"def",
"SetupScript",
"(",
"self",
",",
"target_arch",
")",
":",
"# Check if we are running in the SDK command line environment and use",
"# the setup script from the SDK if so. |target_arch| should be either",
"# 'x86' or 'x64'.",
"assert",
"target_arch",
"in",
"(",
"'x86'",
",",
... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSVersion.py#L70-L96 | ||
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/mymod.py | python | mymod.OnTimer | (self,id) | Timer event: should only be to update the marquee | Timer event: should only be to update the marquee | [
"Timer",
"event",
":",
"should",
"only",
"be",
"to",
"update",
"the",
"marquee"
] | def OnTimer(self,id):
"Timer event: should only be to update the marquee"
#PtDebugPrint("mymod: timer event id=%d" % (id))
# if this the marquee update?
if id == kMarqueeTimerId:
#PtDebugPrint("mymod: marquee timer hit")
# first erase the last thing we put up
marquee_map.textmap.fillRect( 0, 0, 128, 128, black )
marquee_map.textmap.drawText( 0, 0, self._scrollingtext )
marquee_map.textmap.flush()
# rotate the text
self._scrollingtext = self._scrollingtext[1:] + self._scrollingtext[:1]
# restart the timer
PtAtTimeCallback(self.key,marquee_speed.value,kMarqueeTimerId)
else:
for helper in helperslist:
helper.bump_count | [
"def",
"OnTimer",
"(",
"self",
",",
"id",
")",
":",
"#PtDebugPrint(\"mymod: timer event id=%d\" % (id))",
"# if this the marquee update?",
"if",
"id",
"==",
"kMarqueeTimerId",
":",
"#PtDebugPrint(\"mymod: marquee timer hit\")",
"# first erase the last thing we put up",
"marquee_map... | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/mymod.py#L137-L153 | ||
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/grassprovider/ext/v_net_distance.py | python | processCommand | (alg, parameters, context, feedback) | Handle data preparation for v.net.distance:
* Integrate point layers into network vector map.
* Make v.net.distance use those layers.
* Delete the threshold parameter.
* If where statement, connect to the db | Handle data preparation for v.net.distance:
* Integrate point layers into network vector map.
* Make v.net.distance use those layers.
* Delete the threshold parameter.
* If where statement, connect to the db | [
"Handle",
"data",
"preparation",
"for",
"v",
".",
"net",
".",
"distance",
":",
"*",
"Integrate",
"point",
"layers",
"into",
"network",
"vector",
"map",
".",
"*",
"Make",
"v",
".",
"net",
".",
"distance",
"use",
"those",
"layers",
".",
"*",
"Delete",
"t... | def processCommand(alg, parameters, context, feedback):
""" Handle data preparation for v.net.distance:
* Integrate point layers into network vector map.
* Make v.net.distance use those layers.
* Delete the threshold parameter.
* If where statement, connect to the db
"""
# Grab the point layer and delete this parameter
lineLayer = alg.exportedLayers['input']
fromLayer = alg.exportedLayers['flayer']
toLayer = alg.exportedLayers['tlayer']
intLayer = 'bufnet' + os.path.basename(getTempFilename())
netLayer = 'net' + os.path.basename(getTempFilename())
threshold = alg.parameterAsDouble(parameters, 'threshold', context)
# Create the v.net connect command for from_layer integration
command = 'v.net -s input={} points={} output={} operation=connect threshold={} arc_layer=1 node_layer=2'.format(
lineLayer, fromLayer, intLayer, threshold)
alg.commands.append(command)
# Do it again with to_layer
command = 'v.net -s input={} points={} output={} operation=connect threshold={} arc_layer=1 node_layer=3'.format(
intLayer, toLayer, netLayer, threshold)
alg.commands.append(command)
# Connect the point layer database to the layer 2 of the network
command = 'v.db.connect -o map={} table={} layer=2'.format(netLayer, fromLayer)
alg.commands.append(command)
command = 'v.db.connect -o map={} table={} layer=3'.format(netLayer, toLayer)
alg.commands.append(command)
# remove undesired parameters
alg.removeParameter('flayer')
alg.removeParameter('tlayer')
alg.removeParameter('threshold')
alg.exportedLayers['input'] = netLayer
# Add the two new parameters
fLayer = QgsProcessingParameterString('from_layer', None, 2, False, False)
alg.addParameter(fLayer)
tLayer = QgsProcessingParameterString('to_layer', None, 3, False, False)
alg.addParameter(tLayer)
alg.processCommand(parameters, context, feedback) | [
"def",
"processCommand",
"(",
"alg",
",",
"parameters",
",",
"context",
",",
"feedback",
")",
":",
"# Grab the point layer and delete this parameter",
"lineLayer",
"=",
"alg",
".",
"exportedLayers",
"[",
"'input'",
"]",
"fromLayer",
"=",
"alg",
".",
"exportedLayers"... | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/grassprovider/ext/v_net_distance.py#L30-L73 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/typing/npydecl.py | python | _parse_nested_sequence | (context, typ) | Parse a (possibly 0d) nested sequence type.
A (ndim, dtype) tuple is returned. Note the sequence may still be
heterogeneous, as long as it converts to the given dtype. | Parse a (possibly 0d) nested sequence type.
A (ndim, dtype) tuple is returned. Note the sequence may still be
heterogeneous, as long as it converts to the given dtype. | [
"Parse",
"a",
"(",
"possibly",
"0d",
")",
"nested",
"sequence",
"type",
".",
"A",
"(",
"ndim",
"dtype",
")",
"tuple",
"is",
"returned",
".",
"Note",
"the",
"sequence",
"may",
"still",
"be",
"heterogeneous",
"as",
"long",
"as",
"it",
"converts",
"to",
"... | def _parse_nested_sequence(context, typ):
"""
Parse a (possibly 0d) nested sequence type.
A (ndim, dtype) tuple is returned. Note the sequence may still be
heterogeneous, as long as it converts to the given dtype.
"""
if isinstance(typ, (types.Buffer,)):
raise TypingError("%r not allowed in a homogeneous sequence" % typ)
elif isinstance(typ, (types.Sequence,)):
n, dtype = _parse_nested_sequence(context, typ.dtype)
return n + 1, dtype
elif isinstance(typ, (types.BaseTuple,)):
if typ.count == 0:
# Mimick Numpy's behaviour
return 1, types.float64
n, dtype = _parse_nested_sequence(context, typ[0])
dtypes = [dtype]
for i in range(1, typ.count):
_n, dtype = _parse_nested_sequence(context, typ[i])
if _n != n:
raise TypingError("type %r does not have a regular shape"
% (typ,))
dtypes.append(dtype)
dtype = context.unify_types(*dtypes)
if dtype is None:
raise TypingError("cannot convert %r to a homogeneous type" % typ)
return n + 1, dtype
else:
# Scalar type => check it's valid as a Numpy array dtype
as_dtype(typ)
return 0, typ | [
"def",
"_parse_nested_sequence",
"(",
"context",
",",
"typ",
")",
":",
"if",
"isinstance",
"(",
"typ",
",",
"(",
"types",
".",
"Buffer",
",",
")",
")",
":",
"raise",
"TypingError",
"(",
"\"%r not allowed in a homogeneous sequence\"",
"%",
"typ",
")",
"elif",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/typing/npydecl.py#L465-L495 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/tracking/util.py | python | InitializationOnlyStatus.assert_nontrivial_match | (self) | Assertion for consistency with `CheckpointLoadStatus`. Always fails. | Assertion for consistency with `CheckpointLoadStatus`. Always fails. | [
"Assertion",
"for",
"consistency",
"with",
"CheckpointLoadStatus",
".",
"Always",
"fails",
"."
] | def assert_nontrivial_match(self):
"""Assertion for consistency with `CheckpointLoadStatus`. Always fails."""
raise AssertionError(
"No checkpoint specified (save_path=None); nothing is being restored.") | [
"def",
"assert_nontrivial_match",
"(",
"self",
")",
":",
"raise",
"AssertionError",
"(",
"\"No checkpoint specified (save_path=None); nothing is being restored.\"",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/tracking/util.py#L866-L869 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/clang_format.py | python | _format_files | (clang_format, files) | Format a list of files with clang-format | Format a list of files with clang-format | [
"Format",
"a",
"list",
"of",
"files",
"with",
"clang",
"-",
"format"
] | def _format_files(clang_format, files):
"""Format a list of files with clang-format
"""
clang_format = ClangFormat(clang_format, _get_build_dir())
format_clean = parallel.parallel_process([os.path.abspath(f) for f in files],
clang_format.format)
if not format_clean:
print("ERROR: failed to format files")
sys.exit(1) | [
"def",
"_format_files",
"(",
"clang_format",
",",
"files",
")",
":",
"clang_format",
"=",
"ClangFormat",
"(",
"clang_format",
",",
"_get_build_dir",
"(",
")",
")",
"format_clean",
"=",
"parallel",
".",
"parallel_process",
"(",
"[",
"os",
".",
"path",
".",
"a... | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/clang_format.py#L335-L345 | ||
cielavenir/procon | 81aa949a1313999803eefbb2efebca516a779b7f | hackerrank/hash-length-extension.py | python | XX | (func, a, b, c, d, x, s, ac) | return res & 0xffffffffL | Wrapper for call distribution to functions F, G, H and I.
This replaces functions FF, GG, HH and II from "Appl. Crypto.
Rotation is separate from addition to prevent recomputation
(now summed-up in one function). | Wrapper for call distribution to functions F, G, H and I. | [
"Wrapper",
"for",
"call",
"distribution",
"to",
"functions",
"F",
"G",
"H",
"and",
"I",
"."
] | def XX(func, a, b, c, d, x, s, ac):
"""Wrapper for call distribution to functions F, G, H and I.
This replaces functions FF, GG, HH and II from "Appl. Crypto.
Rotation is separate from addition to prevent recomputation
(now summed-up in one function).
"""
res = 0L
res = res + a + func(b, c, d)
res = res + x
res = res + ac
res = res & 0xffffffffL
res = _rotateLeft(res, s)
res = res & 0xffffffffL
res = res + b
return res & 0xffffffffL | [
"def",
"XX",
"(",
"func",
",",
"a",
",",
"b",
",",
"c",
",",
"d",
",",
"x",
",",
"s",
",",
"ac",
")",
":",
"res",
"=",
"0L",
"res",
"=",
"res",
"+",
"a",
"+",
"func",
"(",
"b",
",",
"c",
",",
"d",
")",
"res",
"=",
"res",
"+",
"x",
"... | https://github.com/cielavenir/procon/blob/81aa949a1313999803eefbb2efebca516a779b7f/hackerrank/hash-length-extension.py#L128-L145 | |
cztomczak/cefpython | 5679f28cec18a57a56e298da2927aac8d8f83ad6 | tools/build.py | python | fix_cefpython_api_header_file | () | This function does two things: 1) Disable warnings in cefpython
API header file and 2) Make a copy named cefpython_pyXX_fixed.h,
this copy will be used by C++ projects and its modification time
won't change every time you run build.py script, thus C++ won't
rebuild each time. | This function does two things: 1) Disable warnings in cefpython
API header file and 2) Make a copy named cefpython_pyXX_fixed.h,
this copy will be used by C++ projects and its modification time
won't change every time you run build.py script, thus C++ won't
rebuild each time. | [
"This",
"function",
"does",
"two",
"things",
":",
"1",
")",
"Disable",
"warnings",
"in",
"cefpython",
"API",
"header",
"file",
"and",
"2",
")",
"Make",
"a",
"copy",
"named",
"cefpython_pyXX_fixed",
".",
"h",
"this",
"copy",
"will",
"be",
"used",
"by",
"C... | def fix_cefpython_api_header_file():
"""This function does two things: 1) Disable warnings in cefpython
API header file and 2) Make a copy named cefpython_pyXX_fixed.h,
this copy will be used by C++ projects and its modification time
won't change every time you run build.py script, thus C++ won't
rebuild each time."""
# Fix cefpython_pyXX.h to disable this warning:
# > warning: 'somefunc' has C-linkage specified, but returns
# > user-defined type 'sometype' which is incompatible with C
# On Mac this warning must be disabled using -Wno-return-type-c-linkage
# flag in makefiles.
print("[build.py] Fix cefpython API header file in the build_cefpython/"
" directory")
if not os.path.exists(CEFPYTHON_API_HFILE):
assert not os.path.exists(CEFPYTHON_API_HFILE_FIXED)
print("[build.py] cefpython API header file was not yet generated")
return
# Original contents
with open(CEFPYTHON_API_HFILE, "rb") as fo:
contents = fo.read().decode("utf-8")
# Pragma fix on Windows
if WINDOWS:
pragma = "#pragma warning(disable:4190)"
if pragma in contents:
print("[build.py] cefpython API header file is already fixed")
else:
contents = ("%s\n\n" % pragma) + contents
with open(CEFPYTHON_API_HFILE, "wb") as fo:
fo.write(contents.encode("utf-8"))
print("[build.py] Save {filename}"
.format(filename=CEFPYTHON_API_HFILE))
# Make a copy with a "_fixed" postfix
if os.path.exists(CEFPYTHON_API_HFILE_FIXED):
with open(CEFPYTHON_API_HFILE_FIXED, "rb") as fo:
contents_fixed = fo.read().decode("utf-8")
else:
contents_fixed = ""
# Resave fixed copy only if contents changed. Other scripts
# depend on "modified time" of the "_fixed" file.
if contents != contents_fixed:
print("[build.py] Save cefpython_fixed.h")
with open(CEFPYTHON_API_HFILE_FIXED, "wb") as fo:
fo.write(contents.encode("utf-8")) | [
"def",
"fix_cefpython_api_header_file",
"(",
")",
":",
"# Fix cefpython_pyXX.h to disable this warning:",
"# > warning: 'somefunc' has C-linkage specified, but returns",
"# > user-defined type 'sometype' which is incompatible with C",
"# On Mac this warning must be disabled using -Wno-return-type-c-... | https://github.com/cztomczak/cefpython/blob/5679f28cec18a57a56e298da2927aac8d8f83ad6/tools/build.py#L352-L400 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/distutils/fcompiler/__init__.py | python | FCompiler._compile | (self, obj, src, ext, cc_args, extra_postargs, pp_opts) | Compile 'src' to product 'obj'. | Compile 'src' to product 'obj'. | [
"Compile",
"src",
"to",
"product",
"obj",
"."
] | def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
"""Compile 'src' to product 'obj'."""
src_flags = {}
if is_f_file(src) and not has_f90_header(src):
flavor = ':f77'
compiler = self.compiler_f77
src_flags = get_f77flags(src)
extra_compile_args = self.extra_f77_compile_args or []
elif is_free_format(src):
flavor = ':f90'
compiler = self.compiler_f90
if compiler is None:
raise DistutilsExecError('f90 not supported by %s needed for %s'\
% (self.__class__.__name__, src))
extra_compile_args = self.extra_f90_compile_args or []
else:
flavor = ':fix'
compiler = self.compiler_fix
if compiler is None:
raise DistutilsExecError('f90 (fixed) not supported by %s needed for %s'\
% (self.__class__.__name__, src))
extra_compile_args = self.extra_f90_compile_args or []
if self.object_switch[-1]==' ':
o_args = [self.object_switch.strip(), obj]
else:
o_args = [self.object_switch.strip()+obj]
assert self.compile_switch.strip()
s_args = [self.compile_switch, src]
if extra_compile_args:
log.info('extra %s options: %r' \
% (flavor[1:], ' '.join(extra_compile_args)))
extra_flags = src_flags.get(self.compiler_type, [])
if extra_flags:
log.info('using compile options from source: %r' \
% ' '.join(extra_flags))
command = compiler + cc_args + extra_flags + s_args + o_args \
+ extra_postargs + extra_compile_args
display = '%s: %s' % (os.path.basename(compiler[0]) + flavor,
src)
try:
self.spawn(command, display=display)
except DistutilsExecError as e:
msg = str(e)
raise CompileError(msg) from None | [
"def",
"_compile",
"(",
"self",
",",
"obj",
",",
"src",
",",
"ext",
",",
"cc_args",
",",
"extra_postargs",
",",
"pp_opts",
")",
":",
"src_flags",
"=",
"{",
"}",
"if",
"is_f_file",
"(",
"src",
")",
"and",
"not",
"has_f90_header",
"(",
"src",
")",
":",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/fcompiler/__init__.py#L565-L613 | ||
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py | python | RepeatedCompositeProperty | (cdescriptor, message_type) | return property(Getter, Setter, doc=doc) | Returns a Python property for the given repeated composite field. | Returns a Python property for the given repeated composite field. | [
"Returns",
"a",
"Python",
"property",
"for",
"the",
"given",
"repeated",
"composite",
"field",
"."
] | def RepeatedCompositeProperty(cdescriptor, message_type):
"""Returns a Python property for the given repeated composite field."""
def Getter(self):
container = self._composite_fields.get(cdescriptor.name, None)
if container is None:
container = RepeatedCompositeContainer(
self, cdescriptor, message_type._concrete_class)
self._composite_fields[cdescriptor.name] = container
return container
def Setter(self, new_value):
raise AttributeError('Assignment not allowed to repeated field '
'"%s" in protocol message object.' % cdescriptor.name)
doc = 'Magic attribute generated for "%s" proto field.' % cdescriptor.name
return property(Getter, Setter, doc=doc) | [
"def",
"RepeatedCompositeProperty",
"(",
"cdescriptor",
",",
"message_type",
")",
":",
"def",
"Getter",
"(",
"self",
")",
":",
"container",
"=",
"self",
".",
"_composite_fields",
".",
"get",
"(",
"cdescriptor",
".",
"name",
",",
"None",
")",
"if",
"container... | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py#L274-L290 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/lite/python/lite.py | python | TFLiteConverterBase._parse_saved_model_args | (self, always_enable_saved_model_import=False) | Parses SavedModel arguments from the given Keras/RNN SavedModel.
Args:
always_enable_saved_model_import: Bool. When the value is true, it enables
MLIR saved model import path regardless of checking the conditions. | Parses SavedModel arguments from the given Keras/RNN SavedModel. | [
"Parses",
"SavedModel",
"arguments",
"from",
"the",
"given",
"Keras",
"/",
"RNN",
"SavedModel",
"."
] | def _parse_saved_model_args(self, always_enable_saved_model_import=False):
"""Parses SavedModel arguments from the given Keras/RNN SavedModel.
Args:
always_enable_saved_model_import: Bool. When the value is true, it enables
MLIR saved model import path regardless of checking the conditions.
"""
if not self.experimental_new_converter:
self.saved_model_dir = None
return
if self.saved_model_dir:
try:
saved_model_proto, _ = (
_parse_saved_model_with_debug_info(self.saved_model_dir))
except OSError:
# If it fails to read the given saved model, it will fall back to the
# frozen graph def path.
self.saved_model_dir = None
return
if (not always_enable_saved_model_import and
not self._contains_function_with_implements_attr(saved_model_proto)):
self.saved_model_dir = None
return
if not self._saved_model_exported_names:
self._saved_model_exported_names = []
self._saved_model_version = saved_model_proto.saved_model_schema_version
if self._saved_model_version == 0:
self.saved_model_dir = None
logging.warning("SavedModel schema version is zero.")
return
if self._saved_model_version not in [1, 2]:
raise ValueError("SavedModel file format({0}) is not supported".format(
self._saved_model_version)) | [
"def",
"_parse_saved_model_args",
"(",
"self",
",",
"always_enable_saved_model_import",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"experimental_new_converter",
":",
"self",
".",
"saved_model_dir",
"=",
"None",
"return",
"if",
"self",
".",
"saved_model_dir",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/lite.py#L690-L723 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/queues/feeding_queue_runner.py | python | FeedingQueueRunner._run | (self, sess, enqueue_op, feed_fn, coord=None) | Execute the enqueue op in a loop, close the queue in case of error.
Args:
sess: A `Session`.
enqueue_op: The `Operation` to run.
feed_fn: the feed function to pass to `sess.run`.
coord: Optional `Coordinator` object for reporting errors and checking
for stop conditions. | Execute the enqueue op in a loop, close the queue in case of error. | [
"Execute",
"the",
"enqueue",
"op",
"in",
"a",
"loop",
"close",
"the",
"queue",
"in",
"case",
"of",
"error",
"."
] | def _run(self, sess, enqueue_op, feed_fn, coord=None):
"""Execute the enqueue op in a loop, close the queue in case of error.
Args:
sess: A `Session`.
enqueue_op: The `Operation` to run.
feed_fn: the feed function to pass to `sess.run`.
coord: Optional `Coordinator` object for reporting errors and checking
for stop conditions.
"""
# TODO(jamieas): Reduce code duplication with `QueueRunner`.
decremented = False
try:
while True:
if coord and coord.should_stop():
break
try:
feed_dict = None if feed_fn is None else feed_fn()
sess.run(enqueue_op, feed_dict=feed_dict)
except errors.OutOfRangeError:
# This exception indicates that a queue was closed.
with self._lock:
self._runs -= 1
decremented = True
if self._runs == 0:
try:
sess.run(self._close_op)
except Exception as e:
# Intentionally ignore errors from close_op.
logging.vlog(1, "Ignored exception: %s", str(e))
return
except Exception as e:
# This catches all other exceptions.
if coord:
coord.request_stop(e)
else:
logging.error("Exception in QueueRunner: %s", str(e))
with self._lock:
self._exceptions_raised.append(e)
raise
finally:
# Make sure we account for all terminations: normal or errors.
if not decremented:
with self._lock:
self._runs -= 1 | [
"def",
"_run",
"(",
"self",
",",
"sess",
",",
"enqueue_op",
",",
"feed_fn",
",",
"coord",
"=",
"None",
")",
":",
"# TODO(jamieas): Reduce code duplication with `QueueRunner`.",
"decremented",
"=",
"False",
"try",
":",
"while",
"True",
":",
"if",
"coord",
"and",
... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/queues/feeding_queue_runner.py#L64-L109 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/toeplitz-matrix.py | python | Solution2.isToeplitzMatrix | (self, matrix) | return True | :type matrix: List[List[int]]
:rtype: bool | :type matrix: List[List[int]]
:rtype: bool | [
":",
"type",
"matrix",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"bool"
] | def isToeplitzMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
for row_index, row in enumerate(matrix):
for digit_index, digit in enumerate(row):
if not row_index or not digit_index:
continue
if matrix[row_index - 1][digit_index - 1] != digit:
return False
return True | [
"def",
"isToeplitzMatrix",
"(",
"self",
",",
"matrix",
")",
":",
"for",
"row_index",
",",
"row",
"in",
"enumerate",
"(",
"matrix",
")",
":",
"for",
"digit_index",
",",
"digit",
"in",
"enumerate",
"(",
"row",
")",
":",
"if",
"not",
"row_index",
"or",
"n... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/toeplitz-matrix.py#L16-L27 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/client/timeline.py | python | _ChromeTraceFormatter.emit_counter | (self, category, name, pid, timestamp, counter, value) | Emits a record for a single counter.
Args:
category: The event category as a string.
name: The event name as a string.
pid: Identifier of the process generating this event as an integer.
timestamp: The timestamp of this event as a long integer.
counter: Name of the counter as a string.
value: Value of the counter as an integer. | Emits a record for a single counter. | [
"Emits",
"a",
"record",
"for",
"a",
"single",
"counter",
"."
] | def emit_counter(self, category, name, pid, timestamp, counter, value):
"""Emits a record for a single counter.
Args:
category: The event category as a string.
name: The event name as a string.
pid: Identifier of the process generating this event as an integer.
timestamp: The timestamp of this event as a long integer.
counter: Name of the counter as a string.
value: Value of the counter as an integer.
"""
event = self._create_event('C', category, name, pid, 0, timestamp)
event['args'] = {counter: value}
self._events.append(event) | [
"def",
"emit_counter",
"(",
"self",
",",
"category",
",",
"name",
",",
"pid",
",",
"timestamp",
",",
"counter",
",",
"value",
")",
":",
"event",
"=",
"self",
".",
"_create_event",
"(",
"'C'",
",",
"category",
",",
"name",
",",
"pid",
",",
"0",
",",
... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/client/timeline.py#L218-L231 | ||
adnanaziz/epicode | e81d4387d2ae442d21631dfc958690d424e1d84d | cpp/cpplint.py | python | IsCppString | (line) | return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 | Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant. | Does line terminate so, that the next symbol is in string constant. | [
"Does",
"line",
"terminate",
"so",
"that",
"the",
"next",
"symbol",
"is",
"in",
"string",
"constant",
"."
] | def IsCppString(line):
"""Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant.
"""
line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 | [
"def",
"IsCppString",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"r'\\\\'",
",",
"'XX'",
")",
"# after this, \\\\\" does not match to \\\"",
"return",
"(",
"(",
"line",
".",
"count",
"(",
"'\"'",
")",
"-",
"line",
".",
"count",
"(",
... | https://github.com/adnanaziz/epicode/blob/e81d4387d2ae442d21631dfc958690d424e1d84d/cpp/cpplint.py#L846-L860 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/ops/seq2seq_ops.py | python | rnn_decoder | (decoder_inputs, initial_state, cell, scope=None) | return outputs, states, sampling_outputs, sampling_states | RNN Decoder that creates training and sampling sub-graphs.
Args:
decoder_inputs: Inputs for decoder, list of tensors.
This is used only in training sub-graph.
initial_state: Initial state for the decoder.
cell: RNN cell to use for decoder.
scope: Scope to use, if None new will be produced.
Returns:
List of tensors for outputs and states for training and sampling sub-graphs. | RNN Decoder that creates training and sampling sub-graphs. | [
"RNN",
"Decoder",
"that",
"creates",
"training",
"and",
"sampling",
"sub",
"-",
"graphs",
"."
] | def rnn_decoder(decoder_inputs, initial_state, cell, scope=None):
"""RNN Decoder that creates training and sampling sub-graphs.
Args:
decoder_inputs: Inputs for decoder, list of tensors.
This is used only in training sub-graph.
initial_state: Initial state for the decoder.
cell: RNN cell to use for decoder.
scope: Scope to use, if None new will be produced.
Returns:
List of tensors for outputs and states for training and sampling sub-graphs.
"""
with vs.variable_scope(scope or "dnn_decoder"):
states, sampling_states = [initial_state], [initial_state]
outputs, sampling_outputs = [], []
with ops.name_scope("training", values=[decoder_inputs, initial_state]):
for i, inp in enumerate(decoder_inputs):
if i > 0:
vs.get_variable_scope().reuse_variables()
output, new_state = cell(inp, states[-1])
outputs.append(output)
states.append(new_state)
with ops.name_scope("sampling", values=[initial_state]):
for i, _ in enumerate(decoder_inputs):
if i == 0:
sampling_outputs.append(outputs[i])
sampling_states.append(states[i])
else:
sampling_output, sampling_state = cell(sampling_outputs[-1],
sampling_states[-1])
sampling_outputs.append(sampling_output)
sampling_states.append(sampling_state)
return outputs, states, sampling_outputs, sampling_states | [
"def",
"rnn_decoder",
"(",
"decoder_inputs",
",",
"initial_state",
",",
"cell",
",",
"scope",
"=",
"None",
")",
":",
"with",
"vs",
".",
"variable_scope",
"(",
"scope",
"or",
"\"dnn_decoder\"",
")",
":",
"states",
",",
"sampling_states",
"=",
"[",
"initial_st... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/ops/seq2seq_ops.py#L90-L123 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/tclib.py | python | Message.HasAssignedId | (self) | return bool(self.assigned_id) | Returns True if this message has an assigned id. | Returns True if this message has an assigned id. | [
"Returns",
"True",
"if",
"this",
"message",
"has",
"an",
"assigned",
"id",
"."
] | def HasAssignedId(self):
'''Returns True if this message has an assigned id.'''
return bool(self.assigned_id) | [
"def",
"HasAssignedId",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"assigned_id",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/tclib.py#L176-L178 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/operators/exceptions.py | python | assert_stmt | (expression1, expression2) | Functional form of an assert statement.
This follows the semantics of the Python assert statement, however the
concrete implementations may deviate from it. See the respective
implementation for details.
In general, the assert statement should not be used for control flow.
Furthermore, it is encouraged that the assertion expressions should not have
side effects.
Args:
expression1: Any
expression2: Callable[[], Any], returns the expression to include in the
error message when expression1 evaluates to False. When expression1 is
True, the result of expression2 will not be evaluated, however,
expression2 itself may be evaluated in some implementations.
Returns:
Any, implementation-dependent.
Raises:
ValueError: if any arguments are illegal. | Functional form of an assert statement. | [
"Functional",
"form",
"of",
"an",
"assert",
"statement",
"."
] | def assert_stmt(expression1, expression2):
"""Functional form of an assert statement.
This follows the semantics of the Python assert statement, however the
concrete implementations may deviate from it. See the respective
implementation for details.
In general, the assert statement should not be used for control flow.
Furthermore, it is encouraged that the assertion expressions should not have
side effects.
Args:
expression1: Any
expression2: Callable[[], Any], returns the expression to include in the
error message when expression1 evaluates to False. When expression1 is
True, the result of expression2 will not be evaluated, however,
expression2 itself may be evaluated in some implementations.
Returns:
Any, implementation-dependent.
Raises:
ValueError: if any arguments are illegal.
"""
if not callable(expression2):
raise ValueError('{} must be a callable'.format(expression2))
args, _, keywords, _ = tf_inspect.getargspec(expression2)
if args or keywords:
raise ValueError('{} may not have any arguments'.format(expression2))
if tensor_util.is_tensor(expression1):
return _tf_assert_stmt(expression1, expression2)
else:
return _py_assert_stmt(expression1, expression2) | [
"def",
"assert_stmt",
"(",
"expression1",
",",
"expression2",
")",
":",
"if",
"not",
"callable",
"(",
"expression2",
")",
":",
"raise",
"ValueError",
"(",
"'{} must be a callable'",
".",
"format",
"(",
"expression2",
")",
")",
"args",
",",
"_",
",",
"keyword... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/operators/exceptions.py#L26-L59 | ||
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | adodbapi/adodbapi.py | python | Connection.commit | (self) | Commit any pending transaction to the database.
Note that if the database supports an auto-commit feature,
this must be initially off. An interface method may be provided to turn it back on.
Database modules that do not support transactions should implement this method with void functionality. | Commit any pending transaction to the database. | [
"Commit",
"any",
"pending",
"transaction",
"to",
"the",
"database",
"."
] | def commit(self):
"""Commit any pending transaction to the database.
Note that if the database supports an auto-commit feature,
this must be initially off. An interface method may be provided to turn it back on.
Database modules that do not support transactions should implement this method with void functionality.
"""
self.messages = []
if not self.supportsTransactions:
return
try:
self.transaction_level = self.connector.CommitTrans()
if verbose > 1:
print("commit done on connection at %X" % id(self))
if not (
self._autocommit
or (self.connector.Attributes & adc.adXactAbortRetaining)
):
# If attributes has adXactCommitRetaining it performs retaining commits that is,
# calling CommitTrans automatically starts a new transaction. Not all providers support this.
# If not, we will have to start a new transaction by this command:
self.transaction_level = self.connector.BeginTrans()
except Exception as e:
self._raiseConnectionError(api.ProgrammingError, e) | [
"def",
"commit",
"(",
"self",
")",
":",
"self",
".",
"messages",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"supportsTransactions",
":",
"return",
"try",
":",
"self",
".",
"transaction_level",
"=",
"self",
".",
"connector",
".",
"CommitTrans",
"(",
")",
... | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/adodbapi/adodbapi.py#L383-L407 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | uCSIsPrivateUseArea | (code) | return ret | Check whether the character is part of PrivateUseArea UCS
Block | Check whether the character is part of PrivateUseArea UCS
Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"PrivateUseArea",
"UCS",
"Block"
] | def uCSIsPrivateUseArea(code):
"""Check whether the character is part of PrivateUseArea UCS
Block """
ret = libxml2mod.xmlUCSIsPrivateUseArea(code)
return ret | [
"def",
"uCSIsPrivateUseArea",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsPrivateUseArea",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L2040-L2044 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | HtmlListBox.Create | (*args, **kwargs) | return _windows_.HtmlListBox_Create(*args, **kwargs) | Create(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=VListBoxNameStr) -> bool | Create(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=VListBoxNameStr) -> bool | [
"Create",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"ID_ANY",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"0",
"String",
"name",
"=",
"VListBoxNameStr",
")",
"-",
">",
"bool"
] | def Create(*args, **kwargs):
"""
Create(self, Window parent, int id=ID_ANY, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=VListBoxNameStr) -> bool
"""
return _windows_.HtmlListBox_Create(*args, **kwargs) | [
"def",
"Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"HtmlListBox_Create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L2734-L2739 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/fixes/fix_import.py | python | traverse_imports | (names) | Walks over all the names imported in a dotted_as_names node. | Walks over all the names imported in a dotted_as_names node. | [
"Walks",
"over",
"all",
"the",
"names",
"imported",
"in",
"a",
"dotted_as_names",
"node",
"."
] | def traverse_imports(names):
"""
Walks over all the names imported in a dotted_as_names node.
"""
pending = [names]
while pending:
node = pending.pop()
if node.type == token.NAME:
yield node.value
elif node.type == syms.dotted_name:
yield "".join([ch.value for ch in node.children])
elif node.type == syms.dotted_as_name:
pending.append(node.children[0])
elif node.type == syms.dotted_as_names:
pending.extend(node.children[::-2])
else:
raise AssertionError("unkown node type") | [
"def",
"traverse_imports",
"(",
"names",
")",
":",
"pending",
"=",
"[",
"names",
"]",
"while",
"pending",
":",
"node",
"=",
"pending",
".",
"pop",
"(",
")",
"if",
"node",
".",
"type",
"==",
"token",
".",
"NAME",
":",
"yield",
"node",
".",
"value",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/fixes/fix_import.py#L19-L35 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/scimath.py | python | _fix_real_abs_gt_1 | (x) | return x | Convert `x` to complex if it has real components x_i with abs(x_i)>1.
Otherwise, output is just the array version of the input (via asarray).
Parameters
----------
x : array_like
Returns
-------
array
Examples
--------
>>> np.lib.scimath._fix_real_abs_gt_1([0,1])
array([0, 1])
>>> np.lib.scimath._fix_real_abs_gt_1([0,2])
array([0.+0.j, 2.+0.j]) | Convert `x` to complex if it has real components x_i with abs(x_i)>1. | [
"Convert",
"x",
"to",
"complex",
"if",
"it",
"has",
"real",
"components",
"x_i",
"with",
"abs",
"(",
"x_i",
")",
">",
"1",
"."
] | def _fix_real_abs_gt_1(x):
"""Convert `x` to complex if it has real components x_i with abs(x_i)>1.
Otherwise, output is just the array version of the input (via asarray).
Parameters
----------
x : array_like
Returns
-------
array
Examples
--------
>>> np.lib.scimath._fix_real_abs_gt_1([0,1])
array([0, 1])
>>> np.lib.scimath._fix_real_abs_gt_1([0,2])
array([0.+0.j, 2.+0.j])
"""
x = asarray(x)
if any(isreal(x) & (abs(x) > 1)):
x = _tocomplex(x)
return x | [
"def",
"_fix_real_abs_gt_1",
"(",
"x",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
")",
"if",
"any",
"(",
"isreal",
"(",
"x",
")",
"&",
"(",
"abs",
"(",
"x",
")",
">",
"1",
")",
")",
":",
"x",
"=",
"_tocomplex",
"(",
"x",
")",
"return",
"x"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/scimath.py#L154-L178 | |
Ewenwan/MVision | 97b394dfa48cb21c82cd003b1a952745e413a17f | darknect/tensorflow/yolo_v1/yolo_v1_tf.py | python | Yolo._fc_layer | (self, x, id, num_out, activation=None) | return output | fully connected layer | fully connected layer | [
"fully",
"connected",
"layer"
] | def _fc_layer(self, x, id, num_out, activation=None):
"""fully connected layer"""
num_in = x.get_shape().as_list()[-1]# 输入通道数量
weight = tf.Variable(tf.truncated_normal([num_in, num_out], stddev=0.1))
bias = tf.Variable(tf.zeros([num_out,]))
output = tf.nn.xw_plus_b(x, weight, bias)
if activation:
output = activation(output)
if self.verbose:
print(" Layer %d: type=Fc, num_out=%d, output_shape=%s" \
% (id, num_out, str(output.get_shape())))
return output | [
"def",
"_fc_layer",
"(",
"self",
",",
"x",
",",
"id",
",",
"num_out",
",",
"activation",
"=",
"None",
")",
":",
"num_in",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"-",
"1",
"]",
"# 输入通道数量",
"weight",
"=",
"tf",
".",
... | https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/darknect/tensorflow/yolo_v1/yolo_v1_tf.py#L181-L192 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/tkMessageBox.py | python | askyesno | (title=None, message=None, **options) | return s == YES | Ask a question; return true if the answer is yes | Ask a question; return true if the answer is yes | [
"Ask",
"a",
"question",
";",
"return",
"true",
"if",
"the",
"answer",
"is",
"yes"
] | def askyesno(title=None, message=None, **options):
"Ask a question; return true if the answer is yes"
s = _show(title, message, QUESTION, YESNO, **options)
return s == YES | [
"def",
"askyesno",
"(",
"title",
"=",
"None",
",",
"message",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"s",
"=",
"_show",
"(",
"title",
",",
"message",
",",
"QUESTION",
",",
"YESNO",
",",
"*",
"*",
"options",
")",
"return",
"s",
"==",
"YE... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/tkMessageBox.py#L102-L105 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | BookCtrlBase.SetFitToCurrentPage | (*args, **kwargs) | return _core_.BookCtrlBase_SetFitToCurrentPage(*args, **kwargs) | SetFitToCurrentPage(self, bool fit) | SetFitToCurrentPage(self, bool fit) | [
"SetFitToCurrentPage",
"(",
"self",
"bool",
"fit",
")"
] | def SetFitToCurrentPage(*args, **kwargs):
"""SetFitToCurrentPage(self, bool fit)"""
return _core_.BookCtrlBase_SetFitToCurrentPage(*args, **kwargs) | [
"def",
"SetFitToCurrentPage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"BookCtrlBase_SetFitToCurrentPage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L13598-L13600 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py | python | Barrier.ready_size | (self, name=None) | return gen_data_flow_ops._barrier_ready_size(self._barrier_ref, name=name) | Compute the number of complete elements in the given barrier.
Args:
name: A name for the operation (optional).
Returns:
A single-element tensor containing the number of complete elements in the
given barrier. | Compute the number of complete elements in the given barrier. | [
"Compute",
"the",
"number",
"of",
"complete",
"elements",
"in",
"the",
"given",
"barrier",
"."
] | def ready_size(self, name=None):
"""Compute the number of complete elements in the given barrier.
Args:
name: A name for the operation (optional).
Returns:
A single-element tensor containing the number of complete elements in the
given barrier.
"""
if name is None:
name = "%s_BarrierReadySize" % self._name
return gen_data_flow_ops._barrier_ready_size(self._barrier_ref, name=name) | [
"def",
"ready_size",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"\"%s_BarrierReadySize\"",
"%",
"self",
".",
"_name",
"return",
"gen_data_flow_ops",
".",
"_barrier_ready_size",
"(",
"self",
".",
"_barrier_r... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/data_flow_ops.py#L980-L992 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fft.py | python | fftn | (x, s=None, axes=None, norm="backward", name=None) | Compute the N-D discrete Fourier Transform.
This function calculates the n-D discrete Fourier transform on any number of axes
in the M-D array by fast Fourier transform (FFT).
Args:
x (Tensor): The input data. It's a Tensor type. It's a complex.
s (sequence of ints, optional): Shape (length of each transformed axis) of the output
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
This corresponds to ``n`` for ``fft(x, n)``.
Along any axis, if the given shape is smaller than that of the input,
the input is cropped. If it is larger, the input is padded with zeros.
if `s` is not given, the shape of the input along the axes specified
by `axes` is used.
axes (sequence of ints, optional): Axes used to calculate FFT. If not given, the last ``len(s)``
axes are used, or all axes if `s` is also not specified.
norm (str): Indicates which direction to scale the `forward` or `backward` transform
pair and what normalization factor to use. The parameter value must be one
of "forward" or "backward" or "ortho". Default is "backward", meaning no normalization on
the forward transforms and scaling by ``1/n`` on the `ifft`. "forward" instead applies
the ``1/n`` factor on the forward tranform. For ``norm="ortho"``, both directions are
scaled by ``1/sqrt(n)``.
name (str, optional): The default value is None. Normally there is no need for user to set
this property. For more information, please refer to :ref:`api_guide_Name`.
Returns:
complex tensor. The truncated or zero-padded input, transformed along the axes indicated by
`axes`, or by a combination of `s` and `x`, as explained in the parameters section above.
Examples:
.. code-block:: python
import numpy as np
import paddle
x = np.mgrid[:4, :4, :4][1]
xp = paddle.to_tensor(x)
fftn_xp = paddle.fft.fftn(xp, axes=(1, 2)).numpy()
print(fftn_xp)
# [[[24.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+8.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]]
# [[24.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+8.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]]
# [[24.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+8.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]]
# [[24.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+8.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]]] | Compute the N-D discrete Fourier Transform. | [
"Compute",
"the",
"N",
"-",
"D",
"discrete",
"Fourier",
"Transform",
"."
] | def fftn(x, s=None, axes=None, norm="backward", name=None):
"""
Compute the N-D discrete Fourier Transform.
This function calculates the n-D discrete Fourier transform on any number of axes
in the M-D array by fast Fourier transform (FFT).
Args:
x (Tensor): The input data. It's a Tensor type. It's a complex.
s (sequence of ints, optional): Shape (length of each transformed axis) of the output
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
This corresponds to ``n`` for ``fft(x, n)``.
Along any axis, if the given shape is smaller than that of the input,
the input is cropped. If it is larger, the input is padded with zeros.
if `s` is not given, the shape of the input along the axes specified
by `axes` is used.
axes (sequence of ints, optional): Axes used to calculate FFT. If not given, the last ``len(s)``
axes are used, or all axes if `s` is also not specified.
norm (str): Indicates which direction to scale the `forward` or `backward` transform
pair and what normalization factor to use. The parameter value must be one
of "forward" or "backward" or "ortho". Default is "backward", meaning no normalization on
the forward transforms and scaling by ``1/n`` on the `ifft`. "forward" instead applies
the ``1/n`` factor on the forward tranform. For ``norm="ortho"``, both directions are
scaled by ``1/sqrt(n)``.
name (str, optional): The default value is None. Normally there is no need for user to set
this property. For more information, please refer to :ref:`api_guide_Name`.
Returns:
complex tensor. The truncated or zero-padded input, transformed along the axes indicated by
`axes`, or by a combination of `s` and `x`, as explained in the parameters section above.
Examples:
.. code-block:: python
import numpy as np
import paddle
x = np.mgrid[:4, :4, :4][1]
xp = paddle.to_tensor(x)
fftn_xp = paddle.fft.fftn(xp, axes=(1, 2)).numpy()
print(fftn_xp)
# [[[24.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+8.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]]
# [[24.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+8.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]]
# [[24.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+8.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]]
# [[24.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+8.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.+0.j 0.+0.j 0.+0.j 0.-0.j]
# [-8.-8.j 0.+0.j 0.+0.j 0.-0.j]]]
"""
if is_integer(x) or is_floating_point(x):
return fftn_r2c(
x, s, axes, norm, forward=True, onesided=False, name=name)
else:
return fftn_c2c(x, s, axes, norm, forward=True, name=name) | [
"def",
"fftn",
"(",
"x",
",",
"s",
"=",
"None",
",",
"axes",
"=",
"None",
",",
"norm",
"=",
"\"backward\"",
",",
"name",
"=",
"None",
")",
":",
"if",
"is_integer",
"(",
"x",
")",
"or",
"is_floating_point",
"(",
"x",
")",
":",
"return",
"fftn_r2c",
... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fft.py#L465-L528 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/ndimage/interpolation.py | python | shift | (input, shift, output=None, order=3, mode='constant', cval=0.0,
prefilter=True) | return output | Shift an array.
The array is shifted using spline interpolation of the requested order.
Points outside the boundaries of the input are filled according to the
given mode.
Parameters
----------
%(input)s
shift : float or sequence
The shift along the axes. If a float, `shift` is the same for each
axis. If a sequence, `shift` should contain one value for each axis.
%(output)s
order : int, optional
The order of the spline interpolation, default is 3.
The order has to be in the range 0-5.
%(mode)s
%(cval)s
%(prefilter)s
Returns
-------
shift : ndarray
The shifted input. | Shift an array. | [
"Shift",
"an",
"array",
"."
] | def shift(input, shift, output=None, order=3, mode='constant', cval=0.0,
prefilter=True):
"""
Shift an array.
The array is shifted using spline interpolation of the requested order.
Points outside the boundaries of the input are filled according to the
given mode.
Parameters
----------
%(input)s
shift : float or sequence
The shift along the axes. If a float, `shift` is the same for each
axis. If a sequence, `shift` should contain one value for each axis.
%(output)s
order : int, optional
The order of the spline interpolation, default is 3.
The order has to be in the range 0-5.
%(mode)s
%(cval)s
%(prefilter)s
Returns
-------
shift : ndarray
The shifted input.
"""
if order < 0 or order > 5:
raise RuntimeError('spline order not supported')
input = numpy.asarray(input)
if numpy.iscomplexobj(input):
raise TypeError('Complex type not supported')
if input.ndim < 1:
raise RuntimeError('input and output rank must be > 0')
mode = _ni_support._extend_mode_to_code(mode)
if prefilter and order > 1:
filtered = spline_filter(input, order, output=numpy.float64)
else:
filtered = input
output = _ni_support._get_output(output, input)
shift = _ni_support._normalize_sequence(shift, input.ndim)
shift = [-ii for ii in shift]
shift = numpy.asarray(shift, dtype=numpy.float64)
if not shift.flags.contiguous:
shift = shift.copy()
_nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval)
return output | [
"def",
"shift",
"(",
"input",
",",
"shift",
",",
"output",
"=",
"None",
",",
"order",
"=",
"3",
",",
"mode",
"=",
"'constant'",
",",
"cval",
"=",
"0.0",
",",
"prefilter",
"=",
"True",
")",
":",
"if",
"order",
"<",
"0",
"or",
"order",
">",
"5",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/ndimage/interpolation.py#L485-L533 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/akg/ascend/square.py | python | _square_akg | () | return | Square Akg register | Square Akg register | [
"Square",
"Akg",
"register"
] | def _square_akg():
"""Square Akg register"""
return | [
"def",
"_square_akg",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/akg/ascend/square.py#L33-L35 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/external/bazel_tools/tools/build_defs/pkg/archive.py | python | TarFileWriter.close | (self) | Close the output tar file.
This class should not be used anymore after calling that method.
Raises:
TarFileWriter.Error: if an error happens when compressing the output file. | Close the output tar file. | [
"Close",
"the",
"output",
"tar",
"file",
"."
] | def close(self):
"""Close the output tar file.
This class should not be used anymore after calling that method.
Raises:
TarFileWriter.Error: if an error happens when compressing the output file.
"""
self.tar.close()
if self.xz:
# Support xz compression through xz... until we can use Py3
if subprocess.call('which xz', shell=True, stdout=subprocess.PIPE):
raise self.Error('Cannot handle .xz and .lzma compression: '
'xz not found.')
subprocess.call(
'mv {0} {0}.d && xz -z {0}.d && mv {0}.d.xz {0}'.format(self.name),
shell=True,
stdout=subprocess.PIPE) | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"tar",
".",
"close",
"(",
")",
"if",
"self",
".",
"xz",
":",
"# Support xz compression through xz... until we can use Py3",
"if",
"subprocess",
".",
"call",
"(",
"'which xz'",
",",
"shell",
"=",
"True",
","... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/tools/build_defs/pkg/archive.py#L373-L390 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/client.py | python | GDClient.modify_request | (self, http_request) | return http_request | Adds or changes request before making the HTTP request.
This client will add the API version if it is specified.
Subclasses may override this method to add their own request
modifications before the request is made. | Adds or changes request before making the HTTP request. | [
"Adds",
"or",
"changes",
"request",
"before",
"making",
"the",
"HTTP",
"request",
"."
] | def modify_request(self, http_request):
"""Adds or changes request before making the HTTP request.
This client will add the API version if it is specified.
Subclasses may override this method to add their own request
modifications before the request is made.
"""
http_request = atom.client.AtomPubClient.modify_request(self,
http_request)
if self.api_version is not None:
http_request.headers['GData-Version'] = self.api_version
return http_request | [
"def",
"modify_request",
"(",
"self",
",",
"http_request",
")",
":",
"http_request",
"=",
"atom",
".",
"client",
".",
"AtomPubClient",
".",
"modify_request",
"(",
"self",
",",
"http_request",
")",
"if",
"self",
".",
"api_version",
"is",
"not",
"None",
":",
... | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/client.py#L581-L592 | |
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | modules/tools/mapviewers/gmapviewer.py | python | utm2latlon | (x, y, pzone=10) | return lat, lon | convert the utm x y to lat and lon | convert the utm x y to lat and lon | [
"convert",
"the",
"utm",
"x",
"y",
"to",
"lat",
"and",
"lon"
] | def utm2latlon(x, y, pzone=10):
"""
convert the utm x y to lat and lon
"""
projector2 = pyproj.Proj(proj='utm', zone=pzone, ellps='WGS84')
lon, lat = projector2(x, y, inverse=True)
return lat, lon | [
"def",
"utm2latlon",
"(",
"x",
",",
"y",
",",
"pzone",
"=",
"10",
")",
":",
"projector2",
"=",
"pyproj",
".",
"Proj",
"(",
"proj",
"=",
"'utm'",
",",
"zone",
"=",
"pzone",
",",
"ellps",
"=",
"'WGS84'",
")",
"lon",
",",
"lat",
"=",
"projector2",
"... | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/mapviewers/gmapviewer.py#L96-L102 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/manager.py | python | TransferCoordinatorController.add_transfer_coordinator | (self, transfer_coordinator) | Adds a transfer coordinator of a transfer to be canceled if needed
:type transfer_coordinator: s3transfer.futures.TransferCoordinator
:param transfer_coordinator: The transfer coordinator for the
particular transfer | Adds a transfer coordinator of a transfer to be canceled if needed | [
"Adds",
"a",
"transfer",
"coordinator",
"of",
"a",
"transfer",
"to",
"be",
"canceled",
"if",
"needed"
] | def add_transfer_coordinator(self, transfer_coordinator):
"""Adds a transfer coordinator of a transfer to be canceled if needed
:type transfer_coordinator: s3transfer.futures.TransferCoordinator
:param transfer_coordinator: The transfer coordinator for the
particular transfer
"""
with self._lock:
self._tracked_transfer_coordinators.add(transfer_coordinator) | [
"def",
"add_transfer_coordinator",
"(",
"self",
",",
"transfer_coordinator",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_tracked_transfer_coordinators",
".",
"add",
"(",
"transfer_coordinator",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/manager.py#L602-L610 | ||
DGtal-team/DGtal | b403217bae9a55638a0a8baac69cc7e8d6362af5 | wrap/__init__.py | python | KSpace | (dim) | Factory helper function for DGtal::KhalimskySpace
Call:
kspace.init(lower=dgtal.Point, upper=dgtal.Point , is_closed=True|False)
to initialize it to a valid state.
Parameters
----------
dim: Int
Dimension of the space (2D or 3D)
Example:
ks = dgtal.KSpace(dim=2)
ks.init(lower=dgtal.Point(dim=2).zero,
upper=dgtal.Point(dim=2).diagonal(2),
is_closed=True) | Factory helper function for DGtal::KhalimskySpace
Call:
kspace.init(lower=dgtal.Point, upper=dgtal.Point , is_closed=True|False)
to initialize it to a valid state. | [
"Factory",
"helper",
"function",
"for",
"DGtal",
"::",
"KhalimskySpace",
"Call",
":",
"kspace",
".",
"init",
"(",
"lower",
"=",
"dgtal",
".",
"Point",
"upper",
"=",
"dgtal",
".",
"Point",
"is_closed",
"=",
"True|False",
")",
"to",
"initialize",
"it",
"to",... | def KSpace(dim):
"""
Factory helper function for DGtal::KhalimskySpace
Call:
kspace.init(lower=dgtal.Point, upper=dgtal.Point , is_closed=True|False)
to initialize it to a valid state.
Parameters
----------
dim: Int
Dimension of the space (2D or 3D)
Example:
ks = dgtal.KSpace(dim=2)
ks.init(lower=dgtal.Point(dim=2).zero,
upper=dgtal.Point(dim=2).diagonal(2),
is_closed=True)
"""
_check_dim(dim)
if dim == 2:
return topology.KSpace2D()
elif dim == 3:
return topology.KSpace3D() | [
"def",
"KSpace",
"(",
"dim",
")",
":",
"_check_dim",
"(",
"dim",
")",
"if",
"dim",
"==",
"2",
":",
"return",
"topology",
".",
"KSpace2D",
"(",
")",
"elif",
"dim",
"==",
"3",
":",
"return",
"topology",
".",
"KSpace3D",
"(",
")"
] | https://github.com/DGtal-team/DGtal/blob/b403217bae9a55638a0a8baac69cc7e8d6362af5/wrap/__init__.py#L233-L256 | ||
scribusproject/scribus | 41ec7c775a060912cf251682a8b1437f753f80f4 | scribus/plugins/scriptplugin_py2x/scripts/CalendarWizard.py | python | TkCalendar.okButonn_pressed | (self) | User variables testing and preparing | User variables testing and preparing | [
"User",
"variables",
"testing",
"and",
"preparing"
] | def okButonn_pressed(self):
""" User variables testing and preparing """
# year
try:
year = self.yearVar.get().strip()
if len(year) != 4:
raise ValueError
year = int(year, 10)
except ValueError:
self.statusVar.set('Year must be in the "YYYY" format e.g. 2005.')
return
# months
selMonths = self.monthListbox.curselection()
if len(selMonths) == 0:
self.statusVar.set('At least one month must be selected.')
return
months = []
for i in selMonths:
months.append(int(i))
# draw images etc.
if self.imageVar.get() == 0:
draw = False
else:
draw = True
# create calendar (finally)
if self.typeVar.get() == 0:
cal = ScClassicCalendar(year, months, self.weekVar.get(), draw, self.sepMonthsVar.get(), self.key)
elif self.typeVar.get() == 1:
cal = ScHorizontalEventCalendar(year, months, self.weekVar.get(), draw, self.sepMonthsVar.get(), self.key)
else:
cal = ScVerticalEventCalendar(year, months, self.weekVar.get(), draw, self.sepMonthsVar.get(), self.key)
self.master.withdraw()
err = cal.createCalendar()
if err is not None:
self.master.deiconify()
self.statusVar.set(err)
else:
self.quit() | [
"def",
"okButonn_pressed",
"(",
"self",
")",
":",
"# year",
"try",
":",
"year",
"=",
"self",
".",
"yearVar",
".",
"get",
"(",
")",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"year",
")",
"!=",
"4",
":",
"raise",
"ValueError",
"year",
"=",
"int",
"... | https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/scribus/plugins/scriptplugin_py2x/scripts/CalendarWizard.py#L619-L656 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/polynomial/chebyshev.py | python | chebint | (c, m=1, k=[], lbnd=0, scl=1, axis=0) | return c | Integrate a Chebyshev series.
Returns the Chebyshev series coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `c` is an array of
coefficients from low to high degree along each axis, e.g., [1,2,3]
represents the series ``T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]]
represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) +
2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
Parameters
----------
c : array_like
Array of Chebyshev series coefficients. If c is multidimensional
the different axis correspond to different variables with the
degree in each axis given by the corresponding index.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at zero
is the first value in the list, the value of the second integral
at zero is the second value, etc. If ``k == []`` (the default),
all constants are set to zero. If ``m == 1``, a single scalar can
be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
axis : int, optional
Axis over which the integral is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
S : ndarray
C-series coefficients of the integral.
Raises
------
ValueError
If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
``np.ndim(scl) != 0``.
See Also
--------
chebder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`.
Why is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
:math:`dx = du/a`, so one will need to set `scl` equal to
:math:`1/a`- perhaps not what one would have first thought.
Also note that, in general, the result of integrating a C-series needs
to be "reprojected" onto the C-series basis set. Thus, typically,
the result of this function is "unintuitive," albeit correct; see
Examples section below.
Examples
--------
>>> from numpy.polynomial import chebyshev as C
>>> c = (1,2,3)
>>> C.chebint(c)
array([ 0.5, -0.5, 0.5, 0.5])
>>> C.chebint(c,3)
array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667,
0.00625 ])
>>> C.chebint(c, k=3)
array([ 3.5, -0.5, 0.5, 0.5])
>>> C.chebint(c,lbnd=-2)
array([ 8.5, -0.5, 0.5, 0.5])
>>> C.chebint(c,scl=-2)
array([-1., 1., -1., -1.]) | Integrate a Chebyshev series. | [
"Integrate",
"a",
"Chebyshev",
"series",
"."
] | def chebint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
"""
Integrate a Chebyshev series.
Returns the Chebyshev series coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `c` is an array of
coefficients from low to high degree along each axis, e.g., [1,2,3]
represents the series ``T_0 + 2*T_1 + 3*T_2`` while [[1,2],[1,2]]
represents ``1*T_0(x)*T_0(y) + 1*T_1(x)*T_0(y) + 2*T_0(x)*T_1(y) +
2*T_1(x)*T_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
Parameters
----------
c : array_like
Array of Chebyshev series coefficients. If c is multidimensional
the different axis correspond to different variables with the
degree in each axis given by the corresponding index.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at zero
is the first value in the list, the value of the second integral
at zero is the second value, etc. If ``k == []`` (the default),
all constants are set to zero. If ``m == 1``, a single scalar can
be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
axis : int, optional
Axis over which the integral is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
S : ndarray
C-series coefficients of the integral.
Raises
------
ValueError
If ``m < 1``, ``len(k) > m``, ``np.ndim(lbnd) != 0``, or
``np.ndim(scl) != 0``.
See Also
--------
chebder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`.
Why is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
:math:`dx = du/a`, so one will need to set `scl` equal to
:math:`1/a`- perhaps not what one would have first thought.
Also note that, in general, the result of integrating a C-series needs
to be "reprojected" onto the C-series basis set. Thus, typically,
the result of this function is "unintuitive," albeit correct; see
Examples section below.
Examples
--------
>>> from numpy.polynomial import chebyshev as C
>>> c = (1,2,3)
>>> C.chebint(c)
array([ 0.5, -0.5, 0.5, 0.5])
>>> C.chebint(c,3)
array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667,
0.00625 ])
>>> C.chebint(c, k=3)
array([ 3.5, -0.5, 0.5, 0.5])
>>> C.chebint(c,lbnd=-2)
array([ 8.5, -0.5, 0.5, 0.5])
>>> C.chebint(c,scl=-2)
array([-1., 1., -1., -1.])
"""
c = np.array(c, ndmin=1, copy=1)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
if not np.iterable(k):
k = [k]
cnt, iaxis = [int(t) for t in [m, axis]]
if cnt != m:
raise ValueError("The order of integration must be integer")
if cnt < 0:
raise ValueError("The order of integration must be non-negative")
if len(k) > cnt:
raise ValueError("Too many integration constants")
if np.ndim(lbnd) != 0:
raise ValueError("lbnd must be a scalar.")
if np.ndim(scl) != 0:
raise ValueError("scl must be a scalar.")
if iaxis != axis:
raise ValueError("The axis must be integer")
iaxis = normalize_axis_index(iaxis, c.ndim)
if cnt == 0:
return c
c = np.moveaxis(c, iaxis, 0)
k = list(k) + [0]*(cnt - len(k))
for i in range(cnt):
n = len(c)
c *= scl
if n == 1 and np.all(c[0] == 0):
c[0] += k[i]
else:
tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
tmp[0] = c[0]*0
tmp[1] = c[0]
if n > 1:
tmp[2] = c[1]/4
for j in range(2, n):
t = c[j]/(2*j + 1) # FIXME: t never used
tmp[j + 1] = c[j]/(2*(j + 1))
tmp[j - 1] -= c[j]/(2*(j - 1))
tmp[0] += k[i] - chebval(lbnd, tmp)
c = tmp
c = np.moveaxis(c, 0, iaxis)
return c | [
"def",
"chebint",
"(",
"c",
",",
"m",
"=",
"1",
",",
"k",
"=",
"[",
"]",
",",
"lbnd",
"=",
"0",
",",
"scl",
"=",
"1",
",",
"axis",
"=",
"0",
")",
":",
"c",
"=",
"np",
".",
"array",
"(",
"c",
",",
"ndmin",
"=",
"1",
",",
"copy",
"=",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/chebyshev.py#L976-L1105 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/incubate/fleet/parameter_server/ir/pserver_pass.py | python | _get_output_map_from_op | (varmap, op) | return iomap | Returns a dict from op output name to the vars in varmap. | Returns a dict from op output name to the vars in varmap. | [
"Returns",
"a",
"dict",
"from",
"op",
"output",
"name",
"to",
"the",
"vars",
"in",
"varmap",
"."
] | def _get_output_map_from_op(varmap, op):
"""Returns a dict from op output name to the vars in varmap."""
iomap = collections.OrderedDict()
for key in op.output_names:
vars = []
for varname in op.output(key):
vars.append(varmap[varname])
if len(vars) == 1:
iomap[key] = vars[0]
else:
iomap[key] = vars
return iomap | [
"def",
"_get_output_map_from_op",
"(",
"varmap",
",",
"op",
")",
":",
"iomap",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"key",
"in",
"op",
".",
"output_names",
":",
"vars",
"=",
"[",
"]",
"for",
"varname",
"in",
"op",
".",
"output",
"("... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/parameter_server/ir/pserver_pass.py#L295-L306 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/special_math_ops.py | python | _transpose_if_necessary | (tensor, perm) | Like transpose(), but avoids creating a new tensor if possible. | Like transpose(), but avoids creating a new tensor if possible. | [
"Like",
"transpose",
"()",
"but",
"avoids",
"creating",
"a",
"new",
"tensor",
"if",
"possible",
"."
] | def _transpose_if_necessary(tensor, perm):
"""Like transpose(), but avoids creating a new tensor if possible."""
if perm != list(range(len(perm))):
return array_ops.transpose(tensor, perm=perm)
else:
return tensor | [
"def",
"_transpose_if_necessary",
"(",
"tensor",
",",
"perm",
")",
":",
"if",
"perm",
"!=",
"list",
"(",
"range",
"(",
"len",
"(",
"perm",
")",
")",
")",
":",
"return",
"array_ops",
".",
"transpose",
"(",
"tensor",
",",
"perm",
"=",
"perm",
")",
"els... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/special_math_ops.py#L522-L527 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/_pyio.py | python | TextIOWrapper._get_decoded_chars | (self, n=None) | return chars | Advance into the _decoded_chars buffer. | Advance into the _decoded_chars buffer. | [
"Advance",
"into",
"the",
"_decoded_chars",
"buffer",
"."
] | def _get_decoded_chars(self, n=None):
"""Advance into the _decoded_chars buffer."""
offset = self._decoded_chars_used
if n is None:
chars = self._decoded_chars[offset:]
else:
chars = self._decoded_chars[offset:offset + n]
self._decoded_chars_used += len(chars)
return chars | [
"def",
"_get_decoded_chars",
"(",
"self",
",",
"n",
"=",
"None",
")",
":",
"offset",
"=",
"self",
".",
"_decoded_chars_used",
"if",
"n",
"is",
"None",
":",
"chars",
"=",
"self",
".",
"_decoded_chars",
"[",
"offset",
":",
"]",
"else",
":",
"chars",
"=",... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/_pyio.py#L1634-L1642 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/tensorflow/load.py | python | TFLoader.extract_sub_graph | (graph_def, outputs=None) | Extract sub-graph based on user-provided outputs. | Extract sub-graph based on user-provided outputs. | [
"Extract",
"sub",
"-",
"graph",
"based",
"on",
"user",
"-",
"provided",
"outputs",
"."
] | def extract_sub_graph(graph_def, outputs=None):
"""Extract sub-graph based on user-provided outputs."""
if outputs is None or len(outputs) == 0:
return graph_def
msg = "Extracting sub-graph based on outputs '{}' from the full model"
logging.debug(msg.format(outputs))
outputs = outputs if isinstance(outputs, list) else [outputs]
outputs = [i.split(":")[0] for i in outputs]
if tf.__version__ < _StrictVersion("1.13.1"):
return tf.graph_util.extract_sub_graph(graph_def, outputs)
else:
return tf.compat.v1.graph_util.extract_sub_graph(graph_def, outputs) | [
"def",
"extract_sub_graph",
"(",
"graph_def",
",",
"outputs",
"=",
"None",
")",
":",
"if",
"outputs",
"is",
"None",
"or",
"len",
"(",
"outputs",
")",
"==",
"0",
":",
"return",
"graph_def",
"msg",
"=",
"\"Extracting sub-graph based on outputs '{}' from the full mod... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/tensorflow/load.py#L100-L111 | ||
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py | python | PaneLayout.hide | (self, panes=[]) | Hide panes specified. If empty list provided, hide all. | Hide panes specified. If empty list provided, hide all. | [
"Hide",
"panes",
"specified",
".",
"If",
"empty",
"list",
"provided",
"hide",
"all",
"."
] | def hide(self, panes=[]):
""" Hide panes specified. If empty list provided, hide all. """
for name in self.panes:
if name in panes or len(panes) == 0:
self.panes[name].destroy() | [
"def",
"hide",
"(",
"self",
",",
"panes",
"=",
"[",
"]",
")",
":",
"for",
"name",
"in",
"self",
".",
"panes",
":",
"if",
"name",
"in",
"panes",
"or",
"len",
"(",
"panes",
")",
"==",
"0",
":",
"self",
".",
"panes",
"[",
"name",
"]",
".",
"dest... | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py#L212-L216 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/factorization/python/ops/clustering_ops.py | python | KMeans.training_graph | (self) | return all_scores, cluster_idx, scores, training_op | Generate a training graph for kmeans algorithm.
Returns:
A tuple consisting of:
all_scores: A matrix (or list of matrices) of dimensions (num_input,
num_clusters) where the value is the distance of an input vector and a
cluster center.
cluster_idx: A vector (or list of vectors). Each element in the vector
corresponds to an input row in 'inp' and specifies the cluster id
corresponding to the input.
scores: Similar to cluster_idx but specifies the distance to the
assigned cluster instead.
training_op: an op that runs an iteration of training. | Generate a training graph for kmeans algorithm. | [
"Generate",
"a",
"training",
"graph",
"for",
"kmeans",
"algorithm",
"."
] | def training_graph(self):
"""Generate a training graph for kmeans algorithm.
Returns:
A tuple consisting of:
all_scores: A matrix (or list of matrices) of dimensions (num_input,
num_clusters) where the value is the distance of an input vector and a
cluster center.
cluster_idx: A vector (or list of vectors). Each element in the vector
corresponds to an input row in 'inp' and specifies the cluster id
corresponding to the input.
scores: Similar to cluster_idx but specifies the distance to the
assigned cluster instead.
training_op: an op that runs an iteration of training.
"""
# Implementation of kmeans.
inputs = self._inputs
cluster_centers_var, total_counts = self._init_clusters()
cluster_centers = cluster_centers_var
if self._distance_metric == COSINE_DISTANCE:
inputs = self._l2_normalize_data(inputs)
if not self._clusters_l2_normalized():
cluster_centers = tf.nn.l2_normalize(cluster_centers, dim=1)
all_scores, scores, cluster_idx = self._infer_graph(inputs, cluster_centers)
if self._use_mini_batch:
training_op = self._mini_batch_training_op(
inputs, cluster_idx, cluster_centers, cluster_centers_var,
total_counts)
else:
assert cluster_centers == cluster_centers_var
training_op = self._full_batch_training_op(inputs, cluster_idx,
cluster_centers_var)
return all_scores, cluster_idx, scores, training_op | [
"def",
"training_graph",
"(",
"self",
")",
":",
"# Implementation of kmeans.",
"inputs",
"=",
"self",
".",
"_inputs",
"cluster_centers_var",
",",
"total_counts",
"=",
"self",
".",
"_init_clusters",
"(",
")",
"cluster_centers",
"=",
"cluster_centers_var",
"if",
"self... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/clustering_ops.py#L271-L305 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py | python | Decimal.is_nan | (self) | return self._exp in ('n', 'N') | Return True if self is a qNaN or sNaN; otherwise return False. | Return True if self is a qNaN or sNaN; otherwise return False. | [
"Return",
"True",
"if",
"self",
"is",
"a",
"qNaN",
"or",
"sNaN",
";",
"otherwise",
"return",
"False",
"."
] | def is_nan(self):
"""Return True if self is a qNaN or sNaN; otherwise return False."""
return self._exp in ('n', 'N') | [
"def",
"is_nan",
"(",
"self",
")",
":",
"return",
"self",
".",
"_exp",
"in",
"(",
"'n'",
",",
"'N'",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L3027-L3029 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/AddonManager/addonmanager_utilities.py | python | restart_freecad | () | Shuts down and restarts FreeCAD | Shuts down and restarts FreeCAD | [
"Shuts",
"down",
"and",
"restarts",
"FreeCAD"
] | def restart_freecad():
"Shuts down and restarts FreeCAD"
args = QtWidgets.QApplication.arguments()[1:]
if FreeCADGui.getMainWindow().close():
QtCore.QProcess.startDetached(
QtWidgets.QApplication.applicationFilePath(), args
) | [
"def",
"restart_freecad",
"(",
")",
":",
"args",
"=",
"QtWidgets",
".",
"QApplication",
".",
"arguments",
"(",
")",
"[",
"1",
":",
"]",
"if",
"FreeCADGui",
".",
"getMainWindow",
"(",
")",
".",
"close",
"(",
")",
":",
"QtCore",
".",
"QProcess",
".",
"... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/AddonManager/addonmanager_utilities.py#L114-L121 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py | python | ParserElement.runTests | (self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False) | return success, allResults | Execute the parse expression on a series of test strings, showing each
test, the parsed results or where the parse failed. Quick and easy way to
run a parse expression against a list of sample strings.
Parameters:
- tests - a list of separate test strings, or a multiline string of test strings
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
- comment - (default=C{'#'}) - expression for indicating embedded comments in the test
string; pass None to disable comment filtering
- fullDump - (default=C{True}) - dump results as list followed by results names in nested outline;
if False, only dump nested list
- printResults - (default=C{True}) prints test output to stdout
- failureTests - (default=C{False}) indicates if these tests are expected to fail parsing
Returns: a (success, results) tuple, where success indicates that all tests succeeded
(or failed if C{failureTests} is True), and the results contain a list of lines of each
test's output
Example::
number_expr = pyparsing_common.number.copy()
result = number_expr.runTests('''
# unsigned integer
100
# negative integer
-100
# float with scientific notation
6.02e23
# integer with scientific notation
1e-12
''')
print("Success" if result[0] else "Failed!")
result = number_expr.runTests('''
# stray character
100Z
# missing leading digit before '.'
-.100
# too many '.'
3.14.159
''', failureTests=True)
print("Success" if result[0] else "Failed!")
prints::
# unsigned integer
100
[100]
# negative integer
-100
[-100]
# float with scientific notation
6.02e23
[6.02e+23]
# integer with scientific notation
1e-12
[1e-12]
Success
# stray character
100Z
^
FAIL: Expected end of text (at char 3), (line:1, col:4)
# missing leading digit before '.'
-.100
^
FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)
# too many '.'
3.14.159
^
FAIL: Expected end of text (at char 4), (line:1, col:5)
Success
Each test string must be on a single line. If you want to test a string that spans multiple
lines, create a test like this::
expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines")
(Note that this is a raw string literal, you must include the leading 'r'.) | Execute the parse expression on a series of test strings, showing each
test, the parsed results or where the parse failed. Quick and easy way to
run a parse expression against a list of sample strings.
Parameters:
- tests - a list of separate test strings, or a multiline string of test strings
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
- comment - (default=C{'#'}) - expression for indicating embedded comments in the test
string; pass None to disable comment filtering
- fullDump - (default=C{True}) - dump results as list followed by results names in nested outline;
if False, only dump nested list
- printResults - (default=C{True}) prints test output to stdout
- failureTests - (default=C{False}) indicates if these tests are expected to fail parsing | [
"Execute",
"the",
"parse",
"expression",
"on",
"a",
"series",
"of",
"test",
"strings",
"showing",
"each",
"test",
"the",
"parsed",
"results",
"or",
"where",
"the",
"parse",
"failed",
".",
"Quick",
"and",
"easy",
"way",
"to",
"run",
"a",
"parse",
"expressio... | def runTests(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False):
"""
Execute the parse expression on a series of test strings, showing each
test, the parsed results or where the parse failed. Quick and easy way to
run a parse expression against a list of sample strings.
Parameters:
- tests - a list of separate test strings, or a multiline string of test strings
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
- comment - (default=C{'#'}) - expression for indicating embedded comments in the test
string; pass None to disable comment filtering
- fullDump - (default=C{True}) - dump results as list followed by results names in nested outline;
if False, only dump nested list
- printResults - (default=C{True}) prints test output to stdout
- failureTests - (default=C{False}) indicates if these tests are expected to fail parsing
Returns: a (success, results) tuple, where success indicates that all tests succeeded
(or failed if C{failureTests} is True), and the results contain a list of lines of each
test's output
Example::
number_expr = pyparsing_common.number.copy()
result = number_expr.runTests('''
# unsigned integer
100
# negative integer
-100
# float with scientific notation
6.02e23
# integer with scientific notation
1e-12
''')
print("Success" if result[0] else "Failed!")
result = number_expr.runTests('''
# stray character
100Z
# missing leading digit before '.'
-.100
# too many '.'
3.14.159
''', failureTests=True)
print("Success" if result[0] else "Failed!")
prints::
# unsigned integer
100
[100]
# negative integer
-100
[-100]
# float with scientific notation
6.02e23
[6.02e+23]
# integer with scientific notation
1e-12
[1e-12]
Success
# stray character
100Z
^
FAIL: Expected end of text (at char 3), (line:1, col:4)
# missing leading digit before '.'
-.100
^
FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)
# too many '.'
3.14.159
^
FAIL: Expected end of text (at char 4), (line:1, col:5)
Success
Each test string must be on a single line. If you want to test a string that spans multiple
lines, create a test like this::
expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines")
(Note that this is a raw string literal, you must include the leading 'r'.)
"""
if isinstance(tests, basestring):
tests = list(map(str.strip, tests.rstrip().splitlines()))
if isinstance(comment, basestring):
comment = Literal(comment)
allResults = []
comments = []
success = True
for t in tests:
if comment is not None and comment.matches(t, False) or comments and not t:
comments.append(t)
continue
if not t:
continue
out = ['\n'.join(comments), t]
comments = []
try:
t = t.replace(r'\n','\n')
result = self.parseString(t, parseAll=parseAll)
out.append(result.dump(full=fullDump))
success = success and not failureTests
except ParseBaseException as pe:
fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else ""
if '\n' in t:
out.append(line(pe.loc, t))
out.append(' '*(col(pe.loc,t)-1) + '^' + fatal)
else:
out.append(' '*pe.loc + '^' + fatal)
out.append("FAIL: " + str(pe))
success = success and failureTests
result = pe
except Exception as exc:
out.append("FAIL-EXCEPTION: " + str(exc))
success = success and failureTests
result = exc
if printResults:
if fullDump:
out.append('')
print('\n'.join(out))
allResults.append((t, result))
return success, allResults | [
"def",
"runTests",
"(",
"self",
",",
"tests",
",",
"parseAll",
"=",
"True",
",",
"comment",
"=",
"'#'",
",",
"fullDump",
"=",
"True",
",",
"printResults",
"=",
"True",
",",
"failureTests",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"tests",
",",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/_vendor/pyparsing.py#L2232-L2361 | |
calamares/calamares | 9f6f82405b3074af7c99dc26487d2e46e4ece3e5 | src/modules/unpackfs/main.py | python | UnpackOperation.unpack_image | (self, entry, imgmountdir) | Unpacks image.
:param entry:
:param imgmountdir:
:return: | Unpacks image. | [
"Unpacks",
"image",
"."
] | def unpack_image(self, entry, imgmountdir):
"""
Unpacks image.
:param entry:
:param imgmountdir:
:return:
"""
def progress_cb(copied, total):
""" Copies file to given destination target.
:param copied:
"""
entry.copied = copied
if total > entry.total:
entry.total = total
self.report_progress()
try:
if entry.is_file():
source = entry.source
else:
source = imgmountdir
return file_copy(source, entry, progress_cb)
finally:
if not entry.is_file():
subprocess.check_call(["umount", "-l", imgmountdir]) | [
"def",
"unpack_image",
"(",
"self",
",",
"entry",
",",
"imgmountdir",
")",
":",
"def",
"progress_cb",
"(",
"copied",
",",
"total",
")",
":",
"\"\"\" Copies file to given destination target.\n\n :param copied:\n \"\"\"",
"entry",
".",
"copied",
"=",
... | https://github.com/calamares/calamares/blob/9f6f82405b3074af7c99dc26487d2e46e4ece3e5/src/modules/unpackfs/main.py#L332-L359 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configDialog.py | python | ConfigDialog.SaveNewTheme | (self,themeName,theme) | save a newly created theme.
themeName - string, the name of the new theme
theme - dictionary containing the new theme | save a newly created theme.
themeName - string, the name of the new theme
theme - dictionary containing the new theme | [
"save",
"a",
"newly",
"created",
"theme",
".",
"themeName",
"-",
"string",
"the",
"name",
"of",
"the",
"new",
"theme",
"theme",
"-",
"dictionary",
"containing",
"the",
"new",
"theme"
] | def SaveNewTheme(self,themeName,theme):
"""
save a newly created theme.
themeName - string, the name of the new theme
theme - dictionary containing the new theme
"""
if not idleConf.userCfg['highlight'].has_section(themeName):
idleConf.userCfg['highlight'].add_section(themeName)
for element in theme.keys():
value=theme[element]
idleConf.userCfg['highlight'].SetOption(themeName,element,value) | [
"def",
"SaveNewTheme",
"(",
"self",
",",
"themeName",
",",
"theme",
")",
":",
"if",
"not",
"idleConf",
".",
"userCfg",
"[",
"'highlight'",
"]",
".",
"has_section",
"(",
"themeName",
")",
":",
"idleConf",
".",
"userCfg",
"[",
"'highlight'",
"]",
".",
"add... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configDialog.py#L1079-L1089 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/elementwise/huber.py | python | huber.is_atom_convex | (self) | return True | Is the atom convex? | Is the atom convex? | [
"Is",
"the",
"atom",
"convex?"
] | def is_atom_convex(self) -> bool:
"""Is the atom convex?
"""
return True | [
"def",
"is_atom_convex",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"True"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/elementwise/huber.py#L64-L67 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/state_space_models/periodic.py | python | ResolutionCycleModel.__init__ | (
self,
num_latent_values,
periodicity,
near_integer_threshold=1e-8,
configuration=state_space_model.StateSpaceModelConfiguration()) | Initialize the ResolutionCycleModel.
Args:
num_latent_values: Controls the representational power and memory usage of
the model. The transition matrix has shape [num_latent_values - 1,
num_latent_values - 1]. Must be an odd integer (see class docstring for
why).
periodicity: The number of steps for cyclic behavior. May be a Tensor, and
need not be an integer (although integer values greater than
num_latent_values have more efficient special cases).
near_integer_threshold: When avoiding singularities, controls how close a
number should be to that singularity before the special case takes over.
configuration: A StateSpaceModelConfiguration object.
Raises:
ValueError: If num_latent_values is not odd. | Initialize the ResolutionCycleModel. | [
"Initialize",
"the",
"ResolutionCycleModel",
"."
] | def __init__(
self,
num_latent_values,
periodicity,
near_integer_threshold=1e-8,
configuration=state_space_model.StateSpaceModelConfiguration()):
"""Initialize the ResolutionCycleModel.
Args:
num_latent_values: Controls the representational power and memory usage of
the model. The transition matrix has shape [num_latent_values - 1,
num_latent_values - 1]. Must be an odd integer (see class docstring for
why).
periodicity: The number of steps for cyclic behavior. May be a Tensor, and
need not be an integer (although integer values greater than
num_latent_values have more efficient special cases).
near_integer_threshold: When avoiding singularities, controls how close a
number should be to that singularity before the special case takes over.
configuration: A StateSpaceModelConfiguration object.
Raises:
ValueError: If num_latent_values is not odd.
"""
if num_latent_values % 2 != 1:
raise ValueError("Only odd numbers of latent values are supported.")
self._num_latent_values = num_latent_values
self._true_periodicity = periodicity
self._near_integer_threshold = near_integer_threshold
super(ResolutionCycleModel, self).__init__(
periodicity=num_latent_values,
configuration=configuration) | [
"def",
"__init__",
"(",
"self",
",",
"num_latent_values",
",",
"periodicity",
",",
"near_integer_threshold",
"=",
"1e-8",
",",
"configuration",
"=",
"state_space_model",
".",
"StateSpaceModelConfiguration",
"(",
")",
")",
":",
"if",
"num_latent_values",
"%",
"2",
... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/state_space_models/periodic.py#L232-L262 | ||
liulei01/DRBox | b5c76e033c555c9009590ab384e1f7bd3c66c237 | python/caffe/detector.py | python | Detector.configure_crop | (self, context_pad) | Configure crop dimensions and amount of context for cropping.
If context is included, make the special input mean for context padding.
Parameters
----------
context_pad : amount of context for cropping. | Configure crop dimensions and amount of context for cropping.
If context is included, make the special input mean for context padding. | [
"Configure",
"crop",
"dimensions",
"and",
"amount",
"of",
"context",
"for",
"cropping",
".",
"If",
"context",
"is",
"included",
"make",
"the",
"special",
"input",
"mean",
"for",
"context",
"padding",
"."
] | def configure_crop(self, context_pad):
"""
Configure crop dimensions and amount of context for cropping.
If context is included, make the special input mean for context padding.
Parameters
----------
context_pad : amount of context for cropping.
"""
# crop dimensions
in_ = self.inputs[0]
tpose = self.transformer.transpose[in_]
inv_tpose = [tpose[t] for t in tpose]
self.crop_dims = np.array(self.blobs[in_].data.shape[1:])[inv_tpose]
#.transpose(inv_tpose)
# context padding
self.context_pad = context_pad
if self.context_pad:
in_ = self.inputs[0]
transpose = self.transformer.transpose.get(in_)
channel_order = self.transformer.channel_swap.get(in_)
raw_scale = self.transformer.raw_scale.get(in_)
# Padding context crops needs the mean in unprocessed input space.
mean = self.transformer.mean.get(in_)
if mean is not None:
inv_transpose = [transpose[t] for t in transpose]
crop_mean = mean.copy().transpose(inv_transpose)
if channel_order is not None:
channel_order_inverse = [channel_order.index(i)
for i in range(crop_mean.shape[2])]
crop_mean = crop_mean[:, :, channel_order_inverse]
if raw_scale is not None:
crop_mean /= raw_scale
self.crop_mean = crop_mean
else:
self.crop_mean = np.zeros(self.crop_dims, dtype=np.float32) | [
"def",
"configure_crop",
"(",
"self",
",",
"context_pad",
")",
":",
"# crop dimensions",
"in_",
"=",
"self",
".",
"inputs",
"[",
"0",
"]",
"tpose",
"=",
"self",
".",
"transformer",
".",
"transpose",
"[",
"in_",
"]",
"inv_tpose",
"=",
"[",
"tpose",
"[",
... | https://github.com/liulei01/DRBox/blob/b5c76e033c555c9009590ab384e1f7bd3c66c237/python/caffe/detector.py#L181-L216 | ||
ucb-bar/esp-llvm | 8aec2ae754fd66d4e73b9b777a9f20c4583a0f03 | bindings/python/llvm/object.py | python | Relocation.__init__ | (self, ptr) | Create a new relocation instance.
Relocations are created from objects derived from Section instances.
Therefore, this constructor should not be called outside of this
module. See Section.get_relocations() for the proper method to obtain
a Relocation instance. | Create a new relocation instance. | [
"Create",
"a",
"new",
"relocation",
"instance",
"."
] | def __init__(self, ptr):
"""Create a new relocation instance.
Relocations are created from objects derived from Section instances.
Therefore, this constructor should not be called outside of this
module. See Section.get_relocations() for the proper method to obtain
a Relocation instance.
"""
assert isinstance(ptr, c_object_p)
LLVMObject.__init__(self, ptr)
self.expired = False | [
"def",
"__init__",
"(",
"self",
",",
"ptr",
")",
":",
"assert",
"isinstance",
"(",
"ptr",
",",
"c_object_p",
")",
"LLVMObject",
".",
"__init__",
"(",
"self",
",",
"ptr",
")",
"self",
".",
"expired",
"=",
"False"
] | https://github.com/ucb-bar/esp-llvm/blob/8aec2ae754fd66d4e73b9b777a9f20c4583a0f03/bindings/python/llvm/object.py#L360-L372 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | build/toolchain/mac/linker_driver.py | python | _FindLinkerOutput | (full_args) | return full_args[output_flag_index + 1] | Finds the output of the linker by looking for the output flag in its
argument list. As this is a required linker argument, raises an error if it
cannot be found. | Finds the output of the linker by looking for the output flag in its
argument list. As this is a required linker argument, raises an error if it
cannot be found. | [
"Finds",
"the",
"output",
"of",
"the",
"linker",
"by",
"looking",
"for",
"the",
"output",
"flag",
"in",
"its",
"argument",
"list",
".",
"As",
"this",
"is",
"a",
"required",
"linker",
"argument",
"raises",
"an",
"error",
"if",
"it",
"cannot",
"be",
"found... | def _FindLinkerOutput(full_args):
"""Finds the output of the linker by looking for the output flag in its
argument list. As this is a required linker argument, raises an error if it
cannot be found.
"""
# The linker_driver.py script may be used to wrap either the compiler linker
# (uses -o to configure the output) or lipo (uses -output to configure the
# output). Since wrapping the compiler linker is the most likely possibility
# use try/except and fallback to checking for -output if -o is not found.
try:
output_flag_index = full_args.index('-o')
except ValueError:
output_flag_index = full_args.index('-output')
return full_args[output_flag_index + 1] | [
"def",
"_FindLinkerOutput",
"(",
"full_args",
")",
":",
"# The linker_driver.py script may be used to wrap either the compiler linker",
"# (uses -o to configure the output) or lipo (uses -output to configure the",
"# output). Since wrapping the compiler linker is the most likely possibility",
"# u... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/toolchain/mac/linker_driver.py#L183-L196 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_PP_Commands_REQUEST.toTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def toTpm(self, buf):
""" TpmMarshaller method """
buf.writeValArr(self.setList, 4)
buf.writeValArr(self.clearList, 4) | [
"def",
"toTpm",
"(",
"self",
",",
"buf",
")",
":",
"buf",
".",
"writeValArr",
"(",
"self",
".",
"setList",
",",
"4",
")",
"buf",
".",
"writeValArr",
"(",
"self",
".",
"clearList",
",",
"4",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L15772-L15775 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/cookies.py | python | RequestsCookieJar.update | (self, other) | Updates this jar with cookies from another CookieJar or dict-like | Updates this jar with cookies from another CookieJar or dict-like | [
"Updates",
"this",
"jar",
"with",
"cookies",
"from",
"another",
"CookieJar",
"or",
"dict",
"-",
"like"
] | def update(self, other):
"""Updates this jar with cookies from another CookieJar or dict-like"""
if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super(RequestsCookieJar, self).update(other) | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"cookielib",
".",
"CookieJar",
")",
":",
"for",
"cookie",
"in",
"other",
":",
"self",
".",
"set_cookie",
"(",
"copy",
".",
"copy",
"(",
"cookie",
")",
")",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/cookies.py#L348-L354 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | DC.CanGetTextExtent | (*args, **kwargs) | return _gdi_.DC_CanGetTextExtent(*args, **kwargs) | CanGetTextExtent(self) -> bool | CanGetTextExtent(self) -> bool | [
"CanGetTextExtent",
"(",
"self",
")",
"-",
">",
"bool"
] | def CanGetTextExtent(*args, **kwargs):
"""CanGetTextExtent(self) -> bool"""
return _gdi_.DC_CanGetTextExtent(*args, **kwargs) | [
"def",
"CanGetTextExtent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_CanGetTextExtent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L4291-L4293 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py2/google/protobuf/descriptor.py | python | EnumDescriptor.__init__ | (self, name, full_name, filename, values,
containing_type=None, options=None,
serialized_options=None, file=None, # pylint: disable=redefined-builtin
serialized_start=None, serialized_end=None, create_key=None) | Arguments are as described in the attribute description above.
Note that filename is an obsolete argument, that is not used anymore.
Please use file.name to access this as an attribute. | Arguments are as described in the attribute description above. | [
"Arguments",
"are",
"as",
"described",
"in",
"the",
"attribute",
"description",
"above",
"."
] | def __init__(self, name, full_name, filename, values,
containing_type=None, options=None,
serialized_options=None, file=None, # pylint: disable=redefined-builtin
serialized_start=None, serialized_end=None, create_key=None):
"""Arguments are as described in the attribute description above.
Note that filename is an obsolete argument, that is not used anymore.
Please use file.name to access this as an attribute.
"""
if create_key is not _internal_create_key:
_Deprecated('EnumDescriptor')
super(EnumDescriptor, self).__init__(
options, 'EnumOptions', name, full_name, file,
containing_type, serialized_start=serialized_start,
serialized_end=serialized_end, serialized_options=serialized_options)
self.values = values
for value in self.values:
value.type = self
self.values_by_name = dict((v.name, v) for v in values)
# Values are reversed to ensure that the first alias is retained.
self.values_by_number = dict((v.number, v) for v in reversed(values)) | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"full_name",
",",
"filename",
",",
"values",
",",
"containing_type",
"=",
"None",
",",
"options",
"=",
"None",
",",
"serialized_options",
"=",
"None",
",",
"file",
"=",
"None",
",",
"# pylint: disable=redefin... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/descriptor.py#L676-L698 | ||
carla-simulator/carla | 8854804f4d7748e14d937ec763a2912823a7e5f5 | PythonAPI/examples/no_rendering_mode.py | python | InputControl.start | (self, hud, world) | Assigns other initialized modules that input module needs. | Assigns other initialized modules that input module needs. | [
"Assigns",
"other",
"initialized",
"modules",
"that",
"input",
"module",
"needs",
"."
] | def start(self, hud, world):
"""Assigns other initialized modules that input module needs."""
self._hud = hud
self._world = world
self._hud.notification("Press 'H' or '?' for help.", seconds=4.0) | [
"def",
"start",
"(",
"self",
",",
"hud",
",",
"world",
")",
":",
"self",
".",
"_hud",
"=",
"hud",
"self",
".",
"_world",
"=",
"world",
"self",
".",
"_hud",
".",
"notification",
"(",
"\"Press 'H' or '?' for help.\"",
",",
"seconds",
"=",
"4.0",
")"
] | https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/PythonAPI/examples/no_rendering_mode.py#L1387-L1392 | ||
shedskin/shedskin | ae88dbca7b1d9671cd8be448cb0b497122758936 | examples/c64/cpu.py | python | CPU.BRK | (self, opcode) | software debugging (NMI) | software debugging (NMI) | [
"software",
"debugging",
"(",
"NMI",
")"
] | def BRK(self, opcode):
""" software debugging (NMI) """
self.consume_operand(1) # dummy so you can replace any 1-arg instruction's opcode by BRK.
old_PC = self.read_register(S_PC)
if old_PC - 2 == 0xF8A1 or old_PC - 2 == 0xF7BE or old_PC - 2 == 0xF72F: # tape
tape.call_hook(self, self.MMU, old_PC - 2)
else:
self.cause_interrupt(True) | [
"def",
"BRK",
"(",
"self",
",",
"opcode",
")",
":",
"self",
".",
"consume_operand",
"(",
"1",
")",
"# dummy so you can replace any 1-arg instruction's opcode by BRK.",
"old_PC",
"=",
"self",
".",
"read_register",
"(",
"S_PC",
")",
"if",
"old_PC",
"-",
"2",
"==",... | https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/c64/cpu.py#L1767-L1774 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/ops/logging_ops.py | python | get_summary_op | () | return summary_op | Returns a single Summary op that would run all summaries.
Either existing one from `SUMMARY_OP` collection or merges all existing
summaries.
Returns:
If no summaries were collected, returns None. Otherwise returns a scalar
`Tensor` of type `string` containing the serialized `Summary` protocol
buffer resulting from the merging. | Returns a single Summary op that would run all summaries. | [
"Returns",
"a",
"single",
"Summary",
"op",
"that",
"would",
"run",
"all",
"summaries",
"."
] | def get_summary_op():
"""Returns a single Summary op that would run all summaries.
Either existing one from `SUMMARY_OP` collection or merges all existing
summaries.
Returns:
If no summaries were collected, returns None. Otherwise returns a scalar
`Tensor` of type `string` containing the serialized `Summary` protocol
buffer resulting from the merging.
"""
summary_op = ops.get_collection(ops.GraphKeys.SUMMARY_OP)
if summary_op is not None:
if summary_op:
summary_op = summary_op[0]
else:
summary_op = None
if summary_op is None:
summary_op = merge_all_summaries()
if summary_op is not None:
ops.add_to_collection(ops.GraphKeys.SUMMARY_OP, summary_op)
return summary_op | [
"def",
"get_summary_op",
"(",
")",
":",
"summary_op",
"=",
"ops",
".",
"get_collection",
"(",
"ops",
".",
"GraphKeys",
".",
"SUMMARY_OP",
")",
"if",
"summary_op",
"is",
"not",
"None",
":",
"if",
"summary_op",
":",
"summary_op",
"=",
"summary_op",
"[",
"0",... | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/logging_ops.py#L274-L295 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/numpy/_op.py | python | log2 | (x, out=None, **kwargs) | return _pure_unary_func_helper(x, _api_internal.log2, _np.log2, out=out, **kwargs) | Base-2 logarithm of x.
Parameters
----------
x : ndarray or scalar
Input values.
out : ndarray or None
A location into which the result is stored.
If provided, it must have the same shape and type as the input.
If not provided or None, a freshly-allocated array is returned.
Returns
-------
y : ndarray
The logarithm base two of `x`, element-wise.
This is a scalar if `x` is a scalar.
Notes
-----
This function differs from the original `numpy.log2
<https://www.google.com/search?q=numpy+log2>`_ in
the following way(s):
- only ndarray or scalar is accpted as valid input, tuple of ndarray is not supported
- broadcasting to `out` of different shape is currently not supported
- when input is plain python numerics, the result will not be stored in the `out` param
Examples
--------
>>> x = np.array([0, 1, 2, 2**4])
>>> np.log2(x)
array([-inf, 0., 1., 4.]) | Base-2 logarithm of x. | [
"Base",
"-",
"2",
"logarithm",
"of",
"x",
"."
] | def log2(x, out=None, **kwargs):
"""
Base-2 logarithm of x.
Parameters
----------
x : ndarray or scalar
Input values.
out : ndarray or None
A location into which the result is stored.
If provided, it must have the same shape and type as the input.
If not provided or None, a freshly-allocated array is returned.
Returns
-------
y : ndarray
The logarithm base two of `x`, element-wise.
This is a scalar if `x` is a scalar.
Notes
-----
This function differs from the original `numpy.log2
<https://www.google.com/search?q=numpy+log2>`_ in
the following way(s):
- only ndarray or scalar is accpted as valid input, tuple of ndarray is not supported
- broadcasting to `out` of different shape is currently not supported
- when input is plain python numerics, the result will not be stored in the `out` param
Examples
--------
>>> x = np.array([0, 1, 2, 2**4])
>>> np.log2(x)
array([-inf, 0., 1., 4.])
"""
return _pure_unary_func_helper(x, _api_internal.log2, _np.log2, out=out, **kwargs) | [
"def",
"log2",
"(",
"x",
",",
"out",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_pure_unary_func_helper",
"(",
"x",
",",
"_api_internal",
".",
"log2",
",",
"_np",
".",
"log2",
",",
"out",
"=",
"out",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/numpy/_op.py#L3358-L3392 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | DoubleVar.__init__ | (self, master=None, value=None, name=None) | Construct a float variable.
MASTER can be given as master widget.
VALUE is an optional value (defaults to 0.0)
NAME is an optional Tcl name (defaults to PY_VARnum).
If NAME matches an existing variable and VALUE is omitted
then the existing value is retained. | Construct a float variable. | [
"Construct",
"a",
"float",
"variable",
"."
] | def __init__(self, master=None, value=None, name=None):
"""Construct a float variable.
MASTER can be given as master widget.
VALUE is an optional value (defaults to 0.0)
NAME is an optional Tcl name (defaults to PY_VARnum).
If NAME matches an existing variable and VALUE is omitted
then the existing value is retained.
"""
Variable.__init__(self, master, value, name) | [
"def",
"__init__",
"(",
"self",
",",
"master",
"=",
"None",
",",
"value",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"Variable",
".",
"__init__",
"(",
"self",
",",
"master",
",",
"value",
",",
"name",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L324-L334 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/ssd/dataset/pycocotools/coco.py | python | COCO.loadCats | (self, ids=[]) | Load cats with the specified ids.
:param ids (int array) : integer ids specifying cats
:return: cats (object array) : loaded cat objects | Load cats with the specified ids.
:param ids (int array) : integer ids specifying cats
:return: cats (object array) : loaded cat objects | [
"Load",
"cats",
"with",
"the",
"specified",
"ids",
".",
":",
"param",
"ids",
"(",
"int",
"array",
")",
":",
"integer",
"ids",
"specifying",
"cats",
":",
"return",
":",
"cats",
"(",
"object",
"array",
")",
":",
"loaded",
"cat",
"objects"
] | def loadCats(self, ids=[]):
"""
Load cats with the specified ids.
:param ids (int array) : integer ids specifying cats
:return: cats (object array) : loaded cat objects
"""
if type(ids) == list:
return [self.cats[id] for id in ids]
elif type(ids) == int:
return [self.cats[ids]] | [
"def",
"loadCats",
"(",
"self",
",",
"ids",
"=",
"[",
"]",
")",
":",
"if",
"type",
"(",
"ids",
")",
"==",
"list",
":",
"return",
"[",
"self",
".",
"cats",
"[",
"id",
"]",
"for",
"id",
"in",
"ids",
"]",
"elif",
"type",
"(",
"ids",
")",
"==",
... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/ssd/dataset/pycocotools/coco.py#L206-L215 | ||
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/gui/DirectGuiBase.py | python | DirectGuiBase.isinitoption | (self, option) | return self._optionInfo[option][DGG._OPT_FUNCTION] is DGG.INITOPT | Is this opition one that can only be specified at construction? | Is this opition one that can only be specified at construction? | [
"Is",
"this",
"opition",
"one",
"that",
"can",
"only",
"be",
"specified",
"at",
"construction?"
] | def isinitoption(self, option):
"""
Is this opition one that can only be specified at construction?
"""
return self._optionInfo[option][DGG._OPT_FUNCTION] is DGG.INITOPT | [
"def",
"isinitoption",
"(",
"self",
",",
"option",
")",
":",
"return",
"self",
".",
"_optionInfo",
"[",
"option",
"]",
"[",
"DGG",
".",
"_OPT_FUNCTION",
"]",
"is",
"DGG",
".",
"INITOPT"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/gui/DirectGuiBase.py#L281-L285 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/docs/bcdoc/restdoc.py | python | DocumentStructure.name | (self) | return self._name | The name of the document structure | The name of the document structure | [
"The",
"name",
"of",
"the",
"document",
"structure"
] | def name(self):
"""The name of the document structure"""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/docs/bcdoc/restdoc.py#L131-L133 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | ItemContainer.GetStringSelection | (*args, **kwargs) | return _core_.ItemContainer_GetStringSelection(*args, **kwargs) | GetStringSelection(self) -> String
Returns the label of the selected item or an empty string if no item
is selected. | GetStringSelection(self) -> String | [
"GetStringSelection",
"(",
"self",
")",
"-",
">",
"String"
] | def GetStringSelection(*args, **kwargs):
"""
GetStringSelection(self) -> String
Returns the label of the selected item or an empty string if no item
is selected.
"""
return _core_.ItemContainer_GetStringSelection(*args, **kwargs) | [
"def",
"GetStringSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"ItemContainer_GetStringSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L13012-L13019 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/grid.py | python | Grid.AutoSize | (*args, **kwargs) | return _grid.Grid_AutoSize(*args, **kwargs) | AutoSize(self) | AutoSize(self) | [
"AutoSize",
"(",
"self",
")"
] | def AutoSize(*args, **kwargs):
"""AutoSize(self)"""
return _grid.Grid_AutoSize(*args, **kwargs) | [
"def",
"AutoSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_AutoSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L1898-L1900 | |
l4ka/pistachio | 8be66aa9b85a774ad1b71dbd3a79c5c745a96273 | contrib/cml2/cmlsystem.py | python | CMLSystem.__dep_visible | (self, symbol) | return 1 | Do ancestry relations allow a symbol to be visible? | Do ancestry relations allow a symbol to be visible? | [
"Do",
"ancestry",
"relations",
"allow",
"a",
"symbol",
"to",
"be",
"visible?"
] | def __dep_visible(self, symbol):
"Do ancestry relations allow a symbol to be visible?"
# Note: we don't need to recurse here, assuming dependencies
# get propagated correctly.
for super in symbol.ancestors:
if not cml.evaluate(super):
self.debug_emit(2,self.lang["INVISANC"]%(symbol.name,super.name))
return 0
elif super.visibility and not cml.evaluate(super.visibility):
self.debug_emit(2,self.lang["INVISANC2"]%(symbol.name,super.name))
return 0
return 1 | [
"def",
"__dep_visible",
"(",
"self",
",",
"symbol",
")",
":",
"# Note: we don't need to recurse here, assuming dependencies",
"# get propagated correctly.",
"for",
"super",
"in",
"symbol",
".",
"ancestors",
":",
"if",
"not",
"cml",
".",
"evaluate",
"(",
"super",
")",
... | https://github.com/l4ka/pistachio/blob/8be66aa9b85a774ad1b71dbd3a79c5c745a96273/contrib/cml2/cmlsystem.py#L701-L712 | |
VowpalWabbit/vowpal_wabbit | 866b8fa88ff85a957c7eb72065ea44518b9ba416 | python/vowpalwabbit/pyvw.py | python | Example.feature_weight | (self, ns: Union[NamespaceId, str, int], i: int) | return pylibvw.example.feature_weight(self, self.get_ns(ns).ord_ns, i) | Get the value(weight) associated with a given feature id
Args:
ns: namespace used to get the feature id
i: to get the weight of i-th feature in the given ns. It must range
from 0 to self.num_features_in(ns)-1
Returns:
weight(value) of the i-th feature of given ns | Get the value(weight) associated with a given feature id | [
"Get",
"the",
"value",
"(",
"weight",
")",
"associated",
"with",
"a",
"given",
"feature",
"id"
] | def feature_weight(self, ns: Union[NamespaceId, str, int], i: int) -> float:
"""Get the value(weight) associated with a given feature id
Args:
ns: namespace used to get the feature id
i: to get the weight of i-th feature in the given ns. It must range
from 0 to self.num_features_in(ns)-1
Returns:
weight(value) of the i-th feature of given ns
"""
return pylibvw.example.feature_weight(self, self.get_ns(ns).ord_ns, i) | [
"def",
"feature_weight",
"(",
"self",
",",
"ns",
":",
"Union",
"[",
"NamespaceId",
",",
"str",
",",
"int",
"]",
",",
"i",
":",
"int",
")",
"->",
"float",
":",
"return",
"pylibvw",
".",
"example",
".",
"feature_weight",
"(",
"self",
",",
"self",
".",
... | https://github.com/VowpalWabbit/vowpal_wabbit/blob/866b8fa88ff85a957c7eb72065ea44518b9ba416/python/vowpalwabbit/pyvw.py#L1547-L1558 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/typing.py | python | _subs_tvars | (tp, tvars, subs) | return tp.copy_with(tuple(new_args)) | Substitute type variables 'tvars' with substitutions 'subs'.
These two must have the same length. | Substitute type variables 'tvars' with substitutions 'subs'.
These two must have the same length. | [
"Substitute",
"type",
"variables",
"tvars",
"with",
"substitutions",
"subs",
".",
"These",
"two",
"must",
"have",
"the",
"same",
"length",
"."
] | def _subs_tvars(tp, tvars, subs):
"""Substitute type variables 'tvars' with substitutions 'subs'.
These two must have the same length.
"""
if not isinstance(tp, _GenericAlias):
return tp
new_args = list(tp.__args__)
for a, arg in enumerate(tp.__args__):
if isinstance(arg, TypeVar):
for i, tvar in enumerate(tvars):
if arg == tvar:
new_args[a] = subs[i]
else:
new_args[a] = _subs_tvars(arg, tvars, subs)
if tp.__origin__ is Union:
return Union[tuple(new_args)]
return tp.copy_with(tuple(new_args)) | [
"def",
"_subs_tvars",
"(",
"tp",
",",
"tvars",
",",
"subs",
")",
":",
"if",
"not",
"isinstance",
"(",
"tp",
",",
"_GenericAlias",
")",
":",
"return",
"tp",
"new_args",
"=",
"list",
"(",
"tp",
".",
"__args__",
")",
"for",
"a",
",",
"arg",
"in",
"enu... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/typing.py#L180-L196 | |
google/omaha | 61e8c2833fd69c9a13978400108e5b9ebff24a09 | omaha/installers/tag_meta_installers.py | python | GetAllSetupExeInDirectory | (dir) | return ret_files | Creates a number of application specific binaries for the
passed in binary.
Args:
dir: The input directory.
Returns:
A list of files that are match the regex:
TEST_GoogleUpdateSetup_.*.exe$|^GoogleUpdateSetup_.*.exe$ | Creates a number of application specific binaries for the
passed in binary.
Args:
dir: The input directory.
Returns:
A list of files that are match the regex:
TEST_GoogleUpdateSetup_.*.exe$|^GoogleUpdateSetup_.*.exe$ | [
"Creates",
"a",
"number",
"of",
"application",
"specific",
"binaries",
"for",
"the",
"passed",
"in",
"binary",
".",
"Args",
":",
"dir",
":",
"The",
"input",
"directory",
".",
"Returns",
":",
"A",
"list",
"of",
"files",
"that",
"are",
"match",
"the",
"reg... | def GetAllSetupExeInDirectory(dir):
"""Creates a number of application specific binaries for the
passed in binary.
Args:
dir: The input directory.
Returns:
A list of files that are match the regex:
TEST_GoogleUpdateSetup_.*.exe$|^GoogleUpdateSetup_.*.exe$
"""
ret_files = []
files = os.listdir(dir)
for file in files:
regex = re.compile('^TEST_GoogleUpdateSetup_.*.exe$|'
'^GoogleUpdateSetup_.*.exe$')
if not regex.match(file):
continue
ret_files.append(file)
return ret_files | [
"def",
"GetAllSetupExeInDirectory",
"(",
"dir",
")",
":",
"ret_files",
"=",
"[",
"]",
"files",
"=",
"os",
".",
"listdir",
"(",
"dir",
")",
"for",
"file",
"in",
"files",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"'^TEST_GoogleUpdateSetup_.*.exe$|'",
"'^... | https://github.com/google/omaha/blob/61e8c2833fd69c9a13978400108e5b9ebff24a09/omaha/installers/tag_meta_installers.py#L199-L216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.