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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | clang/bindings/python/clang/cindex.py | python | Cursor.get_template_argument_kind | (self, num) | return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num) | Returns the TemplateArgumentKind for the indicated template
argument. | Returns the TemplateArgumentKind for the indicated template
argument. | [
"Returns",
"the",
"TemplateArgumentKind",
"for",
"the",
"indicated",
"template",
"argument",
"."
] | def get_template_argument_kind(self, num):
"""Returns the TemplateArgumentKind for the indicated template
argument."""
return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num) | [
"def",
"get_template_argument_kind",
"(",
"self",
",",
"num",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_Cursor_getTemplateArgumentKind",
"(",
"self",
",",
"num",
")"
] | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/bindings/python/clang/cindex.py#L1810-L1813 | |
manutdzou/KITTI_SSD | 5b620c2f291d36a0fe14489214f22a992f173f44 | scripts/cpp_lint.py | python | _CppLintState.SetOutputFormat | (self, output_format) | Sets the output format for errors. | Sets the output format for errors. | [
"Sets",
"the",
"output",
"format",
"for",
"errors",
"."
] | def SetOutputFormat(self, output_format):
"""Sets the output format for errors."""
self.output_format = output_format | [
"def",
"SetOutputFormat",
"(",
"self",
",",
"output_format",
")",
":",
"self",
".",
"output_format",
"=",
"output_format"
] | https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/scripts/cpp_lint.py#L703-L705 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PropertyGridManager.GetToolBar | (*args, **kwargs) | return _propgrid.PropertyGridManager_GetToolBar(*args, **kwargs) | GetToolBar(self) -> wxToolBar | GetToolBar(self) -> wxToolBar | [
"GetToolBar",
"(",
"self",
")",
"-",
">",
"wxToolBar"
] | def GetToolBar(*args, **kwargs):
"""GetToolBar(self) -> wxToolBar"""
return _propgrid.PropertyGridManager_GetToolBar(*args, **kwargs) | [
"def",
"GetToolBar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridManager_GetToolBar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L3520-L3522 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py | python | cli | () | Command-line interface (looks at sys.argv to decide what to do). | Command-line interface (looks at sys.argv to decide what to do). | [
"Command",
"-",
"line",
"interface",
"(",
"looks",
"at",
"sys",
".",
"argv",
"to",
"decide",
"what",
"to",
"do",
")",
"."
] | def cli():
"""Command-line interface (looks at sys.argv to decide what to do)."""
import getopt
class BadUsage(Exception): pass
_adjust_cli_sys_path()
try:
opts, args = getopt.getopt(sys.argv[1:], 'bk:n:p:w')
writing = False
start_server = False
open_browser = False
port = 0
hostname = 'localhost'
for opt, val in opts:
if opt == '-b':
start_server = True
open_browser = True
if opt == '-k':
apropos(val)
return
if opt == '-p':
start_server = True
port = val
if opt == '-w':
writing = True
if opt == '-n':
start_server = True
hostname = val
if start_server:
browse(port, hostname=hostname, open_browser=open_browser)
return
if not args: raise BadUsage
for arg in args:
if ispath(arg) and not os.path.exists(arg):
print('file %r does not exist' % arg)
break
try:
if ispath(arg) and os.path.isfile(arg):
arg = importfile(arg)
if writing:
if ispath(arg) and os.path.isdir(arg):
writedocs(arg)
else:
writedoc(arg)
else:
help.help(arg)
except ErrorDuringImport as value:
print(value)
except (getopt.error, BadUsage):
cmd = os.path.splitext(os.path.basename(sys.argv[0]))[0]
print("""pydoc - the Python documentation tool
{cmd} <name> ...
Show text documentation on something. <name> may be the name of a
Python keyword, topic, function, module, or package, or a dotted
reference to a class or function within a module or module in a
package. If <name> contains a '{sep}', it is used as the path to a
Python source file to document. If name is 'keywords', 'topics',
or 'modules', a listing of these things is displayed.
{cmd} -k <keyword>
Search for a keyword in the synopsis lines of all available modules.
{cmd} -n <hostname>
Start an HTTP server with the given hostname (default: localhost).
{cmd} -p <port>
Start an HTTP server on the given port on the local machine. Port
number 0 can be used to get an arbitrary unused port.
{cmd} -b
Start an HTTP server on an arbitrary unused port and open a Web browser
to interactively browse documentation. This option can be used in
combination with -n and/or -p.
{cmd} -w <name> ...
Write out the HTML documentation for a module to a file in the current
directory. If <name> contains a '{sep}', it is treated as a filename; if
it names a directory, documentation is written for all the contents.
""".format(cmd=cmd, sep=os.sep)) | [
"def",
"cli",
"(",
")",
":",
"import",
"getopt",
"class",
"BadUsage",
"(",
"Exception",
")",
":",
"pass",
"_adjust_cli_sys_path",
"(",
")",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
",",
"'bk:n:p:w'",
")",
"writing",
"=",
"False",
"start_server",
"=",
"False",
"open_browser",
"=",
"False",
"port",
"=",
"0",
"hostname",
"=",
"'localhost'",
"for",
"opt",
",",
"val",
"in",
"opts",
":",
"if",
"opt",
"==",
"'-b'",
":",
"start_server",
"=",
"True",
"open_browser",
"=",
"True",
"if",
"opt",
"==",
"'-k'",
":",
"apropos",
"(",
"val",
")",
"return",
"if",
"opt",
"==",
"'-p'",
":",
"start_server",
"=",
"True",
"port",
"=",
"val",
"if",
"opt",
"==",
"'-w'",
":",
"writing",
"=",
"True",
"if",
"opt",
"==",
"'-n'",
":",
"start_server",
"=",
"True",
"hostname",
"=",
"val",
"if",
"start_server",
":",
"browse",
"(",
"port",
",",
"hostname",
"=",
"hostname",
",",
"open_browser",
"=",
"open_browser",
")",
"return",
"if",
"not",
"args",
":",
"raise",
"BadUsage",
"for",
"arg",
"in",
"args",
":",
"if",
"ispath",
"(",
"arg",
")",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"arg",
")",
":",
"print",
"(",
"'file %r does not exist'",
"%",
"arg",
")",
"break",
"try",
":",
"if",
"ispath",
"(",
"arg",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"arg",
")",
":",
"arg",
"=",
"importfile",
"(",
"arg",
")",
"if",
"writing",
":",
"if",
"ispath",
"(",
"arg",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"arg",
")",
":",
"writedocs",
"(",
"arg",
")",
"else",
":",
"writedoc",
"(",
"arg",
")",
"else",
":",
"help",
".",
"help",
"(",
"arg",
")",
"except",
"ErrorDuringImport",
"as",
"value",
":",
"print",
"(",
"value",
")",
"except",
"(",
"getopt",
".",
"error",
",",
"BadUsage",
")",
":",
"cmd",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
"[",
"0",
"]",
"print",
"(",
"\"\"\"pydoc - the Python documentation tool\n\n{cmd} <name> ...\n Show text documentation on something. <name> may be the name of a\n Python keyword, topic, function, module, or package, or a dotted\n reference to a class or function within a module or module in a\n package. If <name> contains a '{sep}', it is used as the path to a\n Python source file to document. If name is 'keywords', 'topics',\n or 'modules', a listing of these things is displayed.\n\n{cmd} -k <keyword>\n Search for a keyword in the synopsis lines of all available modules.\n\n{cmd} -n <hostname>\n Start an HTTP server with the given hostname (default: localhost).\n\n{cmd} -p <port>\n Start an HTTP server on the given port on the local machine. Port\n number 0 can be used to get an arbitrary unused port.\n\n{cmd} -b\n Start an HTTP server on an arbitrary unused port and open a Web browser\n to interactively browse documentation. This option can be used in\n combination with -n and/or -p.\n\n{cmd} -w <name> ...\n Write out the HTML documentation for a module to a file in the current\n directory. If <name> contains a '{sep}', it is treated as a filename; if\n it names a directory, documentation is written for all the contents.\n\"\"\"",
".",
"format",
"(",
"cmd",
"=",
"cmd",
",",
"sep",
"=",
"os",
".",
"sep",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py#L2660-L2743 | ||
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/RomApplication/python_scripts/structural_mechanics_analysis_rom.py | python | StructuralMechanicsAnalysisROM.ModifyAfterSolverInitialize | (self) | Here is where the ROM_BASIS is imposed to each node | Here is where the ROM_BASIS is imposed to each node | [
"Here",
"is",
"where",
"the",
"ROM_BASIS",
"is",
"imposed",
"to",
"each",
"node"
] | def ModifyAfterSolverInitialize(self):
"""Here is where the ROM_BASIS is imposed to each node"""
super().ModifyAfterSolverInitialize()
computing_model_part = self._solver.GetComputingModelPart()
with open('RomParameters.json') as f:
data = json.load(f)
nodal_dofs = len(data["rom_settings"]["nodal_unknowns"])
nodal_modes = data["nodal_modes"]
counter = 0
rom_dofs= self.project_parameters["solver_settings"]["rom_settings"]["number_of_rom_dofs"].GetInt()
for node in computing_model_part.Nodes:
aux = KratosMultiphysics.Matrix(nodal_dofs, rom_dofs)
for j in range(nodal_dofs):
Counter=str(node.Id)
for i in range(rom_dofs):
aux[j,i] = nodal_modes[Counter][j][i]
node.SetValue(romapp.ROM_BASIS, aux ) # ROM basis
counter+=1
if self.hyper_reduction_element_selector != None:
if self.hyper_reduction_element_selector.Name == "EmpiricalCubature":
self.ResidualUtilityObject = romapp.RomResidualsUtility(self._GetSolver().GetComputingModelPart(), self.project_parameters["solver_settings"]["rom_settings"], self._GetSolver()._GetScheme()) | [
"def",
"ModifyAfterSolverInitialize",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"ModifyAfterSolverInitialize",
"(",
")",
"computing_model_part",
"=",
"self",
".",
"_solver",
".",
"GetComputingModelPart",
"(",
")",
"with",
"open",
"(",
"'RomParameters.json'",
")",
"as",
"f",
":",
"data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"nodal_dofs",
"=",
"len",
"(",
"data",
"[",
"\"rom_settings\"",
"]",
"[",
"\"nodal_unknowns\"",
"]",
")",
"nodal_modes",
"=",
"data",
"[",
"\"nodal_modes\"",
"]",
"counter",
"=",
"0",
"rom_dofs",
"=",
"self",
".",
"project_parameters",
"[",
"\"solver_settings\"",
"]",
"[",
"\"rom_settings\"",
"]",
"[",
"\"number_of_rom_dofs\"",
"]",
".",
"GetInt",
"(",
")",
"for",
"node",
"in",
"computing_model_part",
".",
"Nodes",
":",
"aux",
"=",
"KratosMultiphysics",
".",
"Matrix",
"(",
"nodal_dofs",
",",
"rom_dofs",
")",
"for",
"j",
"in",
"range",
"(",
"nodal_dofs",
")",
":",
"Counter",
"=",
"str",
"(",
"node",
".",
"Id",
")",
"for",
"i",
"in",
"range",
"(",
"rom_dofs",
")",
":",
"aux",
"[",
"j",
",",
"i",
"]",
"=",
"nodal_modes",
"[",
"Counter",
"]",
"[",
"j",
"]",
"[",
"i",
"]",
"node",
".",
"SetValue",
"(",
"romapp",
".",
"ROM_BASIS",
",",
"aux",
")",
"# ROM basis",
"counter",
"+=",
"1",
"if",
"self",
".",
"hyper_reduction_element_selector",
"!=",
"None",
":",
"if",
"self",
".",
"hyper_reduction_element_selector",
".",
"Name",
"==",
"\"EmpiricalCubature\"",
":",
"self",
".",
"ResidualUtilityObject",
"=",
"romapp",
".",
"RomResidualsUtility",
"(",
"self",
".",
"_GetSolver",
"(",
")",
".",
"GetComputingModelPart",
"(",
")",
",",
"self",
".",
"project_parameters",
"[",
"\"solver_settings\"",
"]",
"[",
"\"rom_settings\"",
"]",
",",
"self",
".",
"_GetSolver",
"(",
")",
".",
"_GetScheme",
"(",
")",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/RomApplication/python_scripts/structural_mechanics_analysis_rom.py#L39-L59 | ||
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/npp-gh20210917/scintilla/scripts/Dependencies.py | python | WriteDependencies | (output, dependencies) | Write a list of dependencies out to a stream. | Write a list of dependencies out to a stream. | [
"Write",
"a",
"list",
"of",
"dependencies",
"out",
"to",
"a",
"stream",
"."
] | def WriteDependencies(output, dependencies):
""" Write a list of dependencies out to a stream. """
output.write(TextFromDependencies(dependencies)) | [
"def",
"WriteDependencies",
"(",
"output",
",",
"dependencies",
")",
":",
"output",
".",
"write",
"(",
"TextFromDependencies",
"(",
"dependencies",
")",
")"
] | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/npp-gh20210917/scintilla/scripts/Dependencies.py#L145-L147 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | TextAttrDimension.SetPosition | (*args, **kwargs) | return _richtext.TextAttrDimension_SetPosition(*args, **kwargs) | SetPosition(self, int pos) | SetPosition(self, int pos) | [
"SetPosition",
"(",
"self",
"int",
"pos",
")"
] | def SetPosition(*args, **kwargs):
"""SetPosition(self, int pos)"""
return _richtext.TextAttrDimension_SetPosition(*args, **kwargs) | [
"def",
"SetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"TextAttrDimension_SetPosition",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L180-L182 | |
QMCPACK/qmcpack | d0948ab455e38364458740cc8e2239600a14c5cd | nexus/lib/gaussian_process.py | python | GPState.state_filepath | (self,label=None,path=None,prefix='gp_state',filepath=None) | return filepath | Returns the filepath used to store the state of the current iteration. | Returns the filepath used to store the state of the current iteration. | [
"Returns",
"the",
"filepath",
"used",
"to",
"store",
"the",
"state",
"of",
"the",
"current",
"iteration",
"."
] | def state_filepath(self,label=None,path=None,prefix='gp_state',filepath=None):
"""
Returns the filepath used to store the state of the current iteration.
"""
if filepath is not None:
return filepath
#end if
if path is None:
path = self.save_path
#end if
filename = prefix+'_iteration_{0}'.format(self.iteration)
if label is not None:
filename += '_'+label
#end if
filename += '.p'
filepath = os.path.join(path,filename)
return filepath | [
"def",
"state_filepath",
"(",
"self",
",",
"label",
"=",
"None",
",",
"path",
"=",
"None",
",",
"prefix",
"=",
"'gp_state'",
",",
"filepath",
"=",
"None",
")",
":",
"if",
"filepath",
"is",
"not",
"None",
":",
"return",
"filepath",
"#end if",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"self",
".",
"save_path",
"#end if",
"filename",
"=",
"prefix",
"+",
"'_iteration_{0}'",
".",
"format",
"(",
"self",
".",
"iteration",
")",
"if",
"label",
"is",
"not",
"None",
":",
"filename",
"+=",
"'_'",
"+",
"label",
"#end if",
"filename",
"+=",
"'.p'",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"return",
"filepath"
] | https://github.com/QMCPACK/qmcpack/blob/d0948ab455e38364458740cc8e2239600a14c5cd/nexus/lib/gaussian_process.py#L1392-L1408 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/node/structure.py | python | StructureNode.ExpandVariables | (self) | Variable expansion on structures is controlled by an XML attribute.
However, old files assume that expansion is always on for Rc files.
Returns:
A boolean. | Variable expansion on structures is controlled by an XML attribute. | [
"Variable",
"expansion",
"on",
"structures",
"is",
"controlled",
"by",
"an",
"XML",
"attribute",
"."
] | def ExpandVariables(self):
'''Variable expansion on structures is controlled by an XML attribute.
However, old files assume that expansion is always on for Rc files.
Returns:
A boolean.
'''
attrs = self.GetRoot().attrs
if 'grit_version' in attrs and attrs['grit_version'] > 1:
return self.attrs['expand_variables'] == 'true'
else:
return (self.attrs['expand_variables'] == 'true' or
self.attrs['file'].lower().endswith('.rc')) | [
"def",
"ExpandVariables",
"(",
"self",
")",
":",
"attrs",
"=",
"self",
".",
"GetRoot",
"(",
")",
".",
"attrs",
"if",
"'grit_version'",
"in",
"attrs",
"and",
"attrs",
"[",
"'grit_version'",
"]",
">",
"1",
":",
"return",
"self",
".",
"attrs",
"[",
"'expand_variables'",
"]",
"==",
"'true'",
"else",
":",
"return",
"(",
"self",
".",
"attrs",
"[",
"'expand_variables'",
"]",
"==",
"'true'",
"or",
"self",
".",
"attrs",
"[",
"'file'",
"]",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.rc'",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/node/structure.py#L251-L264 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/cli/cmdoptions.py | python | check_install_build_global | (options, check_options=None) | Disable wheels if per-setup.py call options are set.
:param options: The OptionParser options to update.
:param check_options: The options to check, if not supplied defaults to
options. | Disable wheels if per-setup.py call options are set. | [
"Disable",
"wheels",
"if",
"per",
"-",
"setup",
".",
"py",
"call",
"options",
"are",
"set",
"."
] | def check_install_build_global(options, check_options=None):
# type: (Values, Optional[Values]) -> None
"""Disable wheels if per-setup.py call options are set.
:param options: The OptionParser options to update.
:param check_options: The options to check, if not supplied defaults to
options.
"""
if check_options is None:
check_options = options
def getname(n):
# type: (str) -> Optional[Any]
return getattr(check_options, n, None)
names = ["build_options", "global_options", "install_options"]
if any(map(getname, names)):
control = options.format_control
control.disallow_binaries()
warnings.warn(
'Disabling all use of wheels due to the use of --build-option '
'/ --global-option / --install-option.', stacklevel=2,
) | [
"def",
"check_install_build_global",
"(",
"options",
",",
"check_options",
"=",
"None",
")",
":",
"# type: (Values, Optional[Values]) -> None",
"if",
"check_options",
"is",
"None",
":",
"check_options",
"=",
"options",
"def",
"getname",
"(",
"n",
")",
":",
"# type: (str) -> Optional[Any]",
"return",
"getattr",
"(",
"check_options",
",",
"n",
",",
"None",
")",
"names",
"=",
"[",
"\"build_options\"",
",",
"\"global_options\"",
",",
"\"install_options\"",
"]",
"if",
"any",
"(",
"map",
"(",
"getname",
",",
"names",
")",
")",
":",
"control",
"=",
"options",
".",
"format_control",
"control",
".",
"disallow_binaries",
"(",
")",
"warnings",
".",
"warn",
"(",
"'Disabling all use of wheels due to the use of --build-option '",
"'/ --global-option / --install-option.'",
",",
"stacklevel",
"=",
"2",
",",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/cli/cmdoptions.py#L67-L88 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBPlatformConnectOptions.DisableRsync | (self) | return _lldb.SBPlatformConnectOptions_DisableRsync(self) | DisableRsync(self) | DisableRsync(self) | [
"DisableRsync",
"(",
"self",
")"
] | def DisableRsync(self):
"""DisableRsync(self)"""
return _lldb.SBPlatformConnectOptions_DisableRsync(self) | [
"def",
"DisableRsync",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBPlatformConnectOptions_DisableRsync",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L6681-L6683 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/platform.py | python | _mac_ver_gestalt | () | return release,versioninfo,machine | Thanks to Mark R. Levinson for mailing documentation links and
code examples for this function. Documentation for the
gestalt() API is available online at:
http://www.rgaros.nl/gestalt/ | Thanks to Mark R. Levinson for mailing documentation links and
code examples for this function. Documentation for the
gestalt() API is available online at: | [
"Thanks",
"to",
"Mark",
"R",
".",
"Levinson",
"for",
"mailing",
"documentation",
"links",
"and",
"code",
"examples",
"for",
"this",
"function",
".",
"Documentation",
"for",
"the",
"gestalt",
"()",
"API",
"is",
"available",
"online",
"at",
":"
] | def _mac_ver_gestalt():
"""
Thanks to Mark R. Levinson for mailing documentation links and
code examples for this function. Documentation for the
gestalt() API is available online at:
http://www.rgaros.nl/gestalt/
"""
# Check whether the version info module is available
try:
import gestalt
import MacOS
except ImportError:
return None
# Get the infos
sysv,sysa = _mac_ver_lookup(('sysv','sysa'))
# Decode the infos
if sysv:
major = (sysv & 0xFF00) >> 8
minor = (sysv & 0x00F0) >> 4
patch = (sysv & 0x000F)
if (major, minor) >= (10, 4):
# the 'sysv' gestald cannot return patchlevels
# higher than 9. Apple introduced 3 new
# gestalt codes in 10.4 to deal with this
# issue (needed because patch levels can
# run higher than 9, such as 10.4.11)
major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
release = '%i.%i.%i' %(major, minor, patch)
else:
release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
if sysa:
machine = {0x1: '68k',
0x2: 'PowerPC',
0xa: 'i386'}.get(sysa,'')
versioninfo=('', '', '')
return release,versioninfo,machine | [
"def",
"_mac_ver_gestalt",
"(",
")",
":",
"# Check whether the version info module is available",
"try",
":",
"import",
"gestalt",
"import",
"MacOS",
"except",
"ImportError",
":",
"return",
"None",
"# Get the infos",
"sysv",
",",
"sysa",
"=",
"_mac_ver_lookup",
"(",
"(",
"'sysv'",
",",
"'sysa'",
")",
")",
"# Decode the infos",
"if",
"sysv",
":",
"major",
"=",
"(",
"sysv",
"&",
"0xFF00",
")",
">>",
"8",
"minor",
"=",
"(",
"sysv",
"&",
"0x00F0",
")",
">>",
"4",
"patch",
"=",
"(",
"sysv",
"&",
"0x000F",
")",
"if",
"(",
"major",
",",
"minor",
")",
">=",
"(",
"10",
",",
"4",
")",
":",
"# the 'sysv' gestald cannot return patchlevels",
"# higher than 9. Apple introduced 3 new",
"# gestalt codes in 10.4 to deal with this",
"# issue (needed because patch levels can",
"# run higher than 9, such as 10.4.11)",
"major",
",",
"minor",
",",
"patch",
"=",
"_mac_ver_lookup",
"(",
"(",
"'sys1'",
",",
"'sys2'",
",",
"'sys3'",
")",
")",
"release",
"=",
"'%i.%i.%i'",
"%",
"(",
"major",
",",
"minor",
",",
"patch",
")",
"else",
":",
"release",
"=",
"'%s.%i.%i'",
"%",
"(",
"_bcd2str",
"(",
"major",
")",
",",
"minor",
",",
"patch",
")",
"if",
"sysa",
":",
"machine",
"=",
"{",
"0x1",
":",
"'68k'",
",",
"0x2",
":",
"'PowerPC'",
",",
"0xa",
":",
"'i386'",
"}",
".",
"get",
"(",
"sysa",
",",
"''",
")",
"versioninfo",
"=",
"(",
"''",
",",
"''",
",",
"''",
")",
"return",
"release",
",",
"versioninfo",
",",
"machine"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/platform.py#L735-L774 | |
senlinuc/caffe_ocr | 81642f61ea8f888e360cca30e08e05b7bc6d4556 | tools/extra/resize_and_crop_images.py | python | OpenCVResizeCrop.resize_and_crop_image | (self, input_file, output_file, output_side_length = 256) | Takes an image name, resize it and crop the center square | Takes an image name, resize it and crop the center square | [
"Takes",
"an",
"image",
"name",
"resize",
"it",
"and",
"crop",
"the",
"center",
"square"
] | def resize_and_crop_image(self, input_file, output_file, output_side_length = 256):
'''Takes an image name, resize it and crop the center square
'''
img = cv2.imread(input_file)
height, width, depth = img.shape
new_height = output_side_length
new_width = output_side_length
if height > width:
new_height = output_side_length * height / width
else:
new_width = output_side_length * width / height
resized_img = cv2.resize(img, (new_width, new_height))
height_offset = (new_height - output_side_length) / 2
width_offset = (new_width - output_side_length) / 2
cropped_img = resized_img[height_offset:height_offset + output_side_length,
width_offset:width_offset + output_side_length]
cv2.imwrite(output_file, cropped_img) | [
"def",
"resize_and_crop_image",
"(",
"self",
",",
"input_file",
",",
"output_file",
",",
"output_side_length",
"=",
"256",
")",
":",
"img",
"=",
"cv2",
".",
"imread",
"(",
"input_file",
")",
"height",
",",
"width",
",",
"depth",
"=",
"img",
".",
"shape",
"new_height",
"=",
"output_side_length",
"new_width",
"=",
"output_side_length",
"if",
"height",
">",
"width",
":",
"new_height",
"=",
"output_side_length",
"*",
"height",
"/",
"width",
"else",
":",
"new_width",
"=",
"output_side_length",
"*",
"width",
"/",
"height",
"resized_img",
"=",
"cv2",
".",
"resize",
"(",
"img",
",",
"(",
"new_width",
",",
"new_height",
")",
")",
"height_offset",
"=",
"(",
"new_height",
"-",
"output_side_length",
")",
"/",
"2",
"width_offset",
"=",
"(",
"new_width",
"-",
"output_side_length",
")",
"/",
"2",
"cropped_img",
"=",
"resized_img",
"[",
"height_offset",
":",
"height_offset",
"+",
"output_side_length",
",",
"width_offset",
":",
"width_offset",
"+",
"output_side_length",
"]",
"cv2",
".",
"imwrite",
"(",
"output_file",
",",
"cropped_img",
")"
] | https://github.com/senlinuc/caffe_ocr/blob/81642f61ea8f888e360cca30e08e05b7bc6d4556/tools/extra/resize_and_crop_images.py#L20-L36 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/baseparser.py | python | ConfigOptionParser.get_environ_vars | (self) | Returns a generator with all environmental vars with prefix PIP_ | Returns a generator with all environmental vars with prefix PIP_ | [
"Returns",
"a",
"generator",
"with",
"all",
"environmental",
"vars",
"with",
"prefix",
"PIP_"
] | def get_environ_vars(self):
"""Returns a generator with all environmental vars with prefix PIP_"""
for key, val in os.environ.items():
if _environ_prefix_re.search(key):
yield (_environ_prefix_re.sub("", key).lower(), val) | [
"def",
"get_environ_vars",
"(",
"self",
")",
":",
"for",
"key",
",",
"val",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
":",
"if",
"_environ_prefix_re",
".",
"search",
"(",
"key",
")",
":",
"yield",
"(",
"_environ_prefix_re",
".",
"sub",
"(",
"\"\"",
",",
"key",
")",
".",
"lower",
"(",
")",
",",
"val",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/baseparser.py#L246-L250 | ||
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/policy.py | python | TabularPolicy.policy_for_key | (self, key) | return self.action_probability_array[self.state_lookup[key]] | Returns the policy as a vector given a state key string.
Args:
key: A key for the specified state.
Returns:
A vector of probabilities, one per action. This is a slice of the
backing policy array, and so slice or index assignment will update the
policy. For example:
```
tabular_policy.policy_for_key(s)[:] = [0.1, 0.5, 0.4]
``` | Returns the policy as a vector given a state key string. | [
"Returns",
"the",
"policy",
"as",
"a",
"vector",
"given",
"a",
"state",
"key",
"string",
"."
] | def policy_for_key(self, key):
"""Returns the policy as a vector given a state key string.
Args:
key: A key for the specified state.
Returns:
A vector of probabilities, one per action. This is a slice of the
backing policy array, and so slice or index assignment will update the
policy. For example:
```
tabular_policy.policy_for_key(s)[:] = [0.1, 0.5, 0.4]
```
"""
return self.action_probability_array[self.state_lookup[key]] | [
"def",
"policy_for_key",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"action_probability_array",
"[",
"self",
".",
"state_lookup",
"[",
"key",
"]",
"]"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/policy.py#L315-L329 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/wallet.py | python | Wallet.delta_withdrawn | (self, delta_withdrawn) | Sets the delta_withdrawn of this Wallet.
:param delta_withdrawn: The delta_withdrawn of this Wallet. # noqa: E501
:type: float | Sets the delta_withdrawn of this Wallet. | [
"Sets",
"the",
"delta_withdrawn",
"of",
"this",
"Wallet",
"."
] | def delta_withdrawn(self, delta_withdrawn):
"""Sets the delta_withdrawn of this Wallet.
:param delta_withdrawn: The delta_withdrawn of this Wallet. # noqa: E501
:type: float
"""
self._delta_withdrawn = delta_withdrawn | [
"def",
"delta_withdrawn",
"(",
"self",
",",
"delta_withdrawn",
")",
":",
"self",
".",
"_delta_withdrawn",
"=",
"delta_withdrawn"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/wallet.py#L372-L380 | ||
google/clif | cab24d6a105609a65c95a36a1712ae3c20c7b5df | clif/python/pyext.py | python | Module.GenInitFunction | (self, api_source_h) | Generate a function to create the module and initialize it. | Generate a function to create the module and initialize it. | [
"Generate",
"a",
"function",
"to",
"create",
"the",
"module",
"and",
"initialize",
"it",
"."
] | def GenInitFunction(self, api_source_h):
"""Generate a function to create the module and initialize it."""
assert not self.nested, 'Stack was not fully processed'
for s in gen.InitFunction('CLIF-generated module for %s' % api_source_h,
gen.MethodDef.name if self.methods else 'nullptr',
self.init, self.dict):
yield s | [
"def",
"GenInitFunction",
"(",
"self",
",",
"api_source_h",
")",
":",
"assert",
"not",
"self",
".",
"nested",
",",
"'Stack was not fully processed'",
"for",
"s",
"in",
"gen",
".",
"InitFunction",
"(",
"'CLIF-generated module for %s'",
"%",
"api_source_h",
",",
"gen",
".",
"MethodDef",
".",
"name",
"if",
"self",
".",
"methods",
"else",
"'nullptr'",
",",
"self",
".",
"init",
",",
"self",
".",
"dict",
")",
":",
"yield",
"s"
] | https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/python/pyext.py#L668-L674 | ||
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/xs/data_source.py | python | NullDataSource._load_group_structure | (self) | Loads a meaningless bounds array. | Loads a meaningless bounds array. | [
"Loads",
"a",
"meaningless",
"bounds",
"array",
"."
] | def _load_group_structure(self):
"""Loads a meaningless bounds array."""
self.src_group_struct = np.array([0.0]) | [
"def",
"_load_group_structure",
"(",
"self",
")",
":",
"self",
".",
"src_group_struct",
"=",
"np",
".",
"array",
"(",
"[",
"0.0",
"]",
")"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/xs/data_source.py#L283-L285 | ||
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/MolStandardize/standardize.py | python | Standardizer.normalize | (self) | return Normalizer(normalizations=self.normalizations, max_restarts=self.max_restarts) | :returns: A callable :class:`~molvs.normalize.Normalizer` instance. | :returns: A callable :class:`~molvs.normalize.Normalizer` instance. | [
":",
"returns",
":",
"A",
"callable",
":",
"class",
":",
"~molvs",
".",
"normalize",
".",
"Normalizer",
"instance",
"."
] | def normalize(self):
"""
:returns: A callable :class:`~molvs.normalize.Normalizer` instance.
"""
return Normalizer(normalizations=self.normalizations, max_restarts=self.max_restarts) | [
"def",
"normalize",
"(",
"self",
")",
":",
"return",
"Normalizer",
"(",
"normalizations",
"=",
"self",
".",
"normalizations",
",",
"max_restarts",
"=",
"self",
".",
"max_restarts",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/MolStandardize/standardize.py#L243-L247 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | TextUrlEvent.GetURLEnd | (*args, **kwargs) | return _controls_.TextUrlEvent_GetURLEnd(*args, **kwargs) | GetURLEnd(self) -> long | GetURLEnd(self) -> long | [
"GetURLEnd",
"(",
"self",
")",
"-",
">",
"long"
] | def GetURLEnd(*args, **kwargs):
"""GetURLEnd(self) -> long"""
return _controls_.TextUrlEvent_GetURLEnd(*args, **kwargs) | [
"def",
"GetURLEnd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextUrlEvent_GetURLEnd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L2116-L2118 | |
moflow/moflow | 2dfb27c799c90c6caf1477508eca3eec616ef7d2 | bap/libtracewrap/libtrace/protobuf/python/mox.py | python | MockObject.__class__ | (self) | return self._class_to_mock | Return the class that is being mocked. | Return the class that is being mocked. | [
"Return",
"the",
"class",
"that",
"is",
"being",
"mocked",
"."
] | def __class__(self):
"""Return the class that is being mocked."""
return self._class_to_mock | [
"def",
"__class__",
"(",
"self",
")",
":",
"return",
"self",
".",
"_class_to_mock"
] | https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/mox.py#L504-L507 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/Direct/ISISDirecInelasticConfig.py | python | UserProperties.instrument | (self) | return instrument used in last actual experiment | return instrument used in last actual experiment | [
"return",
"instrument",
"used",
"in",
"last",
"actual",
"experiment"
] | def instrument(self):
"""return instrument used in last actual experiment"""
if self._recent_dateID:
return self._instrument[self._recent_dateID]
else:
raise RuntimeError("User's experiment date is not defined. User undefined") | [
"def",
"instrument",
"(",
"self",
")",
":",
"if",
"self",
".",
"_recent_dateID",
":",
"return",
"self",
".",
"_instrument",
"[",
"self",
".",
"_recent_dateID",
"]",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"User's experiment date is not defined. User undefined\"",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py#L197-L202 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/format/data_pack.py | python | Format | (root, lang='en', output_dir='.') | return WriteDataPackToString(data, UTF8) | Writes out the data pack file format (platform agnostic resource file). | Writes out the data pack file format (platform agnostic resource file). | [
"Writes",
"out",
"the",
"data",
"pack",
"file",
"format",
"(",
"platform",
"agnostic",
"resource",
"file",
")",
"."
] | def Format(root, lang='en', output_dir='.'):
"""Writes out the data pack file format (platform agnostic resource file)."""
data = {}
for node in root.ActiveDescendants():
with node:
if isinstance(node, (include.IncludeNode, message.MessageNode,
structure.StructureNode)):
id, value = node.GetDataPackPair(lang, UTF8)
if value is not None:
data[id] = value
return WriteDataPackToString(data, UTF8) | [
"def",
"Format",
"(",
"root",
",",
"lang",
"=",
"'en'",
",",
"output_dir",
"=",
"'.'",
")",
":",
"data",
"=",
"{",
"}",
"for",
"node",
"in",
"root",
".",
"ActiveDescendants",
"(",
")",
":",
"with",
"node",
":",
"if",
"isinstance",
"(",
"node",
",",
"(",
"include",
".",
"IncludeNode",
",",
"message",
".",
"MessageNode",
",",
"structure",
".",
"StructureNode",
")",
")",
":",
"id",
",",
"value",
"=",
"node",
".",
"GetDataPackPair",
"(",
"lang",
",",
"UTF8",
")",
"if",
"value",
"is",
"not",
"None",
":",
"data",
"[",
"id",
"]",
"=",
"value",
"return",
"WriteDataPackToString",
"(",
"data",
",",
"UTF8",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/format/data_pack.py#L38-L48 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/boost_1_66_0/libs/python/config/tools/sphinx4scons.py | python | sphinx_path | (os_path) | return os_path.replace(os.sep, "/") | Create sphinx-style path from os-style path. | Create sphinx-style path from os-style path. | [
"Create",
"sphinx",
"-",
"style",
"path",
"from",
"os",
"-",
"style",
"path",
"."
] | def sphinx_path(os_path):
"""Create sphinx-style path from os-style path."""
return os_path.replace(os.sep, "/") | [
"def",
"sphinx_path",
"(",
"os_path",
")",
":",
"return",
"os_path",
".",
"replace",
"(",
"os",
".",
"sep",
",",
"\"/\"",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/libs/python/config/tools/sphinx4scons.py#L219-L221 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py | python | domain_greater_equal.__init__ | (self, critical_value) | domain_greater_equal(v)(x) = true where x < v | domain_greater_equal(v)(x) = true where x < v | [
"domain_greater_equal",
"(",
"v",
")",
"(",
"x",
")",
"=",
"true",
"where",
"x",
"<",
"v"
] | def __init__(self, critical_value):
"domain_greater_equal(v)(x) = true where x < v"
self.critical_value = critical_value | [
"def",
"__init__",
"(",
"self",
",",
"critical_value",
")",
":",
"self",
".",
"critical_value",
"=",
"critical_value"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L303-L305 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/lookup.py | python | RosdepLookup._load_view_dependencies | (self, view_key, loader) | Initialize internal :exc:`RosdepDatabase` on demand. Not
thread-safe.
:param view_key: name of view to load dependencies for.
:raises: :exc:`rospkg.ResourceNotFound` If view cannot be located
:raises: :exc:`InvalidData` if view's data is invaid
:raises: :exc:`RosdepInternalError` | Initialize internal :exc:`RosdepDatabase` on demand. Not
thread-safe. | [
"Initialize",
"internal",
":",
"exc",
":",
"RosdepDatabase",
"on",
"demand",
".",
"Not",
"thread",
"-",
"safe",
"."
] | def _load_view_dependencies(self, view_key, loader):
"""
Initialize internal :exc:`RosdepDatabase` on demand. Not
thread-safe.
:param view_key: name of view to load dependencies for.
:raises: :exc:`rospkg.ResourceNotFound` If view cannot be located
:raises: :exc:`InvalidData` if view's data is invaid
:raises: :exc:`RosdepInternalError`
"""
rd_debug("_load_view_dependencies[%s]"%(view_key))
db = self.rosdep_db
if db.is_loaded(view_key):
return
try:
loader.load_view(view_key, db, verbose=self.verbose)
entry = db.get_view_data(view_key)
rd_debug("_load_view_dependencies[%s]: %s"%(view_key, entry.view_dependencies))
for d in entry.view_dependencies:
self._load_view_dependencies(d, loader)
except InvalidData:
# mark view as loaded: as we are caching, the valid
# behavior is to not attempt loading this view ever
# again.
db.mark_loaded(view_key)
# re-raise
raise
except KeyError as e:
raise RosdepInternalError(e) | [
"def",
"_load_view_dependencies",
"(",
"self",
",",
"view_key",
",",
"loader",
")",
":",
"rd_debug",
"(",
"\"_load_view_dependencies[%s]\"",
"%",
"(",
"view_key",
")",
")",
"db",
"=",
"self",
".",
"rosdep_db",
"if",
"db",
".",
"is_loaded",
"(",
"view_key",
")",
":",
"return",
"try",
":",
"loader",
".",
"load_view",
"(",
"view_key",
",",
"db",
",",
"verbose",
"=",
"self",
".",
"verbose",
")",
"entry",
"=",
"db",
".",
"get_view_data",
"(",
"view_key",
")",
"rd_debug",
"(",
"\"_load_view_dependencies[%s]: %s\"",
"%",
"(",
"view_key",
",",
"entry",
".",
"view_dependencies",
")",
")",
"for",
"d",
"in",
"entry",
".",
"view_dependencies",
":",
"self",
".",
"_load_view_dependencies",
"(",
"d",
",",
"loader",
")",
"except",
"InvalidData",
":",
"# mark view as loaded: as we are caching, the valid",
"# behavior is to not attempt loading this view ever",
"# again.",
"db",
".",
"mark_loaded",
"(",
"view_key",
")",
"# re-raise",
"raise",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"RosdepInternalError",
"(",
"e",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rosdep2/lookup.py#L506-L535 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rosparam/src/rosparam/__init__.py | python | construct_angle_degrees | (loader, node) | python-yaml utility for converting deg(num) into float value | python-yaml utility for converting deg(num) into float value | [
"python",
"-",
"yaml",
"utility",
"for",
"converting",
"deg",
"(",
"num",
")",
"into",
"float",
"value"
] | def construct_angle_degrees(loader, node):
"""
python-yaml utility for converting deg(num) into float value
"""
value = loader.construct_scalar(node)
exprvalue = value
if exprvalue.startswith("deg("):
exprvalue = exprvalue.strip()[4:-1]
try:
return float(exprvalue) * math.pi / 180.0
except ValueError:
raise RosParamException("invalid degree value: %s"%value) | [
"def",
"construct_angle_degrees",
"(",
"loader",
",",
"node",
")",
":",
"value",
"=",
"loader",
".",
"construct_scalar",
"(",
"node",
")",
"exprvalue",
"=",
"value",
"if",
"exprvalue",
".",
"startswith",
"(",
"\"deg(\"",
")",
":",
"exprvalue",
"=",
"exprvalue",
".",
"strip",
"(",
")",
"[",
"4",
":",
"-",
"1",
"]",
"try",
":",
"return",
"float",
"(",
"exprvalue",
")",
"*",
"math",
".",
"pi",
"/",
"180.0",
"except",
"ValueError",
":",
"raise",
"RosParamException",
"(",
"\"invalid degree value: %s\"",
"%",
"value",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosparam/src/rosparam/__init__.py#L116-L127 | ||
tfwu/FaceDetection-ConvNet-3D | f9251c48eb40c5aec8fba7455115c355466555be | python/mxnet/kvstore.py | python | KVStore._send_command_to_servers | (self, head, body) | Send a command to all server nodes
Send a command to all server nodes, which will make each server node run
KVStoreServer.controller
This function returns after the command has been executed in all server
nodes
Parameters
----------
head : int
the head of the command
body : str
the body of the command | Send a command to all server nodes | [
"Send",
"a",
"command",
"to",
"all",
"server",
"nodes"
] | def _send_command_to_servers(self, head, body):
"""Send a command to all server nodes
Send a command to all server nodes, which will make each server node run
KVStoreServer.controller
This function returns after the command has been executed in all server
nodes
Parameters
----------
head : int
the head of the command
body : str
the body of the command
"""
check_call(_LIB.MXKVStoreSendCommmandToServers(
self.handle, mx_uint(head), c_str(body))) | [
"def",
"_send_command_to_servers",
"(",
"self",
",",
"head",
",",
"body",
")",
":",
"check_call",
"(",
"_LIB",
".",
"MXKVStoreSendCommmandToServers",
"(",
"self",
".",
"handle",
",",
"mx_uint",
"(",
"head",
")",
",",
"c_str",
"(",
"body",
")",
")",
")"
] | https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/mxnet/kvstore.py#L341-L358 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/_distutils/command/bdist_msi.py | python | PyDialog.cancel | (self, title, next, name = "Cancel", active = 1) | return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next) | Add a cancel button with a given title, the tab-next button,
its name in the Control table, possibly initially disabled.
Return the button, so that events can be associated | Add a cancel button with a given title, the tab-next button,
its name in the Control table, possibly initially disabled. | [
"Add",
"a",
"cancel",
"button",
"with",
"a",
"given",
"title",
"the",
"tab",
"-",
"next",
"button",
"its",
"name",
"in",
"the",
"Control",
"table",
"possibly",
"initially",
"disabled",
"."
] | def cancel(self, title, next, name = "Cancel", active = 1):
"""Add a cancel button with a given title, the tab-next button,
its name in the Control table, possibly initially disabled.
Return the button, so that events can be associated"""
if active:
flags = 3 # Visible|Enabled
else:
flags = 1 # Visible
return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next) | [
"def",
"cancel",
"(",
"self",
",",
"title",
",",
"next",
",",
"name",
"=",
"\"Cancel\"",
",",
"active",
"=",
"1",
")",
":",
"if",
"active",
":",
"flags",
"=",
"3",
"# Visible|Enabled",
"else",
":",
"flags",
"=",
"1",
"# Visible",
"return",
"self",
".",
"pushbutton",
"(",
"name",
",",
"304",
",",
"self",
".",
"h",
"-",
"27",
",",
"56",
",",
"17",
",",
"flags",
",",
"title",
",",
"next",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/command/bdist_msi.py#L55-L64 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/pylabtools.py | python | retina_figure | (fig, **kwargs) | return pngdata, metadata | format a figure as a pixel-doubled (retina) PNG | format a figure as a pixel-doubled (retina) PNG | [
"format",
"a",
"figure",
"as",
"a",
"pixel",
"-",
"doubled",
"(",
"retina",
")",
"PNG"
] | def retina_figure(fig, **kwargs):
"""format a figure as a pixel-doubled (retina) PNG"""
pngdata = print_figure(fig, fmt='retina', **kwargs)
# Make sure that retina_figure acts just like print_figure and returns
# None when the figure is empty.
if pngdata is None:
return
w, h = _pngxy(pngdata)
metadata = dict(width=w//2, height=h//2)
return pngdata, metadata | [
"def",
"retina_figure",
"(",
"fig",
",",
"*",
"*",
"kwargs",
")",
":",
"pngdata",
"=",
"print_figure",
"(",
"fig",
",",
"fmt",
"=",
"'retina'",
",",
"*",
"*",
"kwargs",
")",
"# Make sure that retina_figure acts just like print_figure and returns",
"# None when the figure is empty.",
"if",
"pngdata",
"is",
"None",
":",
"return",
"w",
",",
"h",
"=",
"_pngxy",
"(",
"pngdata",
")",
"metadata",
"=",
"dict",
"(",
"width",
"=",
"w",
"//",
"2",
",",
"height",
"=",
"h",
"//",
"2",
")",
"return",
"pngdata",
",",
"metadata"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/pylabtools.py#L137-L146 | |
forkineye/ESPixelStick | 22926f1c0d1131f1369fc7cad405689a095ae3cb | dist/bin/esptool/espefuse.py | python | efuse_write_reg_addr | (block, word) | return EFUSE_REG_WRITE[block] + (4 * word) | Return the physical address of the efuse write data register
block X word X. | Return the physical address of the efuse write data register
block X word X. | [
"Return",
"the",
"physical",
"address",
"of",
"the",
"efuse",
"write",
"data",
"register",
"block",
"X",
"word",
"X",
"."
] | def efuse_write_reg_addr(block, word):
"""
Return the physical address of the efuse write data register
block X word X.
"""
return EFUSE_REG_WRITE[block] + (4 * word) | [
"def",
"efuse_write_reg_addr",
"(",
"block",
",",
"word",
")",
":",
"return",
"EFUSE_REG_WRITE",
"[",
"block",
"]",
"+",
"(",
"4",
"*",
"word",
")"
] | https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/espefuse.py#L133-L138 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/dos/load_castep.py | python | _find_castep_freq_block | (f_handle, data_regex) | Find the start of the frequency block in a .castep file.
This will set the file pointer to the line before the start
of the block.
@param f_handle - handle to the file. | Find the start of the frequency block in a .castep file.
This will set the file pointer to the line before the start
of the block. | [
"Find",
"the",
"start",
"of",
"the",
"frequency",
"block",
"in",
"a",
".",
"castep",
"file",
".",
"This",
"will",
"set",
"the",
"file",
"pointer",
"to",
"the",
"line",
"before",
"the",
"start",
"of",
"the",
"block",
"."
] | def _find_castep_freq_block(f_handle, data_regex):
"""
Find the start of the frequency block in a .castep file.
This will set the file pointer to the line before the start
of the block.
@param f_handle - handle to the file.
"""
while True:
pos = f_handle.tell()
line = f_handle.readline()
if not line:
raise IOError("Could not parse frequency block. Invalid file format.")
if data_regex.match(line):
f_handle.seek(pos)
return | [
"def",
"_find_castep_freq_block",
"(",
"f_handle",
",",
"data_regex",
")",
":",
"while",
"True",
":",
"pos",
"=",
"f_handle",
".",
"tell",
"(",
")",
"line",
"=",
"f_handle",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"raise",
"IOError",
"(",
"\"Could not parse frequency block. Invalid file format.\"",
")",
"if",
"data_regex",
".",
"match",
"(",
"line",
")",
":",
"f_handle",
".",
"seek",
"(",
"pos",
")",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/dos/load_castep.py#L138-L155 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | cmake/std/trilinosprhelpers/TrilinosPRConfigurationBase.py | python | TrilinosPRConfigurationBase.get_property_from_config | (self, section, option, default=None) | return output | Helper to load a property from the ConfigParser configuration data
that was loaded up by the SetEnvironment class. We use this to load
information from free-form sections that we include int he .ini file
which encode information that isn't used by the parser but is used
to encode Trilinos PR configuration data.
Args:
section (str) : The section name we're loading (i.e., [SECTION_NAME])
option (str) : The name of a property inside a section to load (i.e., property: value)
default : Default value to return if the request fails. Default: None
Returns:
str: The value of a property inside some section as a string. For example:
[SECTION_NAME]
property: <value> | Helper to load a property from the ConfigParser configuration data
that was loaded up by the SetEnvironment class. We use this to load
information from free-form sections that we include int he .ini file
which encode information that isn't used by the parser but is used
to encode Trilinos PR configuration data. | [
"Helper",
"to",
"load",
"a",
"property",
"from",
"the",
"ConfigParser",
"configuration",
"data",
"that",
"was",
"loaded",
"up",
"by",
"the",
"SetEnvironment",
"class",
".",
"We",
"use",
"this",
"to",
"load",
"information",
"from",
"free",
"-",
"form",
"sections",
"that",
"we",
"include",
"int",
"he",
".",
"ini",
"file",
"which",
"encode",
"information",
"that",
"isn",
"t",
"used",
"by",
"the",
"parser",
"but",
"is",
"used",
"to",
"encode",
"Trilinos",
"PR",
"configuration",
"data",
"."
] | def get_property_from_config(self, section, option, default=None):
"""
Helper to load a property from the ConfigParser configuration data
that was loaded up by the SetEnvironment class. We use this to load
information from free-form sections that we include int he .ini file
which encode information that isn't used by the parser but is used
to encode Trilinos PR configuration data.
Args:
section (str) : The section name we're loading (i.e., [SECTION_NAME])
option (str) : The name of a property inside a section to load (i.e., property: value)
default : Default value to return if the request fails. Default: None
Returns:
str: The value of a property inside some section as a string. For example:
[SECTION_NAME]
property: <value>
"""
output = default
try:
output = self.config_data.config.get(section, option)
except configparser.NoSectionError:
print("WARNING: Configuration section '{}' does not exist.".format(section))
print(" : Returning default value: '{}'".format(output))
except configparser.NoOptionError:
print("WARNING: Configuration section '{}' has no key '{}'".format(section,option))
print(" : Returning default value: {}".format(output))
return output | [
"def",
"get_property_from_config",
"(",
"self",
",",
"section",
",",
"option",
",",
"default",
"=",
"None",
")",
":",
"output",
"=",
"default",
"try",
":",
"output",
"=",
"self",
".",
"config_data",
".",
"config",
".",
"get",
"(",
"section",
",",
"option",
")",
"except",
"configparser",
".",
"NoSectionError",
":",
"print",
"(",
"\"WARNING: Configuration section '{}' does not exist.\"",
".",
"format",
"(",
"section",
")",
")",
"print",
"(",
"\" : Returning default value: '{}'\"",
".",
"format",
"(",
"output",
")",
")",
"except",
"configparser",
".",
"NoOptionError",
":",
"print",
"(",
"\"WARNING: Configuration section '{}' has no key '{}'\"",
".",
"format",
"(",
"section",
",",
"option",
")",
")",
"print",
"(",
"\" : Returning default value: {}\"",
".",
"format",
"(",
"output",
")",
")",
"return",
"output"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/cmake/std/trilinosprhelpers/TrilinosPRConfigurationBase.py#L334-L361 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/inspector_protocol/jinja2/environment.py | python | Environment.iter_extensions | (self) | return iter(sorted(self.extensions.values(),
key=lambda x: x.priority)) | Iterates over the extensions by priority. | Iterates over the extensions by priority. | [
"Iterates",
"over",
"the",
"extensions",
"by",
"priority",
"."
] | def iter_extensions(self):
"""Iterates over the extensions by priority."""
return iter(sorted(self.extensions.values(),
key=lambda x: x.priority)) | [
"def",
"iter_extensions",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"sorted",
"(",
"self",
".",
"extensions",
".",
"values",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"priority",
")",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/environment.py#L403-L406 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/loss/loss.py | python | BCEWithLogitsLoss.__init__ | (self, reduction='mean', weight=None, pos_weight=None) | Initialize BCEWithLogitsLoss. | Initialize BCEWithLogitsLoss. | [
"Initialize",
"BCEWithLogitsLoss",
"."
] | def __init__(self, reduction='mean', weight=None, pos_weight=None):
"""Initialize BCEWithLogitsLoss."""
super(BCEWithLogitsLoss, self).__init__()
self.bce_with_logits_loss = P.BCEWithLogitsLoss(reduction=reduction)
if isinstance(weight, Parameter):
raise TypeError(f"For '{self.cls_name}', the 'weight' can not be a Parameter.")
if isinstance(pos_weight, Parameter):
raise TypeError(f"For '{self.cls_name}', the 'pos_weight' can not be a Parameter.")
self.weight = weight
self.pos_weight = pos_weight
self.ones = P.OnesLike() | [
"def",
"__init__",
"(",
"self",
",",
"reduction",
"=",
"'mean'",
",",
"weight",
"=",
"None",
",",
"pos_weight",
"=",
"None",
")",
":",
"super",
"(",
"BCEWithLogitsLoss",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"bce_with_logits_loss",
"=",
"P",
".",
"BCEWithLogitsLoss",
"(",
"reduction",
"=",
"reduction",
")",
"if",
"isinstance",
"(",
"weight",
",",
"Parameter",
")",
":",
"raise",
"TypeError",
"(",
"f\"For '{self.cls_name}', the 'weight' can not be a Parameter.\"",
")",
"if",
"isinstance",
"(",
"pos_weight",
",",
"Parameter",
")",
":",
"raise",
"TypeError",
"(",
"f\"For '{self.cls_name}', the 'pos_weight' can not be a Parameter.\"",
")",
"self",
".",
"weight",
"=",
"weight",
"self",
".",
"pos_weight",
"=",
"pos_weight",
"self",
".",
"ones",
"=",
"P",
".",
"OnesLike",
"(",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/loss/loss.py#L1256-L1266 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TRStr.IsLc | (self) | return _snap.TRStr_IsLc(self) | IsLc(TRStr self) -> bool
Parameters:
self: TRStr const * | IsLc(TRStr self) -> bool | [
"IsLc",
"(",
"TRStr",
"self",
")",
"-",
">",
"bool"
] | def IsLc(self):
"""
IsLc(TRStr self) -> bool
Parameters:
self: TRStr const *
"""
return _snap.TRStr_IsLc(self) | [
"def",
"IsLc",
"(",
"self",
")",
":",
"return",
"_snap",
".",
"TRStr_IsLc",
"(",
"self",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L9349-L9357 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/share/gdb/python/gdb/command/pretty_printers.py | python | InfoPrettyPrinter.invoke1 | (self, title, printer_list,
obj_name_to_match, object_re, name_re, subname_re) | Subroutine of invoke to simplify it. | Subroutine of invoke to simplify it. | [
"Subroutine",
"of",
"invoke",
"to",
"simplify",
"it",
"."
] | def invoke1(self, title, printer_list,
obj_name_to_match, object_re, name_re, subname_re):
"""Subroutine of invoke to simplify it."""
if printer_list and object_re.match(obj_name_to_match):
print (title)
self.list_pretty_printers(printer_list, name_re, subname_re) | [
"def",
"invoke1",
"(",
"self",
",",
"title",
",",
"printer_list",
",",
"obj_name_to_match",
",",
"object_re",
",",
"name_re",
",",
"subname_re",
")",
":",
"if",
"printer_list",
"and",
"object_re",
".",
"match",
"(",
"obj_name_to_match",
")",
":",
"print",
"(",
"title",
")",
"self",
".",
"list_pretty_printers",
"(",
"printer_list",
",",
"name_re",
",",
"subname_re",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/share/gdb/python/gdb/command/pretty_printers.py#L145-L150 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/xcode_emulation.py | python | CloneConfigurationForDeviceAndEmulator | (target_dicts) | return target_dicts | If |target_dicts| contains any iOS targets, automatically create -iphoneos
targets for iOS device builds. | If |target_dicts| contains any iOS targets, automatically create -iphoneos
targets for iOS device builds. | [
"If",
"|target_dicts|",
"contains",
"any",
"iOS",
"targets",
"automatically",
"create",
"-",
"iphoneos",
"targets",
"for",
"iOS",
"device",
"builds",
"."
] | def CloneConfigurationForDeviceAndEmulator(target_dicts):
"""If |target_dicts| contains any iOS targets, automatically create -iphoneos
targets for iOS device builds."""
if _HasIOSTarget(target_dicts):
return _AddIOSDeviceConfigurations(target_dicts)
return target_dicts | [
"def",
"CloneConfigurationForDeviceAndEmulator",
"(",
"target_dicts",
")",
":",
"if",
"_HasIOSTarget",
"(",
"target_dicts",
")",
":",
"return",
"_AddIOSDeviceConfigurations",
"(",
"target_dicts",
")",
"return",
"target_dicts"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/xcode_emulation.py#L1805-L1810 | |
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | bin/run-workload.py | python | create_workload_config | () | return WorkloadConfig(**config) | Parse command line inputs.
Some user inputs needs to be transformed from delimited strings to lists in order to be
consumed by the performacne framework. Additionally, plugin_names are converted into
objects, and need to be added to the config. | Parse command line inputs. | [
"Parse",
"command",
"line",
"inputs",
"."
] | def create_workload_config():
"""Parse command line inputs.
Some user inputs needs to be transformed from delimited strings to lists in order to be
consumed by the performacne framework. Additionally, plugin_names are converted into
objects, and need to be added to the config.
"""
config = deepcopy(vars(options))
# We don't need workloads and query_names in the config map as they're already specified
# in the workload object.
del config['workloads']
del config['query_names']
config['plugin_runner'] = plugin_runner
# transform a few options from strings to lists
config['table_formats'] = split_and_strip(config['table_formats'])
impalads = split_and_strip(config['impalads'])
# Randomize the order of impalads.
shuffle(impalads)
config['impalads'] = deque(impalads)
return WorkloadConfig(**config) | [
"def",
"create_workload_config",
"(",
")",
":",
"config",
"=",
"deepcopy",
"(",
"vars",
"(",
"options",
")",
")",
"# We don't need workloads and query_names in the config map as they're already specified",
"# in the workload object.",
"del",
"config",
"[",
"'workloads'",
"]",
"del",
"config",
"[",
"'query_names'",
"]",
"config",
"[",
"'plugin_runner'",
"]",
"=",
"plugin_runner",
"# transform a few options from strings to lists",
"config",
"[",
"'table_formats'",
"]",
"=",
"split_and_strip",
"(",
"config",
"[",
"'table_formats'",
"]",
")",
"impalads",
"=",
"split_and_strip",
"(",
"config",
"[",
"'impalads'",
"]",
")",
"# Randomize the order of impalads.",
"shuffle",
"(",
"impalads",
")",
"config",
"[",
"'impalads'",
"]",
"=",
"deque",
"(",
"impalads",
")",
"return",
"WorkloadConfig",
"(",
"*",
"*",
"config",
")"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/bin/run-workload.py#L199-L218 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | DQM/SiStripMonitorClient/scripts/submitDQMOfflineCAF.py | python | Func_Usage | () | Function Func_Usage():
Displays usage of the script | Function Func_Usage():
Displays usage of the script | [
"Function",
"Func_Usage",
"()",
":",
"Displays",
"usage",
"of",
"the",
"script"
] | def Func_Usage():
""" Function Func_Usage():
Displays usage of the script
"""
print(STR_textUsage) | [
"def",
"Func_Usage",
"(",
")",
":",
"print",
"(",
"STR_textUsage",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/DQM/SiStripMonitorClient/scripts/submitDQMOfflineCAF.py#L238-L242 | ||
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Build.py | python | BuildContext.post_group | (self) | Post task generators from the group indexed by self.current_group; used internally
by :py:meth:`waflib.Build.BuildContext.get_build_iterator` | Post task generators from the group indexed by self.current_group; used internally
by :py:meth:`waflib.Build.BuildContext.get_build_iterator` | [
"Post",
"task",
"generators",
"from",
"the",
"group",
"indexed",
"by",
"self",
".",
"current_group",
";",
"used",
"internally",
"by",
":",
"py",
":",
"meth",
":",
"waflib",
".",
"Build",
".",
"BuildContext",
".",
"get_build_iterator"
] | def post_group(self):
"""
Post task generators from the group indexed by self.current_group; used internally
by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
"""
def tgpost(tg):
try:
f = tg.post
except AttributeError:
pass
else:
f()
if self.targets == '*':
for tg in self.groups[self.current_group]:
tgpost(tg)
elif self.targets:
if self.current_group < self._min_grp:
for tg in self.groups[self.current_group]:
tgpost(tg)
else:
for tg in self._exact_tg:
tg.post()
else:
ln = self.launch_node()
if ln.is_child_of(self.bldnode):
if Logs.verbose > 1:
Logs.warn('Building from the build directory, forcing --targets=*')
ln = self.srcnode
elif not ln.is_child_of(self.srcnode):
if Logs.verbose > 1:
Logs.warn('CWD %s is not under %s, forcing --targets=* (run distclean?)', ln.abspath(), self.srcnode.abspath())
ln = self.srcnode
def is_post(tg, ln):
try:
p = tg.path
except AttributeError:
pass
else:
if p.is_child_of(ln):
return True
def is_post_group():
for i, g in enumerate(self.groups):
if i > self.current_group:
for tg in g:
if is_post(tg, ln):
return True
if self.post_mode == POST_LAZY and ln != self.srcnode:
# partial folder builds require all targets from a previous build group
if is_post_group():
ln = self.srcnode
for tg in self.groups[self.current_group]:
if is_post(tg, ln):
tgpost(tg) | [
"def",
"post_group",
"(",
"self",
")",
":",
"def",
"tgpost",
"(",
"tg",
")",
":",
"try",
":",
"f",
"=",
"tg",
".",
"post",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"f",
"(",
")",
"if",
"self",
".",
"targets",
"==",
"'*'",
":",
"for",
"tg",
"in",
"self",
".",
"groups",
"[",
"self",
".",
"current_group",
"]",
":",
"tgpost",
"(",
"tg",
")",
"elif",
"self",
".",
"targets",
":",
"if",
"self",
".",
"current_group",
"<",
"self",
".",
"_min_grp",
":",
"for",
"tg",
"in",
"self",
".",
"groups",
"[",
"self",
".",
"current_group",
"]",
":",
"tgpost",
"(",
"tg",
")",
"else",
":",
"for",
"tg",
"in",
"self",
".",
"_exact_tg",
":",
"tg",
".",
"post",
"(",
")",
"else",
":",
"ln",
"=",
"self",
".",
"launch_node",
"(",
")",
"if",
"ln",
".",
"is_child_of",
"(",
"self",
".",
"bldnode",
")",
":",
"if",
"Logs",
".",
"verbose",
">",
"1",
":",
"Logs",
".",
"warn",
"(",
"'Building from the build directory, forcing --targets=*'",
")",
"ln",
"=",
"self",
".",
"srcnode",
"elif",
"not",
"ln",
".",
"is_child_of",
"(",
"self",
".",
"srcnode",
")",
":",
"if",
"Logs",
".",
"verbose",
">",
"1",
":",
"Logs",
".",
"warn",
"(",
"'CWD %s is not under %s, forcing --targets=* (run distclean?)'",
",",
"ln",
".",
"abspath",
"(",
")",
",",
"self",
".",
"srcnode",
".",
"abspath",
"(",
")",
")",
"ln",
"=",
"self",
".",
"srcnode",
"def",
"is_post",
"(",
"tg",
",",
"ln",
")",
":",
"try",
":",
"p",
"=",
"tg",
".",
"path",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"if",
"p",
".",
"is_child_of",
"(",
"ln",
")",
":",
"return",
"True",
"def",
"is_post_group",
"(",
")",
":",
"for",
"i",
",",
"g",
"in",
"enumerate",
"(",
"self",
".",
"groups",
")",
":",
"if",
"i",
">",
"self",
".",
"current_group",
":",
"for",
"tg",
"in",
"g",
":",
"if",
"is_post",
"(",
"tg",
",",
"ln",
")",
":",
"return",
"True",
"if",
"self",
".",
"post_mode",
"==",
"POST_LAZY",
"and",
"ln",
"!=",
"self",
".",
"srcnode",
":",
"# partial folder builds require all targets from a previous build group",
"if",
"is_post_group",
"(",
")",
":",
"ln",
"=",
"self",
".",
"srcnode",
"for",
"tg",
"in",
"self",
".",
"groups",
"[",
"self",
".",
"current_group",
"]",
":",
"if",
"is_post",
"(",
"tg",
",",
"ln",
")",
":",
"tgpost",
"(",
"tg",
")"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Build.py#L730-L787 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Tools/SubWCRev.py | python | GitControl.namebranchbyparents | (self) | name multiple branches in case that the last commit was a merge
a merge is identified by having two or more parents
if the describe does not return a ref name (the hash is added)
if one parent is the master and the second one has no ref name, one branch was
merged. | name multiple branches in case that the last commit was a merge
a merge is identified by having two or more parents
if the describe does not return a ref name (the hash is added)
if one parent is the master and the second one has no ref name, one branch was
merged. | [
"name",
"multiple",
"branches",
"in",
"case",
"that",
"the",
"last",
"commit",
"was",
"a",
"merge",
"a",
"merge",
"is",
"identified",
"by",
"having",
"two",
"or",
"more",
"parents",
"if",
"the",
"describe",
"does",
"not",
"return",
"a",
"ref",
"name",
"(",
"the",
"hash",
"is",
"added",
")",
"if",
"one",
"parent",
"is",
"the",
"master",
"and",
"the",
"second",
"one",
"has",
"no",
"ref",
"name",
"one",
"branch",
"was",
"merged",
"."
] | def namebranchbyparents(self):
"""name multiple branches in case that the last commit was a merge
a merge is identified by having two or more parents
if the describe does not return a ref name (the hash is added)
if one parent is the master and the second one has no ref name, one branch was
merged."""
parents=os.popen("git log -n1 --pretty=%P").read()\
.strip().split(' ')
if len(parents) >= 2: #merge commit
parentrefs=[]
names=[]
hasnames=0
for p in parents:
refs=os.popen("git show -s --pretty=%%d %s" % p).read()\
.strip(" ()\n").split(', ')
if refs[0] != '': #has a ref name
parentrefs.append(refs)
names.append(refs[-1])
hasnames += 1
else:
parentrefs.append(p)
names.append(p[:7])
if hasnames >=2: # merging master into dev is not enough
self.branch=','.join(names) | [
"def",
"namebranchbyparents",
"(",
"self",
")",
":",
"parents",
"=",
"os",
".",
"popen",
"(",
"\"git log -n1 --pretty=%P\"",
")",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"' '",
")",
"if",
"len",
"(",
"parents",
")",
">=",
"2",
":",
"#merge commit",
"parentrefs",
"=",
"[",
"]",
"names",
"=",
"[",
"]",
"hasnames",
"=",
"0",
"for",
"p",
"in",
"parents",
":",
"refs",
"=",
"os",
".",
"popen",
"(",
"\"git show -s --pretty=%%d %s\"",
"%",
"p",
")",
".",
"read",
"(",
")",
".",
"strip",
"(",
"\" ()\\n\"",
")",
".",
"split",
"(",
"', '",
")",
"if",
"refs",
"[",
"0",
"]",
"!=",
"''",
":",
"#has a ref name",
"parentrefs",
".",
"append",
"(",
"refs",
")",
"names",
".",
"append",
"(",
"refs",
"[",
"-",
"1",
"]",
")",
"hasnames",
"+=",
"1",
"else",
":",
"parentrefs",
".",
"append",
"(",
"p",
")",
"names",
".",
"append",
"(",
"p",
"[",
":",
"7",
"]",
")",
"if",
"hasnames",
">=",
"2",
":",
"# merging master into dev is not enough",
"self",
".",
"branch",
"=",
"','",
".",
"join",
"(",
"names",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Tools/SubWCRev.py#L292-L315 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb2/table.py | python | Table.delete_global_secondary_index | (self, global_index_name) | Deletes a global index in DynamoDB after the table has been created.
Requires a ``global_index_name`` parameter, which should be a simple
string of the name of the global secondary index.
To update ``global_indexes`` information on the ``Table``, you'll need
to call ``Table.describe``.
Returns ``True`` on success.
Example::
# To delete a global index
>>> users.delete_global_secondary_index('TheIndexNameHere')
True | Deletes a global index in DynamoDB after the table has been created. | [
"Deletes",
"a",
"global",
"index",
"in",
"DynamoDB",
"after",
"the",
"table",
"has",
"been",
"created",
"."
] | def delete_global_secondary_index(self, global_index_name):
"""
Deletes a global index in DynamoDB after the table has been created.
Requires a ``global_index_name`` parameter, which should be a simple
string of the name of the global secondary index.
To update ``global_indexes`` information on the ``Table``, you'll need
to call ``Table.describe``.
Returns ``True`` on success.
Example::
# To delete a global index
>>> users.delete_global_secondary_index('TheIndexNameHere')
True
"""
if global_index_name:
gsi_data = [
{
"Delete": {
"IndexName": global_index_name
}
}
]
self.connection.update_table(
self.table_name,
global_secondary_index_updates=gsi_data,
)
return True
else:
msg = 'You need to provide the global index name to ' \
'delete_global_secondary_index method'
boto.log.error(msg)
return False | [
"def",
"delete_global_secondary_index",
"(",
"self",
",",
"global_index_name",
")",
":",
"if",
"global_index_name",
":",
"gsi_data",
"=",
"[",
"{",
"\"Delete\"",
":",
"{",
"\"IndexName\"",
":",
"global_index_name",
"}",
"}",
"]",
"self",
".",
"connection",
".",
"update_table",
"(",
"self",
".",
"table_name",
",",
"global_secondary_index_updates",
"=",
"gsi_data",
",",
")",
"return",
"True",
"else",
":",
"msg",
"=",
"'You need to provide the global index name to '",
"'delete_global_secondary_index method'",
"boto",
".",
"log",
".",
"error",
"(",
"msg",
")",
"return",
"False"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb2/table.py#L515-L555 | ||
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | python_packaging/src/gmxapi/abc.py | python | OperationDirector.__call__ | (self, resources, label: typing.Optional[str]) | Add an element of work (node) and return a handle to the client.
Implements the client behavior in terms of the NodeBuilder interface
for a NodeBuilder in the target Context. Return a handle to the resulting
operation instance (node) that may be specialized to provide additional
interface particular to the operation. | Add an element of work (node) and return a handle to the client. | [
"Add",
"an",
"element",
"of",
"work",
"(",
"node",
")",
"and",
"return",
"a",
"handle",
"to",
"the",
"client",
"."
] | def __call__(self, resources, label: typing.Optional[str]):
"""Add an element of work (node) and return a handle to the client.
Implements the client behavior in terms of the NodeBuilder interface
for a NodeBuilder in the target Context. Return a handle to the resulting
operation instance (node) that may be specialized to provide additional
interface particular to the operation.
"""
... | [
"def",
"__call__",
"(",
"self",
",",
"resources",
",",
"label",
":",
"typing",
".",
"Optional",
"[",
"str",
"]",
")",
":",
"..."
] | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/python_packaging/src/gmxapi/abc.py#L576-L584 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/traced_module/traced_module.py | python | InternalGraph.outputs | (self) | return self._outputs | r"""Get the list of output Nodes of this graph.
Returns:
A list of ``Node``. | r"""Get the list of output Nodes of this graph. | [
"r",
"Get",
"the",
"list",
"of",
"output",
"Nodes",
"of",
"this",
"graph",
"."
] | def outputs(self) -> List[Node]:
r"""Get the list of output Nodes of this graph.
Returns:
A list of ``Node``.
"""
return self._outputs | [
"def",
"outputs",
"(",
"self",
")",
"->",
"List",
"[",
"Node",
"]",
":",
"return",
"self",
".",
"_outputs"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/traced_module/traced_module.py#L626-L632 | |
lmb-freiburg/flownet2 | b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc | python/caffe/coord_map.py | python | crop_params | (fn) | return (axis, offset) | Extract the crop layer parameters with defaults. | Extract the crop layer parameters with defaults. | [
"Extract",
"the",
"crop",
"layer",
"parameters",
"with",
"defaults",
"."
] | def crop_params(fn):
"""
Extract the crop layer parameters with defaults.
"""
params = fn.params.get('crop_param', fn.params)
axis = params.get('axis', 2) # default to spatial crop for N, C, H, W
offset = np.array(params.get('offset', 0), ndmin=1)
return (axis, offset) | [
"def",
"crop_params",
"(",
"fn",
")",
":",
"params",
"=",
"fn",
".",
"params",
".",
"get",
"(",
"'crop_param'",
",",
"fn",
".",
"params",
")",
"axis",
"=",
"params",
".",
"get",
"(",
"'axis'",
",",
"2",
")",
"# default to spatial crop for N, C, H, W",
"offset",
"=",
"np",
".",
"array",
"(",
"params",
".",
"get",
"(",
"'offset'",
",",
"0",
")",
",",
"ndmin",
"=",
"1",
")",
"return",
"(",
"axis",
",",
"offset",
")"
] | https://github.com/lmb-freiburg/flownet2/blob/b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc/python/caffe/coord_map.py#L40-L47 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/strings.py | python | StringMethods._get_series_list | (self, others) | Auxiliary function for :meth:`str.cat`. Turn potentially mixed input
into a list of Series (elements without an index must match the length
of the calling Series/Index).
Parameters
----------
others : Series, DataFrame, np.ndarray, list-like or list-like of
Objects that are either Series, Index or np.ndarray (1-dim).
Returns
-------
list of Series
Others transformed into list of Series. | Auxiliary function for :meth:`str.cat`. Turn potentially mixed input
into a list of Series (elements without an index must match the length
of the calling Series/Index). | [
"Auxiliary",
"function",
"for",
":",
"meth",
":",
"str",
".",
"cat",
".",
"Turn",
"potentially",
"mixed",
"input",
"into",
"a",
"list",
"of",
"Series",
"(",
"elements",
"without",
"an",
"index",
"must",
"match",
"the",
"length",
"of",
"the",
"calling",
"Series",
"/",
"Index",
")",
"."
] | def _get_series_list(self, others):
"""
Auxiliary function for :meth:`str.cat`. Turn potentially mixed input
into a list of Series (elements without an index must match the length
of the calling Series/Index).
Parameters
----------
others : Series, DataFrame, np.ndarray, list-like or list-like of
Objects that are either Series, Index or np.ndarray (1-dim).
Returns
-------
list of Series
Others transformed into list of Series.
"""
from pandas import Series, DataFrame
# self._orig is either Series or Index
idx = self._orig if isinstance(self._orig, ABCIndexClass) else self._orig.index
# Generally speaking, all objects without an index inherit the index
# `idx` of the calling Series/Index - i.e. must have matching length.
# Objects with an index (i.e. Series/Index/DataFrame) keep their own.
if isinstance(others, ABCSeries):
return [others]
elif isinstance(others, ABCIndexClass):
return [Series(others.values, index=others)]
elif isinstance(others, ABCDataFrame):
return [others[x] for x in others]
elif isinstance(others, np.ndarray) and others.ndim == 2:
others = DataFrame(others, index=idx)
return [others[x] for x in others]
elif is_list_like(others, allow_sets=False):
others = list(others) # ensure iterators do not get read twice etc
# in case of list-like `others`, all elements must be
# either Series/Index/np.ndarray (1-dim)...
if all(
isinstance(x, (ABCSeries, ABCIndexClass))
or (isinstance(x, np.ndarray) and x.ndim == 1)
for x in others
):
los = []
while others: # iterate through list and append each element
los = los + self._get_series_list(others.pop(0))
return los
# ... or just strings
elif all(not is_list_like(x) for x in others):
return [Series(others, index=idx)]
raise TypeError(
"others must be Series, Index, DataFrame, np.ndarrary "
"or list-like (either containing only strings or "
"containing only objects of type Series/Index/"
"np.ndarray[1-dim])"
) | [
"def",
"_get_series_list",
"(",
"self",
",",
"others",
")",
":",
"from",
"pandas",
"import",
"Series",
",",
"DataFrame",
"# self._orig is either Series or Index",
"idx",
"=",
"self",
".",
"_orig",
"if",
"isinstance",
"(",
"self",
".",
"_orig",
",",
"ABCIndexClass",
")",
"else",
"self",
".",
"_orig",
".",
"index",
"# Generally speaking, all objects without an index inherit the index",
"# `idx` of the calling Series/Index - i.e. must have matching length.",
"# Objects with an index (i.e. Series/Index/DataFrame) keep their own.",
"if",
"isinstance",
"(",
"others",
",",
"ABCSeries",
")",
":",
"return",
"[",
"others",
"]",
"elif",
"isinstance",
"(",
"others",
",",
"ABCIndexClass",
")",
":",
"return",
"[",
"Series",
"(",
"others",
".",
"values",
",",
"index",
"=",
"others",
")",
"]",
"elif",
"isinstance",
"(",
"others",
",",
"ABCDataFrame",
")",
":",
"return",
"[",
"others",
"[",
"x",
"]",
"for",
"x",
"in",
"others",
"]",
"elif",
"isinstance",
"(",
"others",
",",
"np",
".",
"ndarray",
")",
"and",
"others",
".",
"ndim",
"==",
"2",
":",
"others",
"=",
"DataFrame",
"(",
"others",
",",
"index",
"=",
"idx",
")",
"return",
"[",
"others",
"[",
"x",
"]",
"for",
"x",
"in",
"others",
"]",
"elif",
"is_list_like",
"(",
"others",
",",
"allow_sets",
"=",
"False",
")",
":",
"others",
"=",
"list",
"(",
"others",
")",
"# ensure iterators do not get read twice etc",
"# in case of list-like `others`, all elements must be",
"# either Series/Index/np.ndarray (1-dim)...",
"if",
"all",
"(",
"isinstance",
"(",
"x",
",",
"(",
"ABCSeries",
",",
"ABCIndexClass",
")",
")",
"or",
"(",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
"and",
"x",
".",
"ndim",
"==",
"1",
")",
"for",
"x",
"in",
"others",
")",
":",
"los",
"=",
"[",
"]",
"while",
"others",
":",
"# iterate through list and append each element",
"los",
"=",
"los",
"+",
"self",
".",
"_get_series_list",
"(",
"others",
".",
"pop",
"(",
"0",
")",
")",
"return",
"los",
"# ... or just strings",
"elif",
"all",
"(",
"not",
"is_list_like",
"(",
"x",
")",
"for",
"x",
"in",
"others",
")",
":",
"return",
"[",
"Series",
"(",
"others",
",",
"index",
"=",
"idx",
")",
"]",
"raise",
"TypeError",
"(",
"\"others must be Series, Index, DataFrame, np.ndarrary \"",
"\"or list-like (either containing only strings or \"",
"\"containing only objects of type Series/Index/\"",
"\"np.ndarray[1-dim])\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/strings.py#L2220-L2275 | ||
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py | python | Beta.cdf | (self, x, name="cdf") | Cumulative distribution function. | Cumulative distribution function. | [
"Cumulative",
"distribution",
"function",
"."
] | def cdf(self, x, name="cdf"):
"""Cumulative distribution function."""
# TODO(srvasude): Implement this once betainc op is checked in.
raise NotImplementedError("Beta cdf not implemented.") | [
"def",
"cdf",
"(",
"self",
",",
"x",
",",
"name",
"=",
"\"cdf\"",
")",
":",
"# TODO(srvasude): Implement this once betainc op is checked in.",
"raise",
"NotImplementedError",
"(",
"\"Beta cdf not implemented.\"",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py#L305-L308 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/inspector_protocol/jinja2/environment.py | python | Environment.call_test | (self, name, value, args=None, kwargs=None) | return func(value, *(args or ()), **(kwargs or {})) | Invokes a test on a value the same way the compiler does it.
.. versionadded:: 2.7 | Invokes a test on a value the same way the compiler does it. | [
"Invokes",
"a",
"test",
"on",
"a",
"value",
"the",
"same",
"way",
"the",
"compiler",
"does",
"it",
"."
] | def call_test(self, name, value, args=None, kwargs=None):
"""Invokes a test on a value the same way the compiler does it.
.. versionadded:: 2.7
"""
func = self.tests.get(name)
if func is None:
fail_for_missing_callable('no test named %r', name)
return func(value, *(args or ()), **(kwargs or {})) | [
"def",
"call_test",
"(",
"self",
",",
"name",
",",
"value",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"func",
"=",
"self",
".",
"tests",
".",
"get",
"(",
"name",
")",
"if",
"func",
"is",
"None",
":",
"fail_for_missing_callable",
"(",
"'no test named %r'",
",",
"name",
")",
"return",
"func",
"(",
"value",
",",
"*",
"(",
"args",
"or",
"(",
")",
")",
",",
"*",
"*",
"(",
"kwargs",
"or",
"{",
"}",
")",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/environment.py#L469-L477 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py | python | ParseExpression.leaveWhitespace | ( self ) | return self | Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on
all contained expressions. | Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on
all contained expressions. | [
"Extends",
"C",
"{",
"leaveWhitespace",
"}",
"defined",
"in",
"base",
"class",
"and",
"also",
"invokes",
"C",
"{",
"leaveWhitespace",
"}",
"on",
"all",
"contained",
"expressions",
"."
] | def leaveWhitespace( self ):
"""Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on
all contained expressions."""
self.skipWhitespace = False
self.exprs = [ e.copy() for e in self.exprs ]
for e in self.exprs:
e.leaveWhitespace()
return self | [
"def",
"leaveWhitespace",
"(",
"self",
")",
":",
"self",
".",
"skipWhitespace",
"=",
"False",
"self",
".",
"exprs",
"=",
"[",
"e",
".",
"copy",
"(",
")",
"for",
"e",
"in",
"self",
".",
"exprs",
"]",
"for",
"e",
"in",
"self",
".",
"exprs",
":",
"e",
".",
"leaveWhitespace",
"(",
")",
"return",
"self"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py#L3289-L3296 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/io/parquet.py | python | to_parquet | (df, path, engine='auto', compression='snappy', index=None,
partition_cols=None, **kwargs) | return impl.write(df, path, compression=compression, index=index,
partition_cols=partition_cols, **kwargs) | Write a DataFrame to the parquet format.
Parameters
----------
path : str
File path or Root Directory path. Will be used as Root Directory path
while writing a partitioned dataset.
.. versionchanged:: 0.24.0
engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto'
Parquet library to use. If 'auto', then the option
``io.parquet.engine`` is used. The default ``io.parquet.engine``
behavior is to try 'pyarrow', falling back to 'fastparquet' if
'pyarrow' is unavailable.
compression : {'snappy', 'gzip', 'brotli', None}, default 'snappy'
Name of the compression to use. Use ``None`` for no compression.
index : bool, default None
If ``True``, include the dataframe's index(es) in the file output. If
``False``, they will not be written to the file. If ``None``, the
engine's default behavior will be used.
.. versionadded 0.24.0
partition_cols : list, optional, default None
Column names by which to partition the dataset
Columns are partitioned in the order they are given
.. versionadded:: 0.24.0
kwargs
Additional keyword arguments passed to the engine | Write a DataFrame to the parquet format. | [
"Write",
"a",
"DataFrame",
"to",
"the",
"parquet",
"format",
"."
] | def to_parquet(df, path, engine='auto', compression='snappy', index=None,
partition_cols=None, **kwargs):
"""
Write a DataFrame to the parquet format.
Parameters
----------
path : str
File path or Root Directory path. Will be used as Root Directory path
while writing a partitioned dataset.
.. versionchanged:: 0.24.0
engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto'
Parquet library to use. If 'auto', then the option
``io.parquet.engine`` is used. The default ``io.parquet.engine``
behavior is to try 'pyarrow', falling back to 'fastparquet' if
'pyarrow' is unavailable.
compression : {'snappy', 'gzip', 'brotli', None}, default 'snappy'
Name of the compression to use. Use ``None`` for no compression.
index : bool, default None
If ``True``, include the dataframe's index(es) in the file output. If
``False``, they will not be written to the file. If ``None``, the
engine's default behavior will be used.
.. versionadded 0.24.0
partition_cols : list, optional, default None
Column names by which to partition the dataset
Columns are partitioned in the order they are given
.. versionadded:: 0.24.0
kwargs
Additional keyword arguments passed to the engine
"""
impl = get_engine(engine)
return impl.write(df, path, compression=compression, index=index,
partition_cols=partition_cols, **kwargs) | [
"def",
"to_parquet",
"(",
"df",
",",
"path",
",",
"engine",
"=",
"'auto'",
",",
"compression",
"=",
"'snappy'",
",",
"index",
"=",
"None",
",",
"partition_cols",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"impl",
"=",
"get_engine",
"(",
"engine",
")",
"return",
"impl",
".",
"write",
"(",
"df",
",",
"path",
",",
"compression",
"=",
"compression",
",",
"index",
"=",
"index",
",",
"partition_cols",
"=",
"partition_cols",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/parquet.py#L214-L252 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/tkinter/filedialog.py | python | askopenfilenames | (**options) | return Open(**options).show() | Ask for multiple filenames to open
Returns a list of filenames or empty list if
cancel button selected | Ask for multiple filenames to open | [
"Ask",
"for",
"multiple",
"filenames",
"to",
"open"
] | def askopenfilenames(**options):
"""Ask for multiple filenames to open
Returns a list of filenames or empty list if
cancel button selected
"""
options["multiple"]=1
return Open(**options).show() | [
"def",
"askopenfilenames",
"(",
"*",
"*",
"options",
")",
":",
"options",
"[",
"\"multiple\"",
"]",
"=",
"1",
"return",
"Open",
"(",
"*",
"*",
"options",
")",
".",
"show",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/filedialog.py#L382-L389 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/model.py | python | OperationModel.__init__ | (self, operation_model, service_model, name=None) | :type operation_model: dict
:param operation_model: The operation model. This comes from the
service model, and is the value associated with the operation
name in the service model (i.e ``model['operations'][op_name]``).
:type service_model: botocore.model.ServiceModel
:param service_model: The service model associated with the operation.
:type name: string
:param name: The operation name. This is the operation name exposed to
the users of this model. This can potentially be different from
the "wire_name", which is the operation name that *must* by
provided over the wire. For example, given::
"CreateCloudFrontOriginAccessIdentity":{
"name":"CreateCloudFrontOriginAccessIdentity2014_11_06",
...
}
The ``name`` would be ``CreateCloudFrontOriginAccessIdentity``,
but the ``self.wire_name`` would be
``CreateCloudFrontOriginAccessIdentity2014_11_06``, which is the
value we must send in the corresponding HTTP request. | [] | def __init__(self, operation_model, service_model, name=None):
"""
:type operation_model: dict
:param operation_model: The operation model. This comes from the
service model, and is the value associated with the operation
name in the service model (i.e ``model['operations'][op_name]``).
:type service_model: botocore.model.ServiceModel
:param service_model: The service model associated with the operation.
:type name: string
:param name: The operation name. This is the operation name exposed to
the users of this model. This can potentially be different from
the "wire_name", which is the operation name that *must* by
provided over the wire. For example, given::
"CreateCloudFrontOriginAccessIdentity":{
"name":"CreateCloudFrontOriginAccessIdentity2014_11_06",
...
}
The ``name`` would be ``CreateCloudFrontOriginAccessIdentity``,
but the ``self.wire_name`` would be
``CreateCloudFrontOriginAccessIdentity2014_11_06``, which is the
value we must send in the corresponding HTTP request.
"""
self._operation_model = operation_model
self._service_model = service_model
self._api_name = name
# Clients can access '.name' to get the operation name
# and '.metadata' to get the top level metdata of the service.
self._wire_name = operation_model.get('name')
self.metadata = service_model.metadata
self.http = operation_model.get('http', {}) | [
"def",
"__init__",
"(",
"self",
",",
"operation_model",
",",
"service_model",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"_operation_model",
"=",
"operation_model",
"self",
".",
"_service_model",
"=",
"service_model",
"self",
".",
"_api_name",
"=",
"name",
"# Clients can access '.name' to get the operation name",
"# and '.metadata' to get the top level metdata of the service.",
"self",
".",
"_wire_name",
"=",
"operation_model",
".",
"get",
"(",
"'name'",
")",
"self",
".",
"metadata",
"=",
"service_model",
".",
"metadata",
"self",
".",
"http",
"=",
"operation_model",
".",
"get",
"(",
"'http'",
",",
"{",
"}",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/model.py#L369-L404 | |||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_basestc.py | python | EditraBaseStc.ConfigureLexer | (self, file_ext) | Sets Lexer and Lexer Keywords for the specified file extension
@param file_ext: a file extension to configure the lexer from | Sets Lexer and Lexer Keywords for the specified file extension
@param file_ext: a file extension to configure the lexer from | [
"Sets",
"Lexer",
"and",
"Lexer",
"Keywords",
"for",
"the",
"specified",
"file",
"extension",
"@param",
"file_ext",
":",
"a",
"file",
"extension",
"to",
"configure",
"the",
"lexer",
"from"
] | def ConfigureLexer(self, file_ext):
"""Sets Lexer and Lexer Keywords for the specified file extension
@param file_ext: a file extension to configure the lexer from
"""
syn_data = self._code['synmgr'].GetSyntaxData(file_ext)
# Set the ID of the selected lexer
self._code['lang_id'] = syn_data.LangId
lexer = syn_data.Lexer
# Check for special cases
# TODO: add fetch method to check if container lexer requires extra
# style bytes beyond the default 5.
if lexer in [ wx.stc.STC_LEX_HTML, wx.stc.STC_LEX_XML]:
self.SetStyleBits(7)
elif lexer == wx.stc.STC_LEX_NULL:
self.SetStyleBits(5)
self.SetLexer(lexer)
self.ClearDocumentStyle()
self.UpdateBaseStyles()
return True
else:
self.SetStyleBits(5)
# Set Lexer
self.SetLexer(lexer)
# Set Keywords
self.SetKeyWords(syn_data.Keywords)
# Set Lexer/Syntax Specifications
self.SetSyntax(syn_data.SyntaxSpec)
# Set Extra Properties
self.SetProperties(syn_data.Properties)
# Set Comment Pattern
self._code['comment'] = syn_data.CommentPattern
# Get Extension Features
clexer = syn_data.GetFeature(synglob.FEATURE_STYLETEXT)
indenter = syn_data.GetFeature(synglob.FEATURE_AUTOINDENT)
# Set the Container Lexer Method
self._code['clexer'] = clexer
# Auto-indenter function
self._code['indenter'] = indenter | [
"def",
"ConfigureLexer",
"(",
"self",
",",
"file_ext",
")",
":",
"syn_data",
"=",
"self",
".",
"_code",
"[",
"'synmgr'",
"]",
".",
"GetSyntaxData",
"(",
"file_ext",
")",
"# Set the ID of the selected lexer",
"self",
".",
"_code",
"[",
"'lang_id'",
"]",
"=",
"syn_data",
".",
"LangId",
"lexer",
"=",
"syn_data",
".",
"Lexer",
"# Check for special cases",
"# TODO: add fetch method to check if container lexer requires extra",
"# style bytes beyond the default 5.",
"if",
"lexer",
"in",
"[",
"wx",
".",
"stc",
".",
"STC_LEX_HTML",
",",
"wx",
".",
"stc",
".",
"STC_LEX_XML",
"]",
":",
"self",
".",
"SetStyleBits",
"(",
"7",
")",
"elif",
"lexer",
"==",
"wx",
".",
"stc",
".",
"STC_LEX_NULL",
":",
"self",
".",
"SetStyleBits",
"(",
"5",
")",
"self",
".",
"SetLexer",
"(",
"lexer",
")",
"self",
".",
"ClearDocumentStyle",
"(",
")",
"self",
".",
"UpdateBaseStyles",
"(",
")",
"return",
"True",
"else",
":",
"self",
".",
"SetStyleBits",
"(",
"5",
")",
"# Set Lexer",
"self",
".",
"SetLexer",
"(",
"lexer",
")",
"# Set Keywords",
"self",
".",
"SetKeyWords",
"(",
"syn_data",
".",
"Keywords",
")",
"# Set Lexer/Syntax Specifications",
"self",
".",
"SetSyntax",
"(",
"syn_data",
".",
"SyntaxSpec",
")",
"# Set Extra Properties",
"self",
".",
"SetProperties",
"(",
"syn_data",
".",
"Properties",
")",
"# Set Comment Pattern",
"self",
".",
"_code",
"[",
"'comment'",
"]",
"=",
"syn_data",
".",
"CommentPattern",
"# Get Extension Features",
"clexer",
"=",
"syn_data",
".",
"GetFeature",
"(",
"synglob",
".",
"FEATURE_STYLETEXT",
")",
"indenter",
"=",
"syn_data",
".",
"GetFeature",
"(",
"synglob",
".",
"FEATURE_AUTOINDENT",
")",
"# Set the Container Lexer Method",
"self",
".",
"_code",
"[",
"'clexer'",
"]",
"=",
"clexer",
"# Auto-indenter function",
"self",
".",
"_code",
"[",
"'indenter'",
"]",
"=",
"indenter"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_basestc.py#L421-L464 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/boost_1_66_0/tools/build/src/build/project.py | python | ProjectRegistry.__build_python_module_cache | (self) | Recursively walks through the b2/src subdirectories and
creates an index of base module name to package name. The
index is stored within self.__python_module_cache and allows
for an O(1) module lookup.
For example, given the base module name `toolset`,
self.__python_module_cache['toolset'] will return
'b2.build.toolset'
pkgutil.walk_packages() will find any python package
provided a directory contains an __init__.py. This has the
added benefit of allowing libraries to be installed and
automatically avaiable within the contrib directory.
*Note*: pkgutil.walk_packages() will import any subpackage
in order to access its __path__variable. Meaning:
any initialization code will be run if the package hasn't
already been imported. | Recursively walks through the b2/src subdirectories and
creates an index of base module name to package name. The
index is stored within self.__python_module_cache and allows
for an O(1) module lookup. | [
"Recursively",
"walks",
"through",
"the",
"b2",
"/",
"src",
"subdirectories",
"and",
"creates",
"an",
"index",
"of",
"base",
"module",
"name",
"to",
"package",
"name",
".",
"The",
"index",
"is",
"stored",
"within",
"self",
".",
"__python_module_cache",
"and",
"allows",
"for",
"an",
"O",
"(",
"1",
")",
"module",
"lookup",
"."
] | def __build_python_module_cache(self):
"""Recursively walks through the b2/src subdirectories and
creates an index of base module name to package name. The
index is stored within self.__python_module_cache and allows
for an O(1) module lookup.
For example, given the base module name `toolset`,
self.__python_module_cache['toolset'] will return
'b2.build.toolset'
pkgutil.walk_packages() will find any python package
provided a directory contains an __init__.py. This has the
added benefit of allowing libraries to be installed and
automatically avaiable within the contrib directory.
*Note*: pkgutil.walk_packages() will import any subpackage
in order to access its __path__variable. Meaning:
any initialization code will be run if the package hasn't
already been imported.
"""
cache = {}
for importer, mname, ispkg in pkgutil.walk_packages(b2.__path__, prefix='b2.'):
basename = mname.split('.')[-1]
# since the jam code is only going to have "import toolset ;"
# it doesn't matter if there are separately named "b2.build.toolset" and
# "b2.contrib.toolset" as it is impossible to know which the user is
# referring to.
if basename in cache:
self.manager.errors()('duplicate module name "{0}" '
'found in boost-build path'.format(basename))
cache[basename] = mname
self.__python_module_cache = cache | [
"def",
"__build_python_module_cache",
"(",
"self",
")",
":",
"cache",
"=",
"{",
"}",
"for",
"importer",
",",
"mname",
",",
"ispkg",
"in",
"pkgutil",
".",
"walk_packages",
"(",
"b2",
".",
"__path__",
",",
"prefix",
"=",
"'b2.'",
")",
":",
"basename",
"=",
"mname",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"# since the jam code is only going to have \"import toolset ;\"",
"# it doesn't matter if there are separately named \"b2.build.toolset\" and",
"# \"b2.contrib.toolset\" as it is impossible to know which the user is",
"# referring to.",
"if",
"basename",
"in",
"cache",
":",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"'duplicate module name \"{0}\" '",
"'found in boost-build path'",
".",
"format",
"(",
"basename",
")",
")",
"cache",
"[",
"basename",
"]",
"=",
"mname",
"self",
".",
"__python_module_cache",
"=",
"cache"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/tools/build/src/build/project.py#L693-L724 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/mailbox.py | python | Mailbox.__setitem__ | (self, key, message) | Replace the keyed message; raise KeyError if it doesn't exist. | Replace the keyed message; raise KeyError if it doesn't exist. | [
"Replace",
"the",
"keyed",
"message",
";",
"raise",
"KeyError",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | def __setitem__(self, key, message):
"""Replace the keyed message; raise KeyError if it doesn't exist."""
raise NotImplementedError('Method must be implemented by subclass') | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"message",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Method must be implemented by subclass'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L66-L68 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | EvtHandler.GetPreviousHandler | (*args, **kwargs) | return _core_.EvtHandler_GetPreviousHandler(*args, **kwargs) | GetPreviousHandler(self) -> EvtHandler | GetPreviousHandler(self) -> EvtHandler | [
"GetPreviousHandler",
"(",
"self",
")",
"-",
">",
"EvtHandler"
] | def GetPreviousHandler(*args, **kwargs):
"""GetPreviousHandler(self) -> EvtHandler"""
return _core_.EvtHandler_GetPreviousHandler(*args, **kwargs) | [
"def",
"GetPreviousHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"EvtHandler_GetPreviousHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L4124-L4126 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pkg_resources/__init__.py | python | Distribution.load_entry_point | (self, group, name) | return ep.load() | Return the `name` entry point of `group` or raise ImportError | Return the `name` entry point of `group` or raise ImportError | [
"Return",
"the",
"name",
"entry",
"point",
"of",
"group",
"or",
"raise",
"ImportError"
] | def load_entry_point(self, group, name):
"""Return the `name` entry point of `group` or raise ImportError"""
ep = self.get_entry_info(group, name)
if ep is None:
raise ImportError("Entry point %r not found" % ((group, name),))
return ep.load() | [
"def",
"load_entry_point",
"(",
"self",
",",
"group",
",",
"name",
")",
":",
"ep",
"=",
"self",
".",
"get_entry_info",
"(",
"group",
",",
"name",
")",
"if",
"ep",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"\"Entry point %r not found\"",
"%",
"(",
"(",
"group",
",",
"name",
")",
",",
")",
")",
"return",
"ep",
".",
"load",
"(",
")"
] | 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/pkg_resources/__init__.py#L2723-L2728 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBDebugger.DispatchInputInterrupt | (self) | return _lldb.SBDebugger_DispatchInputInterrupt(self) | DispatchInputInterrupt(self) | DispatchInputInterrupt(self) | [
"DispatchInputInterrupt",
"(",
"self",
")"
] | def DispatchInputInterrupt(self):
"""DispatchInputInterrupt(self)"""
return _lldb.SBDebugger_DispatchInputInterrupt(self) | [
"def",
"DispatchInputInterrupt",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBDebugger_DispatchInputInterrupt",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L3410-L3412 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pprint.py | python | pformat | (object, indent=1, width=80, depth=None) | return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object) | Format a Python object into a pretty-printed representation. | Format a Python object into a pretty-printed representation. | [
"Format",
"a",
"Python",
"object",
"into",
"a",
"pretty",
"-",
"printed",
"representation",
"."
] | def pformat(object, indent=1, width=80, depth=None):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object) | [
"def",
"pformat",
"(",
"object",
",",
"indent",
"=",
"1",
",",
"width",
"=",
"80",
",",
"depth",
"=",
"None",
")",
":",
"return",
"PrettyPrinter",
"(",
"indent",
"=",
"indent",
",",
"width",
"=",
"width",
",",
"depth",
"=",
"depth",
")",
".",
"pformat",
"(",
"object",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/pprint.py#L61-L63 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | src/icebox/icebox_py/__init__.py | python | Functions.break_on_return | (self, callback, name="") | return libicebox.functions_break_on_return(name, callback) | Set a single-use breakpoint callback on function return. | Set a single-use breakpoint callback on function return. | [
"Set",
"a",
"single",
"-",
"use",
"breakpoint",
"callback",
"on",
"function",
"return",
"."
] | def break_on_return(self, callback, name=""):
"""Set a single-use breakpoint callback on function return."""
# TODO do we need to keep ref on callback ?
return libicebox.functions_break_on_return(name, callback) | [
"def",
"break_on_return",
"(",
"self",
",",
"callback",
",",
"name",
"=",
"\"\"",
")",
":",
"# TODO do we need to keep ref on callback ?",
"return",
"libicebox",
".",
"functions_break_on_return",
"(",
"name",
",",
"callback",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/src/icebox/icebox_py/__init__.py#L536-L539 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Environment.py | python | Base.PrependENVPath | (self, name, newpath, envname = 'ENV', sep = os.pathsep,
delete_existing=1) | Prepend path elements to the path 'name' in the 'ENV'
dictionary for this environment. Will only add any particular
path once, and will normpath and normcase all paths to help
assure this. This can also handle the case where the env
variable is a list instead of a string.
If delete_existing is 0, a newpath which is already in the path
will not be moved to the front (it will be left where it is). | Prepend path elements to the path 'name' in the 'ENV'
dictionary for this environment. Will only add any particular
path once, and will normpath and normcase all paths to help
assure this. This can also handle the case where the env
variable is a list instead of a string. | [
"Prepend",
"path",
"elements",
"to",
"the",
"path",
"name",
"in",
"the",
"ENV",
"dictionary",
"for",
"this",
"environment",
".",
"Will",
"only",
"add",
"any",
"particular",
"path",
"once",
"and",
"will",
"normpath",
"and",
"normcase",
"all",
"paths",
"to",
"help",
"assure",
"this",
".",
"This",
"can",
"also",
"handle",
"the",
"case",
"where",
"the",
"env",
"variable",
"is",
"a",
"list",
"instead",
"of",
"a",
"string",
"."
] | def PrependENVPath(self, name, newpath, envname = 'ENV', sep = os.pathsep,
delete_existing=1):
"""Prepend path elements to the path 'name' in the 'ENV'
dictionary for this environment. Will only add any particular
path once, and will normpath and normcase all paths to help
assure this. This can also handle the case where the env
variable is a list instead of a string.
If delete_existing is 0, a newpath which is already in the path
will not be moved to the front (it will be left where it is).
"""
orig = ''
if envname in self._dict and name in self._dict[envname]:
orig = self._dict[envname][name]
nv = PrependPath(orig, newpath, sep, delete_existing,
canonicalize=self._canonicalize)
if envname not in self._dict:
self._dict[envname] = {}
self._dict[envname][name] = nv | [
"def",
"PrependENVPath",
"(",
"self",
",",
"name",
",",
"newpath",
",",
"envname",
"=",
"'ENV'",
",",
"sep",
"=",
"os",
".",
"pathsep",
",",
"delete_existing",
"=",
"1",
")",
":",
"orig",
"=",
"''",
"if",
"envname",
"in",
"self",
".",
"_dict",
"and",
"name",
"in",
"self",
".",
"_dict",
"[",
"envname",
"]",
":",
"orig",
"=",
"self",
".",
"_dict",
"[",
"envname",
"]",
"[",
"name",
"]",
"nv",
"=",
"PrependPath",
"(",
"orig",
",",
"newpath",
",",
"sep",
",",
"delete_existing",
",",
"canonicalize",
"=",
"self",
".",
"_canonicalize",
")",
"if",
"envname",
"not",
"in",
"self",
".",
"_dict",
":",
"self",
".",
"_dict",
"[",
"envname",
"]",
"=",
"{",
"}",
"self",
".",
"_dict",
"[",
"envname",
"]",
"[",
"name",
"]",
"=",
"nv"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Environment.py#L1751-L1773 | ||
leosac/leosac | 932a2a90bd2e75483d46b24fdbc8f02e0809d731 | python/leosacpy/cli/dev/docker.py | python | build | (ctx, images, nocache) | Build the specified ('main', 'main2', 'server', or 'cross_compile'), or all
leosac related images. | Build the specified ('main', 'main2', 'server', or 'cross_compile'), or all
leosac related images. | [
"Build",
"the",
"specified",
"(",
"main",
"main2",
"server",
"or",
"cross_compile",
")",
"or",
"all",
"leosac",
"related",
"images",
"."
] | def build(ctx, images, nocache):
"""
Build the specified ('main', 'main2', 'server', or 'cross_compile'), or all
leosac related images.
"""
dc = get_docker_api_client()
for image in (images or AVAILABLE_IMAGES):
dockerfile = 'docker/Dockerfile.{}'.format(image)
build_output = dc.build(path=guess_root_dir(),
dockerfile=dockerfile,
tag='leosac_{}'.format(image),
decode=True, # Better stream output
nocache=nocache)
success = True
for line in build_output:
has_error, clean_line = clean_output_build_line(line)
if not has_error:
success = False
print('Building {}: {}'.format(image,
clean_line))
if success:
print('Built {}'.format(image))
else:
print('Error building {}'.format(image))
pass | [
"def",
"build",
"(",
"ctx",
",",
"images",
",",
"nocache",
")",
":",
"dc",
"=",
"get_docker_api_client",
"(",
")",
"for",
"image",
"in",
"(",
"images",
"or",
"AVAILABLE_IMAGES",
")",
":",
"dockerfile",
"=",
"'docker/Dockerfile.{}'",
".",
"format",
"(",
"image",
")",
"build_output",
"=",
"dc",
".",
"build",
"(",
"path",
"=",
"guess_root_dir",
"(",
")",
",",
"dockerfile",
"=",
"dockerfile",
",",
"tag",
"=",
"'leosac_{}'",
".",
"format",
"(",
"image",
")",
",",
"decode",
"=",
"True",
",",
"# Better stream output",
"nocache",
"=",
"nocache",
")",
"success",
"=",
"True",
"for",
"line",
"in",
"build_output",
":",
"has_error",
",",
"clean_line",
"=",
"clean_output_build_line",
"(",
"line",
")",
"if",
"not",
"has_error",
":",
"success",
"=",
"False",
"print",
"(",
"'Building {}: {}'",
".",
"format",
"(",
"image",
",",
"clean_line",
")",
")",
"if",
"success",
":",
"print",
"(",
"'Built {}'",
".",
"format",
"(",
"image",
")",
")",
"else",
":",
"print",
"(",
"'Error building {}'",
".",
"format",
"(",
"image",
")",
")",
"pass"
] | https://github.com/leosac/leosac/blob/932a2a90bd2e75483d46b24fdbc8f02e0809d731/python/leosacpy/cli/dev/docker.py#L56-L84 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/_vendor/six.py | python | add_metaclass | (metaclass) | return wrapper | Class decorator for creating a class with a metaclass. | Class decorator for creating a class with a metaclass. | [
"Class",
"decorator",
"for",
"creating",
"a",
"class",
"with",
"a",
"metaclass",
"."
] | def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper | [
"def",
"add_metaclass",
"(",
"metaclass",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"orig_vars",
"=",
"cls",
".",
"__dict__",
".",
"copy",
"(",
")",
"slots",
"=",
"orig_vars",
".",
"get",
"(",
"'__slots__'",
")",
"if",
"slots",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"slots",
",",
"str",
")",
":",
"slots",
"=",
"[",
"slots",
"]",
"for",
"slots_var",
"in",
"slots",
":",
"orig_vars",
".",
"pop",
"(",
"slots_var",
")",
"orig_vars",
".",
"pop",
"(",
"'__dict__'",
",",
"None",
")",
"orig_vars",
".",
"pop",
"(",
"'__weakref__'",
",",
"None",
")",
"return",
"metaclass",
"(",
"cls",
".",
"__name__",
",",
"cls",
".",
"__bases__",
",",
"orig_vars",
")",
"return",
"wrapper"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/_vendor/six.py#L812-L825 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/tools/cpplint.py | python | CheckAltTokens | (filename, clean_lines, linenum, error) | Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Check alternative keywords being used in boolean expressions. | [
"Check",
"alternative",
"keywords",
"being",
"used",
"in",
"boolean",
"expressions",
"."
] | def CheckAltTokens(filename, clean_lines, linenum, error):
"""Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Avoid preprocessor lines
if Match(r'^\s*#', line):
return
# Last ditch effort to avoid multi-line comments. This will not help
# if the comment started before the current line or ended after the
# current line, but it catches most of the false positives. At least,
# it provides a way to workaround this warning for people who use
# multi-line comments in preprocessor macros.
#
# TODO(unknown): remove this once cpplint has better support for
# multi-line comments.
if line.find('/*') >= 0 or line.find('*/') >= 0:
return
for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
error(filename, linenum, 'readability/alt_tokens', 2,
'Use operator %s instead of %s' % (
_ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) | [
"def",
"CheckAltTokens",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Avoid preprocessor lines",
"if",
"Match",
"(",
"r'^\\s*#'",
",",
"line",
")",
":",
"return",
"# Last ditch effort to avoid multi-line comments. This will not help",
"# if the comment started before the current line or ended after the",
"# current line, but it catches most of the false positives. At least,",
"# it provides a way to workaround this warning for people who use",
"# multi-line comments in preprocessor macros.",
"#",
"# TODO(unknown): remove this once cpplint has better support for",
"# multi-line comments.",
"if",
"line",
".",
"find",
"(",
"'/*'",
")",
">=",
"0",
"or",
"line",
".",
"find",
"(",
"'*/'",
")",
">=",
"0",
":",
"return",
"for",
"match",
"in",
"_ALT_TOKEN_REPLACEMENT_PATTERN",
".",
"finditer",
"(",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/alt_tokens'",
",",
"2",
",",
"'Use operator %s instead of %s'",
"%",
"(",
"_ALT_TOKEN_REPLACEMENT",
"[",
"match",
".",
"group",
"(",
"1",
")",
"]",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/cpplint.py#L4771-L4800 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/auth.py | python | SecureAuthSubToken.GetAuthHeader | (self, http_method, http_url) | return header | Generates the Authorization header.
The form of the secure AuthSub Authorization header is
Authorization: AuthSub token="token" sigalg="sigalg" data="data" sig="sig"
and data represents a string in the form
data = http_method http_url timestamp nonce
Args:
http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc.
http_url: string or atom.url.Url HTTP URL to which request is made.
Returns:
dict Header to be sent with every subsequent request after authentication. | Generates the Authorization header. | [
"Generates",
"the",
"Authorization",
"header",
"."
] | def GetAuthHeader(self, http_method, http_url):
"""Generates the Authorization header.
The form of the secure AuthSub Authorization header is
Authorization: AuthSub token="token" sigalg="sigalg" data="data" sig="sig"
and data represents a string in the form
data = http_method http_url timestamp nonce
Args:
http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc.
http_url: string or atom.url.Url HTTP URL to which request is made.
Returns:
dict Header to be sent with every subsequent request after authentication.
"""
timestamp = int(math.floor(time.time()))
nonce = '%lu' % random.randrange(1, 2**64)
data = '%s %s %d %s' % (http_method, str(http_url), timestamp, nonce)
sig = cryptomath.bytesToBase64(self.rsa_key.hashAndSign(data))
header = {'Authorization': '%s"%s" data="%s" sig="%s" sigalg="rsa-sha1"' %
(AUTHSUB_AUTH_LABEL, self.token_string, data, sig)}
return header | [
"def",
"GetAuthHeader",
"(",
"self",
",",
"http_method",
",",
"http_url",
")",
":",
"timestamp",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"nonce",
"=",
"'%lu'",
"%",
"random",
".",
"randrange",
"(",
"1",
",",
"2",
"**",
"64",
")",
"data",
"=",
"'%s %s %d %s'",
"%",
"(",
"http_method",
",",
"str",
"(",
"http_url",
")",
",",
"timestamp",
",",
"nonce",
")",
"sig",
"=",
"cryptomath",
".",
"bytesToBase64",
"(",
"self",
".",
"rsa_key",
".",
"hashAndSign",
"(",
"data",
")",
")",
"header",
"=",
"{",
"'Authorization'",
":",
"'%s\"%s\" data=\"%s\" sig=\"%s\" sigalg=\"rsa-sha1\"'",
"%",
"(",
"AUTHSUB_AUTH_LABEL",
",",
"self",
".",
"token_string",
",",
"data",
",",
"sig",
")",
"}",
"return",
"header"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/auth.py#L923-L944 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/ndarray.py | python | NDArray.__idiv__ | (self, other) | x.__rdiv__(y) <=> x/=y | x.__rdiv__(y) <=> x/=y | [
"x",
".",
"__rdiv__",
"(",
"y",
")",
"<",
"=",
">",
"x",
"/",
"=",
"y"
] | def __idiv__(self, other):
"""x.__rdiv__(y) <=> x/=y """
if not self.writable:
raise ValueError('trying to divide from a readonly NDArray')
if isinstance(other, NDArray):
return op.broadcast_div(self, other, out=self)
elif isinstance(other, numeric_types):
return _internal._div_scalar(self, float(other), out=self)
else:
raise TypeError('type %s not supported' % str(type(other))) | [
"def",
"__idiv__",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"self",
".",
"writable",
":",
"raise",
"ValueError",
"(",
"'trying to divide from a readonly NDArray'",
")",
"if",
"isinstance",
"(",
"other",
",",
"NDArray",
")",
":",
"return",
"op",
".",
"broadcast_div",
"(",
"self",
",",
"other",
",",
"out",
"=",
"self",
")",
"elif",
"isinstance",
"(",
"other",
",",
"numeric_types",
")",
":",
"return",
"_internal",
".",
"_div_scalar",
"(",
"self",
",",
"float",
"(",
"other",
")",
",",
"out",
"=",
"self",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'type %s not supported'",
"%",
"str",
"(",
"type",
"(",
"other",
")",
")",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L374-L383 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mock/mock.py | python | NonCallableMock.mock_add_spec | (self, spec, spec_set=False) | Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set. | Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock. | [
"Add",
"a",
"spec",
"to",
"a",
"mock",
".",
"spec",
"can",
"either",
"be",
"an",
"object",
"or",
"a",
"list",
"of",
"strings",
".",
"Only",
"attributes",
"on",
"the",
"spec",
"can",
"be",
"fetched",
"as",
"attributes",
"from",
"the",
"mock",
"."
] | def mock_add_spec(self, spec, spec_set=False):
"""Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set."""
self._mock_add_spec(spec, spec_set) | [
"def",
"mock_add_spec",
"(",
"self",
",",
"spec",
",",
"spec_set",
"=",
"False",
")",
":",
"self",
".",
"_mock_add_spec",
"(",
"spec",
",",
"spec_set",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mock/mock.py#L531-L537 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/Editra.py | python | Editra.GetLocaleObject | (self) | return self.locale | Get the locale object owned by this app. Use this method to add
extra catalogs for lookup.
@return: wx.Locale or None | Get the locale object owned by this app. Use this method to add
extra catalogs for lookup.
@return: wx.Locale or None | [
"Get",
"the",
"locale",
"object",
"owned",
"by",
"this",
"app",
".",
"Use",
"this",
"method",
"to",
"add",
"extra",
"catalogs",
"for",
"lookup",
".",
"@return",
":",
"wx",
".",
"Locale",
"or",
"None"
] | def GetLocaleObject(self):
"""Get the locale object owned by this app. Use this method to add
extra catalogs for lookup.
@return: wx.Locale or None
"""
return self.locale | [
"def",
"GetLocaleObject",
"(",
"self",
")",
":",
"return",
"self",
".",
"locale"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/Editra.py#L312-L318 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetBundleContentsFolderPath | (self) | Returns the qualified path to the bundle's contents folder. E.g.
Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles. | Returns the qualified path to the bundle's contents folder. E.g.
Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles. | [
"Returns",
"the",
"qualified",
"path",
"to",
"the",
"bundle",
"s",
"contents",
"folder",
".",
"E",
".",
"g",
".",
"Chromium",
".",
"app",
"/",
"Contents",
"or",
"Foo",
".",
"bundle",
"/",
"Versions",
"/",
"A",
".",
"Only",
"valid",
"for",
"bundles",
"."
] | def GetBundleContentsFolderPath(self):
"""Returns the qualified path to the bundle's contents folder. E.g.
Chromium.app/Contents or Foo.bundle/Versions/A. Only valid for bundles."""
if self.isIOS:
return self.GetWrapperName()
assert self._IsBundle()
if self.spec['type'] == 'shared_library':
return os.path.join(
self.GetWrapperName(), 'Versions', self.GetFrameworkVersion())
else:
# loadable_modules have a 'Contents' folder like executables.
return os.path.join(self.GetWrapperName(), 'Contents') | [
"def",
"GetBundleContentsFolderPath",
"(",
"self",
")",
":",
"if",
"self",
".",
"isIOS",
":",
"return",
"self",
".",
"GetWrapperName",
"(",
")",
"assert",
"self",
".",
"_IsBundle",
"(",
")",
"if",
"self",
".",
"spec",
"[",
"'type'",
"]",
"==",
"'shared_library'",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"GetWrapperName",
"(",
")",
",",
"'Versions'",
",",
"self",
".",
"GetFrameworkVersion",
"(",
")",
")",
"else",
":",
"# loadable_modules have a 'Contents' folder like executables.",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"GetWrapperName",
"(",
")",
",",
"'Contents'",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L287-L298 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/framework/ops.py | python | get_gradient_function | (op) | return _gradient_registry.lookup(op_type) | Returns the function that computes gradients for "op". | Returns the function that computes gradients for "op". | [
"Returns",
"the",
"function",
"that",
"computes",
"gradients",
"for",
"op",
"."
] | def get_gradient_function(op):
"""Returns the function that computes gradients for "op"."""
if not op.inputs: return None
try:
op_type = op.get_attr("_gradient_op_type")
except ValueError:
op_type = op.type
return _gradient_registry.lookup(op_type) | [
"def",
"get_gradient_function",
"(",
"op",
")",
":",
"if",
"not",
"op",
".",
"inputs",
":",
"return",
"None",
"try",
":",
"op_type",
"=",
"op",
".",
"get_attr",
"(",
"\"_gradient_op_type\"",
")",
"except",
"ValueError",
":",
"op_type",
"=",
"op",
".",
"type",
"return",
"_gradient_registry",
".",
"lookup",
"(",
"op_type",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/ops.py#L1634-L1641 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/design-an-ordered-stream.py | python | OrderedStream.insert | (self, id, value) | return result | :type id: int
:type value: str
:rtype: List[str] | :type id: int
:type value: str
:rtype: List[str] | [
":",
"type",
"id",
":",
"int",
":",
"type",
"value",
":",
"str",
":",
"rtype",
":",
"List",
"[",
"str",
"]"
] | def insert(self, id, value):
"""
:type id: int
:type value: str
:rtype: List[str]
"""
id -= 1
self.__values[id] = value
result = []
if self.__i != id:
return result
while self.__i < len(self.__values) and self.__values[self.__i]:
result.append(self.__values[self.__i])
self.__i += 1
return result | [
"def",
"insert",
"(",
"self",
",",
"id",
",",
"value",
")",
":",
"id",
"-=",
"1",
"self",
".",
"__values",
"[",
"id",
"]",
"=",
"value",
"result",
"=",
"[",
"]",
"if",
"self",
".",
"__i",
"!=",
"id",
":",
"return",
"result",
"while",
"self",
".",
"__i",
"<",
"len",
"(",
"self",
".",
"__values",
")",
"and",
"self",
".",
"__values",
"[",
"self",
".",
"__i",
"]",
":",
"result",
".",
"append",
"(",
"self",
".",
"__values",
"[",
"self",
".",
"__i",
"]",
")",
"self",
".",
"__i",
"+=",
"1",
"return",
"result"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/design-an-ordered-stream.py#L13-L27 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/distutils/command/install.py | python | install.create_home_path | (self) | Create directories under ~. | Create directories under ~. | [
"Create",
"directories",
"under",
"~",
"."
] | def create_home_path(self):
"""Create directories under ~."""
if not self.user:
return
home = convert_path(os.path.expanduser("~"))
for name, path in self.config_vars.items():
if path.startswith(home) and not os.path.isdir(path):
self.debug_print("os.makedirs('%s', 0o700)" % path)
os.makedirs(path, 0o700) | [
"def",
"create_home_path",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"user",
":",
"return",
"home",
"=",
"convert_path",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
")",
"for",
"name",
",",
"path",
"in",
"self",
".",
"config_vars",
".",
"items",
"(",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"home",
")",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"self",
".",
"debug_print",
"(",
"\"os.makedirs('%s', 0o700)\"",
"%",
"path",
")",
"os",
".",
"makedirs",
"(",
"path",
",",
"0o700",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/command/install.py#L530-L538 | ||
jiangxiluning/FOTS.PyTorch | b1851c170b4f1ad18406766352cb5171648ce603 | FOTS/utils/eval_tools/icdar2015/rrc_evaluation_funcs.py | python | main_evaluation | (p,default_evaluation_params_fn,validate_data_fn,evaluate_method_fn,show_result=True,per_sample=True) | return resDict | This process validates a method, evaluates it and if it succed generates a ZIP file with a JSON entry for each sample.
Params:
p: Dictionary of parmeters with the GT/submission locations. If None is passed, the parameters send by the system are used.
default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation
validate_data_fn: points to a method that validates the corrct format of the submission
evaluate_method_fn: points to a function that evaluated the submission and return a Dictionary with the results | This process validates a method, evaluates it and if it succed generates a ZIP file with a JSON entry for each sample.
Params:
p: Dictionary of parmeters with the GT/submission locations. If None is passed, the parameters send by the system are used.
default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation
validate_data_fn: points to a method that validates the corrct format of the submission
evaluate_method_fn: points to a function that evaluated the submission and return a Dictionary with the results | [
"This",
"process",
"validates",
"a",
"method",
"evaluates",
"it",
"and",
"if",
"it",
"succed",
"generates",
"a",
"ZIP",
"file",
"with",
"a",
"JSON",
"entry",
"for",
"each",
"sample",
".",
"Params",
":",
"p",
":",
"Dictionary",
"of",
"parmeters",
"with",
"the",
"GT",
"/",
"submission",
"locations",
".",
"If",
"None",
"is",
"passed",
"the",
"parameters",
"send",
"by",
"the",
"system",
"are",
"used",
".",
"default_evaluation_params_fn",
":",
"points",
"to",
"a",
"function",
"that",
"returns",
"a",
"dictionary",
"with",
"the",
"default",
"parameters",
"used",
"for",
"the",
"evaluation",
"validate_data_fn",
":",
"points",
"to",
"a",
"method",
"that",
"validates",
"the",
"corrct",
"format",
"of",
"the",
"submission",
"evaluate_method_fn",
":",
"points",
"to",
"a",
"function",
"that",
"evaluated",
"the",
"submission",
"and",
"return",
"a",
"Dictionary",
"with",
"the",
"results"
] | def main_evaluation(p,default_evaluation_params_fn,validate_data_fn,evaluate_method_fn,show_result=True,per_sample=True):
"""
This process validates a method, evaluates it and if it succed generates a ZIP file with a JSON entry for each sample.
Params:
p: Dictionary of parmeters with the GT/submission locations. If None is passed, the parameters send by the system are used.
default_evaluation_params_fn: points to a function that returns a dictionary with the default parameters used for the evaluation
validate_data_fn: points to a method that validates the corrct format of the submission
evaluate_method_fn: points to a function that evaluated the submission and return a Dictionary with the results
"""
if (p == None):
p = dict([s[1:].split('=') for s in sys.argv[1:]])
if(len(sys.argv)<3):
print_help()
evalParams = default_evaluation_params_fn()
if 'p' in p.keys():
evalParams.update( p['p'] if isinstance(p['p'], dict) else json.loads(p['p'][1:-1]) )
resDict={'calculated':True,'Message':'','method':'{}','per_sample':'{}'}
try:
validate_data_fn(p['g'], p['s'], evalParams)
evalData = evaluate_method_fn(p['g'], p['s'], evalParams)
resDict.update(evalData)
except Exception as e:
resDict['Message']= str(e)
resDict['calculated']=False
if 'o' in p:
if not os.path.exists(p['o']):
os.makedirs(p['o'])
resultsOutputname = p['o'] + '/results.zip'
outZip = zipfile.ZipFile(resultsOutputname, mode='w', allowZip64=True)
del resDict['per_sample']
if 'output_items' in resDict.keys():
del resDict['output_items']
outZip.writestr('method.json',json.dumps(resDict))
if not resDict['calculated']:
if show_result:
sys.stderr.write('Error!\n'+ resDict['Message']+'\n\n')
if 'o' in p:
outZip.close()
return resDict
if 'o' in p:
if per_sample == True:
for k,v in evalData['per_sample'].iteritems():
outZip.writestr( k + '.json',json.dumps(v))
if 'output_items' in evalData.keys():
for k, v in evalData['output_items'].iteritems():
outZip.writestr( k,v)
outZip.close()
if show_result:
sys.stdout.write("Calculated!")
sys.stdout.write(json.dumps(resDict['method']))
return resDict | [
"def",
"main_evaluation",
"(",
"p",
",",
"default_evaluation_params_fn",
",",
"validate_data_fn",
",",
"evaluate_method_fn",
",",
"show_result",
"=",
"True",
",",
"per_sample",
"=",
"True",
")",
":",
"if",
"(",
"p",
"==",
"None",
")",
":",
"p",
"=",
"dict",
"(",
"[",
"s",
"[",
"1",
":",
"]",
".",
"split",
"(",
"'='",
")",
"for",
"s",
"in",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"]",
")",
"if",
"(",
"len",
"(",
"sys",
".",
"argv",
")",
"<",
"3",
")",
":",
"print_help",
"(",
")",
"evalParams",
"=",
"default_evaluation_params_fn",
"(",
")",
"if",
"'p'",
"in",
"p",
".",
"keys",
"(",
")",
":",
"evalParams",
".",
"update",
"(",
"p",
"[",
"'p'",
"]",
"if",
"isinstance",
"(",
"p",
"[",
"'p'",
"]",
",",
"dict",
")",
"else",
"json",
".",
"loads",
"(",
"p",
"[",
"'p'",
"]",
"[",
"1",
":",
"-",
"1",
"]",
")",
")",
"resDict",
"=",
"{",
"'calculated'",
":",
"True",
",",
"'Message'",
":",
"''",
",",
"'method'",
":",
"'{}'",
",",
"'per_sample'",
":",
"'{}'",
"}",
"try",
":",
"validate_data_fn",
"(",
"p",
"[",
"'g'",
"]",
",",
"p",
"[",
"'s'",
"]",
",",
"evalParams",
")",
"evalData",
"=",
"evaluate_method_fn",
"(",
"p",
"[",
"'g'",
"]",
",",
"p",
"[",
"'s'",
"]",
",",
"evalParams",
")",
"resDict",
".",
"update",
"(",
"evalData",
")",
"except",
"Exception",
"as",
"e",
":",
"resDict",
"[",
"'Message'",
"]",
"=",
"str",
"(",
"e",
")",
"resDict",
"[",
"'calculated'",
"]",
"=",
"False",
"if",
"'o'",
"in",
"p",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"p",
"[",
"'o'",
"]",
")",
":",
"os",
".",
"makedirs",
"(",
"p",
"[",
"'o'",
"]",
")",
"resultsOutputname",
"=",
"p",
"[",
"'o'",
"]",
"+",
"'/results.zip'",
"outZip",
"=",
"zipfile",
".",
"ZipFile",
"(",
"resultsOutputname",
",",
"mode",
"=",
"'w'",
",",
"allowZip64",
"=",
"True",
")",
"del",
"resDict",
"[",
"'per_sample'",
"]",
"if",
"'output_items'",
"in",
"resDict",
".",
"keys",
"(",
")",
":",
"del",
"resDict",
"[",
"'output_items'",
"]",
"outZip",
".",
"writestr",
"(",
"'method.json'",
",",
"json",
".",
"dumps",
"(",
"resDict",
")",
")",
"if",
"not",
"resDict",
"[",
"'calculated'",
"]",
":",
"if",
"show_result",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Error!\\n'",
"+",
"resDict",
"[",
"'Message'",
"]",
"+",
"'\\n\\n'",
")",
"if",
"'o'",
"in",
"p",
":",
"outZip",
".",
"close",
"(",
")",
"return",
"resDict",
"if",
"'o'",
"in",
"p",
":",
"if",
"per_sample",
"==",
"True",
":",
"for",
"k",
",",
"v",
"in",
"evalData",
"[",
"'per_sample'",
"]",
".",
"iteritems",
"(",
")",
":",
"outZip",
".",
"writestr",
"(",
"k",
"+",
"'.json'",
",",
"json",
".",
"dumps",
"(",
"v",
")",
")",
"if",
"'output_items'",
"in",
"evalData",
".",
"keys",
"(",
")",
":",
"for",
"k",
",",
"v",
"in",
"evalData",
"[",
"'output_items'",
"]",
".",
"iteritems",
"(",
")",
":",
"outZip",
".",
"writestr",
"(",
"k",
",",
"v",
")",
"outZip",
".",
"close",
"(",
")",
"if",
"show_result",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"Calculated!\"",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"resDict",
"[",
"'method'",
"]",
")",
")",
"return",
"resDict"
] | https://github.com/jiangxiluning/FOTS.PyTorch/blob/b1851c170b4f1ad18406766352cb5171648ce603/FOTS/utils/eval_tools/icdar2015/rrc_evaluation_funcs.py#L281-L345 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/pep425tags.py | python | get_platform | () | return distutils.util.get_platform().replace('.', '_').replace('-', '_') | Return our platform name 'win32', 'linux_x86_64 | Return our platform name 'win32', 'linux_x86_64 | [
"Return",
"our",
"platform",
"name",
"win32",
"linux_x86_64"
] | def get_platform():
"""Return our platform name 'win32', 'linux_x86_64'"""
# XXX remove distutils dependency
return distutils.util.get_platform().replace('.', '_').replace('-', '_') | [
"def",
"get_platform",
"(",
")",
":",
"# XXX remove distutils dependency",
"return",
"distutils",
".",
"util",
".",
"get_platform",
"(",
")",
".",
"replace",
"(",
"'.'",
",",
"'_'",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/pep425tags.py#L32-L35 | |
mkeeter/antimony | ee525bbdad34ae94879fd055821f92bcef74e83f | py/fab/shapes.py | python | loft_xy_z | (a, b, zmin, zmax) | return Shape(('aa-Zf%(zmax)g-f%(zmin)g' +
'Z/+*-Zf%(zmin)g%(b_)s' +
'*-f%(zmax)gZ%(a_)sf%(dz)g') % locals(),
min(a.bounds.xmin, b.bounds.xmin),
min(a.bounds.ymin, b.bounds.ymin), zmin,
max(a.bounds.xmax, b.bounds.xmax),
max(a.bounds.ymax, b.bounds.ymax), zmax) | Creates a blended loft between two shapes.
Input shapes should be 2D (in the XY plane).
The resulting loft will be shape a at zmin and b at zmax. | Creates a blended loft between two shapes. | [
"Creates",
"a",
"blended",
"loft",
"between",
"two",
"shapes",
"."
] | def loft_xy_z(a, b, zmin, zmax):
""" Creates a blended loft between two shapes.
Input shapes should be 2D (in the XY plane).
The resulting loft will be shape a at zmin and b at zmax.
"""
# ((z-zmin)/(zmax-zmin))*b + ((zmax-z)/(zmax-zmin))*a
# In the prefix string below, we add caps at zmin and zmax then
# factor out the division by (zmax - zmin)
dz = zmax - zmin
a_, b_ = a.math, b.math
return Shape(('aa-Zf%(zmax)g-f%(zmin)g' +
'Z/+*-Zf%(zmin)g%(b_)s' +
'*-f%(zmax)gZ%(a_)sf%(dz)g') % locals(),
min(a.bounds.xmin, b.bounds.xmin),
min(a.bounds.ymin, b.bounds.ymin), zmin,
max(a.bounds.xmax, b.bounds.xmax),
max(a.bounds.ymax, b.bounds.ymax), zmax) | [
"def",
"loft_xy_z",
"(",
"a",
",",
"b",
",",
"zmin",
",",
"zmax",
")",
":",
"# ((z-zmin)/(zmax-zmin))*b + ((zmax-z)/(zmax-zmin))*a",
"# In the prefix string below, we add caps at zmin and zmax then",
"# factor out the division by (zmax - zmin)",
"dz",
"=",
"zmax",
"-",
"zmin",
"a_",
",",
"b_",
"=",
"a",
".",
"math",
",",
"b",
".",
"math",
"return",
"Shape",
"(",
"(",
"'aa-Zf%(zmax)g-f%(zmin)g'",
"+",
"'Z/+*-Zf%(zmin)g%(b_)s'",
"+",
"'*-f%(zmax)gZ%(a_)sf%(dz)g'",
")",
"%",
"locals",
"(",
")",
",",
"min",
"(",
"a",
".",
"bounds",
".",
"xmin",
",",
"b",
".",
"bounds",
".",
"xmin",
")",
",",
"min",
"(",
"a",
".",
"bounds",
".",
"ymin",
",",
"b",
".",
"bounds",
".",
"ymin",
")",
",",
"zmin",
",",
"max",
"(",
"a",
".",
"bounds",
".",
"xmax",
",",
"b",
".",
"bounds",
".",
"xmax",
")",
",",
"max",
"(",
"a",
".",
"bounds",
".",
"ymax",
",",
"b",
".",
"bounds",
".",
"ymax",
")",
",",
"zmax",
")"
] | https://github.com/mkeeter/antimony/blob/ee525bbdad34ae94879fd055821f92bcef74e83f/py/fab/shapes.py#L425-L442 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py | python | Standard_Suite_Events.count | (self, _object, _attributes={}, **_arguments) | count: Return the number of elements of a particular class within an object.
Required argument: the object for the command
Keyword argument each: The class of objects to be counted.
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: the reply for the command | count: Return the number of elements of a particular class within an object.
Required argument: the object for the command
Keyword argument each: The class of objects to be counted.
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: the reply for the command | [
"count",
":",
"Return",
"the",
"number",
"of",
"elements",
"of",
"a",
"particular",
"class",
"within",
"an",
"object",
".",
"Required",
"argument",
":",
"the",
"object",
"for",
"the",
"command",
"Keyword",
"argument",
"each",
":",
"The",
"class",
"of",
"objects",
"to",
"be",
"counted",
".",
"Keyword",
"argument",
"_attributes",
":",
"AppleEvent",
"attribute",
"dictionary",
"Returns",
":",
"the",
"reply",
"for",
"the",
"command"
] | def count(self, _object, _attributes={}, **_arguments):
"""count: Return the number of elements of a particular class within an object.
Required argument: the object for the command
Keyword argument each: The class of objects to be counted.
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: the reply for the command
"""
_code = 'core'
_subcode = 'cnte'
aetools.keysubst(_arguments, self._argmap_count)
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----'] | [
"def",
"count",
"(",
"self",
",",
"_object",
",",
"_attributes",
"=",
"{",
"}",
",",
"*",
"*",
"_arguments",
")",
":",
"_code",
"=",
"'core'",
"_subcode",
"=",
"'cnte'",
"aetools",
".",
"keysubst",
"(",
"_arguments",
",",
"self",
".",
"_argmap_count",
")",
"_arguments",
"[",
"'----'",
"]",
"=",
"_object",
"_reply",
",",
"_arguments",
",",
"_attributes",
"=",
"self",
".",
"send",
"(",
"_code",
",",
"_subcode",
",",
"_arguments",
",",
"_attributes",
")",
"if",
"_arguments",
".",
"get",
"(",
"'errn'",
",",
"0",
")",
":",
"raise",
"aetools",
".",
"Error",
",",
"aetools",
".",
"decodeerror",
"(",
"_arguments",
")",
"# XXXX Optionally decode result",
"if",
"_arguments",
".",
"has_key",
"(",
"'----'",
")",
":",
"return",
"_arguments",
"[",
"'----'",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py#L47-L67 | ||
timi-liuliang/echo | 40a5a24d430eee4118314459ab7e03afcb3b8719 | thirdparty/protobuf/python/google/protobuf/message.py | python | Message.Clear | (self) | Clears all data that was set in the message. | Clears all data that was set in the message. | [
"Clears",
"all",
"data",
"that",
"was",
"set",
"in",
"the",
"message",
"."
] | def Clear(self):
"""Clears all data that was set in the message."""
raise NotImplementedError | [
"def",
"Clear",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/message.py#L121-L123 | ||
fengbingchun/NN_Test | d6305825d5273e4569ccd1eda9ffa2a9c72e18d2 | src/tiny-dnn/third_party/cpplint.py | python | CheckAccess | (filename, clean_lines, linenum, nesting_state, error) | Checks for improper use of DISALLOW* macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found. | Checks for improper use of DISALLOW* macros. | [
"Checks",
"for",
"improper",
"use",
"of",
"DISALLOW",
"*",
"macros",
"."
] | def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
"""Checks for improper use of DISALLOW* macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum] # get rid of comments and strings
matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
if not matched:
return
if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
if nesting_state.stack[-1].access != 'private':
error(filename, linenum, 'readability/constructors', 3,
'%s must be in the private: section' % matched.group(1))
else:
# Found DISALLOW* macro outside a class declaration, or perhaps it
# was used inside a function when it should have been part of the
# class declaration. We could issue a warning here, but it
# probably resulted in a compiler error already.
pass | [
"def",
"CheckAccess",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# get rid of comments and strings",
"matched",
"=",
"Match",
"(",
"(",
"r'\\s*(DISALLOW_COPY_AND_ASSIGN|'",
"r'DISALLOW_IMPLICIT_CONSTRUCTORS)'",
")",
",",
"line",
")",
"if",
"not",
"matched",
":",
"return",
"if",
"nesting_state",
".",
"stack",
"and",
"isinstance",
"(",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
",",
"_ClassInfo",
")",
":",
"if",
"nesting_state",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"access",
"!=",
"'private'",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/constructors'",
",",
"3",
",",
"'%s must be in the private: section'",
"%",
"matched",
".",
"group",
"(",
"1",
")",
")",
"else",
":",
"# Found DISALLOW* macro outside a class declaration, or perhaps it",
"# was used inside a function when it should have been part of the",
"# class declaration. We could issue a warning here, but it",
"# probably resulted in a compiler error already.",
"pass"
] | https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/cpplint.py#L3282-L3309 | ||
sonyxperiadev/WebGL | 0299b38196f78c6d5f74bcf6fa312a3daee6de60 | Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py | python | HTMLParserBuilder.handle_pi | (self, text) | Handle a processing instruction as a ProcessingInstruction
object, possibly one with a %SOUP-ENCODING% slot into which an
encoding will be plugged later. | Handle a processing instruction as a ProcessingInstruction
object, possibly one with a %SOUP-ENCODING% slot into which an
encoding will be plugged later. | [
"Handle",
"a",
"processing",
"instruction",
"as",
"a",
"ProcessingInstruction",
"object",
"possibly",
"one",
"with",
"a",
"%SOUP",
"-",
"ENCODING%",
"slot",
"into",
"which",
"an",
"encoding",
"will",
"be",
"plugged",
"later",
"."
] | def handle_pi(self, text):
"""Handle a processing instruction as a ProcessingInstruction
object, possibly one with a %SOUP-ENCODING% slot into which an
encoding will be plugged later."""
if text[:3] == "xml":
text = u"xml version='1.0' encoding='%SOUP-ENCODING%'"
self._toStringSubclass(text, ProcessingInstruction) | [
"def",
"handle_pi",
"(",
"self",
",",
"text",
")",
":",
"if",
"text",
"[",
":",
"3",
"]",
"==",
"\"xml\"",
":",
"text",
"=",
"u\"xml version='1.0' encoding='%SOUP-ENCODING%'\"",
"self",
".",
"_toStringSubclass",
"(",
"text",
",",
"ProcessingInstruction",
")"
] | https://github.com/sonyxperiadev/WebGL/blob/0299b38196f78c6d5f74bcf6fa312a3daee6de60/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py#L1032-L1038 | ||
ValveSoftware/source-sdk-2013 | 0d8dceea4310fde5706b3ce1c70609d72a38efdf | sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py | python | _Tokenizer.AtEnd | (self) | return not self._lines and not self._current_line | Checks the end of the text was reached.
Returns:
True iff the end was reached. | Checks the end of the text was reached. | [
"Checks",
"the",
"end",
"of",
"the",
"text",
"was",
"reached",
"."
] | def AtEnd(self):
"""Checks the end of the text was reached.
Returns:
True iff the end was reached.
"""
return not self._lines and not self._current_line | [
"def",
"AtEnd",
"(",
"self",
")",
":",
"return",
"not",
"self",
".",
"_lines",
"and",
"not",
"self",
".",
"_current_line"
] | https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py#L331-L337 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | mlir/utils/jupyter/mlir_opt_kernel/install.py | python | _is_root | () | Returns whether the current user is root. | Returns whether the current user is root. | [
"Returns",
"whether",
"the",
"current",
"user",
"is",
"root",
"."
] | def _is_root():
"""Returns whether the current user is root."""
try:
return os.geteuid() == 0
except AttributeError:
# Return false wherever unknown.
return False | [
"def",
"_is_root",
"(",
")",
":",
"try",
":",
"return",
"os",
".",
"geteuid",
"(",
")",
"==",
"0",
"except",
"AttributeError",
":",
"# Return false wherever unknown.",
"return",
"False"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/mlir/utils/jupyter/mlir_opt_kernel/install.py#L21-L27 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/site.py | python | execsitecustomize | () | Run custom site specific code, if available. | Run custom site specific code, if available. | [
"Run",
"custom",
"site",
"specific",
"code",
"if",
"available",
"."
] | def execsitecustomize():
"""Run custom site specific code, if available."""
try:
import sitecustomize
except ImportError:
pass
except Exception:
if sys.flags.verbose:
sys.excepthook(*sys.exc_info())
else:
print >>sys.stderr, \
"'import sitecustomize' failed; use -v for traceback" | [
"def",
"execsitecustomize",
"(",
")",
":",
"try",
":",
"import",
"sitecustomize",
"except",
"ImportError",
":",
"pass",
"except",
"Exception",
":",
"if",
"sys",
".",
"flags",
".",
"verbose",
":",
"sys",
".",
"excepthook",
"(",
"*",
"sys",
".",
"exc_info",
"(",
")",
")",
"else",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"'import sitecustomize' failed; use -v for traceback\""
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/site.py#L495-L506 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/cross_device_ops.py | python | _normalize_value_destination_pairs | (value_destination_pairs) | return result | Converts each tensor into a PerReplica object in the input list. | Converts each tensor into a PerReplica object in the input list. | [
"Converts",
"each",
"tensor",
"into",
"a",
"PerReplica",
"object",
"in",
"the",
"input",
"list",
"."
] | def _normalize_value_destination_pairs(value_destination_pairs):
"""Converts each tensor into a PerReplica object in the input list."""
result = []
value_destination_pairs = list(value_destination_pairs)
if not isinstance(value_destination_pairs, (list, tuple)):
raise ValueError("`value_destination_pairs` should be a list or tuple")
for pair in value_destination_pairs:
if not isinstance(pair, tuple):
raise ValueError(
"Each element of `value_destination_pairs` should be a tuple.")
if len(pair) != 2:
raise ValueError("Each element of `value_destination_pairs` should be a "
"tuple of size 2.")
per_replica = _make_tensor_into_per_replica(pair[0])
result.append((per_replica, pair[1]))
return result | [
"def",
"_normalize_value_destination_pairs",
"(",
"value_destination_pairs",
")",
":",
"result",
"=",
"[",
"]",
"value_destination_pairs",
"=",
"list",
"(",
"value_destination_pairs",
")",
"if",
"not",
"isinstance",
"(",
"value_destination_pairs",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"`value_destination_pairs` should be a list or tuple\"",
")",
"for",
"pair",
"in",
"value_destination_pairs",
":",
"if",
"not",
"isinstance",
"(",
"pair",
",",
"tuple",
")",
":",
"raise",
"ValueError",
"(",
"\"Each element of `value_destination_pairs` should be a tuple.\"",
")",
"if",
"len",
"(",
"pair",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"Each element of `value_destination_pairs` should be a \"",
"\"tuple of size 2.\"",
")",
"per_replica",
"=",
"_make_tensor_into_per_replica",
"(",
"pair",
"[",
"0",
"]",
")",
"result",
".",
"append",
"(",
"(",
"per_replica",
",",
"pair",
"[",
"1",
"]",
")",
")",
"return",
"result"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/cross_device_ops.py#L129-L147 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListHeaderWindow.OnPaint | (self, event) | Handles the ``wx.EVT_PAINT`` event for :class:`UltimateListHeaderWindow`.
:param `event`: a :class:`PaintEvent` event to be processed. | Handles the ``wx.EVT_PAINT`` event for :class:`UltimateListHeaderWindow`. | [
"Handles",
"the",
"wx",
".",
"EVT_PAINT",
"event",
"for",
":",
"class",
":",
"UltimateListHeaderWindow",
"."
] | def OnPaint(self, event):
"""
Handles the ``wx.EVT_PAINT`` event for :class:`UltimateListHeaderWindow`.
:param `event`: a :class:`PaintEvent` event to be processed.
"""
dc = wx.BufferedPaintDC(self)
# width and height of the entire header window
w, h = self.GetClientSize()
w, dummy = self._owner.CalcUnscrolledPosition(w, 0)
dc.SetBrush(wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE)))
dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangle(0, -1, w, h+2)
self.AdjustDC(dc)
dc.SetBackgroundMode(wx.TRANSPARENT)
dc.SetTextForeground(self.GetForegroundColour())
x = HEADER_OFFSET_X
numColumns = self._owner.GetColumnCount()
item = UltimateListItem()
renderer = wx.RendererNative.Get()
enabled = self.GetParent().IsEnabled()
virtual = self._owner.IsVirtual()
isFooter = self._isFooter
for i in xrange(numColumns):
# Reset anything in the dc that a custom renderer might have changed
dc.SetTextForeground(self.GetForegroundColour())
if x >= w:
break
if not self.IsColumnShown(i):
continue # do next column if not shown
item = self._owner.GetColumn(i)
wCol = item._width
cw = wCol
ch = h
flags = 0
if not enabled:
flags |= wx.CONTROL_DISABLED
# NB: The code below is not really Mac-specific, but since we are close
# to 2.8 release and I don't have time to test on other platforms, I
# defined this only for wxMac. If this behavior is desired on
# other platforms, please go ahead and revise or remove the #ifdef.
if "__WXMAC__" in wx.PlatformInfo:
if not virtual and item._mask & ULC_MASK_STATE and item._state & ULC_STATE_SELECTED:
flags |= wx.CONTROL_SELECTED
if i == 0:
flags |= wx.CONTROL_SPECIAL # mark as first column
if i == self._currentColumn:
if self._leftDown:
flags |= wx.CONTROL_PRESSED
else:
if self._enter:
flags |= wx.CONTROL_CURRENT
# the width of the rect to draw: make it smaller to fit entirely
# inside the column rect
header_rect = wx.Rect(x, HEADER_OFFSET_Y-1, cw, ch)
if self._headerCustomRenderer != None:
self._headerCustomRenderer.DrawHeaderButton(dc, header_rect, flags)
# The custom renderer will specify the color to draw the header text and buttons
dc.SetTextForeground(self._headerCustomRenderer.GetForegroundColour())
elif item._mask & ULC_MASK_RENDERER:
item.GetCustomRenderer().DrawHeaderButton(dc, header_rect, flags)
# The custom renderer will specify the color to draw the header text and buttons
dc.SetTextForeground(item.GetCustomRenderer().GetForegroundColour())
else:
renderer.DrawHeaderButton(self, dc, header_rect, flags)
# see if we have enough space for the column label
if isFooter:
if item.GetFooterFont().IsOk():
dc.SetFont(item.GetFooterFont())
else:
dc.SetFont(self.GetFont())
else:
if item.GetFont().IsOk():
dc.SetFont(item.GetFont())
else:
dc.SetFont(self.GetFont())
wcheck = hcheck = 0
kind = (isFooter and [item.GetFooterKind()] or [item.GetKind()])[0]
checked = (isFooter and [item.IsFooterChecked()] or [item.IsChecked()])[0]
if kind in [1, 2]:
# We got a checkbox-type item
ix, iy = self._owner.GetCheckboxImageSize()
# We draw it on the left, always
self._owner.DrawCheckbox(dc, x + HEADER_OFFSET_X, HEADER_OFFSET_Y + (h - 4 - iy)/2, kind, checked, enabled)
wcheck += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
cw -= ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
# for this we need the width of the text
text = (isFooter and [item.GetFooterText()] or [item.GetText()])[0]
wLabel, hLabel, dummy = dc.GetMultiLineTextExtent(text)
wLabel += 2*EXTRA_WIDTH
# and the width of the icon, if any
image = (isFooter and [item._footerImage] or [item._image])[0]
if image:
imageList = self._owner._small_image_list
if imageList:
for img in image:
if img >= 0:
ix, iy = imageList.GetSize(img)
wLabel += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
else:
imageList = None
# ignore alignment if there is not enough space anyhow
align = (isFooter and [item.GetFooterAlign()] or [item.GetAlign()])[0]
align = (wLabel < cw and [align] or [ULC_FORMAT_LEFT])[0]
if align == ULC_FORMAT_LEFT:
xAligned = x + wcheck
elif align == ULC_FORMAT_RIGHT:
xAligned = x + cw - wLabel - HEADER_OFFSET_X
elif align == ULC_FORMAT_CENTER:
xAligned = x + wcheck + (cw - wLabel)/2
# if we have an image, draw it on the right of the label
if imageList:
for indx, img in enumerate(image):
if img >= 0:
imageList.Draw(img, dc,
xAligned + wLabel - (ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE)*(indx+1),
HEADER_OFFSET_Y + (h - 4 - iy)/2,
wx.IMAGELIST_DRAW_TRANSPARENT)
cw -= ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
# draw the text clipping it so that it doesn't overwrite the column
# boundary
dc.SetClippingRegion(x, HEADER_OFFSET_Y, cw, h - 4)
self.DrawTextFormatted(dc, text, wx.Rect(xAligned+EXTRA_WIDTH, HEADER_OFFSET_Y, cw-EXTRA_WIDTH, h-4))
x += wCol
dc.DestroyClippingRegion()
# Fill in what's missing to the right of the columns, otherwise we will
# leave an unpainted area when columns are removed (and it looks better)
if x < w:
header_rect = wx.Rect(x, HEADER_OFFSET_Y, w - x, h)
if self._headerCustomRenderer != None:
# Why does the custom renderer need this adjustment??
header_rect.x = header_rect.x - 1
header_rect.y = header_rect.y - 1
self._headerCustomRenderer.DrawHeaderButton(dc, header_rect, wx.CONTROL_DIRTY)
else:
renderer.DrawHeaderButton(self, dc, header_rect, wx.CONTROL_DIRTY) | [
"def",
"OnPaint",
"(",
"self",
",",
"event",
")",
":",
"dc",
"=",
"wx",
".",
"BufferedPaintDC",
"(",
"self",
")",
"# width and height of the entire header window",
"w",
",",
"h",
"=",
"self",
".",
"GetClientSize",
"(",
")",
"w",
",",
"dummy",
"=",
"self",
".",
"_owner",
".",
"CalcUnscrolledPosition",
"(",
"w",
",",
"0",
")",
"dc",
".",
"SetBrush",
"(",
"wx",
".",
"Brush",
"(",
"wx",
".",
"SystemSettings",
".",
"GetColour",
"(",
"wx",
".",
"SYS_COLOUR_BTNFACE",
")",
")",
")",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"TRANSPARENT_PEN",
")",
"dc",
".",
"DrawRectangle",
"(",
"0",
",",
"-",
"1",
",",
"w",
",",
"h",
"+",
"2",
")",
"self",
".",
"AdjustDC",
"(",
"dc",
")",
"dc",
".",
"SetBackgroundMode",
"(",
"wx",
".",
"TRANSPARENT",
")",
"dc",
".",
"SetTextForeground",
"(",
"self",
".",
"GetForegroundColour",
"(",
")",
")",
"x",
"=",
"HEADER_OFFSET_X",
"numColumns",
"=",
"self",
".",
"_owner",
".",
"GetColumnCount",
"(",
")",
"item",
"=",
"UltimateListItem",
"(",
")",
"renderer",
"=",
"wx",
".",
"RendererNative",
".",
"Get",
"(",
")",
"enabled",
"=",
"self",
".",
"GetParent",
"(",
")",
".",
"IsEnabled",
"(",
")",
"virtual",
"=",
"self",
".",
"_owner",
".",
"IsVirtual",
"(",
")",
"isFooter",
"=",
"self",
".",
"_isFooter",
"for",
"i",
"in",
"xrange",
"(",
"numColumns",
")",
":",
"# Reset anything in the dc that a custom renderer might have changed",
"dc",
".",
"SetTextForeground",
"(",
"self",
".",
"GetForegroundColour",
"(",
")",
")",
"if",
"x",
">=",
"w",
":",
"break",
"if",
"not",
"self",
".",
"IsColumnShown",
"(",
"i",
")",
":",
"continue",
"# do next column if not shown",
"item",
"=",
"self",
".",
"_owner",
".",
"GetColumn",
"(",
"i",
")",
"wCol",
"=",
"item",
".",
"_width",
"cw",
"=",
"wCol",
"ch",
"=",
"h",
"flags",
"=",
"0",
"if",
"not",
"enabled",
":",
"flags",
"|=",
"wx",
".",
"CONTROL_DISABLED",
"# NB: The code below is not really Mac-specific, but since we are close",
"# to 2.8 release and I don't have time to test on other platforms, I",
"# defined this only for wxMac. If this behavior is desired on",
"# other platforms, please go ahead and revise or remove the #ifdef.",
"if",
"\"__WXMAC__\"",
"in",
"wx",
".",
"PlatformInfo",
":",
"if",
"not",
"virtual",
"and",
"item",
".",
"_mask",
"&",
"ULC_MASK_STATE",
"and",
"item",
".",
"_state",
"&",
"ULC_STATE_SELECTED",
":",
"flags",
"|=",
"wx",
".",
"CONTROL_SELECTED",
"if",
"i",
"==",
"0",
":",
"flags",
"|=",
"wx",
".",
"CONTROL_SPECIAL",
"# mark as first column",
"if",
"i",
"==",
"self",
".",
"_currentColumn",
":",
"if",
"self",
".",
"_leftDown",
":",
"flags",
"|=",
"wx",
".",
"CONTROL_PRESSED",
"else",
":",
"if",
"self",
".",
"_enter",
":",
"flags",
"|=",
"wx",
".",
"CONTROL_CURRENT",
"# the width of the rect to draw: make it smaller to fit entirely",
"# inside the column rect",
"header_rect",
"=",
"wx",
".",
"Rect",
"(",
"x",
",",
"HEADER_OFFSET_Y",
"-",
"1",
",",
"cw",
",",
"ch",
")",
"if",
"self",
".",
"_headerCustomRenderer",
"!=",
"None",
":",
"self",
".",
"_headerCustomRenderer",
".",
"DrawHeaderButton",
"(",
"dc",
",",
"header_rect",
",",
"flags",
")",
"# The custom renderer will specify the color to draw the header text and buttons",
"dc",
".",
"SetTextForeground",
"(",
"self",
".",
"_headerCustomRenderer",
".",
"GetForegroundColour",
"(",
")",
")",
"elif",
"item",
".",
"_mask",
"&",
"ULC_MASK_RENDERER",
":",
"item",
".",
"GetCustomRenderer",
"(",
")",
".",
"DrawHeaderButton",
"(",
"dc",
",",
"header_rect",
",",
"flags",
")",
"# The custom renderer will specify the color to draw the header text and buttons",
"dc",
".",
"SetTextForeground",
"(",
"item",
".",
"GetCustomRenderer",
"(",
")",
".",
"GetForegroundColour",
"(",
")",
")",
"else",
":",
"renderer",
".",
"DrawHeaderButton",
"(",
"self",
",",
"dc",
",",
"header_rect",
",",
"flags",
")",
"# see if we have enough space for the column label",
"if",
"isFooter",
":",
"if",
"item",
".",
"GetFooterFont",
"(",
")",
".",
"IsOk",
"(",
")",
":",
"dc",
".",
"SetFont",
"(",
"item",
".",
"GetFooterFont",
"(",
")",
")",
"else",
":",
"dc",
".",
"SetFont",
"(",
"self",
".",
"GetFont",
"(",
")",
")",
"else",
":",
"if",
"item",
".",
"GetFont",
"(",
")",
".",
"IsOk",
"(",
")",
":",
"dc",
".",
"SetFont",
"(",
"item",
".",
"GetFont",
"(",
")",
")",
"else",
":",
"dc",
".",
"SetFont",
"(",
"self",
".",
"GetFont",
"(",
")",
")",
"wcheck",
"=",
"hcheck",
"=",
"0",
"kind",
"=",
"(",
"isFooter",
"and",
"[",
"item",
".",
"GetFooterKind",
"(",
")",
"]",
"or",
"[",
"item",
".",
"GetKind",
"(",
")",
"]",
")",
"[",
"0",
"]",
"checked",
"=",
"(",
"isFooter",
"and",
"[",
"item",
".",
"IsFooterChecked",
"(",
")",
"]",
"or",
"[",
"item",
".",
"IsChecked",
"(",
")",
"]",
")",
"[",
"0",
"]",
"if",
"kind",
"in",
"[",
"1",
",",
"2",
"]",
":",
"# We got a checkbox-type item",
"ix",
",",
"iy",
"=",
"self",
".",
"_owner",
".",
"GetCheckboxImageSize",
"(",
")",
"# We draw it on the left, always",
"self",
".",
"_owner",
".",
"DrawCheckbox",
"(",
"dc",
",",
"x",
"+",
"HEADER_OFFSET_X",
",",
"HEADER_OFFSET_Y",
"+",
"(",
"h",
"-",
"4",
"-",
"iy",
")",
"/",
"2",
",",
"kind",
",",
"checked",
",",
"enabled",
")",
"wcheck",
"+=",
"ix",
"+",
"HEADER_IMAGE_MARGIN_IN_REPORT_MODE",
"cw",
"-=",
"ix",
"+",
"HEADER_IMAGE_MARGIN_IN_REPORT_MODE",
"# for this we need the width of the text",
"text",
"=",
"(",
"isFooter",
"and",
"[",
"item",
".",
"GetFooterText",
"(",
")",
"]",
"or",
"[",
"item",
".",
"GetText",
"(",
")",
"]",
")",
"[",
"0",
"]",
"wLabel",
",",
"hLabel",
",",
"dummy",
"=",
"dc",
".",
"GetMultiLineTextExtent",
"(",
"text",
")",
"wLabel",
"+=",
"2",
"*",
"EXTRA_WIDTH",
"# and the width of the icon, if any",
"image",
"=",
"(",
"isFooter",
"and",
"[",
"item",
".",
"_footerImage",
"]",
"or",
"[",
"item",
".",
"_image",
"]",
")",
"[",
"0",
"]",
"if",
"image",
":",
"imageList",
"=",
"self",
".",
"_owner",
".",
"_small_image_list",
"if",
"imageList",
":",
"for",
"img",
"in",
"image",
":",
"if",
"img",
">=",
"0",
":",
"ix",
",",
"iy",
"=",
"imageList",
".",
"GetSize",
"(",
"img",
")",
"wLabel",
"+=",
"ix",
"+",
"HEADER_IMAGE_MARGIN_IN_REPORT_MODE",
"else",
":",
"imageList",
"=",
"None",
"# ignore alignment if there is not enough space anyhow",
"align",
"=",
"(",
"isFooter",
"and",
"[",
"item",
".",
"GetFooterAlign",
"(",
")",
"]",
"or",
"[",
"item",
".",
"GetAlign",
"(",
")",
"]",
")",
"[",
"0",
"]",
"align",
"=",
"(",
"wLabel",
"<",
"cw",
"and",
"[",
"align",
"]",
"or",
"[",
"ULC_FORMAT_LEFT",
"]",
")",
"[",
"0",
"]",
"if",
"align",
"==",
"ULC_FORMAT_LEFT",
":",
"xAligned",
"=",
"x",
"+",
"wcheck",
"elif",
"align",
"==",
"ULC_FORMAT_RIGHT",
":",
"xAligned",
"=",
"x",
"+",
"cw",
"-",
"wLabel",
"-",
"HEADER_OFFSET_X",
"elif",
"align",
"==",
"ULC_FORMAT_CENTER",
":",
"xAligned",
"=",
"x",
"+",
"wcheck",
"+",
"(",
"cw",
"-",
"wLabel",
")",
"/",
"2",
"# if we have an image, draw it on the right of the label",
"if",
"imageList",
":",
"for",
"indx",
",",
"img",
"in",
"enumerate",
"(",
"image",
")",
":",
"if",
"img",
">=",
"0",
":",
"imageList",
".",
"Draw",
"(",
"img",
",",
"dc",
",",
"xAligned",
"+",
"wLabel",
"-",
"(",
"ix",
"+",
"HEADER_IMAGE_MARGIN_IN_REPORT_MODE",
")",
"*",
"(",
"indx",
"+",
"1",
")",
",",
"HEADER_OFFSET_Y",
"+",
"(",
"h",
"-",
"4",
"-",
"iy",
")",
"/",
"2",
",",
"wx",
".",
"IMAGELIST_DRAW_TRANSPARENT",
")",
"cw",
"-=",
"ix",
"+",
"HEADER_IMAGE_MARGIN_IN_REPORT_MODE",
"# draw the text clipping it so that it doesn't overwrite the column",
"# boundary",
"dc",
".",
"SetClippingRegion",
"(",
"x",
",",
"HEADER_OFFSET_Y",
",",
"cw",
",",
"h",
"-",
"4",
")",
"self",
".",
"DrawTextFormatted",
"(",
"dc",
",",
"text",
",",
"wx",
".",
"Rect",
"(",
"xAligned",
"+",
"EXTRA_WIDTH",
",",
"HEADER_OFFSET_Y",
",",
"cw",
"-",
"EXTRA_WIDTH",
",",
"h",
"-",
"4",
")",
")",
"x",
"+=",
"wCol",
"dc",
".",
"DestroyClippingRegion",
"(",
")",
"# Fill in what's missing to the right of the columns, otherwise we will",
"# leave an unpainted area when columns are removed (and it looks better)",
"if",
"x",
"<",
"w",
":",
"header_rect",
"=",
"wx",
".",
"Rect",
"(",
"x",
",",
"HEADER_OFFSET_Y",
",",
"w",
"-",
"x",
",",
"h",
")",
"if",
"self",
".",
"_headerCustomRenderer",
"!=",
"None",
":",
"# Why does the custom renderer need this adjustment??",
"header_rect",
".",
"x",
"=",
"header_rect",
".",
"x",
"-",
"1",
"header_rect",
".",
"y",
"=",
"header_rect",
".",
"y",
"-",
"1",
"self",
".",
"_headerCustomRenderer",
".",
"DrawHeaderButton",
"(",
"dc",
",",
"header_rect",
",",
"wx",
".",
"CONTROL_DIRTY",
")",
"else",
":",
"renderer",
".",
"DrawHeaderButton",
"(",
"self",
",",
"dc",
",",
"header_rect",
",",
"wx",
".",
"CONTROL_DIRTY",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L5125-L5299 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/records.py | python | fromrecords | (recList, dtype=None, shape=None, formats=None, names=None,
titles=None, aligned=False, byteorder=None) | return res | create a recarray from a list of records in text form
The data in the same field can be heterogeneous, they will be promoted
to the highest data type. This method is intended for creating
smaller record arrays. If used to create large array without formats
defined
r=fromrecords([(2,3.,'abc')]*100000)
it can be slow.
If formats is None, then this will auto-detect formats. Use list of
tuples rather than list of lists for faster processing.
>>> r=np.core.records.fromrecords([(456,'dbe',1.2),(2,'de',1.3)],
... names='col1,col2,col3')
>>> print(r[0])
(456, 'dbe', 1.2)
>>> r.col1
array([456, 2])
>>> r.col2
array(['dbe', 'de'], dtype='<U3')
>>> import pickle
>>> pickle.loads(pickle.dumps(r))
rec.array([(456, 'dbe', 1.2), ( 2, 'de', 1.3)],
dtype=[('col1', '<i8'), ('col2', '<U3'), ('col3', '<f8')]) | create a recarray from a list of records in text form | [
"create",
"a",
"recarray",
"from",
"a",
"list",
"of",
"records",
"in",
"text",
"form"
] | def fromrecords(recList, dtype=None, shape=None, formats=None, names=None,
titles=None, aligned=False, byteorder=None):
""" create a recarray from a list of records in text form
The data in the same field can be heterogeneous, they will be promoted
to the highest data type. This method is intended for creating
smaller record arrays. If used to create large array without formats
defined
r=fromrecords([(2,3.,'abc')]*100000)
it can be slow.
If formats is None, then this will auto-detect formats. Use list of
tuples rather than list of lists for faster processing.
>>> r=np.core.records.fromrecords([(456,'dbe',1.2),(2,'de',1.3)],
... names='col1,col2,col3')
>>> print(r[0])
(456, 'dbe', 1.2)
>>> r.col1
array([456, 2])
>>> r.col2
array(['dbe', 'de'], dtype='<U3')
>>> import pickle
>>> pickle.loads(pickle.dumps(r))
rec.array([(456, 'dbe', 1.2), ( 2, 'de', 1.3)],
dtype=[('col1', '<i8'), ('col2', '<U3'), ('col3', '<f8')])
"""
if formats is None and dtype is None: # slower
obj = sb.array(recList, dtype=object)
arrlist = [sb.array(obj[..., i].tolist()) for i in range(obj.shape[-1])]
return fromarrays(arrlist, formats=formats, shape=shape, names=names,
titles=titles, aligned=aligned, byteorder=byteorder)
if dtype is not None:
descr = sb.dtype((record, dtype))
else:
descr = format_parser(formats, names, titles, aligned, byteorder)._descr
try:
retval = sb.array(recList, dtype=descr)
except (TypeError, ValueError):
if (shape is None or shape == 0):
shape = len(recList)
if isinstance(shape, (int, long)):
shape = (shape,)
if len(shape) > 1:
raise ValueError("Can only deal with 1-d array.")
_array = recarray(shape, descr)
for k in range(_array.size):
_array[k] = tuple(recList[k])
# list of lists instead of list of tuples ?
# 2018-02-07, 1.14.1
warnings.warn(
"fromrecords expected a list of tuples, may have received a list "
"of lists instead. In the future that will raise an error",
FutureWarning, stacklevel=2)
return _array
else:
if shape is not None and retval.shape != shape:
retval.shape = shape
res = retval.view(recarray)
return res | [
"def",
"fromrecords",
"(",
"recList",
",",
"dtype",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"formats",
"=",
"None",
",",
"names",
"=",
"None",
",",
"titles",
"=",
"None",
",",
"aligned",
"=",
"False",
",",
"byteorder",
"=",
"None",
")",
":",
"if",
"formats",
"is",
"None",
"and",
"dtype",
"is",
"None",
":",
"# slower",
"obj",
"=",
"sb",
".",
"array",
"(",
"recList",
",",
"dtype",
"=",
"object",
")",
"arrlist",
"=",
"[",
"sb",
".",
"array",
"(",
"obj",
"[",
"...",
",",
"i",
"]",
".",
"tolist",
"(",
")",
")",
"for",
"i",
"in",
"range",
"(",
"obj",
".",
"shape",
"[",
"-",
"1",
"]",
")",
"]",
"return",
"fromarrays",
"(",
"arrlist",
",",
"formats",
"=",
"formats",
",",
"shape",
"=",
"shape",
",",
"names",
"=",
"names",
",",
"titles",
"=",
"titles",
",",
"aligned",
"=",
"aligned",
",",
"byteorder",
"=",
"byteorder",
")",
"if",
"dtype",
"is",
"not",
"None",
":",
"descr",
"=",
"sb",
".",
"dtype",
"(",
"(",
"record",
",",
"dtype",
")",
")",
"else",
":",
"descr",
"=",
"format_parser",
"(",
"formats",
",",
"names",
",",
"titles",
",",
"aligned",
",",
"byteorder",
")",
".",
"_descr",
"try",
":",
"retval",
"=",
"sb",
".",
"array",
"(",
"recList",
",",
"dtype",
"=",
"descr",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"if",
"(",
"shape",
"is",
"None",
"or",
"shape",
"==",
"0",
")",
":",
"shape",
"=",
"len",
"(",
"recList",
")",
"if",
"isinstance",
"(",
"shape",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"shape",
"=",
"(",
"shape",
",",
")",
"if",
"len",
"(",
"shape",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"Can only deal with 1-d array.\"",
")",
"_array",
"=",
"recarray",
"(",
"shape",
",",
"descr",
")",
"for",
"k",
"in",
"range",
"(",
"_array",
".",
"size",
")",
":",
"_array",
"[",
"k",
"]",
"=",
"tuple",
"(",
"recList",
"[",
"k",
"]",
")",
"# list of lists instead of list of tuples ?",
"# 2018-02-07, 1.14.1",
"warnings",
".",
"warn",
"(",
"\"fromrecords expected a list of tuples, may have received a list \"",
"\"of lists instead. In the future that will raise an error\"",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"_array",
"else",
":",
"if",
"shape",
"is",
"not",
"None",
"and",
"retval",
".",
"shape",
"!=",
"shape",
":",
"retval",
".",
"shape",
"=",
"shape",
"res",
"=",
"retval",
".",
"view",
"(",
"recarray",
")",
"return",
"res"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/records.py#L648-L714 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | clang/bindings/python/clang/cindex.py | python | TokenGroup.get_tokens | (tu, extent) | Helper method to return all tokens in an extent.
This functionality is needed multiple places in this module. We define
it here because it seems like a logical place. | Helper method to return all tokens in an extent. | [
"Helper",
"method",
"to",
"return",
"all",
"tokens",
"in",
"an",
"extent",
"."
] | def get_tokens(tu, extent):
"""Helper method to return all tokens in an extent.
This functionality is needed multiple places in this module. We define
it here because it seems like a logical place.
"""
tokens_memory = POINTER(Token)()
tokens_count = c_uint()
conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
byref(tokens_count))
count = int(tokens_count.value)
# If we get no tokens, no memory was allocated. Be sure not to return
# anything and potentially call a destructor on nothing.
if count < 1:
return
tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
token_group = TokenGroup(tu, tokens_memory, tokens_count)
for i in range(0, count):
token = Token()
token.int_data = tokens_array[i].int_data
token.ptr_data = tokens_array[i].ptr_data
token._tu = tu
token._group = token_group
yield token | [
"def",
"get_tokens",
"(",
"tu",
",",
"extent",
")",
":",
"tokens_memory",
"=",
"POINTER",
"(",
"Token",
")",
"(",
")",
"tokens_count",
"=",
"c_uint",
"(",
")",
"conf",
".",
"lib",
".",
"clang_tokenize",
"(",
"tu",
",",
"extent",
",",
"byref",
"(",
"tokens_memory",
")",
",",
"byref",
"(",
"tokens_count",
")",
")",
"count",
"=",
"int",
"(",
"tokens_count",
".",
"value",
")",
"# If we get no tokens, no memory was allocated. Be sure not to return",
"# anything and potentially call a destructor on nothing.",
"if",
"count",
"<",
"1",
":",
"return",
"tokens_array",
"=",
"cast",
"(",
"tokens_memory",
",",
"POINTER",
"(",
"Token",
"*",
"count",
")",
")",
".",
"contents",
"token_group",
"=",
"TokenGroup",
"(",
"tu",
",",
"tokens_memory",
",",
"tokens_count",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"count",
")",
":",
"token",
"=",
"Token",
"(",
")",
"token",
".",
"int_data",
"=",
"tokens_array",
"[",
"i",
"]",
".",
"int_data",
"token",
".",
"ptr_data",
"=",
"tokens_array",
"[",
"i",
"]",
".",
"ptr_data",
"token",
".",
"_tu",
"=",
"tu",
"token",
".",
"_group",
"=",
"token_group",
"yield",
"token"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang/bindings/python/clang/cindex.py#L541-L571 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | build/pymake/pymake/globrelative.py | python | globpattern | (dir, pattern) | return leaves | Return leaf names in the specified directory which match the pattern. | Return leaf names in the specified directory which match the pattern. | [
"Return",
"leaf",
"names",
"in",
"the",
"specified",
"directory",
"which",
"match",
"the",
"pattern",
"."
] | def globpattern(dir, pattern):
"""
Return leaf names in the specified directory which match the pattern.
"""
if not hasglob(pattern):
if pattern == '':
if os.path.isdir(dir):
return ['']
return []
if os.path.exists(util.normaljoin(dir, pattern)):
return [pattern]
return []
leaves = os.listdir(dir) + ['.', '..']
# "hidden" filenames are a bit special
if not pattern.startswith('.'):
leaves = [leaf for leaf in leaves
if not leaf.startswith('.')]
leaves = fnmatch.filter(leaves, pattern)
leaves = filter(lambda l: os.path.exists(util.normaljoin(dir, l)), leaves)
leaves.sort()
return leaves | [
"def",
"globpattern",
"(",
"dir",
",",
"pattern",
")",
":",
"if",
"not",
"hasglob",
"(",
"pattern",
")",
":",
"if",
"pattern",
"==",
"''",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dir",
")",
":",
"return",
"[",
"''",
"]",
"return",
"[",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"util",
".",
"normaljoin",
"(",
"dir",
",",
"pattern",
")",
")",
":",
"return",
"[",
"pattern",
"]",
"return",
"[",
"]",
"leaves",
"=",
"os",
".",
"listdir",
"(",
"dir",
")",
"+",
"[",
"'.'",
",",
"'..'",
"]",
"# \"hidden\" filenames are a bit special",
"if",
"not",
"pattern",
".",
"startswith",
"(",
"'.'",
")",
":",
"leaves",
"=",
"[",
"leaf",
"for",
"leaf",
"in",
"leaves",
"if",
"not",
"leaf",
".",
"startswith",
"(",
"'.'",
")",
"]",
"leaves",
"=",
"fnmatch",
".",
"filter",
"(",
"leaves",
",",
"pattern",
")",
"leaves",
"=",
"filter",
"(",
"lambda",
"l",
":",
"os",
".",
"path",
".",
"exists",
"(",
"util",
".",
"normaljoin",
"(",
"dir",
",",
"l",
")",
")",
",",
"leaves",
")",
"leaves",
".",
"sort",
"(",
")",
"return",
"leaves"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/build/pymake/pymake/globrelative.py#L42-L68 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/slim/python/slim/learning.py | python | multiply_gradients | (grads_and_vars, gradient_multipliers) | return multiplied_grads_and_vars | Multiply specified gradients.
Args:
grads_and_vars: A list of gradient to variable pairs (tuples).
gradient_multipliers: A map from either `Variables` or `Variable` op names
to the coefficient by which the associated gradient should be scaled.
Returns:
The updated list of gradient to variable pairs.
Raises:
ValueError: If `grads_and_vars` is not a list or if `gradient_multipliers`
is empty or None or if `gradient_multipliers` is not a dictionary. | Multiply specified gradients. | [
"Multiply",
"specified",
"gradients",
"."
] | def multiply_gradients(grads_and_vars, gradient_multipliers):
"""Multiply specified gradients.
Args:
grads_and_vars: A list of gradient to variable pairs (tuples).
gradient_multipliers: A map from either `Variables` or `Variable` op names
to the coefficient by which the associated gradient should be scaled.
Returns:
The updated list of gradient to variable pairs.
Raises:
ValueError: If `grads_and_vars` is not a list or if `gradient_multipliers`
is empty or None or if `gradient_multipliers` is not a dictionary.
"""
if not isinstance(grads_and_vars, list):
raise ValueError('`grads_and_vars` must be a list.')
if not gradient_multipliers:
raise ValueError('`gradient_multipliers` is empty.')
if not isinstance(gradient_multipliers, dict):
raise ValueError('`gradient_multipliers` must be a dict.')
multiplied_grads_and_vars = []
for grad, var in grads_and_vars:
if var in gradient_multipliers or var.op.name in gradient_multipliers:
key = var if var in gradient_multipliers else var.op.name
if grad is None:
raise ValueError('Requested multiple of `None` gradient.')
if isinstance(grad, ops.IndexedSlices):
tmp = grad.values * constant_op.constant(gradient_multipliers[key],
dtype=grad.dtype)
grad = ops.IndexedSlices(tmp, grad.indices, grad.dense_shape)
else:
grad *= constant_op.constant(gradient_multipliers[key],
dtype=grad.dtype)
multiplied_grads_and_vars.append((grad, var))
return multiplied_grads_and_vars | [
"def",
"multiply_gradients",
"(",
"grads_and_vars",
",",
"gradient_multipliers",
")",
":",
"if",
"not",
"isinstance",
"(",
"grads_and_vars",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"'`grads_and_vars` must be a list.'",
")",
"if",
"not",
"gradient_multipliers",
":",
"raise",
"ValueError",
"(",
"'`gradient_multipliers` is empty.'",
")",
"if",
"not",
"isinstance",
"(",
"gradient_multipliers",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'`gradient_multipliers` must be a dict.'",
")",
"multiplied_grads_and_vars",
"=",
"[",
"]",
"for",
"grad",
",",
"var",
"in",
"grads_and_vars",
":",
"if",
"var",
"in",
"gradient_multipliers",
"or",
"var",
".",
"op",
".",
"name",
"in",
"gradient_multipliers",
":",
"key",
"=",
"var",
"if",
"var",
"in",
"gradient_multipliers",
"else",
"var",
".",
"op",
".",
"name",
"if",
"grad",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Requested multiple of `None` gradient.'",
")",
"if",
"isinstance",
"(",
"grad",
",",
"ops",
".",
"IndexedSlices",
")",
":",
"tmp",
"=",
"grad",
".",
"values",
"*",
"constant_op",
".",
"constant",
"(",
"gradient_multipliers",
"[",
"key",
"]",
",",
"dtype",
"=",
"grad",
".",
"dtype",
")",
"grad",
"=",
"ops",
".",
"IndexedSlices",
"(",
"tmp",
",",
"grad",
".",
"indices",
",",
"grad",
".",
"dense_shape",
")",
"else",
":",
"grad",
"*=",
"constant_op",
".",
"constant",
"(",
"gradient_multipliers",
"[",
"key",
"]",
",",
"dtype",
"=",
"grad",
".",
"dtype",
")",
"multiplied_grads_and_vars",
".",
"append",
"(",
"(",
"grad",
",",
"var",
")",
")",
"return",
"multiplied_grads_and_vars"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/slim/python/slim/learning.py#L302-L339 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/pyserial/serial/serialposix.py | python | PosixSerial.getRI | (self) | return struct.unpack('I',s)[0] & TIOCM_RI != 0 | Read terminal status line: Ring Indicator | Read terminal status line: Ring Indicator | [
"Read",
"terminal",
"status",
"line",
":",
"Ring",
"Indicator"
] | def getRI(self):
"""Read terminal status line: Ring Indicator"""
if not self._isOpen: raise portNotOpenError
s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
return struct.unpack('I',s)[0] & TIOCM_RI != 0 | [
"def",
"getRI",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_isOpen",
":",
"raise",
"portNotOpenError",
"s",
"=",
"fcntl",
".",
"ioctl",
"(",
"self",
".",
"fd",
",",
"TIOCMGET",
",",
"TIOCM_zero_str",
")",
"return",
"struct",
".",
"unpack",
"(",
"'I'",
",",
"s",
")",
"[",
"0",
"]",
"&",
"TIOCM_RI",
"!=",
"0"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/serialposix.py#L578-L582 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/object_detector/util/_output_formats.py | python | unstack_annotations | (annotations_sframe, num_rows=None) | return annotations_sarray | Converts object detection annotations (ground truth or predictions) to
unstacked format (an `SArray` where each element is a list of object
instances).
Parameters
----------
annotations_sframe: SFrame
An `SFrame` with stacked predictions, produced by the
`stack_annotations` function.
num_rows: int
Optionally specify the number of rows in your original dataset, so that
all get represented in the unstacked format, regardless of whether or
not they had instances or not.
Returns
-------
annotations_sarray: An `SArray` with unstacked annotations.
See also
--------
stack_annotations
Examples
--------
If you have annotations in stacked format:
>>> stacked_predictions
Data:
+--------+------------+-------+-------+-------+-------+--------+
| row_id | confidence | label | x | y | width | height |
+--------+------------+-------+-------+-------+-------+--------+
| 0 | 0.98 | dog | 123.0 | 128.0 | 80.0 | 182.0 |
| 0 | 0.67 | cat | 150.0 | 183.0 | 129.0 | 101.0 |
| 1 | 0.8 | dog | 50.0 | 432.0 | 65.0 | 98.0 |
+--------+------------+-------+-------+-------+-------+--------+
[3 rows x 7 columns]
They can be converted to unstacked format using this function:
>>> turicreate.object_detector.util.unstack_annotations(stacked_predictions)[0]
[{'confidence': 0.98,
'coordinates': {'height': 182.0, 'width': 80.0, 'x': 123.0, 'y': 128.0},
'label': 'dog',
'type': 'rectangle'},
{'confidence': 0.67,
'coordinates': {'height': 101.0, 'width': 129.0, 'x': 150.0, 'y': 183.0},
'label': 'cat',
'type': 'rectangle'}] | Converts object detection annotations (ground truth or predictions) to
unstacked format (an `SArray` where each element is a list of object
instances). | [
"Converts",
"object",
"detection",
"annotations",
"(",
"ground",
"truth",
"or",
"predictions",
")",
"to",
"unstacked",
"format",
"(",
"an",
"SArray",
"where",
"each",
"element",
"is",
"a",
"list",
"of",
"object",
"instances",
")",
"."
] | def unstack_annotations(annotations_sframe, num_rows=None):
"""
Converts object detection annotations (ground truth or predictions) to
unstacked format (an `SArray` where each element is a list of object
instances).
Parameters
----------
annotations_sframe: SFrame
An `SFrame` with stacked predictions, produced by the
`stack_annotations` function.
num_rows: int
Optionally specify the number of rows in your original dataset, so that
all get represented in the unstacked format, regardless of whether or
not they had instances or not.
Returns
-------
annotations_sarray: An `SArray` with unstacked annotations.
See also
--------
stack_annotations
Examples
--------
If you have annotations in stacked format:
>>> stacked_predictions
Data:
+--------+------------+-------+-------+-------+-------+--------+
| row_id | confidence | label | x | y | width | height |
+--------+------------+-------+-------+-------+-------+--------+
| 0 | 0.98 | dog | 123.0 | 128.0 | 80.0 | 182.0 |
| 0 | 0.67 | cat | 150.0 | 183.0 | 129.0 | 101.0 |
| 1 | 0.8 | dog | 50.0 | 432.0 | 65.0 | 98.0 |
+--------+------------+-------+-------+-------+-------+--------+
[3 rows x 7 columns]
They can be converted to unstacked format using this function:
>>> turicreate.object_detector.util.unstack_annotations(stacked_predictions)[0]
[{'confidence': 0.98,
'coordinates': {'height': 182.0, 'width': 80.0, 'x': 123.0, 'y': 128.0},
'label': 'dog',
'type': 'rectangle'},
{'confidence': 0.67,
'coordinates': {'height': 101.0, 'width': 129.0, 'x': 150.0, 'y': 183.0},
'label': 'cat',
'type': 'rectangle'}]
"""
_raise_error_if_not_sframe(annotations_sframe, variable_name="annotations_sframe")
cols = ["label", "type", "coordinates"]
has_confidence = "confidence" in annotations_sframe.column_names()
if has_confidence:
cols.append("confidence")
if num_rows is None:
if len(annotations_sframe) == 0:
num_rows = 0
else:
num_rows = annotations_sframe["row_id"].max() + 1
sf = annotations_sframe
sf["type"] = "rectangle"
sf = sf.pack_columns(
["x", "y", "width", "height"], dtype=dict, new_column_name="coordinates"
)
sf = sf.pack_columns(cols, dtype=dict, new_column_name="ann")
sf = sf.unstack("ann", new_column_name="annotations")
sf_all_ids = _tc.SFrame({"row_id": range(num_rows)})
sf = sf.join(sf_all_ids, on="row_id", how="right")
sf = sf.fillna("annotations", [])
sf = sf.sort("row_id")
annotations_sarray = sf["annotations"]
# Sort the confidences again, since the unstack does not preserve the order
if has_confidence:
annotations_sarray = annotations_sarray.apply(
lambda x: sorted(x, key=lambda ann: ann["confidence"], reverse=True),
dtype=list,
)
return annotations_sarray | [
"def",
"unstack_annotations",
"(",
"annotations_sframe",
",",
"num_rows",
"=",
"None",
")",
":",
"_raise_error_if_not_sframe",
"(",
"annotations_sframe",
",",
"variable_name",
"=",
"\"annotations_sframe\"",
")",
"cols",
"=",
"[",
"\"label\"",
",",
"\"type\"",
",",
"\"coordinates\"",
"]",
"has_confidence",
"=",
"\"confidence\"",
"in",
"annotations_sframe",
".",
"column_names",
"(",
")",
"if",
"has_confidence",
":",
"cols",
".",
"append",
"(",
"\"confidence\"",
")",
"if",
"num_rows",
"is",
"None",
":",
"if",
"len",
"(",
"annotations_sframe",
")",
"==",
"0",
":",
"num_rows",
"=",
"0",
"else",
":",
"num_rows",
"=",
"annotations_sframe",
"[",
"\"row_id\"",
"]",
".",
"max",
"(",
")",
"+",
"1",
"sf",
"=",
"annotations_sframe",
"sf",
"[",
"\"type\"",
"]",
"=",
"\"rectangle\"",
"sf",
"=",
"sf",
".",
"pack_columns",
"(",
"[",
"\"x\"",
",",
"\"y\"",
",",
"\"width\"",
",",
"\"height\"",
"]",
",",
"dtype",
"=",
"dict",
",",
"new_column_name",
"=",
"\"coordinates\"",
")",
"sf",
"=",
"sf",
".",
"pack_columns",
"(",
"cols",
",",
"dtype",
"=",
"dict",
",",
"new_column_name",
"=",
"\"ann\"",
")",
"sf",
"=",
"sf",
".",
"unstack",
"(",
"\"ann\"",
",",
"new_column_name",
"=",
"\"annotations\"",
")",
"sf_all_ids",
"=",
"_tc",
".",
"SFrame",
"(",
"{",
"\"row_id\"",
":",
"range",
"(",
"num_rows",
")",
"}",
")",
"sf",
"=",
"sf",
".",
"join",
"(",
"sf_all_ids",
",",
"on",
"=",
"\"row_id\"",
",",
"how",
"=",
"\"right\"",
")",
"sf",
"=",
"sf",
".",
"fillna",
"(",
"\"annotations\"",
",",
"[",
"]",
")",
"sf",
"=",
"sf",
".",
"sort",
"(",
"\"row_id\"",
")",
"annotations_sarray",
"=",
"sf",
"[",
"\"annotations\"",
"]",
"# Sort the confidences again, since the unstack does not preserve the order",
"if",
"has_confidence",
":",
"annotations_sarray",
"=",
"annotations_sarray",
".",
"apply",
"(",
"lambda",
"x",
":",
"sorted",
"(",
"x",
",",
"key",
"=",
"lambda",
"ann",
":",
"ann",
"[",
"\"confidence\"",
"]",
",",
"reverse",
"=",
"True",
")",
",",
"dtype",
"=",
"list",
",",
")",
"return",
"annotations_sarray"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/object_detector/util/_output_formats.py#L68-L152 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/overrides.py | python | _get_overloaded_args | (relevant_args: Iterable[Any]) | return overloaded_args | Returns a list of arguments on which to call __torch_function__.
Checks arguments in relevant_args for __torch_function__ implementations,
storing references to the arguments and their types in overloaded_args and
overloaded_types in order of calling precedence. Only distinct types are
considered. If a type is a subclass of another type it will have higher
precedence, otherwise the precedence order is the same as the order of
arguments in relevant_args, that is, from left-to-right in the argument list.
The precedence-determining algorithm implemented in this function is
described in `NEP-0018`_.
See torch::append_overloaded_arg for the equivalent function in the C++
implementation.
Parameters
----------
relevant_args : iterable of array-like
Iterable of array-like arguments to check for __torch_function__
methods.
Returns
-------
overloaded_args : list
Arguments from relevant_args on which to call __torch_function__
methods, in the order in which they should be called.
.. _NEP-0018:
https://numpy.org/neps/nep-0018-array-function-protocol.html | Returns a list of arguments on which to call __torch_function__. | [
"Returns",
"a",
"list",
"of",
"arguments",
"on",
"which",
"to",
"call",
"__torch_function__",
"."
] | def _get_overloaded_args(relevant_args: Iterable[Any]) -> List[Any]:
"""Returns a list of arguments on which to call __torch_function__.
Checks arguments in relevant_args for __torch_function__ implementations,
storing references to the arguments and their types in overloaded_args and
overloaded_types in order of calling precedence. Only distinct types are
considered. If a type is a subclass of another type it will have higher
precedence, otherwise the precedence order is the same as the order of
arguments in relevant_args, that is, from left-to-right in the argument list.
The precedence-determining algorithm implemented in this function is
described in `NEP-0018`_.
See torch::append_overloaded_arg for the equivalent function in the C++
implementation.
Parameters
----------
relevant_args : iterable of array-like
Iterable of array-like arguments to check for __torch_function__
methods.
Returns
-------
overloaded_args : list
Arguments from relevant_args on which to call __torch_function__
methods, in the order in which they should be called.
.. _NEP-0018:
https://numpy.org/neps/nep-0018-array-function-protocol.html
"""
# Runtime is O(num_arguments * num_unique_types)
overloaded_types: Set[Type] = set()
overloaded_args: List[Any] = []
for arg in relevant_args:
arg_type = type(arg)
# We only collect arguments if they have a unique type, which ensures
# reasonable performance even with a long list of possibly overloaded
# arguments.
#
# NB: Important to exclude _disabled_torch_function_impl, otherwise
# https://github.com/pytorch/pytorch/issues/64687
if (arg_type not in overloaded_types and hasattr(arg_type, '__torch_function__') and
arg_type.__torch_function__ != torch._C._disabled_torch_function_impl):
# Create lists explicitly for the first type (usually the only one
# done) to avoid setting up the iterator for overloaded_args.
if overloaded_types:
overloaded_types.add(arg_type)
# By default, insert argument at the end, but if it is
# subclass of another argument, insert it before that argument.
# This ensures "subclasses before superclasses".
index = len(overloaded_args)
for i, old_arg in enumerate(overloaded_args):
if issubclass(arg_type, type(old_arg)):
index = i
break
overloaded_args.insert(index, arg)
else:
overloaded_types = {arg_type}
overloaded_args = [arg]
return overloaded_args | [
"def",
"_get_overloaded_args",
"(",
"relevant_args",
":",
"Iterable",
"[",
"Any",
"]",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"# Runtime is O(num_arguments * num_unique_types)",
"overloaded_types",
":",
"Set",
"[",
"Type",
"]",
"=",
"set",
"(",
")",
"overloaded_args",
":",
"List",
"[",
"Any",
"]",
"=",
"[",
"]",
"for",
"arg",
"in",
"relevant_args",
":",
"arg_type",
"=",
"type",
"(",
"arg",
")",
"# We only collect arguments if they have a unique type, which ensures",
"# reasonable performance even with a long list of possibly overloaded",
"# arguments.",
"#",
"# NB: Important to exclude _disabled_torch_function_impl, otherwise",
"# https://github.com/pytorch/pytorch/issues/64687",
"if",
"(",
"arg_type",
"not",
"in",
"overloaded_types",
"and",
"hasattr",
"(",
"arg_type",
",",
"'__torch_function__'",
")",
"and",
"arg_type",
".",
"__torch_function__",
"!=",
"torch",
".",
"_C",
".",
"_disabled_torch_function_impl",
")",
":",
"# Create lists explicitly for the first type (usually the only one",
"# done) to avoid setting up the iterator for overloaded_args.",
"if",
"overloaded_types",
":",
"overloaded_types",
".",
"add",
"(",
"arg_type",
")",
"# By default, insert argument at the end, but if it is",
"# subclass of another argument, insert it before that argument.",
"# This ensures \"subclasses before superclasses\".",
"index",
"=",
"len",
"(",
"overloaded_args",
")",
"for",
"i",
",",
"old_arg",
"in",
"enumerate",
"(",
"overloaded_args",
")",
":",
"if",
"issubclass",
"(",
"arg_type",
",",
"type",
"(",
"old_arg",
")",
")",
":",
"index",
"=",
"i",
"break",
"overloaded_args",
".",
"insert",
"(",
"index",
",",
"arg",
")",
"else",
":",
"overloaded_types",
"=",
"{",
"arg_type",
"}",
"overloaded_args",
"=",
"[",
"arg",
"]",
"return",
"overloaded_args"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/overrides.py#L1277-L1337 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/stats/_multivariate.py | python | multivariate_normal_gen.entropy | (self, mean=None, cov=1) | return 0.5 * logdet | Compute the differential entropy of the multivariate normal.
Parameters
----------
%(_mvn_doc_default_callparams)s
Returns
-------
h : scalar
Entropy of the multivariate normal distribution
Notes
-----
%(_mvn_doc_callparams_note)s | Compute the differential entropy of the multivariate normal. | [
"Compute",
"the",
"differential",
"entropy",
"of",
"the",
"multivariate",
"normal",
"."
] | def entropy(self, mean=None, cov=1):
"""
Compute the differential entropy of the multivariate normal.
Parameters
----------
%(_mvn_doc_default_callparams)s
Returns
-------
h : scalar
Entropy of the multivariate normal distribution
Notes
-----
%(_mvn_doc_callparams_note)s
"""
dim, mean, cov = self._process_parameters(None, mean, cov)
_, logdet = np.linalg.slogdet(2 * np.pi * np.e * cov)
return 0.5 * logdet | [
"def",
"entropy",
"(",
"self",
",",
"mean",
"=",
"None",
",",
"cov",
"=",
"1",
")",
":",
"dim",
",",
"mean",
",",
"cov",
"=",
"self",
".",
"_process_parameters",
"(",
"None",
",",
"mean",
",",
"cov",
")",
"_",
",",
"logdet",
"=",
"np",
".",
"linalg",
".",
"slogdet",
"(",
"2",
"*",
"np",
".",
"pi",
"*",
"np",
".",
"e",
"*",
"cov",
")",
"return",
"0.5",
"*",
"logdet"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/_multivariate.py#L663-L683 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/vpc/__init__.py | python | VPCConnection.associate_dhcp_options | (self, dhcp_options_id, vpc_id, dry_run=False) | return self.get_status('AssociateDhcpOptions', params) | Associate a set of Dhcp Options with a VPC.
:type dhcp_options_id: str
:param dhcp_options_id: The ID of the Dhcp Options
:type vpc_id: str
:param vpc_id: The ID of the VPC.
:type dry_run: bool
:param dry_run: Set to True if the operation should not actually run.
:rtype: bool
:return: True if successful | Associate a set of Dhcp Options with a VPC. | [
"Associate",
"a",
"set",
"of",
"Dhcp",
"Options",
"with",
"a",
"VPC",
"."
] | def associate_dhcp_options(self, dhcp_options_id, vpc_id, dry_run=False):
"""
Associate a set of Dhcp Options with a VPC.
:type dhcp_options_id: str
:param dhcp_options_id: The ID of the Dhcp Options
:type vpc_id: str
:param vpc_id: The ID of the VPC.
:type dry_run: bool
:param dry_run: Set to True if the operation should not actually run.
:rtype: bool
:return: True if successful
"""
params = {'DhcpOptionsId': dhcp_options_id,
'VpcId': vpc_id}
if dry_run:
params['DryRun'] = 'true'
return self.get_status('AssociateDhcpOptions', params) | [
"def",
"associate_dhcp_options",
"(",
"self",
",",
"dhcp_options_id",
",",
"vpc_id",
",",
"dry_run",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'DhcpOptionsId'",
":",
"dhcp_options_id",
",",
"'VpcId'",
":",
"vpc_id",
"}",
"if",
"dry_run",
":",
"params",
"[",
"'DryRun'",
"]",
"=",
"'true'",
"return",
"self",
".",
"get_status",
"(",
"'AssociateDhcpOptions'",
",",
"params",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/vpc/__init__.py#L1322-L1342 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/Input/JsonData.py | python | JsonData.toPickle | (self) | return {"app_path": self.app_path,
"json_data": self.json_data,
} | Return a dict that can be pickled | Return a dict that can be pickled | [
"Return",
"a",
"dict",
"that",
"can",
"be",
"pickled"
] | def toPickle(self):
"""
Return a dict that can be pickled
"""
return {"app_path": self.app_path,
"json_data": self.json_data,
} | [
"def",
"toPickle",
"(",
"self",
")",
":",
"return",
"{",
"\"app_path\"",
":",
"self",
".",
"app_path",
",",
"\"json_data\"",
":",
"self",
".",
"json_data",
",",
"}"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/JsonData.py#L73-L79 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | DirPickerCtrl.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=-1, String path=EmptyString,
String message=DirSelectorPromptStr, Point pos=DefaultPosition,
Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=DirPickerCtrlNameStr) -> DirPickerCtrl | __init__(self, Window parent, int id=-1, String path=EmptyString,
String message=DirSelectorPromptStr, Point pos=DefaultPosition,
Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=DirPickerCtrlNameStr) -> DirPickerCtrl | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"String",
"path",
"=",
"EmptyString",
"String",
"message",
"=",
"DirSelectorPromptStr",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"DIRP_DEFAULT_STYLE",
"Validator",
"validator",
"=",
"DefaultValidator",
"String",
"name",
"=",
"DirPickerCtrlNameStr",
")",
"-",
">",
"DirPickerCtrl"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, String path=EmptyString,
String message=DirSelectorPromptStr, Point pos=DefaultPosition,
Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE,
Validator validator=DefaultValidator,
String name=DirPickerCtrlNameStr) -> DirPickerCtrl
"""
_controls_.DirPickerCtrl_swiginit(self,_controls_.new_DirPickerCtrl(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_controls_",
".",
"DirPickerCtrl_swiginit",
"(",
"self",
",",
"_controls_",
".",
"new_DirPickerCtrl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_setOORInfo",
"(",
"self",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L7154-L7163 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aquabutton.py | python | __ToggleMixin.OnKeyUp | (self, event) | Handles the ``wx.EVT_KEY_UP`` event for :class:`AquaButton` when used as toggle button.
:param `event`: a :class:`KeyEvent` event to be processed. | Handles the ``wx.EVT_KEY_UP`` event for :class:`AquaButton` when used as toggle button. | [
"Handles",
"the",
"wx",
".",
"EVT_KEY_UP",
"event",
"for",
":",
"class",
":",
"AquaButton",
"when",
"used",
"as",
"toggle",
"button",
"."
] | def OnKeyUp(self, event):
"""
Handles the ``wx.EVT_KEY_UP`` event for :class:`AquaButton` when used as toggle button.
:param `event`: a :class:`KeyEvent` event to be processed.
"""
if self.hasFocus and event.GetKeyCode() == ord(" "):
self.up = not self.up
self.Notify()
self.Refresh()
event.Skip() | [
"def",
"OnKeyUp",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"hasFocus",
"and",
"event",
".",
"GetKeyCode",
"(",
")",
"==",
"ord",
"(",
"\" \"",
")",
":",
"self",
".",
"up",
"=",
"not",
"self",
".",
"up",
"self",
".",
"Notify",
"(",
")",
"self",
".",
"Refresh",
"(",
")",
"event",
".",
"Skip",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aquabutton.py#L967-L979 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/mongosymb.py | python | make_argument_parser | (parser=None, **kwargs) | return parser | Make and return an argparse. | Make and return an argparse. | [
"Make",
"and",
"return",
"an",
"argparse",
"."
] | def make_argument_parser(parser=None, **kwargs):
"""Make and return an argparse."""
if parser is None:
parser = argparse.ArgumentParser(**kwargs)
parser.add_argument('--dsym-hint', default=[], action='append')
parser.add_argument('--symbolizer-path', default='')
parser.add_argument('--input-format', choices=['classic', 'thin'], default='classic')
parser.add_argument('--output-format', choices=['classic', 'json'], default='classic',
help='"json" shows some extra information')
parser.add_argument('--debug-file-resolver', choices=['path', 's3', 'pr'], default='pr')
parser.add_argument('--src-dir-to-move', action="store", type=str, default=None,
help="Specify a src dir to move to /data/mci/{original_buildid}/src")
parser.add_argument('--live', action='store_true')
s3_group = parser.add_argument_group(
"s3 options", description='Options used with \'--debug-file-resolver s3\'')
s3_group.add_argument('--s3-cache-dir')
s3_group.add_argument('--s3-bucket')
pr_group = parser.add_argument_group(
'Path Resolver options (Path Resolver uses a special web service to retrieve URL of debug symbols file for '
'a given BuildID), we use "pr" as a shorter/easier name for this',
description='Options used with \'--debug-file-resolver pr\'')
pr_group.add_argument('--pr-host', default='',
help='URL of web service running the API to get debug symbol URL')
pr_group.add_argument('--pr-cache-dir', default='',
help='Full path to a directory to store cache/files')
# caching mechanism is currently not fully developed and needs more advanced cleaning techniques, we add an option
# to enable it after completing the implementation
# Look for symbols in the cwd by default.
parser.add_argument('path_to_executable', nargs="?")
return parser | [
"def",
"make_argument_parser",
"(",
"parser",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"parser",
"is",
"None",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"*",
"*",
"kwargs",
")",
"parser",
".",
"add_argument",
"(",
"'--dsym-hint'",
",",
"default",
"=",
"[",
"]",
",",
"action",
"=",
"'append'",
")",
"parser",
".",
"add_argument",
"(",
"'--symbolizer-path'",
",",
"default",
"=",
"''",
")",
"parser",
".",
"add_argument",
"(",
"'--input-format'",
",",
"choices",
"=",
"[",
"'classic'",
",",
"'thin'",
"]",
",",
"default",
"=",
"'classic'",
")",
"parser",
".",
"add_argument",
"(",
"'--output-format'",
",",
"choices",
"=",
"[",
"'classic'",
",",
"'json'",
"]",
",",
"default",
"=",
"'classic'",
",",
"help",
"=",
"'\"json\" shows some extra information'",
")",
"parser",
".",
"add_argument",
"(",
"'--debug-file-resolver'",
",",
"choices",
"=",
"[",
"'path'",
",",
"'s3'",
",",
"'pr'",
"]",
",",
"default",
"=",
"'pr'",
")",
"parser",
".",
"add_argument",
"(",
"'--src-dir-to-move'",
",",
"action",
"=",
"\"store\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"None",
",",
"help",
"=",
"\"Specify a src dir to move to /data/mci/{original_buildid}/src\"",
")",
"parser",
".",
"add_argument",
"(",
"'--live'",
",",
"action",
"=",
"'store_true'",
")",
"s3_group",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"s3 options\"",
",",
"description",
"=",
"'Options used with \\'--debug-file-resolver s3\\''",
")",
"s3_group",
".",
"add_argument",
"(",
"'--s3-cache-dir'",
")",
"s3_group",
".",
"add_argument",
"(",
"'--s3-bucket'",
")",
"pr_group",
"=",
"parser",
".",
"add_argument_group",
"(",
"'Path Resolver options (Path Resolver uses a special web service to retrieve URL of debug symbols file for '",
"'a given BuildID), we use \"pr\" as a shorter/easier name for this'",
",",
"description",
"=",
"'Options used with \\'--debug-file-resolver pr\\''",
")",
"pr_group",
".",
"add_argument",
"(",
"'--pr-host'",
",",
"default",
"=",
"''",
",",
"help",
"=",
"'URL of web service running the API to get debug symbol URL'",
")",
"pr_group",
".",
"add_argument",
"(",
"'--pr-cache-dir'",
",",
"default",
"=",
"''",
",",
"help",
"=",
"'Full path to a directory to store cache/files'",
")",
"# caching mechanism is currently not fully developed and needs more advanced cleaning techniques, we add an option",
"# to enable it after completing the implementation",
"# Look for symbols in the cwd by default.",
"parser",
".",
"add_argument",
"(",
"'path_to_executable'",
",",
"nargs",
"=",
"\"?\"",
")",
"return",
"parser"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/mongosymb.py#L506-L539 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros/roslib/src/roslib/rospack.py | python | rospack_depends_1 | (pkg) | return rospackexec(['deps1', pkg]).split() | @param pkg: package name
@type pkg: str
@return: A list of the names of the packages which pkg directly depends on
@rtype: list | [] | def rospack_depends_1(pkg):
"""
@param pkg: package name
@type pkg: str
@return: A list of the names of the packages which pkg directly depends on
@rtype: list
"""
return rospackexec(['deps1', pkg]).split() | [
"def",
"rospack_depends_1",
"(",
"pkg",
")",
":",
"return",
"rospackexec",
"(",
"[",
"'deps1'",
",",
"pkg",
"]",
")",
".",
"split",
"(",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/roslib/src/roslib/rospack.py#L90-L97 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/arrays/period.py | python | PeriodArray._check_timedeltalike_freq_compat | (self, other) | Arithmetic operations with timedelta-like scalars or array `other`
are only valid if `other` is an integer multiple of `self.freq`.
If the operation is valid, find that integer multiple. Otherwise,
raise because the operation is invalid.
Parameters
----------
other : timedelta, np.timedelta64, Tick,
ndarray[timedelta64], TimedeltaArray, TimedeltaIndex
Returns
-------
multiple : int or ndarray[int64]
Raises
------
IncompatibleFrequency | Arithmetic operations with timedelta-like scalars or array `other`
are only valid if `other` is an integer multiple of `self.freq`.
If the operation is valid, find that integer multiple. Otherwise,
raise because the operation is invalid. | [
"Arithmetic",
"operations",
"with",
"timedelta",
"-",
"like",
"scalars",
"or",
"array",
"other",
"are",
"only",
"valid",
"if",
"other",
"is",
"an",
"integer",
"multiple",
"of",
"self",
".",
"freq",
".",
"If",
"the",
"operation",
"is",
"valid",
"find",
"that",
"integer",
"multiple",
".",
"Otherwise",
"raise",
"because",
"the",
"operation",
"is",
"invalid",
"."
] | def _check_timedeltalike_freq_compat(self, other):
"""
Arithmetic operations with timedelta-like scalars or array `other`
are only valid if `other` is an integer multiple of `self.freq`.
If the operation is valid, find that integer multiple. Otherwise,
raise because the operation is invalid.
Parameters
----------
other : timedelta, np.timedelta64, Tick,
ndarray[timedelta64], TimedeltaArray, TimedeltaIndex
Returns
-------
multiple : int or ndarray[int64]
Raises
------
IncompatibleFrequency
"""
assert isinstance(self.freq, Tick) # checked by calling function
own_offset = frequencies.to_offset(self.freq.rule_code)
base_nanos = delta_to_nanoseconds(own_offset)
if isinstance(other, (timedelta, np.timedelta64, Tick)):
nanos = delta_to_nanoseconds(other)
elif isinstance(other, np.ndarray):
# numpy timedelta64 array; all entries must be compatible
assert other.dtype.kind == 'm'
if other.dtype != _TD_DTYPE:
# i.e. non-nano unit
# TODO: disallow unit-less timedelta64
other = other.astype(_TD_DTYPE)
nanos = other.view('i8')
else:
# TimedeltaArray/Index
nanos = other.asi8
if np.all(nanos % base_nanos == 0):
# nanos being added is an integer multiple of the
# base-frequency to self.freq
delta = nanos // base_nanos
# delta is the integer (or integer-array) number of periods
# by which will be added to self.
return delta
_raise_on_incompatible(self, other) | [
"def",
"_check_timedeltalike_freq_compat",
"(",
"self",
",",
"other",
")",
":",
"assert",
"isinstance",
"(",
"self",
".",
"freq",
",",
"Tick",
")",
"# checked by calling function",
"own_offset",
"=",
"frequencies",
".",
"to_offset",
"(",
"self",
".",
"freq",
".",
"rule_code",
")",
"base_nanos",
"=",
"delta_to_nanoseconds",
"(",
"own_offset",
")",
"if",
"isinstance",
"(",
"other",
",",
"(",
"timedelta",
",",
"np",
".",
"timedelta64",
",",
"Tick",
")",
")",
":",
"nanos",
"=",
"delta_to_nanoseconds",
"(",
"other",
")",
"elif",
"isinstance",
"(",
"other",
",",
"np",
".",
"ndarray",
")",
":",
"# numpy timedelta64 array; all entries must be compatible",
"assert",
"other",
".",
"dtype",
".",
"kind",
"==",
"'m'",
"if",
"other",
".",
"dtype",
"!=",
"_TD_DTYPE",
":",
"# i.e. non-nano unit",
"# TODO: disallow unit-less timedelta64",
"other",
"=",
"other",
".",
"astype",
"(",
"_TD_DTYPE",
")",
"nanos",
"=",
"other",
".",
"view",
"(",
"'i8'",
")",
"else",
":",
"# TimedeltaArray/Index",
"nanos",
"=",
"other",
".",
"asi8",
"if",
"np",
".",
"all",
"(",
"nanos",
"%",
"base_nanos",
"==",
"0",
")",
":",
"# nanos being added is an integer multiple of the",
"# base-frequency to self.freq",
"delta",
"=",
"nanos",
"//",
"base_nanos",
"# delta is the integer (or integer-array) number of periods",
"# by which will be added to self.",
"return",
"delta",
"_raise_on_incompatible",
"(",
"self",
",",
"other",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/arrays/period.py#L625-L672 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.