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
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/cccc.py
python
Isotxs._read_nuclide_scatter
(self, nuc, block, subBlock)
Read nuclide scattering matrix. In some versions of the specification, the written description of the scattering matrix is wrong! The person who was typing that version had shifted their right hand one key to the right on the keyboard resulting in gibberish. The CCCC-IV pdf has the correct specification.
Read nuclide scattering matrix.
[ "Read", "nuclide", "scattering", "matrix", "." ]
def _read_nuclide_scatter(self, nuc, block, subBlock): """Read nuclide scattering matrix. In some versions of the specification, the written description of the scattering matrix is wrong! The person who was typing that version had shifted their right hand one key to the right on the keyboard resulting in gibberish. The CCCC-IV pdf has the correct specification. """ # Get record r = self.get_fortran_record() # Copy values for number of groups and number of subblocks ng = self.fc['ngroup'] nsblok = self.fc['nsblok'] # Make sure blocks and subblocks are indexed starting from 1 m = subBlock + 1 n = block + 1 # Determine number of scattering orders in this block lordn = nuc.libParams['ords'][block] # This is basically how many scattering cross sections there are for # this scatter type for this nuclide jl = (m - 1)*((ng - 1)//nsblok + 1) + 1 jup = m*((ng - 1)//nsblok + 1) ju = min(ng, jup) # Figure out kmax for this sub-block. kmax = 0 for j in range(jl, ju+1): g = j - 1 # convert to groups starting at 0 kmax += nuc.libParams['jband'][g, block] # scattering from group j for order in range(lordn): # for k in range(kmax): for j in range(jl, ju+1): # There are JBAND values for scattering into group j listed in # order of the "from" group as from j+jup to j, from j+jup-1 to # j, ...,from j to j, from j-1 to j, j-2 to j, ... , j-down to j # anything listed to the left of j represents # upscatter. anything to the right is downscatter. n,2n on # MC**2-2 ISOTXS scatter matrix are reaction based and need to # be multiplied by 2 to get the correct neutron balance. g = j-1 assert g >= 0, "loading negative group in ISOTXS." jup = nuc.libParams['jj'][g, block] - 1 jdown = nuc.libParams['jband'][g, block] - \ nuc.libParams['jj'][g, block] fromgroups = list(range(j-jdown, j+jup+1)) fromgroups.reverse() for k in fromgroups: fromg = k-1 nuc.micros['scat', block, g, fromg, order] = r.get_float()[ 0]
[ "def", "_read_nuclide_scatter", "(", "self", ",", "nuc", ",", "block", ",", "subBlock", ")", ":", "# Get record", "r", "=", "self", ".", "get_fortran_record", "(", ")", "# Copy values for number of groups and number of subblocks", "ng", "=", "self", ".", "fc", "["...
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/cccc.py#L324-L380
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/gyp/pylib/gyp/generator/cmake.py
python
SetTargetProperty
(output, target_name, property_name, values, sep='')
Given a target, sets the given property.
Given a target, sets the given property.
[ "Given", "a", "target", "sets", "the", "given", "property", "." ]
def SetTargetProperty(output, target_name, property_name, values, sep=''): """Given a target, sets the given property.""" output.write('set_target_properties(') output.write(target_name) output.write(' PROPERTIES ') output.write(property_name) output.write(' "') for value in values: output.write(CMakeStringEscape(value)) output.write(sep) output.write('")\n')
[ "def", "SetTargetProperty", "(", "output", ",", "target_name", ",", "property_name", ",", "values", ",", "sep", "=", "''", ")", ":", "output", ".", "write", "(", "'set_target_properties('", ")", "output", ".", "write", "(", "target_name", ")", "output", ".",...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/cmake.py#L169-L179
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
examples/rfcn/lib/rpn/proposal_target_layer.py
python
_compute_targets
(ex_rois, gt_rois, labels)
return np.hstack( (labels[:, np.newaxis], targets)).astype(np.float32, copy=False)
Compute bounding-box regression targets for an image.
Compute bounding-box regression targets for an image.
[ "Compute", "bounding", "-", "box", "regression", "targets", "for", "an", "image", "." ]
def _compute_targets(ex_rois, gt_rois, labels): """Compute bounding-box regression targets for an image.""" assert ex_rois.shape[0] == gt_rois.shape[0] assert ex_rois.shape[1] == 4 assert gt_rois.shape[1] == 4 targets = bbox_transform(ex_rois, gt_rois) if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED: # Optionally normalize targets by a precomputed mean and stdev targets = ((targets - np.array(cfg.TRAIN.BBOX_NORMALIZE_MEANS)) / np.array(cfg.TRAIN.BBOX_NORMALIZE_STDS)) return np.hstack( (labels[:, np.newaxis], targets)).astype(np.float32, copy=False)
[ "def", "_compute_targets", "(", "ex_rois", ",", "gt_rois", ",", "labels", ")", ":", "assert", "ex_rois", ".", "shape", "[", "0", "]", "==", "gt_rois", ".", "shape", "[", "0", "]", "assert", "ex_rois", ".", "shape", "[", "1", "]", "==", "4", "assert",...
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/rfcn/lib/rpn/proposal_target_layer.py#L144-L157
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
outputBuffer.nodeDumpOutput
(self, doc, cur, level, format, encoding)
Dump an XML node, recursive behaviour, children are printed too. Note that @format = 1 provide node indenting only if xmlIndentTreeOutput = 1 or xmlKeepBlanksDefault(0) was called
Dump an XML node, recursive behaviour, children are printed too. Note that
[ "Dump", "an", "XML", "node", "recursive", "behaviour", "children", "are", "printed", "too", ".", "Note", "that" ]
def nodeDumpOutput(self, doc, cur, level, format, encoding): """Dump an XML node, recursive behaviour, children are printed too. Note that @format = 1 provide node indenting only if xmlIndentTreeOutput = 1 or xmlKeepBlanksDefault(0) was called """ if doc is None: doc__o = None else: doc__o = doc._o if cur is None: cur__o = None else: cur__o = cur._o libxml2mod.xmlNodeDumpOutput(self._o, doc__o, cur__o, level, format, encoding)
[ "def", "nodeDumpOutput", "(", "self", ",", "doc", ",", "cur", ",", "level", ",", "format", ",", "encoding", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "if", "cur", "is", "None", ...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L6069-L6078
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/framemanager.py
python
ShowDockingGuides
(guides, show)
Shows or hide the docking guide windows. :param `guides`: a list of :class:`AuiDockingGuide` classes; :param bool `show`: whether to show or hide the docking guide windows.
Shows or hide the docking guide windows.
[ "Shows", "or", "hide", "the", "docking", "guide", "windows", "." ]
def ShowDockingGuides(guides, show): """ Shows or hide the docking guide windows. :param `guides`: a list of :class:`AuiDockingGuide` classes; :param bool `show`: whether to show or hide the docking guide windows. """ for target in guides: if show and not target.host.IsShown(): target.host.Show() target.host.Update() elif not show and target.host.IsShown(): target.host.Hide()
[ "def", "ShowDockingGuides", "(", "guides", ",", "show", ")", ":", "for", "target", "in", "guides", ":", "if", "show", "and", "not", "target", ".", "host", ".", "IsShown", "(", ")", ":", "target", ".", "host", ".", "Show", "(", ")", "target", ".", "...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L3880-L3895
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/index_tricks.py
python
fill_diagonal
(a, val, wrap=False)
Fill the main diagonal of the given array of any dimensionality. For an array `a` with ``a.ndim > 2``, the diagonal is the list of locations with indices ``a[i, i, ..., i]`` all identical. This function modifies the input array in-place, it does not return a value. Parameters ---------- a : array, at least 2-D. Array whose diagonal is to be filled, it gets modified in-place. val : scalar Value to be written on the diagonal, its type must be compatible with that of the array a. wrap : bool For tall matrices in NumPy version up to 1.6.2, the diagonal "wrapped" after N columns. You can have this behavior with this option. This affect only tall matrices. See also -------- diag_indices, diag_indices_from Notes ----- .. versionadded:: 1.4.0 This functionality can be obtained via `diag_indices`, but internally this version uses a much faster implementation that never constructs the indices and uses simple slicing. Examples -------- >>> a = np.zeros((3, 3), int) >>> np.fill_diagonal(a, 5) >>> a array([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) The same function can operate on a 4-D array: >>> a = np.zeros((3, 3, 3, 3), int) >>> np.fill_diagonal(a, 4) We only show a few blocks for clarity: >>> a[0, 0] array([[4, 0, 0], [0, 0, 0], [0, 0, 0]]) >>> a[1, 1] array([[0, 0, 0], [0, 4, 0], [0, 0, 0]]) >>> a[2, 2] array([[0, 0, 0], [0, 0, 0], [0, 0, 4]]) # tall matrices no wrap >>> a = np.zeros((5, 3),int) >>> fill_diagonal(a, 4) array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [0, 0, 0]]) # tall matrices wrap >>> a = np.zeros((5, 3),int) >>> fill_diagonal(a, 4) array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [4, 0, 0]]) # wide matrices >>> a = np.zeros((3, 5),int) >>> fill_diagonal(a, 4) array([[4, 0, 0, 0, 0], [0, 4, 0, 0, 0], [0, 0, 4, 0, 0]])
Fill the main diagonal of the given array of any dimensionality.
[ "Fill", "the", "main", "diagonal", "of", "the", "given", "array", "of", "any", "dimensionality", "." ]
def fill_diagonal(a, val, wrap=False): """Fill the main diagonal of the given array of any dimensionality. For an array `a` with ``a.ndim > 2``, the diagonal is the list of locations with indices ``a[i, i, ..., i]`` all identical. This function modifies the input array in-place, it does not return a value. Parameters ---------- a : array, at least 2-D. Array whose diagonal is to be filled, it gets modified in-place. val : scalar Value to be written on the diagonal, its type must be compatible with that of the array a. wrap : bool For tall matrices in NumPy version up to 1.6.2, the diagonal "wrapped" after N columns. You can have this behavior with this option. This affect only tall matrices. See also -------- diag_indices, diag_indices_from Notes ----- .. versionadded:: 1.4.0 This functionality can be obtained via `diag_indices`, but internally this version uses a much faster implementation that never constructs the indices and uses simple slicing. Examples -------- >>> a = np.zeros((3, 3), int) >>> np.fill_diagonal(a, 5) >>> a array([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) The same function can operate on a 4-D array: >>> a = np.zeros((3, 3, 3, 3), int) >>> np.fill_diagonal(a, 4) We only show a few blocks for clarity: >>> a[0, 0] array([[4, 0, 0], [0, 0, 0], [0, 0, 0]]) >>> a[1, 1] array([[0, 0, 0], [0, 4, 0], [0, 0, 0]]) >>> a[2, 2] array([[0, 0, 0], [0, 0, 0], [0, 0, 4]]) # tall matrices no wrap >>> a = np.zeros((5, 3),int) >>> fill_diagonal(a, 4) array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [0, 0, 0]]) # tall matrices wrap >>> a = np.zeros((5, 3),int) >>> fill_diagonal(a, 4) array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [4, 0, 0]]) # wide matrices >>> a = np.zeros((3, 5),int) >>> fill_diagonal(a, 4) array([[4, 0, 0, 0, 0], [0, 4, 0, 0, 0], [0, 0, 4, 0, 0]]) """ if a.ndim < 2: raise ValueError("array must be at least 2-d") end = None if a.ndim == 2: # Explicit, fast formula for the common case. For 2-d arrays, we # accept rectangular ones. step = a.shape[1] + 1 #This is needed to don't have tall matrix have the diagonal wrap. if not wrap: end = a.shape[1] * a.shape[1] else: # For more than d=2, the strided formula is only valid for arrays with # all dimensions equal, so we check first. if not alltrue(diff(a.shape)==0): raise ValueError("All dimensions of input must be of equal length") step = 1 + (cumprod(a.shape[:-1])).sum() # Write the value out into the diagonal. a.flat[:end:step] = val
[ "def", "fill_diagonal", "(", "a", ",", "val", ",", "wrap", "=", "False", ")", ":", "if", "a", ".", "ndim", "<", "2", ":", "raise", "ValueError", "(", "\"array must be at least 2-d\"", ")", "end", "=", "None", "if", "a", ".", "ndim", "==", "2", ":", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/index_tricks.py#L645-L751
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBWatchpoint_GetWatchpointFromEvent
(*args)
return _lldb.SBWatchpoint_GetWatchpointFromEvent(*args)
SBWatchpoint_GetWatchpointFromEvent(SBEvent event) -> SBWatchpoint
SBWatchpoint_GetWatchpointFromEvent(SBEvent event) -> SBWatchpoint
[ "SBWatchpoint_GetWatchpointFromEvent", "(", "SBEvent", "event", ")", "-", ">", "SBWatchpoint" ]
def SBWatchpoint_GetWatchpointFromEvent(*args): """SBWatchpoint_GetWatchpointFromEvent(SBEvent event) -> SBWatchpoint""" return _lldb.SBWatchpoint_GetWatchpointFromEvent(*args)
[ "def", "SBWatchpoint_GetWatchpointFromEvent", "(", "*", "args", ")", ":", "return", "_lldb", ".", "SBWatchpoint_GetWatchpointFromEvent", "(", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L12691-L12693
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/devil/devil/android/device_utils.py
python
DeviceUtils.FileExists
(self, device_path, timeout=None, retries=None)
return self.PathExists(device_path, timeout=timeout, retries=retries)
Checks whether the given file exists on the device. Arguments are the same as PathExists.
Checks whether the given file exists on the device.
[ "Checks", "whether", "the", "given", "file", "exists", "on", "the", "device", "." ]
def FileExists(self, device_path, timeout=None, retries=None): """Checks whether the given file exists on the device. Arguments are the same as PathExists. """ return self.PathExists(device_path, timeout=timeout, retries=retries)
[ "def", "FileExists", "(", "self", ",", "device_path", ",", "timeout", "=", "None", ",", "retries", "=", "None", ")", ":", "return", "self", ".", "PathExists", "(", "device_path", ",", "timeout", "=", "timeout", ",", "retries", "=", "retries", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/device_utils.py#L1444-L1449
freesurfer/freesurfer
6dbe527d43ffa611acb2cd112e9469f9bfec8e36
python/freesurfer/ndarray.py
python
Volume.resample_like
(self, target, interp_method='linear', fill=0)
return resampled
Returns a resampled image in the target space.
Returns a resampled image in the target space.
[ "Returns", "a", "resampled", "image", "in", "the", "target", "space", "." ]
def resample_like(self, target, interp_method='linear', fill=0): ''' Returns a resampled image in the target space. ''' if target.affine is None or self.affine is None: raise ValueError("Can't resample volume without geometry information.") vox2vox = LinearTransform.matmul(self.ras2vox(), target.vox2ras()) resampled_data = resample(self.data, target.shape, vox2vox, interp_method=interp_method, fill=fill) resampled = Volume(resampled_data) resampled.copy_geometry(target) resampled.copy_metadata(self) return resampled
[ "def", "resample_like", "(", "self", ",", "target", ",", "interp_method", "=", "'linear'", ",", "fill", "=", "0", ")", ":", "if", "target", ".", "affine", "is", "None", "or", "self", ".", "affine", "is", "None", ":", "raise", "ValueError", "(", "\"Can'...
https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/python/freesurfer/ndarray.py#L519-L532
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py
python
IRBuilder.cmpxchg
(self, ptr, cmp, val, ordering, failordering=None, name='')
return inst
Atomic compared-and-set: atomic { old = *ptr success = (old == cmp) if (success) *ptr = val } name = { old, success } If failordering is `None`, the value of `ordering` is used.
Atomic compared-and-set: atomic { old = *ptr success = (old == cmp) if (success) *ptr = val } name = { old, success }
[ "Atomic", "compared", "-", "and", "-", "set", ":", "atomic", "{", "old", "=", "*", "ptr", "success", "=", "(", "old", "==", "cmp", ")", "if", "(", "success", ")", "*", "ptr", "=", "val", "}", "name", "=", "{", "old", "success", "}" ]
def cmpxchg(self, ptr, cmp, val, ordering, failordering=None, name=''): """ Atomic compared-and-set: atomic { old = *ptr success = (old == cmp) if (success) *ptr = val } name = { old, success } If failordering is `None`, the value of `ordering` is used. """ failordering = ordering if failordering is None else failordering inst = instructions.CmpXchg(self.block, ptr, cmp, val, ordering, failordering, name=name) self._insert(inst) return inst
[ "def", "cmpxchg", "(", "self", ",", "ptr", ",", "cmp", ",", "val", ",", "ordering", ",", "failordering", "=", "None", ",", "name", "=", "''", ")", ":", "failordering", "=", "ordering", "if", "failordering", "is", "None", "else", "failordering", "inst", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/builder.py#L960-L977
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/stats/_multivariate.py
python
multivariate_normal_gen.rvs
(self, mean=None, cov=1, size=1, random_state=None)
return _squeeze_output(out)
Draw random samples from a multivariate normal distribution. Parameters ---------- %(_mvn_doc_default_callparams)s size : integer, optional Number of samples to draw (default 1). %(_doc_random_state)s Returns ------- rvs : ndarray or scalar Random variates of size (`size`, `N`), where `N` is the dimension of the random variable. Notes ----- %(_mvn_doc_callparams_note)s
Draw random samples from a multivariate normal distribution.
[ "Draw", "random", "samples", "from", "a", "multivariate", "normal", "distribution", "." ]
def rvs(self, mean=None, cov=1, size=1, random_state=None): """ Draw random samples from a multivariate normal distribution. Parameters ---------- %(_mvn_doc_default_callparams)s size : integer, optional Number of samples to draw (default 1). %(_doc_random_state)s Returns ------- rvs : ndarray or scalar Random variates of size (`size`, `N`), where `N` is the dimension of the random variable. Notes ----- %(_mvn_doc_callparams_note)s """ dim, mean, cov = self._process_parameters(None, mean, cov) random_state = self._get_random_state(random_state) out = random_state.multivariate_normal(mean, cov, size) return _squeeze_output(out)
[ "def", "rvs", "(", "self", ",", "mean", "=", "None", ",", "cov", "=", "1", ",", "size", "=", "1", ",", "random_state", "=", "None", ")", ":", "dim", ",", "mean", ",", "cov", "=", "self", ".", "_process_parameters", "(", "None", ",", "mean", ",", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/stats/_multivariate.py#L635-L661
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/__init__.py
python
autocomplete
()
Command and option completion for the main option parser (and options) and its subcommands (and options). Enable by sourcing one of the completion shell scripts (bash or zsh).
Command and option completion for the main option parser (and options) and its subcommands (and options).
[ "Command", "and", "option", "completion", "for", "the", "main", "option", "parser", "(", "and", "options", ")", "and", "its", "subcommands", "(", "and", "options", ")", "." ]
def autocomplete(): """Command and option completion for the main option parser (and options) and its subcommands (and options). Enable by sourcing one of the completion shell scripts (bash or zsh). """ # Don't complete if user hasn't sourced bash_completion file. if 'PIP_AUTO_COMPLETE' not in os.environ: return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: current = cwords[cword - 1] except IndexError: current = '' subcommands = [cmd for cmd, summary in get_summaries()] options = [] # subcommand try: subcommand_name = [w for w in cwords if w in subcommands][0] except IndexError: subcommand_name = None parser = create_main_parser() # subcommand options if subcommand_name: # special case: 'help' subcommand has no options if subcommand_name == 'help': sys.exit(1) # special case: list locally installed dists for uninstall command if subcommand_name == 'uninstall' and not current.startswith('-'): installed = [] lc = current.lower() for dist in get_installed_distributions(local_only=True): if dist.key.startswith(lc) and dist.key not in cwords[1:]: installed.append(dist.key) # if there are no dists installed, fall back to option completion if installed: for dist in installed: print(dist) sys.exit(1) subcommand = commands[subcommand_name](parser) options += [(opt.get_opt_string(), opt.nargs) for opt in subcommand.parser.option_list_all if opt.help != optparse.SUPPRESS_HELP] # filter out previously specified options from available options prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]] options = [(x, v) for (x, v) in options if x not in prev_opts] # filter options by current input options = [(k, v) for k, v in options if k.startswith(current)] for option in options: opt_label = option[0] # append '=' to options which require args if option[1]: opt_label += '=' print(opt_label) else: # show main parser options only when necessary if current.startswith('-') or current.startswith('--'): opts = [i.option_list for i in parser.option_groups] opts.append(parser.option_list) opts = (o for it in opts for o in it) subcommands += [i.get_opt_string() for i in opts if i.help != optparse.SUPPRESS_HELP] print(' '.join([x for x in subcommands if x.startswith(current)])) sys.exit(1)
[ "def", "autocomplete", "(", ")", ":", "# Don't complete if user hasn't sourced bash_completion file.", "if", "'PIP_AUTO_COMPLETE'", "not", "in", "os", ".", "environ", ":", "return", "cwords", "=", "os", ".", "environ", "[", "'COMP_WORDS'", "]", ".", "split", "(", ...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/__init__.py#L19-L89
baidu/AnyQ
d94d450d2aaa5f7ed73424b10aa4539835b97527
tools/simnet/train/tf/layers/tf_layers.py
python
GRULayer.ops
(self, input_emb)
return rnn_outputs
operation
operation
[ "operation" ]
def ops(self, input_emb): """ operation """ rnn_outputs, _ = rnn(GRUCell(self.hidden_size), inputs=input_emb, dtype=tf.float32) return rnn_outputs
[ "def", "ops", "(", "self", ",", "input_emb", ")", ":", "rnn_outputs", ",", "_", "=", "rnn", "(", "GRUCell", "(", "self", ".", "hidden_size", ")", ",", "inputs", "=", "input_emb", ",", "dtype", "=", "tf", ".", "float32", ")", "return", "rnn_outputs" ]
https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/simnet/train/tf/layers/tf_layers.py#L191-L197
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/pyserial/serial/serialjava.py
python
Serial.close
(self)
Close port
Close port
[ "Close", "port" ]
def close(self): """Close port""" if self.is_open: if self.sPort: self._instream.close() self._outstream.close() self.sPort.close() self.sPort = None self.is_open = False
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "is_open", ":", "if", "self", ".", "sPort", ":", "self", ".", "_instream", ".", "close", "(", ")", "self", ".", "_outstream", ".", "close", "(", ")", "self", ".", "sPort", ".", "close", "(...
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialjava.py#L137-L145
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/command_argument.py
python
CommandArgument.MakeZeroOrMoreCloudBucketURLsArgument
()
return CommandArgument( 'file', nargs='*', completer=CompleterType.CLOUD_BUCKET)
Constructs an argument that takes 0+ Cloud bucket URLs as parameters.
Constructs an argument that takes 0+ Cloud bucket URLs as parameters.
[ "Constructs", "an", "argument", "that", "takes", "0", "+", "Cloud", "bucket", "URLs", "as", "parameters", "." ]
def MakeZeroOrMoreCloudBucketURLsArgument(): """Constructs an argument that takes 0+ Cloud bucket URLs as parameters.""" return CommandArgument( 'file', nargs='*', completer=CompleterType.CLOUD_BUCKET)
[ "def", "MakeZeroOrMoreCloudBucketURLsArgument", "(", ")", ":", "return", "CommandArgument", "(", "'file'", ",", "nargs", "=", "'*'", ",", "completer", "=", "CompleterType", ".", "CLOUD_BUCKET", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/command_argument.py#L51-L54
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/mozboot/mozboot/android.py
python
ensure_android_sdk_and_ndk
(path, sdk_path, sdk_url, ndk_path, ndk_url)
Ensure the Android SDK and NDK are found at the given paths. If not, fetch and unpack the SDK and/or NDK from the given URLs into |path|.
Ensure the Android SDK and NDK are found at the given paths. If not, fetch and unpack the SDK and/or NDK from the given URLs into |path|.
[ "Ensure", "the", "Android", "SDK", "and", "NDK", "are", "found", "at", "the", "given", "paths", ".", "If", "not", "fetch", "and", "unpack", "the", "SDK", "and", "/", "or", "NDK", "from", "the", "given", "URLs", "into", "|path|", "." ]
def ensure_android_sdk_and_ndk(path, sdk_path, sdk_url, ndk_path, ndk_url): ''' Ensure the Android SDK and NDK are found at the given paths. If not, fetch and unpack the SDK and/or NDK from the given URLs into |path|. ''' # It's not particularyl bad to overwrite the NDK toolchain, but it does take # a while to unpack, so let's avoid the disk activity if possible. The SDK # may prompt about licensing, so we do this first. if os.path.isdir(ndk_path): print(ANDROID_NDK_EXISTS % ndk_path) else: install_mobile_android_sdk_or_ndk(ndk_url, path) # We don't want to blindly overwrite, since we use the |android| tool to # install additional parts of the Android toolchain. If we overwrite, # we lose whatever Android packages the user may have already installed. if os.path.isdir(sdk_path): print(ANDROID_SDK_EXISTS % sdk_path) else: install_mobile_android_sdk_or_ndk(sdk_url, path)
[ "def", "ensure_android_sdk_and_ndk", "(", "path", ",", "sdk_path", ",", "sdk_url", ",", "ndk_path", ",", "ndk_url", ")", ":", "# It's not particularyl bad to overwrite the NDK toolchain, but it does take", "# a while to unpack, so let's avoid the disk activity if possible. The SDK", ...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozboot/mozboot/android.py#L159-L179
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/sketch.py
python
Sketch.sketch_ready
(self)
Returns True if the sketch has been executed on all the data. If the sketch is created with background == False (default), this will always return True. Otherwise, this will return False until the sketch is ready.
Returns True if the sketch has been executed on all the data. If the sketch is created with background == False (default), this will always return True. Otherwise, this will return False until the sketch is ready.
[ "Returns", "True", "if", "the", "sketch", "has", "been", "executed", "on", "all", "the", "data", ".", "If", "the", "sketch", "is", "created", "with", "background", "==", "False", "(", "default", ")", "this", "will", "always", "return", "True", ".", "Othe...
def sketch_ready(self): """ Returns True if the sketch has been executed on all the data. If the sketch is created with background == False (default), this will always return True. Otherwise, this will return False until the sketch is ready. """ with cython_context(): return self.__proxy__.sketch_ready()
[ "def", "sketch_ready", "(", "self", ")", ":", "with", "cython_context", "(", ")", ":", "return", "self", ".", "__proxy__", ".", "sketch_ready", "(", ")" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sketch.py#L489-L497
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/image/image.py
python
SequentialAug.dumps
(self)
return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]]
Override the default to avoid duplicate dump.
Override the default to avoid duplicate dump.
[ "Override", "the", "default", "to", "avoid", "duplicate", "dump", "." ]
def dumps(self): """Override the default to avoid duplicate dump.""" return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]]
[ "def", "dumps", "(", "self", ")", ":", "return", "[", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ",", "[", "x", ".", "dumps", "(", ")", "for", "x", "in", "self", ".", "ts", "]", "]" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/image/image.py#L799-L801
google-coral/edgetpu
5020de9386ff370dcc1f63291a2d0f98eeb98adb
benchmarks/classification_benchmarks.py
python
run_benchmark
(model, image)
return result
Returns average inference time in ms on specified model and image.
Returns average inference time in ms on specified model and image.
[ "Returns", "average", "inference", "time", "in", "ms", "on", "specified", "model", "and", "image", "." ]
def run_benchmark(model, image): """Returns average inference time in ms on specified model and image.""" print('Benchmark for [%s] on %s' % (model, image)) engine = ClassificationEngine(test_utils.test_data_path(model)) iterations = 200 if 'edgetpu' in model else 10 with test_utils.test_image(image) as img: result = 1000 * timeit.timeit( lambda: engine.classify_with_image(img, threshold=0.4, top_k=10), number=iterations) / iterations print('%.2f ms (iterations = %d)' % (result, iterations)) return result
[ "def", "run_benchmark", "(", "model", ",", "image", ")", ":", "print", "(", "'Benchmark for [%s] on %s'", "%", "(", "model", ",", "image", ")", ")", "engine", "=", "ClassificationEngine", "(", "test_utils", ".", "test_data_path", "(", "model", ")", ")", "ite...
https://github.com/google-coral/edgetpu/blob/5020de9386ff370dcc1f63291a2d0f98eeb98adb/benchmarks/classification_benchmarks.py#L24-L36
opengauss-mirror/openGauss-server
e383f1b77720a00ddbe4c0655bc85914d9b02a2b
src/gausskernel/dbmind/tools/xtuner/tuner/knob.py
python
RecommendedKnobs.__init__
(self)
Package tuned knobs. Record recommendation results and final tuning results and outputs formatted results text.
Package tuned knobs. Record recommendation results and final tuning results and outputs formatted results text.
[ "Package", "tuned", "knobs", ".", "Record", "recommendation", "results", "and", "final", "tuning", "results", "and", "outputs", "formatted", "results", "text", "." ]
def __init__(self): """ Package tuned knobs. Record recommendation results and final tuning results and outputs formatted results text. """ self._need_tune_knobs = list() self._only_report_knobs = list() self._tbl = dict() self.report = 'There is no report because the current mode specifies the list of tuning knobs ' \ 'through the configuration file.'
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "_need_tune_knobs", "=", "list", "(", ")", "self", ".", "_only_report_knobs", "=", "list", "(", ")", "self", ".", "_tbl", "=", "dict", "(", ")", "self", ".", "report", "=", "'There is no report becau...
https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/xtuner/tuner/knob.py#L29-L38
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/showutil/TexMemWatcher.py
python
TexPlacement.clearBitmasks
(self, bitmasks)
Clears all of the appropriate bits to indicate this region is available.
Clears all of the appropriate bits to indicate this region is available.
[ "Clears", "all", "of", "the", "appropriate", "bits", "to", "indicate", "this", "region", "is", "available", "." ]
def clearBitmasks(self, bitmasks): """ Clears all of the appropriate bits to indicate this region is available. """ l, r, b, t = self.p mask = ~BitArray.range(l, r - l) for yi in range(b, t): assert (bitmasks[yi] | mask).isAllOn() bitmasks[yi] &= mask
[ "def", "clearBitmasks", "(", "self", ",", "bitmasks", ")", ":", "l", ",", "r", ",", "b", ",", "t", "=", "self", ".", "p", "mask", "=", "~", "BitArray", ".", "range", "(", "l", ",", "r", "-", "l", ")", "for", "yi", "in", "range", "(", "b", "...
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showutil/TexMemWatcher.py#L1247-L1256
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
FontData.GetChosenFont
(*args, **kwargs)
return _windows_.FontData_GetChosenFont(*args, **kwargs)
GetChosenFont(self) -> Font Gets the font chosen by the user.
GetChosenFont(self) -> Font
[ "GetChosenFont", "(", "self", ")", "-", ">", "Font" ]
def GetChosenFont(*args, **kwargs): """ GetChosenFont(self) -> Font Gets the font chosen by the user. """ return _windows_.FontData_GetChosenFont(*args, **kwargs)
[ "def", "GetChosenFont", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "FontData_GetChosenFont", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L3485-L3491
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
SystemColourProperty.GetCustomColourIndex
(*args, **kwargs)
return _propgrid.SystemColourProperty_GetCustomColourIndex(*args, **kwargs)
GetCustomColourIndex(self) -> int
GetCustomColourIndex(self) -> int
[ "GetCustomColourIndex", "(", "self", ")", "-", ">", "int" ]
def GetCustomColourIndex(*args, **kwargs): """GetCustomColourIndex(self) -> int""" return _propgrid.SystemColourProperty_GetCustomColourIndex(*args, **kwargs)
[ "def", "GetCustomColourIndex", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "SystemColourProperty_GetCustomColourIndex", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L3315-L3317
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/autocomplete_w.py
python
AutoCompleteWindow.show_window
(self, comp_lists, index, complete, mode, userWantsWin)
return None
Show the autocomplete list, bind events. If complete is True, complete the text, and if there is exactly one matching completion, don't open a list.
Show the autocomplete list, bind events.
[ "Show", "the", "autocomplete", "list", "bind", "events", "." ]
def show_window(self, comp_lists, index, complete, mode, userWantsWin): """Show the autocomplete list, bind events. If complete is True, complete the text, and if there is exactly one matching completion, don't open a list. """ # Handle the start we already have self.completions, self.morecompletions = comp_lists self.mode = mode self.startindex = self.widget.index(index) self.start = self.widget.get(self.startindex, "insert") if complete: completed = self._complete_string(self.start) start = self.start self._change_start(completed) i = self._binary_search(completed) if self.completions[i] == completed and \ (i == len(self.completions)-1 or self.completions[i+1][:len(completed)] != completed): # There is exactly one matching completion return completed == start self.userwantswindow = userWantsWin self.lasttypedstart = self.start # Put widgets in place self.autocompletewindow = acw = Toplevel(self.widget) # Put it in a position so that it is not seen. acw.wm_geometry("+10000+10000") # Make it float acw.wm_overrideredirect(1) try: # This command is only needed and available on Tk >= 8.4.0 for OSX # Without it, call tips intrude on the typing process by grabbing # the focus. acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w, "help", "noActivates") except TclError: pass self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL) self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set, exportselection=False) for item in self.completions: listbox.insert(END, item) self.origselforeground = listbox.cget("selectforeground") self.origselbackground = listbox.cget("selectbackground") scrollbar.config(command=listbox.yview) scrollbar.pack(side=RIGHT, fill=Y) listbox.pack(side=LEFT, fill=BOTH, expand=True) acw.lift() # work around bug in Tk 8.5.18+ (issue #24570) # Initialize the listbox selection self.listbox.select_set(self._binary_search(self.start)) self._selection_changed() # bind events self.hideaid = acw.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) self.hidewid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) acw.event_add(HIDE_VIRTUAL_EVENT_NAME, HIDE_FOCUS_OUT_SEQUENCE) for seq in HIDE_SEQUENCES: self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq) self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypress_event) for seq in KEYPRESS_SEQUENCES: self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq) self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyrelease_event) self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE) self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE, self.listselect_event) self.is_configuring = False self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event) self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE, self.doubleclick_event) return None
[ "def", "show_window", "(", "self", ",", "comp_lists", ",", "index", ",", "complete", ",", "mode", ",", "userWantsWin", ")", ":", "# Handle the start we already have", "self", ".", "completions", ",", "self", ".", "morecompletions", "=", "comp_lists", "self", "."...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/autocomplete_w.py#L158-L232
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/graph_editor/util.py
python
ControlOutputs.update
(self)
return self
Update the control outputs if the graph has changed.
Update the control outputs if the graph has changed.
[ "Update", "the", "control", "outputs", "if", "the", "graph", "has", "changed", "." ]
def update(self): """Update the control outputs if the graph has changed.""" if self._version != self._graph.version: self._build() return self
[ "def", "update", "(", "self", ")", ":", "if", "self", ".", "_version", "!=", "self", ".", "_graph", ".", "version", ":", "self", ".", "_build", "(", ")", "return", "self" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/graph_editor/util.py#L353-L357
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
bindings/experimental/distrdf/python/DistRDF/HeadNode.py
python
TreeHeadNode.__init__
(self, npartitions, *args)
Creates a new RDataFrame instance for the given arguments. Args: *args (iterable): Iterable with the arguments to the RDataFrame constructor. npartitions (int): The number of partitions the dataset will be split in for distributed execution.
Creates a new RDataFrame instance for the given arguments.
[ "Creates", "a", "new", "RDataFrame", "instance", "for", "the", "given", "arguments", "." ]
def __init__(self, npartitions, *args): """ Creates a new RDataFrame instance for the given arguments. Args: *args (iterable): Iterable with the arguments to the RDataFrame constructor. npartitions (int): The number of partitions the dataset will be split in for distributed execution. """ super(TreeHeadNode, self).__init__(None, None) self.npartitions = npartitions self.defaultbranches = None self.friendinfo = None # Retrieve the TTree/TChain that will be processed if isinstance(args[0], ROOT.TTree): # RDataFrame(tree, defaultBranches = {}) self.tree = args[0] # Retrieve information about friend trees when user passes a TTree # or TChain object. self.friendinfo = ROOT.Internal.TreeUtils.GetFriendInfo(args[0]) if len(args) == 2: self.defaultbranches = args[1] else: if isinstance(args[1], ROOT.TDirectory): # RDataFrame(treeName, dirPtr, defaultBranches = {}) # We can assume both the argument TDirectory* and the TTree* # returned from TDirectory::Get are not nullptr since we already # did and early check of the user arguments in get_headnode self.tree = args[1].Get(args[0]) elif isinstance(args[1], (str, ROOT.std.string_view)): # RDataFrame(treeName, filenameglob, defaultBranches = {}) self.tree = ROOT.TChain(args[0]) self.tree.Add(str(args[1])) elif isinstance(args[1], (list, ROOT.std.vector[ROOT.std.string])): # RDataFrame(treename, fileglobs, defaultBranches = {}) self.tree = ROOT.TChain(args[0]) for filename in args[1]: self.tree.Add(str(filename)) # In any of the three constructors considered in this branch, if # the user supplied three arguments then the third argument is a # list of default branches if len(args) == 3: self.defaultbranches = args[2] # maintreename: name of the tree or main name of the chain self.maintreename = self.tree.GetName() # subtreenames: names of all subtrees in the chain or full path to the tree in the file it belongs to self.subtreenames = [str(treename) for treename in ROOT.Internal.TreeUtils.GetTreeFullPaths(self.tree)] self.inputfiles = [str(filename) for filename in ROOT.Internal.TreeUtils.GetFileNamesFromTree(self.tree)]
[ "def", "__init__", "(", "self", ",", "npartitions", ",", "*", "args", ")", ":", "super", "(", "TreeHeadNode", ",", "self", ")", ".", "__init__", "(", "None", ",", "None", ")", "self", ".", "npartitions", "=", "npartitions", "self", ".", "defaultbranches"...
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/bindings/experimental/distrdf/python/DistRDF/HeadNode.py#L144-L197
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/value_object/init/game_version.py
python
GameExpansion.__init__
(self, name, game_id, support, game_hashes, media_paths, modpacks, **flags)
Create a new GameExpansion instance. :param name: Name of the game. :type name: str :param game_id: Unique id for the given game. :type game_id: str
Create a new GameExpansion instance.
[ "Create", "a", "new", "GameExpansion", "instance", "." ]
def __init__(self, name, game_id, support, game_hashes, media_paths, modpacks, **flags): """ Create a new GameExpansion instance. :param name: Name of the game. :type name: str :param game_id: Unique id for the given game. :type game_id: str """ super().__init__(game_id, support, game_hashes, media_paths, modpacks, **flags) self.expansion_name = name
[ "def", "__init__", "(", "self", ",", "name", ",", "game_id", ",", "support", ",", "game_hashes", ",", "media_paths", ",", "modpacks", ",", "*", "*", "flags", ")", ":", "super", "(", ")", ".", "__init__", "(", "game_id", ",", "support", ",", "game_hashe...
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/value_object/init/game_version.py#L97-L110
crosslife/OpenBird
9e0198a1a2295f03fa1e8676e216e22c9c7d380b
cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
CursorKind.name
(self)
return self._name_map[self]
Get the enumeration name of this cursor kind.
Get the enumeration name of this cursor kind.
[ "Get", "the", "enumeration", "name", "of", "this", "cursor", "kind", "." ]
def name(self): """Get the enumeration name of this cursor kind.""" if self._name_map is None: self._name_map = {} for key,value in CursorKind.__dict__.items(): if isinstance(value,CursorKind): self._name_map[value] = key return self._name_map[self]
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "_name_map", "is", "None", ":", "self", ".", "_name_map", "=", "{", "}", "for", "key", ",", "value", "in", "CursorKind", ".", "__dict__", ".", "items", "(", ")", ":", "if", "isinstance", "(",...
https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L499-L506
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/shutil.py
python
_make_zipfile
(base_name, base_dir, verbose=0, dry_run=0, logger=None)
return zip_filename
Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file.
Create a zip file from all the files under 'base_dir'.
[ "Create", "a", "zip", "file", "from", "all", "the", "files", "under", "base_dir", "." ]
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Returns the name of the output zip file. """ zip_filename = base_name + ".zip" archive_dir = os.path.dirname(base_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", archive_dir) if not dry_run: os.makedirs(archive_dir) # If zipfile module is not available, try spawning an external 'zip' # command. try: import zipfile except ImportError: zipfile = None if zipfile is None: _call_external_zip(base_dir, zip_filename, verbose, dry_run) else: if logger is not None: logger.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) if not dry_run: zip = zipfile.ZipFile(zip_filename, "w", compression=zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(base_dir): for name in filenames: path = os.path.normpath(os.path.join(dirpath, name)) if os.path.isfile(path): zip.write(path, path) if logger is not None: logger.info("adding '%s'", path) zip.close() return zip_filename
[ "def", "_make_zipfile", "(", "base_name", ",", "base_dir", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "logger", "=", "None", ")", ":", "zip_filename", "=", "base_name", "+", "\".zip\"", "archive_dir", "=", "os", ".", "path", ".", "dirname",...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/shutil.py#L452-L497
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/python/google/process_utils.py
python
RunCommandFull
(command, verbose=True, collect_output=False, print_output=True)
return (proc.returncode, output)
Runs the command list. Prints the given command (which should be a list of one or more strings). If specified, prints its stderr (and optionally stdout) to stdout, line-buffered, converting line endings to CRLF (see note below). If specified, collects the output as a list of lines and returns it. Waits for the command to terminate and returns its status. Args: command: the full command to run, as a list of one or more strings verbose: if True, combines all output (stdout and stderr) into stdout. Otherwise, prints only the command's stderr to stdout. collect_output: if True, collects the output of the command as a list of lines and returns it print_output: if True, prints the output of the command Returns: A tuple consisting of the process's exit status and output. If collect_output is False, the output will be []. Raises: CommandNotFound if the command executable could not be found.
Runs the command list.
[ "Runs", "the", "command", "list", "." ]
def RunCommandFull(command, verbose=True, collect_output=False, print_output=True): """Runs the command list. Prints the given command (which should be a list of one or more strings). If specified, prints its stderr (and optionally stdout) to stdout, line-buffered, converting line endings to CRLF (see note below). If specified, collects the output as a list of lines and returns it. Waits for the command to terminate and returns its status. Args: command: the full command to run, as a list of one or more strings verbose: if True, combines all output (stdout and stderr) into stdout. Otherwise, prints only the command's stderr to stdout. collect_output: if True, collects the output of the command as a list of lines and returns it print_output: if True, prints the output of the command Returns: A tuple consisting of the process's exit status and output. If collect_output is False, the output will be []. Raises: CommandNotFound if the command executable could not be found. """ print '\n' + subprocess.list2cmdline(command).replace('\\', '/') + '\n', ### if verbose: out = subprocess.PIPE err = subprocess.STDOUT else: out = file(os.devnull, 'w') err = subprocess.PIPE try: proc = subprocess.Popen(command, stdout=out, stderr=err, bufsize=1) except OSError, e: if e.errno == errno.ENOENT: raise CommandNotFound('Unable to find "%s"' % command[0]) raise output = [] if verbose: read_from = proc.stdout else: read_from = proc.stderr line = read_from.readline() while line: line = line.rstrip() if collect_output: output.append(line) if print_output: # Windows Python converts \n to \r\n automatically whenever it # encounters it written to a text file (including stdout). The only # way around it is to write to a binary file, which isn't feasible for # stdout. So we end up with \r\n here even though we explicitly write # \n. (We could write \r instead, which doesn't get converted to \r\n, # but that's probably more troublesome for people trying to read the # files.) print line + '\n', # Python on windows writes the buffer only when it reaches 4k. This is # not fast enough for all purposes. sys.stdout.flush() line = read_from.readline() # Make sure the process terminates. proc.wait() if not verbose: out.close() return (proc.returncode, output)
[ "def", "RunCommandFull", "(", "command", ",", "verbose", "=", "True", ",", "collect_output", "=", "False", ",", "print_output", "=", "True", ")", ":", "print", "'\\n'", "+", "subprocess", ".", "list2cmdline", "(", "command", ")", ".", "replace", "(", "'\\\...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/python/google/process_utils.py#L40-L113
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
onnxruntime/python/onnxruntime_inference_collection.py
python
SparseTensor.__init__
(self, sparse_tensor)
Internal constructor
Internal constructor
[ "Internal", "constructor" ]
def __init__(self, sparse_tensor): ''' Internal constructor ''' if isinstance(sparse_tensor, C.SparseTensor): self._tensor = sparse_tensor else: # An end user won't hit this error raise ValueError("`Provided object` needs to be of type " + "`onnxruntime.capi.onnxruntime_pybind11_state.SparseTensor`")
[ "def", "__init__", "(", "self", ",", "sparse_tensor", ")", ":", "if", "isinstance", "(", "sparse_tensor", ",", "C", ".", "SparseTensor", ")", ":", "self", ".", "_tensor", "=", "sparse_tensor", "else", ":", "# An end user won't hit this error", "raise", "ValueErr...
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/onnxruntime_inference_collection.py#L680-L689
LisaAnne/lisa-caffe-public
49b8643ddef23a4f6120017968de30c45e693f59
scripts/cpp_lint.py
python
_CppLintState.SetFilters
(self, filters)
Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
Sets the error-message filters.
[ "Sets", "the", "error", "-", "message", "filters", "." ]
def SetFilters(self, filters): """Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" """ # Default filters always have less priority than the flag ones. self.filters = _DEFAULT_FILTERS[:] for filt in filters.split(','): clean_filt = filt.strip() if clean_filt: self.filters.append(clean_filt) for filt in self.filters: if not (filt.startswith('+') or filt.startswith('-')): raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt)
[ "def", "SetFilters", "(", "self", ",", "filters", ")", ":", "# Default filters always have less priority than the flag ones.", "self", ".", "filters", "=", "_DEFAULT_FILTERS", "[", ":", "]", "for", "filt", "in", "filters", ".", "split", "(", "','", ")", ":", "cl...
https://github.com/LisaAnne/lisa-caffe-public/blob/49b8643ddef23a4f6120017968de30c45e693f59/scripts/cpp_lint.py#L717-L740
baidu/bigflow
449245016c0df7d1252e85581e588bfc60cefad3
bigflow_python/python/bigflow/transform_impls/processor.py
python
AbstractProcessor.begin
(self, keys, inputs, emitter)
Indicate the beginning of a group Args: keys (list): keys of the group to start inputs (list): re-iterable inputs with the group emitter (FlumeEmitter): emitter to send the output
Indicate the beginning of a group
[ "Indicate", "the", "beginning", "of", "a", "group" ]
def begin(self, keys, inputs, emitter): """ Indicate the beginning of a group Args: keys (list): keys of the group to start inputs (list): re-iterable inputs with the group emitter (FlumeEmitter): emitter to send the output """ self._emitter = emitter pass
[ "def", "begin", "(", "self", ",", "keys", ",", "inputs", ",", "emitter", ")", ":", "self", ".", "_emitter", "=", "emitter", "pass" ]
https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/transform_impls/processor.py#L39-L49
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/wire_format.py
python
IsTypePackable
(field_type)
return field_type not in NON_PACKABLE_TYPES
Return true iff packable = true is valid for fields of this type. Args: field_type: a FieldDescriptor::Type value. Returns: True iff fields of this type are packable.
Return true iff packable = true is valid for fields of this type.
[ "Return", "true", "iff", "packable", "=", "true", "is", "valid", "for", "fields", "of", "this", "type", "." ]
def IsTypePackable(field_type): """Return true iff packable = true is valid for fields of this type. Args: field_type: a FieldDescriptor::Type value. Returns: True iff fields of this type are packable. """ return field_type not in NON_PACKABLE_TYPES
[ "def", "IsTypePackable", "(", "field_type", ")", ":", "return", "field_type", "not", "in", "NON_PACKABLE_TYPES" ]
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/wire_format.py#L259-L268
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Wm.wm_group
(self, pathName=None)
return self.tk.call('wm', 'group', self._w, pathName)
Set the group leader widgets for related widgets to PATHNAME. Return the group leader of this widget if None is given.
Set the group leader widgets for related widgets to PATHNAME. Return the group leader of this widget if None is given.
[ "Set", "the", "group", "leader", "widgets", "for", "related", "widgets", "to", "PATHNAME", ".", "Return", "the", "group", "leader", "of", "this", "widget", "if", "None", "is", "given", "." ]
def wm_group(self, pathName=None): """Set the group leader widgets for related widgets to PATHNAME. Return the group leader of this widget if None is given.""" return self.tk.call('wm', 'group', self._w, pathName)
[ "def", "wm_group", "(", "self", ",", "pathName", "=", "None", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "'wm'", ",", "'group'", ",", "self", ".", "_w", ",", "pathName", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1607-L1610
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/trade.py
python
Trade.__repr__
(self)
return self.to_str()
For `print` and `pprint`
For `print` and `pprint`
[ "For", "print", "and", "pprint" ]
def __repr__(self): """For `print` and `pprint`""" return self.to_str()
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "to_str", "(", ")" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/trade.py#L338-L340
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py
python
Metrowerks_Shell_Suite_Events.Get_Segments
(self, _no_object=None, _attributes={}, **_arguments)
Get Segments: Returns a description of each segment in the project. Keyword argument _attributes: AppleEvent attribute dictionary Returns: undocumented, typecode 'Seg '
Get Segments: Returns a description of each segment in the project. Keyword argument _attributes: AppleEvent attribute dictionary Returns: undocumented, typecode 'Seg '
[ "Get", "Segments", ":", "Returns", "a", "description", "of", "each", "segment", "in", "the", "project", ".", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary", "Returns", ":", "undocumented", "typecode", "Seg" ]
def Get_Segments(self, _no_object=None, _attributes={}, **_arguments): """Get Segments: Returns a description of each segment in the project. Keyword argument _attributes: AppleEvent attribute dictionary Returns: undocumented, typecode 'Seg ' """ _code = 'MMPR' _subcode = 'GSeg' if _arguments: raise TypeError, 'No optional args expected' if _no_object is not None: raise TypeError, 'No direct arg expected' _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "Get_Segments", "(", "self", ",", "_no_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'MMPR'", "_subcode", "=", "'GSeg'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No opti...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py#L277-L295
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/profiler/parser/integrator.py
python
BaseTimelineGenerator.get_thread_label_name
(self)
return [ {"name": "process_labels", "ph": "M", "pid": self._device_id, "args": {"labels": "AI Core Op"}}, {"name": "process_labels", "ph": "M", "pid": self._AI_CPU_PID, "args": {"labels": "AI CPU Op"}}, {"name": "process_labels", "ph": "M", "pid": self._COMMUNICATION_OP_PID, "args": {"labels": "Communication Op"}}, {"name": "process_labels", "ph": "M", "pid": self._HOST_CPU_PID, "args": {"labels": "Host CPU Op"}}, {"name": "process_labels", "ph": "M", "pid": self._OP_OVERLAP_PID, "args": {"labels": "Op Overlap Analyse"}}, {"name": "process_sort_index", "ph": "M", "pid": self._device_id, "args": {"sort_index": 0}}, {"name": "process_sort_index", "ph": "M", "pid": self._AI_CPU_PID, "args": {"sort_index": 10}}, {"name": "process_sort_index", "ph": "M", "pid": self._COMMUNICATION_OP_PID, "args": {"sort_index": 20}}, {"name": "process_sort_index", "ph": "M", "pid": self._HOST_CPU_PID, "args": {"sort_index": 30}}, {"name": "process_sort_index", "ph": "M", "pid": self._OP_OVERLAP_PID, "args": {"sort_index": 40}}, {"name": "thread_name", "ph": "M", "pid": self._HOST_CPU_PID, "tid": self._HOST_CPU_OP_TID, "args": {"name": "Host CPU Op"}}, {"name": "thread_name", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._MERGED_COMPUTATION_TID, "args": {"name": "Merged Computation Op"}}, {"name": "thread_name", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._PURE_COMMUNICATION_TID, "args": {"name": "Pure Communication Op"}}, {"name": "thread_name", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._MERGED_COMMUNICATION_TID, "args": {"name": "Merged Communication Op"}}, {"name": "thread_name", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._FREE_TIME_TID, "args": {"name": "Free Time"}}, {"name": "thread_sort_index", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._MERGED_COMPUTATION_TID, "args": {"sort_index": self._MERGED_COMPUTATION_TID}}, {"name": "thread_sort_index", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._PURE_COMMUNICATION_TID, "args": {"sort_index": self._PURE_COMMUNICATION_TID}}, {"name": "thread_sort_index", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._MERGED_COMMUNICATION_TID, "args": {"sort_index": self._MERGED_COMMUNICATION_TID}}, {"name": "thread_sort_index", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._FREE_TIME_TID, "args": {"sort_index": self._FREE_TIME_TID}} ]
Get process and thread config.
Get process and thread config.
[ "Get", "process", "and", "thread", "config", "." ]
def get_thread_label_name(self): """Get process and thread config.""" return [ {"name": "process_labels", "ph": "M", "pid": self._device_id, "args": {"labels": "AI Core Op"}}, {"name": "process_labels", "ph": "M", "pid": self._AI_CPU_PID, "args": {"labels": "AI CPU Op"}}, {"name": "process_labels", "ph": "M", "pid": self._COMMUNICATION_OP_PID, "args": {"labels": "Communication Op"}}, {"name": "process_labels", "ph": "M", "pid": self._HOST_CPU_PID, "args": {"labels": "Host CPU Op"}}, {"name": "process_labels", "ph": "M", "pid": self._OP_OVERLAP_PID, "args": {"labels": "Op Overlap Analyse"}}, {"name": "process_sort_index", "ph": "M", "pid": self._device_id, "args": {"sort_index": 0}}, {"name": "process_sort_index", "ph": "M", "pid": self._AI_CPU_PID, "args": {"sort_index": 10}}, {"name": "process_sort_index", "ph": "M", "pid": self._COMMUNICATION_OP_PID, "args": {"sort_index": 20}}, {"name": "process_sort_index", "ph": "M", "pid": self._HOST_CPU_PID, "args": {"sort_index": 30}}, {"name": "process_sort_index", "ph": "M", "pid": self._OP_OVERLAP_PID, "args": {"sort_index": 40}}, {"name": "thread_name", "ph": "M", "pid": self._HOST_CPU_PID, "tid": self._HOST_CPU_OP_TID, "args": {"name": "Host CPU Op"}}, {"name": "thread_name", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._MERGED_COMPUTATION_TID, "args": {"name": "Merged Computation Op"}}, {"name": "thread_name", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._PURE_COMMUNICATION_TID, "args": {"name": "Pure Communication Op"}}, {"name": "thread_name", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._MERGED_COMMUNICATION_TID, "args": {"name": "Merged Communication Op"}}, {"name": "thread_name", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._FREE_TIME_TID, "args": {"name": "Free Time"}}, {"name": "thread_sort_index", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._MERGED_COMPUTATION_TID, "args": {"sort_index": self._MERGED_COMPUTATION_TID}}, {"name": "thread_sort_index", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._PURE_COMMUNICATION_TID, "args": {"sort_index": self._PURE_COMMUNICATION_TID}}, {"name": "thread_sort_index", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._MERGED_COMMUNICATION_TID, "args": {"sort_index": self._MERGED_COMMUNICATION_TID}}, {"name": "thread_sort_index", "ph": "M", "pid": self._OP_OVERLAP_PID, "tid": self._FREE_TIME_TID, "args": {"sort_index": self._FREE_TIME_TID}} ]
[ "def", "get_thread_label_name", "(", "self", ")", ":", "return", "[", "{", "\"name\"", ":", "\"process_labels\"", ",", "\"ph\"", ":", "\"M\"", ",", "\"pid\"", ":", "self", ".", "_device_id", ",", "\"args\"", ":", "{", "\"labels\"", ":", "\"AI Core Op\"", "}"...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/integrator.py#L544-L580
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/download.py
python
DownloadOutputManager.get_io_write_task
(self, fileobj, data, offset)
return IOWriteTask( self._transfer_coordinator, main_kwargs={ 'fileobj': fileobj, 'data': data, 'offset': offset, } )
Get an IO write task for the requested set of data This task can be ran immediately or be submitted to the IO executor for it to run. :type fileobj: file-like object :param fileobj: The file-like object to write to :type data: bytes :param data: The data to write out :type offset: integer :param offset: The offset to write the data to in the file-like object :returns: An IO task to be used to write data to a file-like object
Get an IO write task for the requested set of data
[ "Get", "an", "IO", "write", "task", "for", "the", "requested", "set", "of", "data" ]
def get_io_write_task(self, fileobj, data, offset): """Get an IO write task for the requested set of data This task can be ran immediately or be submitted to the IO executor for it to run. :type fileobj: file-like object :param fileobj: The file-like object to write to :type data: bytes :param data: The data to write out :type offset: integer :param offset: The offset to write the data to in the file-like object :returns: An IO task to be used to write data to a file-like object """ return IOWriteTask( self._transfer_coordinator, main_kwargs={ 'fileobj': fileobj, 'data': data, 'offset': offset, } )
[ "def", "get_io_write_task", "(", "self", ",", "fileobj", ",", "data", ",", "offset", ")", ":", "return", "IOWriteTask", "(", "self", ".", "_transfer_coordinator", ",", "main_kwargs", "=", "{", "'fileobj'", ":", "fileobj", ",", "'data'", ":", "data", ",", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/s3transfer/download.py#L103-L127
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Fem/ObjectsFem.py
python
makeEquationElectricforce
( doc, base_solver=None, name="Electricforce" )
return obj
makeEquationElectricforce(document, [base_solver], [name]): creates a FEM Electricforce equation for a solver
makeEquationElectricforce(document, [base_solver], [name]): creates a FEM Electricforce equation for a solver
[ "makeEquationElectricforce", "(", "document", "[", "base_solver", "]", "[", "name", "]", ")", ":", "creates", "a", "FEM", "Electricforce", "equation", "for", "a", "solver" ]
def makeEquationElectricforce( doc, base_solver=None, name="Electricforce" ): """makeEquationElectricforce(document, [base_solver], [name]): creates a FEM Electricforce equation for a solver""" from femsolver.elmer.equations import electricforce obj = electricforce.create(doc, name) if base_solver: base_solver.addObject(obj) return obj
[ "def", "makeEquationElectricforce", "(", "doc", ",", "base_solver", "=", "None", ",", "name", "=", "\"Electricforce\"", ")", ":", "from", "femsolver", ".", "elmer", ".", "equations", "import", "electricforce", "obj", "=", "electricforce", ".", "create", "(", "...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/ObjectsFem.py#L705-L716
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/engine/datasets.py
python
Dataset.__init_size_getter
(self)
return getter, runtime_context, api_tree
Get pipeline information.
Get pipeline information.
[ "Get", "pipeline", "information", "." ]
def __init_size_getter(self): """ Get pipeline information. """ ir_tree, api_tree = self.create_ir_tree() runtime_context = cde.PythonRuntimeContext() runtime_context.Init() getter = cde.DatasetSizeGetters() getter.Init(ir_tree) runtime_context.AssignConsumer(getter) return getter, runtime_context, api_tree
[ "def", "__init_size_getter", "(", "self", ")", ":", "ir_tree", ",", "api_tree", "=", "self", ".", "create_ir_tree", "(", ")", "runtime_context", "=", "cde", ".", "PythonRuntimeContext", "(", ")", "runtime_context", ".", "Init", "(", ")", "getter", "=", "cde"...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/datasets.py#L1449-L1460
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy/multiarray.py
python
isnan
(x, out=None, **kwargs)
return _mx_nd_np.isnan(x, out=out, **kwargs)
Test element-wise for NaN and return result as a boolean array. Parameters ---------- x : ndarray Input array. out : ndarray or None, optional A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or `None`, a freshly-allocated array is returned. Returns ------- y : ndarray or bool True where x is NaN, false otherwise. This is a scalar if x is a scalar. Notes ----- NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). .. note:: This function differs from the original `numpy.isinf <https://docs.scipy.org/doc/numpy/reference/generated/numpy.isnan.html>`_ in the following aspects: * Does not support complex number for now * Input type does not support Python native iterables(list, tuple, ...). * ``out`` param: cannot perform auto broadcasting. ``out`` ndarray's shape must be the same as the expected output. * ``out`` param: cannot perform auto type cast. ``out`` ndarray's dtype must be the same as the expected output. * ``out`` param does not support scalar input case. Examples -------- >>> np.isnan(np.nan) True >>> np.isnan(np.inf) False >>> np.isnan(np.array([np.log(-1.),1.,np.log(0)])) array([ True, False, False])
Test element-wise for NaN and return result as a boolean array.
[ "Test", "element", "-", "wise", "for", "NaN", "and", "return", "result", "as", "a", "boolean", "array", "." ]
def isnan(x, out=None, **kwargs): """ Test element-wise for NaN and return result as a boolean array. Parameters ---------- x : ndarray Input array. out : ndarray or None, optional A location into which the result is stored. If provided, it must have the same shape and dtype as input ndarray. If not provided or `None`, a freshly-allocated array is returned. Returns ------- y : ndarray or bool True where x is NaN, false otherwise. This is a scalar if x is a scalar. Notes ----- NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). .. note:: This function differs from the original `numpy.isinf <https://docs.scipy.org/doc/numpy/reference/generated/numpy.isnan.html>`_ in the following aspects: * Does not support complex number for now * Input type does not support Python native iterables(list, tuple, ...). * ``out`` param: cannot perform auto broadcasting. ``out`` ndarray's shape must be the same as the expected output. * ``out`` param: cannot perform auto type cast. ``out`` ndarray's dtype must be the same as the expected output. * ``out`` param does not support scalar input case. Examples -------- >>> np.isnan(np.nan) True >>> np.isnan(np.inf) False >>> np.isnan(np.array([np.log(-1.),1.,np.log(0)])) array([ True, False, False]) """ return _mx_nd_np.isnan(x, out=out, **kwargs)
[ "def", "isnan", "(", "x", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_mx_nd_np", ".", "isnan", "(", "x", ",", "out", "=", "out", ",", "*", "*", "kwargs", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L11986-L12032
Ifsttar/I-Simpa
2283385f4cac769a92e265edabb9c79cb6c42d03
currentRelease/SystemScript/graphy/common.py
python
Marker.__init__
(self, shape, color, size)
Construct a Marker. See class docstring for details on args.
Construct a Marker. See class docstring for details on args.
[ "Construct", "a", "Marker", ".", "See", "class", "docstring", "for", "details", "on", "args", "." ]
def __init__(self, shape, color, size): """Construct a Marker. See class docstring for details on args.""" # TODO: Shapes 'r' and 'b' would be much easier to use if they had a # special-purpose API (instead of trying to fake it with markers) self.shape = shape self.color = color self.size = size
[ "def", "__init__", "(", "self", ",", "shape", ",", "color", ",", "size", ")", ":", "# TODO: Shapes 'r' and 'b' would be much easier to use if they had a", "# special-purpose API (instead of trying to fake it with markers)", "self", ".", "shape", "=", "shape", "self", ".", "...
https://github.com/Ifsttar/I-Simpa/blob/2283385f4cac769a92e265edabb9c79cb6c42d03/currentRelease/SystemScript/graphy/common.py#L50-L56
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/appdirs.py
python
_get_win_folder_from_registry
(csidl_name)
return dir
This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names.
This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names.
[ "This", "is", "a", "fallback", "technique", "at", "best", ".", "I", "m", "not", "sure", "if", "using", "the", "registry", "for", "this", "guarantees", "us", "the", "correct", "answer", "for", "all", "CSIDL_", "*", "names", "." ]
def _get_win_folder_from_registry(csidl_name): """This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ if PY3: import winreg as _winreg else: import _winreg shell_folder_name = { "CSIDL_APPDATA": "AppData", "CSIDL_COMMON_APPDATA": "Common AppData", "CSIDL_LOCAL_APPDATA": "Local AppData", }[csidl_name] key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) dir, type = _winreg.QueryValueEx(key, shell_folder_name) return dir
[ "def", "_get_win_folder_from_registry", "(", "csidl_name", ")", ":", "if", "PY3", ":", "import", "winreg", "as", "_winreg", "else", ":", "import", "_winreg", "shell_folder_name", "=", "{", "\"CSIDL_APPDATA\"", ":", "\"AppData\"", ",", "\"CSIDL_COMMON_APPDATA\"", ":"...
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/appdirs.py#L455-L476
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
storage/ndb/mcc/util.py
python
ConvertToPython.endElement
(self, name)
Pops the element stack and inserts the popped element as a child of the new top
Pops the element stack and inserts the popped element as a child of the new top
[ "Pops", "the", "element", "stack", "and", "inserts", "the", "popped", "element", "as", "a", "child", "of", "the", "new", "top" ]
def endElement(self, name): """Pops the element stack and inserts the popped element as a child of the new top""" #print 'end(', name, ')' if len(self._estack) > 1: e = self._estack.pop() self._estack[-1].append(e)
[ "def", "endElement", "(", "self", ",", "name", ")", ":", "#print 'end(', name, ')'", "if", "len", "(", "self", ".", "_estack", ")", ">", "1", ":", "e", "=", "self", ".", "_estack", ".", "pop", "(", ")", "self", ".", "_estack", "[", "-", "1", "]", ...
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/storage/ndb/mcc/util.py#L182-L188
carla-simulator/carla
8854804f4d7748e14d937ec763a2912823a7e5f5
PythonAPI/carla/agents/tools/misc.py
python
vector
(location_1, location_2)
return [x / norm, y / norm, z / norm]
Returns the unit vector from location_1 to location_2 :param location_1, location_2: carla.Location objects
Returns the unit vector from location_1 to location_2
[ "Returns", "the", "unit", "vector", "from", "location_1", "to", "location_2" ]
def vector(location_1, location_2): """ Returns the unit vector from location_1 to location_2 :param location_1, location_2: carla.Location objects """ x = location_2.x - location_1.x y = location_2.y - location_1.y z = location_2.z - location_1.z norm = np.linalg.norm([x, y, z]) + np.finfo(float).eps return [x / norm, y / norm, z / norm]
[ "def", "vector", "(", "location_1", ",", "location_2", ")", ":", "x", "=", "location_2", ".", "x", "-", "location_1", ".", "x", "y", "=", "location_2", ".", "y", "-", "location_1", ".", "y", "z", "=", "location_2", ".", "z", "-", "location_1", ".", ...
https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/PythonAPI/carla/agents/tools/misc.py#L138-L149
tensorflow/minigo
6d89c202cdceaf449aefc3149ab2110d44f1a6a4
cluster/evaluator/launch_eval.py
python
add_top_pairs
(dry_run=False, pair_now=False)
Pairs up the top twenty models against each other. #1 plays 2,3,4,5, #2 plays 3,4,5,6 etc. for a total of 15*4 matches. Default behavior is to add the pairs to the working pairlist. `pair_now` will immediately create the pairings on the cluster. `dry_run` makes it only print the pairings that would be added
Pairs up the top twenty models against each other. #1 plays 2,3,4,5, #2 plays 3,4,5,6 etc. for a total of 15*4 matches.
[ "Pairs", "up", "the", "top", "twenty", "models", "against", "each", "other", ".", "#1", "plays", "2", "3", "4", "5", "#2", "plays", "3", "4", "5", "6", "etc", ".", "for", "a", "total", "of", "15", "*", "4", "matches", "." ]
def add_top_pairs(dry_run=False, pair_now=False): """ Pairs up the top twenty models against each other. #1 plays 2,3,4,5, #2 plays 3,4,5,6 etc. for a total of 15*4 matches. Default behavior is to add the pairs to the working pairlist. `pair_now` will immediately create the pairings on the cluster. `dry_run` makes it only print the pairings that would be added """ top = ratings.top_n(15) new_pairs = [] for idx, t in enumerate(top[:10]): new_pairs += [[t[0], o[0]] for o in top[idx+1:idx+5]] if dry_run: print(new_pairs) return if pair_now: maybe_enqueue(new_pairs) else: _append_pairs(new_pairs)
[ "def", "add_top_pairs", "(", "dry_run", "=", "False", ",", "pair_now", "=", "False", ")", ":", "top", "=", "ratings", ".", "top_n", "(", "15", ")", "new_pairs", "=", "[", "]", "for", "idx", ",", "t", "in", "enumerate", "(", "top", "[", ":", "10", ...
https://github.com/tensorflow/minigo/blob/6d89c202cdceaf449aefc3149ab2110d44f1a6a4/cluster/evaluator/launch_eval.py#L113-L133
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/utils/chemutils.py
python
SplitComposition
(compStr)
return res
Takes a simple chemical composition and turns into a list of element,# pairs. i.e. 'Fe3Al' -> [('Fe',3),('Al',1)] **Arguments** - compStr: the composition string to be processed **Returns** - the *composVect* corresponding to _compStr_ **Note** -this isn't smart enough by half to deal with anything even remotely subtle, so be gentle.
Takes a simple chemical composition and turns into a list of element,# pairs.
[ "Takes", "a", "simple", "chemical", "composition", "and", "turns", "into", "a", "list", "of", "element", "#", "pairs", "." ]
def SplitComposition(compStr): """ Takes a simple chemical composition and turns into a list of element,# pairs. i.e. 'Fe3Al' -> [('Fe',3),('Al',1)] **Arguments** - compStr: the composition string to be processed **Returns** - the *composVect* corresponding to _compStr_ **Note** -this isn't smart enough by half to deal with anything even remotely subtle, so be gentle. """ target = r'([A-Z][a-z]?)([0-9\.]*)' theExpr = re.compile(target) matches = theExpr.findall(compStr) res = [] for match in matches: if len(match[1]) > 0: res.append((match[0], float(match[1]))) else: res.append((match[0], 1)) return res
[ "def", "SplitComposition", "(", "compStr", ")", ":", "target", "=", "r'([A-Z][a-z]?)([0-9\\.]*)'", "theExpr", "=", "re", ".", "compile", "(", "target", ")", "matches", "=", "theExpr", ".", "findall", "(", "compStr", ")", "res", "=", "[", "]", "for", "match...
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/utils/chemutils.py#L81-L112
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/urllib.py
python
FancyURLopener.http_error_307
(self, url, fp, errcode, errmsg, headers, data=None)
Error 307 -- relocated, but turn POST into error.
Error 307 -- relocated, but turn POST into error.
[ "Error", "307", "--", "relocated", "but", "turn", "POST", "into", "error", "." ]
def http_error_307(self, url, fp, errcode, errmsg, headers, data=None): """Error 307 -- relocated, but turn POST into error.""" if data is None: return self.http_error_302(url, fp, errcode, errmsg, headers, data) else: return self.http_error_default(url, fp, errcode, errmsg, headers)
[ "def", "http_error_307", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ",", "data", "=", "None", ")", ":", "if", "data", "is", "None", ":", "return", "self", ".", "http_error_302", "(", "url", ",", "fp", ",", "e...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/urllib.py#L663-L668
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/json_schema_compiler/memoize.py
python
memoize
(fn)
return impl
Decorates |fn| to memoize.
Decorates |fn| to memoize.
[ "Decorates", "|fn|", "to", "memoize", "." ]
def memoize(fn): '''Decorates |fn| to memoize. ''' memory = {} def impl(*args, **optargs): full_args = args + tuple(optargs.iteritems()) if full_args not in memory: memory[full_args] = fn(*args, **optargs) return memory[full_args] return impl
[ "def", "memoize", "(", "fn", ")", ":", "memory", "=", "{", "}", "def", "impl", "(", "*", "args", ",", "*", "*", "optargs", ")", ":", "full_args", "=", "args", "+", "tuple", "(", "optargs", ".", "iteritems", "(", ")", ")", "if", "full_args", "not"...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_schema_compiler/memoize.py#L5-L14
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiManager_GetManager
(*args, **kwargs)
return _aui.AuiManager_GetManager(*args, **kwargs)
AuiManager_GetManager(Window window) -> AuiManager
AuiManager_GetManager(Window window) -> AuiManager
[ "AuiManager_GetManager", "(", "Window", "window", ")", "-", ">", "AuiManager" ]
def AuiManager_GetManager(*args, **kwargs): """AuiManager_GetManager(Window window) -> AuiManager""" return _aui.AuiManager_GetManager(*args, **kwargs)
[ "def", "AuiManager_GetManager", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiManager_GetManager", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L800-L802
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/apple/plist_util.py
python
MergePList
(plist1, plist2)
return result
Merges |plist1| with |plist2| recursively. Creates a new dictionary representing a Property List (.plist) files by merging the two dictionary |plist1| and |plist2| recursively (only for dictionary values). List value will be concatenated. Args: plist1: a dictionary representing a Property List (.plist) file plist2: a dictionary representing a Property List (.plist) file Returns: A new dictionary representing a Property List (.plist) file by merging |plist1| with |plist2|. If any value is a dictionary, they are merged recursively, otherwise |plist2| value is used. If values are list, they are concatenated.
Merges |plist1| with |plist2| recursively.
[ "Merges", "|plist1|", "with", "|plist2|", "recursively", "." ]
def MergePList(plist1, plist2): """Merges |plist1| with |plist2| recursively. Creates a new dictionary representing a Property List (.plist) files by merging the two dictionary |plist1| and |plist2| recursively (only for dictionary values). List value will be concatenated. Args: plist1: a dictionary representing a Property List (.plist) file plist2: a dictionary representing a Property List (.plist) file Returns: A new dictionary representing a Property List (.plist) file by merging |plist1| with |plist2|. If any value is a dictionary, they are merged recursively, otherwise |plist2| value is used. If values are list, they are concatenated. """ result = plist1.copy() for key, value in plist2.items(): if isinstance(value, dict): old_value = result.get(key) if isinstance(old_value, dict): value = MergePList(old_value, value) if isinstance(value, list): value = plist1.get(key, []) + plist2.get(key, []) result[key] = value return result
[ "def", "MergePList", "(", "plist1", ",", "plist2", ")", ":", "result", "=", "plist1", ".", "copy", "(", ")", "for", "key", ",", "value", "in", "plist2", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "old_valu...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/apple/plist_util.py#L134-L160
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/service.py
python
BaseService._get_stack_resource
(self, resource_name)
return self._context.stack.get_physical_resource_id(self._stack_id, resource_name)
Gets the list of outputs in given stack
Gets the list of outputs in given stack
[ "Gets", "the", "list", "of", "outputs", "in", "given", "stack" ]
def _get_stack_resource(self, resource_name) -> str: """ Gets the list of outputs in given stack """ return self._context.stack.get_physical_resource_id(self._stack_id, resource_name)
[ "def", "_get_stack_resource", "(", "self", ",", "resource_name", ")", "->", "str", ":", "return", "self", ".", "_context", ".", "stack", ".", "get_physical_resource_id", "(", "self", ".", "_stack_id", ",", "resource_name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/service.py#L48-L52
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/estimators/head.py
python
_BinarySvmHead._transform_labels
(self, mode, labels)
return labels_tensor
Applies transformations to labels tensor.
Applies transformations to labels tensor.
[ "Applies", "transformations", "to", "labels", "tensor", "." ]
def _transform_labels(self, mode, labels): """Applies transformations to labels tensor.""" if (mode == model_fn.ModeKeys.INFER) or (labels is None): return None labels_tensor = _to_labels_tensor(labels, self._label_name) _check_no_sparse_tensor(labels_tensor) return labels_tensor
[ "def", "_transform_labels", "(", "self", ",", "mode", ",", "labels", ")", ":", "if", "(", "mode", "==", "model_fn", ".", "ModeKeys", ".", "INFER", ")", "or", "(", "labels", "is", "None", ")", ":", "return", "None", "labels_tensor", "=", "_to_labels_tenso...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/estimators/head.py#L1260-L1266
yyzybb537/libgo
4af17b7c67643c4d54aa354dcc77963ea07847d0
third_party/boost.context/tools/build/src/tools/builtin.py
python
reset
()
Clear the module state. This is mainly for testing purposes.
Clear the module state. This is mainly for testing purposes.
[ "Clear", "the", "module", "state", ".", "This", "is", "mainly", "for", "testing", "purposes", "." ]
def reset (): """ Clear the module state. This is mainly for testing purposes. """ global __variant_explicit_properties __variant_explicit_properties = {}
[ "def", "reset", "(", ")", ":", "global", "__variant_explicit_properties", "__variant_explicit_properties", "=", "{", "}" ]
https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/tools/builtin.py#L25-L30
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32com/client/__init__.py
python
GetObject
(Pathname = None, Class = None, clsctx = None)
Mimic VB's GetObject() function. ob = GetObject(Class = "ProgID") or GetObject(Class = clsid) will connect to an already running instance of the COM object. ob = GetObject(r"c:\blah\blah\foo.xls") (aka the COM moniker syntax) will return a ready to use Python wrapping of the required COM object. Note: You must specifiy one or the other of these arguments. I know this isn't pretty, but it is what VB does. Blech. If you don't I'll throw ValueError at you. :) This will most likely throw pythoncom.com_error if anything fails.
Mimic VB's GetObject() function.
[ "Mimic", "VB", "s", "GetObject", "()", "function", "." ]
def GetObject(Pathname = None, Class = None, clsctx = None): """ Mimic VB's GetObject() function. ob = GetObject(Class = "ProgID") or GetObject(Class = clsid) will connect to an already running instance of the COM object. ob = GetObject(r"c:\blah\blah\foo.xls") (aka the COM moniker syntax) will return a ready to use Python wrapping of the required COM object. Note: You must specifiy one or the other of these arguments. I know this isn't pretty, but it is what VB does. Blech. If you don't I'll throw ValueError at you. :) This will most likely throw pythoncom.com_error if anything fails. """ if clsctx is None: clsctx = pythoncom.CLSCTX_ALL if (Pathname is None and Class is None) or \ (Pathname is not None and Class is not None): raise ValueError("You must specify a value for Pathname or Class, but not both.") if Class is not None: return GetActiveObject(Class, clsctx) else: return Moniker(Pathname, clsctx)
[ "def", "GetObject", "(", "Pathname", "=", "None", ",", "Class", "=", "None", ",", "clsctx", "=", "None", ")", ":", "if", "clsctx", "is", "None", ":", "clsctx", "=", "pythoncom", ".", "CLSCTX_ALL", "if", "(", "Pathname", "is", "None", "and", "Class", ...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/win32com/client/__init__.py#L46-L72
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_vendor/pyparsing.py
python
ParseResults.haskeys
( self )
return bool(self.__tokdict)
Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.
Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.
[ "Since", "keys", "()", "returns", "an", "iterator", "this", "method", "is", "helpful", "in", "bypassing", "code", "that", "looks", "for", "the", "existence", "of", "any", "defined", "results", "names", "." ]
def haskeys( self ): """Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.""" return bool(self.__tokdict)
[ "def", "haskeys", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "__tokdict", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/pyparsing.py#L506-L509
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/auibar.py
python
CommandToolBarEvent.GetToolId
(self)
return self.tool_id
Returns the :class:`AuiToolBarItem` identifier.
Returns the :class:`AuiToolBarItem` identifier.
[ "Returns", "the", ":", "class", ":", "AuiToolBarItem", "identifier", "." ]
def GetToolId(self): """ Returns the :class:`AuiToolBarItem` identifier. """ return self.tool_id
[ "def", "GetToolId", "(", "self", ")", ":", "return", "self", ".", "tool_id" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L117-L120
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/math_ops.py
python
log_sigmoid
(x, name=None)
Computes log sigmoid of `x` element-wise. Specifically, `y = log(1 / (1 + exp(-x)))`. For numerical stability, we use `y = -tf.nn.softplus(-x)`. Args: x: A Tensor with type `float32` or `float64`. name: A name for the operation (optional). Returns: A Tensor with the same type as `x`.
Computes log sigmoid of `x` element-wise.
[ "Computes", "log", "sigmoid", "of", "x", "element", "-", "wise", "." ]
def log_sigmoid(x, name=None): """Computes log sigmoid of `x` element-wise. Specifically, `y = log(1 / (1 + exp(-x)))`. For numerical stability, we use `y = -tf.nn.softplus(-x)`. Args: x: A Tensor with type `float32` or `float64`. name: A name for the operation (optional). Returns: A Tensor with the same type as `x`. """ with ops.name_scope(name, "LogSigmoid", [x]) as name: x = ops.convert_to_tensor(x, name="x") return gen_math_ops._neg(gen_nn_ops.softplus(-x), name=name)
[ "def", "log_sigmoid", "(", "x", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"LogSigmoid\"", ",", "[", "x", "]", ")", "as", "name", ":", "x", "=", "ops", ".", "convert_to_tensor", "(", "x", ",", "name", ...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/math_ops.py#L2056-L2071
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/FindUBUtility.py
python
AddScansForUBDialog.__init__
(self, parent)
initialization :param parent: main GUI, reductionControl
initialization :param parent: main GUI, reductionControl
[ "initialization", ":", "param", "parent", ":", "main", "GUI", "reductionControl" ]
def __init__(self, parent): """ initialization :param parent: main GUI, reductionControl """ super(AddScansForUBDialog, self).__init__(parent) self._myParent = parent # set up UI ui_path = "AddUBPeaksDialog.ui" self.ui = load_ui(__file__, ui_path, baseinstance=self) # initialize widgets self.ui.checkBox_loadHKLfromFile.setChecked(True) self.ui.pushButton_findPeak.clicked.connect(self.do_find_peak) self.ui.pushButton_addPeakToCalUB.clicked.connect(self.do_add_single_scan) self.ui.pushButton_loadScans.clicked.connect(self.do_load_scans) self.ui.pushButton_addScans.clicked.connect(self.do_add_scans) self.ui.pushButton_quit.clicked.connect(self.do_quit)
[ "def", "__init__", "(", "self", ",", "parent", ")", ":", "super", "(", "AddScansForUBDialog", ",", "self", ")", ".", "__init__", "(", "parent", ")", "self", ".", "_myParent", "=", "parent", "# set up UI", "ui_path", "=", "\"AddUBPeaksDialog.ui\"", "self", "....
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/FindUBUtility.py#L25-L46
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/jinja2/compiler.py
python
generate
(node, environment, name, filename, stream=None, defer_init=False, optimized=True)
Generate the python source for a node tree.
Generate the python source for a node tree.
[ "Generate", "the", "python", "source", "for", "a", "node", "tree", "." ]
def generate(node, environment, name, filename, stream=None, defer_init=False, optimized=True): """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError('Can\'t compile non template nodes') generator = environment.code_generator_class(environment, name, filename, stream, defer_init, optimized) generator.visit(node) if stream is None: return generator.stream.getvalue()
[ "def", "generate", "(", "node", ",", "environment", ",", "name", ",", "filename", ",", "stream", "=", "None", ",", "defer_init", "=", "False", ",", "optimized", "=", "True", ")", ":", "if", "not", "isinstance", "(", "node", ",", "nodes", ".", "Template...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/compiler.py#L74-L84
bigtreetech/BIGTREETECH-SKR-mini-E3
221247c12502ff92d071c701ea63cf3aa9bb3b29
firmware/V2.0/Marlin-2.0.8.2.x-SKR-mini-E3-V2.0/Marlin/src/lcd/extui/ftdi_eve_touch_ui/ftdi_eve_lib/scripts/bitmap2cpp.py
python
pack_rle
(data)
return rle
Use run-length encoding to pack the bytes
Use run-length encoding to pack the bytes
[ "Use", "run", "-", "length", "encoding", "to", "pack", "the", "bytes" ]
def pack_rle(data): """Use run-length encoding to pack the bytes""" rle = [] value = data[0] count = 0 for i in data: if i != value or count == 255: rle.append(count) rle.append(value) value = i count = 1 else: count += 1 rle.append(count) rle.append(value) return rle
[ "def", "pack_rle", "(", "data", ")", ":", "rle", "=", "[", "]", "value", "=", "data", "[", "0", "]", "count", "=", "0", "for", "i", "in", "data", ":", "if", "i", "!=", "value", "or", "count", "==", "255", ":", "rle", ".", "append", "(", "coun...
https://github.com/bigtreetech/BIGTREETECH-SKR-mini-E3/blob/221247c12502ff92d071c701ea63cf3aa9bb3b29/firmware/V2.0/Marlin-2.0.8.2.x-SKR-mini-E3-V2.0/Marlin/src/lcd/extui/ftdi_eve_touch_ui/ftdi_eve_lib/scripts/bitmap2cpp.py#L23-L38
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/memonger.py
python
get_updated_ranges
(ranges, max_live=None)
return ranges
Set LiveRange.defined = -1 if it is None Set LiveRange.used = max_live if it is None Set LiveRanee.size = 1 if it is None
Set LiveRange.defined = -1 if it is None Set LiveRange.used = max_live if it is None Set LiveRanee.size = 1 if it is None
[ "Set", "LiveRange", ".", "defined", "=", "-", "1", "if", "it", "is", "None", "Set", "LiveRange", ".", "used", "=", "max_live", "if", "it", "is", "None", "Set", "LiveRanee", ".", "size", "=", "1", "if", "it", "is", "None" ]
def get_updated_ranges(ranges, max_live=None): ''' Set LiveRange.defined = -1 if it is None Set LiveRange.used = max_live if it is None Set LiveRanee.size = 1 if it is None ''' def _get_max_live(ranges): max_live = max(x[1].used for x in ranges if x[1].used) + 1 return max_live def _update_range(x, max_live, size): cx = x if x[1].defined is None: cx = (cx[0], cx[1]._replace(defined=-1)) if x[1].used is None: cx = (cx[0], cx[1]._replace(used=max_live)) if x[1].size is None: cx = (cx[0], cx[1]._replace(size=size)) return cx if max_live is None: max_live = _get_max_live(ranges) ranges = [_update_range(x, max_live, 1) for x in ranges] return ranges
[ "def", "get_updated_ranges", "(", "ranges", ",", "max_live", "=", "None", ")", ":", "def", "_get_max_live", "(", "ranges", ")", ":", "max_live", "=", "max", "(", "x", "[", "1", "]", ".", "used", "for", "x", "in", "ranges", "if", "x", "[", "1", "]",...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/memonger.py#L690-L714
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/TaskGen.py
python
task_gen.__str__
(self)
return "<task_gen %r declared in %s>" % (self.name, self.path.abspath())
for debugging purposes
for debugging purposes
[ "for", "debugging", "purposes" ]
def __str__(self): """for debugging purposes""" return "<task_gen %r declared in %s>" % (self.name, self.path.abspath())
[ "def", "__str__", "(", "self", ")", ":", "return", "\"<task_gen %r declared in %s>\"", "%", "(", "self", ".", "name", ",", "self", ".", "path", ".", "abspath", "(", ")", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/TaskGen.py#L92-L94
eomahony/Numberjack
53fa9e994a36f881ffd320d8d04158097190aad8
Numberjack/XCSPOut.py
python
XCSPOutput.output_expressions
(self, outfile)
Print all the constraints and predicates to the file
Print all the constraints and predicates to the file
[ "Print", "all", "the", "constraints", "and", "predicates", "to", "the", "file" ]
def output_expressions(self, outfile): """ Print all the constraints and predicates to the file """ if len(self.__predicates)>0: outfile.write("\n<predicates nbPredicates=\"%d\">" % len(self.__predicates)) for pred in self.__predicates: outfile.write(pred) outfile.write("</predicates>\n") outfile.write("\n<constraints nbConstraints=\"%d\">" % len(self.__constraints)) for con in self.__constraints: outfile.write(con) outfile.write("</constraints>\n")
[ "def", "output_expressions", "(", "self", ",", "outfile", ")", ":", "if", "len", "(", "self", ".", "__predicates", ")", ">", "0", ":", "outfile", ".", "write", "(", "\"\\n<predicates nbPredicates=\\\"%d\\\">\"", "%", "len", "(", "self", ".", "__predicates", ...
https://github.com/eomahony/Numberjack/blob/53fa9e994a36f881ffd320d8d04158097190aad8/Numberjack/XCSPOut.py#L644-L657
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/histogram_ops.py
python
histogram_fixed_width
(values, value_range, nbins=100, dtype=dtypes.int32, name=None)
Return histogram of values. Given the tensor `values`, this operation returns a rank 1 histogram counting the number of entries in `values` that fell into every bin. The bins are equal width and determined by the arguments `value_range` and `nbins`. Args: values: Numeric `Tensor`. value_range: Shape [2] `Tensor` of same `dtype` as `values`. values <= value_range[0] will be mapped to hist[0], values >= value_range[1] will be mapped to hist[-1]. nbins: Scalar `int32 Tensor`. Number of histogram bins. dtype: dtype for returned histogram. name: A name for this operation (defaults to 'histogram_fixed_width'). Returns: A 1-D `Tensor` holding histogram of values. Raises: TypeError: If any unsupported dtype is provided. tf.errors.InvalidArgumentError: If value_range does not satisfy value_range[0] < value_range[1]. Examples: ```python # Bins will be: (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf) nbins = 5 value_range = [0.0, 5.0] new_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15] with tf.compat.v1.get_default_session() as sess: hist = tf.histogram_fixed_width(new_values, value_range, nbins=5) variables.global_variables_initializer().run() sess.run(hist) => [2, 1, 1, 0, 2] ```
Return histogram of values.
[ "Return", "histogram", "of", "values", "." ]
def histogram_fixed_width(values, value_range, nbins=100, dtype=dtypes.int32, name=None): """Return histogram of values. Given the tensor `values`, this operation returns a rank 1 histogram counting the number of entries in `values` that fell into every bin. The bins are equal width and determined by the arguments `value_range` and `nbins`. Args: values: Numeric `Tensor`. value_range: Shape [2] `Tensor` of same `dtype` as `values`. values <= value_range[0] will be mapped to hist[0], values >= value_range[1] will be mapped to hist[-1]. nbins: Scalar `int32 Tensor`. Number of histogram bins. dtype: dtype for returned histogram. name: A name for this operation (defaults to 'histogram_fixed_width'). Returns: A 1-D `Tensor` holding histogram of values. Raises: TypeError: If any unsupported dtype is provided. tf.errors.InvalidArgumentError: If value_range does not satisfy value_range[0] < value_range[1]. Examples: ```python # Bins will be: (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf) nbins = 5 value_range = [0.0, 5.0] new_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15] with tf.compat.v1.get_default_session() as sess: hist = tf.histogram_fixed_width(new_values, value_range, nbins=5) variables.global_variables_initializer().run() sess.run(hist) => [2, 1, 1, 0, 2] ``` """ with ops.name_scope(name, 'histogram_fixed_width', [values, value_range, nbins]) as name: # pylint: disable=protected-access return gen_math_ops._histogram_fixed_width( values, value_range, nbins, dtype=dtype, name=name)
[ "def", "histogram_fixed_width", "(", "values", ",", "value_range", ",", "nbins", "=", "100", ",", "dtype", "=", "dtypes", ".", "int32", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "'histogram_fixed_width'", ",", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/histogram_ops.py#L104-L150
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/FilterEvents/eventFilterGUI.py
python
MainWindow.filterByLogValue
(self)
Filter by log value
Filter by log value
[ "Filter", "by", "log", "value" ]
def filterByLogValue(self): """ Filter by log value """ # Generate event filter kwargs = {} samplelog = str(self.ui.comboBox_2.currentText()) if len(samplelog) == 0: error_msg = "No sample log is selected!" Logger("Filter_Events").error(error_msg) return if self.ui.lineEdit_3.text() != "": rel_starttime = float(self.ui.lineEdit_3.text()) kwargs["StartTime"] = str(rel_starttime) if self.ui.lineEdit_4.text() != "": rel_stoptime = float(self.ui.lineEdit_4.text()) kwargs["StopTime"] = str(rel_stoptime) if self.ui.lineEdit_5.text() != "": minlogvalue = float(self.ui.lineEdit_5.text()) kwargs["MinimumLogValue"] = minlogvalue if self.ui.lineEdit_6.text() != "": maxlogvalue = float(self.ui.lineEdit_6.text()) kwargs["MaximumLogValue"] = maxlogvalue if self.ui.lineEdit_7.text() != "": logvalueintv = float(self.ui.lineEdit_7.text()) kwargs["LogValueInterval"] = logvalueintv logvalchangedir = str(self.ui.comboBox_4.currentText()) kwargs["FilterLogValueByChangingDirection"] = logvalchangedir if self.ui.lineEdit_9.text() != "": logvalueintv = float(self.ui.lineEdit_9.text()) kwargs["TimeTolerance"] = logvalueintv logboundtype = str(self.ui.comboBox_5.currentText()) kwargs["LogBoundary"] = logboundtype if self.ui.lineEdit_8.text() != "": logvaluetol = float(self.ui.lineEdit_8.text()) kwargs["LogValueTolerance"] = logvaluetol splitwsname = str(self._dataWS) + "_splitters" splitinfowsname = str(self._dataWS) + "_info" fastLog = self.ui.checkBox_fastLog.isChecked() title = str(self.ui.lineEdit_title.text()) try: splitws, infows = api.GenerateEventsFilter(InputWorkspace=self._dataWS, UnitOfTime="Seconds", TitleOfSplitters=title, OutputWorkspace=splitwsname, LogName=samplelog, FastLog=fastLog, InformationWorkspace=splitinfowsname, **kwargs) self.splitWksp(splitws, infows) except RuntimeError as e: self._setErrorMsg("Splitting Failed!\n %s" % (str(e)))
[ "def", "filterByLogValue", "(", "self", ")", ":", "# Generate event filter", "kwargs", "=", "{", "}", "samplelog", "=", "str", "(", "self", ".", "ui", ".", "comboBox_2", ".", "currentText", "(", ")", ")", "if", "len", "(", "samplelog", ")", "==", "0", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/FilterEvents/eventFilterGUI.py#L956-L1015
PaddlePaddle/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
tools/external_converter_v2/parser/graph_io.py
python
GraphProtoIO.add_out_edge
(self, node_name_0, node_name_1, scale=None)
add_out_edge is directive from node_name_0 to node_name_1
add_out_edge is directive from node_name_0 to node_name_1
[ "add_out_edge", "is", "directive", "from", "node_name_0", "to", "node_name_1" ]
def add_out_edge(self, node_name_0, node_name_1, scale=None): """ add_out_edge is directive from node_name_0 to node_name_1 """ edges_out = self.graph_proto.edges_out nexts = list() for target in edges_out[node_name_0].target: nexts.append(target.node) if node_name_1 not in nexts: target = edges_out[node_name_0].target.add() if scale is not None: target.scale.append(scale) target.node = node_name_1
[ "def", "add_out_edge", "(", "self", ",", "node_name_0", ",", "node_name_1", ",", "scale", "=", "None", ")", ":", "edges_out", "=", "self", ".", "graph_proto", ".", "edges_out", "nexts", "=", "list", "(", ")", "for", "target", "in", "edges_out", "[", "nod...
https://github.com/PaddlePaddle/Anakin/blob/5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730/tools/external_converter_v2/parser/graph_io.py#L364-L376
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/inverse_gamma.py
python
InverseGamma.batch_shape
(self, name="batch_shape")
Batch dimensions of this instance as a 1-D int32 `Tensor`. The product of the dimensions of the `batch_shape` is the number of independent distributions of this kind the instance represents. Args: name: name to give to the op Returns: `Tensor` `batch_shape`
Batch dimensions of this instance as a 1-D int32 `Tensor`.
[ "Batch", "dimensions", "of", "this", "instance", "as", "a", "1", "-", "D", "int32", "Tensor", "." ]
def batch_shape(self, name="batch_shape"): """Batch dimensions of this instance as a 1-D int32 `Tensor`. The product of the dimensions of the `batch_shape` is the number of independent distributions of this kind the instance represents. Args: name: name to give to the op Returns: `Tensor` `batch_shape` """ with ops.name_scope(self.name): with ops.op_scope([self._broadcast_tensor], name): return array_ops.shape(self._broadcast_tensor)
[ "def", "batch_shape", "(", "self", ",", "name", "=", "\"batch_shape\"", ")", ":", "with", "ops", ".", "name_scope", "(", "self", ".", "name", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "self", ".", "_broadcast_tensor", "]", ",", "name", ")", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/inverse_gamma.py#L137-L151
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/grid.py
python
GridTableBase.InsertCols
(*args, **kwargs)
return _grid.GridTableBase_InsertCols(*args, **kwargs)
InsertCols(self, size_t pos=0, size_t numCols=1) -> bool
InsertCols(self, size_t pos=0, size_t numCols=1) -> bool
[ "InsertCols", "(", "self", "size_t", "pos", "=", "0", "size_t", "numCols", "=", "1", ")", "-", ">", "bool" ]
def InsertCols(*args, **kwargs): """InsertCols(self, size_t pos=0, size_t numCols=1) -> bool""" return _grid.GridTableBase_InsertCols(*args, **kwargs)
[ "def", "InsertCols", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridTableBase_InsertCols", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L874-L876
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/ma/extras.py
python
notmasked_edges
(a, axis=None)
return [tuple([idx[i].min(axis).compressed() for i in range(a.ndim)]), tuple([idx[i].max(axis).compressed() for i in range(a.ndim)]), ]
Find the indices of the first and last unmasked values along an axis. If all values are masked, return None. Otherwise, return a list of two tuples, corresponding to the indices of the first and last unmasked values respectively. Parameters ---------- a : array_like The input array. axis : int, optional Axis along which to perform the operation. If None (default), applies to a flattened version of the array. Returns ------- edges : ndarray or list An array of start and end indexes if there are any masked data in the array. If there are no masked data in the array, `edges` is a list of the first and last index. See Also -------- flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous, clump_masked, clump_unmasked Examples -------- >>> a = np.arange(9).reshape((3, 3)) >>> m = np.zeros_like(a) >>> m[1:, 1:] = 1 >>> am = np.ma.array(a, mask=m) >>> np.array(am[~am.mask]) array([0, 1, 2, 3, 6]) >>> np.ma.notmasked_edges(ma) array([0, 6])
Find the indices of the first and last unmasked values along an axis.
[ "Find", "the", "indices", "of", "the", "first", "and", "last", "unmasked", "values", "along", "an", "axis", "." ]
def notmasked_edges(a, axis=None): """ Find the indices of the first and last unmasked values along an axis. If all values are masked, return None. Otherwise, return a list of two tuples, corresponding to the indices of the first and last unmasked values respectively. Parameters ---------- a : array_like The input array. axis : int, optional Axis along which to perform the operation. If None (default), applies to a flattened version of the array. Returns ------- edges : ndarray or list An array of start and end indexes if there are any masked data in the array. If there are no masked data in the array, `edges` is a list of the first and last index. See Also -------- flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous, clump_masked, clump_unmasked Examples -------- >>> a = np.arange(9).reshape((3, 3)) >>> m = np.zeros_like(a) >>> m[1:, 1:] = 1 >>> am = np.ma.array(a, mask=m) >>> np.array(am[~am.mask]) array([0, 1, 2, 3, 6]) >>> np.ma.notmasked_edges(ma) array([0, 6]) """ a = asarray(a) if axis is None or a.ndim == 1: return flatnotmasked_edges(a) m = getmaskarray(a) idx = array(np.indices(a.shape), mask=np.asarray([m] * a.ndim)) return [tuple([idx[i].min(axis).compressed() for i in range(a.ndim)]), tuple([idx[i].max(axis).compressed() for i in range(a.ndim)]), ]
[ "def", "notmasked_edges", "(", "a", ",", "axis", "=", "None", ")", ":", "a", "=", "asarray", "(", "a", ")", "if", "axis", "is", "None", "or", "a", ".", "ndim", "==", "1", ":", "return", "flatnotmasked_edges", "(", "a", ")", "m", "=", "getmaskarray"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/extras.py#L1553-L1601
intel-iot-devkit/how-to-code-samples
b4ea616f36bbfa2e042beb1698f968cfd651d79f
range-finder-scanner/python/iot_range_finder_scanner/runner.py
python
Runner.serve_css
(self)
return static_file(resource_path, root=package_root)
Serve the 'styles.css' file.
Serve the 'styles.css' file.
[ "Serve", "the", "styles", ".", "css", "file", "." ]
def serve_css(self): """ Serve the 'styles.css' file. """ resource_package = __name__ resource_path = "styles.css" package_root = resource_filename(resource_package, "") return static_file(resource_path, root=package_root)
[ "def", "serve_css", "(", "self", ")", ":", "resource_package", "=", "__name__", "resource_path", "=", "\"styles.css\"", "package_root", "=", "resource_filename", "(", "resource_package", ",", "\"\"", ")", "return", "static_file", "(", "resource_path", ",", "root", ...
https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/range-finder-scanner/python/iot_range_finder_scanner/runner.py#L91-L100
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Modules/Scripted/DICOMLib/DICOMRecentActivityWidget.py
python
DICOMRecentActivityWidget.__init__
(self, parent, dicomDatabase=None, browserWidget=None)
If browserWidget is specified (e.g., set to slicer.modules.DICOMInstance.browserWidget) then clicking on an item selects the series in that browserWidget.
If browserWidget is specified (e.g., set to slicer.modules.DICOMInstance.browserWidget) then clicking on an item selects the series in that browserWidget.
[ "If", "browserWidget", "is", "specified", "(", "e", ".", "g", ".", "set", "to", "slicer", ".", "modules", ".", "DICOMInstance", ".", "browserWidget", ")", "then", "clicking", "on", "an", "item", "selects", "the", "series", "in", "that", "browserWidget", "....
def __init__(self, parent, dicomDatabase=None, browserWidget=None): """If browserWidget is specified (e.g., set to slicer.modules.DICOMInstance.browserWidget) then clicking on an item selects the series in that browserWidget. """ super().__init__(parent) if dicomDatabase: self.dicomDatabase = dicomDatabase else: self.dicomDatabase = slicer.dicomDatabase self.browserWidget = browserWidget self.recentSeries = [] self.name = 'recentActivityWidget' self.setLayout(qt.QVBoxLayout()) self.statusLabel = qt.QLabel() self.layout().addWidget(self.statusLabel) self.statusLabel.text = '' self.scrollArea = qt.QScrollArea() self.layout().addWidget(self.scrollArea) self.listWidget = qt.QListWidget() self.listWidget.name = 'recentActivityListWidget' self.scrollArea.setWidget(self.listWidget) self.scrollArea.setWidgetResizable(True) self.listWidget.setProperty('SH_ItemView_ActivateItemOnSingleClick', 1) self.listWidget.connect('activated(QModelIndex)', self.onActivated) self.refreshButton = qt.QPushButton() self.layout().addWidget(self.refreshButton) self.refreshButton.text = 'Refresh' self.refreshButton.connect('clicked()', self.update) self.tags = {} self.tags['seriesDescription'] = "0008,103e" self.tags['patientName'] = "0010,0010"
[ "def", "__init__", "(", "self", ",", "parent", ",", "dicomDatabase", "=", "None", ",", "browserWidget", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "parent", ")", "if", "dicomDatabase", ":", "self", ".", "dicomDatabase", "=", "dicomDa...
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/DICOMLib/DICOMRecentActivityWidget.py#L16-L50
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
examples/python/linear_programming.py
python
RunLinearExampleNaturalLanguageAPI
(optimization_problem_type)
Example of simple linear program with natural language API.
Example of simple linear program with natural language API.
[ "Example", "of", "simple", "linear", "program", "with", "natural", "language", "API", "." ]
def RunLinearExampleNaturalLanguageAPI(optimization_problem_type): """Example of simple linear program with natural language API.""" solver = pywraplp.Solver.CreateSolver(optimization_problem_type) if not solver: return Announce(optimization_problem_type, 'natural language API') infinity = solver.infinity() # x1, x2 and x3 are continuous non-negative variables. x1 = solver.NumVar(0.0, infinity, 'x1') x2 = solver.NumVar(0.0, infinity, 'x2') x3 = solver.NumVar(0.0, infinity, 'x3') solver.Maximize(10 * x1 + 6 * x2 + 4 * x3) c0 = solver.Add(10 * x1 + 4 * x2 + 5 * x3 <= 600, 'ConstraintName0') c1 = solver.Add(2 * x1 + 2 * x2 + 6 * x3 <= 300) sum_of_vars = sum([x1, x2, x3]) c2 = solver.Add(sum_of_vars <= 100.0, 'OtherConstraintName') SolveAndPrint(solver, [x1, x2, x3], [c0, c1, c2]) # Print a linear expression's solution value. print('Sum of vars: %s = %s' % (sum_of_vars, sum_of_vars.solution_value()))
[ "def", "RunLinearExampleNaturalLanguageAPI", "(", "optimization_problem_type", ")", ":", "solver", "=", "pywraplp", ".", "Solver", ".", "CreateSolver", "(", "optimization_problem_type", ")", "if", "not", "solver", ":", "return", "Announce", "(", "optimization_problem_ty...
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/examples/python/linear_programming.py#L24-L47
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
example/nce-loss/wordvec_subwords.py
python
get_subword_units
(token, gram=GRAMS)
return [t[i:i + gram] for i in range(0, len(t) - gram + 1)]
Return subword-units presentation, given a word/token.
Return subword-units presentation, given a word/token.
[ "Return", "subword", "-", "units", "presentation", "given", "a", "word", "/", "token", "." ]
def get_subword_units(token, gram=GRAMS): """Return subword-units presentation, given a word/token. """ if token == '</s>': # special token for padding purpose. return [token] t = '#' + token + '#' return [t[i:i + gram] for i in range(0, len(t) - gram + 1)]
[ "def", "get_subword_units", "(", "token", ",", "gram", "=", "GRAMS", ")", ":", "if", "token", "==", "'</s>'", ":", "# special token for padding purpose.", "return", "[", "token", "]", "t", "=", "'#'", "+", "token", "+", "'#'", "return", "[", "t", "[", "i...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/nce-loss/wordvec_subwords.py#L83-L89
eomahony/Numberjack
53fa9e994a36f881ffd320d8d04158097190aad8
Numberjack/__init__.py
python
Expression.initial
(self)
return output
Returns a string representing the initial domain of the expression. For example: .. code-block:: python var1 = Variable(0, 10) print var1.initial() >>> x0 in {0..10} :return: A String representation of original expression definition :rtype: str
Returns a string representing the initial domain of the expression. For example:
[ "Returns", "a", "string", "representing", "the", "initial", "domain", "of", "the", "expression", ".", "For", "example", ":" ]
def initial(self): """ Returns a string representing the initial domain of the expression. For example: .. code-block:: python var1 = Variable(0, 10) print var1.initial() >>> x0 in {0..10} :return: A String representation of original expression definition :rtype: str """ output = self.name() if self.domain_ is None: output += ' in ' + str(Domain(self.lb, self.ub)) else: output += ' in ' + str(Domain(self.domain_)) return output
[ "def", "initial", "(", "self", ")", ":", "output", "=", "self", ".", "name", "(", ")", "if", "self", ".", "domain_", "is", "None", ":", "output", "+=", "' in '", "+", "str", "(", "Domain", "(", "self", ".", "lb", ",", "self", ".", "ub", ")", ")...
https://github.com/eomahony/Numberjack/blob/53fa9e994a36f881ffd320d8d04158097190aad8/Numberjack/__init__.py#L260-L279
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/bindings/python/MythTV/services_api/utilities.py
python
url_encode
(value=None)
return quote(value)
This is really unnecessary. It's more of a reminder about how to use urllib.[parse]quote(). At least as of this writing, 0.28-pre doesn't decode the escaped values and the endpoints just get the percent encoded text. E.g. don't use it. How show titles with & or = in them work isn't clear. Input: A string. E.g. a program's title or anything that has special characters like ?, & and UTF characters beyond the ASCII set. Output: The URL encoded string. E.g. the DEGREE SIGN becomes: %C2%B0 or a QUESTION MARK becomes %3F.
This is really unnecessary. It's more of a reminder about how to use urllib.[parse]quote(). At least as of this writing, 0.28-pre doesn't decode the escaped values and the endpoints just get the percent encoded text. E.g. don't use it. How show titles with & or = in them work isn't clear.
[ "This", "is", "really", "unnecessary", ".", "It", "s", "more", "of", "a", "reminder", "about", "how", "to", "use", "urllib", ".", "[", "parse", "]", "quote", "()", ".", "At", "least", "as", "of", "this", "writing", "0", ".", "28", "-", "pre", "does...
def url_encode(value=None): """ This is really unnecessary. It's more of a reminder about how to use urllib.[parse]quote(). At least as of this writing, 0.28-pre doesn't decode the escaped values and the endpoints just get the percent encoded text. E.g. don't use it. How show titles with & or = in them work isn't clear. Input: A string. E.g. a program's title or anything that has special characters like ?, & and UTF characters beyond the ASCII set. Output: The URL encoded string. E.g. the DEGREE SIGN becomes: %C2%B0 or a QUESTION MARK becomes %3F. """ if value is None: LOG.warning('url_encode() called without any value') return value return quote(value)
[ "def", "url_encode", "(", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "LOG", ".", "warning", "(", "'url_encode() called without any value'", ")", "return", "value", "return", "quote", "(", "value", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/bindings/python/MythTV/services_api/utilities.py#L26-L46
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/bayesflow/python/ops/stochastic_gradient_estimators.py
python
get_mean_baseline
(ema_decay=0.99, name=None)
return mean_baseline
ExponentialMovingAverage baseline. Args: ema_decay: decay rate for the ExponentialMovingAverage. name: name for variable scope of the ExponentialMovingAverage. Returns: Callable baseline function that takes the `StochasticTensor` (unused) and the downstream `loss`, and returns an EMA of the loss.
ExponentialMovingAverage baseline.
[ "ExponentialMovingAverage", "baseline", "." ]
def get_mean_baseline(ema_decay=0.99, name=None): """ExponentialMovingAverage baseline. Args: ema_decay: decay rate for the ExponentialMovingAverage. name: name for variable scope of the ExponentialMovingAverage. Returns: Callable baseline function that takes the `StochasticTensor` (unused) and the downstream `loss`, and returns an EMA of the loss. """ def mean_baseline(_, loss): with vs.variable_scope(name, default_name="MeanBaseline"): reduced_loss = math_ops.reduce_mean(loss) ema = training.ExponentialMovingAverage(decay=ema_decay, zero_debias=True) update_op = ema.apply([reduced_loss]) with ops.control_dependencies([update_op]): # Using `identity` causes an op to be added in this context, which # triggers the update. Removing the `identity` means nothing is updated. baseline = array_ops.identity(ema.average(reduced_loss)) return baseline return mean_baseline
[ "def", "get_mean_baseline", "(", "ema_decay", "=", "0.99", ",", "name", "=", "None", ")", ":", "def", "mean_baseline", "(", "_", ",", "loss", ")", ":", "with", "vs", ".", "variable_scope", "(", "name", ",", "default_name", "=", "\"MeanBaseline\"", ")", "...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/bayesflow/python/ops/stochastic_gradient_estimators.py#L170-L196
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/filters.py
python
do_attr
( environment: "Environment", obj: t.Any, name: str )
return environment.undefined(obj=obj, name=name)
Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up.
[ "Get", "an", "attribute", "of", "an", "object", ".", "foo|attr", "(", "bar", ")", "works", "like", "foo", ".", "bar", "just", "that", "always", "an", "attribute", "is", "returned", "and", "items", "are", "not", "looked", "up", "." ]
def do_attr( environment: "Environment", obj: t.Any, name: str ) -> t.Union[Undefined, t.Any]: """Get an attribute of an object. ``foo|attr("bar")`` works like ``foo.bar`` just that always an attribute is returned and items are not looked up. See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details. """ try: name = str(name) except UnicodeError: pass else: try: value = getattr(obj, name) except AttributeError: pass else: if environment.sandboxed: environment = t.cast("SandboxedEnvironment", environment) if not environment.is_safe_attribute(obj, name, value): return environment.unsafe_undefined(obj, name) return value return environment.undefined(obj=obj, name=name)
[ "def", "do_attr", "(", "environment", ":", "\"Environment\"", ",", "obj", ":", "t", ".", "Any", ",", "name", ":", "str", ")", "->", "t", ".", "Union", "[", "Undefined", ",", "t", ".", "Any", "]", ":", "try", ":", "name", "=", "str", "(", "name", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/filters.py#L1358-L1385
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/special/orthogonal.py
python
sh_legendre
(n, monic=False)
return p
r"""Shifted Legendre polynomial. Defined as :math:`P^*_n(x) = P_n(2x - 1)` for :math:`P_n` the nth Legendre polynomial. Parameters ---------- n : int Degree of the polynomial. monic : bool, optional If `True`, scale the leading coefficient to be 1. Default is `False`. Returns ------- P : orthopoly1d Shifted Legendre polynomial. Notes ----- The polynomials :math:`P^*_n` are orthogonal over :math:`[0, 1]` with weight function 1.
r"""Shifted Legendre polynomial.
[ "r", "Shifted", "Legendre", "polynomial", "." ]
def sh_legendre(n, monic=False): r"""Shifted Legendre polynomial. Defined as :math:`P^*_n(x) = P_n(2x - 1)` for :math:`P_n` the nth Legendre polynomial. Parameters ---------- n : int Degree of the polynomial. monic : bool, optional If `True`, scale the leading coefficient to be 1. Default is `False`. Returns ------- P : orthopoly1d Shifted Legendre polynomial. Notes ----- The polynomials :math:`P^*_n` are orthogonal over :math:`[0, 1]` with weight function 1. """ if n < 0: raise ValueError("n must be nonnegative.") wfunc = lambda x: 0.0 * x + 1.0 if n == 0: return orthopoly1d([], [], 1.0, 1.0, wfunc, (0, 1), monic, lambda x: eval_sh_legendre(n, x)) x, w, mu0 = ps_roots(n, mu=True) hn = 1.0 / (2 * n + 1.0) kn = _gam(2 * n + 1) / _gam(n + 1)**2 p = orthopoly1d(x, w, hn, kn, wfunc, limits=(0, 1), monic=monic, eval_func=lambda x: eval_sh_legendre(n, x)) return p
[ "def", "sh_legendre", "(", "n", ",", "monic", "=", "False", ")", ":", "if", "n", "<", "0", ":", "raise", "ValueError", "(", "\"n must be nonnegative.\"", ")", "wfunc", "=", "lambda", "x", ":", "0.0", "*", "x", "+", "1.0", "if", "n", "==", "0", ":",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/special/orthogonal.py#L2014-L2051
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/training/python/training/evaluation.py
python
evaluate_repeatedly
(checkpoint_dir, master='', scaffold=None, eval_ops=None, feed_dict=None, final_ops=None, final_ops_feed_dict=None, eval_interval_secs=60, hooks=None, config=None, max_number_of_evaluations=None, timeout=None, timeout_fn=None)
return final_ops_hook.final_ops_values
Repeatedly searches for a checkpoint in `checkpoint_dir` and evaluates it. During a single evaluation, the `eval_ops` is run until the session is interrupted or requested to finish. This is typically requested via a `tf.contrib.training.StopAfterNEvalsHook` which results in `eval_ops` running the requested number of times. Optionally, a user can pass in `final_ops`, a single `Tensor`, a list of `Tensors` or a dictionary from names to `Tensors`. The `final_ops` is evaluated a single time after `eval_ops` has finished running and the fetched values of `final_ops` are returned. If `final_ops` is left as `None`, then `None` is returned. One may also consider using a `tf.contrib.training.SummaryAtEndHook` to record summaries after the `eval_ops` have run. If `eval_ops` is `None`, the summaries run immediately after the model checkpoint has been restored. Note that `evaluate_once` creates a local variable used to track the number of evaluations run via `tf.contrib.training.get_or_create_eval_step`. Consequently, if a custom local init op is provided via a `scaffold`, the caller should ensure that the local init op also initializes the eval step. Args: checkpoint_dir: The directory where checkpoints are stored. master: The address of the TensorFlow master. scaffold: An tf.compat.v1.train.Scaffold instance for initializing variables and restoring variables. Note that `scaffold.init_fn` is used by the function to restore the checkpoint. If you supply a custom init_fn, then it must also take care of restoring the model from its checkpoint. eval_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to `Tensors`, which is run until the session is requested to stop, commonly done by a `tf.contrib.training.StopAfterNEvalsHook`. feed_dict: The feed dictionary to use when executing the `eval_ops`. final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to `Tensors`. final_ops_feed_dict: A feed dictionary to use when evaluating `final_ops`. eval_interval_secs: The minimum number of seconds between evaluations. hooks: List of `tf.estimator.SessionRunHook` callbacks which are run inside the evaluation loop. config: An instance of `tf.compat.v1.ConfigProto` that will be used to configure the `Session`. If left as `None`, the default will be used. max_number_of_evaluations: The maximum times to run the evaluation. If left as `None`, then evaluation runs indefinitely. timeout: The maximum number of seconds to wait between checkpoints. If left as `None`, then the process will wait indefinitely. timeout_fn: Optional function to call after a timeout. If the function returns True, then it means that no new checkpoints will be generated and the iterator will exit. The function is called with no arguments. Returns: The fetched values of `final_ops` or `None` if `final_ops` is `None`.
Repeatedly searches for a checkpoint in `checkpoint_dir` and evaluates it.
[ "Repeatedly", "searches", "for", "a", "checkpoint", "in", "checkpoint_dir", "and", "evaluates", "it", "." ]
def evaluate_repeatedly(checkpoint_dir, master='', scaffold=None, eval_ops=None, feed_dict=None, final_ops=None, final_ops_feed_dict=None, eval_interval_secs=60, hooks=None, config=None, max_number_of_evaluations=None, timeout=None, timeout_fn=None): """Repeatedly searches for a checkpoint in `checkpoint_dir` and evaluates it. During a single evaluation, the `eval_ops` is run until the session is interrupted or requested to finish. This is typically requested via a `tf.contrib.training.StopAfterNEvalsHook` which results in `eval_ops` running the requested number of times. Optionally, a user can pass in `final_ops`, a single `Tensor`, a list of `Tensors` or a dictionary from names to `Tensors`. The `final_ops` is evaluated a single time after `eval_ops` has finished running and the fetched values of `final_ops` are returned. If `final_ops` is left as `None`, then `None` is returned. One may also consider using a `tf.contrib.training.SummaryAtEndHook` to record summaries after the `eval_ops` have run. If `eval_ops` is `None`, the summaries run immediately after the model checkpoint has been restored. Note that `evaluate_once` creates a local variable used to track the number of evaluations run via `tf.contrib.training.get_or_create_eval_step`. Consequently, if a custom local init op is provided via a `scaffold`, the caller should ensure that the local init op also initializes the eval step. Args: checkpoint_dir: The directory where checkpoints are stored. master: The address of the TensorFlow master. scaffold: An tf.compat.v1.train.Scaffold instance for initializing variables and restoring variables. Note that `scaffold.init_fn` is used by the function to restore the checkpoint. If you supply a custom init_fn, then it must also take care of restoring the model from its checkpoint. eval_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to `Tensors`, which is run until the session is requested to stop, commonly done by a `tf.contrib.training.StopAfterNEvalsHook`. feed_dict: The feed dictionary to use when executing the `eval_ops`. final_ops: A single `Tensor`, a list of `Tensors` or a dictionary of names to `Tensors`. final_ops_feed_dict: A feed dictionary to use when evaluating `final_ops`. eval_interval_secs: The minimum number of seconds between evaluations. hooks: List of `tf.estimator.SessionRunHook` callbacks which are run inside the evaluation loop. config: An instance of `tf.compat.v1.ConfigProto` that will be used to configure the `Session`. If left as `None`, the default will be used. max_number_of_evaluations: The maximum times to run the evaluation. If left as `None`, then evaluation runs indefinitely. timeout: The maximum number of seconds to wait between checkpoints. If left as `None`, then the process will wait indefinitely. timeout_fn: Optional function to call after a timeout. If the function returns True, then it means that no new checkpoints will be generated and the iterator will exit. The function is called with no arguments. Returns: The fetched values of `final_ops` or `None` if `final_ops` is `None`. """ eval_step = get_or_create_eval_step() # Prepare the run hooks. hooks = hooks or [] if eval_ops is not None: update_eval_step = state_ops.assign_add(eval_step, 1) for h in hooks: if isinstance(h, StopAfterNEvalsHook): h._set_evals_completed_tensor(update_eval_step) # pylint: disable=protected-access if isinstance(eval_ops, dict): eval_ops['update_eval_step'] = update_eval_step elif isinstance(eval_ops, (tuple, list)): eval_ops = list(eval_ops) + [update_eval_step] else: eval_ops = [eval_ops, update_eval_step] final_ops_hook = basic_session_run_hooks.FinalOpsHook(final_ops, final_ops_feed_dict) hooks.append(final_ops_hook) num_evaluations = 0 for checkpoint_path in checkpoints_iterator( checkpoint_dir, min_interval_secs=eval_interval_secs, timeout=timeout, timeout_fn=timeout_fn): session_creator = monitored_session.ChiefSessionCreator( scaffold=scaffold, checkpoint_filename_with_path=checkpoint_path, master=master, config=config) with monitored_session.MonitoredSession( session_creator=session_creator, hooks=hooks) as session: logging.info('Starting evaluation at ' + time.strftime('%Y-%m-%d-%H:%M:%S', time.gmtime())) if eval_ops is not None: while not session.should_stop(): session.run(eval_ops, feed_dict) logging.info('Finished evaluation at ' + time.strftime('%Y-%m-%d-%H:%M:%S', time.gmtime())) num_evaluations += 1 if (max_number_of_evaluations is not None and num_evaluations >= max_number_of_evaluations): return final_ops_hook.final_ops_values return final_ops_hook.final_ops_values
[ "def", "evaluate_repeatedly", "(", "checkpoint_dir", ",", "master", "=", "''", ",", "scaffold", "=", "None", ",", "eval_ops", "=", "None", ",", "feed_dict", "=", "None", ",", "final_ops", "=", "None", ",", "final_ops_feed_dict", "=", "None", ",", "eval_inter...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/training/python/training/evaluation.py#L346-L463
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/plotting/markers.py
python
RangeMarker.set_maximum
(self, maximum)
Sets the maximum for the range. :param maximum: The maximum of the range.
Sets the maximum for the range. :param maximum: The maximum of the range.
[ "Sets", "the", "maximum", "for", "the", "range", ".", ":", "param", "maximum", ":", "The", "maximum", "of", "the", "range", "." ]
def set_maximum(self, maximum): """ Sets the maximum for the range. :param maximum: The maximum of the range. """ minimum = min([self.min_marker.get_position(), self.max_marker.get_position()]) self.set_range(minimum, maximum)
[ "def", "set_maximum", "(", "self", ",", "maximum", ")", ":", "minimum", "=", "min", "(", "[", "self", ".", "min_marker", ".", "get_position", "(", ")", ",", "self", ".", "max_marker", ".", "get_position", "(", ")", "]", ")", "self", ".", "set_range", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/plotting/markers.py#L1115-L1121
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py
python
_signature_from_builtin
(cls, func, skip_bound_arg=True)
return _signature_fromstr(cls, func, s, skip_bound_arg)
Private helper function to get signature for builtin callables.
Private helper function to get signature for builtin callables.
[ "Private", "helper", "function", "to", "get", "signature", "for", "builtin", "callables", "." ]
def _signature_from_builtin(cls, func, skip_bound_arg=True): """Private helper function to get signature for builtin callables. """ if not _signature_is_builtin(func): raise TypeError("{!r} is not a Python builtin " "function".format(func)) s = getattr(func, "__text_signature__", None) if not s: raise ValueError("no signature found for builtin {!r}".format(func)) return _signature_fromstr(cls, func, s, skip_bound_arg)
[ "def", "_signature_from_builtin", "(", "cls", ",", "func", ",", "skip_bound_arg", "=", "True", ")", ":", "if", "not", "_signature_is_builtin", "(", "func", ")", ":", "raise", "TypeError", "(", "\"{!r} is not a Python builtin \"", "\"function\"", ".", "format", "("...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/inspect.py#L2101-L2114
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/devil/devil/android/device_utils.py
python
DeviceUtils._EnsureCacheInitialized
(self)
Populates cache token, runs getprop and fetches $EXTERNAL_STORAGE.
Populates cache token, runs getprop and fetches $EXTERNAL_STORAGE.
[ "Populates", "cache", "token", "runs", "getprop", "and", "fetches", "$EXTERNAL_STORAGE", "." ]
def _EnsureCacheInitialized(self): """Populates cache token, runs getprop and fetches $EXTERNAL_STORAGE.""" if self._cache['token']: return with self._cache_lock: if self._cache['token']: return # Change the token every time to ensure that it will match only the # previously dumped cache. token = str(uuid.uuid1()) cmd = ( 'c=/data/local/tmp/cache_token;' 'echo $EXTERNAL_STORAGE;' 'cat $c 2>/dev/null||echo;' 'echo "%s">$c &&' % token + 'getprop' ) output = self.RunShellCommand(cmd, check_return=True, large_output=True) # Error-checking for this existing is done in GetExternalStoragePath(). self._cache['external_storage'] = output[0] self._cache['prev_token'] = output[1] output = output[2:] prop_cache = self._cache['getprop'] prop_cache.clear() for key, value in _GETPROP_RE.findall(''.join(output)): prop_cache[key] = value self._cache['token'] = token
[ "def", "_EnsureCacheInitialized", "(", "self", ")", ":", "if", "self", ".", "_cache", "[", "'token'", "]", ":", "return", "with", "self", ".", "_cache_lock", ":", "if", "self", ".", "_cache", "[", "'token'", "]", ":", "return", "# Change the token every time...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/devil/devil/android/device_utils.py#L1926-L1953
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/pyreadline/console/ironpython_console.py
python
event.__init__
(self, console, input)
Initialize an event from the Windows input structure.
Initialize an event from the Windows input structure.
[ "Initialize", "an", "event", "from", "the", "Windows", "input", "structure", "." ]
def __init__(self, console, input): '''Initialize an event from the Windows input structure.''' self.type = '??' self.serial = console.next_serial() self.width = 0 self.height = 0 self.x = 0 self.y = 0 self.char = str(input.KeyChar) self.keycode = input.Key self.state = input.Modifiers log_sock("%s,%s,%s"%(input.Modifiers,input.Key,input.KeyChar),"console") self.type="KeyRelease" self.keysym = make_keysym(self.keycode) self.keyinfo = make_KeyPress(self.char, self.state, self.keycode)
[ "def", "__init__", "(", "self", ",", "console", ",", "input", ")", ":", "self", ".", "type", "=", "'??'", "self", ".", "serial", "=", "console", ".", "next_serial", "(", ")", "self", ".", "width", "=", "0", "self", ".", "height", "=", "0", "self", ...
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/console/ironpython_console.py#L356-L370
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py
python
Standard_Suite_Events.count
(self, _object, _attributes={}, **_arguments)
count: Return the number of elements of a particular class within an object. Required argument: the object for the command Keyword argument each: The class of objects to be counted. Keyword argument _attributes: AppleEvent attribute dictionary Returns: the reply for the command
count: Return the number of elements of a particular class within an object. Required argument: the object for the command Keyword argument each: The class of objects to be counted. Keyword argument _attributes: AppleEvent attribute dictionary Returns: the reply for the command
[ "count", ":", "Return", "the", "number", "of", "elements", "of", "a", "particular", "class", "within", "an", "object", ".", "Required", "argument", ":", "the", "object", "for", "the", "command", "Keyword", "argument", "each", ":", "The", "class", "of", "ob...
def count(self, _object, _attributes={}, **_arguments): """count: Return the number of elements of a particular class within an object. Required argument: the object for the command Keyword argument each: The class of objects to be counted. Keyword argument _attributes: AppleEvent attribute dictionary Returns: the reply for the command """ _code = 'core' _subcode = 'cnte' aetools.keysubst(_arguments, self._argmap_count) _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "count", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'core'", "_subcode", "=", "'cnte'", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", "_argmap_count", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py#L47-L67
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/array_analysis.py
python
ShapeEquivSet.intersect
(self, equiv_set)
return newset
Overload the intersect method to handle ind_to_var.
Overload the intersect method to handle ind_to_var.
[ "Overload", "the", "intersect", "method", "to", "handle", "ind_to_var", "." ]
def intersect(self, equiv_set): """Overload the intersect method to handle ind_to_var. """ newset = super(ShapeEquivSet, self).intersect(equiv_set) ind_to_var = {} for i, objs in newset.ind_to_obj.items(): assert(len(objs) > 0) obj = objs[0] assert(obj in self.obj_to_ind) assert(obj in equiv_set.obj_to_ind) j = self.obj_to_ind[obj] k = equiv_set.obj_to_ind[obj] assert(j in self.ind_to_var) assert(k in equiv_set.ind_to_var) varlist = [] names = [x.name for x in equiv_set.ind_to_var[k]] for x in self.ind_to_var[j]: if x.name in names: varlist.append(x) ind_to_var[i] = varlist newset.ind_to_var = ind_to_var return newset
[ "def", "intersect", "(", "self", ",", "equiv_set", ")", ":", "newset", "=", "super", "(", "ShapeEquivSet", ",", "self", ")", ".", "intersect", "(", "equiv_set", ")", "ind_to_var", "=", "{", "}", "for", "i", ",", "objs", "in", "newset", ".", "ind_to_obj...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/array_analysis.py#L577-L598
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_parser.py
python
p_top_conjecture_labeledfmla
(p)
top : top CONJECTURE labeledfmla
top : top CONJECTURE labeledfmla
[ "top", ":", "top", "CONJECTURE", "labeledfmla" ]
def p_top_conjecture_labeledfmla(p): 'top : top CONJECTURE labeledfmla' p[0] = p[1] d = ConjectureDecl(addlabel(p[3],'conj')) d.lineno = get_lineno(p,2) p[0].declare(d)
[ "def", "p_top_conjecture_labeledfmla", "(", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "d", "=", "ConjectureDecl", "(", "addlabel", "(", "p", "[", "3", "]", ",", "'conj'", ")", ")", "d", ".", "lineno", "=", "get_lineno", "(", "p"...
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L419-L424
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/combo.py
python
ComboPopup_DefaultPaintComboControl
(*args, **kwargs)
return _combo.ComboPopup_DefaultPaintComboControl(*args, **kwargs)
ComboPopup_DefaultPaintComboControl(wxComboCtrlBase combo, DC dc, Rect rect) Default PaintComboControl behaviour
ComboPopup_DefaultPaintComboControl(wxComboCtrlBase combo, DC dc, Rect rect)
[ "ComboPopup_DefaultPaintComboControl", "(", "wxComboCtrlBase", "combo", "DC", "dc", "Rect", "rect", ")" ]
def ComboPopup_DefaultPaintComboControl(*args, **kwargs): """ ComboPopup_DefaultPaintComboControl(wxComboCtrlBase combo, DC dc, Rect rect) Default PaintComboControl behaviour """ return _combo.ComboPopup_DefaultPaintComboControl(*args, **kwargs)
[ "def", "ComboPopup_DefaultPaintComboControl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboPopup_DefaultPaintComboControl", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/combo.py#L793-L799
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_NV_GlobalWriteLock_REQUEST.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(TPM2_NV_GlobalWriteLock_REQUEST)
Returns new TPM2_NV_GlobalWriteLock_REQUEST object constructed from its marshaled representation in the given byte buffer
Returns new TPM2_NV_GlobalWriteLock_REQUEST object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "TPM2_NV_GlobalWriteLock_REQUEST", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new TPM2_NV_GlobalWriteLock_REQUEST object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(TPM2_NV_GlobalWriteLock_REQUEST)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "TPM2_NV_GlobalWriteLock_REQUEST", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L17003-L17007
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/special/_generate_pyx.py
python
FusedFunc._get_incallvars
(self, intypes, c)
return incallvars
Generate pure input variables to a specialization, i.e. variables that aren't used to return a value.
Generate pure input variables to a specialization, i.e. variables that aren't used to return a value.
[ "Generate", "pure", "input", "variables", "to", "a", "specialization", "i", ".", "e", ".", "variables", "that", "aren", "t", "used", "to", "return", "a", "value", "." ]
def _get_incallvars(self, intypes, c): """Generate pure input variables to a specialization, i.e. variables that aren't used to return a value. """ incallvars = [] for n, intype in enumerate(intypes): var = self.invars[n] if c and intype == "double complex": var = npy_cdouble_from_double_complex(var) incallvars.append(var) return incallvars
[ "def", "_get_incallvars", "(", "self", ",", "intypes", ",", "c", ")", ":", "incallvars", "=", "[", "]", "for", "n", ",", "intype", "in", "enumerate", "(", "intypes", ")", ":", "var", "=", "self", ".", "invars", "[", "n", "]", "if", "c", "and", "i...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/special/_generate_pyx.py#L788-L799
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
onnxruntime/python/tools/quantization/calibrate.py
python
CalibraterBase._create_inference_session
(self)
create an OnnxRuntime InferenceSession.
create an OnnxRuntime InferenceSession.
[ "create", "an", "OnnxRuntime", "InferenceSession", "." ]
def _create_inference_session(self): ''' create an OnnxRuntime InferenceSession. ''' sess_options = onnxruntime.SessionOptions() sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL self.infer_session = onnxruntime.InferenceSession(self.augmented_model_path, sess_options=sess_options, providers=self.execution_providers)
[ "def", "_create_inference_session", "(", "self", ")", ":", "sess_options", "=", "onnxruntime", ".", "SessionOptions", "(", ")", "sess_options", ".", "graph_optimization_level", "=", "onnxruntime", ".", "GraphOptimizationLevel", ".", "ORT_DISABLE_ALL", "self", ".", "in...
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/onnxruntime/python/tools/quantization/calibrate.py#L74-L82
stack-of-tasks/pinocchio
593d4d43fded997bb9aa2421f4e55294dbd233c4
bindings/python/pinocchio/robot_wrapper.py
python
RobotWrapper.getViewerNodeName
(self, geometry_object, geometry_type)
return self.viz.getViewerNodeName(geometry_object, geometry_type)
For each geometry object, returns the corresponding name of the node in the display.
For each geometry object, returns the corresponding name of the node in the display.
[ "For", "each", "geometry", "object", "returns", "the", "corresponding", "name", "of", "the", "node", "in", "the", "display", "." ]
def getViewerNodeName(self, geometry_object, geometry_type): """For each geometry object, returns the corresponding name of the node in the display.""" return self.viz.getViewerNodeName(geometry_object, geometry_type)
[ "def", "getViewerNodeName", "(", "self", ",", "geometry_object", ",", "geometry_type", ")", ":", "return", "self", ".", "viz", ".", "getViewerNodeName", "(", "geometry_object", ",", "geometry_type", ")" ]
https://github.com/stack-of-tasks/pinocchio/blob/593d4d43fded997bb9aa2421f4e55294dbd233c4/bindings/python/pinocchio/robot_wrapper.py#L261-L263
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatMenuBar.AddControl
(self, control)
Adds any control to the toolbar, typically e.g. a combobox. :param `control`: the control to be added, a subclass of :class:`Window` (but no :class:`TopLevelWindow`).
Adds any control to the toolbar, typically e.g. a combobox. :param `control`: the control to be added, a subclass of :class:`Window` (but no :class:`TopLevelWindow`).
[ "Adds", "any", "control", "to", "the", "toolbar", "typically", "e", ".", "g", ".", "a", "combobox", ".", ":", "param", "control", ":", "the", "control", "to", "be", "added", "a", "subclass", "of", ":", "class", ":", "Window", "(", "but", "no", ":", ...
def AddControl(self, control): """ Adds any control to the toolbar, typically e.g. a combobox. :param `control`: the control to be added, a subclass of :class:`Window` (but no :class:`TopLevelWindow`). """ self._tbButtons.append(ToolBarItem(FlatToolbarItem(control), wx.Rect(), ControlNormal))
[ "def", "AddControl", "(", "self", ",", "control", ")", ":", "self", ".", "_tbButtons", ".", "append", "(", "ToolBarItem", "(", "FlatToolbarItem", "(", "control", ")", ",", "wx", ".", "Rect", "(", ")", ",", "ControlNormal", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L3703-L3710
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_grad/grad_base.py
python
get_bprop_fn
(prim)
return bprops.get(prim, None)
get bprop function by primitive obj or prim name for c++
get bprop function by primitive obj or prim name for c++
[ "get", "bprop", "function", "by", "primitive", "obj", "or", "prim", "name", "for", "c", "++" ]
def get_bprop_fn(prim): """get bprop function by primitive obj or prim name for c++""" out = bprop_getters.get(prim, None) if out: return out(prim) return bprops.get(prim, None)
[ "def", "get_bprop_fn", "(", "prim", ")", ":", "out", "=", "bprop_getters", ".", "get", "(", "prim", ",", "None", ")", "if", "out", ":", "return", "out", "(", "prim", ")", "return", "bprops", ".", "get", "(", "prim", ",", "None", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_base.py#L44-L49
linyouhappy/kongkongxiyou
7a69b2913eb29f4be77f9a62fb90cdd72c4160f1
cocosjs/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
Index.read
(self, path)
return TranslationUnit.from_ast(path, self)
Load a TranslationUnit from the given AST file.
Load a TranslationUnit from the given AST file.
[ "Load", "a", "TranslationUnit", "from", "the", "given", "AST", "file", "." ]
def read(self, path): """Load a TranslationUnit from the given AST file.""" return TranslationUnit.from_ast(path, self)
[ "def", "read", "(", "self", ",", "path", ")", ":", "return", "TranslationUnit", ".", "from_ast", "(", "path", ",", "self", ")" ]
https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1919-L1921
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/wheel.py
python
message_about_scripts_not_on_PATH
(scripts)
return "\n".join(msg_lines)
Determine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None.
Determine if any scripts are not on PATH and format a warning.
[ "Determine", "if", "any", "scripts", "are", "not", "on", "PATH", "and", "format", "a", "warning", "." ]
def message_about_scripts_not_on_PATH(scripts): # type: (Sequence[str]) -> Optional[str] """Determine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None. """ if not scripts: return None # Group scripts by the path they were installed in grouped_by_dir = collections.defaultdict(set) # type: Dict[str, set] for destfile in scripts: parent_dir = os.path.dirname(destfile) script_name = os.path.basename(destfile) grouped_by_dir[parent_dir].add(script_name) # We don't want to warn for directories that are on PATH. not_warn_dirs = [ os.path.normcase(i).rstrip(os.sep) for i in os.environ.get("PATH", "").split(os.pathsep) ] # If an executable sits with sys.executable, we don't warn for it. # This covers the case of venv invocations without activating the venv. not_warn_dirs.append(os.path.normcase(os.path.dirname(sys.executable))) warn_for = { parent_dir: scripts for parent_dir, scripts in grouped_by_dir.items() if os.path.normcase(parent_dir) not in not_warn_dirs } if not warn_for: return None # Format a message msg_lines = [] for parent_dir, scripts in warn_for.items(): scripts = sorted(scripts) if len(scripts) == 1: start_text = "script {} is".format(scripts[0]) else: start_text = "scripts {} are".format( ", ".join(scripts[:-1]) + " and " + scripts[-1] ) msg_lines.append( "The {} installed in '{}' which is not on PATH." .format(start_text, parent_dir) ) last_line_fmt = ( "Consider adding {} to PATH or, if you prefer " "to suppress this warning, use --no-warn-script-location." ) if len(msg_lines) == 1: msg_lines.append(last_line_fmt.format("this directory")) else: msg_lines.append(last_line_fmt.format("these directories")) # Returns the formatted multiline message return "\n".join(msg_lines)
[ "def", "message_about_scripts_not_on_PATH", "(", "scripts", ")", ":", "# type: (Sequence[str]) -> Optional[str]", "if", "not", "scripts", ":", "return", "None", "# Group scripts by the path they were installed in", "grouped_by_dir", "=", "collections", ".", "defaultdict", "(", ...
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/wheel.py#L180-L238
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
ThirdParty/cinema/paraview/tpl/cinema_python/adaptors/paraview/pv_introspect.py
python
extend_range
(arrayRanges, name, minmax)
This updates the data ranges in the data base meta file. Throughout a time varying data export ranges will vary. Here we accumulate them as we go so that by the end we get the min and max values over for each array component over all time. This version happens in catalyst, where we recreate the database file every timestep.
This updates the data ranges in the data base meta file. Throughout a time varying data export ranges will vary. Here we accumulate them as we go so that by the end we get the min and max values over for each array component over all time.
[ "This", "updates", "the", "data", "ranges", "in", "the", "data", "base", "meta", "file", ".", "Throughout", "a", "time", "varying", "data", "export", "ranges", "will", "vary", ".", "Here", "we", "accumulate", "them", "as", "we", "go", "so", "that", "by",...
def extend_range(arrayRanges, name, minmax): """ This updates the data ranges in the data base meta file. Throughout a time varying data export ranges will vary. Here we accumulate them as we go so that by the end we get the min and max values over for each array component over all time. This version happens in catalyst, where we recreate the database file every timestep. """ adjustedMinMax = range_epsilon(minmax) if name in arrayRanges: temporalMinMax = list(arrayRanges[name]) if adjustedMinMax[0] < temporalMinMax[0]: temporalMinMax[0] = adjustedMinMax[0] if adjustedMinMax[1] > temporalMinMax[1]: temporalMinMax[1] = adjustedMinMax[1] arrayRanges[name] = temporalMinMax else: arrayRanges[name] = adjustedMinMax
[ "def", "extend_range", "(", "arrayRanges", ",", "name", ",", "minmax", ")", ":", "adjustedMinMax", "=", "range_epsilon", "(", "minmax", ")", "if", "name", "in", "arrayRanges", ":", "temporalMinMax", "=", "list", "(", "arrayRanges", "[", "name", "]", ")", "...
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/adaptors/paraview/pv_introspect.py#L350-L370
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/client/session.py
python
SessionInterface.sess_str
(self)
The TensorFlow process to which this session will connect.
The TensorFlow process to which this session will connect.
[ "The", "TensorFlow", "process", "to", "which", "this", "session", "will", "connect", "." ]
def sess_str(self): """The TensorFlow process to which this session will connect.""" raise NotImplementedError('sess_str')
[ "def", "sess_str", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'sess_str'", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/client/session.py#L46-L48
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/Binarization.py
python
EnumBinarization.enum_size
(self, enum_size)
Sets the number of constants in the enumeration.
Sets the number of constants in the enumeration.
[ "Sets", "the", "number", "of", "constants", "in", "the", "enumeration", "." ]
def enum_size(self, enum_size): """Sets the number of constants in the enumeration. """ self._internal.set_enum_size(enum_size)
[ "def", "enum_size", "(", "self", ",", "enum_size", ")", ":", "self", ".", "_internal", ".", "set_enum_size", "(", "enum_size", ")" ]
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Binarization.py#L68-L71