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
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/imaplib.py
python
IMAP4.create
(self, mailbox)
return self._simple_command('CREATE', mailbox)
Create new mailbox. (typ, [data]) = <instance>.create(mailbox)
Create new mailbox.
[ "Create", "new", "mailbox", "." ]
def create(self, mailbox): """Create new mailbox. (typ, [data]) = <instance>.create(mailbox) """ return self._simple_command('CREATE', mailbox)
[ "def", "create", "(", "self", ",", "mailbox", ")", ":", "return", "self", ".", "_simple_command", "(", "'CREATE'", ",", "mailbox", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/imaplib.py#L396-L401
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
src/lib/python/bundy/bundy/component.py
python
Configurator.reconfigure
(self, configuration)
Changes configuration from the current one to the provided. It starts and stops all the components as needed (eg. if there's a component that was not in the original configuration, it is started, any component that was in the old and is not in the new one is stopped).
Changes configuration from the current one to the provided. It starts and stops all the components as needed (eg. if there's a component that was not in the original configuration, it is started, any component that was in the old and is not in the new one is stopped).
[ "Changes", "configuration", "from", "the", "current", "one", "to", "the", "provided", ".", "It", "starts", "and", "stops", "all", "the", "components", "as", "needed", "(", "eg", ".", "if", "there", "s", "a", "component", "that", "was", "not", "in", "the"...
def reconfigure(self, configuration): """ Changes configuration from the current one to the provided. It starts and stops all the components as needed (eg. if there's a component that was not in the original configuration, it is started, any component that was in the old and is not in the new one is stopped). """ if not self._running: raise ValueError("Trying to reconfigure the component " + "configurator while it's not yet running") logger.info(BUNDY_CONFIGURATOR_RECONFIGURE) self.__reconfigure_internal(self._components, configuration)
[ "def", "reconfigure", "(", "self", ",", "configuration", ")", ":", "if", "not", "self", ".", "_running", ":", "raise", "ValueError", "(", "\"Trying to reconfigure the component \"", "+", "\"configurator while it's not yet running\"", ")", "logger", ".", "info", "(", ...
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/bundy/component.py#L590-L602
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/chigger/exodus/ExodusSource.py
python
ExodusSource.__getRange
(self)
return utils.get_min_max(*pairs)
Private version of range for the update method.
Private version of range for the update method.
[ "Private", "version", "of", "range", "for", "the", "update", "method", "." ]
def __getRange(self): """ Private version of range for the update method. """ component = self.getOption('component') pairs = [] for i in range(self.__vtkextractblock.GetOutput().GetNumberOfBlocks()): current = self.__vtkextractblock.GetOutput().GetBlock(i) if isinstance(current, vtk.vtkUnstructuredGrid): array = self.__getActiveArray(current) if array: pairs.append(array.GetRange(component)) elif isinstance(current, vtk.vtkMultiBlockDataSet): for j in range(current.GetNumberOfBlocks()): array = self.__getActiveArray(current.GetBlock(j)) if array: pairs.append(array.GetRange(component)) return utils.get_min_max(*pairs)
[ "def", "__getRange", "(", "self", ")", ":", "component", "=", "self", ".", "getOption", "(", "'component'", ")", "pairs", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "__vtkextractblock", ".", "GetOutput", "(", ")", ".", "GetNumberOfBlocks...
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/chigger/exodus/ExodusSource.py#L130-L149
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/PfemFluidDynamicsApplication/python_scripts/pfem_check_and_prepare_fluid_model_process.py
python
Factory
(settings, Model)
return CheckAndPrepareModelProcess(Model, settings["Parameters"])
This function creates the process
This function creates the process
[ "This", "function", "creates", "the", "process" ]
def Factory(settings, Model): """This function creates the process """ if type(settings) != KratosMultiphysics.Parameters: raise Exception("Expected input shall be a Parameters object, encapsulating a json string") return CheckAndPrepareModelProcess(Model, settings["Parameters"])
[ "def", "Factory", "(", "settings", ",", "Model", ")", ":", "if", "type", "(", "settings", ")", "!=", "KratosMultiphysics", ".", "Parameters", ":", "raise", "Exception", "(", "\"Expected input shall be a Parameters object, encapsulating a json string\"", ")", "return", ...
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/PfemFluidDynamicsApplication/python_scripts/pfem_check_and_prepare_fluid_model_process.py#L25-L30
VowpalWabbit/vowpal_wabbit
866b8fa88ff85a957c7eb72065ea44518b9ba416
python/vowpalwabbit/sklearn.py
python
VW.__getstate__
(self)
return state
Support pickling
Support pickling
[ "Support", "pickling" ]
def __getstate__(self): """Support pickling""" f = NamedTemporaryFile() self.save(filename=f.name) state = self.get_params() with open(f.name, "rb") as tmp: state["vw_"] = tmp.read() f.close() return state
[ "def", "__getstate__", "(", "self", ")", ":", "f", "=", "NamedTemporaryFile", "(", ")", "self", ".", "save", "(", "filename", "=", "f", ".", "name", ")", "state", "=", "self", ".", "get_params", "(", ")", "with", "open", "(", "f", ".", "name", ",",...
https://github.com/VowpalWabbit/vowpal_wabbit/blob/866b8fa88ff85a957c7eb72065ea44518b9ba416/python/vowpalwabbit/sklearn.py#L500-L508
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/dygraph/io.py
python
_get_output_from_program
(program, program_holder, dict_rename_var_old_new=None)
return outs
Get output name of 'program' according to program_holder
Get output name of 'program' according to program_holder
[ "Get", "output", "name", "of", "program", "according", "to", "program_holder" ]
def _get_output_from_program(program, program_holder, dict_rename_var_old_new=None): """ Get output name of 'program' according to program_holder """ outs = list() for var in program_holder.output_descs: for idx in range(program.num_blocks): vars = program.block(idx).vars var_name = var.name() if dict_rename_var_old_new: var_name = dict_rename_var_old_new[var_name] if var_name in vars: out = vars[var_name] if out not in outs: outs.append(out) return outs
[ "def", "_get_output_from_program", "(", "program", ",", "program_holder", ",", "dict_rename_var_old_new", "=", "None", ")", ":", "outs", "=", "list", "(", ")", "for", "var", "in", "program_holder", ".", "output_descs", ":", "for", "idx", "in", "range", "(", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dygraph/io.py#L975-L992
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py
python
NDFrame._to_dict_of_blocks
(self, copy: bool_t = True)
return { k: self._constructor(v).__finalize__(self) for k, v, in self._data.to_dict(copy=copy).items() }
Return a dict of dtype -> Constructor Types that each is a homogeneous dtype. Internal ONLY
Return a dict of dtype -> Constructor Types that each is a homogeneous dtype.
[ "Return", "a", "dict", "of", "dtype", "-", ">", "Constructor", "Types", "that", "each", "is", "a", "homogeneous", "dtype", "." ]
def _to_dict_of_blocks(self, copy: bool_t = True): """ Return a dict of dtype -> Constructor Types that each is a homogeneous dtype. Internal ONLY """ return { k: self._constructor(v).__finalize__(self) for k, v, in self._data.to_dict(copy=copy).items() }
[ "def", "_to_dict_of_blocks", "(", "self", ",", "copy", ":", "bool_t", "=", "True", ")", ":", "return", "{", "k", ":", "self", ".", "_constructor", "(", "v", ")", ".", "__finalize__", "(", "self", ")", "for", "k", ",", "v", ",", "in", "self", ".", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py#L5551-L5561
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/perf/metrics/speedindex.py
python
PaintRectSpeedIndexImpl._TimeAreaDict
(self, paint_events, viewport)
return event_area_dict
Make a dict from time to adjusted area value for events at that time. The adjusted area value of each paint event is determined by how many paint events cover the same rectangle, and whether it's a full-window paint event. "Adjusted area" can also be thought of as "points" of visual completeness -- each rectangle has a certain number of points and these points are distributed amongst the paint events that paint that rectangle. Args: paint_events: A list of paint events viewport: A tuple (width, height) of the window. Returns: A dictionary of times of each paint event (in milliseconds) to the adjusted area that the paint event is worth.
Make a dict from time to adjusted area value for events at that time.
[ "Make", "a", "dict", "from", "time", "to", "adjusted", "area", "value", "for", "events", "at", "that", "time", "." ]
def _TimeAreaDict(self, paint_events, viewport): """Make a dict from time to adjusted area value for events at that time. The adjusted area value of each paint event is determined by how many paint events cover the same rectangle, and whether it's a full-window paint event. "Adjusted area" can also be thought of as "points" of visual completeness -- each rectangle has a certain number of points and these points are distributed amongst the paint events that paint that rectangle. Args: paint_events: A list of paint events viewport: A tuple (width, height) of the window. Returns: A dictionary of times of each paint event (in milliseconds) to the adjusted area that the paint event is worth. """ width, height = viewport fullscreen_area = width * height def ClippedArea(rectangle): """Returns rectangle area clipped to viewport size.""" _, x0, y0, x1, y1 = rectangle clipped_width = max(0, min(width, x1) - max(0, x0)) clipped_height = max(0, min(height, y1) - max(0, y0)) return clipped_width * clipped_height grouped = self._GroupEventByRectangle(paint_events) event_area_dict = collections.defaultdict(int) for rectangle, events in grouped.items(): # The area points for each rectangle are divided up among the paint # events in that rectangle. area = ClippedArea(rectangle) update_count = len(events) adjusted_area = float(area) / update_count # Paint events for the largest-area rectangle are counted as 50%. if area == fullscreen_area: adjusted_area /= 2 for event in events: # The end time for an event is used for that event's time. event_time = event.end event_area_dict[event_time] += adjusted_area return event_area_dict
[ "def", "_TimeAreaDict", "(", "self", ",", "paint_events", ",", "viewport", ")", ":", "width", ",", "height", "=", "viewport", "fullscreen_area", "=", "width", "*", "height", "def", "ClippedArea", "(", "rectangle", ")", ":", "\"\"\"Returns rectangle area clipped to...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/perf/metrics/speedindex.py#L251-L297
lawy623/SVS
b7c7ae367c82a4797ff4a896a2ff304f02e7f724
caffe/python/caffe/classifier.py
python
Classifier.predict
(self, inputs, oversample=True)
return predictions
Predict classification probabilities of inputs. Parameters ---------- inputs : iterable of (H x W x K) input ndarrays. oversample : boolean average predictions across center, corners, and mirrors when True (default). Center-only prediction when False. Returns ------- predictions: (N x C) ndarray of class probabilities for N images and C classes.
Predict classification probabilities of inputs.
[ "Predict", "classification", "probabilities", "of", "inputs", "." ]
def predict(self, inputs, oversample=True): """ Predict classification probabilities of inputs. Parameters ---------- inputs : iterable of (H x W x K) input ndarrays. oversample : boolean average predictions across center, corners, and mirrors when True (default). Center-only prediction when False. Returns ------- predictions: (N x C) ndarray of class probabilities for N images and C classes. """ # Scale to standardize input dimensions. input_ = np.zeros((len(inputs), self.image_dims[0], self.image_dims[1], inputs[0].shape[2]), dtype=np.float32) for ix, in_ in enumerate(inputs): input_[ix] = caffe.io.resize_image(in_, self.image_dims) if oversample: # Generate center, corner, and mirrored crops. input_ = caffe.io.oversample(input_, self.crop_dims) else: # Take center crop. center = np.array(self.image_dims) / 2.0 crop = np.tile(center, (1, 2))[0] + np.concatenate([ -self.crop_dims / 2.0, self.crop_dims / 2.0 ]) crop = crop.astype(int) input_ = input_[:, crop[0]:crop[2], crop[1]:crop[3], :] # Classify caffe_in = np.zeros(np.array(input_.shape)[[0, 3, 1, 2]], dtype=np.float32) for ix, in_ in enumerate(input_): caffe_in[ix] = self.transformer.preprocess(self.inputs[0], in_) out = self.forward_all(**{self.inputs[0]: caffe_in}) predictions = out[self.outputs[0]] # For oversampling, average predictions across crops. if oversample: predictions = predictions.reshape((len(predictions) / 10, 10, -1)) predictions = predictions.mean(1) return predictions
[ "def", "predict", "(", "self", ",", "inputs", ",", "oversample", "=", "True", ")", ":", "# Scale to standardize input dimensions.", "input_", "=", "np", ".", "zeros", "(", "(", "len", "(", "inputs", ")", ",", "self", ".", "image_dims", "[", "0", "]", ","...
https://github.com/lawy623/SVS/blob/b7c7ae367c82a4797ff4a896a2ff304f02e7f724/caffe/python/caffe/classifier.py#L47-L98
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
DLG_SZE
(win, size_width, height=None)
Convenience function for converting a Size or (w,h) in dialog units to pixel units.
Convenience function for converting a Size or (w,h) in dialog units to pixel units.
[ "Convenience", "function", "for", "converting", "a", "Size", "or", "(", "w", "h", ")", "in", "dialog", "units", "to", "pixel", "units", "." ]
def DLG_SZE(win, size_width, height=None): """ Convenience function for converting a Size or (w,h) in dialog units to pixel units. """ if height is None: return win.ConvertDialogSizeToPixels(size_width) else: return win.ConvertDialogSizeToPixels(wx.Size(size_width, height))
[ "def", "DLG_SZE", "(", "win", ",", "size_width", ",", "height", "=", "None", ")", ":", "if", "height", "is", "None", ":", "return", "win", ".", "ConvertDialogSizeToPixels", "(", "size_width", ")", "else", ":", "return", "win", ".", "ConvertDialogSizeToPixels...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L11791-L11799
Jittor/jittor
e9aca0444c2bdc8e2389d99122954cd0903eec46
python/jittor/transform/__init__.py
python
RandomAffine.__call__
(self, img:Image.Image)
return F_pil.affine(img, *ret, resample=self.resample, fillcolor=self.fillcolor)
img (PIL Image): Image to be transformed. Returns: PIL Image: Affine transformed image.
img (PIL Image): Image to be transformed.
[ "img", "(", "PIL", "Image", ")", ":", "Image", "to", "be", "transformed", "." ]
def __call__(self, img:Image.Image): """ img (PIL Image): Image to be transformed. Returns: PIL Image: Affine transformed image. """ if not isinstance(img, Image.Image): img = to_pil_image(img) ret = self.get_params(self.degrees, self.translate, self.scale, self.shear, img.size) return F_pil.affine(img, *ret, resample=self.resample, fillcolor=self.fillcolor)
[ "def", "__call__", "(", "self", ",", "img", ":", "Image", ".", "Image", ")", ":", "if", "not", "isinstance", "(", "img", ",", "Image", ".", "Image", ")", ":", "img", "=", "to_pil_image", "(", "img", ")", "ret", "=", "self", ".", "get_params", "(", ...
https://github.com/Jittor/jittor/blob/e9aca0444c2bdc8e2389d99122954cd0903eec46/python/jittor/transform/__init__.py#L1438-L1448
include-what-you-use/include-what-you-use
208fbfffa5d69364b9f78e427caa443441279283
fix_includes.py
python
_MarkHeaderGuardIfPresent
(file_lines)
If any line in file_lines is a header-guard, mark it in file_lines. We define a header-guard as follows: an #ifdef where there is nothing contentful before or after the #ifdef. Also, the #ifdef should have no #elif in it (though we don't currently test that). This catches the common case of an 'ifdef guard' in .h file, such as '#ifndef FOO_H\n#define FOO_H\n...contents...\n#endif', but it can also catch other whole-program #ifdefs, such as '#ifdef __linux\n...\n#endif'. The issue here is that if an #ifdef encloses the entire file, then we are willing to put new #includes/fwd-declares inside the #ifdef (which normally we wouldn't do). So we want to mark such #ifdefs with a special label. If we find such an #ifdef line -- and a single file can have at most one -- we change its type to a special type for header guards. Arguments: file_lines: an array of LineInfo objects with .type filled in.
If any line in file_lines is a header-guard, mark it in file_lines.
[ "If", "any", "line", "in", "file_lines", "is", "a", "header", "-", "guard", "mark", "it", "in", "file_lines", "." ]
def _MarkHeaderGuardIfPresent(file_lines): """If any line in file_lines is a header-guard, mark it in file_lines. We define a header-guard as follows: an #ifdef where there is nothing contentful before or after the #ifdef. Also, the #ifdef should have no #elif in it (though we don't currently test that). This catches the common case of an 'ifdef guard' in .h file, such as '#ifndef FOO_H\n#define FOO_H\n...contents...\n#endif', but it can also catch other whole-program #ifdefs, such as '#ifdef __linux\n...\n#endif'. The issue here is that if an #ifdef encloses the entire file, then we are willing to put new #includes/fwd-declares inside the #ifdef (which normally we wouldn't do). So we want to mark such #ifdefs with a special label. If we find such an #ifdef line -- and a single file can have at most one -- we change its type to a special type for header guards. Arguments: file_lines: an array of LineInfo objects with .type filled in. """ # Pass over blank lines, pragmas and comments at the top of the file. i = 0 for i in range(len(file_lines)): if (not file_lines[i].deleted and file_lines[i].type not in [_COMMENT_LINE_RE, _BLANK_LINE_RE, _PRAGMA_ONCE_LINE_RE]): break else: # for/else: got to EOF without finding any non-blank/comment lines return # This next line is the candidate header guard-line. ifdef_start = i if file_lines[ifdef_start].type != _IF_RE: # Not a header guard, just return without doing anything. return # Find the end of this ifdef, to see if it's really a header guard.. ifdef_depth = 0 for ifdef_end in range(ifdef_start, len(file_lines)): if file_lines[ifdef_end].deleted: continue if file_lines[ifdef_end].type == _IF_RE: ifdef_depth += 1 elif file_lines[ifdef_end].type == _ENDIF_RE: ifdef_depth -= 1 if ifdef_depth == 0: # The end of our #ifdef! break else: # for/else return False # Weird: never found a close to this #ifdef # Finally, all the lines after the end of the ifdef must be blank or comments. for i in range(ifdef_end + 1, len(file_lines)): if (not file_lines[i].deleted and file_lines[i].type not in [_COMMENT_LINE_RE, _BLANK_LINE_RE]): return # We passed the gauntlet! file_lines[ifdef_start].type = _HEADER_GUARD_RE # And the line after the header guard #ifdef is the '#define' (usually). if _HEADER_GUARD_DEFINE_RE.match(file_lines[ifdef_start + 1].line): file_lines[ifdef_start+1].type = _HEADER_GUARD_DEFINE_RE
[ "def", "_MarkHeaderGuardIfPresent", "(", "file_lines", ")", ":", "# Pass over blank lines, pragmas and comments at the top of the file.", "i", "=", "0", "for", "i", "in", "range", "(", "len", "(", "file_lines", ")", ")", ":", "if", "(", "not", "file_lines", "[", "...
https://github.com/include-what-you-use/include-what-you-use/blob/208fbfffa5d69364b9f78e427caa443441279283/fix_includes.py#L630-L691
telefonicaid/fiware-orion
27c3202b9ddcfb9e3635a0af8d373f76e89b1d24
scripts/check_files_compliance.py
python
supported_extension
(root, file)
return False
Check if the file is supported depending of the name, the extension of the name inside a path :param root: :param file: :return:
Check if the file is supported depending of the name, the extension of the name inside a path :param root: :param file: :return:
[ "Check", "if", "the", "file", "is", "supported", "depending", "of", "the", "name", "the", "extension", "of", "the", "name", "inside", "a", "path", ":", "param", "root", ":", ":", "param", "file", ":", ":", "return", ":" ]
def supported_extension(root, file): """ Check if the file is supported depending of the name, the extension of the name inside a path :param root: :param file: :return: """ extensions = ['py', 'cpp', 'h', 'xml', 'json', 'test', 'vtest', 'txt', 'sh', 'spec', 'cfg', 'DISABLED', 'xtest', 'centos', 'js', 'jmx', 'vtestx', 'feature', 'go'] names = ['makefile', 'Makefile'] # Check extensions if os.path.splitext(file)[1][1:] in extensions: return True # Check filenames if file in names: return True # Check a filename in a root if 'config' in root and file == 'contextBroker': return True filename = os.path.join(root, file) print 'not supported extension: {filename}'.format(filename=filename) return False
[ "def", "supported_extension", "(", "root", ",", "file", ")", ":", "extensions", "=", "[", "'py'", ",", "'cpp'", ",", "'h'", ",", "'xml'", ",", "'json'", ",", "'test'", ",", "'vtest'", ",", "'txt'", ",", "'sh'", ",", "'spec'", ",", "'cfg'", ",", "'DIS...
https://github.com/telefonicaid/fiware-orion/blob/27c3202b9ddcfb9e3635a0af8d373f76e89b1d24/scripts/check_files_compliance.py#L152-L177
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/misc/pilutil.py
python
imresize
(arr, size, interp='bilinear', mode=None)
return fromimage(imnew)
Resize an image. Parameters ---------- arr : ndarray The array of image to be resized. size : int, float or tuple * int - Percentage of current size. * float - Fraction of current size. * tuple - Size of the output image. interp : str, optional Interpolation to use for re-sizing ('nearest', 'lanczos', 'bilinear', 'bicubic' or 'cubic'). mode : str, optional The PIL image mode ('P', 'L', etc.) to convert `arr` before resizing. Returns ------- imresize : ndarray The resized array of image. See Also -------- toimage : Implicitly used to convert `arr` according to `mode`. scipy.ndimage.zoom : More generic implementation that does not use PIL.
Resize an image.
[ "Resize", "an", "image", "." ]
def imresize(arr, size, interp='bilinear', mode=None): """ Resize an image. Parameters ---------- arr : ndarray The array of image to be resized. size : int, float or tuple * int - Percentage of current size. * float - Fraction of current size. * tuple - Size of the output image. interp : str, optional Interpolation to use for re-sizing ('nearest', 'lanczos', 'bilinear', 'bicubic' or 'cubic'). mode : str, optional The PIL image mode ('P', 'L', etc.) to convert `arr` before resizing. Returns ------- imresize : ndarray The resized array of image. See Also -------- toimage : Implicitly used to convert `arr` according to `mode`. scipy.ndimage.zoom : More generic implementation that does not use PIL. """ im = toimage(arr, mode=mode) ts = type(size) if issubdtype(ts, int): percent = size / 100.0 size = tuple((array(im.size)*percent).astype(int)) elif issubdtype(type(size), float): size = tuple((array(im.size)*size).astype(int)) else: size = (size[1], size[0]) func = {'nearest': 0, 'lanczos': 1, 'bilinear': 2, 'bicubic': 3, 'cubic': 3} imnew = im.resize(size, resample=func[interp]) return fromimage(imnew)
[ "def", "imresize", "(", "arr", ",", "size", ",", "interp", "=", "'bilinear'", ",", "mode", "=", "None", ")", ":", "im", "=", "toimage", "(", "arr", ",", "mode", "=", "mode", ")", "ts", "=", "type", "(", "size", ")", "if", "issubdtype", "(", "ts",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/misc/pilutil.py#L446-L489
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_3_0_0.py
python
MiroInterpreter.do_download
(self, line)
download <name> -- Downloads an item by name in the feed/playlist selected.
download <name> -- Downloads an item by name in the feed/playlist selected.
[ "download", "<name", ">", "--", "Downloads", "an", "item", "by", "name", "in", "the", "feed", "/", "playlist", "selected", "." ]
def do_download(self, line): """download <name> -- Downloads an item by name in the feed/playlist selected.""" if self.selection_type is None: print "Error: No feed/playlist selected" return item = self._find_item(line) if item is None: print "No item named %r" % line return if item.get_state() == 'downloading': print '%s is currently being downloaded' % item.get_title() elif item.is_downloaded(): print '%s is already downloaded' % item.get_title() else: item.download()
[ "def", "do_download", "(", "self", ",", "line", ")", ":", "if", "self", ".", "selection_type", "is", "None", ":", "print", "\"Error: No feed/playlist selected\"", "return", "item", "=", "self", ".", "_find_item", "(", "line", ")", "if", "item", "is", "None",...
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_3_0_0.py#L618-L632
JumpingYang001/webrtc
c03d6e965e1f54aeadd670e491eabe5fdb8db968
tools_webrtc/autoroller/roll_deps.py
python
ReadUrlContent
(url)
Connect to a remote host and read the contents. Returns a list of lines.
Connect to a remote host and read the contents. Returns a list of lines.
[ "Connect", "to", "a", "remote", "host", "and", "read", "the", "contents", ".", "Returns", "a", "list", "of", "lines", "." ]
def ReadUrlContent(url): """Connect to a remote host and read the contents. Returns a list of lines.""" conn = urllib2.urlopen(url) try: return conn.readlines() except IOError as e: logging.exception('Error connecting to %s. Error: %s', url, e) raise finally: conn.close()
[ "def", "ReadUrlContent", "(", "url", ")", ":", "conn", "=", "urllib2", ".", "urlopen", "(", "url", ")", "try", ":", "return", "conn", ".", "readlines", "(", ")", "except", "IOError", "as", "e", ":", "logging", ".", "exception", "(", "'Error connecting to...
https://github.com/JumpingYang001/webrtc/blob/c03d6e965e1f54aeadd670e491eabe5fdb8db968/tools_webrtc/autoroller/roll_deps.py#L211-L220
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/wheel.py
python
WheelBuilder._build_one
(self, req)
Build one wheel.
Build one wheel.
[ "Build", "one", "wheel", "." ]
def _build_one(self, req): """Build one wheel.""" base_args = [ sys.executable, '-c', "import setuptools;__file__=%r;"\ "exec(compile(open(__file__).read().replace('\\r\\n', '\\n'), __file__, 'exec'))" % req.setup_py] + \ list(self.global_options) logger.notify('Running setup.py bdist_wheel for %s' % req.name) logger.notify('Destination directory: %s' % self.wheel_dir) wheel_args = base_args + ['bdist_wheel', '-d', self.wheel_dir] + self.build_options try: call_subprocess(wheel_args, cwd=req.source_dir, show_stdout=False) return True except: logger.error('Failed building wheel for %s' % req.name) return False
[ "def", "_build_one", "(", "self", ",", "req", ")", ":", "base_args", "=", "[", "sys", ".", "executable", ",", "'-c'", ",", "\"import setuptools;__file__=%r;\"", "\"exec(compile(open(__file__).read().replace('\\\\r\\\\n', '\\\\n'), __file__, 'exec'))\"", "%", "req", ".", "...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/wheel.py#L286-L303
RobotLocomotion/drake
0e18a34604c45ed65bc9018a54f7610f91cdad5b
bindings/pydrake/systems/drawing.py
python
plot_graphviz
(dot_text)
return plt.imshow(plt.imread(f.name), aspect="equal")
Renders a DOT graph in matplotlib.
Renders a DOT graph in matplotlib.
[ "Renders", "a", "DOT", "graph", "in", "matplotlib", "." ]
def plot_graphviz(dot_text): """Renders a DOT graph in matplotlib.""" # @ref https://stackoverflow.com/a/18522941/7829525 # Tried (reason ignored): pydotplus (`pydot` works), networkx # (`read_dot` does not work robustly?), pygraphviz (coupled with # `networkx`). g = pydot.graph_from_dot_data(dot_text) if isinstance(g, list): # Per Ioannis's follow-up comment in the above link, in pydot >= 1.2.3 # `graph_from_dot_data` returns a list of graphs. # Handle this case for now. assert len(g) == 1 g = g[0] f = NamedTemporaryFile(suffix='.png', dir=temp_directory()) g.write_png(f.name) plt.axis('off') return plt.imshow(plt.imread(f.name), aspect="equal")
[ "def", "plot_graphviz", "(", "dot_text", ")", ":", "# @ref https://stackoverflow.com/a/18522941/7829525", "# Tried (reason ignored): pydotplus (`pydot` works), networkx", "# (`read_dot` does not work robustly?), pygraphviz (coupled with", "# `networkx`).", "g", "=", "pydot", ".", "graph_...
https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/bindings/pydrake/systems/drawing.py#L16-L33
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/parse.py
python
Parser.__init__
(self, grammar, convert=None)
Constructor. The grammar argument is a grammar.Grammar instance; see the grammar module for more information. The parser is not ready yet for parsing; you must call the setup() method to get it started. The optional convert argument is a function mapping concrete syntax tree nodes to abstract syntax tree nodes. If not given, no conversion is done and the syntax tree produced is the concrete syntax tree. If given, it must be a function of two arguments, the first being the grammar (a grammar.Grammar instance), and the second being the concrete syntax tree node to be converted. The syntax tree is converted from the bottom up. A concrete syntax tree node is a (type, value, context, nodes) tuple, where type is the node type (a token or symbol number), value is None for symbols and a string for tokens, context is None or an opaque value used for error reporting (typically a (lineno, offset) pair), and nodes is a list of children for symbols, and None for tokens. An abstract syntax tree node may be anything; this is entirely up to the converter function.
Constructor.
[ "Constructor", "." ]
def __init__(self, grammar, convert=None): """Constructor. The grammar argument is a grammar.Grammar instance; see the grammar module for more information. The parser is not ready yet for parsing; you must call the setup() method to get it started. The optional convert argument is a function mapping concrete syntax tree nodes to abstract syntax tree nodes. If not given, no conversion is done and the syntax tree produced is the concrete syntax tree. If given, it must be a function of two arguments, the first being the grammar (a grammar.Grammar instance), and the second being the concrete syntax tree node to be converted. The syntax tree is converted from the bottom up. A concrete syntax tree node is a (type, value, context, nodes) tuple, where type is the node type (a token or symbol number), value is None for symbols and a string for tokens, context is None or an opaque value used for error reporting (typically a (lineno, offset) pair), and nodes is a list of children for symbols, and None for tokens. An abstract syntax tree node may be anything; this is entirely up to the converter function. """ self.grammar = grammar self.convert = convert or (lambda grammar, node: node)
[ "def", "__init__", "(", "self", ",", "grammar", ",", "convert", "=", "None", ")", ":", "self", ".", "grammar", "=", "grammar", "self", ".", "convert", "=", "convert", "or", "(", "lambda", "grammar", ",", "node", ":", "node", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/parse.py#L57-L87
nodejs/nan
8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62
cpplint.py
python
RemoveMultiLineCommentsFromRange
(lines, begin, end)
Clears a range of lines for multi-line comments.
Clears a range of lines for multi-line comments.
[ "Clears", "a", "range", "of", "lines", "for", "multi", "-", "line", "comments", "." ]
def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '/**/'
[ "def", "RemoveMultiLineCommentsFromRange", "(", "lines", ",", "begin", ",", "end", ")", ":", "# Having // dummy comments makes the lines non-empty, so we will not get", "# unnecessary blank line warnings later in the code.", "for", "i", "in", "range", "(", "begin", ",", "end", ...
https://github.com/nodejs/nan/blob/8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62/cpplint.py#L1609-L1614
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/youtube/service.py
python
YouTubeService.AddVideoEntryToFavorites
(self, video_entry, username='default')
return self.Post(video_entry, post_uri, converter=gdata.youtube.YouTubeVideoEntryFromString)
Add a video entry to a users favorite feed. Needs authentication. Args: video_entry: The YouTubeVideoEntry to add. username: An optional string representing the username to whose favorite feed you wish to add the entry. Defaults to the currently authenticated user. Returns: The posted YouTubeVideoEntry if successfully posted.
Add a video entry to a users favorite feed.
[ "Add", "a", "video", "entry", "to", "a", "users", "favorite", "feed", "." ]
def AddVideoEntryToFavorites(self, video_entry, username='default'): """Add a video entry to a users favorite feed. Needs authentication. Args: video_entry: The YouTubeVideoEntry to add. username: An optional string representing the username to whose favorite feed you wish to add the entry. Defaults to the currently authenticated user. Returns: The posted YouTubeVideoEntry if successfully posted. """ post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites') return self.Post(video_entry, post_uri, converter=gdata.youtube.YouTubeVideoEntryFromString)
[ "def", "AddVideoEntryToFavorites", "(", "self", ",", "video_entry", ",", "username", "=", "'default'", ")", ":", "post_uri", "=", "'%s/%s/%s'", "%", "(", "YOUTUBE_USER_FEED_URI", ",", "username", ",", "'favorites'", ")", "return", "self", ".", "Post", "(", "vi...
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/youtube/service.py#L874-L890
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
DateTime.GetCountry
(*args, **kwargs)
return _misc_.DateTime_GetCountry(*args, **kwargs)
GetCountry() -> int
GetCountry() -> int
[ "GetCountry", "()", "-", ">", "int" ]
def GetCountry(*args, **kwargs): """GetCountry() -> int""" return _misc_.DateTime_GetCountry(*args, **kwargs)
[ "def", "GetCountry", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DateTime_GetCountry", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L3677-L3679
flexflow/FlexFlow
581fad8ba8d10a16a3102ee2b406b0319586df24
python/flexflow/keras/utils/generic_utils.py
python
custom_object_scope
(*args)
return CustomObjectScope(*args)
Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Convenience wrapper for `CustomObjectScope`. Code within a `with` statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with` statement, global custom objects are reverted to state at beginning of the `with` statement. # Example Consider a custom object `MyObject` ```python with custom_object_scope({'MyObject':MyObject}): layer = Dense(..., kernel_regularizer='MyObject') # save, load, etc. will recognize custom object by name ``` # Arguments *args: Variable length list of dictionaries of name, class pairs to add to custom objects. # Returns Object of type `CustomObjectScope`.
Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape.
[ "Provides", "a", "scope", "that", "changes", "to", "_GLOBAL_CUSTOM_OBJECTS", "cannot", "escape", "." ]
def custom_object_scope(*args): """Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Convenience wrapper for `CustomObjectScope`. Code within a `with` statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with` statement, global custom objects are reverted to state at beginning of the `with` statement. # Example Consider a custom object `MyObject` ```python with custom_object_scope({'MyObject':MyObject}): layer = Dense(..., kernel_regularizer='MyObject') # save, load, etc. will recognize custom object by name ``` # Arguments *args: Variable length list of dictionaries of name, class pairs to add to custom objects. # Returns Object of type `CustomObjectScope`. """ return CustomObjectScope(*args)
[ "def", "custom_object_scope", "(", "*", "args", ")", ":", "return", "CustomObjectScope", "(", "*", "args", ")" ]
https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/python/flexflow/keras/utils/generic_utils.py#L56-L83
RoboJackets/robocup-software
bce13ce53ddb2ecb9696266d980722c34617dc15
rj_gameplay/rj_gameplay/tactic/clear_tactic.py
python
Clear.tick
( self, world_state: rc.WorldState, role_results: tactic.RoleResults, )
return []
:return: A list of size 1 or 2 skills depending on which roles are filled and state of aiming TODO: Come up with better timings for starting receive
:return: A list of size 1 or 2 skills depending on which roles are filled and state of aiming TODO: Come up with better timings for starting receive
[ ":", "return", ":", "A", "list", "of", "size", "1", "or", "2", "skills", "depending", "on", "which", "roles", "are", "filled", "and", "state", "of", "aiming", "TODO", ":", "Come", "up", "with", "better", "timings", "for", "starting", "receive" ]
def tick( self, world_state: rc.WorldState, role_results: tactic.RoleResults, ) -> List[tactic.SkillEntry]: """ :return: A list of size 1 or 2 skills depending on which roles are filled and state of aiming TODO: Come up with better timings for starting receive """ clearer_result = role_results[self.kick] if clearer_result and clearer_result[0].is_filled(): return [self.kick] return []
[ "def", "tick", "(", "self", ",", "world_state", ":", "rc", ".", "WorldState", ",", "role_results", ":", "tactic", ".", "RoleResults", ",", ")", "->", "List", "[", "tactic", ".", "SkillEntry", "]", ":", "clearer_result", "=", "role_results", "[", "self", ...
https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/rj_gameplay/tactic/clear_tactic.py#L85-L97
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/framemanager.py
python
AuiManager.HitTest
(self, x, y)
return result
This is an internal function which determines which UI item the specified coordinates are over. :param integer `x`: specifies a x position in client coordinates; :param integer `y`: specifies a y position in client coordinates.
This is an internal function which determines which UI item the specified coordinates are over.
[ "This", "is", "an", "internal", "function", "which", "determines", "which", "UI", "item", "the", "specified", "coordinates", "are", "over", "." ]
def HitTest(self, x, y): """ This is an internal function which determines which UI item the specified coordinates are over. :param integer `x`: specifies a x position in client coordinates; :param integer `y`: specifies a y position in client coordinates. """ result = None for item in self._uiparts: # we are not interested in typeDock, because this space # isn't used to draw anything, just for measurements # besides, the entire dock area is covered with other # rectangles, which we are interested in. if item.type == AuiDockUIPart.typeDock: continue # if we already have a hit on a more specific item, we are not # interested in a pane hit. If, however, we don't already have # a hit, returning a pane hit is necessary for some operations if item.type in [AuiDockUIPart.typePane, AuiDockUIPart.typePaneBorder] and result: continue # if the point is inside the rectangle, we have a hit if item.rect.Contains((x, y)): result = item return result
[ "def", "HitTest", "(", "self", ",", "x", ",", "y", ")", ":", "result", "=", "None", "for", "item", "in", "self", ".", "_uiparts", ":", "# we are not interested in typeDock, because this space", "# isn't used to draw anything, just for measurements", "# besides, the entire...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/framemanager.py#L4341-L4370
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pdb.py
python
Pdb.displayhook
(self, obj)
Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins.
Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins.
[ "Custom", "displayhook", "for", "the", "exec", "in", "default", "()", "which", "prevents", "assignment", "of", "the", "_", "variable", "in", "the", "builtins", "." ]
def displayhook(self, obj): """Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins. """ # reproduce the behavior of the standard displayhook, not printing None if obj is not None: self.message(repr(obj))
[ "def", "displayhook", "(", "self", ",", "obj", ")", ":", "# reproduce the behavior of the standard displayhook, not printing None", "if", "obj", "is", "not", "None", ":", "self", ".", "message", "(", "repr", "(", "obj", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pdb.py#L353-L359
RapidsAtHKUST/CommunityDetectionCodes
23dbafd2e57ab0f5f0528b1322c4a409f21e5892
Algorithms/2008-CliquePercolation/src_python/seq_clique_percolation.py
python
loadNet_edg
(input, mutualEdges=False, splitterChar=None, symmetricNet=True)
return newNet
Reads a network data from input in edg format. If mutualEdges is set to True, an edge is added between nodes i and j only if both edges (i,j) and (j,i) are listed. The weight of the edge is the average of the weights of the original edges.
Reads a network data from input in edg format.
[ "Reads", "a", "network", "data", "from", "input", "in", "edg", "format", "." ]
def loadNet_edg(input, mutualEdges=False, splitterChar=None, symmetricNet=True): """ Reads a network data from input in edg format. If mutualEdges is set to True, an edge is added between nodes i and j only if both edges (i,j) and (j,i) are listed. The weight of the edge is the average of the weights of the original edges. """ def isNumerical(input): try: for line in input: int(line.split(splitterChar)[0]) int(line.split(splitterChar)[1]) except ValueError: input.seek(0) return False input.seek(0) return True numerical = isNumerical(input) if symmetricNet: newNet = SymmNet() else: newNet = Net() nodeMap = {} # Used only if mutualEdges = True. for line in input: fields = line.split(splitterChar) if len(fields) > 2: if numerical: fields[0] = int(fields[0]) fields[1] = int(fields[1]) if fields[0] != fields[1]: if mutualEdges: if nodeMap.has_key((fields[1], fields[0])): value = 0.5 * (nodeMap[(fields[1], fields[0])] + float(fields[2])) newNet[fields[0]][fields[1]] = value else: nodeMap[(fields[0], fields[1])] = float(fields[2]) else: newNet[fields[0]][fields[1]] = float(fields[2]) return newNet
[ "def", "loadNet_edg", "(", "input", ",", "mutualEdges", "=", "False", ",", "splitterChar", "=", "None", ",", "symmetricNet", "=", "True", ")", ":", "def", "isNumerical", "(", "input", ")", ":", "try", ":", "for", "line", "in", "input", ":", "int", "(",...
https://github.com/RapidsAtHKUST/CommunityDetectionCodes/blob/23dbafd2e57ab0f5f0528b1322c4a409f21e5892/Algorithms/2008-CliquePercolation/src_python/seq_clique_percolation.py#L197-L242
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/timeseries/python/timeseries/model.py
python
SequentialTimeSeriesModel._prediction_step
(self, current_times, state)
Compute a batch of single-step predictions. Args: current_times: A [batch size] Tensor of times for each observation. state: Model state, imputed to one step before current_times. Returns: A tuple of (updated state, outputs): updated state: Model state updated to current_times. outputs: A dictionary of Tensors with keys corresponding to self._predict_output_names.
Compute a batch of single-step predictions.
[ "Compute", "a", "batch", "of", "single", "-", "step", "predictions", "." ]
def _prediction_step(self, current_times, state): """Compute a batch of single-step predictions. Args: current_times: A [batch size] Tensor of times for each observation. state: Model state, imputed to one step before current_times. Returns: A tuple of (updated state, outputs): updated state: Model state updated to current_times. outputs: A dictionary of Tensors with keys corresponding to self._predict_output_names. """ pass
[ "def", "_prediction_step", "(", "self", ",", "current_times", ",", "state", ")", ":", "pass" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/timeseries/python/timeseries/model.py#L428-L440
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/manifests.py
python
InstallManifest.add_preprocess
(self, source, dest, deps, marker='#', defines={})
Add a preprocessed file to this manifest. ``source`` will be passed through preprocessor.py, and the output will be written to ``dest``.
Add a preprocessed file to this manifest.
[ "Add", "a", "preprocessed", "file", "to", "this", "manifest", "." ]
def add_preprocess(self, source, dest, deps, marker='#', defines={}): """Add a preprocessed file to this manifest. ``source`` will be passed through preprocessor.py, and the output will be written to ``dest``. """ self._add_entry(dest, (self.PREPROCESS, source, deps, marker, self._encode_field_entry(defines)))
[ "def", "add_preprocess", "(", "self", ",", "source", ",", "dest", ",", "deps", ",", "marker", "=", "'#'", ",", "defines", "=", "{", "}", ")", ":", "self", ".", "_add_entry", "(", "dest", ",", "(", "self", ".", "PREPROCESS", ",", "source", ",", "dep...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/manifests.py#L284-L291
cvmfs/cvmfs
4637bdb5153178eadf885c1acf37bdc5c685bf8a
cpplint.py
python
ProcessFileData
(filename, file_extension, lines, error, extra_check_functions=[])
Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Performs lint checks and reports any errors to the given error function.
[ "Performs", "lint", "checks", "and", "reports", "any", "errors", "to", "the", "given", "error", "function", "." ]
def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=[]): """Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ lines = (['// marker so line numbers and indices both start at 1'] + lines + ['// marker so line numbers end in a known way']) include_state = _IncludeState() function_state = _FunctionState() nesting_state = NestingState() ResetNolintSuppressions() CheckForCopyright(filename, lines, error) RemoveMultiLineComments(filename, lines, error) clean_lines = CleansedLines(lines) if file_extension == 'h': CheckForHeaderGuard(filename, clean_lines, error) for line in xrange(clean_lines.NumLines()): ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions) FlagCxx11Features(filename, clean_lines, line, error) nesting_state.CheckCompletedBlocks(filename, error) CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) # Check that the .cc file has included its header if it exists. if file_extension == 'cc': CheckHeaderFileIncluded(filename, include_state, error) # We check here rather than inside ProcessLine so that we see raw # lines rather than "cleaned" lines. CheckForBadCharacters(filename, lines, error) CheckForNewlineAtEOF(filename, lines, error)
[ "def", "ProcessFileData", "(", "filename", ",", "file_extension", ",", "lines", ",", "error", ",", "extra_check_functions", "=", "[", "]", ")", ":", "lines", "=", "(", "[", "'// marker so line numbers and indices both start at 1'", "]", "+", "lines", "+", "[", "...
https://github.com/cvmfs/cvmfs/blob/4637bdb5153178eadf885c1acf37bdc5c685bf8a/cpplint.py#L6004-L6053
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/minimum-number-of-refueling-stops.py
python
Solution.minRefuelStops
(self, target, startFuel, stations)
return result
:type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int
:type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int
[ ":", "type", "target", ":", "int", ":", "type", "startFuel", ":", "int", ":", "type", "stations", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "int" ]
def minRefuelStops(self, target, startFuel, stations): """ :type target: int :type startFuel: int :type stations: List[List[int]] :rtype: int """ max_heap = [] stations.append((target, float("inf"))) result = prev = 0 for location, capacity in stations: startFuel -= location - prev while max_heap and startFuel < 0: startFuel += -heapq.heappop(max_heap) result += 1 if startFuel < 0: return -1 heapq.heappush(max_heap, -capacity) prev = location return result
[ "def", "minRefuelStops", "(", "self", ",", "target", ",", "startFuel", ",", "stations", ")", ":", "max_heap", "=", "[", "]", "stations", ".", "append", "(", "(", "target", ",", "float", "(", "\"inf\"", ")", ")", ")", "result", "=", "prev", "=", "0", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/minimum-number-of-refueling-stops.py#L8-L29
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Rect.SetHeight
(*args, **kwargs)
return _core_.Rect_SetHeight(*args, **kwargs)
SetHeight(self, int h)
SetHeight(self, int h)
[ "SetHeight", "(", "self", "int", "h", ")" ]
def SetHeight(*args, **kwargs): """SetHeight(self, int h)""" return _core_.Rect_SetHeight(*args, **kwargs)
[ "def", "SetHeight", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Rect_SetHeight", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L1297-L1299
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
ThirdParty/cinema/paraview/tpl/cinema_python/database/oexr_helper.py
python
save_rgb
(image, filePath, comp=OexrCompression.ZIP)
Saves the rgb (image) in OpenEXR format. Expects a 3-chan uint32 image.
Saves the rgb (image) in OpenEXR format. Expects a 3-chan uint32 image.
[ "Saves", "the", "rgb", "(", "image", ")", "in", "OpenEXR", "format", ".", "Expects", "a", "3", "-", "chan", "uint32", "image", "." ]
def save_rgb(image, filePath, comp=OexrCompression.ZIP): ''' Saves the rgb (image) in OpenEXR format. Expects a 3-chan uint32 image. ''' if len(image.shape) != 3: raise Exception("Incorrect dimensions!") h, w, c = image.shape if c != 3: raise Exception("Incorrect number of channels!") if image.dtype != "uint32": raise Exception("Incorrect type!, expected uint32") try: header = oe.Header(w, h) header["channels"] = {"R": im.Channel(im.PixelType(oe.UINT)), "G": im.Channel(im.PixelType(oe.UINT)), "B": im.Channel(im.PixelType(oe.UINT))} header['compression'] = im.Compression(comp) of = oe.OutputFile(filePath, header) r_data = image[:, :, 0].tostring() g_data = image[:, :, 1].tostring() b_data = image[:, :, 2].tostring() of.writePixels({"R": r_data, "G": g_data, "B": b_data}) of.close() except: raise
[ "def", "save_rgb", "(", "image", ",", "filePath", ",", "comp", "=", "OexrCompression", ".", "ZIP", ")", ":", "if", "len", "(", "image", ".", "shape", ")", "!=", "3", ":", "raise", "Exception", "(", "\"Incorrect dimensions!\"", ")", "h", ",", "w", ",", ...
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/database/oexr_helper.py#L19-L52
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/MSCommon/sdk.py
python
get_default_sdk
()
return InstalledSDKList[0]
Set up the default Platform/Windows SDK.
Set up the default Platform/Windows SDK.
[ "Set", "up", "the", "default", "Platform", "/", "Windows", "SDK", "." ]
def get_default_sdk(): """Set up the default Platform/Windows SDK.""" get_installed_sdks() if not InstalledSDKList: return None return InstalledSDKList[0]
[ "def", "get_default_sdk", "(", ")", ":", "get_installed_sdks", "(", ")", "if", "not", "InstalledSDKList", ":", "return", "None", "return", "InstalledSDKList", "[", "0", "]" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/MSCommon/sdk.py#L316-L321
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/distributions/beta.py
python
Beta.__init__
(self, concentration1=None, concentration0=None, validate_args=False, allow_nan_stats=True, name="Beta")
Initialize a batch of Beta distributions. Args: concentration1: Positive floating-point `Tensor` indicating mean number of successes; aka "alpha". Implies `self.dtype` and `self.batch_shape`, i.e., `concentration1.shape = [N1, N2, ..., Nm] = self.batch_shape`. concentration0: Positive floating-point `Tensor` indicating mean number of failures; aka "beta". Otherwise has same semantics as `concentration1`. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class.
Initialize a batch of Beta distributions.
[ "Initialize", "a", "batch", "of", "Beta", "distributions", "." ]
def __init__(self, concentration1=None, concentration0=None, validate_args=False, allow_nan_stats=True, name="Beta"): """Initialize a batch of Beta distributions. Args: concentration1: Positive floating-point `Tensor` indicating mean number of successes; aka "alpha". Implies `self.dtype` and `self.batch_shape`, i.e., `concentration1.shape = [N1, N2, ..., Nm] = self.batch_shape`. concentration0: Positive floating-point `Tensor` indicating mean number of failures; aka "beta". Otherwise has same semantics as `concentration1`. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. """ parameters = locals() with ops.name_scope(name, values=[concentration1, concentration0]): self._concentration1 = self._maybe_assert_valid_concentration( ops.convert_to_tensor(concentration1, name="concentration1"), validate_args) self._concentration0 = self._maybe_assert_valid_concentration( ops.convert_to_tensor(concentration0, name="concentration0"), validate_args) check_ops.assert_same_float_dtype([ self._concentration1, self._concentration0]) self._total_concentration = self._concentration1 + self._concentration0 super(Beta, self).__init__( dtype=self._total_concentration.dtype, validate_args=validate_args, allow_nan_stats=allow_nan_stats, reparameterization_type=distribution.NOT_REPARAMETERIZED, parameters=parameters, graph_parents=[self._concentration1, self._concentration0, self._total_concentration], name=name)
[ "def", "__init__", "(", "self", ",", "concentration1", "=", "None", ",", "concentration0", "=", "None", ",", "validate_args", "=", "False", ",", "allow_nan_stats", "=", "True", ",", "name", "=", "\"Beta\"", ")", ":", "parameters", "=", "locals", "(", ")", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/distributions/beta.py#L125-L171
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/sysconfig.py
python
get_makefile_filename
()
return os.path.join(lib_dir, "config", "Makefile")
Return full pathname of installed Makefile from the Python build.
Return full pathname of installed Makefile from the Python build.
[ "Return", "full", "pathname", "of", "installed", "Makefile", "from", "the", "Python", "build", "." ]
def get_makefile_filename(): """Return full pathname of installed Makefile from the Python build.""" if python_build: return os.path.join(project_base, "Makefile") lib_dir = get_python_lib(plat_specific=1, standard_lib=1) return os.path.join(lib_dir, "config", "Makefile")
[ "def", "get_makefile_filename", "(", ")", ":", "if", "python_build", ":", "return", "os", ".", "path", ".", "join", "(", "project_base", ",", "\"Makefile\"", ")", "lib_dir", "=", "get_python_lib", "(", "plat_specific", "=", "1", ",", "standard_lib", "=", "1"...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/sysconfig.py#L248-L253
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/share/gdb/system-gdbinit/elinos.py
python
get_elinos_environment
()
return result
Return the ELinOS environment. If the ELinOS environment is properly set up, return a dictionary which contains: * The path to the ELinOS project at key 'project'; * The path to the ELinOS CDK at key 'cdk'; * The ELinOS target name at key 'target' (Eg. 'i486-linux'); * A list of Xenomai install prefixes (which could be empty, if the ELinOS project does not include Xenomai) at key 'xenomai'. If one of these cannot be found, print a warning; the corresponding value in the returned dictionary will be None.
Return the ELinOS environment.
[ "Return", "the", "ELinOS", "environment", "." ]
def get_elinos_environment(): """Return the ELinOS environment. If the ELinOS environment is properly set up, return a dictionary which contains: * The path to the ELinOS project at key 'project'; * The path to the ELinOS CDK at key 'cdk'; * The ELinOS target name at key 'target' (Eg. 'i486-linux'); * A list of Xenomai install prefixes (which could be empty, if the ELinOS project does not include Xenomai) at key 'xenomai'. If one of these cannot be found, print a warning; the corresponding value in the returned dictionary will be None. """ result = {} for key in ("project", "cdk", "target"): var = "ELINOS_" + key.upper() if var in os.environ: result[key] = os.environ[var] else: warn("%s not set" % var) result[key] = None if result["project"] is not None: result["xenomai"] = glob.glob(result["project"] + "/xenomai-[0-9.]*") else: result["xenomai"] = [] return result
[ "def", "get_elinos_environment", "(", ")", ":", "result", "=", "{", "}", "for", "key", "in", "(", "\"project\"", ",", "\"cdk\"", ",", "\"target\"", ")", ":", "var", "=", "\"ELINOS_\"", "+", "key", ".", "upper", "(", ")", "if", "var", "in", "os", ".",...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/share/gdb/system-gdbinit/elinos.py#L27-L55
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/Devices/EFI/Firmware/BaseTools/Source/Python/GenPatchPcdTable/GenPatchPcdTable.py
python
_parseForGCC
(lines, efifilepath)
return pcds
Parse map file generated by GCC linker
Parse map file generated by GCC linker
[ "Parse", "map", "file", "generated", "by", "GCC", "linker" ]
def _parseForGCC(lines, efifilepath): """ Parse map file generated by GCC linker """ status = 0 imageBase = -1 sections = [] bpcds = [] for line in lines: line = line.strip() # status machine transection if status == 0 and line == "Memory Configuration": status = 1 continue elif status == 1 and line == 'Linker script and memory map': status = 2 continue elif status ==2 and line == 'START GROUP': status = 3 continue # status handler if status == 2: m = re.match('^([\w_\.]+) +([\da-fA-Fx]+) +([\da-fA-Fx]+)$', line) if m != None: sections.append(m.groups(0)) if status == 2: m = re.match("^([\da-fA-Fx]+) +[_]+gPcd_BinaryPatch_([\w_\d]+)$", line) if m != None: bpcds.append((m.groups(0)[1], int(m.groups(0)[0], 16) , int(sections[-1][1], 16), sections[-1][0])) # get section information from efi file efisecs = PeImageClass(efifilepath).SectionHeaderList if efisecs == None or len(efisecs) == 0: return None #redirection redirection = 0 for efisec in efisecs: for section in sections: if section[0].strip() == efisec[0].strip() and section[0].strip() == '.text': redirection = int(section[1], 16) - efisec[1] pcds = [] for pcd in bpcds: for efisec in efisecs: if pcd[1] >= efisec[1] and pcd[1] < efisec[1]+efisec[3]: #assert efisec[0].strip() == pcd[3].strip() and efisec[1] + redirection == pcd[2], "There are some differences between map file and efi file" pcds.append([pcd[0], efisec[2] + pcd[1] - efisec[1] - redirection, efisec[0]]) return pcds
[ "def", "_parseForGCC", "(", "lines", ",", "efifilepath", ")", ":", "status", "=", "0", "imageBase", "=", "-", "1", "sections", "=", "[", "]", "bpcds", "=", "[", "]", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "strip", "(", ")", ...
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Devices/EFI/Firmware/BaseTools/Source/Python/GenPatchPcdTable/GenPatchPcdTable.py#L63-L108
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
catboost/python-package/catboost/metrics.py
python
BuiltinMetric.set_hints
(self, **hints)
Sets hints for the metric. Hints are not validated. Implemented in child classes. Returns ---------- self: for chained calls.
Sets hints for the metric. Hints are not validated. Implemented in child classes.
[ "Sets", "hints", "for", "the", "metric", ".", "Hints", "are", "not", "validated", ".", "Implemented", "in", "child", "classes", "." ]
def set_hints(self, **hints): """ Sets hints for the metric. Hints are not validated. Implemented in child classes. Returns ---------- self: for chained calls. """ raise NotImplementedError('Should be overridden by the child class.')
[ "def", "set_hints", "(", "self", ",", "*", "*", "hints", ")", ":", "raise", "NotImplementedError", "(", "'Should be overridden by the child class.'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/python-package/catboost/metrics.py#L45-L54
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/internals/blocks.py
python
EABackedBlock.delete
(self, loc)
Delete given loc(-s) from block in-place.
Delete given loc(-s) from block in-place.
[ "Delete", "given", "loc", "(", "-", "s", ")", "from", "block", "in", "-", "place", "." ]
def delete(self, loc) -> None: """ Delete given loc(-s) from block in-place. """ # This will be unnecessary if/when __array_function__ is implemented self.values = self.values.delete(loc) self.mgr_locs = self._mgr_locs.delete(loc) try: self._cache.clear() except AttributeError: # _cache not yet initialized pass
[ "def", "delete", "(", "self", ",", "loc", ")", "->", "None", ":", "# This will be unnecessary if/when __array_function__ is implemented", "self", ".", "values", "=", "self", ".", "values", ".", "delete", "(", "loc", ")", "self", ".", "mgr_locs", "=", "self", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/internals/blocks.py#L1334-L1345
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Event.GetSkipped
(*args, **kwargs)
return _core_.Event_GetSkipped(*args, **kwargs)
GetSkipped(self) -> bool Returns true if the event handler should be skipped, false otherwise. :see: `Skip`
GetSkipped(self) -> bool
[ "GetSkipped", "(", "self", ")", "-", ">", "bool" ]
def GetSkipped(*args, **kwargs): """ GetSkipped(self) -> bool Returns true if the event handler should be skipped, false otherwise. :see: `Skip` """ return _core_.Event_GetSkipped(*args, **kwargs)
[ "def", "GetSkipped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Event_GetSkipped", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L5061-L5068
microsoft/clang
86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5
bindings/python/clang/cindex.py
python
Cursor.kind
(self)
return CursorKind.from_id(self._kind_id)
Return the kind of this cursor.
Return the kind of this cursor.
[ "Return", "the", "kind", "of", "this", "cursor", "." ]
def kind(self): """Return the kind of this cursor.""" return CursorKind.from_id(self._kind_id)
[ "def", "kind", "(", "self", ")", ":", "return", "CursorKind", ".", "from_id", "(", "self", ".", "_kind_id", ")" ]
https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/bindings/python/clang/cindex.py#L1521-L1523
MrMC/mrmc
5a8e460b2aec44f03eb9604cbd7681d4277dbb81
tools/Fake Episode Maker/openAnything.py
python
openAnything
(source, etag=None, lastmodified=None, agent=USER_AGENT)
return StringIO(str(source))
URL, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object is guaranteed to have all the basic stdio read methods (read, readline, readlines). Just .close() the object when you're done with it. If the etag argument is supplied, it will be used as the value of an If-None-Match request header. If the lastmodified argument is supplied, it must be a formatted date/time string in GMT (as returned in the Last-Modified header of a previous request). The formatted date/time will be used as the value of an If-Modified-Since request header. If the agent argument is supplied, it will be used as the value of a User-Agent request header.
URL, filename, or string --> stream
[ "URL", "filename", "or", "string", "--", ">", "stream" ]
def openAnything(source, etag=None, lastmodified=None, agent=USER_AGENT): '''URL, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object is guaranteed to have all the basic stdio read methods (read, readline, readlines). Just .close() the object when you're done with it. If the etag argument is supplied, it will be used as the value of an If-None-Match request header. If the lastmodified argument is supplied, it must be a formatted date/time string in GMT (as returned in the Last-Modified header of a previous request). The formatted date/time will be used as the value of an If-Modified-Since request header. If the agent argument is supplied, it will be used as the value of a User-Agent request header. ''' if hasattr(source, 'read'): return source if source == '-': return sys.stdin if urlparse.urlparse(source)[0] == 'http': # open URL with urllib2 request = urllib2.Request(source) request.add_header('User-Agent', agent) if etag: request.add_header('If-None-Match', etag) if lastmodified: request.add_header('If-Modified-Since', lastmodified) request.add_header('Accept-encoding', 'gzip') opener = urllib2.build_opener(SmartRedirectHandler(), DefaultErrorHandler()) return opener.open(request) # try to open with native open function (if source is a filename) try: return open(source) except (IOError, OSError): pass # treat source as string return StringIO(str(source))
[ "def", "openAnything", "(", "source", ",", "etag", "=", "None", ",", "lastmodified", "=", "None", ",", "agent", "=", "USER_AGENT", ")", ":", "if", "hasattr", "(", "source", ",", "'read'", ")", ":", "return", "source", "if", "source", "==", "'-'", ":", ...
https://github.com/MrMC/mrmc/blob/5a8e460b2aec44f03eb9604cbd7681d4277dbb81/tools/Fake Episode Maker/openAnything.py#L46-L92
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/RNN/rnn_quantizer/nndct_shared/nndct_graph/base_graph.py
python
GraphBase.nodes
(self)
Yield node in graph according to topo order Returns: generator: yiled a node when tranverse graph
Yield node in graph according to topo order
[ "Yield", "node", "in", "graph", "according", "to", "topo", "order" ]
def nodes(self): """Yield node in graph according to topo order Returns: generator: yiled a node when tranverse graph """
[ "def", "nodes", "(", "self", ")", ":" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/RNN/rnn_quantizer/nndct_shared/nndct_graph/base_graph.py#L43-L48
microsoft/CCF
14801dc01f3f225fc85772eeb1c066d1b1b10a47
python/ccf/ledger.py
python
LedgerValidator.add_transaction
(self, transaction)
To validate the ledger, ledger transactions need to be added via this method. Depending on the tables that were part of the transaction, it does different things. When transaction contains signature table, it starts the verification process and verifies that the root of merkle tree was signed by a node which was part of the network. It also matches the root of the merkle tree that this class maintains with the one extracted from the ledger. If any of the above checks fail, this method throws.
To validate the ledger, ledger transactions need to be added via this method. Depending on the tables that were part of the transaction, it does different things. When transaction contains signature table, it starts the verification process and verifies that the root of merkle tree was signed by a node which was part of the network. It also matches the root of the merkle tree that this class maintains with the one extracted from the ledger. If any of the above checks fail, this method throws.
[ "To", "validate", "the", "ledger", "ledger", "transactions", "need", "to", "be", "added", "via", "this", "method", ".", "Depending", "on", "the", "tables", "that", "were", "part", "of", "the", "transaction", "it", "does", "different", "things", ".", "When", ...
def add_transaction(self, transaction): """ To validate the ledger, ledger transactions need to be added via this method. Depending on the tables that were part of the transaction, it does different things. When transaction contains signature table, it starts the verification process and verifies that the root of merkle tree was signed by a node which was part of the network. It also matches the root of the merkle tree that this class maintains with the one extracted from the ledger. If any of the above checks fail, this method throws. """ transaction_public_domain = transaction.get_public_domain() tables = transaction_public_domain.get_tables() # Add contributing nodes certs and update nodes network trust status for verification node_certs = {} if NODES_TABLE_NAME in tables: node_table = tables[NODES_TABLE_NAME] for node_id, node_info in node_table.items(): node_id = node_id.decode() if node_info is None: # Node has been removed from the store self.node_activity_status.pop(node_id) continue node_info = json.loads(node_info) # Add the self-signed node certificate (only available in 1.x, # refer to node endorsed certificates table otherwise) if "cert" in node_info: node_certs[node_id] = node_info["cert"].encode() self.node_certificates[node_id] = node_certs[node_id] # Update node trust status # Also record the seqno at which the node status changed to # track when a primary node should stop issuing signatures self.node_activity_status[node_id] = ( node_info["status"], transaction_public_domain.get_seqno(), ) if ENDORSED_NODE_CERTIFICATES_TABLE_NAME in tables: node_endorsed_certificates_tables = tables[ ENDORSED_NODE_CERTIFICATES_TABLE_NAME ] for ( node_id, endorsed_node_cert, ) in node_endorsed_certificates_tables.items(): node_id = node_id.decode() assert ( node_id not in node_certs ), f"Only one of node self-signed certificate and endorsed certificate should be recorded for node {node_id}" if endorsed_node_cert is None: # Node has been removed from the store self.node_certificates.pop(node_id) else: self.node_certificates[node_id] = endorsed_node_cert # This is a merkle root/signature tx if the table exists if SIGNATURE_TX_TABLE_NAME in tables: self.signature_count += 1 signature_table = tables[SIGNATURE_TX_TABLE_NAME] for _, signature in signature_table.items(): signature = json.loads(signature) current_seqno = signature["seqno"] current_view = signature["view"] signing_node = signature["node"] # Get binary representations for the cert, existing root, and signature cert = self.node_certificates[signing_node] existing_root = bytes.fromhex(signature["root"]) sig = base64.b64decode(signature["sig"]) tx_info = TxBundleInfo( self.merkle, existing_root, cert, sig, self.node_activity_status, signing_node, ) # validations for 1, 2 and 3 # throws if ledger validation failed. self._verify_tx_set(tx_info) self.last_verified_seqno = current_seqno self.last_verified_view = current_view # Checks complete, add this transaction to tree self.merkle.add_leaf(transaction.get_tx_digest(), False)
[ "def", "add_transaction", "(", "self", ",", "transaction", ")", ":", "transaction_public_domain", "=", "transaction", ".", "get_public_domain", "(", ")", "tables", "=", "transaction_public_domain", ".", "get_tables", "(", ")", "# Add contributing nodes certs and update no...
https://github.com/microsoft/CCF/blob/14801dc01f3f225fc85772eeb1c066d1b1b10a47/python/ccf/ledger.py#L356-L444
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/ipaddress.py
python
IPv4Address.packed
(self)
return v4_int_to_packed(self._ip)
The binary representation of this address.
The binary representation of this address.
[ "The", "binary", "representation", "of", "this", "address", "." ]
def packed(self): """The binary representation of this address.""" return v4_int_to_packed(self._ip)
[ "def", "packed", "(", "self", ")", ":", "return", "v4_int_to_packed", "(", "self", ".", "_ip", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ipaddress.py#L1310-L1312
google/skia
82d65d0487bd72f5f7332d002429ec2dc61d2463
infra/bots/zip_utils.py
python
unzip
(zip_file, target_dir)
Unzip the given zip file into the target dir.
Unzip the given zip file into the target dir.
[ "Unzip", "the", "given", "zip", "file", "into", "the", "target", "dir", "." ]
def unzip(zip_file, target_dir): """Unzip the given zip file into the target dir.""" if not os.path.isdir(target_dir): os.makedirs(target_dir) with zipfile.ZipFile(zip_file, 'r', zipfile.ZIP_DEFLATED, True) as z: for zi in z.infolist(): dst_subpath = zi.filename if os.name == 'nt': # Dumb path separator replacement for Windows. dst_subpath = dst_subpath.replace(posixpath.sep, ntpath.sep) dst_path = os.path.join(target_dir, dst_subpath) if dst_path.endswith(os.path.sep): os.mkdir(dst_path) else: with open(dst_path, 'wb') as f: f.write(z.read(zi)) perms = zi.external_attr >> 16 os.chmod(dst_path, perms)
[ "def", "unzip", "(", "zip_file", ",", "target_dir", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "target_dir", ")", ":", "os", ".", "makedirs", "(", "target_dir", ")", "with", "zipfile", ".", "ZipFile", "(", "zip_file", ",", "'r'", ",...
https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/infra/bots/zip_utils.py#L61-L78
wesnoth/wesnoth
6ccac5a5e8ff75303c9190c0da60580925cb32c0
data/tools/wesnoth/wmltools3.py
python
is_namespace
(name)
return name in map(os.path.basename, scopelist())
Is the name either a valid campaign name or core?
Is the name either a valid campaign name or core?
[ "Is", "the", "name", "either", "a", "valid", "campaign", "name", "or", "core?" ]
def is_namespace(name): "Is the name either a valid campaign name or core?" return name in map(os.path.basename, scopelist())
[ "def", "is_namespace", "(", "name", ")", ":", "return", "name", "in", "map", "(", "os", ".", "path", ".", "basename", ",", "scopelist", "(", ")", ")" ]
https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmltools3.py#L1075-L1077
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/estimator/export/export.py
python
build_parsing_serving_input_receiver_fn
(feature_spec, default_batch_size=None)
return serving_input_receiver_fn
Build a serving_input_receiver_fn expecting fed tf.Examples. Creates a serving_input_receiver_fn that expects a serialized tf.Example fed into a string placeholder. The function parses the tf.Example according to the provided feature_spec, and returns all parsed Tensors as features. Args: feature_spec: a dict of string to `VarLenFeature`/`FixedLenFeature`. default_batch_size: the number of query examples expected per batch. Leave unset for variable batch size (recommended). Returns: A serving_input_receiver_fn suitable for use in serving.
Build a serving_input_receiver_fn expecting fed tf.Examples.
[ "Build", "a", "serving_input_receiver_fn", "expecting", "fed", "tf", ".", "Examples", "." ]
def build_parsing_serving_input_receiver_fn(feature_spec, default_batch_size=None): """Build a serving_input_receiver_fn expecting fed tf.Examples. Creates a serving_input_receiver_fn that expects a serialized tf.Example fed into a string placeholder. The function parses the tf.Example according to the provided feature_spec, and returns all parsed Tensors as features. Args: feature_spec: a dict of string to `VarLenFeature`/`FixedLenFeature`. default_batch_size: the number of query examples expected per batch. Leave unset for variable batch size (recommended). Returns: A serving_input_receiver_fn suitable for use in serving. """ def serving_input_receiver_fn(): """An input_fn that expects a serialized tf.Example.""" serialized_tf_example = array_ops.placeholder(dtype=dtypes.string, shape=[default_batch_size], name='input_example_tensor') receiver_tensors = {'examples': serialized_tf_example} features = parsing_ops.parse_example(serialized_tf_example, feature_spec) return ServingInputReceiver(features, receiver_tensors) return serving_input_receiver_fn
[ "def", "build_parsing_serving_input_receiver_fn", "(", "feature_spec", ",", "default_batch_size", "=", "None", ")", ":", "def", "serving_input_receiver_fn", "(", ")", ":", "\"\"\"An input_fn that expects a serialized tf.Example.\"\"\"", "serialized_tf_example", "=", "array_ops", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/estimator/export/export.py#L121-L146
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py
python
Message._become_message
(self, message)
Assume the non-format-specific state of message.
Assume the non-format-specific state of message.
[ "Assume", "the", "non", "-", "format", "-", "specific", "state", "of", "message", "." ]
def _become_message(self, message): """Assume the non-format-specific state of message.""" for name in ('_headers', '_unixfrom', '_payload', '_charset', 'preamble', 'epilogue', 'defects', '_default_type'): self.__dict__[name] = message.__dict__[name]
[ "def", "_become_message", "(", "self", ",", "message", ")", ":", "for", "name", "in", "(", "'_headers'", ",", "'_unixfrom'", ",", "'_payload'", ",", "'_charset'", ",", "'preamble'", ",", "'epilogue'", ",", "'defects'", ",", "'_default_type'", ")", ":", "self...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/mailbox.py#L1457-L1461
baidu/bigflow
449245016c0df7d1252e85581e588bfc60cefad3
bigflow_python/python/bigflow/runtime/python_resource.py
python
Resource.files_list
(self)
return self.__files[:]
Returns a list containing all files added. Returns: list: added files
Returns a list containing all files added.
[ "Returns", "a", "list", "containing", "all", "files", "added", "." ]
def files_list(self): """ Returns a list containing all files added. Returns: list: added files """ return self.__files[:]
[ "def", "files_list", "(", "self", ")", ":", "return", "self", ".", "__files", "[", ":", "]" ]
https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/runtime/python_resource.py#L172-L179
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/system_info.py
python
system_info.combine_paths
(self, *args)
return combine_paths(*args, **{'verbosity': self.verbosity})
Return a list of existing paths composed by all combinations of items from the arguments.
Return a list of existing paths composed by all combinations of items from the arguments.
[ "Return", "a", "list", "of", "existing", "paths", "composed", "by", "all", "combinations", "of", "items", "from", "the", "arguments", "." ]
def combine_paths(self, *args): """Return a list of existing paths composed by all combinations of items from the arguments. """ return combine_paths(*args, **{'verbosity': self.verbosity})
[ "def", "combine_paths", "(", "self", ",", "*", "args", ")", ":", "return", "combine_paths", "(", "*", "args", ",", "*", "*", "{", "'verbosity'", ":", "self", ".", "verbosity", "}", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/system_info.py#L724-L728
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/writer.py
python
IndentedTextWriter.write_unindented_line
(self, msg)
Write an unindented line to the stream, no template formattin applied.
Write an unindented line to the stream, no template formattin applied.
[ "Write", "an", "unindented", "line", "to", "the", "stream", "no", "template", "formattin", "applied", "." ]
def write_unindented_line(self, msg): # type: (str) -> None """Write an unindented line to the stream, no template formattin applied.""" self._stream.write(msg) self._stream.write("\n")
[ "def", "write_unindented_line", "(", "self", ",", "msg", ")", ":", "# type: (str) -> None", "self", ".", "_stream", ".", "write", "(", "msg", ")", "self", ".", "_stream", ".", "write", "(", "\"\\n\"", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/writer.py#L111-L115
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/debug/lib/debug_data.py
python
DebugDumpDir._prune_non_control_edges_of_debug_ops
(self, device_name)
Prune (non-control) edges related to debug ops. Prune the Copy ops and associated _Send ops inserted by the debugger out from the non-control inputs and output recipients map. Replace the inputs and recipients with original ones. Args: device_name: (`str`) device name.
Prune (non-control) edges related to debug ops.
[ "Prune", "(", "non", "-", "control", ")", "edges", "related", "to", "debug", "ops", "." ]
def _prune_non_control_edges_of_debug_ops(self, device_name): """Prune (non-control) edges related to debug ops. Prune the Copy ops and associated _Send ops inserted by the debugger out from the non-control inputs and output recipients map. Replace the inputs and recipients with original ones. Args: device_name: (`str`) device name. """ copy_nodes = [] for node in self._node_inputs[device_name]: if node in self._copy_send_nodes[device_name]: continue if is_copy_node(node): copy_nodes.append(node) inputs = self._node_inputs[device_name][node] for i in xrange(len(inputs)): inp = inputs[i] if is_copy_node(inp): # Find the input to the Copy node, which should be the original # input to the node. orig_inp = self._node_inputs[device_name][inp][0] inputs[i] = orig_inp self._prune_nodes_from_input_and_recipient_maps(device_name, copy_nodes) self._prune_nodes_from_input_and_recipient_maps( device_name, self._copy_send_nodes[device_name])
[ "def", "_prune_non_control_edges_of_debug_ops", "(", "self", ",", "device_name", ")", ":", "copy_nodes", "=", "[", "]", "for", "node", "in", "self", ".", "_node_inputs", "[", "device_name", "]", ":", "if", "node", "in", "self", ".", "_copy_send_nodes", "[", ...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/lib/debug_data.py#L1106-L1137
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/fourcircle_utility.py
python
get_merge_pt_info_ws_name
(exp_no, scan_no)
return ws_name
Create the standard table workspace's name to contain the information to merge Pts. in a scan :param exp_no: :param scan_no: :return:
Create the standard table workspace's name to contain the information to merge Pts. in a scan :param exp_no: :param scan_no: :return:
[ "Create", "the", "standard", "table", "workspace", "s", "name", "to", "contain", "the", "information", "to", "merge", "Pts", ".", "in", "a", "scan", ":", "param", "exp_no", ":", ":", "param", "scan_no", ":", ":", "return", ":" ]
def get_merge_pt_info_ws_name(exp_no, scan_no): """ Create the standard table workspace's name to contain the information to merge Pts. in a scan :param exp_no: :param scan_no: :return: """ ws_name = 'ScanPtInfo_Exp%d_Scan%d' % (exp_no, scan_no) return ws_name
[ "def", "get_merge_pt_info_ws_name", "(", "exp_no", ",", "scan_no", ")", ":", "ws_name", "=", "'ScanPtInfo_Exp%d_Scan%d'", "%", "(", "exp_no", ",", "scan_no", ")", "return", "ws_name" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/fourcircle_utility.py#L607-L615
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
Fuzzbunch/fuzzbunch/command.py
python
FbCmd.parseline
(self, line)
return cmd, arg, line
Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if line couldn't be parsed. Check for registered special handlers.
Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if line couldn't be parsed. Check for registered special handlers.
[ "Parse", "the", "line", "into", "a", "command", "name", "and", "a", "string", "containing", "the", "arguments", ".", "Returns", "a", "tuple", "containing", "(", "command", "args", "line", ")", ".", "command", "and", "args", "may", "be", "None", "if", "li...
def parseline(self, line): """Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if line couldn't be parsed. Check for registered special handlers. """ line = line.strip() if not line: return None, None, line if line[-1:] in self.helpKeys: line = self.helpKeys[line[-1:]] + " " + line[:-1] if line[0] in self.shortcutKeys: line = self.shortcutKeys[line[0]] + " " + line[1:] i, n = 0, len(line) while i < n and line[i] in self.identchars: i = i+1 cmd, arg = line[:i], line[i:].strip() return cmd, arg, line
[ "def", "parseline", "(", "self", ",", "line", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", ":", "return", "None", ",", "None", ",", "line", "if", "line", "[", "-", "1", ":", "]", "in", "self", ".", "helpKeys", ":"...
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/command.py#L238-L258
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/lmbr_aws/cleanup_utils/cleanup_iam_utils.py
python
_delete_access_keys
(cleaner, iam_user_name)
Deletes all access keys from the client. It will construct a list of resources, delete them, then wait for each deletion. :param cleaner: A Cleaner object from the main cleanup.py script :param iam_user_name: The iam user name to be cleaned :return: None
Deletes all access keys from the client. It will construct a list of resources, delete them, then wait for each deletion. :param cleaner: A Cleaner object from the main cleanup.py script :param iam_user_name: The iam user name to be cleaned :return: None
[ "Deletes", "all", "access", "keys", "from", "the", "client", ".", "It", "will", "construct", "a", "list", "of", "resources", "delete", "them", "then", "wait", "for", "each", "deletion", ".", ":", "param", "cleaner", ":", "A", "Cleaner", "object", "from", ...
def _delete_access_keys(cleaner, iam_user_name): """ Deletes all access keys from the client. It will construct a list of resources, delete them, then wait for each deletion. :param cleaner: A Cleaner object from the main cleanup.py script :param iam_user_name: The iam user name to be cleaned :return: None """ print('\n\nlooking for access keys with names starting with one of {0}'.format(cleaner.describe_prefixes())) iam_access_key_id_list = [] # Construct list try: iam_access_key_paginator = cleaner.iam.get_paginator('list_access_keys') iam_access_key_page_iterator = iam_access_key_paginator.paginate(UserName=iam_user_name) for page in iam_access_key_page_iterator: for iam_access_key_info in page['AccessKeyMetadata']: iam_access_key_id_list.append(iam_access_key_info['AccessKeyId']) except KeyError as e: print(" ERROR: Unexpected KeyError while deleting access keys. {}".format(exception_utils.message(e))) return except ClientError as e: print(" ERROR: Unexpected error for paginator for the iam client. {}".format(exception_utils.message(e))) return # delete access keys for access_key_id in iam_access_key_id_list: print(' deleting access key {}'.format(access_key_id)) try: cleaner.iam.delete_access_key(UserName=iam_user_name, AccessKeyId=access_key_id) except ClientError as e: if e.response["Error"]["Code"] == "TooManyRequestsException": print(' too many requests, sleeping...') time.sleep(cleaner.wait_interval) else: print(' ERROR: Failed to delete access key {0} due to {1}'.format(access_key_id, exception_utils.message(e))) cleaner.add_to_failed_resources("iam", access_key_id) # Wait for deletion for access_key_id in iam_access_key_id_list: try: cleanup_utils.wait_for(lambda: not __access_key_exists(cleaner, iam_user_name, access_key_id), attempts=cleaner.wait_attempts, interval=cleaner.wait_interval, timeout_exception=cleanup_utils.WaitError) except cleanup_utils.WaitError: print(' ERROR. access key {0} was not deleted after timeout'.format(access_key_id)) cleaner.add_to_failed_resources("iam", access_key_id) except ClientError as e: if e.response["Error"]["Code"] == "TooManyRequestsException": print(' too many requests, sleeping...') time.sleep(cleaner.wait_interval) else: print(" ERROR: Unexpected error occurred waiting for access key {0} to delete due to {1}" .format(access_key_id, exception_utils.message(e))) cleaner.add_to_failed_resources("iam", access_key_id)
[ "def", "_delete_access_keys", "(", "cleaner", ",", "iam_user_name", ")", ":", "print", "(", "'\\n\\nlooking for access keys with names starting with one of {0}'", ".", "format", "(", "cleaner", ".", "describe_prefixes", "(", ")", ")", ")", "iam_access_key_id_list", "=", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/lmbr_aws/cleanup_utils/cleanup_iam_utils.py#L530-L587
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBLaunchInfo.GetUserID
(self)
return _lldb.SBLaunchInfo_GetUserID(self)
GetUserID(self) -> uint32_t
GetUserID(self) -> uint32_t
[ "GetUserID", "(", "self", ")", "-", ">", "uint32_t" ]
def GetUserID(self): """GetUserID(self) -> uint32_t""" return _lldb.SBLaunchInfo_GetUserID(self)
[ "def", "GetUserID", "(", "self", ")", ":", "return", "_lldb", ".", "SBLaunchInfo_GetUserID", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L5425-L5427
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Window_GetClassDefaultAttributes
(*args, **kwargs)
return _core_.Window_GetClassDefaultAttributes(*args, **kwargs)
Window_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this.
Window_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "Window_GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def Window_GetClassDefaultAttributes(*args, **kwargs): """ Window_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _core_.Window_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "Window_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L11764-L11779
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/config_key.py
python
GetKeysDialog.set_modifiers_for_platform
(self)
Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys; it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering.
Determine list of names of key modifiers for this platform.
[ "Determine", "list", "of", "names", "of", "key", "modifiers", "for", "this", "platform", "." ]
def set_modifiers_for_platform(self): """Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys; it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering. """ if sys.platform == "darwin": self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'}
[ "def", "set_modifiers_for_platform", "(", "self", ")", ":", "if", "sys", ".", "platform", "==", "\"darwin\"", ":", "self", ".", "modifiers", "=", "[", "'Shift'", ",", "'Control'", ",", "'Option'", ",", "'Command'", "]", "else", ":", "self", ".", "modifiers...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/config_key.py#L202-L214
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mailcap.py
python
parsefield
(line, i, n)
return line[start:i].strip(), i
Separate one key-value pair in a mailcap entry.
Separate one key-value pair in a mailcap entry.
[ "Separate", "one", "key", "-", "value", "pair", "in", "a", "mailcap", "entry", "." ]
def parsefield(line, i, n): """Separate one key-value pair in a mailcap entry.""" start = i while i < n: c = line[i] if c == ';': break elif c == '\\': i = i+2 else: i = i+1 return line[start:i].strip(), i
[ "def", "parsefield", "(", "line", ",", "i", ",", "n", ")", ":", "start", "=", "i", "while", "i", "<", "n", ":", "c", "=", "line", "[", "i", "]", "if", "c", "==", "';'", ":", "break", "elif", "c", "==", "'\\\\'", ":", "i", "=", "i", "+", "...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mailcap.py#L122-L133
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/resmokelib/selector.py
python
_TestList.include_any_pattern
(self, patterns)
Filters the test list to only include tests that match any of the given glob patterns.
Filters the test list to only include tests that match any of the given glob patterns.
[ "Filters", "the", "test", "list", "to", "only", "include", "tests", "that", "match", "any", "of", "the", "given", "glob", "patterns", "." ]
def include_any_pattern(self, patterns): """ Filters the test list to only include tests that match any of the given glob patterns. """ def match(test): for pattern in patterns: if test == pattern or fnmatch.fnmatchcase(test, pattern): return True return False self._filtered = {test for test in self._filtered if match(test)}
[ "def", "include_any_pattern", "(", "self", ",", "patterns", ")", ":", "def", "match", "(", "test", ")", ":", "for", "pattern", "in", "patterns", ":", "if", "test", "==", "pattern", "or", "fnmatch", ".", "fnmatchcase", "(", "test", ",", "pattern", ")", ...
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/resmokelib/selector.py#L214-L224
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/graph_editor/util.py
python
get_predefined_collection_names
()
return [getattr(tf_ops.GraphKeys, key) for key in dir(tf_ops.GraphKeys) if not _INTERNAL_VARIABLE_RE.match(key)]
Return all the predefined collection names.
Return all the predefined collection names.
[ "Return", "all", "the", "predefined", "collection", "names", "." ]
def get_predefined_collection_names(): """Return all the predefined collection names.""" return [getattr(tf_ops.GraphKeys, key) for key in dir(tf_ops.GraphKeys) if not _INTERNAL_VARIABLE_RE.match(key)]
[ "def", "get_predefined_collection_names", "(", ")", ":", "return", "[", "getattr", "(", "tf_ops", ".", "GraphKeys", ",", "key", ")", "for", "key", "in", "dir", "(", "tf_ops", ".", "GraphKeys", ")", "if", "not", "_INTERNAL_VARIABLE_RE", ".", "match", "(", "...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/graph_editor/util.py#L485-L488
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/_vendor/six.py
python
_import_module
(name)
return sys.modules[name]
Import module, returning the module after the last dot.
Import module, returning the module after the last dot.
[ "Import", "module", "returning", "the", "module", "after", "the", "last", "dot", "." ]
def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
[ "def", "_import_module", "(", "name", ")", ":", "__import__", "(", "name", ")", "return", "sys", ".", "modules", "[", "name", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/_vendor/six.py#L80-L83
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/types.py
python
Type._get_ll_pointer_type
(self, target_data, context=None)
Convert this type object to an LLVM type.
Convert this type object to an LLVM type.
[ "Convert", "this", "type", "object", "to", "an", "LLVM", "type", "." ]
def _get_ll_pointer_type(self, target_data, context=None): """ Convert this type object to an LLVM type. """ from . import Module, GlobalVariable from ..binding import parse_assembly if context is None: m = Module() else: m = Module(context=context) foo = GlobalVariable(m, self, name="foo") with parse_assembly(str(m)) as llmod: return llmod.get_global_variable(foo.name).type
[ "def", "_get_ll_pointer_type", "(", "self", ",", "target_data", ",", "context", "=", "None", ")", ":", "from", ".", "import", "Module", ",", "GlobalVariable", "from", ".", ".", "binding", "import", "parse_assembly", "if", "context", "is", "None", ":", "m", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/ir/types.py#L35-L48
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/py/sliceshell.py
python
SlicesShellFrame.OnEnableShellMode
(self,event)
Change between Slices Mode and Shell Mode
Change between Slices Mode and Shell Mode
[ "Change", "between", "Slices", "Mode", "and", "Shell", "Mode" ]
def OnEnableShellMode(self,event): """Change between Slices Mode and Shell Mode""" frame.Frame.OnEnableShellMode(self,event) self.sliceshell.ToggleShellMode(self.enableShellMode)
[ "def", "OnEnableShellMode", "(", "self", ",", "event", ")", ":", "frame", ".", "Frame", ".", "OnEnableShellMode", "(", "self", ",", "event", ")", "self", ".", "sliceshell", ".", "ToggleShellMode", "(", "self", ".", "enableShellMode", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/sliceshell.py#L240-L243
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
demo/BERT/squad/evaluate-v2.0.py
python
normalize_answer
(s)
return white_space_fix(remove_articles(remove_punc(lower(s))))
Lower text and remove punctuation, articles and extra whitespace.
Lower text and remove punctuation, articles and extra whitespace.
[ "Lower", "text", "and", "remove", "punctuation", "articles", "and", "extra", "whitespace", "." ]
def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): regex = re.compile(r'\b(a|an|the)\b', re.UNICODE) return re.sub(regex, ' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): exclude = set(string.punctuation) return ''.join(ch for ch in text if ch not in exclude) def lower(text): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(s))))
[ "def", "normalize_answer", "(", "s", ")", ":", "def", "remove_articles", "(", "text", ")", ":", "regex", "=", "re", ".", "compile", "(", "r'\\b(a|an|the)\\b'", ",", "re", ".", "UNICODE", ")", "return", "re", ".", "sub", "(", "regex", ",", "' '", ",", ...
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/demo/BERT/squad/evaluate-v2.0.py#L64-L76
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Platform/virtualenv.py
python
_is_path_in
(path, base)
return (not rp.startswith(os.path.pardir)) and (not rp == os.path.curdir)
Returns true if **path** is located under the **base** directory.
Returns true if **path** is located under the **base** directory.
[ "Returns", "true", "if", "**", "path", "**", "is", "located", "under", "the", "**", "base", "**", "directory", "." ]
def _is_path_in(path, base): """Returns true if **path** is located under the **base** directory.""" if not path or not base: # empty path may happen, base too return False rp = os.path.relpath(path, base) return (not rp.startswith(os.path.pardir)) and (not rp == os.path.curdir)
[ "def", "_is_path_in", "(", "path", ",", "base", ")", ":", "if", "not", "path", "or", "not", "base", ":", "# empty path may happen, base too", "return", "False", "rp", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "base", ")", "return", "(", ...
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Platform/virtualenv.py#L54-L59
vtraag/leidenalg
b53366829360e10922a2dbf57eb405a516c23bc9
src/leidenalg/VertexPartition.py
python
MutableVertexPartition.weight_to_comm
(self, v, comm)
return _c_leiden._MutableVertexPartition_weight_to_comm(self._partition, v, comm)
The total number of edges (or sum of weights) from node ``v`` to community ``comm``. See Also -------- :func:`~VertexPartition.MutableVertexPartition.weight_from_comm`
The total number of edges (or sum of weights) from node ``v`` to community ``comm``.
[ "The", "total", "number", "of", "edges", "(", "or", "sum", "of", "weights", ")", "from", "node", "v", "to", "community", "comm", "." ]
def weight_to_comm(self, v, comm): """ The total number of edges (or sum of weights) from node ``v`` to community ``comm``. See Also -------- :func:`~VertexPartition.MutableVertexPartition.weight_from_comm` """ return _c_leiden._MutableVertexPartition_weight_to_comm(self._partition, v, comm)
[ "def", "weight_to_comm", "(", "self", ",", "v", ",", "comm", ")", ":", "return", "_c_leiden", ".", "_MutableVertexPartition_weight_to_comm", "(", "self", ".", "_partition", ",", "v", ",", "comm", ")" ]
https://github.com/vtraag/leidenalg/blob/b53366829360e10922a2dbf57eb405a516c23bc9/src/leidenalg/VertexPartition.py#L364-L372
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/summary/event_file_inspector.py
python
get_field_to_observations_map
(generator, query_for_tag='')
return field_to_obs
Return a field to `Observations` dict for the event generator. Args: generator: A generator over event protos. query_for_tag: A string that if specified, only create observations for events with this tag name. Returns: A dict mapping keys in `TRACKED_FIELDS` to an `Observation` list.
Return a field to `Observations` dict for the event generator.
[ "Return", "a", "field", "to", "Observations", "dict", "for", "the", "event", "generator", "." ]
def get_field_to_observations_map(generator, query_for_tag=''): """Return a field to `Observations` dict for the event generator. Args: generator: A generator over event protos. query_for_tag: A string that if specified, only create observations for events with this tag name. Returns: A dict mapping keys in `TRACKED_FIELDS` to an `Observation` list. """ def increment(stat, event, tag=''): assert stat in TRACKED_FIELDS field_to_obs[stat].append(Observation(step=event.step, wall_time=event.wall_time, tag=tag)._asdict()) field_to_obs = dict([(t, []) for t in TRACKED_FIELDS]) for event in generator: ## Process the event if event.HasField('graph_def') and (not query_for_tag): increment('graph', event) if event.HasField('session_log') and (not query_for_tag): status = event.session_log.status if status == SessionLog.START: increment('sessionlog:start', event) elif status == SessionLog.STOP: increment('sessionlog:stop', event) elif status == SessionLog.CHECKPOINT: increment('sessionlog:checkpoint', event) elif event.HasField('summary'): for value in event.summary.value: if query_for_tag and value.tag != query_for_tag: continue for proto_name, display_name in SUMMARY_TYPE_TO_FIELD.items(): if value.HasField(proto_name): increment(display_name, event, value.tag) return field_to_obs
[ "def", "get_field_to_observations_map", "(", "generator", ",", "query_for_tag", "=", "''", ")", ":", "def", "increment", "(", "stat", ",", "event", ",", "tag", "=", "''", ")", ":", "assert", "stat", "in", "TRACKED_FIELDS", "field_to_obs", "[", "stat", "]", ...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/summary/event_file_inspector.py#L172-L212
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/google/protobuf/internal/containers.py
python
RepeatedCompositeFieldContainer.remove
(self, elem)
Removes an item from the list. Similar to list.remove().
Removes an item from the list. Similar to list.remove().
[ "Removes", "an", "item", "from", "the", "list", ".", "Similar", "to", "list", ".", "remove", "()", "." ]
def remove(self, elem): """Removes an item from the list. Similar to list.remove().""" self._values.remove(elem) self._message_listener.Modified()
[ "def", "remove", "(", "self", ",", "elem", ")", ":", "self", ".", "_values", ".", "remove", "(", "elem", ")", "self", ".", "_message_listener", ".", "Modified", "(", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/internal/containers.py#L399-L402
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_inductionloop.py
python
InductionLoopDomain.getLastStepVehicleNumber
(self, loopID)
return self._getUniversal(tc.LAST_STEP_VEHICLE_NUMBER, loopID)
getLastStepVehicleNumber(string) -> integer Returns the number of vehicles that were on the named induction loop within the last simulation step.
getLastStepVehicleNumber(string) -> integer
[ "getLastStepVehicleNumber", "(", "string", ")", "-", ">", "integer" ]
def getLastStepVehicleNumber(self, loopID): """getLastStepVehicleNumber(string) -> integer Returns the number of vehicles that were on the named induction loop within the last simulation step. """ return self._getUniversal(tc.LAST_STEP_VEHICLE_NUMBER, loopID)
[ "def", "getLastStepVehicleNumber", "(", "self", ",", "loopID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "LAST_STEP_VEHICLE_NUMBER", ",", "loopID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_inductionloop.py#L64-L69
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
linked_list/library/linked_list.py
python
Node.set_data
(self, new_data)
replace the existing value of the self.data attribute with new_data parameter
replace the existing value of the self.data attribute with new_data parameter
[ "replace", "the", "existing", "value", "of", "the", "self", ".", "data", "attribute", "with", "new_data", "parameter" ]
def set_data(self, new_data): """ replace the existing value of the self.data attribute with new_data parameter """ self.data = new_data
[ "def", "set_data", "(", "self", ",", "new_data", ")", ":", "self", ".", "data", "=", "new_data" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/linked_list/library/linked_list.py#L19-L23
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PGTextCtrlEditor_OnTextCtrlEvent
(*args, **kwargs)
return _propgrid.PGTextCtrlEditor_OnTextCtrlEvent(*args, **kwargs)
PGTextCtrlEditor_OnTextCtrlEvent(PropertyGrid propgrid, PGProperty property, Window ctrl, Event event) -> bool
PGTextCtrlEditor_OnTextCtrlEvent(PropertyGrid propgrid, PGProperty property, Window ctrl, Event event) -> bool
[ "PGTextCtrlEditor_OnTextCtrlEvent", "(", "PropertyGrid", "propgrid", "PGProperty", "property", "Window", "ctrl", "Event", "event", ")", "-", ">", "bool" ]
def PGTextCtrlEditor_OnTextCtrlEvent(*args, **kwargs): """ PGTextCtrlEditor_OnTextCtrlEvent(PropertyGrid propgrid, PGProperty property, Window ctrl, Event event) -> bool """ return _propgrid.PGTextCtrlEditor_OnTextCtrlEvent(*args, **kwargs)
[ "def", "PGTextCtrlEditor_OnTextCtrlEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGTextCtrlEditor_OnTextCtrlEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L2744-L2749
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/response.py
python
StreamingBody.set_socket_timeout
(self, timeout)
Set the timeout seconds on the socket.
Set the timeout seconds on the socket.
[ "Set", "the", "timeout", "seconds", "on", "the", "socket", "." ]
def set_socket_timeout(self, timeout): """Set the timeout seconds on the socket.""" # The problem we're trying to solve is to prevent .read() calls from # hanging. This can happen in rare cases. What we'd like to ideally # do is set a timeout on the .read() call so that callers can retry # the request. # Unfortunately, this isn't currently possible in requests. # See: https://github.com/kennethreitz/requests/issues/1803 # So what we're going to do is reach into the guts of the stream and # grab the socket object, which we can set the timeout on. We're # putting in a check here so in case this interface goes away, we'll # know. try: # To further complicate things, the way to grab the # underlying socket object from an HTTPResponse is different # in py2 and py3. So this code has been pushed to botocore.compat. set_socket_timeout(self._raw_stream, timeout) except AttributeError: logger.error("Cannot access the socket object of " "a streaming response. It's possible " "the interface has changed.", exc_info=True) raise
[ "def", "set_socket_timeout", "(", "self", ",", "timeout", ")", ":", "# The problem we're trying to solve is to prevent .read() calls from", "# hanging. This can happen in rare cases. What we'd like to ideally", "# do is set a timeout on the .read() call so that callers can retry", "# the req...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/response.py#L46-L67
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/telnetlib.py
python
Telnet.mt_interact
(self)
Multithreaded version of interact().
Multithreaded version of interact().
[ "Multithreaded", "version", "of", "interact", "()", "." ]
def mt_interact(self): """Multithreaded version of interact().""" import thread thread.start_new_thread(self.listener, ()) while 1: line = sys.stdin.readline() if not line: break self.write(line)
[ "def", "mt_interact", "(", "self", ")", ":", "import", "thread", "thread", ".", "start_new_thread", "(", "self", ".", "listener", ",", "(", ")", ")", "while", "1", ":", "line", "=", "sys", ".", "stdin", ".", "readline", "(", ")", "if", "not", "line",...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/telnetlib.py#L604-L612
ChilliWorks/ChilliSource
1f482f1e84c1402b7ded7130d9ff9d114b4a458d
Tools/Scripts/ninja_syntax.py
python
Writer._line
(self, text, indent=0)
Write 'text' word-wrapped at self.width characters.
Write 'text' word-wrapped at self.width characters.
[ "Write", "text", "word", "-", "wrapped", "at", "self", ".", "width", "characters", "." ]
def _line(self, text, indent=0): """Write 'text' word-wrapped at self.width characters.""" leading_space = ' ' * indent while len(leading_space) + len(text) > self.width: # The text is too wide; wrap if possible. # Find the rightmost space that would obey our width constraint and # that's not an escaped space. available_space = self.width - len(leading_space) - len(' $') space = available_space while True: space = text.rfind(' ', 0, space) if space < 0 or \ self._count_dollars_before_index(text, space) % 2 == 0: break if space < 0: # No such space; just use the first unescaped space we can find. space = available_space - 1 while True: space = text.find(' ', space + 1) if space < 0 or \ self._count_dollars_before_index(text, space) % 2 == 0: break if space < 0: # Give up on breaking. break self.output.write(leading_space + text[0:space] + ' $\n') text = text[space+1:] # Subsequent lines are continuations, so indent them. leading_space = ' ' * (indent+2) self.output.write(leading_space + text + '\n')
[ "def", "_line", "(", "self", ",", "text", ",", "indent", "=", "0", ")", ":", "leading_space", "=", "' '", "*", "indent", "while", "len", "(", "leading_space", ")", "+", "len", "(", "text", ")", ">", "self", ".", "width", ":", "# The text is too wide; ...
https://github.com/ChilliWorks/ChilliSource/blob/1f482f1e84c1402b7ded7130d9ff9d114b4a458d/Tools/Scripts/ninja_syntax.py#L109-L143
Cantera/cantera
0119484b261967ccb55a0066c020599cacc312e4
interfaces/cython/cantera/onedim.py
python
FlameBase.set_profile
(self, component, positions, values)
Set an initial estimate for a profile of one component. :param component: component name or index :param positions: sequence of relative positions, from 0 on the left to 1 on the right :param values: sequence of values at the relative positions specified in *positions* >>> f.set_profile('T', [0.0, 0.2, 1.0], [400.0, 800.0, 1500.0])
Set an initial estimate for a profile of one component.
[ "Set", "an", "initial", "estimate", "for", "a", "profile", "of", "one", "component", "." ]
def set_profile(self, component, positions, values): """ Set an initial estimate for a profile of one component. :param component: component name or index :param positions: sequence of relative positions, from 0 on the left to 1 on the right :param values: sequence of values at the relative positions specified in *positions* >>> f.set_profile('T', [0.0, 0.2, 1.0], [400.0, 800.0, 1500.0]) """ super().set_profile(self.flame, component, positions, values)
[ "def", "set_profile", "(", "self", ",", "component", ",", "positions", ",", "values", ")", ":", "super", "(", ")", ".", "set_profile", "(", "self", ".", "flame", ",", "component", ",", "positions", ",", "values", ")" ]
https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/onedim.py#L184-L197
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/engine/validators.py
python
check_imdb_dataset
(method)
return new_method
A wrapper that wraps a parameter checker around the original IMDBDataset.
A wrapper that wraps a parameter checker around the original IMDBDataset.
[ "A", "wrapper", "that", "wraps", "a", "parameter", "checker", "around", "the", "original", "IMDBDataset", "." ]
def check_imdb_dataset(method): """A wrapper that wraps a parameter checker around the original IMDBDataset.""" @wraps(method) def new_method(self, *args, **kwargs): _, param_dict = parse_user_args(method, *args, **kwargs) nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shards', 'shard_id'] nreq_param_bool = ['shuffle'] dataset_dir = param_dict.get('dataset_dir') check_dir(dataset_dir) validate_dataset_param_value(nreq_param_int, param_dict, int) validate_dataset_param_value(nreq_param_bool, param_dict, bool) check_sampler_shuffle_shard_options(param_dict) cache = param_dict.get('cache') check_cache_option(cache) usage = param_dict.get('usage') if usage is not None: check_valid_str(usage, ["train", "test", "all"], "usage") return method(self, *args, **kwargs) return new_method
[ "def", "check_imdb_dataset", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "new_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_", ",", "param_dict", "=", "parse_user_args", "(", "method", ",", "*", "a...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/validators.py#L66-L92
GJDuck/LowFat
ecf6a0f0fa1b73a27a626cf493cc39e477b6faea
llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py
python
TranslationUnit.spelling
(self)
return conf.lib.clang_getTranslationUnitSpelling(self)
Get the original translation unit source file name.
Get the original translation unit source file name.
[ "Get", "the", "original", "translation", "unit", "source", "file", "name", "." ]
def spelling(self): """Get the original translation unit source file name.""" return conf.lib.clang_getTranslationUnitSpelling(self)
[ "def", "spelling", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getTranslationUnitSpelling", "(", "self", ")" ]
https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py#L2607-L2609
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/deephol/holparam_predictor.py
python
recommend_from_scores
(scores: List[List[float]], n: int)
return [top_idx(s) for s in scores]
Return the index of the top n predicted scores. Args: scores: A list of tactic probabilities, each of length equal to the number of tactics. n: The number of recommendations requested. Returns: A list of the indices with the highest scores.
Return the index of the top n predicted scores.
[ "Return", "the", "index", "of", "the", "top", "n", "predicted", "scores", "." ]
def recommend_from_scores(scores: List[List[float]], n: int) -> List[List[int]]: """Return the index of the top n predicted scores. Args: scores: A list of tactic probabilities, each of length equal to the number of tactics. n: The number of recommendations requested. Returns: A list of the indices with the highest scores. """ def top_idx(scores): return np.array(scores).argsort()[::-1][:n] return [top_idx(s) for s in scores]
[ "def", "recommend_from_scores", "(", "scores", ":", "List", "[", "List", "[", "float", "]", "]", ",", "n", ":", "int", ")", "->", "List", "[", "List", "[", "int", "]", "]", ":", "def", "top_idx", "(", "scores", ")", ":", "return", "np", ".", "arr...
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/deephol/holparam_predictor.py#L25-L40
RegrowthStudios/SoACode-Public
c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe
utils/git-hooks/pep8.py
python
Checker.check_logical
(self)
Build a line from tokens and run all logical checks on it.
Build a line from tokens and run all logical checks on it.
[ "Build", "a", "line", "from", "tokens", "and", "run", "all", "logical", "checks", "on", "it", "." ]
def check_logical(self): """ Build a line from tokens and run all logical checks on it. """ self.build_tokens_line() self.report.increment_logical_line() first_line = self.lines[self.mapping[0][1][2][0] - 1] indent = first_line[:self.mapping[0][1][2][1]] self.previous_indent_level = self.indent_level self.indent_level = expand_indent(indent) if self.verbose >= 2: print(self.logical_line[:80].rstrip()) for name, check, argument_names in self._logical_checks: if self.verbose >= 4: print(' ' + name) for result in self.run_check(check, argument_names): offset, text = result if isinstance(offset, tuple): orig_number, orig_offset = offset else: for token_offset, token in self.mapping: if offset >= token_offset: orig_number = token[2][0] orig_offset = (token[2][1] + offset - token_offset) self.report_error(orig_number, orig_offset, text, check) self.previous_logical = self.logical_line
[ "def", "check_logical", "(", "self", ")", ":", "self", ".", "build_tokens_line", "(", ")", "self", ".", "report", ".", "increment_logical_line", "(", ")", "first_line", "=", "self", ".", "lines", "[", "self", ".", "mapping", "[", "0", "]", "[", "1", "]...
https://github.com/RegrowthStudios/SoACode-Public/blob/c3ddd69355b534d5e70e2e6d0c489b4e93ab1ffe/utils/git-hooks/pep8.py#L1312-L1337
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/api/trade_api.py
python
TradeApi.trade_get_bucketed_with_http_info
(self, **kwargs)
return self.api_client.call_api( '/trade/bucketed', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[TradeBin]', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
Get previous trades in time buckets. # noqa: E501 Timestamps returned by our bucketed endpoints are the **end** of the period, indicating when the bucket was written to disk. Some other common systems use the timestamp as the beginning of the period. Please be aware of this when using this endpoint. Also note the `open` price is equal to the `close` price of the previous timeframe bucket. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.trade_get_bucketed_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :param str bin_size: Time interval to bucket by. Available options: [1m,5m,1h,1d]. :param bool partial: If true, will send in-progress (incomplete) bins for the current time period. :param str symbol: Instrument symbol. Send a bare series (e.g. XBT) to get data for the nearest expiring contract in that series. You can also send a timeframe, e.g. `XBT:quarterly`. Timeframes are `nearest`, `daily`, `weekly`, `monthly`, `quarterly`, `biquarterly`, and `perpetual`. :param str filter: Generic table filter. Send JSON key/value pairs, such as `{\"key\": \"value\"}`. You can key on individual fields, and do more advanced querying on timestamps. See the [Timestamp Docs](https://www.bitmex.com/app/restAPI#Timestamp-Filters) for more details. :param str columns: Array of column names to fetch. If omitted, will return all columns. Note that this method will always return item keys, even when not specified, so you may receive more columns that you expect. :param float count: Number of results to fetch. :param float start: Starting point for results. :param bool reverse: If true, will sort results newest first. :param datetime start_time: Starting date filter for results. :param datetime end_time: Ending date filter for results. :return: list[TradeBin] If the method is called asynchronously, returns the request thread.
Get previous trades in time buckets. # noqa: E501
[ "Get", "previous", "trades", "in", "time", "buckets", ".", "#", "noqa", ":", "E501" ]
def trade_get_bucketed_with_http_info(self, **kwargs): # noqa: E501 """Get previous trades in time buckets. # noqa: E501 Timestamps returned by our bucketed endpoints are the **end** of the period, indicating when the bucket was written to disk. Some other common systems use the timestamp as the beginning of the period. Please be aware of this when using this endpoint. Also note the `open` price is equal to the `close` price of the previous timeframe bucket. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.trade_get_bucketed_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :param str bin_size: Time interval to bucket by. Available options: [1m,5m,1h,1d]. :param bool partial: If true, will send in-progress (incomplete) bins for the current time period. :param str symbol: Instrument symbol. Send a bare series (e.g. XBT) to get data for the nearest expiring contract in that series. You can also send a timeframe, e.g. `XBT:quarterly`. Timeframes are `nearest`, `daily`, `weekly`, `monthly`, `quarterly`, `biquarterly`, and `perpetual`. :param str filter: Generic table filter. Send JSON key/value pairs, such as `{\"key\": \"value\"}`. You can key on individual fields, and do more advanced querying on timestamps. See the [Timestamp Docs](https://www.bitmex.com/app/restAPI#Timestamp-Filters) for more details. :param str columns: Array of column names to fetch. If omitted, will return all columns. Note that this method will always return item keys, even when not specified, so you may receive more columns that you expect. :param float count: Number of results to fetch. :param float start: Starting point for results. :param bool reverse: If true, will sort results newest first. :param datetime start_time: Starting date filter for results. :param datetime end_time: Ending date filter for results. :return: list[TradeBin] If the method is called asynchronously, returns the request thread. """ all_params = ['bin_size', 'partial', 'symbol', 'filter', 'columns', 'count', 'start', 'reverse', 'start_time', 'end_time'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method trade_get_bucketed" % key ) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'bin_size' in params: query_params.append(('binSize', params['bin_size'])) # noqa: E501 if 'partial' in params: query_params.append(('partial', params['partial'])) # noqa: E501 if 'symbol' in params: query_params.append(('symbol', params['symbol'])) # noqa: E501 if 'filter' in params: query_params.append(('filter', params['filter'])) # noqa: E501 if 'columns' in params: query_params.append(('columns', params['columns'])) # noqa: E501 if 'count' in params: query_params.append(('count', params['count'])) # noqa: E501 if 'start' in params: query_params.append(('start', params['start'])) # noqa: E501 if 'reverse' in params: query_params.append(('reverse', params['reverse'])) # noqa: E501 if 'start_time' in params: query_params.append(('startTime', params['start_time'])) # noqa: E501 if 'end_time' in params: query_params.append(('endTime', params['end_time'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json', 'application/x-www-form-urlencoded']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/trade/bucketed', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='list[TradeBin]', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
[ "def", "trade_get_bucketed_with_http_info", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "all_params", "=", "[", "'bin_size'", ",", "'partial'", ",", "'symbol'", ",", "'filter'", ",", "'columns'", ",", "'count'", ",", "'start'", ",", "'rever...
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/api/trade_api.py#L190-L288
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/configuration.py
python
Configuration.load
(self)
Loads configuration from configuration files and environment
Loads configuration from configuration files and environment
[ "Loads", "configuration", "from", "configuration", "files", "and", "environment" ]
def load(self): # type: () -> None """Loads configuration from configuration files and environment """ self._load_config_files() if not self.isolated: self._load_environment_vars()
[ "def", "load", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_load_config_files", "(", ")", "if", "not", "self", ".", "isolated", ":", "self", ".", "_load_environment_vars", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/configuration.py#L133-L139
cvmfs/cvmfs
4637bdb5153178eadf885c1acf37bdc5c685bf8a
cpplint.py
python
CheckForIncludeWhatYouUse
(filename, clean_lines, include_state, error, io=codecs)
Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection.
Reports for missing stl includes.
[ "Reports", "for", "missing", "stl", "includes", "." ]
def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection. """ required = {} # A map of header name to linenumber and the template entity. # Example of required: { '<functional>': (1219, 'less<>') } for linenum in xrange(clean_lines.NumLines()): line = clean_lines.elided[linenum] if not line or line[0] == '#': continue # String is special -- it is a non-templatized type in STL. matched = _RE_PATTERN_STRING.search(line) if matched: # Don't warn about strings in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required['<string>'] = (linenum, 'string') for pattern, template, header in _re_pattern_algorithm_header: if pattern.search(line): required[header] = (linenum, template) # The following function is just a speed up, no semantics are changed. if not '<' in line: # Reduces the cpu time usage by skipping lines. continue for pattern, template, header in _re_pattern_templates: if pattern.search(line): required[header] = (linenum, template) # The policy is that if you #include something in foo.h you don't need to # include it again in foo.cc. Here, we will look at possible includes. # Let's flatten the include_state include_list and copy it into a dictionary. include_dict = dict([item for sublist in include_state.include_list for item in sublist]) # Did we find the header for this file (if any) and successfully load it? header_found = False # Use the absolute path so that matching works properly. abs_filename = FileInfo(filename).FullName() # For Emacs's flymake. # If cpplint is invoked from Emacs's flymake, a temporary file is generated # by flymake and that file name might end with '_flymake.cc'. In that case, # restore original file name here so that the corresponding header file can be # found. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' # instead of 'foo_flymake.h' abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) # include_dict is modified during iteration, so we iterate over a copy of # the keys. header_keys = include_dict.keys() for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header if same_module and UpdateIncludeState(fullpath, include_dict, io): header_found = True # If we can't find the header file for a .cc, assume it's because we don't # know where to look. In that case we'll give up as we're not sure they # didn't include it in the .h file. # TODO(unknown): Do a better job of finding .h files so we are confident that # not having the .h file means there isn't one. if filename.endswith('.cc') and not header_found: return # All the lines have been processed, report the errors found. for required_header_unstripped in required: template = required[required_header_unstripped][1] if required_header_unstripped.strip('<>"') not in include_dict: error(filename, required[required_header_unstripped][0], 'build/include_what_you_use', 4, 'Add #include ' + required_header_unstripped + ' for ' + template)
[ "def", "CheckForIncludeWhatYouUse", "(", "filename", ",", "clean_lines", ",", "include_state", ",", "error", ",", "io", "=", "codecs", ")", ":", "required", "=", "{", "}", "# A map of header name to linenumber and the template entity.", "# Example of required: { '<functiona...
https://github.com/cvmfs/cvmfs/blob/4637bdb5153178eadf885c1acf37bdc5c685bf8a/cpplint.py#L5611-L5702
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html.py
python
HtmlWindow.SetRelatedStatusBar
(*args)
return _html.HtmlWindow_SetRelatedStatusBar(*args)
SetRelatedStatusBar(self, int bar) SetRelatedStatusBar(self, StatusBar ?, int index=0)
SetRelatedStatusBar(self, int bar) SetRelatedStatusBar(self, StatusBar ?, int index=0)
[ "SetRelatedStatusBar", "(", "self", "int", "bar", ")", "SetRelatedStatusBar", "(", "self", "StatusBar", "?", "int", "index", "=", "0", ")" ]
def SetRelatedStatusBar(*args): """ SetRelatedStatusBar(self, int bar) SetRelatedStatusBar(self, StatusBar ?, int index=0) """ return _html.HtmlWindow_SetRelatedStatusBar(*args)
[ "def", "SetRelatedStatusBar", "(", "*", "args", ")", ":", "return", "_html", ".", "HtmlWindow_SetRelatedStatusBar", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L1022-L1027
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/eager/context.py
python
Context._import_config
(self)
Import config if passed in during construction. If Context was created with a ConfigProto such as when calling tf.compat.v1.enable_eager_execution(), then we need to pull out the various pieces we might be replacing and import then into our internal class representation.
Import config if passed in during construction.
[ "Import", "config", "if", "passed", "in", "during", "construction", "." ]
def _import_config(self): """Import config if passed in during construction. If Context was created with a ConfigProto such as when calling tf.compat.v1.enable_eager_execution(), then we need to pull out the various pieces we might be replacing and import then into our internal class representation. """ if self._config is None: return num_cpus = self._config.device_count.get("CPU", 1) if num_cpus != 1: cpus = [d for d in self._physical_devices if d.device_type == "CPU"] if num_cpus == 0: self.set_visible_devices([], "CPU") elif num_cpus > 1: self.set_logical_device_configuration( cpus[0], [LogicalDeviceConfiguration() for _ in range(num_cpus)]) # Parse GPU options gpus = [d for d in self._physical_devices if d.device_type == "GPU"] # If there are no GPUs detected, simply ignore all the GPU options passed in # rather than doing any validation checks. if not gpus: return gpu_count = self._config.device_count.get("GPU", None) visible_gpus = [] # TODO(gjn): Handle importing existing virtual GPU configuration visible_indices = self._config.gpu_options.visible_device_list if visible_indices: for index in visible_indices.split(","): if int(index) >= len(gpus): raise ValueError("Invalid visible device index: %s" % index) visible_gpus.append(gpus[int(index)]) else: visible_gpus = gpus if gpu_count is not None: visible_gpus = visible_gpus[:gpu_count] self.set_visible_devices(visible_gpus, "GPU")
[ "def", "_import_config", "(", "self", ")", ":", "if", "self", ".", "_config", "is", "None", ":", "return", "num_cpus", "=", "self", ".", "_config", ".", "device_count", ".", "get", "(", "\"CPU\"", ",", "1", ")", "if", "num_cpus", "!=", "1", ":", "cpu...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/context.py#L1485-L1529
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/service_reflection.py
python
_ServiceBuilder._NonImplementedMethod
(self, method_name, rpc_controller, callback)
The body of all methods in the generated service class. Args: method_name: Name of the method being executed. rpc_controller: RPC controller used to execute this method. callback: A callback which will be invoked when the method finishes.
The body of all methods in the generated service class.
[ "The", "body", "of", "all", "methods", "in", "the", "generated", "service", "class", "." ]
def _NonImplementedMethod(self, method_name, rpc_controller, callback): """The body of all methods in the generated service class. Args: method_name: Name of the method being executed. rpc_controller: RPC controller used to execute this method. callback: A callback which will be invoked when the method finishes. """ rpc_controller.SetFailed('Method %s not implemented.' % method_name) callback(None)
[ "def", "_NonImplementedMethod", "(", "self", ",", "method_name", ",", "rpc_controller", ",", "callback", ")", ":", "rpc_controller", ".", "SetFailed", "(", "'Method %s not implemented.'", "%", "method_name", ")", "callback", "(", "None", ")" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/service_reflection.py#L218-L227
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/pylib/results/flakiness_dashboard/json_results_generator.py
python
AddPathToTrie
(path, value, trie)
Inserts a single path and value into a directory trie structure.
Inserts a single path and value into a directory trie structure.
[ "Inserts", "a", "single", "path", "and", "value", "into", "a", "directory", "trie", "structure", "." ]
def AddPathToTrie(path, value, trie): """Inserts a single path and value into a directory trie structure.""" if not '/' in path: trie[path] = value return directory, _, rest = path.partition('/') if not directory in trie: trie[directory] = {} AddPathToTrie(rest, value, trie[directory])
[ "def", "AddPathToTrie", "(", "path", ",", "value", ",", "trie", ")", ":", "if", "not", "'/'", "in", "path", ":", "trie", "[", "path", "]", "=", "value", "return", "directory", ",", "_", ",", "rest", "=", "path", ".", "partition", "(", "'/'", ")", ...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/pylib/results/flakiness_dashboard/json_results_generator.py#L65-L74
xiaohaoChen/rrc_detection
4f2b110cd122da7f55e8533275a9b4809a88785a
scripts/cpp_lint.py
python
_NestingState.SeenOpenBrace
(self)
return (not self.stack) or self.stack[-1].seen_open_brace
Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace.
Check if we have seen the opening brace for the innermost block.
[ "Check", "if", "we", "have", "seen", "the", "opening", "brace", "for", "the", "innermost", "block", "." ]
def SeenOpenBrace(self): """Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace. """ return (not self.stack) or self.stack[-1].seen_open_brace
[ "def", "SeenOpenBrace", "(", "self", ")", ":", "return", "(", "not", "self", ".", "stack", ")", "or", "self", ".", "stack", "[", "-", "1", "]", ".", "seen_open_brace" ]
https://github.com/xiaohaoChen/rrc_detection/blob/4f2b110cd122da7f55e8533275a9b4809a88785a/scripts/cpp_lint.py#L1935-L1942
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
dom/bindings/parser/WebIDL.py
python
Parser.p_RelativeScopedName
(self, p)
RelativeScopedName : IDENTIFIER ScopedNameParts
RelativeScopedName : IDENTIFIER ScopedNameParts
[ "RelativeScopedName", ":", "IDENTIFIER", "ScopedNameParts" ]
def p_RelativeScopedName(self, p): """ RelativeScopedName : IDENTIFIER ScopedNameParts """ assert not p[2] # Not implemented! p[0] = IDLUnresolvedIdentifier(self.getLocation(p, 1), p[1])
[ "def", "p_RelativeScopedName", "(", "self", ",", "p", ")", ":", "assert", "not", "p", "[", "2", "]", "# Not implemented!", "p", "[", "0", "]", "=", "IDLUnresolvedIdentifier", "(", "self", ".", "getLocation", "(", "p", ",", "1", ")", ",", "p", "[", "1...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/parser/WebIDL.py#L5490-L5496
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/box.py
python
Box.square
(cls, L)
return cls(L, L, 0, 0, 0, 0)
Create a square with side lengths ``L``. Args: L (float): The box side length :math:`[\\mathrm{length}]`. Returns: hoomd.Box: The created 2D box.
Create a square with side lengths ``L``.
[ "Create", "a", "square", "with", "side", "lengths", "L", "." ]
def square(cls, L): """Create a square with side lengths ``L``. Args: L (float): The box side length :math:`[\\mathrm{length}]`. Returns: hoomd.Box: The created 2D box. """ return cls(L, L, 0, 0, 0, 0)
[ "def", "square", "(", "cls", ",", "L", ")", ":", "return", "cls", "(", "L", ",", "L", ",", "0", ",", "0", ",", "0", ",", "0", ")" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/box.py#L122-L131
lightvector/KataGo
20d34784703c5b4000643d3ccc43bb37d418f3b5
python/elo.py
python
EloInfo.get_approx_elo_stderr
(self, p1: Player)
return self.elo_stderr[p1]
Returns an approximation of the standard error on the Elo of p1, ASSUMING all other players Elos are equal to their maximum likelihood value. This approximation may underestimate if the amount of data is very small.
Returns an approximation of the standard error on the Elo of p1, ASSUMING all other players Elos are equal to their maximum likelihood value. This approximation may underestimate if the amount of data is very small.
[ "Returns", "an", "approximation", "of", "the", "standard", "error", "on", "the", "Elo", "of", "p1", "ASSUMING", "all", "other", "players", "Elos", "are", "equal", "to", "their", "maximum", "likelihood", "value", ".", "This", "approximation", "may", "underestim...
def get_approx_elo_stderr(self, p1: Player) -> float: """Returns an approximation of the standard error on the Elo of p1, ASSUMING all other players Elos are equal to their maximum likelihood value. This approximation may underestimate if the amount of data is very small.""" return self.elo_stderr[p1]
[ "def", "get_approx_elo_stderr", "(", "self", ",", "p1", ":", "Player", ")", "->", "float", ":", "return", "self", ".", "elo_stderr", "[", "p1", "]" ]
https://github.com/lightvector/KataGo/blob/20d34784703c5b4000643d3ccc43bb37d418f3b5/python/elo.py#L39-L42
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/formats/style_render.py
python
StylerRenderer._translate
(self, sparse_index: bool, sparse_cols: bool, blank: str = "&nbsp;")
return d
Process Styler data and settings into a dict for template rendering. Convert data and settings from ``Styler`` attributes such as ``self.data``, ``self.tooltips`` including applying any methods in ``self._todo``. Parameters ---------- sparse_index : bool Whether to sparsify the index or print all hierarchical index elements. Upstream defaults are typically to `pandas.options.styler.sparse.index`. sparse_cols : bool Whether to sparsify the columns or print all hierarchical column elements. Upstream defaults are typically to `pandas.options.styler.sparse.columns`. Returns ------- d : dict The following structure: {uuid, table_styles, caption, head, body, cellstyle, table_attributes}
Process Styler data and settings into a dict for template rendering.
[ "Process", "Styler", "data", "and", "settings", "into", "a", "dict", "for", "template", "rendering", "." ]
def _translate(self, sparse_index: bool, sparse_cols: bool, blank: str = "&nbsp;"): """ Process Styler data and settings into a dict for template rendering. Convert data and settings from ``Styler`` attributes such as ``self.data``, ``self.tooltips`` including applying any methods in ``self._todo``. Parameters ---------- sparse_index : bool Whether to sparsify the index or print all hierarchical index elements. Upstream defaults are typically to `pandas.options.styler.sparse.index`. sparse_cols : bool Whether to sparsify the columns or print all hierarchical column elements. Upstream defaults are typically to `pandas.options.styler.sparse.columns`. Returns ------- d : dict The following structure: {uuid, table_styles, caption, head, body, cellstyle, table_attributes} """ ROW_HEADING_CLASS = "row_heading" COL_HEADING_CLASS = "col_heading" INDEX_NAME_CLASS = "index_name" TRIMMED_COL_CLASS = "col_trim" TRIMMED_ROW_CLASS = "row_trim" DATA_CLASS = "data" BLANK_CLASS = "blank" BLANK_VALUE = blank # construct render dict d = { "uuid": self.uuid, "table_styles": _format_table_styles(self.table_styles or []), "caption": self.caption, } max_elements = get_option("styler.render.max_elements") max_rows, max_cols = _get_trimming_maximums( len(self.data.index), len(self.data.columns), max_elements ) head = self._translate_header( BLANK_CLASS, BLANK_VALUE, INDEX_NAME_CLASS, COL_HEADING_CLASS, sparse_cols, max_cols, TRIMMED_COL_CLASS, ) d.update({"head": head}) self.cellstyle_map: DefaultDict[tuple[CSSPair, ...], list[str]] = defaultdict( list ) body = self._translate_body( DATA_CLASS, ROW_HEADING_CLASS, sparse_index, max_rows, max_cols, TRIMMED_ROW_CLASS, TRIMMED_COL_CLASS, ) d.update({"body": body}) cellstyle: list[dict[str, CSSList | list[str]]] = [ {"props": list(props), "selectors": selectors} for props, selectors in self.cellstyle_map.items() ] d.update({"cellstyle": cellstyle}) table_attr = self.table_attributes use_mathjax = get_option("display.html.use_mathjax") if not use_mathjax: table_attr = table_attr or "" if 'class="' in table_attr: table_attr = table_attr.replace('class="', 'class="tex2jax_ignore ') else: table_attr += ' class="tex2jax_ignore"' d.update({"table_attributes": table_attr}) if self.tooltips: d = self.tooltips._translate(self.data, self.uuid, d) return d
[ "def", "_translate", "(", "self", ",", "sparse_index", ":", "bool", ",", "sparse_cols", ":", "bool", ",", "blank", ":", "str", "=", "\"&nbsp;\"", ")", ":", "ROW_HEADING_CLASS", "=", "\"row_heading\"", "COL_HEADING_CLASS", "=", "\"col_heading\"", "INDEX_NAME_CLASS"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/style_render.py#L163-L251
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/heapq.py
python
_siftdown_max
(heap, startpos, pos)
Maxheap variant of _siftdown
Maxheap variant of _siftdown
[ "Maxheap", "variant", "of", "_siftdown" ]
def _siftdown_max(heap, startpos, pos): 'Maxheap variant of _siftdown' newitem = heap[pos] # Follow the path to the root, moving parents down until finding a place # newitem fits. while pos > startpos: parentpos = (pos - 1) >> 1 parent = heap[parentpos] if parent < newitem: heap[pos] = parent pos = parentpos continue break heap[pos] = newitem
[ "def", "_siftdown_max", "(", "heap", ",", "startpos", ",", "pos", ")", ":", "newitem", "=", "heap", "[", "pos", "]", "# Follow the path to the root, moving parents down until finding a place", "# newitem fits.", "while", "pos", ">", "startpos", ":", "parentpos", "=", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/heapq.py#L278-L291
quantOS-org/DataCore
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/descriptor.py
python
DescriptorBase.__init__
(self, options, options_class_name)
Initialize the descriptor given its options message and the name of the class of the options message. The name of the class is required in case the options message is None and has to be created.
Initialize the descriptor given its options message and the name of the class of the options message. The name of the class is required in case the options message is None and has to be created.
[ "Initialize", "the", "descriptor", "given", "its", "options", "message", "and", "the", "name", "of", "the", "class", "of", "the", "options", "message", ".", "The", "name", "of", "the", "class", "is", "required", "in", "case", "the", "options", "message", "...
def __init__(self, options, options_class_name): """Initialize the descriptor given its options message and the name of the class of the options message. The name of the class is required in case the options message is None and has to be created. """ self._options = options self._options_class_name = options_class_name # Does this descriptor have non-default options? self.has_options = options is not None
[ "def", "__init__", "(", "self", ",", "options", ",", "options_class_name", ")", ":", "self", ".", "_options", "=", "options", "self", ".", "_options_class_name", "=", "options_class_name", "# Does this descriptor have non-default options?", "self", ".", "has_options", ...
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/descriptor.py#L71-L80
nvdla/sw
79538ba1b52b040a4a4645f630e457fa01839e90
umd/external/protobuf-2.6/python/google/protobuf/text_format.py
python
_Tokenizer.ConsumeInt64
(self)
return result
Consumes a signed 64bit integer number. Returns: The integer parsed. Raises: ParseError: If a signed 64bit integer couldn't be consumed.
Consumes a signed 64bit integer number.
[ "Consumes", "a", "signed", "64bit", "integer", "number", "." ]
def ConsumeInt64(self): """Consumes a signed 64bit integer number. Returns: The integer parsed. Raises: ParseError: If a signed 64bit integer couldn't be consumed. """ try: result = ParseInteger(self.token, is_signed=True, is_long=True) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result
[ "def", "ConsumeInt64", "(", "self", ")", ":", "try", ":", "result", "=", "ParseInteger", "(", "self", ".", "token", ",", "is_signed", "=", "True", ",", "is_long", "=", "True", ")", "except", "ValueError", ",", "e", ":", "raise", "self", ".", "_ParseErr...
https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/text_format.py#L593-L607
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py
python
_concat
(prefix, suffix, static=False)
return shape
Concat that enables int, Tensor, or TensorShape values. This function takes a size specification, which can be an integer, a TensorShape, or a Tensor, and converts it into a concatenated Tensor (if static = False) or a list of integers (if static = True). Args: prefix: The prefix; usually the batch size (and/or time step size). (TensorShape, int, or Tensor.) suffix: TensorShape, int, or Tensor. static: If `True`, return a python list with possibly unknown dimensions. Otherwise return a `Tensor`. Returns: shape: the concatenation of prefix and suffix. Raises: ValueError: if `suffix` is not a scalar or vector (or TensorShape). ValueError: if prefix or suffix was `None` and asked for dynamic Tensors out.
Concat that enables int, Tensor, or TensorShape values.
[ "Concat", "that", "enables", "int", "Tensor", "or", "TensorShape", "values", "." ]
def _concat(prefix, suffix, static=False): """Concat that enables int, Tensor, or TensorShape values. This function takes a size specification, which can be an integer, a TensorShape, or a Tensor, and converts it into a concatenated Tensor (if static = False) or a list of integers (if static = True). Args: prefix: The prefix; usually the batch size (and/or time step size). (TensorShape, int, or Tensor.) suffix: TensorShape, int, or Tensor. static: If `True`, return a python list with possibly unknown dimensions. Otherwise return a `Tensor`. Returns: shape: the concatenation of prefix and suffix. Raises: ValueError: if `suffix` is not a scalar or vector (or TensorShape). ValueError: if prefix or suffix was `None` and asked for dynamic Tensors out. """ if isinstance(prefix, ops.Tensor): p = prefix p_static = tensor_util.constant_value(prefix) if p.shape.ndims == 0: p = array_ops.expand_dims(p, 0) elif p.shape.ndims != 1: raise ValueError("prefix tensor must be either a scalar or vector, " "but saw tensor: %s" % p) else: p = tensor_shape.TensorShape(prefix) p_static = p.as_list() if p.ndims is not None else None p = ( constant_op.constant(p.as_list(), dtype=dtypes.int32) if p.is_fully_defined() else None) if isinstance(suffix, ops.Tensor): s = suffix s_static = tensor_util.constant_value(suffix) if s.shape.ndims == 0: s = array_ops.expand_dims(s, 0) elif s.shape.ndims != 1: raise ValueError("suffix tensor must be either a scalar or vector, " "but saw tensor: %s" % s) else: s = tensor_shape.TensorShape(suffix) s_static = s.as_list() if s.ndims is not None else None s = ( constant_op.constant(s.as_list(), dtype=dtypes.int32) if s.is_fully_defined() else None) if static: shape = tensor_shape.TensorShape(p_static).concatenate(s_static) shape = shape.as_list() if shape.ndims is not None else None else: if p is None or s is None: raise ValueError("Provided a prefix or suffix of None: %s and %s" % (prefix, suffix)) shape = array_ops.concat((p, s), 0) return shape
[ "def", "_concat", "(", "prefix", ",", "suffix", ",", "static", "=", "False", ")", ":", "if", "isinstance", "(", "prefix", ",", "ops", ".", "Tensor", ")", ":", "p", "=", "prefix", "p_static", "=", "tensor_util", ".", "constant_value", "(", "prefix", ")"...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py#L106-L165
deepmodeling/deepmd-kit
159e45d248b0429844fb6a8cb3b3a201987c8d79
deepmd/loggers/loggers.py
python
set_log_handles
( level: int, log_path: Optional["Path"] = None, mpi_log: Optional[str] = None )
Set desired level for package loggers and add file handlers. Parameters ---------- level: int logging level log_path: Optional[str] path to log file, if None logs will be send only to console. If the parent directory does not exist it will be automatically created, by default None mpi_log : Optional[str], optional mpi log type. Has three options. `master` will output logs to file and console only from rank==0. `collect` will write messages from all ranks to one file opened under rank==0 and to console. `workers` will open one log file for each worker designated by its rank, console behaviour is the same as for `collect`. If this argument is specified, package 'mpi4py' must be already installed. by default None Raises ------ RuntimeError If the argument `mpi_log` is specified, package `mpi4py` is not installed. References ---------- https://groups.google.com/g/mpi4py/c/SaNzc8bdj6U https://stackoverflow.com/questions/35869137/avoid-tensorflow-print-on-standard-error https://stackoverflow.com/questions/56085015/suppress-openmp-debug-messages-when-running-tensorflow-on-cpu Notes ----- Logging levels: +---------+--------------+----------------+----------------+----------------+ | | our notation | python logging | tensorflow cpp | OpenMP | +=========+==============+================+================+================+ | debug | 10 | 10 | 0 | 1/on/true/yes | +---------+--------------+----------------+----------------+----------------+ | info | 20 | 20 | 1 | 0/off/false/no | +---------+--------------+----------------+----------------+----------------+ | warning | 30 | 30 | 2 | 0/off/false/no | +---------+--------------+----------------+----------------+----------------+ | error | 40 | 40 | 3 | 0/off/false/no | +---------+--------------+----------------+----------------+----------------+
Set desired level for package loggers and add file handlers.
[ "Set", "desired", "level", "for", "package", "loggers", "and", "add", "file", "handlers", "." ]
def set_log_handles( level: int, log_path: Optional["Path"] = None, mpi_log: Optional[str] = None ): """Set desired level for package loggers and add file handlers. Parameters ---------- level: int logging level log_path: Optional[str] path to log file, if None logs will be send only to console. If the parent directory does not exist it will be automatically created, by default None mpi_log : Optional[str], optional mpi log type. Has three options. `master` will output logs to file and console only from rank==0. `collect` will write messages from all ranks to one file opened under rank==0 and to console. `workers` will open one log file for each worker designated by its rank, console behaviour is the same as for `collect`. If this argument is specified, package 'mpi4py' must be already installed. by default None Raises ------ RuntimeError If the argument `mpi_log` is specified, package `mpi4py` is not installed. References ---------- https://groups.google.com/g/mpi4py/c/SaNzc8bdj6U https://stackoverflow.com/questions/35869137/avoid-tensorflow-print-on-standard-error https://stackoverflow.com/questions/56085015/suppress-openmp-debug-messages-when-running-tensorflow-on-cpu Notes ----- Logging levels: +---------+--------------+----------------+----------------+----------------+ | | our notation | python logging | tensorflow cpp | OpenMP | +=========+==============+================+================+================+ | debug | 10 | 10 | 0 | 1/on/true/yes | +---------+--------------+----------------+----------------+----------------+ | info | 20 | 20 | 1 | 0/off/false/no | +---------+--------------+----------------+----------------+----------------+ | warning | 30 | 30 | 2 | 0/off/false/no | +---------+--------------+----------------+----------------+----------------+ | error | 40 | 40 | 3 | 0/off/false/no | +---------+--------------+----------------+----------------+----------------+ """ # silence logging for OpenMP when running on CPU if level is any other than debug if level <= 10: os.environ["KMP_WARNINGS"] = "FALSE" # set TF cpp internal logging level os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(int((level / 10) - 1)) # get root logger root_log = logging.getLogger() # remove all old handlers root_log.setLevel(level) for hdlr in root_log.handlers[:]: root_log.removeHandler(hdlr) # check if arguments are present MPI = None if mpi_log: try: from mpi4py import MPI except ImportError as e: raise RuntimeError("You cannot specify 'mpi_log' when mpi4py not installed") from e # * add console handler ************************************************************ ch = logging.StreamHandler() if MPI: rank = MPI.COMM_WORLD.Get_rank() if mpi_log == "master": ch.setFormatter(CFORMATTER) ch.addFilter(_MPIMasterFilter(rank)) else: ch.setFormatter(CFORMATTER_MPI) ch.addFilter(_MPIRankFilter(rank)) else: ch.setFormatter(CFORMATTER) ch.setLevel(level) ch.addFilter(_AppFilter()) root_log.addHandler(ch) # * add file handler *************************************************************** if log_path: # create directory log_path.parent.mkdir(exist_ok=True, parents=True) fh = None if mpi_log == "master": rank = MPI.COMM_WORLD.Get_rank() if rank == 0: fh = logging.FileHandler(log_path, mode="w") fh.addFilter(_MPIMasterFilter(rank)) fh.setFormatter(FFORMATTER) elif mpi_log == "collect": rank = MPI.COMM_WORLD.Get_rank() fh = _MPIHandler(log_path, MPI, mode=MPI.MODE_WRONLY | MPI.MODE_CREATE) fh.addFilter(_MPIRankFilter(rank)) fh.setFormatter(FFORMATTER_MPI) elif mpi_log == "workers": rank = MPI.COMM_WORLD.Get_rank() # if file has suffix than inser rank number before suffix # e.g deepmd.log -> deepmd_<rank>.log # if no suffix is present, insert rank as suffix # e.g. deepmdlog -> deepmdlog.<rank> if log_path.suffix: worker_log = (log_path.parent / f"{log_path.stem}_{rank}").with_suffix( log_path.suffix ) else: worker_log = log_path.with_suffix(f".{rank}") fh = logging.FileHandler(worker_log, mode="w") fh.setFormatter(FFORMATTER) else: fh = logging.FileHandler(log_path, mode="w") fh.setFormatter(FFORMATTER) if fh: fh.setLevel(level) fh.addFilter(_AppFilter()) root_log.addHandler(fh)
[ "def", "set_log_handles", "(", "level", ":", "int", ",", "log_path", ":", "Optional", "[", "\"Path\"", "]", "=", "None", ",", "mpi_log", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "# silence logging for OpenMP when running on CPU if level is any othe...
https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/loggers/loggers.py#L137-L268
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/client/session.py
python
BaseSession._do_run
(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
Runs a step based on the given fetches and feeds. Args: handle: a handle for partial_run. None if this is just a call to run(). target_list: A list of byte arrays corresponding to names of tensors or operations to be run to, but not fetched. fetch_list: A list of byte arrays corresponding to names of tensors to be fetched and operations to be run. feed_dict: A dictionary that maps tensor names (as byte arrays) to numpy ndarrays. options: A (pointer to a) [`RunOptions`] protocol buffer, or None run_metadata: A (pointer to a) [`RunMetadata`] protocol buffer, or None Returns: A list of numpy ndarrays, corresponding to the elements of `fetch_list`. If the ith element of `fetch_list` contains the name of an operation, the first Tensor output of that operation will be returned for that element. Raises: tf.errors.OpError: Or one of its subclasses on error.
Runs a step based on the given fetches and feeds.
[ "Runs", "a", "step", "based", "on", "the", "given", "fetches", "and", "feeds", "." ]
def _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata): """Runs a step based on the given fetches and feeds. Args: handle: a handle for partial_run. None if this is just a call to run(). target_list: A list of byte arrays corresponding to names of tensors or operations to be run to, but not fetched. fetch_list: A list of byte arrays corresponding to names of tensors to be fetched and operations to be run. feed_dict: A dictionary that maps tensor names (as byte arrays) to numpy ndarrays. options: A (pointer to a) [`RunOptions`] protocol buffer, or None run_metadata: A (pointer to a) [`RunMetadata`] protocol buffer, or None Returns: A list of numpy ndarrays, corresponding to the elements of `fetch_list`. If the ith element of `fetch_list` contains the name of an operation, the first Tensor output of that operation will be returned for that element. Raises: tf.errors.OpError: Or one of its subclasses on error. """ def _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata): # Ensure any changes to the graph are reflected in the runtime. self._extend_graph() with errors.raise_exception_on_not_ok_status() as status: return tf_session.TF_Run(session, options, feed_dict, fetch_list, target_list, status, run_metadata) def _prun_fn(session, handle, feed_dict, fetch_list): if target_list: raise RuntimeError('partial_run() requires empty target_list.') with errors.raise_exception_on_not_ok_status() as status: return tf_session.TF_PRun(session, handle, feed_dict, fetch_list, status) if handle is None: return self._do_call(_run_fn, self._session, feed_dict, fetch_list, target_list, options, run_metadata) else: return self._do_call(_prun_fn, self._session, handle, feed_dict, fetch_list)
[ "def", "_do_run", "(", "self", ",", "handle", ",", "target_list", ",", "fetch_list", ",", "feed_dict", ",", "options", ",", "run_metadata", ")", ":", "def", "_run_fn", "(", "session", ",", "feed_dict", ",", "fetch_list", ",", "target_list", ",", "options", ...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/client/session.py#L923-L968