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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/site_compare/drivers/win32/keyboard.py | python | PressKey | (down, key) | Presses or unpresses a key.
Uses keybd_event to simulate either depressing or releasing
a key
Args:
down: Whether the key is to be pressed or released
key: Virtual key code of key to press or release | Presses or unpresses a key. | [
"Presses",
"or",
"unpresses",
"a",
"key",
"."
] | def PressKey(down, key):
"""Presses or unpresses a key.
Uses keybd_event to simulate either depressing or releasing
a key
Args:
down: Whether the key is to be pressed or released
key: Virtual key code of key to press or release
"""
# keybd_event injects key events at a very low level (it's the
# Windows API keyboard device drivers call) so this is a very
# reliable way of simulating user input
win32api.keybd_event(key, 0, (not down) * win32con.KEYEVENTF_KEYUP) | [
"def",
"PressKey",
"(",
"down",
",",
"key",
")",
":",
"# keybd_event injects key events at a very low level (it's the",
"# Windows API keyboard device drivers call) so this is a very",
"# reliable way of simulating user input",
"win32api",
".",
"keybd_event",
"(",
"key",
",",
"0",
",",
"(",
"not",
"down",
")",
"*",
"win32con",
".",
"KEYEVENTF_KEYUP",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/site_compare/drivers/win32/keyboard.py#L26-L40 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/py/shell.py | python | ShellFrame.OnClose | (self, event) | Event handler for closing. | Event handler for closing. | [
"Event",
"handler",
"for",
"closing",
"."
] | def OnClose(self, event):
"""Event handler for closing."""
# This isn't working the way I want, but I'll leave it for now.
if self.shell.waiting:
if event.CanVeto():
event.Veto(True)
else:
self.SaveSettings()
self.shell.destroy()
self.Destroy() | [
"def",
"OnClose",
"(",
"self",
",",
"event",
")",
":",
"# This isn't working the way I want, but I'll leave it for now.",
"if",
"self",
".",
"shell",
".",
"waiting",
":",
"if",
"event",
".",
"CanVeto",
"(",
")",
":",
"event",
".",
"Veto",
"(",
"True",
")",
"else",
":",
"self",
".",
"SaveSettings",
"(",
")",
"self",
".",
"shell",
".",
"destroy",
"(",
")",
"self",
".",
"Destroy",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/shell.py#L73-L82 | ||
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/YouCompleteMe/third_party/bottle/bottle.py | python | StplParser.get_syntax | (self) | return self._syntax | Tokens as a space separated string (default: <% %> % {{ }}) | Tokens as a space separated string (default: <% %> % {{ }}) | [
"Tokens",
"as",
"a",
"space",
"separated",
"string",
"(",
"default",
":",
"<%",
"%",
">",
"%",
"{{",
"}}",
")"
] | def get_syntax(self):
''' Tokens as a space separated string (default: <% %> % {{ }}) '''
return self._syntax | [
"def",
"get_syntax",
"(",
"self",
")",
":",
"return",
"self",
".",
"_syntax"
] | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/bottle/bottle.py#L3315-L3317 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | python/lammps/data.py | python | NeighList.get | (self, element) | return iatom, numneigh, neighbors | Access a specific neighbor list entry. "element" must be a number from 0 to the size-1 of the list
:return: tuple with atom local index, number of neighbors and ctypes pointer to neighbor's local atom indices
:rtype: (int, int, ctypes.POINTER(c_int)) | Access a specific neighbor list entry. "element" must be a number from 0 to the size-1 of the list | [
"Access",
"a",
"specific",
"neighbor",
"list",
"entry",
".",
"element",
"must",
"be",
"a",
"number",
"from",
"0",
"to",
"the",
"size",
"-",
"1",
"of",
"the",
"list"
] | def get(self, element):
"""
Access a specific neighbor list entry. "element" must be a number from 0 to the size-1 of the list
:return: tuple with atom local index, number of neighbors and ctypes pointer to neighbor's local atom indices
:rtype: (int, int, ctypes.POINTER(c_int))
"""
iatom, numneigh, neighbors = self.lmp.get_neighlist_element_neighbors(self.idx, element)
return iatom, numneigh, neighbors | [
"def",
"get",
"(",
"self",
",",
"element",
")",
":",
"iatom",
",",
"numneigh",
",",
"neighbors",
"=",
"self",
".",
"lmp",
".",
"get_neighlist_element_neighbors",
"(",
"self",
".",
"idx",
",",
"element",
")",
"return",
"iatom",
",",
"numneigh",
",",
"neighbors"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/python/lammps/data.py#L53-L61 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ribbon/gallery.py | python | RibbonGallery.OnEraseBackground | (self, event) | Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`RibbonGallery`.
:param `event`: a :class:`EraseEvent` event to be processed. | Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`RibbonGallery`. | [
"Handles",
"the",
"wx",
".",
"EVT_ERASE_BACKGROUND",
"event",
"for",
":",
"class",
":",
"RibbonGallery",
"."
] | def OnEraseBackground(self, event):
"""
Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`RibbonGallery`.
:param `event`: a :class:`EraseEvent` event to be processed.
"""
# All painting done in main paint handler to minimise flicker
pass | [
"def",
"OnEraseBackground",
"(",
"self",
",",
"event",
")",
":",
"# All painting done in main paint handler to minimise flicker",
"pass"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ribbon/gallery.py#L546-L554 | ||
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | lldb/scripts/Python/modify-python-lldb.py | python | NewContent.finish | (self) | Call this when you're finished with populating content. | Call this when you're finished with populating content. | [
"Call",
"this",
"when",
"you",
"re",
"finished",
"with",
"populating",
"content",
"."
] | def finish(self):
"""Call this when you're finished with populating content."""
if self.prev_line is not None:
self.write(self.prev_line + "\n")
self.prev_line = None | [
"def",
"finish",
"(",
"self",
")",
":",
"if",
"self",
".",
"prev_line",
"is",
"not",
"None",
":",
"self",
".",
"write",
"(",
"self",
".",
"prev_line",
"+",
"\"\\n\"",
")",
"self",
".",
"prev_line",
"=",
"None"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/scripts/Python/modify-python-lldb.py#L310-L314 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/training/device_setter.py | python | _ReplicaDeviceChooser._next_task | (self) | return task | Returns the next task to use.
Returns:
A number. | Returns the next task to use. | [
"Returns",
"the",
"next",
"task",
"to",
"use",
"."
] | def _next_task(self):
"""Returns the next task to use.
Returns:
A number.
"""
task = self._next_task_num
self._next_task_num = (self._next_task_num + 1) % self._ps_tasks
return task | [
"def",
"_next_task",
"(",
"self",
")",
":",
"task",
"=",
"self",
".",
"_next_task_num",
"self",
".",
"_next_task_num",
"=",
"(",
"self",
".",
"_next_task_num",
"+",
"1",
")",
"%",
"self",
".",
"_ps_tasks",
"return",
"task"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/device_setter.py#L55-L63 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/clang_format.py | python | usage | () | Print usage | Print usage | [
"Print",
"usage"
] | def usage():
"""Print usage
"""
print("clang-format.py supports 5 commands [ lint, lint-all, lint-patch, format, reformat-branch].") | [
"def",
"usage",
"(",
")",
":",
"print",
"(",
"\"clang-format.py supports 5 commands [ lint, lint-all, lint-patch, format, reformat-branch].\"",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/clang_format.py#L486-L489 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateSpan.Multiply | (*args, **kwargs) | return _misc_.DateSpan_Multiply(*args, **kwargs) | Multiply(self, int factor) -> DateSpan | Multiply(self, int factor) -> DateSpan | [
"Multiply",
"(",
"self",
"int",
"factor",
")",
"-",
">",
"DateSpan"
] | def Multiply(*args, **kwargs):
"""Multiply(self, int factor) -> DateSpan"""
return _misc_.DateSpan_Multiply(*args, **kwargs) | [
"def",
"Multiply",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_Multiply",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L4701-L4703 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.SetRectangularSelectionCaret | (*args, **kwargs) | return _stc.StyledTextCtrl_SetRectangularSelectionCaret(*args, **kwargs) | SetRectangularSelectionCaret(self, int pos) | SetRectangularSelectionCaret(self, int pos) | [
"SetRectangularSelectionCaret",
"(",
"self",
"int",
"pos",
")"
] | def SetRectangularSelectionCaret(*args, **kwargs):
"""SetRectangularSelectionCaret(self, int pos)"""
return _stc.StyledTextCtrl_SetRectangularSelectionCaret(*args, **kwargs) | [
"def",
"SetRectangularSelectionCaret",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetRectangularSelectionCaret",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L6208-L6210 | |
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | llvm/tools/opt-viewer/optpmap.py | python | pmap | (func, iterable, processes, should_print_progress, filter_=None, *args, **kwargs) | return result | A parallel map function that reports on its progress.
Applies `func` to every item of `iterable` and return a list of the
results. If `processes` is greater than one, a process pool is used to run
the functions in parallel. `should_print_progress` is a boolean value that
indicates whether a string 'N of M' should be printed to indicate how many
of the functions have finished being run. | A parallel map function that reports on its progress. | [
"A",
"parallel",
"map",
"function",
"that",
"reports",
"on",
"its",
"progress",
"."
] | def pmap(func, iterable, processes, should_print_progress, filter_=None, *args, **kwargs):
"""
A parallel map function that reports on its progress.
Applies `func` to every item of `iterable` and return a list of the
results. If `processes` is greater than one, a process pool is used to run
the functions in parallel. `should_print_progress` is a boolean value that
indicates whether a string 'N of M' should be printed to indicate how many
of the functions have finished being run.
"""
global _current
global _total
_current = multiprocessing.Value('i', 0)
_total = multiprocessing.Value('i', len(iterable))
func_and_args = [(func, arg, should_print_progress, filter_) for arg in iterable]
if processes == 1:
result = list(map(_wrapped_func, func_and_args, *args, **kwargs))
else:
pool = multiprocessing.Pool(initializer=_init,
initargs=(_current, _total,),
processes=processes)
result = pool.map(_wrapped_func, func_and_args, *args, **kwargs)
pool.close()
pool.join()
if should_print_progress:
sys.stdout.write('\r')
return result | [
"def",
"pmap",
"(",
"func",
",",
"iterable",
",",
"processes",
",",
"should_print_progress",
",",
"filter_",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_current",
"global",
"_total",
"_current",
"=",
"multiprocessing",
".",
"Value",
"(",
"'i'",
",",
"0",
")",
"_total",
"=",
"multiprocessing",
".",
"Value",
"(",
"'i'",
",",
"len",
"(",
"iterable",
")",
")",
"func_and_args",
"=",
"[",
"(",
"func",
",",
"arg",
",",
"should_print_progress",
",",
"filter_",
")",
"for",
"arg",
"in",
"iterable",
"]",
"if",
"processes",
"==",
"1",
":",
"result",
"=",
"list",
"(",
"map",
"(",
"_wrapped_func",
",",
"func_and_args",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"else",
":",
"pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"initializer",
"=",
"_init",
",",
"initargs",
"=",
"(",
"_current",
",",
"_total",
",",
")",
",",
"processes",
"=",
"processes",
")",
"result",
"=",
"pool",
".",
"map",
"(",
"_wrapped_func",
",",
"func_and_args",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"pool",
".",
"close",
"(",
")",
"pool",
".",
"join",
"(",
")",
"if",
"should_print_progress",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\r'",
")",
"return",
"result"
] | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/llvm/tools/opt-viewer/optpmap.py#L28-L56 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/android/gyp/prepare_resources.py | python | _GenerateRTxt | (options, r_txt_path) | Generate R.txt file.
Args:
options: The command-line options tuple.
r_txt_path: Locates where the R.txt file goes. | Generate R.txt file. | [
"Generate",
"R",
".",
"txt",
"file",
"."
] | def _GenerateRTxt(options, r_txt_path):
"""Generate R.txt file.
Args:
options: The command-line options tuple.
r_txt_path: Locates where the R.txt file goes.
"""
ignore_pattern = resource_utils.AAPT_IGNORE_PATTERN
if options.strip_drawables:
ignore_pattern += ':*drawable*'
resources_parser.RTxtGenerator(options.resource_dirs,
ignore_pattern).WriteRTxtFile(r_txt_path) | [
"def",
"_GenerateRTxt",
"(",
"options",
",",
"r_txt_path",
")",
":",
"ignore_pattern",
"=",
"resource_utils",
".",
"AAPT_IGNORE_PATTERN",
"if",
"options",
".",
"strip_drawables",
":",
"ignore_pattern",
"+=",
"':*drawable*'",
"resources_parser",
".",
"RTxtGenerator",
"(",
"options",
".",
"resource_dirs",
",",
"ignore_pattern",
")",
".",
"WriteRTxtFile",
"(",
"r_txt_path",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/prepare_resources.py#L122-L134 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/html.py | python | HtmlPrintout.AddFilter | (*args, **kwargs) | return _html.HtmlPrintout_AddFilter(*args, **kwargs) | AddFilter(wxHtmlFilter filter) | AddFilter(wxHtmlFilter filter) | [
"AddFilter",
"(",
"wxHtmlFilter",
"filter",
")"
] | def AddFilter(*args, **kwargs):
"""AddFilter(wxHtmlFilter filter)"""
return _html.HtmlPrintout_AddFilter(*args, **kwargs) | [
"def",
"AddFilter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlPrintout_AddFilter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L1307-L1309 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/ndarray/sparse.py | python | CSRNDArray.__setitem__ | (self, key, value) | x.__setitem__(i, y) <=> x[i]=y
Set self[key] to value. Only slice key [:] is supported.
Parameters
----------
key : mxnet.ndarray.NDArray.slice
The indexing key.
value : NDArray or CSRNDArray or numpy.ndarray
The value to set.
Examples
--------
>>> src = mx.nd.sparse.zeros('csr', (3,3))
>>> src.asnumpy()
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]], dtype=float32)
>>> # assign CSRNDArray with same storage type
>>> x = mx.nd.ones((3,3)).tostype('csr')
>>> x[:] = src
>>> x.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> # assign NDArray to CSRNDArray
>>> x[:] = mx.nd.ones((3,3)) * 2
>>> x.asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32) | x.__setitem__(i, y) <=> x[i]=y | [
"x",
".",
"__setitem__",
"(",
"i",
"y",
")",
"<",
"=",
">",
"x",
"[",
"i",
"]",
"=",
"y"
] | def __setitem__(self, key, value):
"""x.__setitem__(i, y) <=> x[i]=y
Set self[key] to value. Only slice key [:] is supported.
Parameters
----------
key : mxnet.ndarray.NDArray.slice
The indexing key.
value : NDArray or CSRNDArray or numpy.ndarray
The value to set.
Examples
--------
>>> src = mx.nd.sparse.zeros('csr', (3,3))
>>> src.asnumpy()
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]], dtype=float32)
>>> # assign CSRNDArray with same storage type
>>> x = mx.nd.ones((3,3)).tostype('csr')
>>> x[:] = src
>>> x.asnumpy()
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=float32)
>>> # assign NDArray to CSRNDArray
>>> x[:] = mx.nd.ones((3,3)) * 2
>>> x.asnumpy()
array([[ 2., 2., 2.],
[ 2., 2., 2.],
[ 2., 2., 2.]], dtype=float32)
"""
if not self.writable:
raise ValueError('Failed to assign to a readonly CSRNDArray')
if isinstance(key, py_slice):
if key.step is not None or key.start is not None or key.stop is not None:
raise ValueError('Assignment with slice for CSRNDArray is not ' \
'implemented yet.')
if isinstance(value, NDArray):
# avoid copying to itself
if value.handle is not self.handle:
value.copyto(self)
elif isinstance(value, numeric_types):
raise ValueError("Assigning numeric types to CSRNDArray is " \
"not implemented yet.")
elif isinstance(value, (np.ndarray, np.generic)):
# TODO(haibin/anisub) check scipy.sparse and use _sync_copy_from to
# avoid the temporary copy
warnings.warn('Assigning non-NDArray object to CSRNDArray is not efficient',
RuntimeWarning)
tmp = _array(value)
tmp.copyto(self)
else:
raise TypeError('type %s not supported' % str(type(value)))
else:
assert(isinstance(key, (int, tuple)))
raise Exception('CSRNDArray only supports [:] for assignment') | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"writable",
":",
"raise",
"ValueError",
"(",
"'Failed to assign to a readonly CSRNDArray'",
")",
"if",
"isinstance",
"(",
"key",
",",
"py_slice",
")",
":",
"if",
"key",
".",
"step",
"is",
"not",
"None",
"or",
"key",
".",
"start",
"is",
"not",
"None",
"or",
"key",
".",
"stop",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Assignment with slice for CSRNDArray is not '",
"'implemented yet.'",
")",
"if",
"isinstance",
"(",
"value",
",",
"NDArray",
")",
":",
"# avoid copying to itself",
"if",
"value",
".",
"handle",
"is",
"not",
"self",
".",
"handle",
":",
"value",
".",
"copyto",
"(",
"self",
")",
"elif",
"isinstance",
"(",
"value",
",",
"numeric_types",
")",
":",
"raise",
"ValueError",
"(",
"\"Assigning numeric types to CSRNDArray is \"",
"\"not implemented yet.\"",
")",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"np",
".",
"ndarray",
",",
"np",
".",
"generic",
")",
")",
":",
"# TODO(haibin/anisub) check scipy.sparse and use _sync_copy_from to",
"# avoid the temporary copy",
"warnings",
".",
"warn",
"(",
"'Assigning non-NDArray object to CSRNDArray is not efficient'",
",",
"RuntimeWarning",
")",
"tmp",
"=",
"_array",
"(",
"value",
")",
"tmp",
".",
"copyto",
"(",
"self",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'type %s not supported'",
"%",
"str",
"(",
"type",
"(",
"value",
")",
")",
")",
"else",
":",
"assert",
"(",
"isinstance",
"(",
"key",
",",
"(",
"int",
",",
"tuple",
")",
")",
")",
"raise",
"Exception",
"(",
"'CSRNDArray only supports [:] for assignment'",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/sparse.py#L399-L456 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/engine/topology.py | python | Layer.set_weights | (self, weights) | Sets the weights of the layer, from Numpy arrays.
Arguments:
weights: a list of Numpy arrays. The number
of arrays and their shape must match
number of the dimensions of the weights
of the layer (i.e. it should match the
output of `get_weights`).
Raises:
ValueError: If the provided weights list does not match the
layer's specifications. | Sets the weights of the layer, from Numpy arrays. | [
"Sets",
"the",
"weights",
"of",
"the",
"layer",
"from",
"Numpy",
"arrays",
"."
] | def set_weights(self, weights):
"""Sets the weights of the layer, from Numpy arrays.
Arguments:
weights: a list of Numpy arrays. The number
of arrays and their shape must match
number of the dimensions of the weights
of the layer (i.e. it should match the
output of `get_weights`).
Raises:
ValueError: If the provided weights list does not match the
layer's specifications.
"""
params = self.weights
if len(params) != len(weights):
raise ValueError('You called `set_weights(weights)` on layer "' +
self.name + '" with a weight list of length ' +
str(len(weights)) + ', but the layer was expecting ' +
str(len(params)) + ' weights. Provided weights: ' +
str(weights)[:50] + '...')
if not params:
return
weight_value_tuples = []
param_values = K.batch_get_value(params)
for pv, p, w in zip(param_values, params, weights):
if pv.shape != w.shape:
raise ValueError('Layer weight shape ' + str(pv.shape) +
' not compatible with '
'provided weight shape ' + str(w.shape))
weight_value_tuples.append((p, w))
K.batch_set_value(weight_value_tuples) | [
"def",
"set_weights",
"(",
"self",
",",
"weights",
")",
":",
"params",
"=",
"self",
".",
"weights",
"if",
"len",
"(",
"params",
")",
"!=",
"len",
"(",
"weights",
")",
":",
"raise",
"ValueError",
"(",
"'You called `set_weights(weights)` on layer \"'",
"+",
"self",
".",
"name",
"+",
"'\" with a weight list of length '",
"+",
"str",
"(",
"len",
"(",
"weights",
")",
")",
"+",
"', but the layer was expecting '",
"+",
"str",
"(",
"len",
"(",
"params",
")",
")",
"+",
"' weights. Provided weights: '",
"+",
"str",
"(",
"weights",
")",
"[",
":",
"50",
"]",
"+",
"'...'",
")",
"if",
"not",
"params",
":",
"return",
"weight_value_tuples",
"=",
"[",
"]",
"param_values",
"=",
"K",
".",
"batch_get_value",
"(",
"params",
")",
"for",
"pv",
",",
"p",
",",
"w",
"in",
"zip",
"(",
"param_values",
",",
"params",
",",
"weights",
")",
":",
"if",
"pv",
".",
"shape",
"!=",
"w",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"'Layer weight shape '",
"+",
"str",
"(",
"pv",
".",
"shape",
")",
"+",
"' not compatible with '",
"'provided weight shape '",
"+",
"str",
"(",
"w",
".",
"shape",
")",
")",
"weight_value_tuples",
".",
"append",
"(",
"(",
"p",
",",
"w",
")",
")",
"K",
".",
"batch_set_value",
"(",
"weight_value_tuples",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/engine/topology.py#L398-L429 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/html.py | python | HtmlHelpFrame.GetHelpWindow | (*args, **kwargs) | return _html.HtmlHelpFrame_GetHelpWindow(*args, **kwargs) | GetHelpWindow(self) -> HtmlHelpWindow | GetHelpWindow(self) -> HtmlHelpWindow | [
"GetHelpWindow",
"(",
"self",
")",
"-",
">",
"HtmlHelpWindow"
] | def GetHelpWindow(*args, **kwargs):
"""GetHelpWindow(self) -> HtmlHelpWindow"""
return _html.HtmlHelpFrame_GetHelpWindow(*args, **kwargs) | [
"def",
"GetHelpWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlHelpFrame_GetHelpWindow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L1774-L1776 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/ir_utils.py | python | copy_propagate | (blocks, typemap) | return in_copies, out_copies | compute copy propagation information for each block using fixed-point
iteration on data flow equations:
in_b = intersect(predec(B))
out_b = gen_b | (in_b - kill_b) | compute copy propagation information for each block using fixed-point
iteration on data flow equations:
in_b = intersect(predec(B))
out_b = gen_b | (in_b - kill_b) | [
"compute",
"copy",
"propagation",
"information",
"for",
"each",
"block",
"using",
"fixed",
"-",
"point",
"iteration",
"on",
"data",
"flow",
"equations",
":",
"in_b",
"=",
"intersect",
"(",
"predec",
"(",
"B",
"))",
"out_b",
"=",
"gen_b",
"|",
"(",
"in_b",
"-",
"kill_b",
")"
] | def copy_propagate(blocks, typemap):
"""compute copy propagation information for each block using fixed-point
iteration on data flow equations:
in_b = intersect(predec(B))
out_b = gen_b | (in_b - kill_b)
"""
cfg = compute_cfg_from_blocks(blocks)
entry = cfg.entry_point()
# format: dict of block labels to copies as tuples
# label -> (l,r)
c_data = init_copy_propagate_data(blocks, entry, typemap)
(gen_copies, all_copies, kill_copies, in_copies, out_copies) = c_data
old_point = None
new_point = copy.deepcopy(out_copies)
# comparison works since dictionary of built-in types
while old_point != new_point:
for label in blocks.keys():
if label == entry:
continue
predecs = [i for i, _d in cfg.predecessors(label)]
# in_b = intersect(predec(B))
in_copies[label] = out_copies[predecs[0]].copy()
for p in predecs:
in_copies[label] &= out_copies[p]
# out_b = gen_b | (in_b - kill_b)
out_copies[label] = (gen_copies[label]
| (in_copies[label] - kill_copies[label]))
old_point = new_point
new_point = copy.deepcopy(out_copies)
if config.DEBUG_ARRAY_OPT >= 1:
print("copy propagate out_copies:", out_copies)
return in_copies, out_copies | [
"def",
"copy_propagate",
"(",
"blocks",
",",
"typemap",
")",
":",
"cfg",
"=",
"compute_cfg_from_blocks",
"(",
"blocks",
")",
"entry",
"=",
"cfg",
".",
"entry_point",
"(",
")",
"# format: dict of block labels to copies as tuples",
"# label -> (l,r)",
"c_data",
"=",
"init_copy_propagate_data",
"(",
"blocks",
",",
"entry",
",",
"typemap",
")",
"(",
"gen_copies",
",",
"all_copies",
",",
"kill_copies",
",",
"in_copies",
",",
"out_copies",
")",
"=",
"c_data",
"old_point",
"=",
"None",
"new_point",
"=",
"copy",
".",
"deepcopy",
"(",
"out_copies",
")",
"# comparison works since dictionary of built-in types",
"while",
"old_point",
"!=",
"new_point",
":",
"for",
"label",
"in",
"blocks",
".",
"keys",
"(",
")",
":",
"if",
"label",
"==",
"entry",
":",
"continue",
"predecs",
"=",
"[",
"i",
"for",
"i",
",",
"_d",
"in",
"cfg",
".",
"predecessors",
"(",
"label",
")",
"]",
"# in_b = intersect(predec(B))",
"in_copies",
"[",
"label",
"]",
"=",
"out_copies",
"[",
"predecs",
"[",
"0",
"]",
"]",
".",
"copy",
"(",
")",
"for",
"p",
"in",
"predecs",
":",
"in_copies",
"[",
"label",
"]",
"&=",
"out_copies",
"[",
"p",
"]",
"# out_b = gen_b | (in_b - kill_b)",
"out_copies",
"[",
"label",
"]",
"=",
"(",
"gen_copies",
"[",
"label",
"]",
"|",
"(",
"in_copies",
"[",
"label",
"]",
"-",
"kill_copies",
"[",
"label",
"]",
")",
")",
"old_point",
"=",
"new_point",
"new_point",
"=",
"copy",
".",
"deepcopy",
"(",
"out_copies",
")",
"if",
"config",
".",
"DEBUG_ARRAY_OPT",
">=",
"1",
":",
"print",
"(",
"\"copy propagate out_copies:\"",
",",
"out_copies",
")",
"return",
"in_copies",
",",
"out_copies"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/ir_utils.py#L819-L853 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/nodes.py | python | Element.update_all_atts_consistantly | (self, dict_, replace = True,
and_source = False) | Updates all attributes from node or dictionary `dict_`.
Appends the basic attributes ('ids', 'names', 'classes',
'dupnames', but not 'source') and then, for all other attributes in
dict_, updates the same attribute in self. When attributes with the
same identifier appear in both self and dict_ and replace is True, the
values in self are replaced with the values in dict_; otherwise, the
values in self are preserved. When and_source is True, the 'source'
attribute is included in the copy.
NOTE: When replace is False, and self contains a 'source' attribute,
'source' is not replaced even when dict_ has a 'source'
attribute, though it may still be merged into a list depending
on the value of update_fun. | Updates all attributes from node or dictionary `dict_`. | [
"Updates",
"all",
"attributes",
"from",
"node",
"or",
"dictionary",
"dict_",
"."
] | def update_all_atts_consistantly(self, dict_, replace = True,
and_source = False):
"""
Updates all attributes from node or dictionary `dict_`.
Appends the basic attributes ('ids', 'names', 'classes',
'dupnames', but not 'source') and then, for all other attributes in
dict_, updates the same attribute in self. When attributes with the
same identifier appear in both self and dict_ and replace is True, the
values in self are replaced with the values in dict_; otherwise, the
values in self are preserved. When and_source is True, the 'source'
attribute is included in the copy.
NOTE: When replace is False, and self contains a 'source' attribute,
'source' is not replaced even when dict_ has a 'source'
attribute, though it may still be merged into a list depending
on the value of update_fun.
"""
self.update_all_atts(dict_, Element.copy_attr_consistent, replace,
and_source) | [
"def",
"update_all_atts_consistantly",
"(",
"self",
",",
"dict_",
",",
"replace",
"=",
"True",
",",
"and_source",
"=",
"False",
")",
":",
"self",
".",
"update_all_atts",
"(",
"dict_",
",",
"Element",
".",
"copy_attr_consistent",
",",
"replace",
",",
"and_source",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/nodes.py#L832-L851 | ||
tiann/android-native-debug | 198903ed9346dc4a74327a63cb98d449b97d8047 | app/source/art/tools/cpplint.py | python | ProcessFileData | (filename, file_extension, lines, error,
extra_check_functions=[]) | Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Performs lint checks and reports any errors to the given error function. | [
"Performs",
"lint",
"checks",
"and",
"reports",
"any",
"errors",
"to",
"the",
"given",
"error",
"function",
"."
] | def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = _NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
if file_extension == 'h':
CheckForHeaderGuard(filename, lines, error)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
nesting_state.CheckClassFinished(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForUnicodeReplacementCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error) | [
"def",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"error",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"lines",
"=",
"(",
"[",
"'// marker so line numbers and indices both start at 1'",
"]",
"+",
"lines",
"+",
"[",
"'// marker so line numbers end in a known way'",
"]",
")",
"include_state",
"=",
"_IncludeState",
"(",
")",
"function_state",
"=",
"_FunctionState",
"(",
")",
"nesting_state",
"=",
"_NestingState",
"(",
")",
"ResetNolintSuppressions",
"(",
")",
"CheckForCopyright",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"if",
"file_extension",
"==",
"'h'",
":",
"CheckForHeaderGuard",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"clean_lines",
"=",
"CleansedLines",
"(",
"lines",
")",
"for",
"line",
"in",
"xrange",
"(",
"clean_lines",
".",
"NumLines",
"(",
")",
")",
":",
"ProcessLine",
"(",
"filename",
",",
"file_extension",
",",
"clean_lines",
",",
"line",
",",
"include_state",
",",
"function_state",
",",
"nesting_state",
",",
"error",
",",
"extra_check_functions",
")",
"nesting_state",
".",
"CheckClassFinished",
"(",
"filename",
",",
"error",
")",
"CheckForIncludeWhatYouUse",
"(",
"filename",
",",
"clean_lines",
",",
"include_state",
",",
"error",
")",
"# We check here rather than inside ProcessLine so that we see raw",
"# lines rather than \"cleaned\" lines.",
"CheckForUnicodeReplacementCharacters",
"(",
"filename",
",",
"lines",
",",
"error",
")",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")"
] | https://github.com/tiann/android-native-debug/blob/198903ed9346dc4a74327a63cb98d449b97d8047/app/source/art/tools/cpplint.py#L3824-L3867 | ||
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/unit/unit.py | python | Unit.get_symbol | (self) | return symbol | Returns a unit symbol (string) for this Unit, composed of its various
BaseUnit symbols. e.g. 'kg m**2 s**-1' | Returns a unit symbol (string) for this Unit, composed of its various
BaseUnit symbols. e.g. 'kg m**2 s**-1' | [
"Returns",
"a",
"unit",
"symbol",
"(",
"string",
")",
"for",
"this",
"Unit",
"composed",
"of",
"its",
"various",
"BaseUnit",
"symbols",
".",
"e",
".",
"g",
".",
"kg",
"m",
"**",
"2",
"s",
"**",
"-",
"1"
] | def get_symbol(self):
"""
Returns a unit symbol (string) for this Unit, composed of its various
BaseUnit symbols. e.g. 'kg m**2 s**-1'
"""
symbol = ""
# emit positive exponents first
pos = ""
pos_count = 0
for unit, power in self.iter_base_or_scaled_units():
if power > 0:
pos_count += 1
if pos_count > 1: pos += " "
pos += unit.symbol
if power != 1.0:
pos += "**%g" % power
# emit negative exponents second
neg = ""
neg_count = 0
simple_denominator = True
for unit, power in self.iter_base_or_scaled_units():
if power < 0:
neg_count += 1
if neg_count > 1: neg += " "
neg += unit.symbol
if power != -1.0:
neg += "**%g" % -power
simple_denominator = False
# Format of denominator depends on number of terms
if 0 == neg_count:
neg_string = ""
elif 1 == neg_count and simple_denominator:
neg_string = "/%s" % neg
else:
neg_string = "/(%s)" % neg
if 0 == pos_count:
pos_string = ""
else:
pos_string = pos
if 0 == pos_count == neg_count:
symbol = "dimensionless"
else:
symbol = "%s%s" % (pos_string, neg_string)
return symbol | [
"def",
"get_symbol",
"(",
"self",
")",
":",
"symbol",
"=",
"\"\"",
"# emit positive exponents first",
"pos",
"=",
"\"\"",
"pos_count",
"=",
"0",
"for",
"unit",
",",
"power",
"in",
"self",
".",
"iter_base_or_scaled_units",
"(",
")",
":",
"if",
"power",
">",
"0",
":",
"pos_count",
"+=",
"1",
"if",
"pos_count",
">",
"1",
":",
"pos",
"+=",
"\" \"",
"pos",
"+=",
"unit",
".",
"symbol",
"if",
"power",
"!=",
"1.0",
":",
"pos",
"+=",
"\"**%g\"",
"%",
"power",
"# emit negative exponents second",
"neg",
"=",
"\"\"",
"neg_count",
"=",
"0",
"simple_denominator",
"=",
"True",
"for",
"unit",
",",
"power",
"in",
"self",
".",
"iter_base_or_scaled_units",
"(",
")",
":",
"if",
"power",
"<",
"0",
":",
"neg_count",
"+=",
"1",
"if",
"neg_count",
">",
"1",
":",
"neg",
"+=",
"\" \"",
"neg",
"+=",
"unit",
".",
"symbol",
"if",
"power",
"!=",
"-",
"1.0",
":",
"neg",
"+=",
"\"**%g\"",
"%",
"-",
"power",
"simple_denominator",
"=",
"False",
"# Format of denominator depends on number of terms",
"if",
"0",
"==",
"neg_count",
":",
"neg_string",
"=",
"\"\"",
"elif",
"1",
"==",
"neg_count",
"and",
"simple_denominator",
":",
"neg_string",
"=",
"\"/%s\"",
"%",
"neg",
"else",
":",
"neg_string",
"=",
"\"/(%s)\"",
"%",
"neg",
"if",
"0",
"==",
"pos_count",
":",
"pos_string",
"=",
"\"\"",
"else",
":",
"pos_string",
"=",
"pos",
"if",
"0",
"==",
"pos_count",
"==",
"neg_count",
":",
"symbol",
"=",
"\"dimensionless\"",
"else",
":",
"symbol",
"=",
"\"%s%s\"",
"%",
"(",
"pos_string",
",",
"neg_string",
")",
"return",
"symbol"
] | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/unit/unit.py#L423-L466 | |
sonyxperiadev/WebGL | 0299b38196f78c6d5f74bcf6fa312a3daee6de60 | Tools/Scripts/webkitpy/common/checkout/diff_parser.py | python | get_diff_converter | (first_diff_line) | return lambda input: input | Gets a converter function of diff lines.
Args:
first_diff_line: The first filename line of a diff file.
If this line is git formatted, we'll return a
converter from git to SVN. | Gets a converter function of diff lines. | [
"Gets",
"a",
"converter",
"function",
"of",
"diff",
"lines",
"."
] | def get_diff_converter(first_diff_line):
"""Gets a converter function of diff lines.
Args:
first_diff_line: The first filename line of a diff file.
If this line is git formatted, we'll return a
converter from git to SVN.
"""
if match(r"^diff --git \w/", first_diff_line):
return git_diff_to_svn_diff
return lambda input: input | [
"def",
"get_diff_converter",
"(",
"first_diff_line",
")",
":",
"if",
"match",
"(",
"r\"^diff --git \\w/\"",
",",
"first_diff_line",
")",
":",
"return",
"git_diff_to_svn_diff",
"return",
"lambda",
"input",
":",
"input"
] | https://github.com/sonyxperiadev/WebGL/blob/0299b38196f78c6d5f74bcf6fa312a3daee6de60/Tools/Scripts/webkitpy/common/checkout/diff_parser.py#L73-L83 | |
eric612/Caffe-YOLOv3-Windows | 6736ca6e16781789b828cc64218ff77cc3454e5d | scripts/cpp_lint.py | python | FindNextMatchingAngleBracket | (clean_lines, linenum, init_suffix) | return True | Find the corresponding > to close a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_suffix: Remainder of the current line after the initial <.
Returns:
True if a matching bracket exists. | Find the corresponding > to close a template. | [
"Find",
"the",
"corresponding",
">",
"to",
"close",
"a",
"template",
"."
] | def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix):
"""Find the corresponding > to close a template.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Current line number.
init_suffix: Remainder of the current line after the initial <.
Returns:
True if a matching bracket exists.
"""
line = init_suffix
nesting_stack = ['<']
while True:
# Find the next operator that can tell us whether < is used as an
# opening bracket or as a less-than operator. We only want to
# warn on the latter case.
#
# We could also check all other operators and terminate the search
# early, e.g. if we got something like this "a<b+c", the "<" is
# most likely a less-than operator, but then we will get false
# positives for default arguments and other template expressions.
match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line)
if match:
# Found an operator, update nesting stack
operator = match.group(1)
line = match.group(2)
if nesting_stack[-1] == '<':
# Expecting closing angle bracket
if operator in ('<', '(', '['):
nesting_stack.append(operator)
elif operator == '>':
nesting_stack.pop()
if not nesting_stack:
# Found matching angle bracket
return True
elif operator == ',':
# Got a comma after a bracket, this is most likely a template
# argument. We have not seen a closing angle bracket yet, but
# it's probably a few lines later if we look for it, so just
# return early here.
return True
else:
# Got some other operator.
return False
else:
# Expecting closing parenthesis or closing bracket
if operator in ('<', '(', '['):
nesting_stack.append(operator)
elif operator in (')', ']'):
# We don't bother checking for matching () or []. If we got
# something like (] or [), it would have been a syntax error.
nesting_stack.pop()
else:
# Scan the next line
linenum += 1
if linenum >= len(clean_lines.elided):
break
line = clean_lines.elided[linenum]
# Exhausted all remaining lines and still no matching angle bracket.
# Most likely the input was incomplete, otherwise we should have
# seen a semicolon and returned early.
return True | [
"def",
"FindNextMatchingAngleBracket",
"(",
"clean_lines",
",",
"linenum",
",",
"init_suffix",
")",
":",
"line",
"=",
"init_suffix",
"nesting_stack",
"=",
"[",
"'<'",
"]",
"while",
"True",
":",
"# Find the next operator that can tell us whether < is used as an",
"# opening bracket or as a less-than operator. We only want to",
"# warn on the latter case.",
"#",
"# We could also check all other operators and terminate the search",
"# early, e.g. if we got something like this \"a<b+c\", the \"<\" is",
"# most likely a less-than operator, but then we will get false",
"# positives for default arguments and other template expressions.",
"match",
"=",
"Search",
"(",
"r'^[^<>(),;\\[\\]]*([<>(),;\\[\\]])(.*)$'",
",",
"line",
")",
"if",
"match",
":",
"# Found an operator, update nesting stack",
"operator",
"=",
"match",
".",
"group",
"(",
"1",
")",
"line",
"=",
"match",
".",
"group",
"(",
"2",
")",
"if",
"nesting_stack",
"[",
"-",
"1",
"]",
"==",
"'<'",
":",
"# Expecting closing angle bracket",
"if",
"operator",
"in",
"(",
"'<'",
",",
"'('",
",",
"'['",
")",
":",
"nesting_stack",
".",
"append",
"(",
"operator",
")",
"elif",
"operator",
"==",
"'>'",
":",
"nesting_stack",
".",
"pop",
"(",
")",
"if",
"not",
"nesting_stack",
":",
"# Found matching angle bracket",
"return",
"True",
"elif",
"operator",
"==",
"','",
":",
"# Got a comma after a bracket, this is most likely a template",
"# argument. We have not seen a closing angle bracket yet, but",
"# it's probably a few lines later if we look for it, so just",
"# return early here.",
"return",
"True",
"else",
":",
"# Got some other operator.",
"return",
"False",
"else",
":",
"# Expecting closing parenthesis or closing bracket",
"if",
"operator",
"in",
"(",
"'<'",
",",
"'('",
",",
"'['",
")",
":",
"nesting_stack",
".",
"append",
"(",
"operator",
")",
"elif",
"operator",
"in",
"(",
"')'",
",",
"']'",
")",
":",
"# We don't bother checking for matching () or []. If we got",
"# something like (] or [), it would have been a syntax error.",
"nesting_stack",
".",
"pop",
"(",
")",
"else",
":",
"# Scan the next line",
"linenum",
"+=",
"1",
"if",
"linenum",
">=",
"len",
"(",
"clean_lines",
".",
"elided",
")",
":",
"break",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Exhausted all remaining lines and still no matching angle bracket.",
"# Most likely the input was incomplete, otherwise we should have",
"# seen a semicolon and returned early.",
"return",
"True"
] | https://github.com/eric612/Caffe-YOLOv3-Windows/blob/6736ca6e16781789b828cc64218ff77cc3454e5d/scripts/cpp_lint.py#L2521-L2587 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/v7.9.317/third_party/jinja2/filters.py | python | do_forceescape | (value) | return escape(text_type(value)) | Enforce HTML escaping. This will probably double escape variables. | Enforce HTML escaping. This will probably double escape variables. | [
"Enforce",
"HTML",
"escaping",
".",
"This",
"will",
"probably",
"double",
"escape",
"variables",
"."
] | def do_forceescape(value):
"""Enforce HTML escaping. This will probably double escape variables."""
if hasattr(value, '__html__'):
value = value.__html__()
return escape(text_type(value)) | [
"def",
"do_forceescape",
"(",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"'__html__'",
")",
":",
"value",
"=",
"value",
".",
"__html__",
"(",
")",
"return",
"escape",
"(",
"text_type",
"(",
"value",
")",
")"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/filters.py#L87-L91 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/SocketServer.py | python | BaseServer.verify_request | (self, request, client_address) | return True | Verify the request. May be overridden.
Return True if we should proceed with this request. | Verify the request. May be overridden. | [
"Verify",
"the",
"request",
".",
"May",
"be",
"overridden",
"."
] | def verify_request(self, request, client_address):
"""Verify the request. May be overridden.
Return True if we should proceed with this request.
"""
return True | [
"def",
"verify_request",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"return",
"True"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/SocketServer.py#L307-L313 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/misc.py | python | maybe_literal | (value) | Get a Literal type for the value or None. | Get a Literal type for the value or None. | [
"Get",
"a",
"Literal",
"type",
"for",
"the",
"value",
"or",
"None",
"."
] | def maybe_literal(value):
"""Get a Literal type for the value or None.
"""
try:
return literal(value)
except LiteralTypingError:
return | [
"def",
"maybe_literal",
"(",
"value",
")",
":",
"try",
":",
"return",
"literal",
"(",
"value",
")",
"except",
"LiteralTypingError",
":",
"return"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/misc.py#L73-L79 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/ma/core.py | python | power | (a, b, third=None) | return result | Returns element-wise base array raised to power from second array.
This is the masked array version of `numpy.power`. For details see
`numpy.power`.
See Also
--------
numpy.power
Notes
-----
The *out* argument to `numpy.power` is not supported, `third` has to be
None. | Returns element-wise base array raised to power from second array. | [
"Returns",
"element",
"-",
"wise",
"base",
"array",
"raised",
"to",
"power",
"from",
"second",
"array",
"."
] | def power(a, b, third=None):
"""
Returns element-wise base array raised to power from second array.
This is the masked array version of `numpy.power`. For details see
`numpy.power`.
See Also
--------
numpy.power
Notes
-----
The *out* argument to `numpy.power` is not supported, `third` has to be
None.
"""
if third is not None:
raise MaskError("3-argument power not supported.")
# Get the masks
ma = getmask(a)
mb = getmask(b)
m = mask_or(ma, mb)
# Get the rawdata
fa = getdata(a)
fb = getdata(b)
# Get the type of the result (so that we preserve subclasses)
if isinstance(a, MaskedArray):
basetype = type(a)
else:
basetype = MaskedArray
# Get the result and view it as a (subclass of) MaskedArray
with np.errstate(divide='ignore', invalid='ignore'):
result = np.where(m, fa, umath.power(fa, fb)).view(basetype)
result._update_from(a)
# Find where we're in trouble w/ NaNs and Infs
invalid = np.logical_not(np.isfinite(result.view(ndarray)))
# Add the initial mask
if m is not nomask:
if not result.ndim:
return masked
result._mask = np.logical_or(m, invalid)
# Fix the invalid parts
if invalid.any():
if not result.ndim:
return masked
elif result._mask is nomask:
result._mask = invalid
result._data[invalid] = result.fill_value
return result | [
"def",
"power",
"(",
"a",
",",
"b",
",",
"third",
"=",
"None",
")",
":",
"if",
"third",
"is",
"not",
"None",
":",
"raise",
"MaskError",
"(",
"\"3-argument power not supported.\"",
")",
"# Get the masks",
"ma",
"=",
"getmask",
"(",
"a",
")",
"mb",
"=",
"getmask",
"(",
"b",
")",
"m",
"=",
"mask_or",
"(",
"ma",
",",
"mb",
")",
"# Get the rawdata",
"fa",
"=",
"getdata",
"(",
"a",
")",
"fb",
"=",
"getdata",
"(",
"b",
")",
"# Get the type of the result (so that we preserve subclasses)",
"if",
"isinstance",
"(",
"a",
",",
"MaskedArray",
")",
":",
"basetype",
"=",
"type",
"(",
"a",
")",
"else",
":",
"basetype",
"=",
"MaskedArray",
"# Get the result and view it as a (subclass of) MaskedArray",
"with",
"np",
".",
"errstate",
"(",
"divide",
"=",
"'ignore'",
",",
"invalid",
"=",
"'ignore'",
")",
":",
"result",
"=",
"np",
".",
"where",
"(",
"m",
",",
"fa",
",",
"umath",
".",
"power",
"(",
"fa",
",",
"fb",
")",
")",
".",
"view",
"(",
"basetype",
")",
"result",
".",
"_update_from",
"(",
"a",
")",
"# Find where we're in trouble w/ NaNs and Infs",
"invalid",
"=",
"np",
".",
"logical_not",
"(",
"np",
".",
"isfinite",
"(",
"result",
".",
"view",
"(",
"ndarray",
")",
")",
")",
"# Add the initial mask",
"if",
"m",
"is",
"not",
"nomask",
":",
"if",
"not",
"result",
".",
"ndim",
":",
"return",
"masked",
"result",
".",
"_mask",
"=",
"np",
".",
"logical_or",
"(",
"m",
",",
"invalid",
")",
"# Fix the invalid parts",
"if",
"invalid",
".",
"any",
"(",
")",
":",
"if",
"not",
"result",
".",
"ndim",
":",
"return",
"masked",
"elif",
"result",
".",
"_mask",
"is",
"nomask",
":",
"result",
".",
"_mask",
"=",
"invalid",
"result",
".",
"_data",
"[",
"invalid",
"]",
"=",
"result",
".",
"fill_value",
"return",
"result"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/core.py#L6816-L6865 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBStringList.__init__ | (self, *args) | __init__(self) -> SBStringList
__init__(self, SBStringList rhs) -> SBStringList | __init__(self) -> SBStringList
__init__(self, SBStringList rhs) -> SBStringList | [
"__init__",
"(",
"self",
")",
"-",
">",
"SBStringList",
"__init__",
"(",
"self",
"SBStringList",
"rhs",
")",
"-",
">",
"SBStringList"
] | def __init__(self, *args):
"""
__init__(self) -> SBStringList
__init__(self, SBStringList rhs) -> SBStringList
"""
this = _lldb.new_SBStringList(*args)
try: self.this.append(this)
except: self.this = this | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"this",
"=",
"_lldb",
".",
"new_SBStringList",
"(",
"*",
"args",
")",
"try",
":",
"self",
".",
"this",
".",
"append",
"(",
"this",
")",
"except",
":",
"self",
".",
"this",
"=",
"this"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L7985-L7992 | ||
xhzdeng/crpn | a5aef0f80dbe486103123f740c634fb01e6cc9a1 | lib/pycocotools/coco.py | python | COCO.getCatIds | (self, catNms=[], supNms=[], catIds=[]) | return ids | filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids | filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids | [
"filtering",
"parameters",
".",
"default",
"skips",
"that",
"filter",
".",
":",
"param",
"catNms",
"(",
"str",
"array",
")",
":",
"get",
"cats",
"for",
"given",
"cat",
"names",
":",
"param",
"supNms",
"(",
"str",
"array",
")",
":",
"get",
"cats",
"for",
"given",
"supercategory",
"names",
":",
"param",
"catIds",
"(",
"int",
"array",
")",
":",
"get",
"cats",
"for",
"given",
"cat",
"ids",
":",
"return",
":",
"ids",
"(",
"int",
"array",
")",
":",
"integer",
"array",
"of",
"cat",
"ids"
] | def getCatIds(self, catNms=[], supNms=[], catIds=[]):
"""
filtering parameters. default skips that filter.
:param catNms (str array) : get cats for given cat names
:param supNms (str array) : get cats for given supercategory names
:param catIds (int array) : get cats for given cat ids
:return: ids (int array) : integer array of cat ids
"""
catNms = catNms if type(catNms) == list else [catNms]
supNms = supNms if type(supNms) == list else [supNms]
catIds = catIds if type(catIds) == list else [catIds]
if len(catNms) == len(supNms) == len(catIds) == 0:
cats = self.dataset['categories']
else:
cats = self.dataset['categories']
cats = cats if len(catNms) == 0 else [cat for cat in cats if cat['name'] in catNms]
cats = cats if len(supNms) == 0 else [cat for cat in cats if cat['supercategory'] in supNms]
cats = cats if len(catIds) == 0 else [cat for cat in cats if cat['id'] in catIds]
ids = [cat['id'] for cat in cats]
return ids | [
"def",
"getCatIds",
"(",
"self",
",",
"catNms",
"=",
"[",
"]",
",",
"supNms",
"=",
"[",
"]",
",",
"catIds",
"=",
"[",
"]",
")",
":",
"catNms",
"=",
"catNms",
"if",
"type",
"(",
"catNms",
")",
"==",
"list",
"else",
"[",
"catNms",
"]",
"supNms",
"=",
"supNms",
"if",
"type",
"(",
"supNms",
")",
"==",
"list",
"else",
"[",
"supNms",
"]",
"catIds",
"=",
"catIds",
"if",
"type",
"(",
"catIds",
")",
"==",
"list",
"else",
"[",
"catIds",
"]",
"if",
"len",
"(",
"catNms",
")",
"==",
"len",
"(",
"supNms",
")",
"==",
"len",
"(",
"catIds",
")",
"==",
"0",
":",
"cats",
"=",
"self",
".",
"dataset",
"[",
"'categories'",
"]",
"else",
":",
"cats",
"=",
"self",
".",
"dataset",
"[",
"'categories'",
"]",
"cats",
"=",
"cats",
"if",
"len",
"(",
"catNms",
")",
"==",
"0",
"else",
"[",
"cat",
"for",
"cat",
"in",
"cats",
"if",
"cat",
"[",
"'name'",
"]",
"in",
"catNms",
"]",
"cats",
"=",
"cats",
"if",
"len",
"(",
"supNms",
")",
"==",
"0",
"else",
"[",
"cat",
"for",
"cat",
"in",
"cats",
"if",
"cat",
"[",
"'supercategory'",
"]",
"in",
"supNms",
"]",
"cats",
"=",
"cats",
"if",
"len",
"(",
"catIds",
")",
"==",
"0",
"else",
"[",
"cat",
"for",
"cat",
"in",
"cats",
"if",
"cat",
"[",
"'id'",
"]",
"in",
"catIds",
"]",
"ids",
"=",
"[",
"cat",
"[",
"'id'",
"]",
"for",
"cat",
"in",
"cats",
"]",
"return",
"ids"
] | https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/lib/pycocotools/coco.py#L159-L179 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/parameters/InputParameters.py | python | InputParameters.values | (self) | Provides dict.values() functionality. | Provides dict.values() functionality. | [
"Provides",
"dict",
".",
"values",
"()",
"functionality",
"."
] | def values(self):
"""
Provides dict.values() functionality.
"""
for param in self.__parameters.values():
if not param.private:
yield param.value | [
"def",
"values",
"(",
"self",
")",
":",
"for",
"param",
"in",
"self",
".",
"__parameters",
".",
"values",
"(",
")",
":",
"if",
"not",
"param",
".",
"private",
":",
"yield",
"param",
".",
"value"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/parameters/InputParameters.py#L90-L96 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/sites/client.py | python | SitesClient.create_webattachment | (self, src, content_type, title, parent,
description=None, auth_token=None, **kwargs) | return self.post(new_entry, self.make_content_feed_uri(),
auth_token=auth_token, **kwargs) | Creates a new webattachment within a filecabinet.
Args:
src: string The url of the web attachment.
content_type: string The MIME type of the web attachment.
title: string The title to name the web attachment.
parent: string or gdata.sites.data.ContentEntry (optional) The
parent entry or url of the filecabinet to create the attachment under.
description: string (optional) A summary/description for the attachment.
auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or
OAuthToken which authorizes this client to edit the user's data.
kwargs: Other parameters to pass to gdata.client.post().
Returns:
gdata.sites.data.ContentEntry of the created page. | Creates a new webattachment within a filecabinet. | [
"Creates",
"a",
"new",
"webattachment",
"within",
"a",
"filecabinet",
"."
] | def create_webattachment(self, src, content_type, title, parent,
description=None, auth_token=None, **kwargs):
"""Creates a new webattachment within a filecabinet.
Args:
src: string The url of the web attachment.
content_type: string The MIME type of the web attachment.
title: string The title to name the web attachment.
parent: string or gdata.sites.data.ContentEntry (optional) The
parent entry or url of the filecabinet to create the attachment under.
description: string (optional) A summary/description for the attachment.
auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or
OAuthToken which authorizes this client to edit the user's data.
kwargs: Other parameters to pass to gdata.client.post().
Returns:
gdata.sites.data.ContentEntry of the created page.
"""
new_entry = gdata.sites.data.ContentEntry(
title=atom.data.Title(text=title), kind='webattachment',
content=gdata.sites.data.Content(src=src, type=content_type))
if isinstance(parent, gdata.sites.data.ContentEntry):
link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL,
type='application/atom+xml',
href=parent.GetSelfLink().href)
elif parent is not None:
link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL,
type='application/atom+xml', href=parent)
new_entry.link.append(link)
# Add file decription if it was specified
if description is not None:
new_entry.summary = gdata.sites.data.Summary(type='text',
text=description)
return self.post(new_entry, self.make_content_feed_uri(),
auth_token=auth_token, **kwargs) | [
"def",
"create_webattachment",
"(",
"self",
",",
"src",
",",
"content_type",
",",
"title",
",",
"parent",
",",
"description",
"=",
"None",
",",
"auth_token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"new_entry",
"=",
"gdata",
".",
"sites",
".",
"data",
".",
"ContentEntry",
"(",
"title",
"=",
"atom",
".",
"data",
".",
"Title",
"(",
"text",
"=",
"title",
")",
",",
"kind",
"=",
"'webattachment'",
",",
"content",
"=",
"gdata",
".",
"sites",
".",
"data",
".",
"Content",
"(",
"src",
"=",
"src",
",",
"type",
"=",
"content_type",
")",
")",
"if",
"isinstance",
"(",
"parent",
",",
"gdata",
".",
"sites",
".",
"data",
".",
"ContentEntry",
")",
":",
"link",
"=",
"atom",
".",
"data",
".",
"Link",
"(",
"rel",
"=",
"gdata",
".",
"sites",
".",
"data",
".",
"SITES_PARENT_LINK_REL",
",",
"type",
"=",
"'application/atom+xml'",
",",
"href",
"=",
"parent",
".",
"GetSelfLink",
"(",
")",
".",
"href",
")",
"elif",
"parent",
"is",
"not",
"None",
":",
"link",
"=",
"atom",
".",
"data",
".",
"Link",
"(",
"rel",
"=",
"gdata",
".",
"sites",
".",
"data",
".",
"SITES_PARENT_LINK_REL",
",",
"type",
"=",
"'application/atom+xml'",
",",
"href",
"=",
"parent",
")",
"new_entry",
".",
"link",
".",
"append",
"(",
"link",
")",
"# Add file decription if it was specified",
"if",
"description",
"is",
"not",
"None",
":",
"new_entry",
".",
"summary",
"=",
"gdata",
".",
"sites",
".",
"data",
".",
"Summary",
"(",
"type",
"=",
"'text'",
",",
"text",
"=",
"description",
")",
"return",
"self",
".",
"post",
"(",
"new_entry",
",",
"self",
".",
"make_content_feed_uri",
"(",
")",
",",
"auth_token",
"=",
"auth_token",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/sites/client.py#L231-L269 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/psutil/psutil/__init__.py | python | Process.as_dict | (self, attrs=[], ad_value=None) | return retdict | Utility method returning process information as a hashable
dictionary.
If 'attrs' is specified it must be a list of strings reflecting
available Process class's attribute names (e.g. ['get_cpu_times',
'name']) else all public (read only) attributes are assumed.
'ad_value' is the value which gets assigned to a dict key in case
AccessDenied exception is raised when retrieving that particular
process information. | Utility method returning process information as a hashable
dictionary. | [
"Utility",
"method",
"returning",
"process",
"information",
"as",
"a",
"hashable",
"dictionary",
"."
] | def as_dict(self, attrs=[], ad_value=None):
"""Utility method returning process information as a hashable
dictionary.
If 'attrs' is specified it must be a list of strings reflecting
available Process class's attribute names (e.g. ['get_cpu_times',
'name']) else all public (read only) attributes are assumed.
'ad_value' is the value which gets assigned to a dict key in case
AccessDenied exception is raised when retrieving that particular
process information.
"""
excluded_names = set(['send_signal', 'suspend', 'resume', 'terminate',
'kill', 'wait', 'is_running', 'as_dict', 'parent',
'get_children', 'nice'])
retdict = dict()
for name in set(attrs or dir(self)):
if name.startswith('_'):
continue
if name.startswith('set_'):
continue
if name in excluded_names:
continue
try:
attr = getattr(self, name)
if callable(attr):
if name == 'get_cpu_percent':
ret = attr(interval=0)
else:
ret = attr()
else:
ret = attr
except AccessDenied:
ret = ad_value
except NotImplementedError:
# in case of not implemented functionality (may happen
# on old or exotic systems) we want to crash only if
# the user explicitly asked for that particular attr
if attrs:
raise
continue
if name.startswith('get'):
if name[3] == '_':
name = name[4:]
elif name == 'getcwd':
name = 'cwd'
retdict[name] = ret
return retdict | [
"def",
"as_dict",
"(",
"self",
",",
"attrs",
"=",
"[",
"]",
",",
"ad_value",
"=",
"None",
")",
":",
"excluded_names",
"=",
"set",
"(",
"[",
"'send_signal'",
",",
"'suspend'",
",",
"'resume'",
",",
"'terminate'",
",",
"'kill'",
",",
"'wait'",
",",
"'is_running'",
",",
"'as_dict'",
",",
"'parent'",
",",
"'get_children'",
",",
"'nice'",
"]",
")",
"retdict",
"=",
"dict",
"(",
")",
"for",
"name",
"in",
"set",
"(",
"attrs",
"or",
"dir",
"(",
"self",
")",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'_'",
")",
":",
"continue",
"if",
"name",
".",
"startswith",
"(",
"'set_'",
")",
":",
"continue",
"if",
"name",
"in",
"excluded_names",
":",
"continue",
"try",
":",
"attr",
"=",
"getattr",
"(",
"self",
",",
"name",
")",
"if",
"callable",
"(",
"attr",
")",
":",
"if",
"name",
"==",
"'get_cpu_percent'",
":",
"ret",
"=",
"attr",
"(",
"interval",
"=",
"0",
")",
"else",
":",
"ret",
"=",
"attr",
"(",
")",
"else",
":",
"ret",
"=",
"attr",
"except",
"AccessDenied",
":",
"ret",
"=",
"ad_value",
"except",
"NotImplementedError",
":",
"# in case of not implemented functionality (may happen",
"# on old or exotic systems) we want to crash only if",
"# the user explicitly asked for that particular attr",
"if",
"attrs",
":",
"raise",
"continue",
"if",
"name",
".",
"startswith",
"(",
"'get'",
")",
":",
"if",
"name",
"[",
"3",
"]",
"==",
"'_'",
":",
"name",
"=",
"name",
"[",
"4",
":",
"]",
"elif",
"name",
"==",
"'getcwd'",
":",
"name",
"=",
"'cwd'",
"retdict",
"[",
"name",
"]",
"=",
"ret",
"return",
"retdict"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/__init__.py#L196-L243 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/cef_source/tools/crash_server.py | python | CrashHTTPRequestHandler.do_HEAD | (self) | Default empty implementation for handling HEAD requests. | Default empty implementation for handling HEAD requests. | [
"Default",
"empty",
"implementation",
"for",
"handling",
"HEAD",
"requests",
"."
] | def do_HEAD(self):
""" Default empty implementation for handling HEAD requests. """
self._send_default_response_headers() | [
"def",
"do_HEAD",
"(",
"self",
")",
":",
"self",
".",
"_send_default_response_headers",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/crash_server.py#L205-L207 | ||
HackWebRTC/webrtc | 7abfc990c00ab35090fff285fcf635d1d7892433 | tools_webrtc/PRESUBMIT.py | python | _LicenseHeader | (input_api) | return license_header | Returns the license header regexp. | Returns the license header regexp. | [
"Returns",
"the",
"license",
"header",
"regexp",
"."
] | def _LicenseHeader(input_api):
"""Returns the license header regexp."""
# Accept any year number from 2003 to the current year
current_year = int(input_api.time.strftime('%Y'))
allowed_years = (str(s) for s in reversed(xrange(2003, current_year + 1)))
years_re = '(' + '|'.join(allowed_years) + ')'
license_header = (
r'.*? Copyright( \(c\))? %(year)s The WebRTC [Pp]roject [Aa]uthors\. '
r'All [Rr]ights [Rr]eserved\.\n'
r'.*?\n'
r'.*? Use of this source code is governed by a BSD-style license\n'
r'.*? that can be found in the LICENSE file in the root of the source\n'
r'.*? tree\. An additional intellectual property rights grant can be '
r'found\n'
r'.*? in the file PATENTS\. All contributing project authors may\n'
r'.*? be found in the AUTHORS file in the root of the source tree\.\n'
) % {
'year': years_re,
}
return license_header | [
"def",
"_LicenseHeader",
"(",
"input_api",
")",
":",
"# Accept any year number from 2003 to the current year",
"current_year",
"=",
"int",
"(",
"input_api",
".",
"time",
".",
"strftime",
"(",
"'%Y'",
")",
")",
"allowed_years",
"=",
"(",
"str",
"(",
"s",
")",
"for",
"s",
"in",
"reversed",
"(",
"xrange",
"(",
"2003",
",",
"current_year",
"+",
"1",
")",
")",
")",
"years_re",
"=",
"'('",
"+",
"'|'",
".",
"join",
"(",
"allowed_years",
")",
"+",
"')'",
"license_header",
"=",
"(",
"r'.*? Copyright( \\(c\\))? %(year)s The WebRTC [Pp]roject [Aa]uthors\\. '",
"r'All [Rr]ights [Rr]eserved\\.\\n'",
"r'.*?\\n'",
"r'.*? Use of this source code is governed by a BSD-style license\\n'",
"r'.*? that can be found in the LICENSE file in the root of the source\\n'",
"r'.*? tree\\. An additional intellectual property rights grant can be '",
"r'found\\n'",
"r'.*? in the file PATENTS\\. All contributing project authors may\\n'",
"r'.*? be found in the AUTHORS file in the root of the source tree\\.\\n'",
")",
"%",
"{",
"'year'",
":",
"years_re",
",",
"}",
"return",
"license_header"
] | https://github.com/HackWebRTC/webrtc/blob/7abfc990c00ab35090fff285fcf635d1d7892433/tools_webrtc/PRESUBMIT.py#L10-L29 | |
jiaxiang-wu/quantized-cnn | 4d020e17026df90e40111d219e3eb74e0afb1588 | cpplint.py | python | CheckInvalidIncrement | (filename, clean_lines, linenum, error) | Checks for invalid increment *count++.
For example following function:
void increment_counter(int* count) {
*count++;
}
is invalid, because it effectively does count++, moving pointer, and should
be replaced with ++*count, (*count)++ or *count += 1.
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. | Checks for invalid increment *count++. | [
"Checks",
"for",
"invalid",
"increment",
"*",
"count",
"++",
"."
] | def CheckInvalidIncrement(filename, clean_lines, linenum, error):
"""Checks for invalid increment *count++.
For example following function:
void increment_counter(int* count) {
*count++;
}
is invalid, because it effectively does count++, moving pointer, and should
be replaced with ++*count, (*count)++ or *count += 1.
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]
if _RE_PATTERN_INVALID_INCREMENT.match(line):
error(filename, linenum, 'runtime/invalid_increment', 5,
'Changing pointer instead of value (or unused value of operator*).') | [
"def",
"CheckInvalidIncrement",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"_RE_PATTERN_INVALID_INCREMENT",
".",
"match",
"(",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/invalid_increment'",
",",
"5",
",",
"'Changing pointer instead of value (or unused value of operator*).'",
")"
] | https://github.com/jiaxiang-wu/quantized-cnn/blob/4d020e17026df90e40111d219e3eb74e0afb1588/cpplint.py#L1961-L1980 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/debug/wrappers/grpc_wrapper.py | python | GrpcDebugWrapperSession.__init__ | (self,
sess,
grpc_debug_server_addresses,
watch_fn=None,
thread_name_filter=None,
log_usage=True) | Constructor of DumpingDebugWrapperSession.
Args:
sess: The TensorFlow `Session` object being wrapped.
grpc_debug_server_addresses: (`str` or `list` of `str`) Single or a list
of the gRPC debug server addresses, in the format of
<host:port>, without the "grpc://" prefix. For example:
"localhost:7000",
["localhost:7000", "192.168.0.2:8000"]
watch_fn: (`Callable`) A Callable that can be used to define per-run
debug ops and watched tensors. See the doc of
`NonInteractiveDebugWrapperSession.__init__()` for details.
thread_name_filter: Regular-expression white list for threads on which the
wrapper session will be active. See doc of `BaseDebugWrapperSession` for
more details.
log_usage: (`bool`) whether the usage of this class is to be logged.
Raises:
TypeError: If `grpc_debug_server_addresses` is not a `str` or a `list`
of `str`. | Constructor of DumpingDebugWrapperSession. | [
"Constructor",
"of",
"DumpingDebugWrapperSession",
"."
] | def __init__(self,
sess,
grpc_debug_server_addresses,
watch_fn=None,
thread_name_filter=None,
log_usage=True):
"""Constructor of DumpingDebugWrapperSession.
Args:
sess: The TensorFlow `Session` object being wrapped.
grpc_debug_server_addresses: (`str` or `list` of `str`) Single or a list
of the gRPC debug server addresses, in the format of
<host:port>, without the "grpc://" prefix. For example:
"localhost:7000",
["localhost:7000", "192.168.0.2:8000"]
watch_fn: (`Callable`) A Callable that can be used to define per-run
debug ops and watched tensors. See the doc of
`NonInteractiveDebugWrapperSession.__init__()` for details.
thread_name_filter: Regular-expression white list for threads on which the
wrapper session will be active. See doc of `BaseDebugWrapperSession` for
more details.
log_usage: (`bool`) whether the usage of this class is to be logged.
Raises:
TypeError: If `grpc_debug_server_addresses` is not a `str` or a `list`
of `str`.
"""
if log_usage:
pass # No logging for open-source.
framework.NonInteractiveDebugWrapperSession.__init__(
self, sess, watch_fn=watch_fn, thread_name_filter=thread_name_filter)
if isinstance(grpc_debug_server_addresses, str):
self._grpc_debug_server_urls = [
self._GRPC_URL_PREFIX + grpc_debug_server_addresses
]
elif isinstance(grpc_debug_server_addresses, list):
self._grpc_debug_server_urls = []
for address in grpc_debug_server_addresses:
if not isinstance(address, str):
raise TypeError(
"Expected type str in list grpc_debug_server_addresses, "
"received type %s" % type(address))
self._grpc_debug_server_urls.append(self._GRPC_URL_PREFIX + address)
else:
raise TypeError(
"Expected type str or list in grpc_debug_server_addresses, "
"received type %s" % type(grpc_debug_server_addresses)) | [
"def",
"__init__",
"(",
"self",
",",
"sess",
",",
"grpc_debug_server_addresses",
",",
"watch_fn",
"=",
"None",
",",
"thread_name_filter",
"=",
"None",
",",
"log_usage",
"=",
"True",
")",
":",
"if",
"log_usage",
":",
"pass",
"# No logging for open-source.",
"framework",
".",
"NonInteractiveDebugWrapperSession",
".",
"__init__",
"(",
"self",
",",
"sess",
",",
"watch_fn",
"=",
"watch_fn",
",",
"thread_name_filter",
"=",
"thread_name_filter",
")",
"if",
"isinstance",
"(",
"grpc_debug_server_addresses",
",",
"str",
")",
":",
"self",
".",
"_grpc_debug_server_urls",
"=",
"[",
"self",
".",
"_GRPC_URL_PREFIX",
"+",
"grpc_debug_server_addresses",
"]",
"elif",
"isinstance",
"(",
"grpc_debug_server_addresses",
",",
"list",
")",
":",
"self",
".",
"_grpc_debug_server_urls",
"=",
"[",
"]",
"for",
"address",
"in",
"grpc_debug_server_addresses",
":",
"if",
"not",
"isinstance",
"(",
"address",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected type str in list grpc_debug_server_addresses, \"",
"\"received type %s\"",
"%",
"type",
"(",
"address",
")",
")",
"self",
".",
"_grpc_debug_server_urls",
".",
"append",
"(",
"self",
".",
"_GRPC_URL_PREFIX",
"+",
"address",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Expected type str or list in grpc_debug_server_addresses, \"",
"\"received type %s\"",
"%",
"type",
"(",
"grpc_debug_server_addresses",
")",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/wrappers/grpc_wrapper.py#L29-L78 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mapreduce/mapreduce/datastore_range_iterators.py | python | _PropertyRangeModelIterator.__init__ | (self, p_range, ns_range, query_spec) | Init.
Args:
p_range: a property_range.PropertyRange object that defines the
conditions entities should safisfy.
ns_range: a namesrange.NamespaceRange object that defines the namespaces
to examine.
query_spec: a model.QuerySpec object that defines how to retrieve
entities from datastore. | Init. | [
"Init",
"."
] | def __init__(self, p_range, ns_range, query_spec):
"""Init.
Args:
p_range: a property_range.PropertyRange object that defines the
conditions entities should safisfy.
ns_range: a namesrange.NamespaceRange object that defines the namespaces
to examine.
query_spec: a model.QuerySpec object that defines how to retrieve
entities from datastore.
"""
self._property_range = p_range
self._ns_range = ns_range
self._query_spec = query_spec
self._cursor = None
self._query = None | [
"def",
"__init__",
"(",
"self",
",",
"p_range",
",",
"ns_range",
",",
"query_spec",
")",
":",
"self",
".",
"_property_range",
"=",
"p_range",
"self",
".",
"_ns_range",
"=",
"ns_range",
"self",
".",
"_query_spec",
"=",
"query_spec",
"self",
".",
"_cursor",
"=",
"None",
"self",
".",
"_query",
"=",
"None"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/datastore_range_iterators.py#L135-L150 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/_extends/parallel_compile/tbe_compiler/tbe_helper.py | python | get_module_name | (compute_op_info) | return op_module_name | get compute_op_info
:param compute_op_info:
:return: | get compute_op_info
:param compute_op_info:
:return: | [
"get",
"compute_op_info",
":",
"param",
"compute_op_info",
":",
":",
"return",
":"
] | def get_module_name(compute_op_info):
"""
get compute_op_info
:param compute_op_info:
:return:
"""
dynamic_compile_static = compute_op_info["dynamic_compile_static"]
unknown_shape = compute_op_info["unknown_shape"]
op_module_name = compute_op_info["module_name"]
if dynamic_compile_static or unknown_shape:
op_module_name = op_module_name.split(".")[0] + ".dynamic." + op_module_name.split(".")[-1]
return op_module_name | [
"def",
"get_module_name",
"(",
"compute_op_info",
")",
":",
"dynamic_compile_static",
"=",
"compute_op_info",
"[",
"\"dynamic_compile_static\"",
"]",
"unknown_shape",
"=",
"compute_op_info",
"[",
"\"unknown_shape\"",
"]",
"op_module_name",
"=",
"compute_op_info",
"[",
"\"module_name\"",
"]",
"if",
"dynamic_compile_static",
"or",
"unknown_shape",
":",
"op_module_name",
"=",
"op_module_name",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"+",
"\".dynamic.\"",
"+",
"op_module_name",
".",
"split",
"(",
"\".\"",
")",
"[",
"-",
"1",
"]",
"return",
"op_module_name"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parallel_compile/tbe_compiler/tbe_helper.py#L247-L258 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/mantid/fitfunctions.py | python | FunctionWrapper.__init__ | (self, name, **kwargs) | Called when creating an instance
:param name: name of fitting function to create or
an Ifunction object to wrap.
:param kwargs: standard argument for initializing fit
function | Called when creating an instance | [
"Called",
"when",
"creating",
"an",
"instance"
] | def __init__(self, name, **kwargs):
"""
Called when creating an instance
:param name: name of fitting function to create or
an Ifunction object to wrap.
:param kwargs: standard argument for initializing fit
function
"""
if not isinstance(name, str):
self.fun = name
else:
self.fun = FunctionFactory.createFunction(name)
self.init_paramgeters_and_attributes(**kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"self",
".",
"fun",
"=",
"name",
"else",
":",
"self",
".",
"fun",
"=",
"FunctionFactory",
".",
"createFunction",
"(",
"name",
")",
"self",
".",
"init_paramgeters_and_attributes",
"(",
"*",
"*",
"kwargs",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/mantid/fitfunctions.py#L26-L39 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/data/python/ops/parsing_ops.py | python | parse_example_dataset | (features, num_parallel_calls=1) | return parsing_ops.parse_example_dataset(features, num_parallel_calls) | A transformation that parses `Example` protos into a `dict` of tensors.
Parses a number of serialized `Example` protos given in `serialized`. We refer
to `serialized` as a batch with `batch_size` many entries of individual
`Example` protos.
This op parses serialized examples into a dictionary mapping keys to `Tensor`
and `SparseTensor` objects. `features` is a dict from keys to `VarLenFeature`,
`SparseFeature`, and `FixedLenFeature` objects. Each `VarLenFeature`
and `SparseFeature` is mapped to a `SparseTensor`, and each
`FixedLenFeature` is mapped to a `Tensor`. See `tf.io.parse_example` for more
details about feature dictionaries.
Args:
features: A `dict` mapping feature keys to `FixedLenFeature`,
`VarLenFeature`, and `SparseFeature` values.
num_parallel_calls: (Optional.) A `tf.int32` scalar `tf.Tensor`,
representing the number of parsing processes to call in parallel.
Returns:
A dataset transformation function, which can be passed to
`tf.data.Dataset.apply`.
Raises:
ValueError: if features argument is None. | A transformation that parses `Example` protos into a `dict` of tensors. | [
"A",
"transformation",
"that",
"parses",
"Example",
"protos",
"into",
"a",
"dict",
"of",
"tensors",
"."
] | def parse_example_dataset(features, num_parallel_calls=1):
"""A transformation that parses `Example` protos into a `dict` of tensors.
Parses a number of serialized `Example` protos given in `serialized`. We refer
to `serialized` as a batch with `batch_size` many entries of individual
`Example` protos.
This op parses serialized examples into a dictionary mapping keys to `Tensor`
and `SparseTensor` objects. `features` is a dict from keys to `VarLenFeature`,
`SparseFeature`, and `FixedLenFeature` objects. Each `VarLenFeature`
and `SparseFeature` is mapped to a `SparseTensor`, and each
`FixedLenFeature` is mapped to a `Tensor`. See `tf.io.parse_example` for more
details about feature dictionaries.
Args:
features: A `dict` mapping feature keys to `FixedLenFeature`,
`VarLenFeature`, and `SparseFeature` values.
num_parallel_calls: (Optional.) A `tf.int32` scalar `tf.Tensor`,
representing the number of parsing processes to call in parallel.
Returns:
A dataset transformation function, which can be passed to
`tf.data.Dataset.apply`.
Raises:
ValueError: if features argument is None.
"""
return parsing_ops.parse_example_dataset(features, num_parallel_calls) | [
"def",
"parse_example_dataset",
"(",
"features",
",",
"num_parallel_calls",
"=",
"1",
")",
":",
"return",
"parsing_ops",
".",
"parse_example_dataset",
"(",
"features",
",",
"num_parallel_calls",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/data/python/ops/parsing_ops.py#L26-L53 | |
chanyn/3Dpose_ssl | 585696676279683a279b1ecca136c0e0d02aef2a | caffe-3dssl/python/caffe/io.py | python | Transformer.set_mean | (self, in_, mean) | Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable) | Set the mean to subtract for centering the data. | [
"Set",
"the",
"mean",
"to",
"subtract",
"for",
"centering",
"the",
"data",
"."
] | def set_mean(self, in_, mean):
"""
Set the mean to subtract for centering the data.
Parameters
----------
in_ : which input to assign this mean.
mean : mean ndarray (input dimensional or broadcastable)
"""
self.__check_input(in_)
ms = mean.shape
if mean.ndim == 1:
# broadcast channels
if ms[0] != self.inputs[in_][1]:
raise ValueError('Mean channels incompatible with input.')
mean = mean[:, np.newaxis, np.newaxis]
else:
# elementwise mean
if len(ms) == 2:
ms = (1,) + ms
if len(ms) != 3:
raise ValueError('Mean shape invalid')
if ms != self.inputs[in_][1:]:
raise ValueError('Mean shape incompatible with input shape.')
self.mean[in_] = mean | [
"def",
"set_mean",
"(",
"self",
",",
"in_",
",",
"mean",
")",
":",
"self",
".",
"__check_input",
"(",
"in_",
")",
"ms",
"=",
"mean",
".",
"shape",
"if",
"mean",
".",
"ndim",
"==",
"1",
":",
"# broadcast channels",
"if",
"ms",
"[",
"0",
"]",
"!=",
"self",
".",
"inputs",
"[",
"in_",
"]",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'Mean channels incompatible with input.'",
")",
"mean",
"=",
"mean",
"[",
":",
",",
"np",
".",
"newaxis",
",",
"np",
".",
"newaxis",
"]",
"else",
":",
"# elementwise mean",
"if",
"len",
"(",
"ms",
")",
"==",
"2",
":",
"ms",
"=",
"(",
"1",
",",
")",
"+",
"ms",
"if",
"len",
"(",
"ms",
")",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'Mean shape invalid'",
")",
"if",
"ms",
"!=",
"self",
".",
"inputs",
"[",
"in_",
"]",
"[",
"1",
":",
"]",
":",
"raise",
"ValueError",
"(",
"'Mean shape incompatible with input shape.'",
")",
"self",
".",
"mean",
"[",
"in_",
"]",
"=",
"mean"
] | https://github.com/chanyn/3Dpose_ssl/blob/585696676279683a279b1ecca136c0e0d02aef2a/caffe-3dssl/python/caffe/io.py#L236-L260 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/zoombar.py | python | ZoomBarImage.LoopScales | (self, size) | Caches the bitmaps at various zoom levels to avoid calling every time
`image.Scale` on the button bitmap.
:param `size`: the original button size, in pixels. | Caches the bitmaps at various zoom levels to avoid calling every time
`image.Scale` on the button bitmap. | [
"Caches",
"the",
"bitmaps",
"at",
"various",
"zoom",
"levels",
"to",
"avoid",
"calling",
"every",
"time",
"image",
".",
"Scale",
"on",
"the",
"button",
"bitmap",
"."
] | def LoopScales(self, size):
"""
Caches the bitmaps at various zoom levels to avoid calling every time
`image.Scale` on the button bitmap.
:param `size`: the original button size, in pixels.
"""
if self._isAReflection:
return
for scale in range(size-10*self._zoomFactor, size+15*self._zoomFactor, self._zoomFactor):
if scale in self._cachedBitmaps or scale <= 0:
continue
img = self._bitmap.ConvertToImage()
img = img.Scale(scale, scale, wx.IMAGE_QUALITY_HIGH)
bmp = img.ConvertToBitmap()
self._cachedBitmaps[scale] = bmp
img = self._disabledBmp.ConvertToImage()
img = img.Scale(scale, scale, wx.IMAGE_QUALITY_HIGH)
bmp = img.ConvertToBitmap()
self._cachedDisabledBitmaps[scale] = bmp | [
"def",
"LoopScales",
"(",
"self",
",",
"size",
")",
":",
"if",
"self",
".",
"_isAReflection",
":",
"return",
"for",
"scale",
"in",
"range",
"(",
"size",
"-",
"10",
"*",
"self",
".",
"_zoomFactor",
",",
"size",
"+",
"15",
"*",
"self",
".",
"_zoomFactor",
",",
"self",
".",
"_zoomFactor",
")",
":",
"if",
"scale",
"in",
"self",
".",
"_cachedBitmaps",
"or",
"scale",
"<=",
"0",
":",
"continue",
"img",
"=",
"self",
".",
"_bitmap",
".",
"ConvertToImage",
"(",
")",
"img",
"=",
"img",
".",
"Scale",
"(",
"scale",
",",
"scale",
",",
"wx",
".",
"IMAGE_QUALITY_HIGH",
")",
"bmp",
"=",
"img",
".",
"ConvertToBitmap",
"(",
")",
"self",
".",
"_cachedBitmaps",
"[",
"scale",
"]",
"=",
"bmp",
"img",
"=",
"self",
".",
"_disabledBmp",
".",
"ConvertToImage",
"(",
")",
"img",
"=",
"img",
".",
"Scale",
"(",
"scale",
",",
"scale",
",",
"wx",
".",
"IMAGE_QUALITY_HIGH",
")",
"bmp",
"=",
"img",
".",
"ConvertToBitmap",
"(",
")",
"self",
".",
"_cachedDisabledBitmaps",
"[",
"scale",
"]",
"=",
"bmp"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/zoombar.py#L514-L537 | ||
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.WritePchTargets | (self, ninja_file, pch_commands) | Writes ninja rules to compile prefix headers. | Writes ninja rules to compile prefix headers. | [
"Writes",
"ninja",
"rules",
"to",
"compile",
"prefix",
"headers",
"."
] | def WritePchTargets(self, ninja_file, pch_commands):
"""Writes ninja rules to compile prefix headers."""
if not pch_commands:
return
for gch, lang_flag, lang, input in pch_commands:
var_name = {
"c": "cflags_pch_c",
"cc": "cflags_pch_cc",
"m": "cflags_pch_objc",
"mm": "cflags_pch_objcc",
}[lang]
map = {
"c": "cc",
"cc": "cxx",
"m": "objc",
"mm": "objcxx",
}
cmd = map.get(lang)
ninja_file.build(gch, cmd, input, variables=[(var_name, lang_flag)]) | [
"def",
"WritePchTargets",
"(",
"self",
",",
"ninja_file",
",",
"pch_commands",
")",
":",
"if",
"not",
"pch_commands",
":",
"return",
"for",
"gch",
",",
"lang_flag",
",",
"lang",
",",
"input",
"in",
"pch_commands",
":",
"var_name",
"=",
"{",
"\"c\"",
":",
"\"cflags_pch_c\"",
",",
"\"cc\"",
":",
"\"cflags_pch_cc\"",
",",
"\"m\"",
":",
"\"cflags_pch_objc\"",
",",
"\"mm\"",
":",
"\"cflags_pch_objcc\"",
",",
"}",
"[",
"lang",
"]",
"map",
"=",
"{",
"\"c\"",
":",
"\"cc\"",
",",
"\"cc\"",
":",
"\"cxx\"",
",",
"\"m\"",
":",
"\"objc\"",
",",
"\"mm\"",
":",
"\"objcxx\"",
",",
"}",
"cmd",
"=",
"map",
".",
"get",
"(",
"lang",
")",
"ninja_file",
".",
"build",
"(",
"gch",
",",
"cmd",
",",
"input",
",",
"variables",
"=",
"[",
"(",
"var_name",
",",
"lang_flag",
")",
"]",
")"
] | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L1285-L1305 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | LogChain.IsPassingMessages | (*args, **kwargs) | return _misc_.LogChain_IsPassingMessages(*args, **kwargs) | IsPassingMessages(self) -> bool | IsPassingMessages(self) -> bool | [
"IsPassingMessages",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsPassingMessages(*args, **kwargs):
"""IsPassingMessages(self) -> bool"""
return _misc_.LogChain_IsPassingMessages(*args, **kwargs) | [
"def",
"IsPassingMessages",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"LogChain_IsPassingMessages",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L1809-L1811 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/getlimits.py | python | _fr0 | (a) | return a | fix rank-0 --> rank-1 | fix rank-0 --> rank-1 | [
"fix",
"rank",
"-",
"0",
"--",
">",
"rank",
"-",
"1"
] | def _fr0(a):
"""fix rank-0 --> rank-1"""
if a.ndim == 0:
a = a.copy()
a.shape = (1,)
return a | [
"def",
"_fr0",
"(",
"a",
")",
":",
"if",
"a",
".",
"ndim",
"==",
"0",
":",
"a",
"=",
"a",
".",
"copy",
"(",
")",
"a",
".",
"shape",
"=",
"(",
"1",
",",
")",
"return",
"a"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/getlimits.py#L19-L24 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/gensuitemodule.py | python | processfile | (fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, dump=None,
verbose=None) | Ask an application for its terminology and process that | Ask an application for its terminology and process that | [
"Ask",
"an",
"application",
"for",
"its",
"terminology",
"and",
"process",
"that"
] | def processfile(fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, dump=None,
verbose=None):
"""Ask an application for its terminology and process that"""
if not is_scriptable(fullname) and verbose:
print >>verbose, "Warning: app does not seem scriptable: %s" % fullname
if verbose:
print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname)
try:
aedescobj, launched = OSATerminology.GetAppTerminology(fullname)
except MacOS.Error, arg:
if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound
if verbose:
print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually"
aedata, sig = getappterminology(fullname, verbose=verbose)
if not creatorsignature:
creatorsignature = sig
else:
raise
else:
if launched:
if verbose:
print >>verbose, "Launched", fullname
raw = aetools.unpack(aedescobj)
if not raw:
if verbose:
print >>verbose, 'Unpack returned empty value:', raw
return
if not raw[0].data:
if verbose:
print >>verbose, 'Unpack returned value without data:', raw
return
aedata = raw[0]
aete = decode(aedata.data, verbose)
if dump:
dumpaetelist([aete], dump)
return
compileaete(aete, None, fullname, output=output, basepkgname=basepkgname,
creatorsignature=creatorsignature, edit_modnames=edit_modnames,
verbose=verbose) | [
"def",
"processfile",
"(",
"fullname",
",",
"output",
"=",
"None",
",",
"basepkgname",
"=",
"None",
",",
"edit_modnames",
"=",
"None",
",",
"creatorsignature",
"=",
"None",
",",
"dump",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"not",
"is_scriptable",
"(",
"fullname",
")",
"and",
"verbose",
":",
"print",
">>",
"verbose",
",",
"\"Warning: app does not seem scriptable: %s\"",
"%",
"fullname",
"if",
"verbose",
":",
"print",
">>",
"verbose",
",",
"\"\\nASKING FOR aete DICTIONARY IN\"",
",",
"repr",
"(",
"fullname",
")",
"try",
":",
"aedescobj",
",",
"launched",
"=",
"OSATerminology",
".",
"GetAppTerminology",
"(",
"fullname",
")",
"except",
"MacOS",
".",
"Error",
",",
"arg",
":",
"if",
"arg",
"[",
"0",
"]",
"in",
"(",
"-",
"1701",
",",
"-",
"192",
")",
":",
"# errAEDescNotFound, resNotFound",
"if",
"verbose",
":",
"print",
">>",
"verbose",
",",
"\"GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually\"",
"aedata",
",",
"sig",
"=",
"getappterminology",
"(",
"fullname",
",",
"verbose",
"=",
"verbose",
")",
"if",
"not",
"creatorsignature",
":",
"creatorsignature",
"=",
"sig",
"else",
":",
"raise",
"else",
":",
"if",
"launched",
":",
"if",
"verbose",
":",
"print",
">>",
"verbose",
",",
"\"Launched\"",
",",
"fullname",
"raw",
"=",
"aetools",
".",
"unpack",
"(",
"aedescobj",
")",
"if",
"not",
"raw",
":",
"if",
"verbose",
":",
"print",
">>",
"verbose",
",",
"'Unpack returned empty value:'",
",",
"raw",
"return",
"if",
"not",
"raw",
"[",
"0",
"]",
".",
"data",
":",
"if",
"verbose",
":",
"print",
">>",
"verbose",
",",
"'Unpack returned value without data:'",
",",
"raw",
"return",
"aedata",
"=",
"raw",
"[",
"0",
"]",
"aete",
"=",
"decode",
"(",
"aedata",
".",
"data",
",",
"verbose",
")",
"if",
"dump",
":",
"dumpaetelist",
"(",
"[",
"aete",
"]",
",",
"dump",
")",
"return",
"compileaete",
"(",
"aete",
",",
"None",
",",
"fullname",
",",
"output",
"=",
"output",
",",
"basepkgname",
"=",
"basepkgname",
",",
"creatorsignature",
"=",
"creatorsignature",
",",
"edit_modnames",
"=",
"edit_modnames",
",",
"verbose",
"=",
"verbose",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/gensuitemodule.py#L186-L225 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py | python | Wm.wm_grid | (self,
baseWidth=None, baseHeight=None,
widthInc=None, heightInc=None) | return self._getints(self.tk.call(
'wm', 'grid', self._w,
baseWidth, baseHeight, widthInc, heightInc)) | Instruct the window manager that this widget shall only be
resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
number of grid units requested in Tk_GeometryRequest. | Instruct the window manager that this widget shall only be
resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
number of grid units requested in Tk_GeometryRequest. | [
"Instruct",
"the",
"window",
"manager",
"that",
"this",
"widget",
"shall",
"only",
"be",
"resized",
"on",
"grid",
"boundaries",
".",
"WIDTHINC",
"and",
"HEIGHTINC",
"are",
"the",
"width",
"and",
"height",
"of",
"a",
"grid",
"unit",
"in",
"pixels",
".",
"BASEWIDTH",
"and",
"BASEHEIGHT",
"are",
"the",
"number",
"of",
"grid",
"units",
"requested",
"in",
"Tk_GeometryRequest",
"."
] | def wm_grid(self,
baseWidth=None, baseHeight=None,
widthInc=None, heightInc=None):
"""Instruct the window manager that this widget shall only be
resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
number of grid units requested in Tk_GeometryRequest."""
return self._getints(self.tk.call(
'wm', 'grid', self._w,
baseWidth, baseHeight, widthInc, heightInc)) | [
"def",
"wm_grid",
"(",
"self",
",",
"baseWidth",
"=",
"None",
",",
"baseHeight",
"=",
"None",
",",
"widthInc",
"=",
"None",
",",
"heightInc",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getints",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"'wm'",
",",
"'grid'",
",",
"self",
".",
"_w",
",",
"baseWidth",
",",
"baseHeight",
",",
"widthInc",
",",
"heightInc",
")",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L1596-L1605 | |
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/serialupdi/nvm.py | python | NvmUpdi.execute_nvm_command | (self, command) | return self.readwrite.write_byte(self.device.nvmctrl_address + constants.UPDI_NVMCTRL_CTRLA, command) | Executes an NVM COMMAND on the NVM CTRL
:param command: command to execute | Executes an NVM COMMAND on the NVM CTRL
:param command: command to execute | [
"Executes",
"an",
"NVM",
"COMMAND",
"on",
"the",
"NVM",
"CTRL",
":",
"param",
"command",
":",
"command",
"to",
"execute"
] | def execute_nvm_command(self, command):
"""
Executes an NVM COMMAND on the NVM CTRL
:param command: command to execute
"""
self.logger.debug("NVMCMD %d executing", command)
return self.readwrite.write_byte(self.device.nvmctrl_address + constants.UPDI_NVMCTRL_CTRLA, command) | [
"def",
"execute_nvm_command",
"(",
"self",
",",
"command",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"NVMCMD %d executing\"",
",",
"command",
")",
"return",
"self",
".",
"readwrite",
".",
"write_byte",
"(",
"self",
".",
"device",
".",
"nvmctrl_address",
"+",
"constants",
".",
"UPDI_NVMCTRL_CTRLA",
",",
"command",
")"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/serialupdi/nvm.py#L71-L77 | |
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/photos/__init__.py | python | CommentEntry.GetCommentId | (self) | return self.GetSelfLink().href.split('/')[-1] | Return the globally unique id of this comment | Return the globally unique id of this comment | [
"Return",
"the",
"globally",
"unique",
"id",
"of",
"this",
"comment"
] | def GetCommentId(self):
"""Return the globally unique id of this comment"""
return self.GetSelfLink().href.split('/')[-1] | [
"def",
"GetCommentId",
"(",
"self",
")",
":",
"return",
"self",
".",
"GetSelfLink",
"(",
")",
".",
"href",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/photos/__init__.py#L919-L921 | |
tensorflow/minigo | 6d89c202cdceaf449aefc3149ab2110d44f1a6a4 | ratings/rate_subdir.py | python | fancyprint_ratings | (ids, ratings, results=None) | Prints the dictionary given in `ratings` with fancy headings.
Optional arg `results` is the individual pairs of (winner_id, loser_id).
If passed, this function will also print the W/L records of each player. | Prints the dictionary given in `ratings` with fancy headings. | [
"Prints",
"the",
"dictionary",
"given",
"in",
"ratings",
"with",
"fancy",
"headings",
"."
] | def fancyprint_ratings(ids, ratings, results=None):
"""Prints the dictionary given in `ratings` with fancy headings.
Optional arg `results` is the individual pairs of (winner_id, loser_id).
If passed, this function will also print the W/L records of each player.
"""
player_lookup = {v:k for k, v in ids.items()}
HEADER = "\n{:<25s}{:>8s}{:>8s}{:>8}{:>7}-{:<8}"
ROW = "{:<25.23s} {:6.0f} {:6.0f} {:>6d} {:>6d}-{:<6d}"
sorted_ratings = sorted(
ratings.items(), key=lambda i: i[1][0], reverse=True)
# If we don't have win-loss results, just summarize the ratings of the
# players and bail.
if not results:
for pid, (rating, sigma) in sorted_ratings:
print("{:25s}\t{:5.1f}\t{:5.1f}".format(player_lookup[pid], rating, sigma))
return
wins = {pid : sum([1 for r in results if r[0] == pid]) for pid in ids.values()}
losses = {pid : sum([1 for r in results if r[1] == pid]) for pid in ids.values()}
print("\n{} games played among {} players\n".format(len(results), len(ids)))
print(HEADER.format("Name", "Rating", "Error", "Games", "Win", "Loss"))
max_r = max(v[0] for v in ratings.values())
for pid, (rating, sigma) in sorted_ratings:
if rating != max_r:
rating -= max_r
print(ROW.format(player_lookup[pid], rating, sigma,
wins[pid] + losses[pid], wins[pid], losses[pid]))
print("\n") | [
"def",
"fancyprint_ratings",
"(",
"ids",
",",
"ratings",
",",
"results",
"=",
"None",
")",
":",
"player_lookup",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"ids",
".",
"items",
"(",
")",
"}",
"HEADER",
"=",
"\"\\n{:<25s}{:>8s}{:>8s}{:>8}{:>7}-{:<8}\"",
"ROW",
"=",
"\"{:<25.23s} {:6.0f} {:6.0f} {:>6d} {:>6d}-{:<6d}\"",
"sorted_ratings",
"=",
"sorted",
"(",
"ratings",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"i",
":",
"i",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"reverse",
"=",
"True",
")",
"# If we don't have win-loss results, just summarize the ratings of the",
"# players and bail.",
"if",
"not",
"results",
":",
"for",
"pid",
",",
"(",
"rating",
",",
"sigma",
")",
"in",
"sorted_ratings",
":",
"print",
"(",
"\"{:25s}\\t{:5.1f}\\t{:5.1f}\"",
".",
"format",
"(",
"player_lookup",
"[",
"pid",
"]",
",",
"rating",
",",
"sigma",
")",
")",
"return",
"wins",
"=",
"{",
"pid",
":",
"sum",
"(",
"[",
"1",
"for",
"r",
"in",
"results",
"if",
"r",
"[",
"0",
"]",
"==",
"pid",
"]",
")",
"for",
"pid",
"in",
"ids",
".",
"values",
"(",
")",
"}",
"losses",
"=",
"{",
"pid",
":",
"sum",
"(",
"[",
"1",
"for",
"r",
"in",
"results",
"if",
"r",
"[",
"1",
"]",
"==",
"pid",
"]",
")",
"for",
"pid",
"in",
"ids",
".",
"values",
"(",
")",
"}",
"print",
"(",
"\"\\n{} games played among {} players\\n\"",
".",
"format",
"(",
"len",
"(",
"results",
")",
",",
"len",
"(",
"ids",
")",
")",
")",
"print",
"(",
"HEADER",
".",
"format",
"(",
"\"Name\"",
",",
"\"Rating\"",
",",
"\"Error\"",
",",
"\"Games\"",
",",
"\"Win\"",
",",
"\"Loss\"",
")",
")",
"max_r",
"=",
"max",
"(",
"v",
"[",
"0",
"]",
"for",
"v",
"in",
"ratings",
".",
"values",
"(",
")",
")",
"for",
"pid",
",",
"(",
"rating",
",",
"sigma",
")",
"in",
"sorted_ratings",
":",
"if",
"rating",
"!=",
"max_r",
":",
"rating",
"-=",
"max_r",
"print",
"(",
"ROW",
".",
"format",
"(",
"player_lookup",
"[",
"pid",
"]",
",",
"rating",
",",
"sigma",
",",
"wins",
"[",
"pid",
"]",
"+",
"losses",
"[",
"pid",
"]",
",",
"wins",
"[",
"pid",
"]",
",",
"losses",
"[",
"pid",
"]",
")",
")",
"print",
"(",
"\"\\n\"",
")"
] | https://github.com/tensorflow/minigo/blob/6d89c202cdceaf449aefc3149ab2110d44f1a6a4/ratings/rate_subdir.py#L72-L103 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PGProperty.OnSetValue | (*args, **kwargs) | return _propgrid.PGProperty_OnSetValue(*args, **kwargs) | OnSetValue(self) | OnSetValue(self) | [
"OnSetValue",
"(",
"self",
")"
] | def OnSetValue(*args, **kwargs):
"""OnSetValue(self)"""
return _propgrid.PGProperty_OnSetValue(*args, **kwargs) | [
"def",
"OnSetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_OnSetValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L360-L362 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/aui/auibook.py | python | AuiTabCtrl.OnRightDown | (self, event) | Handles the ``wx.EVT_RIGHT_DOWN`` event for :class:`AuiTabCtrl`.
:param `event`: a :class:`MouseEvent` event to be processed. | Handles the ``wx.EVT_RIGHT_DOWN`` event for :class:`AuiTabCtrl`. | [
"Handles",
"the",
"wx",
".",
"EVT_RIGHT_DOWN",
"event",
"for",
":",
"class",
":",
"AuiTabCtrl",
"."
] | def OnRightDown(self, event):
"""
Handles the ``wx.EVT_RIGHT_DOWN`` event for :class:`AuiTabCtrl`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
x, y = event.GetX(), event.GetY()
wnd = self.TabHitTest(x, y)
if wnd:
e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_DOWN, self.GetId())
e.SetEventObject(self)
e.SetSelection(self.GetIdxFromWindow(wnd))
e.Page = wnd
self.GetEventHandler().ProcessEvent(e)
elif not self.ButtonHitTest(x, y):
e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BG_RIGHT_DOWN, self.GetId())
e.SetEventObject(self)
self.GetEventHandler().ProcessEvent(e) | [
"def",
"OnRightDown",
"(",
"self",
",",
"event",
")",
":",
"x",
",",
"y",
"=",
"event",
".",
"GetX",
"(",
")",
",",
"event",
".",
"GetY",
"(",
")",
"wnd",
"=",
"self",
".",
"TabHitTest",
"(",
"x",
",",
"y",
")",
"if",
"wnd",
":",
"e",
"=",
"AuiNotebookEvent",
"(",
"wxEVT_COMMAND_AUINOTEBOOK_TAB_RIGHT_DOWN",
",",
"self",
".",
"GetId",
"(",
")",
")",
"e",
".",
"SetEventObject",
"(",
"self",
")",
"e",
".",
"SetSelection",
"(",
"self",
".",
"GetIdxFromWindow",
"(",
"wnd",
")",
")",
"e",
".",
"Page",
"=",
"wnd",
"self",
".",
"GetEventHandler",
"(",
")",
".",
"ProcessEvent",
"(",
"e",
")",
"elif",
"not",
"self",
".",
"ButtonHitTest",
"(",
"x",
",",
"y",
")",
":",
"e",
"=",
"AuiNotebookEvent",
"(",
"wxEVT_COMMAND_AUINOTEBOOK_BG_RIGHT_DOWN",
",",
"self",
".",
"GetId",
"(",
")",
")",
"e",
".",
"SetEventObject",
"(",
"self",
")",
"self",
".",
"GetEventHandler",
"(",
")",
".",
"ProcessEvent",
"(",
"e",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L2108-L2127 | ||
ComputationalRadiationPhysics/picongpu | 59e9b53605f9a5c1bf271eeb055bc74370a99052 | src/tools/bin/smooth.py | python | smooth | (x, sigma, window_len=11, fkt=gaussWindow) | return y[overlap:len(y)-overlap] | A function that returns smoothed 1D-data from given data.
Parameters:
-----------
x - numpy.ndarray (1D)
original (noisy) data
sigma - float
standard deviation used by the window function 'fkt'
window_len - int (optinal)
number of bins used for the window function 'fkt'
default: 11 bins
fkt - function (optional)
window function used for smoothing
default: smooth.gaussWindow
Returns:
--------
returns smoothed data with samle length as x | A function that returns smoothed 1D-data from given data. | [
"A",
"function",
"that",
"returns",
"smoothed",
"1D",
"-",
"data",
"from",
"given",
"data",
"."
] | def smooth(x, sigma, window_len=11, fkt=gaussWindow):
"""
A function that returns smoothed 1D-data from given data.
Parameters:
-----------
x - numpy.ndarray (1D)
original (noisy) data
sigma - float
standard deviation used by the window function 'fkt'
window_len - int (optinal)
number of bins used for the window function 'fkt'
default: 11 bins
fkt - function (optional)
window function used for smoothing
default: smooth.gaussWindow
Returns:
--------
returns smoothed data with samle length as x
"""
# check input:
if type(x) != np.ndarray:
error_msg = "ERROR: input needs to by a 1D numpy array. " + \
"Data type is {}".format(type(x))
raise Exception(error_msg)
if len(x.shape) != 1:
# not a 1D array
error_msg = "ERROR: input needs to by a 1D numpy array. " + \
"Data shape is {}".format(x.shape)
raise Exception(error_msg)
# extending the data at the beginning and at the end
# to apply the window at the borders
s = np.r_[x[window_len-1:0:-1], x, x[-1:-window_len:-1]]
w = fkt(window_len, sigma) # compute window values
# smooth data by convolution with window function
# smoothed data with borders
y = np.convolve(w/w.sum(), s, mode='valid')
# usually window_len is odd, and int-devision is used
overlap = window_len//2
return y[overlap:len(y)-overlap] | [
"def",
"smooth",
"(",
"x",
",",
"sigma",
",",
"window_len",
"=",
"11",
",",
"fkt",
"=",
"gaussWindow",
")",
":",
"# check input:",
"if",
"type",
"(",
"x",
")",
"!=",
"np",
".",
"ndarray",
":",
"error_msg",
"=",
"\"ERROR: input needs to by a 1D numpy array. \"",
"+",
"\"Data type is {}\"",
".",
"format",
"(",
"type",
"(",
"x",
")",
")",
"raise",
"Exception",
"(",
"error_msg",
")",
"if",
"len",
"(",
"x",
".",
"shape",
")",
"!=",
"1",
":",
"# not a 1D array",
"error_msg",
"=",
"\"ERROR: input needs to by a 1D numpy array. \"",
"+",
"\"Data shape is {}\"",
".",
"format",
"(",
"x",
".",
"shape",
")",
"raise",
"Exception",
"(",
"error_msg",
")",
"# extending the data at the beginning and at the end",
"# to apply the window at the borders",
"s",
"=",
"np",
".",
"r_",
"[",
"x",
"[",
"window_len",
"-",
"1",
":",
"0",
":",
"-",
"1",
"]",
",",
"x",
",",
"x",
"[",
"-",
"1",
":",
"-",
"window_len",
":",
"-",
"1",
"]",
"]",
"w",
"=",
"fkt",
"(",
"window_len",
",",
"sigma",
")",
"# compute window values",
"# smooth data by convolution with window function",
"# smoothed data with borders",
"y",
"=",
"np",
".",
"convolve",
"(",
"w",
"/",
"w",
".",
"sum",
"(",
")",
",",
"s",
",",
"mode",
"=",
"'valid'",
")",
"# usually window_len is odd, and int-devision is used",
"overlap",
"=",
"window_len",
"//",
"2",
"return",
"y",
"[",
"overlap",
":",
"len",
"(",
"y",
")",
"-",
"overlap",
"]"
] | https://github.com/ComputationalRadiationPhysics/picongpu/blob/59e9b53605f9a5c1bf271eeb055bc74370a99052/src/tools/bin/smooth.py#L107-L153 | |
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/276.paint-fence.py | python | Solution.numWays | (self, n, k) | return f[n] | :type n: int
:type k: int
:rtype: int | :type n: int
:type k: int
:rtype: int | [
":",
"type",
"n",
":",
"int",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"int"
] | def numWays(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if n == 0 or k == 0:
return 0
if n == 1:
return k
f = [0 for _ in range(n + 1)]
f[1] = k
f[2] = k * k
for i in range(3, n + 1):
f[i] = (k - 1) * f[i - 1] + (k - 1) * f[i - 2]
return f[n] | [
"def",
"numWays",
"(",
"self",
",",
"n",
",",
"k",
")",
":",
"if",
"n",
"==",
"0",
"or",
"k",
"==",
"0",
":",
"return",
"0",
"if",
"n",
"==",
"1",
":",
"return",
"k",
"f",
"=",
"[",
"0",
"for",
"_",
"in",
"range",
"(",
"n",
"+",
"1",
")",
"]",
"f",
"[",
"1",
"]",
"=",
"k",
"f",
"[",
"2",
"]",
"=",
"k",
"*",
"k",
"for",
"i",
"in",
"range",
"(",
"3",
",",
"n",
"+",
"1",
")",
":",
"f",
"[",
"i",
"]",
"=",
"(",
"k",
"-",
"1",
")",
"*",
"f",
"[",
"i",
"-",
"1",
"]",
"+",
"(",
"k",
"-",
"1",
")",
"*",
"f",
"[",
"i",
"-",
"2",
"]",
"return",
"f",
"[",
"n",
"]"
] | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/276.paint-fence.py#L3-L23 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/quantize/python/graph_matcher.py | python | GraphMatcher.match_graph | (self, graph) | Matches each operation in `graph` against `self._pattern`.
Args:
graph: `tf.Graph` containing operations to match.
Yields:
`MatchResult` for each `tf.Operation` in `graph` that matches the pattern. | Matches each operation in `graph` against `self._pattern`. | [
"Matches",
"each",
"operation",
"in",
"graph",
"against",
"self",
".",
"_pattern",
"."
] | def match_graph(self, graph):
"""Matches each operation in `graph` against `self._pattern`.
Args:
graph: `tf.Graph` containing operations to match.
Yields:
`MatchResult` for each `tf.Operation` in `graph` that matches the pattern.
"""
# Python 3.3.2+ implements `yield from`, but for now:
for match_result in self.match_ops(graph.get_operations()):
yield match_result | [
"def",
"match_graph",
"(",
"self",
",",
"graph",
")",
":",
"# Python 3.3.2+ implements `yield from`, but for now:",
"for",
"match_result",
"in",
"self",
".",
"match_ops",
"(",
"graph",
".",
"get_operations",
"(",
")",
")",
":",
"yield",
"match_result"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/quantize/python/graph_matcher.py#L189-L200 | ||
NetSys/bess | ae52fc5804290fc3116daf2aef52226fafcedf5d | bin/dpdk-devbind.py | python | has_driver | (dev_id) | return "Driver_str" in devices[dev_id] | return true if a device is assigned to a driver. False otherwise | return true if a device is assigned to a driver. False otherwise | [
"return",
"true",
"if",
"a",
"device",
"is",
"assigned",
"to",
"a",
"driver",
".",
"False",
"otherwise"
] | def has_driver(dev_id):
'''return true if a device is assigned to a driver. False otherwise'''
return "Driver_str" in devices[dev_id] | [
"def",
"has_driver",
"(",
"dev_id",
")",
":",
"return",
"\"Driver_str\"",
"in",
"devices",
"[",
"dev_id",
"]"
] | https://github.com/NetSys/bess/blob/ae52fc5804290fc3116daf2aef52226fafcedf5d/bin/dpdk-devbind.py#L227-L229 | |
luliyucoordinate/Leetcode | 96afcdc54807d1d184e881a075d1dbf3371e31fb | src/0061-Rotate-List/0061.py | python | Solution.rotateRight | (self, head, k) | return ret | :type head: ListNode
:type k: int
:rtype: ListNode | :type head: ListNode
:type k: int
:rtype: ListNode | [
":",
"type",
"head",
":",
"ListNode",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"ListNode"
] | def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head == None or head.next == None:
return head
pre = head
count = 1
while pre.next != None:
count += 1
pre = pre.next
pre.next = head
n = count - k%count
q = pre
for _ in range(n):
q = q.next
ret = q.next
q.next = None
return ret | [
"def",
"rotateRight",
"(",
"self",
",",
"head",
",",
"k",
")",
":",
"if",
"head",
"==",
"None",
"or",
"head",
".",
"next",
"==",
"None",
":",
"return",
"head",
"pre",
"=",
"head",
"count",
"=",
"1",
"while",
"pre",
".",
"next",
"!=",
"None",
":",
"count",
"+=",
"1",
"pre",
"=",
"pre",
".",
"next",
"pre",
".",
"next",
"=",
"head",
"n",
"=",
"count",
"-",
"k",
"%",
"count",
"q",
"=",
"pre",
"for",
"_",
"in",
"range",
"(",
"n",
")",
":",
"q",
"=",
"q",
".",
"next",
"ret",
"=",
"q",
".",
"next",
"q",
".",
"next",
"=",
"None",
"return",
"ret"
] | https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0061-Rotate-List/0061.py#L8-L32 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/StructuralMechanicsApplication/python_scripts/structural_mechanics_solver.py | python | MechanicalSolver.ImportModelPart | (self) | This function imports the ModelPart | This function imports the ModelPart | [
"This",
"function",
"imports",
"the",
"ModelPart"
] | def ImportModelPart(self):
"""This function imports the ModelPart
"""
self._ImportModelPart(self.main_model_part, self.settings["model_import_settings"]) | [
"def",
"ImportModelPart",
"(",
"self",
")",
":",
"self",
".",
"_ImportModelPart",
"(",
"self",
".",
"main_model_part",
",",
"self",
".",
"settings",
"[",
"\"model_import_settings\"",
"]",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/StructuralMechanicsApplication/python_scripts/structural_mechanics_solver.py#L214-L217 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/vala.py | python | options | (opt) | Load the :py:mod:`waflib.Tools.gnu_dirs` tool and add the ``--vala-target-glib`` command-line option | Load the :py:mod:`waflib.Tools.gnu_dirs` tool and add the ``--vala-target-glib`` command-line option | [
"Load",
"the",
":",
"py",
":",
"mod",
":",
"waflib",
".",
"Tools",
".",
"gnu_dirs",
"tool",
"and",
"add",
"the",
"--",
"vala",
"-",
"target",
"-",
"glib",
"command",
"-",
"line",
"option"
] | def options(opt):
"""
Load the :py:mod:`waflib.Tools.gnu_dirs` tool and add the ``--vala-target-glib`` command-line option
"""
opt.load('gnu_dirs')
valaopts = opt.add_option_group('Vala Compiler Options')
valaopts.add_option ('--vala-target-glib', default=None,
dest='vala_target_glib', metavar='MAJOR.MINOR',
help='Target version of glib for Vala GObject code generation') | [
"def",
"options",
"(",
"opt",
")",
":",
"opt",
".",
"load",
"(",
"'gnu_dirs'",
")",
"valaopts",
"=",
"opt",
".",
"add_option_group",
"(",
"'Vala Compiler Options'",
")",
"valaopts",
".",
"add_option",
"(",
"'--vala-target-glib'",
",",
"default",
"=",
"None",
",",
"dest",
"=",
"'vala_target_glib'",
",",
"metavar",
"=",
"'MAJOR.MINOR'",
",",
"help",
"=",
"'Target version of glib for Vala GObject code generation'",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/vala.py#L323-L331 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/learn/python/learn/estimators/estimator.py | python | BaseEstimator._get_predict_ops | (self, features) | Method that builds model graph and returns prediction ops.
Args:
features: `Tensor` or `dict` of `Tensor` objects.
Returns:
predictions: `Tensor` or `dict` of `Tensor` objects. | Method that builds model graph and returns prediction ops. | [
"Method",
"that",
"builds",
"model",
"graph",
"and",
"returns",
"prediction",
"ops",
"."
] | def _get_predict_ops(self, features):
"""Method that builds model graph and returns prediction ops.
Args:
features: `Tensor` or `dict` of `Tensor` objects.
Returns:
predictions: `Tensor` or `dict` of `Tensor` objects.
"""
pass | [
"def",
"_get_predict_ops",
"(",
"self",
",",
"features",
")",
":",
"pass"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L544-L553 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/instrument_interval.py | python | InstrumentInterval.symbols | (self) | return self._symbols | Gets the symbols of this InstrumentInterval. # noqa: E501
:return: The symbols of this InstrumentInterval. # noqa: E501
:rtype: list[str] | Gets the symbols of this InstrumentInterval. # noqa: E501 | [
"Gets",
"the",
"symbols",
"of",
"this",
"InstrumentInterval",
".",
"#",
"noqa",
":",
"E501"
] | def symbols(self):
"""Gets the symbols of this InstrumentInterval. # noqa: E501
:return: The symbols of this InstrumentInterval. # noqa: E501
:rtype: list[str]
"""
return self._symbols | [
"def",
"symbols",
"(",
"self",
")",
":",
"return",
"self",
".",
"_symbols"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/instrument_interval.py#L77-L84 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/hang_analyzer.py | python | check_dump_quota | (quota, ext) | return (size_sum <= quota) | Check if sum of the files with ext is within the specified quota in megabytes | Check if sum of the files with ext is within the specified quota in megabytes | [
"Check",
"if",
"sum",
"of",
"the",
"files",
"with",
"ext",
"is",
"within",
"the",
"specified",
"quota",
"in",
"megabytes"
] | def check_dump_quota(quota, ext):
"""Check if sum of the files with ext is within the specified quota in megabytes"""
files = glob.glob("*." + ext)
size_sum = 0
for file_name in files:
size_sum += os.path.getsize(file_name)
return (size_sum <= quota) | [
"def",
"check_dump_quota",
"(",
"quota",
",",
"ext",
")",
":",
"files",
"=",
"glob",
".",
"glob",
"(",
"\"*.\"",
"+",
"ext",
")",
"size_sum",
"=",
"0",
"for",
"file_name",
"in",
"files",
":",
"size_sum",
"+=",
"os",
".",
"path",
".",
"getsize",
"(",
"file_name",
")",
"return",
"(",
"size_sum",
"<=",
"quota",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/hang_analyzer.py#L502-L511 | |
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/module/qat/quant_dequant.py | python | QuantStub.from_float_module | (cls, float_module: Float.QuantStub) | return cls(name=float_module.name) | r"""
Return a :class:`~.QATModule` instance converted from
a float :class:`~.Module` instance. | r"""
Return a :class:`~.QATModule` instance converted from
a float :class:`~.Module` instance. | [
"r",
"Return",
"a",
":",
"class",
":",
"~",
".",
"QATModule",
"instance",
"converted",
"from",
"a",
"float",
":",
"class",
":",
"~",
".",
"Module",
"instance",
"."
] | def from_float_module(cls, float_module: Float.QuantStub):
r"""
Return a :class:`~.QATModule` instance converted from
a float :class:`~.Module` instance.
"""
return cls(name=float_module.name) | [
"def",
"from_float_module",
"(",
"cls",
",",
"float_module",
":",
"Float",
".",
"QuantStub",
")",
":",
"return",
"cls",
"(",
"name",
"=",
"float_module",
".",
"name",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/module/qat/quant_dequant.py#L23-L28 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | SystemOptions_SetOptionInt | (*args, **kwargs) | return _misc_.SystemOptions_SetOptionInt(*args, **kwargs) | SystemOptions_SetOptionInt(String name, int value) | SystemOptions_SetOptionInt(String name, int value) | [
"SystemOptions_SetOptionInt",
"(",
"String",
"name",
"int",
"value",
")"
] | def SystemOptions_SetOptionInt(*args, **kwargs):
"""SystemOptions_SetOptionInt(String name, int value)"""
return _misc_.SystemOptions_SetOptionInt(*args, **kwargs) | [
"def",
"SystemOptions_SetOptionInt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"SystemOptions_SetOptionInt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L259-L261 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/aui.py | python | AuiDefaultDockArt.__init__ | (self, *args, **kwargs) | __init__(self) -> AuiDefaultDockArt | __init__(self) -> AuiDefaultDockArt | [
"__init__",
"(",
"self",
")",
"-",
">",
"AuiDefaultDockArt"
] | def __init__(self, *args, **kwargs):
"""__init__(self) -> AuiDefaultDockArt"""
_aui.AuiDefaultDockArt_swiginit(self,_aui.new_AuiDefaultDockArt(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_aui",
".",
"AuiDefaultDockArt_swiginit",
"(",
"self",
",",
"_aui",
".",
"new_AuiDefaultDockArt",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L1031-L1033 | ||
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/trade.py | python | Trade.tick_direction | (self, tick_direction) | Sets the tick_direction of this Trade.
:param tick_direction: The tick_direction of this Trade. # noqa: E501
:type: str | Sets the tick_direction of this Trade. | [
"Sets",
"the",
"tick_direction",
"of",
"this",
"Trade",
"."
] | def tick_direction(self, tick_direction):
"""Sets the tick_direction of this Trade.
:param tick_direction: The tick_direction of this Trade. # noqa: E501
:type: str
"""
self._tick_direction = tick_direction | [
"def",
"tick_direction",
"(",
"self",
",",
"tick_direction",
")",
":",
"self",
".",
"_tick_direction",
"=",
"tick_direction"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/trade.py#L213-L221 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/math/so3.py | python | align | (a : Vector3, b : Vector3) | return vectorops.madd(vectorops.add(identity(),vhat),vhat2,1.0/(1.0+c)) | Returns a minimal-angle rotation that aligns the vector a to align with
the vector b. Both a and b must be nonzero. | Returns a minimal-angle rotation that aligns the vector a to align with
the vector b. Both a and b must be nonzero. | [
"Returns",
"a",
"minimal",
"-",
"angle",
"rotation",
"that",
"aligns",
"the",
"vector",
"a",
"to",
"align",
"with",
"the",
"vector",
"b",
".",
"Both",
"a",
"and",
"b",
"must",
"be",
"nonzero",
"."
] | def align(a : Vector3, b : Vector3) -> Rotation:
"""Returns a minimal-angle rotation that aligns the vector a to align with
the vector b. Both a and b must be nonzero."""
an = vectorops.norm(a)
bn = vectorops.norm(b)
if abs(an) < 1e-5 or abs(bn) < 1e-5:
return identity()
a = vectorops.mul(a,1.0/an)
b = vectorops.mul(b,1.0/bn)
v = vectorops.cross(a,b)
c = vectorops.dot(a,b)
if abs(c+1)<1e-5: #rotation of pi
v = vectorops.cross(a,[0,0,1])
vn = vectorops.norm(v)
if vn < 1e-5:
v = vectorops.cross(a,[0,1,0])
vn = vectorops.norm(v)
return rotation(vectorops.mul(v,1.0/vn),math.pi)
vhat = cross_product(v)
vhat2 = mul(vhat,vhat)
return vectorops.madd(vectorops.add(identity(),vhat),vhat2,1.0/(1.0+c)) | [
"def",
"align",
"(",
"a",
":",
"Vector3",
",",
"b",
":",
"Vector3",
")",
"->",
"Rotation",
":",
"an",
"=",
"vectorops",
".",
"norm",
"(",
"a",
")",
"bn",
"=",
"vectorops",
".",
"norm",
"(",
"b",
")",
"if",
"abs",
"(",
"an",
")",
"<",
"1e-5",
"or",
"abs",
"(",
"bn",
")",
"<",
"1e-5",
":",
"return",
"identity",
"(",
")",
"a",
"=",
"vectorops",
".",
"mul",
"(",
"a",
",",
"1.0",
"/",
"an",
")",
"b",
"=",
"vectorops",
".",
"mul",
"(",
"b",
",",
"1.0",
"/",
"bn",
")",
"v",
"=",
"vectorops",
".",
"cross",
"(",
"a",
",",
"b",
")",
"c",
"=",
"vectorops",
".",
"dot",
"(",
"a",
",",
"b",
")",
"if",
"abs",
"(",
"c",
"+",
"1",
")",
"<",
"1e-5",
":",
"#rotation of pi",
"v",
"=",
"vectorops",
".",
"cross",
"(",
"a",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
")",
"vn",
"=",
"vectorops",
".",
"norm",
"(",
"v",
")",
"if",
"vn",
"<",
"1e-5",
":",
"v",
"=",
"vectorops",
".",
"cross",
"(",
"a",
",",
"[",
"0",
",",
"1",
",",
"0",
"]",
")",
"vn",
"=",
"vectorops",
".",
"norm",
"(",
"v",
")",
"return",
"rotation",
"(",
"vectorops",
".",
"mul",
"(",
"v",
",",
"1.0",
"/",
"vn",
")",
",",
"math",
".",
"pi",
")",
"vhat",
"=",
"cross_product",
"(",
"v",
")",
"vhat2",
"=",
"mul",
"(",
"vhat",
",",
"vhat",
")",
"return",
"vectorops",
".",
"madd",
"(",
"vectorops",
".",
"add",
"(",
"identity",
"(",
")",
",",
"vhat",
")",
",",
"vhat2",
",",
"1.0",
"/",
"(",
"1.0",
"+",
"c",
")",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/so3.py#L349-L369 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/client/timeline.py | python | _TensorTracker.object_id | (self) | return self._object_id | Returns the object identifier of this tensor (integer). | Returns the object identifier of this tensor (integer). | [
"Returns",
"the",
"object",
"identifier",
"of",
"this",
"tensor",
"(",
"integer",
")",
"."
] | def object_id(self):
"""Returns the object identifier of this tensor (integer)."""
return self._object_id | [
"def",
"object_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_object_id"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/client/timeline.py#L310-L312 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | build/pymake/pymake/data.py | python | Target.isphony | (self, makefile) | return makefile.gettarget('.PHONY').hasdependency(self.target) | Is this a phony target? We don't check for existence of phony targets. | Is this a phony target? We don't check for existence of phony targets. | [
"Is",
"this",
"a",
"phony",
"target?",
"We",
"don",
"t",
"check",
"for",
"existence",
"of",
"phony",
"targets",
"."
] | def isphony(self, makefile):
"""Is this a phony target? We don't check for existence of phony targets."""
return makefile.gettarget('.PHONY').hasdependency(self.target) | [
"def",
"isphony",
"(",
"self",
",",
"makefile",
")",
":",
"return",
"makefile",
".",
"gettarget",
"(",
"'.PHONY'",
")",
".",
"hasdependency",
"(",
"self",
".",
"target",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/build/pymake/pymake/data.py#L1004-L1006 | |
xiaohaoChen/rrc_detection | 4f2b110cd122da7f55e8533275a9b4809a88785a | scripts/cpp_lint.py | python | PrintCategories | () | Prints a list of all the error-categories used by error messages.
These are the categories used to filter messages via --filter. | Prints a list of all the error-categories used by error messages. | [
"Prints",
"a",
"list",
"of",
"all",
"the",
"error",
"-",
"categories",
"used",
"by",
"error",
"messages",
"."
] | def PrintCategories():
"""Prints a list of all the error-categories used by error messages.
These are the categories used to filter messages via --filter.
"""
sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
sys.exit(0) | [
"def",
"PrintCategories",
"(",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"''",
".",
"join",
"(",
"' %s\\n'",
"%",
"cat",
"for",
"cat",
"in",
"_ERROR_CATEGORIES",
")",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | https://github.com/xiaohaoChen/rrc_detection/blob/4f2b110cd122da7f55e8533275a9b4809a88785a/scripts/cpp_lint.py#L4774-L4780 | ||
GoSSIP-SJTU/TripleDoggy | 03648d6b19c812504b14e8b98c8c7b3f443f4e54 | bindings/python/llvm/common.py | python | LLVMObject.take_ownership | (self, obj) | Take ownership of another object.
When you take ownership of another object, you are responsible for
destroying that object. In addition, a reference to that object is
placed inside this object so the Python garbage collector will not
collect the object while it is still alive in libLLVM.
This method should likely only be called from within modules inside
this package. | Take ownership of another object. | [
"Take",
"ownership",
"of",
"another",
"object",
"."
] | def take_ownership(self, obj):
"""Take ownership of another object.
When you take ownership of another object, you are responsible for
destroying that object. In addition, a reference to that object is
placed inside this object so the Python garbage collector will not
collect the object while it is still alive in libLLVM.
This method should likely only be called from within modules inside
this package.
"""
assert isinstance(obj, LLVMObject)
self._owned_objects.append(obj)
obj._self_owned = False | [
"def",
"take_ownership",
"(",
"self",
",",
"obj",
")",
":",
"assert",
"isinstance",
"(",
"obj",
",",
"LLVMObject",
")",
"self",
".",
"_owned_objects",
".",
"append",
"(",
"obj",
")",
"obj",
".",
"_self_owned",
"=",
"False"
] | https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/bindings/python/llvm/common.py#L44-L58 | ||
TimoSaemann/caffe-segnet-cudnn5 | abcf30dca449245e101bf4ced519f716177f0885 | python/caffe/net_spec.py | python | assign_proto | (proto, name, val) | Assign a Python object to a protobuf message, based on the Python
type (in recursive fashion). Lists become repeated fields/messages, dicts
become messages, and other types are assigned directly. For convenience,
repeated fields whose values are not lists are converted to single-element
lists; e.g., `my_repeated_int_field=3` is converted to
`my_repeated_int_field=[3]`. | Assign a Python object to a protobuf message, based on the Python
type (in recursive fashion). Lists become repeated fields/messages, dicts
become messages, and other types are assigned directly. For convenience,
repeated fields whose values are not lists are converted to single-element
lists; e.g., `my_repeated_int_field=3` is converted to
`my_repeated_int_field=[3]`. | [
"Assign",
"a",
"Python",
"object",
"to",
"a",
"protobuf",
"message",
"based",
"on",
"the",
"Python",
"type",
"(",
"in",
"recursive",
"fashion",
")",
".",
"Lists",
"become",
"repeated",
"fields",
"/",
"messages",
"dicts",
"become",
"messages",
"and",
"other",
"types",
"are",
"assigned",
"directly",
".",
"For",
"convenience",
"repeated",
"fields",
"whose",
"values",
"are",
"not",
"lists",
"are",
"converted",
"to",
"single",
"-",
"element",
"lists",
";",
"e",
".",
"g",
".",
"my_repeated_int_field",
"=",
"3",
"is",
"converted",
"to",
"my_repeated_int_field",
"=",
"[",
"3",
"]",
"."
] | def assign_proto(proto, name, val):
"""Assign a Python object to a protobuf message, based on the Python
type (in recursive fashion). Lists become repeated fields/messages, dicts
become messages, and other types are assigned directly. For convenience,
repeated fields whose values are not lists are converted to single-element
lists; e.g., `my_repeated_int_field=3` is converted to
`my_repeated_int_field=[3]`."""
is_repeated_field = hasattr(getattr(proto, name), 'extend')
if is_repeated_field and not isinstance(val, list):
val = [val]
if isinstance(val, list):
if isinstance(val[0], dict):
for item in val:
proto_item = getattr(proto, name).add()
for k, v in six.iteritems(item):
assign_proto(proto_item, k, v)
else:
getattr(proto, name).extend(val)
elif isinstance(val, dict):
for k, v in six.iteritems(val):
assign_proto(getattr(proto, name), k, v)
else:
setattr(proto, name, val) | [
"def",
"assign_proto",
"(",
"proto",
",",
"name",
",",
"val",
")",
":",
"is_repeated_field",
"=",
"hasattr",
"(",
"getattr",
"(",
"proto",
",",
"name",
")",
",",
"'extend'",
")",
"if",
"is_repeated_field",
"and",
"not",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"val",
"=",
"[",
"val",
"]",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"if",
"isinstance",
"(",
"val",
"[",
"0",
"]",
",",
"dict",
")",
":",
"for",
"item",
"in",
"val",
":",
"proto_item",
"=",
"getattr",
"(",
"proto",
",",
"name",
")",
".",
"add",
"(",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"item",
")",
":",
"assign_proto",
"(",
"proto_item",
",",
"k",
",",
"v",
")",
"else",
":",
"getattr",
"(",
"proto",
",",
"name",
")",
".",
"extend",
"(",
"val",
")",
"elif",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"val",
")",
":",
"assign_proto",
"(",
"getattr",
"(",
"proto",
",",
"name",
")",
",",
"k",
",",
"v",
")",
"else",
":",
"setattr",
"(",
"proto",
",",
"name",
",",
"val",
")"
] | https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/python/caffe/net_spec.py#L56-L79 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/wizard.py | python | WizardEvent.__init__ | (self, *args, **kwargs) | __init__(self, EventType type=wxEVT_NULL, int id=-1, bool direction=True,
WizardPage page=None) -> WizardEvent | __init__(self, EventType type=wxEVT_NULL, int id=-1, bool direction=True,
WizardPage page=None) -> WizardEvent | [
"__init__",
"(",
"self",
"EventType",
"type",
"=",
"wxEVT_NULL",
"int",
"id",
"=",
"-",
"1",
"bool",
"direction",
"=",
"True",
"WizardPage",
"page",
"=",
"None",
")",
"-",
">",
"WizardEvent"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, EventType type=wxEVT_NULL, int id=-1, bool direction=True,
WizardPage page=None) -> WizardEvent
"""
_wizard.WizardEvent_swiginit(self,_wizard.new_WizardEvent(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_wizard",
".",
"WizardEvent_swiginit",
"(",
"self",
",",
"_wizard",
".",
"new_WizardEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/wizard.py#L90-L95 | ||
eomahony/Numberjack | 53fa9e994a36f881ffd320d8d04158097190aad8 | Numberjack/__init__.py | python | Expression.get_max | (self, solver=None) | return the_max | Current upper bound of variable.
:param `NBJ_STD_Solver` solver: If specified, the solver from which the
upper bound will be sourced, if `None` then the most recently loaded
solver is used.
:return: The current upper bound of the variable.
:rtype: The same as the original domain, either `int`, `float`, or
`str`. | Current upper bound of variable. | [
"Current",
"upper",
"bound",
"of",
"variable",
"."
] | def get_max(self, solver=None):
"""
Current upper bound of variable.
:param `NBJ_STD_Solver` solver: If specified, the solver from which the
upper bound will be sourced, if `None` then the most recently loaded
solver is used.
:return: The current upper bound of the variable.
:rtype: The same as the original domain, either `int`, `float`, or
`str`.
"""
the_max = self.ub
if solver is not None:
if self.is_built(solver):
the_max = self.var_list[solver.solver_id - 1].get_max()
elif self.is_built():
the_max = self.var_list[-1].get_max()
if self.is_str():
return self.model.strings[the_max]
return the_max | [
"def",
"get_max",
"(",
"self",
",",
"solver",
"=",
"None",
")",
":",
"the_max",
"=",
"self",
".",
"ub",
"if",
"solver",
"is",
"not",
"None",
":",
"if",
"self",
".",
"is_built",
"(",
"solver",
")",
":",
"the_max",
"=",
"self",
".",
"var_list",
"[",
"solver",
".",
"solver_id",
"-",
"1",
"]",
".",
"get_max",
"(",
")",
"elif",
"self",
".",
"is_built",
"(",
")",
":",
"the_max",
"=",
"self",
".",
"var_list",
"[",
"-",
"1",
"]",
".",
"get_max",
"(",
")",
"if",
"self",
".",
"is_str",
"(",
")",
":",
"return",
"self",
".",
"model",
".",
"strings",
"[",
"the_max",
"]",
"return",
"the_max"
] | https://github.com/eomahony/Numberjack/blob/53fa9e994a36f881ffd320d8d04158097190aad8/Numberjack/__init__.py#L494-L513 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/py3compat.py | python | get_func_code | (func) | Return function code object | Return function code object | [
"Return",
"function",
"code",
"object"
] | def get_func_code(func):
"""Return function code object"""
if PY2:
# Python 2
return func.func_code
else:
# Python 3
return func.__code__ | [
"def",
"get_func_code",
"(",
"func",
")",
":",
"if",
"PY2",
":",
"# Python 2",
"return",
"func",
".",
"func_code",
"else",
":",
"# Python 3",
"return",
"func",
".",
"__code__"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/py3compat.py#L147-L154 | ||
intel-iot-devkit/how-to-code-samples | b4ea616f36bbfa2e042beb1698f968cfd651d79f | equipment-activity-monitor/python/iot_equipment_activity_monitor/hardware/board.py | python | Board.add_event_handler | (self, event, handler, once=False) | Add hardware event handler. | Add hardware event handler. | [
"Add",
"hardware",
"event",
"handler",
"."
] | def add_event_handler(self, event, handler, once=False):
"""
Add hardware event handler.
"""
if once:
self.emitter.once(event, handler)
else:
self.emitter.on(event, handler) | [
"def",
"add_event_handler",
"(",
"self",
",",
"event",
",",
"handler",
",",
"once",
"=",
"False",
")",
":",
"if",
"once",
":",
"self",
".",
"emitter",
".",
"once",
"(",
"event",
",",
"handler",
")",
"else",
":",
"self",
".",
"emitter",
".",
"on",
"(",
"event",
",",
"handler",
")"
] | https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/equipment-activity-monitor/python/iot_equipment_activity_monitor/hardware/board.py#L75-L84 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/generator/analyzer.py | python | _ToGypPath | (path) | return path | Converts a path to the format used by gyp. | Converts a path to the format used by gyp. | [
"Converts",
"a",
"path",
"to",
"the",
"format",
"used",
"by",
"gyp",
"."
] | def _ToGypPath(path):
"""Converts a path to the format used by gyp."""
if os.sep == '\\' and os.altsep == '/':
return path.replace('\\', '/')
return path | [
"def",
"_ToGypPath",
"(",
"path",
")",
":",
"if",
"os",
".",
"sep",
"==",
"'\\\\'",
"and",
"os",
".",
"altsep",
"==",
"'/'",
":",
"return",
"path",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"return",
"path"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/analyzer.py#L112-L116 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | ListCtrl.SetStringItem | (*args, **kwargs) | return _controls_.ListCtrl_SetStringItem(*args, **kwargs) | SetStringItem(self, long index, int col, String label, int imageId=-1) -> long | SetStringItem(self, long index, int col, String label, int imageId=-1) -> long | [
"SetStringItem",
"(",
"self",
"long",
"index",
"int",
"col",
"String",
"label",
"int",
"imageId",
"=",
"-",
"1",
")",
"-",
">",
"long"
] | def SetStringItem(*args, **kwargs):
"""SetStringItem(self, long index, int col, String label, int imageId=-1) -> long"""
return _controls_.ListCtrl_SetStringItem(*args, **kwargs) | [
"def",
"SetStringItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl_SetStringItem",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4519-L4521 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.GetCaretForeground | (*args, **kwargs) | return _stc.StyledTextCtrl_GetCaretForeground(*args, **kwargs) | GetCaretForeground(self) -> Colour
Get the foreground colour of the caret. | GetCaretForeground(self) -> Colour | [
"GetCaretForeground",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetCaretForeground(*args, **kwargs):
"""
GetCaretForeground(self) -> Colour
Get the foreground colour of the caret.
"""
return _stc.StyledTextCtrl_GetCaretForeground(*args, **kwargs) | [
"def",
"GetCaretForeground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetCaretForeground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3404-L3410 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/json_schema_compiler/cc_generator.py | python | _Generator._GenerateFunction | (self, function) | return c | Generates the definitions for function structs. | Generates the definitions for function structs. | [
"Generates",
"the",
"definitions",
"for",
"function",
"structs",
"."
] | def _GenerateFunction(self, function):
"""Generates the definitions for function structs.
"""
c = Code()
# TODO(kalman): use function.unix_name not Classname.
function_namespace = cpp_util.Classname(function.name)
# Windows has a #define for SendMessage, so to avoid any issues, we need
# to not use the name.
if function_namespace == 'SendMessage':
function_namespace = 'PassMessage'
(c.Append('namespace %s {' % function_namespace)
.Append()
)
# Params::Populate function
if function.params:
c.Concat(self._GeneratePropertyFunctions('Params', function.params))
(c.Append('Params::Params() {}')
.Append('Params::~Params() {}')
.Append()
.Cblock(self._GenerateFunctionParamsCreate(function))
)
# Results::Create function
if function.callback:
c.Concat(self._GenerateCreateCallbackArguments('Results',
function.callback))
c.Append('} // namespace %s' % function_namespace)
return c | [
"def",
"_GenerateFunction",
"(",
"self",
",",
"function",
")",
":",
"c",
"=",
"Code",
"(",
")",
"# TODO(kalman): use function.unix_name not Classname.",
"function_namespace",
"=",
"cpp_util",
".",
"Classname",
"(",
"function",
".",
"name",
")",
"# Windows has a #define for SendMessage, so to avoid any issues, we need",
"# to not use the name.",
"if",
"function_namespace",
"==",
"'SendMessage'",
":",
"function_namespace",
"=",
"'PassMessage'",
"(",
"c",
".",
"Append",
"(",
"'namespace %s {'",
"%",
"function_namespace",
")",
".",
"Append",
"(",
")",
")",
"# Params::Populate function",
"if",
"function",
".",
"params",
":",
"c",
".",
"Concat",
"(",
"self",
".",
"_GeneratePropertyFunctions",
"(",
"'Params'",
",",
"function",
".",
"params",
")",
")",
"(",
"c",
".",
"Append",
"(",
"'Params::Params() {}'",
")",
".",
"Append",
"(",
"'Params::~Params() {}'",
")",
".",
"Append",
"(",
")",
".",
"Cblock",
"(",
"self",
".",
"_GenerateFunctionParamsCreate",
"(",
"function",
")",
")",
")",
"# Results::Create function",
"if",
"function",
".",
"callback",
":",
"c",
".",
"Concat",
"(",
"self",
".",
"_GenerateCreateCallbackArguments",
"(",
"'Results'",
",",
"function",
".",
"callback",
")",
")",
"c",
".",
"Append",
"(",
"'} // namespace %s'",
"%",
"function_namespace",
")",
"return",
"c"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_schema_compiler/cc_generator.py#L520-L550 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/apiclient/googleapiclient/channel.py | python | Notification.__init__ | (self, message_number, state, resource_uri, resource_id) | Notification constructor.
Args:
message_number: int, The unique id number of this notification.
state: str, The state of the resource being monitored. Can be one
of "exists", "not_exists", or "sync".
resource_uri: str, The address of the resource being monitored.
resource_id: str, The identifier of the watched resource. | Notification constructor. | [
"Notification",
"constructor",
"."
] | def __init__(self, message_number, state, resource_uri, resource_id):
"""Notification constructor.
Args:
message_number: int, The unique id number of this notification.
state: str, The state of the resource being monitored. Can be one
of "exists", "not_exists", or "sync".
resource_uri: str, The address of the resource being monitored.
resource_id: str, The identifier of the watched resource.
"""
self.message_number = message_number
self.state = state
self.resource_uri = resource_uri
self.resource_id = resource_id | [
"def",
"__init__",
"(",
"self",
",",
"message_number",
",",
"state",
",",
"resource_uri",
",",
"resource_id",
")",
":",
"self",
".",
"message_number",
"=",
"message_number",
"self",
".",
"state",
"=",
"state",
"self",
".",
"resource_uri",
"=",
"resource_uri",
"self",
".",
"resource_id",
"=",
"resource_id"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/apiclient/googleapiclient/channel.py#L112-L125 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_subelements.py | python | SubelementHighlight.proceed | (self) | Continue with the command. | Continue with the command. | [
"Continue",
"with",
"the",
"command",
"."
] | def proceed(self):
"""Continue with the command."""
self.remove_view_callback()
self.get_editable_objects_from_selection()
if not self.editable_objects:
return self.finish()
self.call = self.view.addEventCallback("SoEvent", self.action)
self.highlight_editable_objects() | [
"def",
"proceed",
"(",
"self",
")",
":",
"self",
".",
"remove_view_callback",
"(",
")",
"self",
".",
"get_editable_objects_from_selection",
"(",
")",
"if",
"not",
"self",
".",
"editable_objects",
":",
"return",
"self",
".",
"finish",
"(",
")",
"self",
".",
"call",
"=",
"self",
".",
"view",
".",
"addEventCallback",
"(",
"\"SoEvent\"",
",",
"self",
".",
"action",
")",
"self",
".",
"highlight_editable_objects",
"(",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_subelements.py#L72-L79 | ||
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | clang/tools/scan-build-py/lib/libscanbuild/analyze.py | python | prefix_with | (constant, pieces) | return [elem for piece in pieces for elem in [constant, piece]] | From a sequence create another sequence where every second element
is from the original sequence and the odd elements are the prefix.
eg.: prefix_with(0, [1,2,3]) creates [0, 1, 0, 2, 0, 3] | From a sequence create another sequence where every second element
is from the original sequence and the odd elements are the prefix. | [
"From",
"a",
"sequence",
"create",
"another",
"sequence",
"where",
"every",
"second",
"element",
"is",
"from",
"the",
"original",
"sequence",
"and",
"the",
"odd",
"elements",
"are",
"the",
"prefix",
"."
] | def prefix_with(constant, pieces):
""" From a sequence create another sequence where every second element
is from the original sequence and the odd elements are the prefix.
eg.: prefix_with(0, [1,2,3]) creates [0, 1, 0, 2, 0, 3] """
return [elem for piece in pieces for elem in [constant, piece]] | [
"def",
"prefix_with",
"(",
"constant",
",",
"pieces",
")",
":",
"return",
"[",
"elem",
"for",
"piece",
"in",
"pieces",
"for",
"elem",
"in",
"[",
"constant",
",",
"piece",
"]",
"]"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/tools/scan-build-py/lib/libscanbuild/analyze.py#L107-L113 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | catboost/benchmarks/training_speed/data_loader.py | python | abalone | (dataset_dir) | return X, y | https://archive.ics.uci.edu/ml/machine-learning-databases/abalone
TaskType:regression
NumberOfFeatures:8
NumberOfInstances:4177 | https://archive.ics.uci.edu/ml/machine-learning-databases/abalone | [
"https",
":",
"//",
"archive",
".",
"ics",
".",
"uci",
".",
"edu",
"/",
"ml",
"/",
"machine",
"-",
"learning",
"-",
"databases",
"/",
"abalone"
] | def abalone(dataset_dir):
"""
https://archive.ics.uci.edu/ml/machine-learning-databases/abalone
TaskType:regression
NumberOfFeatures:8
NumberOfInstances:4177
"""
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data'
filename = os.path.join(dataset_dir, 'abalone.data')
if not os.path.exists(filename):
urlretrieve(url, filename)
abalone = pd.read_csv(filename, header=None)
abalone[0] = abalone[0].astype('category').cat.codes
X = abalone.iloc[:, :-1].values
y = abalone.iloc[:, -1].values
return X, y | [
"def",
"abalone",
"(",
"dataset_dir",
")",
":",
"url",
"=",
"'https://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data'",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dataset_dir",
",",
"'abalone.data'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"urlretrieve",
"(",
"url",
",",
"filename",
")",
"abalone",
"=",
"pd",
".",
"read_csv",
"(",
"filename",
",",
"header",
"=",
"None",
")",
"abalone",
"[",
"0",
"]",
"=",
"abalone",
"[",
"0",
"]",
".",
"astype",
"(",
"'category'",
")",
".",
"cat",
".",
"codes",
"X",
"=",
"abalone",
".",
"iloc",
"[",
":",
",",
":",
"-",
"1",
"]",
".",
"values",
"y",
"=",
"abalone",
".",
"iloc",
"[",
":",
",",
"-",
"1",
"]",
".",
"values",
"return",
"X",
",",
"y"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/benchmarks/training_speed/data_loader.py#L168-L186 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/pavement.py | python | internal_wininst_name | (arch) | return "scipy-%s-%s%s" % (FULLVERSION, arch, ext) | Return the name of the wininst as it will be inside the superpack (i.e.
with the arch encoded. | Return the name of the wininst as it will be inside the superpack (i.e.
with the arch encoded. | [
"Return",
"the",
"name",
"of",
"the",
"wininst",
"as",
"it",
"will",
"be",
"inside",
"the",
"superpack",
"(",
"i",
".",
"e",
".",
"with",
"the",
"arch",
"encoded",
"."
] | def internal_wininst_name(arch):
"""Return the name of the wininst as it will be inside the superpack (i.e.
with the arch encoded."""
ext = '.exe'
return "scipy-%s-%s%s" % (FULLVERSION, arch, ext) | [
"def",
"internal_wininst_name",
"(",
"arch",
")",
":",
"ext",
"=",
"'.exe'",
"return",
"\"scipy-%s-%s%s\"",
"%",
"(",
"FULLVERSION",
",",
"arch",
",",
"ext",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/pavement.py#L377-L381 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/closure_compiler/compile2.py | python | Checker.check | (self, sources, out_file=None, runner_args=None, closure_args=None,
custom_sources=True) | return bool(errors), stderr | Closure compile |sources| while checking for errors.
Args:
sources: Files to check. sources[0] is the typically the target file.
sources[1:] are externs and dependencies in topological order. Order
is not guaranteed if custom_sources is True.
out_file: A file where the compiled output is written to.
runner_args: Arguments passed to runner.jar.
closure_args: Arguments passed directly to the Closure compiler.
custom_sources: Whether |sources| was customized by the target (e.g. not
in GYP dependency order).
Returns:
(found_errors, stderr) A boolean indicating whether errors were found and
the raw Closure compiler stderr (as a string). | Closure compile |sources| while checking for errors. | [
"Closure",
"compile",
"|sources|",
"while",
"checking",
"for",
"errors",
"."
] | def check(self, sources, out_file=None, runner_args=None, closure_args=None,
custom_sources=True):
"""Closure compile |sources| while checking for errors.
Args:
sources: Files to check. sources[0] is the typically the target file.
sources[1:] are externs and dependencies in topological order. Order
is not guaranteed if custom_sources is True.
out_file: A file where the compiled output is written to.
runner_args: Arguments passed to runner.jar.
closure_args: Arguments passed directly to the Closure compiler.
custom_sources: Whether |sources| was customized by the target (e.g. not
in GYP dependency order).
Returns:
(found_errors, stderr) A boolean indicating whether errors were found and
the raw Closure compiler stderr (as a string).
"""
is_extern = lambda f: 'extern' in f
externs_and_deps = [self._POLYMER_EXTERNS]
if custom_sources:
externs_and_deps += sources
else:
self._target = sources[0]
externs_and_deps += sources[1:]
externs = filter(is_extern, externs_and_deps)
deps = filter(lambda f: not is_extern(f), externs_and_deps)
assert externs or deps or self._target
self._log_debug("Externs: %s" % externs)
self._log_debug("Dependencies: %s" % deps)
self._log_debug("Target: %s" % self._target)
js_args = deps + ([self._target] if self._target else [])
if not custom_sources:
# TODO(dbeam): compiler.jar automatically detects "@externs" in a --js arg
# and moves these files to a different AST tree. However, because we use
# one big funky <include> meta-file, it thinks all the code is one big
# externs. Just use --js when <include> dies.
cwd, tmp_dir = os.getcwd(), tempfile.gettempdir()
rel_path = lambda f: os.path.join(os.path.relpath(cwd, tmp_dir), f)
contents = ['<include src="%s">' % rel_path(f) for f in js_args]
meta_file = self._create_temp_file("\n".join(contents))
self._log_debug("Meta file: %s" % meta_file)
self._processor = processor.Processor(meta_file)
self._expanded_file = self._create_temp_file(self._processor.contents)
self._log_debug("Expanded file: %s" % self._expanded_file)
js_args = [self._expanded_file]
closure_args = closure_args or []
closure_args += ["summary_detail_level=3"]
args = ["--externs=%s" % e for e in externs] + \
["--js=%s" % s for s in js_args] + \
["--%s" % arg for arg in closure_args]
if out_file:
out_dir = os.path.dirname(out_file)
if not os.path.exists(out_dir):
os.makedirs(out_dir)
args += ["--js_output_file=%s" % out_file]
args += ["--create_source_map=%s" % (self._MAP_FILE_FORMAT % out_file)]
args_file_content = " %s" % " ".join(args)
self._log_debug("Args: %s" % args_file_content.strip())
args_file = self._create_temp_file(args_file_content)
self._log_debug("Args file: %s" % args_file)
processed_runner_args = ["--%s" % arg for arg in runner_args or []]
processed_runner_args += ["--compiler-args-file=%s" % args_file]
_, stderr = self._run_jar(self._runner_jar, processed_runner_args)
errors = stderr.strip().split("\n\n")
maybe_summary = errors.pop()
summary = re.search("(?P<error_count>\d+).*error.*warning", maybe_summary)
if summary:
self._log_debug("Summary: %s" % maybe_summary)
else:
# Not a summary. Running the jar failed. Bail.
self._log_error(stderr)
self._nuke_temp_files()
sys.exit(1)
if summary.group('error_count') != "0" and out_file:
if os.path.exists(out_file):
os.remove(out_file)
if os.path.exists(self._MAP_FILE_FORMAT % out_file):
os.remove(self._MAP_FILE_FORMAT % out_file)
if not custom_sources:
filtered_errors = self._filter_errors(errors)
errors = map(self._clean_up_error, filtered_errors)
output = self._format_errors(errors)
if errors:
prefix = "\n" if output else ""
self._log_error("Error in: %s%s%s" % (self._target, prefix, output))
elif output:
self._log_debug("Output: %s" % output)
self._nuke_temp_files()
return bool(errors), stderr | [
"def",
"check",
"(",
"self",
",",
"sources",
",",
"out_file",
"=",
"None",
",",
"runner_args",
"=",
"None",
",",
"closure_args",
"=",
"None",
",",
"custom_sources",
"=",
"True",
")",
":",
"is_extern",
"=",
"lambda",
"f",
":",
"'extern'",
"in",
"f",
"externs_and_deps",
"=",
"[",
"self",
".",
"_POLYMER_EXTERNS",
"]",
"if",
"custom_sources",
":",
"externs_and_deps",
"+=",
"sources",
"else",
":",
"self",
".",
"_target",
"=",
"sources",
"[",
"0",
"]",
"externs_and_deps",
"+=",
"sources",
"[",
"1",
":",
"]",
"externs",
"=",
"filter",
"(",
"is_extern",
",",
"externs_and_deps",
")",
"deps",
"=",
"filter",
"(",
"lambda",
"f",
":",
"not",
"is_extern",
"(",
"f",
")",
",",
"externs_and_deps",
")",
"assert",
"externs",
"or",
"deps",
"or",
"self",
".",
"_target",
"self",
".",
"_log_debug",
"(",
"\"Externs: %s\"",
"%",
"externs",
")",
"self",
".",
"_log_debug",
"(",
"\"Dependencies: %s\"",
"%",
"deps",
")",
"self",
".",
"_log_debug",
"(",
"\"Target: %s\"",
"%",
"self",
".",
"_target",
")",
"js_args",
"=",
"deps",
"+",
"(",
"[",
"self",
".",
"_target",
"]",
"if",
"self",
".",
"_target",
"else",
"[",
"]",
")",
"if",
"not",
"custom_sources",
":",
"# TODO(dbeam): compiler.jar automatically detects \"@externs\" in a --js arg",
"# and moves these files to a different AST tree. However, because we use",
"# one big funky <include> meta-file, it thinks all the code is one big",
"# externs. Just use --js when <include> dies.",
"cwd",
",",
"tmp_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
",",
"tempfile",
".",
"gettempdir",
"(",
")",
"rel_path",
"=",
"lambda",
"f",
":",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"relpath",
"(",
"cwd",
",",
"tmp_dir",
")",
",",
"f",
")",
"contents",
"=",
"[",
"'<include src=\"%s\">'",
"%",
"rel_path",
"(",
"f",
")",
"for",
"f",
"in",
"js_args",
"]",
"meta_file",
"=",
"self",
".",
"_create_temp_file",
"(",
"\"\\n\"",
".",
"join",
"(",
"contents",
")",
")",
"self",
".",
"_log_debug",
"(",
"\"Meta file: %s\"",
"%",
"meta_file",
")",
"self",
".",
"_processor",
"=",
"processor",
".",
"Processor",
"(",
"meta_file",
")",
"self",
".",
"_expanded_file",
"=",
"self",
".",
"_create_temp_file",
"(",
"self",
".",
"_processor",
".",
"contents",
")",
"self",
".",
"_log_debug",
"(",
"\"Expanded file: %s\"",
"%",
"self",
".",
"_expanded_file",
")",
"js_args",
"=",
"[",
"self",
".",
"_expanded_file",
"]",
"closure_args",
"=",
"closure_args",
"or",
"[",
"]",
"closure_args",
"+=",
"[",
"\"summary_detail_level=3\"",
"]",
"args",
"=",
"[",
"\"--externs=%s\"",
"%",
"e",
"for",
"e",
"in",
"externs",
"]",
"+",
"[",
"\"--js=%s\"",
"%",
"s",
"for",
"s",
"in",
"js_args",
"]",
"+",
"[",
"\"--%s\"",
"%",
"arg",
"for",
"arg",
"in",
"closure_args",
"]",
"if",
"out_file",
":",
"out_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"out_file",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"out_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"out_dir",
")",
"args",
"+=",
"[",
"\"--js_output_file=%s\"",
"%",
"out_file",
"]",
"args",
"+=",
"[",
"\"--create_source_map=%s\"",
"%",
"(",
"self",
".",
"_MAP_FILE_FORMAT",
"%",
"out_file",
")",
"]",
"args_file_content",
"=",
"\" %s\"",
"%",
"\" \"",
".",
"join",
"(",
"args",
")",
"self",
".",
"_log_debug",
"(",
"\"Args: %s\"",
"%",
"args_file_content",
".",
"strip",
"(",
")",
")",
"args_file",
"=",
"self",
".",
"_create_temp_file",
"(",
"args_file_content",
")",
"self",
".",
"_log_debug",
"(",
"\"Args file: %s\"",
"%",
"args_file",
")",
"processed_runner_args",
"=",
"[",
"\"--%s\"",
"%",
"arg",
"for",
"arg",
"in",
"runner_args",
"or",
"[",
"]",
"]",
"processed_runner_args",
"+=",
"[",
"\"--compiler-args-file=%s\"",
"%",
"args_file",
"]",
"_",
",",
"stderr",
"=",
"self",
".",
"_run_jar",
"(",
"self",
".",
"_runner_jar",
",",
"processed_runner_args",
")",
"errors",
"=",
"stderr",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"\\n\\n\"",
")",
"maybe_summary",
"=",
"errors",
".",
"pop",
"(",
")",
"summary",
"=",
"re",
".",
"search",
"(",
"\"(?P<error_count>\\d+).*error.*warning\"",
",",
"maybe_summary",
")",
"if",
"summary",
":",
"self",
".",
"_log_debug",
"(",
"\"Summary: %s\"",
"%",
"maybe_summary",
")",
"else",
":",
"# Not a summary. Running the jar failed. Bail.",
"self",
".",
"_log_error",
"(",
"stderr",
")",
"self",
".",
"_nuke_temp_files",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"summary",
".",
"group",
"(",
"'error_count'",
")",
"!=",
"\"0\"",
"and",
"out_file",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"out_file",
")",
":",
"os",
".",
"remove",
"(",
"out_file",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_MAP_FILE_FORMAT",
"%",
"out_file",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"_MAP_FILE_FORMAT",
"%",
"out_file",
")",
"if",
"not",
"custom_sources",
":",
"filtered_errors",
"=",
"self",
".",
"_filter_errors",
"(",
"errors",
")",
"errors",
"=",
"map",
"(",
"self",
".",
"_clean_up_error",
",",
"filtered_errors",
")",
"output",
"=",
"self",
".",
"_format_errors",
"(",
"errors",
")",
"if",
"errors",
":",
"prefix",
"=",
"\"\\n\"",
"if",
"output",
"else",
"\"\"",
"self",
".",
"_log_error",
"(",
"\"Error in: %s%s%s\"",
"%",
"(",
"self",
".",
"_target",
",",
"prefix",
",",
"output",
")",
")",
"elif",
"output",
":",
"self",
".",
"_log_debug",
"(",
"\"Output: %s\"",
"%",
"output",
")",
"self",
".",
"_nuke_temp_files",
"(",
")",
"return",
"bool",
"(",
"errors",
")",
",",
"stderr"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/closure_compiler/compile2.py#L192-L302 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/bayesian-methods/algos.py | python | HMC | (sym, data_inputs, X, Y, X_test, Y_test, sample_num,
initializer=None, noise_precision=1 / 9.0, prior_precision=0.1,
learning_rate=1E-6, L=10, dev=mx.gpu()) | return sample_pool | Generate the implementation of HMC | Generate the implementation of HMC | [
"Generate",
"the",
"implementation",
"of",
"HMC"
] | def HMC(sym, data_inputs, X, Y, X_test, Y_test, sample_num,
initializer=None, noise_precision=1 / 9.0, prior_precision=0.1,
learning_rate=1E-6, L=10, dev=mx.gpu()):
"""Generate the implementation of HMC"""
label_key = list(set(data_inputs.keys()) - set(['data']))[0]
exe, exe_params, exe_grads, _ = get_executor(sym, dev, data_inputs, initializer)
exe.arg_dict['data'][:] = X
exe.arg_dict[label_key][:] = Y
sample_pool = []
accept_num = 0
start = time.time()
for i in range(sample_num):
sample_params, is_accept = step_HMC(exe, exe_params, exe_grads, label_key, noise_precision,
prior_precision, L, learning_rate)
accept_num += is_accept
if (i + 1) % 10 == 0:
sample_pool.append(sample_params)
if (i + 1) % 100000 == 0:
end = time.time()
print("Current Iter Num: %d" % (i + 1), "Time Spent: %f" % (end - start), "MSE:",
sample_test_regression(exe, X=X_test, Y=Y_test, sample_pool=sample_pool,
minibatch_size=Y.shape[0],
save_path='regression_HMC.txt'))
start = time.time()
exe.copy_params_from(sample_params)
print('accept ratio', accept_num / float(sample_num))
return sample_pool | [
"def",
"HMC",
"(",
"sym",
",",
"data_inputs",
",",
"X",
",",
"Y",
",",
"X_test",
",",
"Y_test",
",",
"sample_num",
",",
"initializer",
"=",
"None",
",",
"noise_precision",
"=",
"1",
"/",
"9.0",
",",
"prior_precision",
"=",
"0.1",
",",
"learning_rate",
"=",
"1E-6",
",",
"L",
"=",
"10",
",",
"dev",
"=",
"mx",
".",
"gpu",
"(",
")",
")",
":",
"label_key",
"=",
"list",
"(",
"set",
"(",
"data_inputs",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"[",
"'data'",
"]",
")",
")",
"[",
"0",
"]",
"exe",
",",
"exe_params",
",",
"exe_grads",
",",
"_",
"=",
"get_executor",
"(",
"sym",
",",
"dev",
",",
"data_inputs",
",",
"initializer",
")",
"exe",
".",
"arg_dict",
"[",
"'data'",
"]",
"[",
":",
"]",
"=",
"X",
"exe",
".",
"arg_dict",
"[",
"label_key",
"]",
"[",
":",
"]",
"=",
"Y",
"sample_pool",
"=",
"[",
"]",
"accept_num",
"=",
"0",
"start",
"=",
"time",
".",
"time",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"sample_num",
")",
":",
"sample_params",
",",
"is_accept",
"=",
"step_HMC",
"(",
"exe",
",",
"exe_params",
",",
"exe_grads",
",",
"label_key",
",",
"noise_precision",
",",
"prior_precision",
",",
"L",
",",
"learning_rate",
")",
"accept_num",
"+=",
"is_accept",
"if",
"(",
"i",
"+",
"1",
")",
"%",
"10",
"==",
"0",
":",
"sample_pool",
".",
"append",
"(",
"sample_params",
")",
"if",
"(",
"i",
"+",
"1",
")",
"%",
"100000",
"==",
"0",
":",
"end",
"=",
"time",
".",
"time",
"(",
")",
"print",
"(",
"\"Current Iter Num: %d\"",
"%",
"(",
"i",
"+",
"1",
")",
",",
"\"Time Spent: %f\"",
"%",
"(",
"end",
"-",
"start",
")",
",",
"\"MSE:\"",
",",
"sample_test_regression",
"(",
"exe",
",",
"X",
"=",
"X_test",
",",
"Y",
"=",
"Y_test",
",",
"sample_pool",
"=",
"sample_pool",
",",
"minibatch_size",
"=",
"Y",
".",
"shape",
"[",
"0",
"]",
",",
"save_path",
"=",
"'regression_HMC.txt'",
")",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"exe",
".",
"copy_params_from",
"(",
"sample_params",
")",
"print",
"(",
"'accept ratio'",
",",
"accept_num",
"/",
"float",
"(",
"sample_num",
")",
")",
"return",
"sample_pool"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/bayesian-methods/algos.py#L103-L130 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/cpplint.py | python | _OutputFormat | () | return _cpplint_state.output_format | Gets the module's output format. | Gets the module's output format. | [
"Gets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format | [
"def",
"_OutputFormat",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"output_format"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/cpplint.py#L846-L848 | |
nsnam/ns-3-dev-git | efdb2e21f45c0a87a60b47c547b68fa140a7b686 | src/visualizer/visualizer/ipython_view.py | python | IPythonView.__init__ | (self) | Initialize. Redirect I/O to console. | Initialize. Redirect I/O to console. | [
"Initialize",
".",
"Redirect",
"I",
"/",
"O",
"to",
"console",
"."
] | def __init__(self):
"""
Initialize. Redirect I/O to console.
"""
ConsoleView.__init__(self)
self.cout = StringIO()
IterableIPShell.__init__(self, cout=self.cout,cerr=self.cout,
input_func=self.raw_input)
self.interrupt = False
self.execute()
self.prompt = self.generatePrompt(False)
self.cout.truncate(0)
self.showPrompt(self.prompt) | [
"def",
"__init__",
"(",
"self",
")",
":",
"ConsoleView",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"cout",
"=",
"StringIO",
"(",
")",
"IterableIPShell",
".",
"__init__",
"(",
"self",
",",
"cout",
"=",
"self",
".",
"cout",
",",
"cerr",
"=",
"self",
".",
"cout",
",",
"input_func",
"=",
"self",
".",
"raw_input",
")",
"self",
".",
"interrupt",
"=",
"False",
"self",
".",
"execute",
"(",
")",
"self",
".",
"prompt",
"=",
"self",
".",
"generatePrompt",
"(",
"False",
")",
"self",
".",
"cout",
".",
"truncate",
"(",
"0",
")",
"self",
".",
"showPrompt",
"(",
"self",
".",
"prompt",
")"
] | https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/src/visualizer/visualizer/ipython_view.py#L586-L598 | ||
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | openr/py/openr/cli/commands/decision.py | python | DecisionValidateCmd.print_db_diff | (
self,
nodes_set_a: Set,
nodes_set_b: Set,
db_sources: List[str],
db_type: str,
json: bool,
) | return return_code | Returns a status code, 0 = success, 1 = failure | Returns a status code, 0 = success, 1 = failure | [
"Returns",
"a",
"status",
"code",
"0",
"=",
"success",
"1",
"=",
"failure"
] | def print_db_diff(
self,
nodes_set_a: Set,
nodes_set_b: Set,
db_sources: List[str],
db_type: str,
json: bool,
) -> int:
"""Returns a status code, 0 = success, 1 = failure"""
a_minus_b = sorted(nodes_set_a - nodes_set_b)
b_minus_a = sorted(nodes_set_b - nodes_set_a)
return_code = 0
if json:
diffs_up = []
diffs_down = []
for node in a_minus_b:
diffs_up.append(node)
for node in b_minus_a:
diffs_down.append(node)
if diffs_up or diffs_down:
diffs = {
"db_type": db_type,
"db_up": db_sources[0],
"db_down": db_sources[1],
"nodes_up": diffs_up,
"nodes_down": diffs_down,
}
return_code = 1
utils.print_json(diffs)
else:
rows = []
for node in a_minus_b:
rows.append(
[
"node {}'s {} db in {} but not in {}".format(
node, db_type, *db_sources
)
]
)
for node in b_minus_a:
rows.append(
[
"node {}'s {} db in {} but not in {}".format(
node, db_type, *reversed(db_sources)
)
]
)
if rows:
print(printing.render_vertical_table(rows))
return_code = 1
if return_code == 1:
if utils.is_color_output_supported():
click.echo(click.style("FAIL", bg="red", fg="black"))
else:
click.echo("FAIL")
print("{} table for {} and {} do not match".format(db_type, *db_sources))
else:
if utils.is_color_output_supported():
click.echo(click.style("PASS", bg="green", fg="black"))
else:
click.echo("PASS")
print("{} table for {} and {} match".format(db_type, *db_sources))
return return_code | [
"def",
"print_db_diff",
"(",
"self",
",",
"nodes_set_a",
":",
"Set",
",",
"nodes_set_b",
":",
"Set",
",",
"db_sources",
":",
"List",
"[",
"str",
"]",
",",
"db_type",
":",
"str",
",",
"json",
":",
"bool",
",",
")",
"->",
"int",
":",
"a_minus_b",
"=",
"sorted",
"(",
"nodes_set_a",
"-",
"nodes_set_b",
")",
"b_minus_a",
"=",
"sorted",
"(",
"nodes_set_b",
"-",
"nodes_set_a",
")",
"return_code",
"=",
"0",
"if",
"json",
":",
"diffs_up",
"=",
"[",
"]",
"diffs_down",
"=",
"[",
"]",
"for",
"node",
"in",
"a_minus_b",
":",
"diffs_up",
".",
"append",
"(",
"node",
")",
"for",
"node",
"in",
"b_minus_a",
":",
"diffs_down",
".",
"append",
"(",
"node",
")",
"if",
"diffs_up",
"or",
"diffs_down",
":",
"diffs",
"=",
"{",
"\"db_type\"",
":",
"db_type",
",",
"\"db_up\"",
":",
"db_sources",
"[",
"0",
"]",
",",
"\"db_down\"",
":",
"db_sources",
"[",
"1",
"]",
",",
"\"nodes_up\"",
":",
"diffs_up",
",",
"\"nodes_down\"",
":",
"diffs_down",
",",
"}",
"return_code",
"=",
"1",
"utils",
".",
"print_json",
"(",
"diffs",
")",
"else",
":",
"rows",
"=",
"[",
"]",
"for",
"node",
"in",
"a_minus_b",
":",
"rows",
".",
"append",
"(",
"[",
"\"node {}'s {} db in {} but not in {}\"",
".",
"format",
"(",
"node",
",",
"db_type",
",",
"*",
"db_sources",
")",
"]",
")",
"for",
"node",
"in",
"b_minus_a",
":",
"rows",
".",
"append",
"(",
"[",
"\"node {}'s {} db in {} but not in {}\"",
".",
"format",
"(",
"node",
",",
"db_type",
",",
"*",
"reversed",
"(",
"db_sources",
")",
")",
"]",
")",
"if",
"rows",
":",
"print",
"(",
"printing",
".",
"render_vertical_table",
"(",
"rows",
")",
")",
"return_code",
"=",
"1",
"if",
"return_code",
"==",
"1",
":",
"if",
"utils",
".",
"is_color_output_supported",
"(",
")",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"\"FAIL\"",
",",
"bg",
"=",
"\"red\"",
",",
"fg",
"=",
"\"black\"",
")",
")",
"else",
":",
"click",
".",
"echo",
"(",
"\"FAIL\"",
")",
"print",
"(",
"\"{} table for {} and {} do not match\"",
".",
"format",
"(",
"db_type",
",",
"*",
"db_sources",
")",
")",
"else",
":",
"if",
"utils",
".",
"is_color_output_supported",
"(",
")",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"\"PASS\"",
",",
"bg",
"=",
"\"green\"",
",",
"fg",
"=",
"\"black\"",
")",
")",
"else",
":",
"click",
".",
"echo",
"(",
"\"PASS\"",
")",
"print",
"(",
"\"{} table for {} and {} match\"",
".",
"format",
"(",
"db_type",
",",
"*",
"db_sources",
")",
")",
"return",
"return_code"
] | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/commands/decision.py#L616-L683 | |
Atarity/Lightpack | 4dee73a443cba4c4073291febe450e6c1941f3af | Software/apiexamples/liOSC/OSC.py | python | OSCMessage.__reversed__ | (self) | return reversed(self.values()) | Returns a reverse iterator of the OSCMessage's arguments | Returns a reverse iterator of the OSCMessage's arguments | [
"Returns",
"a",
"reverse",
"iterator",
"of",
"the",
"OSCMessage",
"s",
"arguments"
] | def __reversed__(self):
"""Returns a reverse iterator of the OSCMessage's arguments
"""
return reversed(self.values()) | [
"def",
"__reversed__",
"(",
"self",
")",
":",
"return",
"reversed",
"(",
"self",
".",
"values",
"(",
")",
")"
] | https://github.com/Atarity/Lightpack/blob/4dee73a443cba4c4073291febe450e6c1941f3af/Software/apiexamples/liOSC/OSC.py#L511-L514 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/thumbnailctrl.py | python | ScrolledThumbnail.OnMouseMove | (self, event) | Handles the ``wx.EVT_MOTION`` event for :class:`ThumbnailCtrl`.
:param `event`: a :class:`MouseEvent` event to be processed. | Handles the ``wx.EVT_MOTION`` event for :class:`ThumbnailCtrl`. | [
"Handles",
"the",
"wx",
".",
"EVT_MOTION",
"event",
"for",
":",
"class",
":",
"ThumbnailCtrl",
"."
] | def OnMouseMove(self, event):
"""
Handles the ``wx.EVT_MOTION`` event for :class:`ThumbnailCtrl`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
# -- drag & drop --
if self._dragging and event.Dragging() and len(self._selectedarray) > 0:
files = wx.FileDataObject()
for ii in xrange(len(self._selectedarray)):
files.AddFile(opj(self.GetSelectedItem(ii).GetFullFileName()))
source = wx.DropSource(self)
source.SetData(files)
source.DoDragDrop(wx.Drag_DefaultMove)
# -- light-effect --
x = event.GetX()
y = event.GetY()
x, y = self.CalcUnscrolledPosition(x, y)
# get item number
sel = self.GetItemIndex(x, y)
if sel == self._pointed:
if self._enabletooltip and sel >= 0:
if not hasattr(self, "_tipwindow"):
self._tipwindow = wx.ToolTip(self.GetThumbInfo(sel))
self._tipwindow.SetDelay(1000)
self.SetToolTip(self._tipwindow)
else:
self._tipwindow.SetDelay(1000)
self._tipwindow.SetTip(self.GetThumbInfo(sel))
event.Skip()
return
if self._enabletooltip:
if hasattr(self, "_tipwindow"):
self._tipwindow.Enable(False)
# update thumbnail
self._pointed = sel
if self._enabletooltip and sel >= 0:
if not hasattr(self, "_tipwindow"):
self._tipwindow = wx.ToolTip(self.GetThumbInfo(sel))
self._tipwindow.SetDelay(1000)
self._tipwindow.Enable(True)
self.SetToolTip(self._tipwindow)
else:
self._tipwindow.SetDelay(1000)
self._tipwindow.Enable(True)
self._tipwindow.SetTip(self.GetThumbInfo(sel))
self.Refresh()
eventOut = ThumbnailEvent(wxEVT_THUMBNAILS_POINTED, self.GetId())
self.GetEventHandler().ProcessEvent(eventOut)
event.Skip() | [
"def",
"OnMouseMove",
"(",
"self",
",",
"event",
")",
":",
"# -- drag & drop --",
"if",
"self",
".",
"_dragging",
"and",
"event",
".",
"Dragging",
"(",
")",
"and",
"len",
"(",
"self",
".",
"_selectedarray",
")",
">",
"0",
":",
"files",
"=",
"wx",
".",
"FileDataObject",
"(",
")",
"for",
"ii",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"_selectedarray",
")",
")",
":",
"files",
".",
"AddFile",
"(",
"opj",
"(",
"self",
".",
"GetSelectedItem",
"(",
"ii",
")",
".",
"GetFullFileName",
"(",
")",
")",
")",
"source",
"=",
"wx",
".",
"DropSource",
"(",
"self",
")",
"source",
".",
"SetData",
"(",
"files",
")",
"source",
".",
"DoDragDrop",
"(",
"wx",
".",
"Drag_DefaultMove",
")",
"# -- light-effect --",
"x",
"=",
"event",
".",
"GetX",
"(",
")",
"y",
"=",
"event",
".",
"GetY",
"(",
")",
"x",
",",
"y",
"=",
"self",
".",
"CalcUnscrolledPosition",
"(",
"x",
",",
"y",
")",
"# get item number",
"sel",
"=",
"self",
".",
"GetItemIndex",
"(",
"x",
",",
"y",
")",
"if",
"sel",
"==",
"self",
".",
"_pointed",
":",
"if",
"self",
".",
"_enabletooltip",
"and",
"sel",
">=",
"0",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_tipwindow\"",
")",
":",
"self",
".",
"_tipwindow",
"=",
"wx",
".",
"ToolTip",
"(",
"self",
".",
"GetThumbInfo",
"(",
"sel",
")",
")",
"self",
".",
"_tipwindow",
".",
"SetDelay",
"(",
"1000",
")",
"self",
".",
"SetToolTip",
"(",
"self",
".",
"_tipwindow",
")",
"else",
":",
"self",
".",
"_tipwindow",
".",
"SetDelay",
"(",
"1000",
")",
"self",
".",
"_tipwindow",
".",
"SetTip",
"(",
"self",
".",
"GetThumbInfo",
"(",
"sel",
")",
")",
"event",
".",
"Skip",
"(",
")",
"return",
"if",
"self",
".",
"_enabletooltip",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_tipwindow\"",
")",
":",
"self",
".",
"_tipwindow",
".",
"Enable",
"(",
"False",
")",
"# update thumbnail",
"self",
".",
"_pointed",
"=",
"sel",
"if",
"self",
".",
"_enabletooltip",
"and",
"sel",
">=",
"0",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_tipwindow\"",
")",
":",
"self",
".",
"_tipwindow",
"=",
"wx",
".",
"ToolTip",
"(",
"self",
".",
"GetThumbInfo",
"(",
"sel",
")",
")",
"self",
".",
"_tipwindow",
".",
"SetDelay",
"(",
"1000",
")",
"self",
".",
"_tipwindow",
".",
"Enable",
"(",
"True",
")",
"self",
".",
"SetToolTip",
"(",
"self",
".",
"_tipwindow",
")",
"else",
":",
"self",
".",
"_tipwindow",
".",
"SetDelay",
"(",
"1000",
")",
"self",
".",
"_tipwindow",
".",
"Enable",
"(",
"True",
")",
"self",
".",
"_tipwindow",
".",
"SetTip",
"(",
"self",
".",
"GetThumbInfo",
"(",
"sel",
")",
")",
"self",
".",
"Refresh",
"(",
")",
"eventOut",
"=",
"ThumbnailEvent",
"(",
"wxEVT_THUMBNAILS_POINTED",
",",
"self",
".",
"GetId",
"(",
")",
")",
"self",
".",
"GetEventHandler",
"(",
")",
".",
"ProcessEvent",
"(",
"eventOut",
")",
"event",
".",
"Skip",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/thumbnailctrl.py#L2313-L2373 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/core/debugger.py | python | Pdb.new_do_restart | (self, arg) | return self.do_quit(arg) | Restart command. In the context of ipython this is exactly the same
thing as 'quit'. | Restart command. In the context of ipython this is exactly the same
thing as 'quit'. | [
"Restart",
"command",
".",
"In",
"the",
"context",
"of",
"ipython",
"this",
"is",
"exactly",
"the",
"same",
"thing",
"as",
"quit",
"."
] | def new_do_restart(self, arg):
"""Restart command. In the context of ipython this is exactly the same
thing as 'quit'."""
self.msg("Restart doesn't make sense here. Using 'quit' instead.")
return self.do_quit(arg) | [
"def",
"new_do_restart",
"(",
"self",
",",
"arg",
")",
":",
"self",
".",
"msg",
"(",
"\"Restart doesn't make sense here. Using 'quit' instead.\"",
")",
"return",
"self",
".",
"do_quit",
"(",
"arg",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/debugger.py#L313-L317 | |
zerollzeng/tiny-tensorrt | e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2 | third_party/pybind11/tools/clang/cindex.py | python | TypeKind.spelling | (self) | return conf.lib.clang_getTypeKindSpelling(self.value) | Retrieve the spelling of this TypeKind. | Retrieve the spelling of this TypeKind. | [
"Retrieve",
"the",
"spelling",
"of",
"this",
"TypeKind",
"."
] | def spelling(self):
"""Retrieve the spelling of this TypeKind."""
return conf.lib.clang_getTypeKindSpelling(self.value) | [
"def",
"spelling",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTypeKindSpelling",
"(",
"self",
".",
"value",
")"
] | https://github.com/zerollzeng/tiny-tensorrt/blob/e7bdb8f82934342a0f22ce68dfefdb8e15eb72b2/third_party/pybind11/tools/clang/cindex.py#L1821-L1823 | |
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | MULAN_universal_lesion_analysis/maskrcnn/modeling/roi_heads/box_head/loss.py | python | FastRCNNLossComputation.subsample | (self, proposals, targets) | return proposals | This method performs the positive/negative sampling, and return
the sampled proposals.
Note: this function keeps a state.
Arguments:
proposals (list[BoxList])
targets (list[BoxList]) | This method performs the positive/negative sampling, and return
the sampled proposals.
Note: this function keeps a state. | [
"This",
"method",
"performs",
"the",
"positive",
"/",
"negative",
"sampling",
"and",
"return",
"the",
"sampled",
"proposals",
".",
"Note",
":",
"this",
"function",
"keeps",
"a",
"state",
"."
] | def subsample(self, proposals, targets):
"""
This method performs the positive/negative sampling, and return
the sampled proposals.
Note: this function keeps a state.
Arguments:
proposals (list[BoxList])
targets (list[BoxList])
"""
labels, regression_targets, matched_idxs = self.prepare_targets(proposals, targets)
sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels)
proposals = list(proposals)
# add corresponding label and regression_targets information to the bounding boxes
for labels_per_image, regression_targets_per_image, \
proposals_per_image, matched_idxs_per_image in zip(
labels, regression_targets, proposals, matched_idxs
):
proposals_per_image.add_field("labels", labels_per_image)
proposals_per_image.add_field(
"regression_targets", regression_targets_per_image
)
proposals_per_image.add_field("matched_idxs", matched_idxs_per_image)
# distributed sampled proposals, that were obtained on all feature maps
# concatenated via the fg_bg_sampler, into individual feature map levels
for img_idx, (pos_inds_img, neg_inds_img) in enumerate(
zip(sampled_pos_inds, sampled_neg_inds)
):
img_sampled_inds = torch.nonzero(pos_inds_img | neg_inds_img).squeeze(1)
proposals_per_image = proposals[img_idx][img_sampled_inds]
proposals[img_idx] = proposals_per_image
self._proposals = proposals
return proposals | [
"def",
"subsample",
"(",
"self",
",",
"proposals",
",",
"targets",
")",
":",
"labels",
",",
"regression_targets",
",",
"matched_idxs",
"=",
"self",
".",
"prepare_targets",
"(",
"proposals",
",",
"targets",
")",
"sampled_pos_inds",
",",
"sampled_neg_inds",
"=",
"self",
".",
"fg_bg_sampler",
"(",
"labels",
")",
"proposals",
"=",
"list",
"(",
"proposals",
")",
"# add corresponding label and regression_targets information to the bounding boxes",
"for",
"labels_per_image",
",",
"regression_targets_per_image",
",",
"proposals_per_image",
",",
"matched_idxs_per_image",
"in",
"zip",
"(",
"labels",
",",
"regression_targets",
",",
"proposals",
",",
"matched_idxs",
")",
":",
"proposals_per_image",
".",
"add_field",
"(",
"\"labels\"",
",",
"labels_per_image",
")",
"proposals_per_image",
".",
"add_field",
"(",
"\"regression_targets\"",
",",
"regression_targets_per_image",
")",
"proposals_per_image",
".",
"add_field",
"(",
"\"matched_idxs\"",
",",
"matched_idxs_per_image",
")",
"# distributed sampled proposals, that were obtained on all feature maps",
"# concatenated via the fg_bg_sampler, into individual feature map levels",
"for",
"img_idx",
",",
"(",
"pos_inds_img",
",",
"neg_inds_img",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"sampled_pos_inds",
",",
"sampled_neg_inds",
")",
")",
":",
"img_sampled_inds",
"=",
"torch",
".",
"nonzero",
"(",
"pos_inds_img",
"|",
"neg_inds_img",
")",
".",
"squeeze",
"(",
"1",
")",
"proposals_per_image",
"=",
"proposals",
"[",
"img_idx",
"]",
"[",
"img_sampled_inds",
"]",
"proposals",
"[",
"img_idx",
"]",
"=",
"proposals_per_image",
"self",
".",
"_proposals",
"=",
"proposals",
"return",
"proposals"
] | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/MULAN_universal_lesion_analysis/maskrcnn/modeling/roi_heads/box_head/loss.py#L87-L123 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/elasticache/layer1.py | python | ElastiCacheConnection.authorize_cache_security_group_ingress | (self,
cache_security_group_name,
ec2_security_group_name,
ec2_security_group_owner_id) | return self._make_request(
action='AuthorizeCacheSecurityGroupIngress',
verb='POST',
path='/', params=params) | The AuthorizeCacheSecurityGroupIngress operation allows
network ingress to a cache security group. Applications using
ElastiCache must be running on Amazon EC2, and Amazon EC2
security groups are used as the authorization mechanism.
You cannot authorize ingress from an Amazon EC2 security group
in one Region to an ElastiCache cluster in another Region.
:type cache_security_group_name: string
:param cache_security_group_name: The cache security group which will
allow network ingress.
:type ec2_security_group_name: string
:param ec2_security_group_name: The Amazon EC2 security group to be
authorized for ingress to the cache security group.
:type ec2_security_group_owner_id: string
:param ec2_security_group_owner_id: The AWS account number of the
Amazon EC2 security group owner. Note that this is not the same
thing as an AWS access key ID - you must provide a valid AWS
account number for this parameter. | The AuthorizeCacheSecurityGroupIngress operation allows
network ingress to a cache security group. Applications using
ElastiCache must be running on Amazon EC2, and Amazon EC2
security groups are used as the authorization mechanism.
You cannot authorize ingress from an Amazon EC2 security group
in one Region to an ElastiCache cluster in another Region. | [
"The",
"AuthorizeCacheSecurityGroupIngress",
"operation",
"allows",
"network",
"ingress",
"to",
"a",
"cache",
"security",
"group",
".",
"Applications",
"using",
"ElastiCache",
"must",
"be",
"running",
"on",
"Amazon",
"EC2",
"and",
"Amazon",
"EC2",
"security",
"groups",
"are",
"used",
"as",
"the",
"authorization",
"mechanism",
".",
"You",
"cannot",
"authorize",
"ingress",
"from",
"an",
"Amazon",
"EC2",
"security",
"group",
"in",
"one",
"Region",
"to",
"an",
"ElastiCache",
"cluster",
"in",
"another",
"Region",
"."
] | def authorize_cache_security_group_ingress(self,
cache_security_group_name,
ec2_security_group_name,
ec2_security_group_owner_id):
"""
The AuthorizeCacheSecurityGroupIngress operation allows
network ingress to a cache security group. Applications using
ElastiCache must be running on Amazon EC2, and Amazon EC2
security groups are used as the authorization mechanism.
You cannot authorize ingress from an Amazon EC2 security group
in one Region to an ElastiCache cluster in another Region.
:type cache_security_group_name: string
:param cache_security_group_name: The cache security group which will
allow network ingress.
:type ec2_security_group_name: string
:param ec2_security_group_name: The Amazon EC2 security group to be
authorized for ingress to the cache security group.
:type ec2_security_group_owner_id: string
:param ec2_security_group_owner_id: The AWS account number of the
Amazon EC2 security group owner. Note that this is not the same
thing as an AWS access key ID - you must provide a valid AWS
account number for this parameter.
"""
params = {
'CacheSecurityGroupName': cache_security_group_name,
'EC2SecurityGroupName': ec2_security_group_name,
'EC2SecurityGroupOwnerId': ec2_security_group_owner_id,
}
return self._make_request(
action='AuthorizeCacheSecurityGroupIngress',
verb='POST',
path='/', params=params) | [
"def",
"authorize_cache_security_group_ingress",
"(",
"self",
",",
"cache_security_group_name",
",",
"ec2_security_group_name",
",",
"ec2_security_group_owner_id",
")",
":",
"params",
"=",
"{",
"'CacheSecurityGroupName'",
":",
"cache_security_group_name",
",",
"'EC2SecurityGroupName'",
":",
"ec2_security_group_name",
",",
"'EC2SecurityGroupOwnerId'",
":",
"ec2_security_group_owner_id",
",",
"}",
"return",
"self",
".",
"_make_request",
"(",
"action",
"=",
"'AuthorizeCacheSecurityGroupIngress'",
",",
"verb",
"=",
"'POST'",
",",
"path",
"=",
"'/'",
",",
"params",
"=",
"params",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/elasticache/layer1.py#L64-L99 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py | python | TarInfo._proc_gnulong | (self, tarfile) | return next | Process the blocks that hold a GNU longname
or longlink member. | Process the blocks that hold a GNU longname
or longlink member. | [
"Process",
"the",
"blocks",
"that",
"hold",
"a",
"GNU",
"longname",
"or",
"longlink",
"member",
"."
] | def _proc_gnulong(self, tarfile):
"""Process the blocks that hold a GNU longname
or longlink member.
"""
buf = tarfile.fileobj.read(self._block(self.size))
# Fetch the next header and process it.
try:
next = self.fromtarfile(tarfile)
except HeaderError:
raise SubsequentHeaderError("missing or bad subsequent header")
# Patch the TarInfo object from the next header with
# the longname information.
next.offset = self.offset
if self.type == GNUTYPE_LONGNAME:
next.name = nts(buf, tarfile.encoding, tarfile.errors)
elif self.type == GNUTYPE_LONGLINK:
next.linkname = nts(buf, tarfile.encoding, tarfile.errors)
return next | [
"def",
"_proc_gnulong",
"(",
"self",
",",
"tarfile",
")",
":",
"buf",
"=",
"tarfile",
".",
"fileobj",
".",
"read",
"(",
"self",
".",
"_block",
"(",
"self",
".",
"size",
")",
")",
"# Fetch the next header and process it.",
"try",
":",
"next",
"=",
"self",
".",
"fromtarfile",
"(",
"tarfile",
")",
"except",
"HeaderError",
":",
"raise",
"SubsequentHeaderError",
"(",
"\"missing or bad subsequent header\"",
")",
"# Patch the TarInfo object from the next header with",
"# the longname information.",
"next",
".",
"offset",
"=",
"self",
".",
"offset",
"if",
"self",
".",
"type",
"==",
"GNUTYPE_LONGNAME",
":",
"next",
".",
"name",
"=",
"nts",
"(",
"buf",
",",
"tarfile",
".",
"encoding",
",",
"tarfile",
".",
"errors",
")",
"elif",
"self",
".",
"type",
"==",
"GNUTYPE_LONGLINK",
":",
"next",
".",
"linkname",
"=",
"nts",
"(",
"buf",
",",
"tarfile",
".",
"encoding",
",",
"tarfile",
".",
"errors",
")",
"return",
"next"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L1333-L1353 | |
RegrowthStudios/SoACode-Public | c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe | utils/git-hooks/pep8.py | python | python_3000_raise_comma | (logical_line) | When raising an exception, use "raise ValueError('message')"
instead of the older form "raise ValueError, 'message'".
The paren-using form is preferred because when the exception arguments
are long or include string formatting, you don't need to use line
continuation characters thanks to the containing parentheses. The older
form is removed in Python 3.
Okay: raise DummyError("Message")
W602: raise DummyError, "Message" | When raising an exception, use "raise ValueError('message')"
instead of the older form "raise ValueError, 'message'". | [
"When",
"raising",
"an",
"exception",
"use",
"raise",
"ValueError",
"(",
"message",
")",
"instead",
"of",
"the",
"older",
"form",
"raise",
"ValueError",
"message",
"."
] | def python_3000_raise_comma(logical_line):
"""
When raising an exception, use "raise ValueError('message')"
instead of the older form "raise ValueError, 'message'".
The paren-using form is preferred because when the exception arguments
are long or include string formatting, you don't need to use line
continuation characters thanks to the containing parentheses. The older
form is removed in Python 3.
Okay: raise DummyError("Message")
W602: raise DummyError, "Message"
"""
match = RAISE_COMMA_REGEX.match(logical_line)
if match and not RERAISE_COMMA_REGEX.match(logical_line):
yield match.end() - 1, "W602 deprecated form of raising exception" | [
"def",
"python_3000_raise_comma",
"(",
"logical_line",
")",
":",
"match",
"=",
"RAISE_COMMA_REGEX",
".",
"match",
"(",
"logical_line",
")",
"if",
"match",
"and",
"not",
"RERAISE_COMMA_REGEX",
".",
"match",
"(",
"logical_line",
")",
":",
"yield",
"match",
".",
"end",
"(",
")",
"-",
"1",
",",
"\"W602 deprecated form of raising exception\""
] | https://github.com/RegrowthStudios/SoACode-Public/blob/c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe/utils/git-hooks/pep8.py#L967-L982 | ||
NVIDIA/DALI | bf16cc86ba8f091b145f91962f21fe1b6aff243d | third_party/cpplint.py | python | _OutputFormat | () | return _cpplint_state.output_format | Gets the module's output format. | Gets the module's output format. | [
"Gets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format | [
"def",
"_OutputFormat",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"output_format"
] | https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/third_party/cpplint.py#L961-L963 | |
rootm0s/Protectors | 5b3f4d11687a5955caf9c3af30666c4bfc2c19ab | OWASP-ZSC/module/readline_windows/pyreadline/modes/notemacs.py | python | NotEmacsMode.clear_screen | (self, e) | Clear the screen and redraw the current line, leaving the current
line at the top of the screen. | Clear the screen and redraw the current line, leaving the current
line at the top of the screen. | [
"Clear",
"the",
"screen",
"and",
"redraw",
"the",
"current",
"line",
"leaving",
"the",
"current",
"line",
"at",
"the",
"top",
"of",
"the",
"screen",
"."
] | def clear_screen(self, e): # (C-l)
'''Clear the screen and redraw the current line, leaving the current
line at the top of the screen.'''
self.console.page() | [
"def",
"clear_screen",
"(",
"self",
",",
"e",
")",
":",
"# (C-l)",
"self",
".",
"console",
".",
"page",
"(",
")"
] | https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/modes/notemacs.py#L124-L127 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pyedbglib/primitive/gen4controller.py | python | Gen4ControllerCommand.set_script_source | (self, src_id) | Sets the script source | Sets the script source | [
"Sets",
"the",
"script",
"source"
] | def set_script_source(self, src_id):
"""Sets the script source"""
if src_id != SCRIPT_SOURCE_INLINE:
raise PyedbglibNotSupportedError("Only inline scripts are currently supported!")
self.script_source = src_id | [
"def",
"set_script_source",
"(",
"self",
",",
"src_id",
")",
":",
"if",
"src_id",
"!=",
"SCRIPT_SOURCE_INLINE",
":",
"raise",
"PyedbglibNotSupportedError",
"(",
"\"Only inline scripts are currently supported!\"",
")",
"self",
".",
"script_source",
"=",
"src_id"
] | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/primitive/gen4controller.py#L72-L76 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.