nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/decorators.py
python
jitdevice
(func, link=[], debug=None, inline=False)
return compile_device_template(func, debug=debug, inline=inline)
Wrapper for device-jit.
Wrapper for device-jit.
[ "Wrapper", "for", "device", "-", "jit", "." ]
def jitdevice(func, link=[], debug=None, inline=False): """Wrapper for device-jit. """ debug = config.CUDA_DEBUGINFO_DEFAULT if debug is None else debug if link: raise ValueError("link keyword invalid for device function") return compile_device_template(func, debug=debug, inline=inline)
[ "def", "jitdevice", "(", "func", ",", "link", "=", "[", "]", ",", "debug", "=", "None", ",", "inline", "=", "False", ")", ":", "debug", "=", "config", ".", "CUDA_DEBUGINFO_DEFAULT", "if", "debug", "is", "None", "else", "debug", "if", "link", ":", "ra...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/decorators.py#L9-L15
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/generator/eclipse.py
python
CalculateGeneratorInputInfo
(params)
Calculate the generator specific info that gets fed to input (called by gyp).
Calculate the generator specific info that gets fed to input (called by gyp).
[ "Calculate", "the", "generator", "specific", "info", "that", "gets", "fed", "to", "input", "(", "called", "by", "gyp", ")", "." ]
def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) if generator_flags.get('adjust_static_libraries', False): global generator_wants_static_library_dependencies_adjusted generator_wants_static_library_dependencies_adjusted = True
[ "def", "CalculateGeneratorInputInfo", "(", "params", ")", ":", "generator_flags", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", "if", "generator_flags", ".", "get", "(", "'adjust_static_libraries'", ",", "False", ")", ":", "global", ...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/eclipse.py#L71-L77
baidu/AnyQ
d94d450d2aaa5f7ed73424b10aa4539835b97527
tools/solr/solr_tools.py
python
_get_error_message
(respond_str)
Extract error information
Extract error information
[ "Extract", "error", "information" ]
def _get_error_message(respond_str): """ Extract error information """ respond_dict = json.loads(respond_str.strip()) errmsg = respond_dict.get('error', dict()).get('msg', '') print _make_smart_hint(HINT_TYPE_REQ_ERR, errmsg)
[ "def", "_get_error_message", "(", "respond_str", ")", ":", "respond_dict", "=", "json", ".", "loads", "(", "respond_str", ".", "strip", "(", ")", ")", "errmsg", "=", "respond_dict", ".", "get", "(", "'error'", ",", "dict", "(", ")", ")", ".", "get", "(...
https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/solr/solr_tools.py#L49-L55
qt/qt
0a2f2382541424726168804be2c90b91381608c6
src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/generator/msvs.py
python
_EscapeEnvironmentVariableExpansion
(s)
return s
Escapes any % characters so that Windows-style environment variable expansions will leave them alone. See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile to understand why we have to do this.
Escapes any % characters so that Windows-style environment variable expansions will leave them alone. See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile to understand why we have to do this.
[ "Escapes", "any", "%", "characters", "so", "that", "Windows", "-", "style", "environment", "variable", "expansions", "will", "leave", "them", "alone", ".", "See", "http", ":", "//", "connect", ".", "microsoft", ".", "com", "/", "VisualStudio", "/", "feedback...
def _EscapeEnvironmentVariableExpansion(s): """Escapes any % characters so that Windows-style environment variable expansions will leave them alone. See http://connect.microsoft.com/VisualStudio/feedback/details/106127/cl-d-name-text-containing-percentage-characters-doesnt-compile to understand why we have to do this.""" s = s.replace('%', '%%') return s
[ "def", "_EscapeEnvironmentVariableExpansion", "(", "s", ")", ":", "s", "=", "s", ".", "replace", "(", "'%'", ",", "'%%'", ")", "return", "s" ]
https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/generator/msvs.py#L556-L562
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_wx/objpanel.py
python
WidgetContainer.get_obj
(self)
return self._attrconf.get_obj()
Returns object to be displayed on panel.
Returns object to be displayed on panel.
[ "Returns", "object", "to", "be", "displayed", "on", "panel", "." ]
def get_obj(self): """ Returns object to be displayed on panel. """ return self._attrconf.get_obj()
[ "def", "get_obj", "(", "self", ")", ":", "return", "self", ".", "_attrconf", ".", "get_obj", "(", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py#L521-L525
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
llvm/utils/lit/lit/discovery.py
python
getTestSuite
(item, litConfig, cache)
return ts, tuple(relative + tuple(components))
getTestSuite(item, litConfig, cache) -> (suite, relative_path) Find the test suite containing @arg item. @retval (None, ...) - Indicates no test suite contains @arg item. @retval (suite, relative_path) - The suite that @arg item is in, and its relative path inside that suite.
getTestSuite(item, litConfig, cache) -> (suite, relative_path)
[ "getTestSuite", "(", "item", "litConfig", "cache", ")", "-", ">", "(", "suite", "relative_path", ")" ]
def getTestSuite(item, litConfig, cache): """getTestSuite(item, litConfig, cache) -> (suite, relative_path) Find the test suite containing @arg item. @retval (None, ...) - Indicates no test suite contains @arg item. @retval (suite, relative_path) - The suite that @arg item is in, and its relative path inside that suite. """ def search1(path): # Check for a site config or a lit config. cfgpath = dirContainsTestSuite(path, litConfig) # If we didn't find a config file, keep looking. if not cfgpath: parent,base = os.path.split(path) if parent == path: return (None, ()) ts, relative = search(parent) return (ts, relative + (base,)) # This is a private builtin parameter which can be used to perform # translation of configuration paths. Specifically, this parameter # can be set to a dictionary that the discovery process will consult # when it finds a configuration it is about to load. If the given # path is in the map, the value of that key is a path to the # configuration to load instead. config_map = litConfig.params.get('config_map') if config_map: cfgpath = os.path.realpath(cfgpath) cfgpath = os.path.normcase(cfgpath) target = config_map.get(cfgpath) if target: cfgpath = target # We found a test suite, create a new config for it and load it. if litConfig.debug: litConfig.note('loading suite config %r' % cfgpath) cfg = TestingConfig.fromdefaults(litConfig) cfg.load_from_path(cfgpath, litConfig) source_root = os.path.realpath(cfg.test_source_root or path) exec_root = os.path.realpath(cfg.test_exec_root or path) return Test.TestSuite(cfg.name, source_root, exec_root, cfg), () def search(path): # Check for an already instantiated test suite. real_path = os.path.realpath(path) res = cache.get(real_path) if res is None: cache[real_path] = res = search1(path) return res # Canonicalize the path. item = os.path.normpath(os.path.join(os.getcwd(), item)) # Skip files and virtual components. components = [] while not os.path.isdir(item): parent,base = os.path.split(item) if parent == item: return (None, ()) components.append(base) item = parent components.reverse() ts, relative = search(item) return ts, tuple(relative + tuple(components))
[ "def", "getTestSuite", "(", "item", ",", "litConfig", ",", "cache", ")", ":", "def", "search1", "(", "path", ")", ":", "# Check for a site config or a lit config.", "cfgpath", "=", "dirContainsTestSuite", "(", "path", ",", "litConfig", ")", "# If we didn't find a co...
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/llvm/utils/lit/lit/discovery.py#L25-L93
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/pylib/host_driven/setup.py
python
_GetTestsFromClass
(test_case_class, **kwargs)
return [test_case_class(name, **kwargs) for name in test_names]
Returns one test object for each test method in |test_case_class|. Test methods are methods on the class which begin with 'test'. Args: test_case_class: Class derived from HostDrivenTestCase which contains zero or more test methods. kwargs: Keyword args to pass into the constructor of test cases. Returns: A list of test case objects, each initialized for a particular test method.
Returns one test object for each test method in |test_case_class|.
[ "Returns", "one", "test", "object", "for", "each", "test", "method", "in", "|test_case_class|", "." ]
def _GetTestsFromClass(test_case_class, **kwargs): """Returns one test object for each test method in |test_case_class|. Test methods are methods on the class which begin with 'test'. Args: test_case_class: Class derived from HostDrivenTestCase which contains zero or more test methods. kwargs: Keyword args to pass into the constructor of test cases. Returns: A list of test case objects, each initialized for a particular test method. """ test_names = [m for m in dir(test_case_class) if _IsTestMethod(m, test_case_class)] return [test_case_class(name, **kwargs) for name in test_names]
[ "def", "_GetTestsFromClass", "(", "test_case_class", ",", "*", "*", "kwargs", ")", ":", "test_names", "=", "[", "m", "for", "m", "in", "dir", "(", "test_case_class", ")", "if", "_IsTestMethod", "(", "m", ",", "test_case_class", ")", "]", "return", "[", "...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/host_driven/setup.py#L90-L105
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/base/role_maker.py
python
PaddleCloudRoleMaker._heter_device
(self)
return self._heter_trainer_device
return the heter device that current heter worker is using
return the heter device that current heter worker is using
[ "return", "the", "heter", "device", "that", "current", "heter", "worker", "is", "using" ]
def _heter_device(self): """ return the heter device that current heter worker is using """ if not self._role_is_generated: self._generate_role() return self._heter_trainer_device
[ "def", "_heter_device", "(", "self", ")", ":", "if", "not", "self", ".", "_role_is_generated", ":", "self", ".", "_generate_role", "(", ")", "return", "self", ".", "_heter_trainer_device" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/base/role_maker.py#L553-L559
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Cipher/Blowfish.py
python
_create_base_cipher
(dict_parameters)
return SmartPointer(void_p.get(), stop_operation)
This method instantiates and returns a smart pointer to a low-level base cipher. It will absorb named parameters in the process.
This method instantiates and returns a smart pointer to a low-level base cipher. It will absorb named parameters in the process.
[ "This", "method", "instantiates", "and", "returns", "a", "smart", "pointer", "to", "a", "low", "-", "level", "base", "cipher", ".", "It", "will", "absorb", "named", "parameters", "in", "the", "process", "." ]
def _create_base_cipher(dict_parameters): """This method instantiates and returns a smart pointer to a low-level base cipher. It will absorb named parameters in the process.""" try: key = dict_parameters.pop("key") except KeyError: raise TypeError("Missing 'key' parameter") if len(key) not in key_size: raise ValueError("Incorrect Blowfish key length (%d bytes)" % len(key)) start_operation = _raw_blowfish_lib.Blowfish_start_operation stop_operation = _raw_blowfish_lib.Blowfish_stop_operation void_p = VoidPointer() result = start_operation(c_uint8_ptr(key), c_size_t(len(key)), void_p.address_of()) if result: raise ValueError("Error %X while instantiating the Blowfish cipher" % result) return SmartPointer(void_p.get(), stop_operation)
[ "def", "_create_base_cipher", "(", "dict_parameters", ")", ":", "try", ":", "key", "=", "dict_parameters", ".", "pop", "(", "\"key\"", ")", "except", "KeyError", ":", "raise", "TypeError", "(", "\"Missing 'key' parameter\"", ")", "if", "len", "(", "key", ")", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Cipher/Blowfish.py#L60-L83
msftguy/ssh-rd
a5f3a79daeac5844edebf01916c9613563f1c390
_3rd/boost_1_48_0/tools/build/v2/build/scanner.py
python
registered
(scanner_class)
return __scanners.has_key(str(scanner_class))
Returns true iff a scanner of that class is registered
Returns true iff a scanner of that class is registered
[ "Returns", "true", "iff", "a", "scanner", "of", "that", "class", "is", "registered" ]
def registered(scanner_class): """ Returns true iff a scanner of that class is registered """ return __scanners.has_key(str(scanner_class))
[ "def", "registered", "(", "scanner_class", ")", ":", "return", "__scanners", ".", "has_key", "(", "str", "(", "scanner_class", ")", ")" ]
https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/scanner.py#L61-L64
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
src/bindings/python/src/openvino/runtime/opset8/ops.py
python
prior_box
( layer_shape: Node, image_shape: NodeInput, attrs: dict, name: Optional[str] = None )
return _get_node_factory_opset8().create("PriorBox", [layer_shape, as_node(image_shape)], attrs)
Generate prior boxes of specified sizes and aspect ratios across all dimensions. @param layer_shape: Shape of layer for which prior boxes are computed. @param image_shape: Shape of image to which prior boxes are scaled. @param attrs: The dictionary containing key, value pairs for attributes. @param name: Optional name for the output node. @return Node representing prior box operation. Available attributes are: * min_size The minimum box size (in pixels). Range of values: positive floating point numbers Default value: [] Required: no * max_size The maximum box size (in pixels). Range of values: positive floating point numbers Default value: [] Required: no * aspect_ratio Aspect ratios of prior boxes. Range of values: set of positive floating point numbers Default value: [] Required: no * flip The flag that denotes that each aspect_ratio is duplicated and flipped. Range of values: {True, False} Default value: False Required: no * clip The flag that denotes if each value in the output tensor should be clipped to [0,1] interval. Range of values: {True, False} Default value: False Required: no * step The distance between box centers. Range of values: floating point non-negative number Default value: 0 Required: no * offset This is a shift of box respectively to top left corner. Range of values: floating point non-negative number Default value: None Required: yes * variance The variance denotes a variance of adjusting bounding boxes. The attribute could contain 0, 1 or 4 elements. Range of values: floating point positive numbers Default value: [] Required: no * scale_all_sizes The flag that denotes type of inference. Range of values: False - max_size is ignored True - max_size is used Default value: True Required: no * fixed_ratio This is an aspect ratio of a box. Range of values: a list of positive floating-point numbers Default value: None Required: no * fixed_size This is an initial box size (in pixels). Range of values: a list of positive floating-point numbers Default value: None Required: no * density This is the square root of the number of boxes of each type. Range of values: a list of positive floating-point numbers Default value: None Required: no * min_max_aspect_ratios_order The flag that denotes the order of output prior box. Range of values: False - the output prior box is in order of [min, aspect_ratios, max] True - the output prior box is in order of [min, max, aspect_ratios] Default value: True Required: no Example of attribute dictionary: @code{.py} # just required ones attrs = { 'offset': 85, } attrs = { 'offset': 85, 'flip': True, 'clip': True, 'fixed_size': [32, 64, 128] } @endcode Optional attributes which are absent from dictionary will be set with corresponding default.
Generate prior boxes of specified sizes and aspect ratios across all dimensions.
[ "Generate", "prior", "boxes", "of", "specified", "sizes", "and", "aspect", "ratios", "across", "all", "dimensions", "." ]
def prior_box( layer_shape: Node, image_shape: NodeInput, attrs: dict, name: Optional[str] = None ) -> Node: """Generate prior boxes of specified sizes and aspect ratios across all dimensions. @param layer_shape: Shape of layer for which prior boxes are computed. @param image_shape: Shape of image to which prior boxes are scaled. @param attrs: The dictionary containing key, value pairs for attributes. @param name: Optional name for the output node. @return Node representing prior box operation. Available attributes are: * min_size The minimum box size (in pixels). Range of values: positive floating point numbers Default value: [] Required: no * max_size The maximum box size (in pixels). Range of values: positive floating point numbers Default value: [] Required: no * aspect_ratio Aspect ratios of prior boxes. Range of values: set of positive floating point numbers Default value: [] Required: no * flip The flag that denotes that each aspect_ratio is duplicated and flipped. Range of values: {True, False} Default value: False Required: no * clip The flag that denotes if each value in the output tensor should be clipped to [0,1] interval. Range of values: {True, False} Default value: False Required: no * step The distance between box centers. Range of values: floating point non-negative number Default value: 0 Required: no * offset This is a shift of box respectively to top left corner. Range of values: floating point non-negative number Default value: None Required: yes * variance The variance denotes a variance of adjusting bounding boxes. The attribute could contain 0, 1 or 4 elements. Range of values: floating point positive numbers Default value: [] Required: no * scale_all_sizes The flag that denotes type of inference. Range of values: False - max_size is ignored True - max_size is used Default value: True Required: no * fixed_ratio This is an aspect ratio of a box. Range of values: a list of positive floating-point numbers Default value: None Required: no * fixed_size This is an initial box size (in pixels). Range of values: a list of positive floating-point numbers Default value: None Required: no * density This is the square root of the number of boxes of each type. Range of values: a list of positive floating-point numbers Default value: None Required: no * min_max_aspect_ratios_order The flag that denotes the order of output prior box. Range of values: False - the output prior box is in order of [min, aspect_ratios, max] True - the output prior box is in order of [min, max, aspect_ratios] Default value: True Required: no Example of attribute dictionary: @code{.py} # just required ones attrs = { 'offset': 85, } attrs = { 'offset': 85, 'flip': True, 'clip': True, 'fixed_size': [32, 64, 128] } @endcode Optional attributes which are absent from dictionary will be set with corresponding default. """ requirements = [ ("offset", True, np.floating, is_non_negative_value), ("min_size", False, np.floating, is_positive_value), ("max_size", False, np.floating, is_positive_value), ("aspect_ratio", False, np.floating, is_positive_value), ("flip", False, np.bool_, None), ("clip", False, np.bool_, None), ("step", False, np.floating, is_non_negative_value), ("variance", False, np.floating, is_positive_value), ("scale_all_sizes", False, np.bool_, None), ("fixed_ratio", False, np.floating, is_positive_value), ("fixed_size", False, np.floating, is_positive_value), ("density", False, np.floating, is_positive_value), ("min_max_aspect_ratios_order", False, np.bool_, None), ] check_valid_attributes("PriorBox", attrs, requirements) return _get_node_factory_opset8().create("PriorBox", [layer_shape, as_node(image_shape)], attrs)
[ "def", "prior_box", "(", "layer_shape", ":", "Node", ",", "image_shape", ":", "NodeInput", ",", "attrs", ":", "dict", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Node", ":", "requirements", "=", "[", "(", "\"offset\"", ",", ...
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/openvino/runtime/opset8/ops.py#L407-L509
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PaalmanPingsMonteCarloAbsorption.py
python
PaalmanPingsMonteCarloAbsorption._update_instrument_angles
(self, workspace, q_values, wave)
Updates the instrument angles in the specified workspace, using the specified wavelength and the specified Q-Values. This is required when calculating absorption corrections for indirect elastic. This is used only for ISIS instruments. :param workspace: The workspace whose instrument angles to update. :param q_values: The extracted Q-Values (MomentumTransfer) :param wave: The wavelength
Updates the instrument angles in the specified workspace, using the specified wavelength and the specified Q-Values. This is required when calculating absorption corrections for indirect elastic. This is used only for ISIS instruments.
[ "Updates", "the", "instrument", "angles", "in", "the", "specified", "workspace", "using", "the", "specified", "wavelength", "and", "the", "specified", "Q", "-", "Values", ".", "This", "is", "required", "when", "calculating", "absorption", "corrections", "for", "...
def _update_instrument_angles(self, workspace, q_values, wave): """ Updates the instrument angles in the specified workspace, using the specified wavelength and the specified Q-Values. This is required when calculating absorption corrections for indirect elastic. This is used only for ISIS instruments. :param workspace: The workspace whose instrument angles to update. :param q_values: The extracted Q-Values (MomentumTransfer) :param wave: The wavelength """ work_dir = config['defaultsave.directory'] k0 = 4.0 * math.pi / wave theta = 2.0 * np.degrees(np.arcsin(q_values / k0)) # convert to angle filename = 'Elastic_angles.txt' path = os.path.join(work_dir, filename) logger.information('Creating angles file : ' + path) handle = open(path, 'w') head = 'spectrum,theta' handle.write(head + " \n") for n in range(0, len(theta)): handle.write(str(n + 1) + ' ' + str(theta[n]) + "\n") handle.close() update_alg = self.createChildAlgorithm("UpdateInstrumentFromFile", enableLogging=False) update_alg.setProperty("Workspace", workspace) update_alg.setProperty("Filename", path) update_alg.setProperty("MoveMonitors", False) update_alg.setProperty("IgnorePhi", True) update_alg.setProperty("AsciiHeader", head) update_alg.setProperty("SkipFirstNLines", 1)
[ "def", "_update_instrument_angles", "(", "self", ",", "workspace", ",", "q_values", ",", "wave", ")", ":", "work_dir", "=", "config", "[", "'defaultsave.directory'", "]", "k0", "=", "4.0", "*", "math", ".", "pi", "/", "wave", "theta", "=", "2.0", "*", "n...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PaalmanPingsMonteCarloAbsorption.py#L763-L793
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
clang/bindings/python/clang/cindex.py
python
TranslationUnit.reparse
(self, unsaved_files=None, options=0)
Reparse an already parsed translation unit. In-memory contents for files can be provided by passing a list of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects.
Reparse an already parsed translation unit.
[ "Reparse", "an", "already", "parsed", "translation", "unit", "." ]
def reparse(self, unsaved_files=None, options=0): """ Reparse an already parsed translation unit. In-memory contents for files can be provided by passing a list of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ if unsaved_files is None: unsaved_files = [] unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,contents) in enumerate(unsaved_files): if hasattr(contents, "read"): contents = contents.read() contents = b(contents) unsaved_files_array[i].name = b(fspath(name)) unsaved_files_array[i].contents = contents unsaved_files_array[i].length = len(contents) ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), unsaved_files_array, options)
[ "def", "reparse", "(", "self", ",", "unsaved_files", "=", "None", ",", "options", "=", "0", ")", ":", "if", "unsaved_files", "is", "None", ":", "unsaved_files", "=", "[", "]", "unsaved_files_array", "=", "0", "if", "len", "(", "unsaved_files", ")", ":", ...
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang/bindings/python/clang/cindex.py#L2989-L3012
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBLaunchInfo.SetDetachOnError
(self, enable)
return _lldb.SBLaunchInfo_SetDetachOnError(self, enable)
SetDetachOnError(SBLaunchInfo self, bool enable)
SetDetachOnError(SBLaunchInfo self, bool enable)
[ "SetDetachOnError", "(", "SBLaunchInfo", "self", "bool", "enable", ")" ]
def SetDetachOnError(self, enable): """SetDetachOnError(SBLaunchInfo self, bool enable)""" return _lldb.SBLaunchInfo_SetDetachOnError(self, enable)
[ "def", "SetDetachOnError", "(", "self", ",", "enable", ")", ":", "return", "_lldb", ".", "SBLaunchInfo_SetDetachOnError", "(", "self", ",", "enable", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L6636-L6638
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/reductions/solvers/solver.py
python
Solver.import_solver
(self)
Imports the solver.
Imports the solver.
[ "Imports", "the", "solver", "." ]
def import_solver(self): """Imports the solver. """ raise NotImplementedError()
[ "def", "import_solver", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/reductions/solvers/solver.py#L51-L54
google/nucleus
68d3947fafba1337f294c0668a6e1c7f3f1273e3
nucleus/io/genomics_reader.py
python
GenomicsReader.__init__
(self)
Initializer.
Initializer.
[ "Initializer", "." ]
def __init__(self): """Initializer.""" # Some readers can only support one iterator at a time, so don't # create one now. Rather, create it when needed in next(). self.iterator = None
[ "def", "__init__", "(", "self", ")", ":", "# Some readers can only support one iterator at a time, so don't", "# create one now. Rather, create it when needed in next().", "self", ".", "iterator", "=", "None" ]
https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/io/genomics_reader.py#L102-L106
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
utils/indigo-service/service/v2/indigo_api.py
python
automap
()
return get_response( md, data["output_format"], data["json_output"], data["options"] )
Automatically calculate reaction atoms mapping --- tags: - indigo parameters: - name: json_request in: body required: true schema: id: IndigoAutomapRequest properties: struct: type: string required: true examples: C1=CC=CC=C1.N>>C1=CC=CC=N1.C output_format: type: string default: chemical/x-mdl-rxnfile enum: - chemical/x-mdl-rxnfile - chemical/x-mdl-molfile - chemical/x-indigo-ket - chemical/x-daylight-smiles - chemical/x-chemaxon-cxsmiles - chemical/x-cml - chemical/x-inchi - chemical/x-iupac - chemical/x-daylight-smarts - chemical/x-inchi-aux example: struct: C1=CC=CC=C1.N>>C1=CC=CC=N1.C output_format: chemical/x-mdl-rxnfile responses: 200: description: Reaction with calculated atom-to-atom mappings schema: $ref: "#/definitions/IndigoResponse" 400: description: 'A problem with supplied client data' schema: $ref: "#/definitions/ClientError" 500: description: 'A problem on server side' schema: $ref: "#/definitions/ServerError"
Automatically calculate reaction atoms mapping --- tags: - indigo parameters: - name: json_request in: body required: true schema: id: IndigoAutomapRequest properties: struct: type: string required: true examples: C1=CC=CC=C1.N>>C1=CC=CC=N1.C output_format: type: string default: chemical/x-mdl-rxnfile enum: - chemical/x-mdl-rxnfile - chemical/x-mdl-molfile - chemical/x-indigo-ket - chemical/x-daylight-smiles - chemical/x-chemaxon-cxsmiles - chemical/x-cml - chemical/x-inchi - chemical/x-iupac - chemical/x-daylight-smarts - chemical/x-inchi-aux example: struct: C1=CC=CC=C1.N>>C1=CC=CC=N1.C output_format: chemical/x-mdl-rxnfile responses: 200: description: Reaction with calculated atom-to-atom mappings schema: $ref: "#/definitions/IndigoResponse" 400: description: 'A problem with supplied client data' schema: $ref: "#/definitions/ClientError" 500: description: 'A problem on server side' schema: $ref: "#/definitions/ServerError"
[ "Automatically", "calculate", "reaction", "atoms", "mapping", "---", "tags", ":", "-", "indigo", "parameters", ":", "-", "name", ":", "json_request", "in", ":", "body", "required", ":", "true", "schema", ":", "id", ":", "IndigoAutomapRequest", "properties", ":...
def automap(): """ Automatically calculate reaction atoms mapping --- tags: - indigo parameters: - name: json_request in: body required: true schema: id: IndigoAutomapRequest properties: struct: type: string required: true examples: C1=CC=CC=C1.N>>C1=CC=CC=N1.C output_format: type: string default: chemical/x-mdl-rxnfile enum: - chemical/x-mdl-rxnfile - chemical/x-mdl-molfile - chemical/x-indigo-ket - chemical/x-daylight-smiles - chemical/x-chemaxon-cxsmiles - chemical/x-cml - chemical/x-inchi - chemical/x-iupac - chemical/x-daylight-smarts - chemical/x-inchi-aux example: struct: C1=CC=CC=C1.N>>C1=CC=CC=N1.C output_format: chemical/x-mdl-rxnfile responses: 200: description: Reaction with calculated atom-to-atom mappings schema: $ref: "#/definitions/IndigoResponse" 400: description: 'A problem with supplied client data' schema: $ref: "#/definitions/ClientError" 500: description: 'A problem on server side' schema: $ref: "#/definitions/ServerError" """ data = IndigoAutomapSchema().load(get_request_data(request)) LOG_DATA( "[REQUEST] /automap", data["input_format"], data["output_format"], data["mode"], data["struct"], data["options"], ) md = load_moldata( data["struct"], mime_type=data["input_format"], options=data["options"] ) md.struct.automap(data["mode"]) return get_response( md, data["output_format"], data["json_output"], data["options"] )
[ "def", "automap", "(", ")", ":", "data", "=", "IndigoAutomapSchema", "(", ")", ".", "load", "(", "get_request_data", "(", "request", ")", ")", "LOG_DATA", "(", "\"[REQUEST] /automap\"", ",", "data", "[", "\"input_format\"", "]", ",", "data", "[", "\"output_f...
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/utils/indigo-service/service/v2/indigo_api.py#L950-L1013
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
build/android/gradle/generate_gradle.py
python
_ProjectEntry.ProjectName
(self)
return self.GradleSubdir().replace(os.path.sep, '\\$')
Returns the Gradle project name.
Returns the Gradle project name.
[ "Returns", "the", "Gradle", "project", "name", "." ]
def ProjectName(self): """Returns the Gradle project name.""" return self.GradleSubdir().replace(os.path.sep, '\\$')
[ "def", "ProjectName", "(", "self", ")", ":", "return", "self", ".", "GradleSubdir", "(", ")", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'\\\\$'", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/gradle/generate_gradle.py#L116-L118
dmlc/decord
96b750c7221322391969929e855b942d2fdcd06b
python/decord/av_reader.py
python
AVReader._validate_indices
(self, indices)
return indices
Validate int64 integers and convert negative integers to positive by backward search
Validate int64 integers and convert negative integers to positive by backward search
[ "Validate", "int64", "integers", "and", "convert", "negative", "integers", "to", "positive", "by", "backward", "search" ]
def _validate_indices(self, indices): """Validate int64 integers and convert negative integers to positive by backward search""" assert self.__video_reader is not None and self.__audio_reader is not None indices = np.array(indices, dtype=np.int64) # process negative indices indices[indices < 0] += len(self.__video_reader) if not (indices >= 0).all(): raise IndexError( 'Invalid negative indices: {}'.format(indices[indices < 0] + len(self.__video_reader))) if not (indices < len(self.__video_reader)).all(): raise IndexError('Out of bound indices: {}'.format(indices[indices >= len(self.__video_reader)])) return indices
[ "def", "_validate_indices", "(", "self", ",", "indices", ")", ":", "assert", "self", ".", "__video_reader", "is", "not", "None", "and", "self", ".", "__audio_reader", "is", "not", "None", "indices", "=", "np", ".", "array", "(", "indices", ",", "dtype", ...
https://github.com/dmlc/decord/blob/96b750c7221322391969929e855b942d2fdcd06b/python/decord/av_reader.py#L138-L149
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/math/symbolic.py
python
OperatorExpression._do
(self,constargs)
Calculates function with the given resolved argument tuple
Calculates function with the given resolved argument tuple
[ "Calculates", "function", "with", "the", "given", "resolved", "argument", "tuple" ]
def _do(self,constargs): """Calculates function with the given resolved argument tuple""" assert not any(isinstance(a,Expression) for a in constargs),"Trying to evaluate an Expression's base function with non-constant inputs?" assert self.op is not None try: return self.op(*constargs) except Exception as e: #this will be handled during eval's exception handler """ print "Error while evaluating",self.functionInfo.name,"with arguments:" if self.functionInfo.argNames: for (name,a) in zip(self.functionInfo.argNames,constargs): print " ",name,"=",a else: print " ",','.join([str(a) for a in constargs]) print "Error",e import traceback print "Traceback" traceback.print_exc() try: print "Call stack:", self._print_call_stack() except Exception as e2: print "Hmm... exception occured while calling print_call_stack()?" print e2 import traceback print "Traceback" traceback.print_exc() raise ValueError("Exception "+str(e)+" while evaluating function "+self.functionInfo.name+" with args "+",".join(str(v) for v in constargs)) """ task = "Evaluating "+self.functionInfo.name+" with args "+",".join(str(v) for v in constargs) import sys raise _TraverseException(e,self,task,sys.exc_info()[2]),None,sys.exc_info()[2]
[ "def", "_do", "(", "self", ",", "constargs", ")", ":", "assert", "not", "any", "(", "isinstance", "(", "a", ",", "Expression", ")", "for", "a", "in", "constargs", ")", ",", "\"Trying to evaluate an Expression's base function with non-constant inputs?\"", "assert", ...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/symbolic.py#L2704-L2736
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
DC.DrawCirclePoint
(*args, **kwargs)
return _gdi_.DC_DrawCirclePoint(*args, **kwargs)
DrawCirclePoint(self, Point pt, int radius) Draws a circle with the given center point and radius. The current pen is used for the outline and the current brush for filling the shape.
DrawCirclePoint(self, Point pt, int radius)
[ "DrawCirclePoint", "(", "self", "Point", "pt", "int", "radius", ")" ]
def DrawCirclePoint(*args, **kwargs): """ DrawCirclePoint(self, Point pt, int radius) Draws a circle with the given center point and radius. The current pen is used for the outline and the current brush for filling the shape. """ return _gdi_.DC_DrawCirclePoint(*args, **kwargs)
[ "def", "DrawCirclePoint", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_DrawCirclePoint", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L3632-L3640
OpenGenus/cosmos
1a94e8880068e51d571543be179c323936bd0936
code/networking/src/packetsniffer/packetsniffer.py
python
main
()
Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-b yte swap operation.
Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-b yte swap operation.
[ "Convert", "16", "-", "bit", "positive", "integers", "from", "host", "to", "network", "byte", "order", ".", "On", "machines", "where", "the", "host", "byte", "order", "is", "the", "same", "as", "network", "byte", "order", "this", "is", "a", "no", "-", ...
def main(): """Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-b yte swap operation.""" """socket.PF_PACKET to send and recieve messages, below the internet protocol layer The process must be run with root access""" """ When using socket.bind(()) we will redirect the access to an especific port I am using socket.RAW, so i dont want to bind my connection to a port""" sniffer = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x3)) wireshark_file = wireshark_open("aux.pcap") while True: recv = sniffer.recv(65535) wireshark_write(wireshark_file, recv) dados_novos, ip = met_ethernet_header(recv) if ip: dados_novos, prox, tam = met_ip_header(dados_novos) if prox == "TCP": dados_novos, src, dest = met_tcp_header(dados_novos, tam) if src == 80 or dest == 80: dados_novos = met_http_header(dados_novos, tam) elif prox == "UDP": dados_novos = met_udp_header(dados_novos, tam) wireshark_close(wireshark_file)
[ "def", "main", "(", ")", ":", "\"\"\"socket.PF_PACKET to send and recieve messages, below the internet protocol layer\n The process must be run with root access\"\"\"", "\"\"\" When using socket.bind(()) we will redirect the access to an especific port\n I am using socket.RAW, so i dont want to bi...
https://github.com/OpenGenus/cosmos/blob/1a94e8880068e51d571543be179c323936bd0936/code/networking/src/packetsniffer/packetsniffer.py#L299-L329
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
examples/machine_learning/lasso_regression.py
python
generate_data
(m: int = 100, n: int = 20, sigma: int = 5, density: float = 0.2)
return X, Y, beta_star
Generates data matrix X and observations Y.
Generates data matrix X and observations Y.
[ "Generates", "data", "matrix", "X", "and", "observations", "Y", "." ]
def generate_data(m: int = 100, n: int = 20, sigma: int = 5, density: float = 0.2): "Generates data matrix X and observations Y." np.random.seed(1) beta_star = np.random.randn(n) idxs = np.random.choice(range(n), int((1-density)*n), replace=False) for idx in idxs: beta_star[idx] = 0 X = np.random.randn(m,n) Y = X.dot(beta_star) + np.random.normal(0, sigma, size=m) return X, Y, beta_star
[ "def", "generate_data", "(", "m", ":", "int", "=", "100", ",", "n", ":", "int", "=", "20", ",", "sigma", ":", "int", "=", "5", ",", "density", ":", "float", "=", "0.2", ")", ":", "np", ".", "random", ".", "seed", "(", "1", ")", "beta_star", "...
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/examples/machine_learning/lasso_regression.py#L23-L32
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/external/bazel_tools/tools/j2objc/j2objc_wrapper.py
python
_ParseArgs
(j2objc_args)
return (source_files, flags)
Separate arguments passed to J2ObjC into source files and J2ObjC flags. Args: j2objc_args: A list of args to pass to J2ObjC transpiler. Returns: A tuple containing source files and J2ObjC flags
Separate arguments passed to J2ObjC into source files and J2ObjC flags.
[ "Separate", "arguments", "passed", "to", "J2ObjC", "into", "source", "files", "and", "J2ObjC", "flags", "." ]
def _ParseArgs(j2objc_args): """Separate arguments passed to J2ObjC into source files and J2ObjC flags. Args: j2objc_args: A list of args to pass to J2ObjC transpiler. Returns: A tuple containing source files and J2ObjC flags """ source_files = [] flags = [] is_next_flag_value = False for j2objc_arg in j2objc_args: if j2objc_arg.startswith('-'): flags.append(j2objc_arg) is_next_flag_value = True elif is_next_flag_value: flags.append(j2objc_arg) is_next_flag_value = False else: source_files.append(j2objc_arg) return (source_files, flags)
[ "def", "_ParseArgs", "(", "j2objc_args", ")", ":", "source_files", "=", "[", "]", "flags", "=", "[", "]", "is_next_flag_value", "=", "False", "for", "j2objc_arg", "in", "j2objc_args", ":", "if", "j2objc_arg", ".", "startswith", "(", "'-'", ")", ":", "flags...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/tools/j2objc/j2objc_wrapper.py#L180-L200
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/plan/rigidobjectcspace.py
python
RigidObjectCSpace.envCollision
(self,x=None)
return False
Checks whether the robot at its current configuration is in collision with the environment.
Checks whether the robot at its current configuration is in collision with the environment.
[ "Checks", "whether", "the", "robot", "at", "its", "current", "configuration", "is", "in", "collision", "with", "the", "environment", "." ]
def envCollision(self,x=None): """Checks whether the robot at its current configuration is in collision with the environment.""" if not self.collider: return False if x is not None: self.setConfig(x) for o in xrange(self.collider.world.numRobots()): if any(self.collider.robotObjectCollisions(o.index,self.rigidObject.index)): return True; for o in xrange(self.collider.world.numRigidObjects()): if any(self.collider.objectObjectCollisions(self.rigidObject.index,o)): return True; for o in xrange(self.collider.world.numTerrains()): if any(self.collider.objectTerrainCollisions(self.rigidObject.index,o)): return True; return False
[ "def", "envCollision", "(", "self", ",", "x", "=", "None", ")", ":", "if", "not", "self", ".", "collider", ":", "return", "False", "if", "x", "is", "not", "None", ":", "self", ".", "setConfig", "(", "x", ")", "for", "o", "in", "xrange", "(", "sel...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/plan/rigidobjectcspace.py#L112-L126
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py
python
Signature.bind
(*args, **kwargs)
return args[0]._bind(args[1:], kwargs)
Get a BoundArguments object, that maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound.
Get a BoundArguments object, that maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound.
[ "Get", "a", "BoundArguments", "object", "that", "maps", "the", "passed", "args", "and", "kwargs", "to", "the", "function", "s", "signature", ".", "Raises", "TypeError", "if", "the", "passed", "arguments", "can", "not", "be", "bound", "." ]
def bind(*args, **kwargs): """Get a BoundArguments object, that maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. """ return args[0]._bind(args[1:], kwargs)
[ "def", "bind", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "args", "[", "0", "]", ".", "_bind", "(", "args", "[", "1", ":", "]", ",", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py#L3010-L3015
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
clang/bindings/python/clang/cindex.py
python
CompileCommand.directory
(self)
return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
Get the working directory for this CompileCommand
Get the working directory for this CompileCommand
[ "Get", "the", "working", "directory", "for", "this", "CompileCommand" ]
def directory(self): """Get the working directory for this CompileCommand""" return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
[ "def", "directory", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CompileCommand_getDirectory", "(", "self", ".", "cmd", ")" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/clang/bindings/python/clang/cindex.py#L3180-L3182
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/array_ops.py
python
slice
(input_, begin, size, name=None)
return gen_array_ops._slice(input_, begin, size, name=name)
Extracts a slice from a tensor. This operation extracts a slice of size `size` from a tensor `input` starting at the location specified by `begin`. The slice `size` is represented as a tensor shape, where `size[i]` is the number of elements of the 'i'th dimension of `input` that you want to slice. The starting location (`begin`) for the slice is represented as an offset in each dimension of `input`. In other words, `begin[i]` is the offset into the 'i'th dimension of `input` that you want to slice from. Note that @{tf.Tensor.__getitem__} is typically a more pythonic way to perform slices, as it allows you to write `foo[3:7, :-2]` instead of `tf.slice([3, 0], [4, foo.get_shape()[1]-2])`. `begin` is zero-based; `size` is one-based. If `size[i]` is -1, all remaining elements in dimension i are included in the slice. In other words, this is equivalent to setting: `size[i] = input.dim_size(i) - begin[i]` This operation requires that: `0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n]` For example: ```python # 'input' is [[[1, 1, 1], [2, 2, 2]], # [[3, 3, 3], [4, 4, 4]], # [[5, 5, 5], [6, 6, 6]]] tf.slice(input, [1, 0, 0], [1, 1, 3]) ==> [[[3, 3, 3]]] tf.slice(input, [1, 0, 0], [1, 2, 3]) ==> [[[3, 3, 3], [4, 4, 4]]] tf.slice(input, [1, 0, 0], [2, 1, 3]) ==> [[[3, 3, 3]], [[5, 5, 5]]] ``` Args: input_: A `Tensor`. begin: An `int32` or `int64` `Tensor`. size: An `int32` or `int64` `Tensor`. name: A name for the operation (optional). Returns: A `Tensor` the same type as `input`.
Extracts a slice from a tensor.
[ "Extracts", "a", "slice", "from", "a", "tensor", "." ]
def slice(input_, begin, size, name=None): # pylint: disable=redefined-builtin """Extracts a slice from a tensor. This operation extracts a slice of size `size` from a tensor `input` starting at the location specified by `begin`. The slice `size` is represented as a tensor shape, where `size[i]` is the number of elements of the 'i'th dimension of `input` that you want to slice. The starting location (`begin`) for the slice is represented as an offset in each dimension of `input`. In other words, `begin[i]` is the offset into the 'i'th dimension of `input` that you want to slice from. Note that @{tf.Tensor.__getitem__} is typically a more pythonic way to perform slices, as it allows you to write `foo[3:7, :-2]` instead of `tf.slice([3, 0], [4, foo.get_shape()[1]-2])`. `begin` is zero-based; `size` is one-based. If `size[i]` is -1, all remaining elements in dimension i are included in the slice. In other words, this is equivalent to setting: `size[i] = input.dim_size(i) - begin[i]` This operation requires that: `0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n]` For example: ```python # 'input' is [[[1, 1, 1], [2, 2, 2]], # [[3, 3, 3], [4, 4, 4]], # [[5, 5, 5], [6, 6, 6]]] tf.slice(input, [1, 0, 0], [1, 1, 3]) ==> [[[3, 3, 3]]] tf.slice(input, [1, 0, 0], [1, 2, 3]) ==> [[[3, 3, 3], [4, 4, 4]]] tf.slice(input, [1, 0, 0], [2, 1, 3]) ==> [[[3, 3, 3]], [[5, 5, 5]]] ``` Args: input_: A `Tensor`. begin: An `int32` or `int64` `Tensor`. size: An `int32` or `int64` `Tensor`. name: A name for the operation (optional). Returns: A `Tensor` the same type as `input`. """ return gen_array_ops._slice(input_, begin, size, name=name)
[ "def", "slice", "(", "input_", ",", "begin", ",", "size", ",", "name", "=", "None", ")", ":", "# pylint: disable=redefined-builtin", "return", "gen_array_ops", ".", "_slice", "(", "input_", ",", "begin", ",", "size", ",", "name", "=", "name", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/array_ops.py#L513-L561
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/pylib/valgrind_tools.py
python
AddressSanitizerTool.CopyFiles
(cls, device)
Copies ASan tools to the device.
Copies ASan tools to the device.
[ "Copies", "ASan", "tools", "to", "the", "device", "." ]
def CopyFiles(cls, device): """Copies ASan tools to the device.""" del device
[ "def", "CopyFiles", "(", "cls", ",", "device", ")", ":", "del", "device" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/pylib/valgrind_tools.py#L42-L44
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/poolmanager.py
python
PoolManager._new_pool
(self, scheme, host, port, request_context=None)
return pool_cls(host, port, **request_context)
Create a new :class:`ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization.
Create a new :class:`ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments.
[ "Create", "a", "new", ":", "class", ":", "ConnectionPool", "based", "on", "host", "port", "scheme", "and", "any", "additional", "pool", "keyword", "arguments", "." ]
def _new_pool(self, scheme, host, port, request_context=None): """ Create a new :class:`ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization. """ pool_cls = self.pool_classes_by_scheme[scheme] if request_context is None: request_context = self.connection_pool_kw.copy() # Although the context has everything necessary to create the pool, # this function has historically only used the scheme, host, and port # in the positional args. When an API change is acceptable these can # be removed. for key in ("scheme", "host", "port"): request_context.pop(key, None) if scheme == "http": for kw in SSL_KEYWORDS: request_context.pop(kw, None) return pool_cls(host, port, **request_context)
[ "def", "_new_pool", "(", "self", ",", "scheme", ",", "host", ",", "port", ",", "request_context", "=", "None", ")", ":", "pool_cls", "=", "self", ".", "pool_classes_by_scheme", "[", "scheme", "]", "if", "request_context", "is", "None", ":", "request_context"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/poolmanager.py#L177-L202
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/automate/automate-git.py
python
get_chromium_channel_version
(os, channel)
return get_chromium_channel_data(os, channel, 'current_version')
Returns the current version for the specified Chromium channel.
Returns the current version for the specified Chromium channel.
[ "Returns", "the", "current", "version", "for", "the", "specified", "Chromium", "channel", "." ]
def get_chromium_channel_version(os, channel): """ Returns the current version for the specified Chromium channel. """ return get_chromium_channel_data(os, channel, 'current_version')
[ "def", "get_chromium_channel_version", "(", "os", ",", "channel", ")", ":", "return", "get_chromium_channel_data", "(", "os", ",", "channel", ",", "'current_version'", ")" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/automate/automate-git.py#L367-L369
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/texture_cube.py
python
TextureCube.bind_to_image
(self, unit: int, read: bool = True, write: bool = True, level: int = 0, format: int = 0)
Bind a texture to an image unit (OpenGL 4.2 required) This is used to bind textures to image units for shaders. The idea with image load/store is that the user can bind one of the images in a Texture to a number of image binding points (which are separate from texture image units). Shaders can read information from these images and write information to them, in ways that they cannot with textures. It's important to specify the right access type for the image. This can be set with the ``read`` and ``write`` arguments. Allowed combinations are: - **Read-only**: ``read=True`` and ``write=False`` - **Write-only**: ``read=False`` and ``write=True`` - **Read-write**: ``read=True`` and ``write=True`` ``format`` specifies the format that is to be used when performing formatted stores into the image from shaders. ``format`` must be compatible with the texture's internal format. **By default the format of the texture is passed in. The format parameter is only needed when overriding this behavior.** Note that we bind the texture cube as layered to make all the faces accessible. This can be updated to map single faces in the future. The Z component in imageLoad/Store represents the face id we are writing to (0-5). More information: - https://www.khronos.org/opengl/wiki/Image_Load_Store - https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindImageTexture.xhtml Args: unit (int): Specifies the index of the image unit to which to bind the texture texture (:py:class:`moderngl.Texture`): The texture to bind Keyword Args: read (bool): Allows the shader to read the image (default: ``True``) write (bool): Allows the shader to write to the image (default: ``True``) level (int): Level of the texture to bind (default: ``0``). format (int): (optional) The OpenGL enum value representing the format (defaults to the texture's format)
Bind a texture to an image unit (OpenGL 4.2 required)
[ "Bind", "a", "texture", "to", "an", "image", "unit", "(", "OpenGL", "4", ".", "2", "required", ")" ]
def bind_to_image(self, unit: int, read: bool = True, write: bool = True, level: int = 0, format: int = 0) -> None: """Bind a texture to an image unit (OpenGL 4.2 required) This is used to bind textures to image units for shaders. The idea with image load/store is that the user can bind one of the images in a Texture to a number of image binding points (which are separate from texture image units). Shaders can read information from these images and write information to them, in ways that they cannot with textures. It's important to specify the right access type for the image. This can be set with the ``read`` and ``write`` arguments. Allowed combinations are: - **Read-only**: ``read=True`` and ``write=False`` - **Write-only**: ``read=False`` and ``write=True`` - **Read-write**: ``read=True`` and ``write=True`` ``format`` specifies the format that is to be used when performing formatted stores into the image from shaders. ``format`` must be compatible with the texture's internal format. **By default the format of the texture is passed in. The format parameter is only needed when overriding this behavior.** Note that we bind the texture cube as layered to make all the faces accessible. This can be updated to map single faces in the future. The Z component in imageLoad/Store represents the face id we are writing to (0-5). More information: - https://www.khronos.org/opengl/wiki/Image_Load_Store - https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindImageTexture.xhtml Args: unit (int): Specifies the index of the image unit to which to bind the texture texture (:py:class:`moderngl.Texture`): The texture to bind Keyword Args: read (bool): Allows the shader to read the image (default: ``True``) write (bool): Allows the shader to write to the image (default: ``True``) level (int): Level of the texture to bind (default: ``0``). format (int): (optional) The OpenGL enum value representing the format (defaults to the texture's format) """ self.mglo.bind(unit, read, write, level, format)
[ "def", "bind_to_image", "(", "self", ",", "unit", ":", "int", ",", "read", ":", "bool", "=", "True", ",", "write", ":", "bool", "=", "True", ",", "level", ":", "int", "=", "0", ",", "format", ":", "int", "=", "0", ")", "->", "None", ":", "self"...
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/texture_cube.py#L265-L308
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
llvm/utils/lit/lit/util.py
python
abort_now
()
Abort the current process without doing any exception teardown
Abort the current process without doing any exception teardown
[ "Abort", "the", "current", "process", "without", "doing", "any", "exception", "teardown" ]
def abort_now(): """Abort the current process without doing any exception teardown""" sys.stdout.flush() if win32api: win32api.TerminateProcess(win32api.GetCurrentProcess(), 3) else: os.kill(0, 9)
[ "def", "abort_now", "(", ")", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "if", "win32api", ":", "win32api", ".", "TerminateProcess", "(", "win32api", ".", "GetCurrentProcess", "(", ")", ",", "3", ")", "else", ":", "os", ".", "kill", "(", "0",...
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/llvm/utils/lit/lit/util.py#L434-L440
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/motionplanning.py
python
PlannerInterface.getMilestone
(self, arg2)
return _motionplanning.PlannerInterface_getMilestone(self, arg2)
getMilestone(PlannerInterface self, int arg2) -> PyObject *
getMilestone(PlannerInterface self, int arg2) -> PyObject *
[ "getMilestone", "(", "PlannerInterface", "self", "int", "arg2", ")", "-", ">", "PyObject", "*" ]
def getMilestone(self, arg2): """ getMilestone(PlannerInterface self, int arg2) -> PyObject * """ return _motionplanning.PlannerInterface_getMilestone(self, arg2)
[ "def", "getMilestone", "(", "self", ",", "arg2", ")", ":", "return", "_motionplanning", ".", "PlannerInterface_getMilestone", "(", "self", ",", "arg2", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/motionplanning.py#L874-L881
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/frame.py
python
DataFrame._get_column_array
(self, i: int)
return self._mgr.iget_values(i)
Get the values of the i'th column (ndarray or ExtensionArray, as stored in the Block)
Get the values of the i'th column (ndarray or ExtensionArray, as stored in the Block)
[ "Get", "the", "values", "of", "the", "i", "th", "column", "(", "ndarray", "or", "ExtensionArray", "as", "stored", "in", "the", "Block", ")" ]
def _get_column_array(self, i: int) -> ArrayLike: """ Get the values of the i'th column (ndarray or ExtensionArray, as stored in the Block) """ return self._mgr.iget_values(i)
[ "def", "_get_column_array", "(", "self", ",", "i", ":", "int", ")", "->", "ArrayLike", ":", "return", "self", ".", "_mgr", ".", "iget_values", "(", "i", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/frame.py#L3403-L3408
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
AboutDialogInfo.GetDescriptionAndCredits
(*args, **kwargs)
return _misc_.AboutDialogInfo_GetDescriptionAndCredits(*args, **kwargs)
GetDescriptionAndCredits(self) -> String
GetDescriptionAndCredits(self) -> String
[ "GetDescriptionAndCredits", "(", "self", ")", "-", ">", "String" ]
def GetDescriptionAndCredits(*args, **kwargs): """GetDescriptionAndCredits(self) -> String""" return _misc_.AboutDialogInfo_GetDescriptionAndCredits(*args, **kwargs)
[ "def", "GetDescriptionAndCredits", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "AboutDialogInfo_GetDescriptionAndCredits", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L6935-L6937
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
v8_7_5/tools/stats-viewer.py
python
StatsViewer.UpdateCounters
(self)
Read the contents of the memory-mapped file and update the ui if necessary. If the same counters are present in the file as before we just update the existing labels. If any counters have been added or removed we scrap the existing ui and draw a new one.
Read the contents of the memory-mapped file and update the ui if necessary. If the same counters are present in the file as before we just update the existing labels. If any counters have been added or removed we scrap the existing ui and draw a new one.
[ "Read", "the", "contents", "of", "the", "memory", "-", "mapped", "file", "and", "update", "the", "ui", "if", "necessary", ".", "If", "the", "same", "counters", "are", "present", "in", "the", "file", "as", "before", "we", "just", "update", "the", "existin...
def UpdateCounters(self): """Read the contents of the memory-mapped file and update the ui if necessary. If the same counters are present in the file as before we just update the existing labels. If any counters have been added or removed we scrap the existing ui and draw a new one. """ changed = False counters_in_use = self.data.CountersInUse() if counters_in_use != len(self.ui_counters): self.RefreshCounters() changed = True else: for i in range(self.data.CountersInUse()): counter = self.data.Counter(i) name = counter.Name() if name in self.ui_counters: value = counter.Value() ui_counter = self.ui_counters[name] counter_changed = ui_counter.Set(value) changed = (changed or counter_changed) else: self.RefreshCounters() changed = True break if changed: # The title of the window shows the last time the file was # changed. self.UpdateTime() self.ScheduleUpdate()
[ "def", "UpdateCounters", "(", "self", ")", ":", "changed", "=", "False", "counters_in_use", "=", "self", ".", "data", ".", "CountersInUse", "(", ")", "if", "counters_in_use", "!=", "len", "(", "self", ".", "ui_counters", ")", ":", "self", ".", "RefreshCoun...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/v8_7_5/tools/stats-viewer.py#L137-L165
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/dtypes/concat.py
python
_concat_datetime
(to_concat, axis=0, typs=None)
provide concatenation of an datetimelike array of arrays each of which is a single M8[ns], datetimet64[ns, tz] or m8[ns] dtype Parameters ---------- to_concat : array of arrays axis : axis to provide concatenation typs : set of to_concat dtypes Returns ------- a single array, preserving the combined dtypes
provide concatenation of an datetimelike array of arrays each of which is a single M8[ns], datetimet64[ns, tz] or m8[ns] dtype
[ "provide", "concatenation", "of", "an", "datetimelike", "array", "of", "arrays", "each", "of", "which", "is", "a", "single", "M8", "[", "ns", "]", "datetimet64", "[", "ns", "tz", "]", "or", "m8", "[", "ns", "]", "dtype" ]
def _concat_datetime(to_concat, axis=0, typs=None): """ provide concatenation of an datetimelike array of arrays each of which is a single M8[ns], datetimet64[ns, tz] or m8[ns] dtype Parameters ---------- to_concat : array of arrays axis : axis to provide concatenation typs : set of to_concat dtypes Returns ------- a single array, preserving the combined dtypes """ if typs is None: typs = get_dtype_kinds(to_concat) # multiple types, need to coerce to object if len(typs) != 1: return _concatenate_2d([_convert_datetimelike_to_object(x) for x in to_concat], axis=axis) # must be single dtype if any(typ.startswith('datetime') for typ in typs): if 'datetime' in typs: to_concat = [x.astype(np.int64, copy=False) for x in to_concat] return _concatenate_2d(to_concat, axis=axis).view(_NS_DTYPE) else: # when to_concat has different tz, len(typs) > 1. # thus no need to care return _concat_datetimetz(to_concat) elif 'timedelta' in typs: return _concatenate_2d([x.view(np.int64) for x in to_concat], axis=axis).view(_TD_DTYPE) elif any(typ.startswith('period') for typ in typs): assert len(typs) == 1 cls = to_concat[0] new_values = cls._concat_same_type(to_concat) return new_values
[ "def", "_concat_datetime", "(", "to_concat", ",", "axis", "=", "0", ",", "typs", "=", "None", ")", ":", "if", "typs", "is", "None", ":", "typs", "=", "get_dtype_kinds", "(", "to_concat", ")", "# multiple types, need to coerce to object", "if", "len", "(", "t...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/dtypes/concat.py#L396-L440
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/io/ros.py
python
to_Path
(klampt_path,start_time='now',frame='1')
return rospath
Converts a Klampt SE3Trajectory, SO3Trajectory, or 2D or 3D Trajectory to a ROS Path. start_time can be 'now' or a rospy.Time object. frame is the frame_id in the object's headers (1 means global frame).
Converts a Klampt SE3Trajectory, SO3Trajectory, or 2D or 3D Trajectory to a ROS Path.
[ "Converts", "a", "Klampt", "SE3Trajectory", "SO3Trajectory", "or", "2D", "or", "3D", "Trajectory", "to", "a", "ROS", "Path", "." ]
def to_Path(klampt_path,start_time='now',frame='1'): """Converts a Klampt SE3Trajectory, SO3Trajectory, or 2D or 3D Trajectory to a ROS Path. start_time can be 'now' or a rospy.Time object. frame is the frame_id in the object's headers (1 means global frame). """ from klampt.model.trajectory import SO3Trajectory,SE3Trajectory rospath = Path() if start_time == 'now': start_time = rospy.Time.now() elif isinstance(start_time,(int,float)): start_time = rospy.Time(start_time) rospath.header.stamp = start_time rospath.header.frame_id = frame if len(klampt_path.milestones) == 0: return rospath milestone_to_se3 = None if isinstance(klampt_path,SE3Trajectory): milestone_to_se3 = lambda x:klampt_path.to_se3(x) elif isinstance(klampt_path,SO3Trajectory): milestone_to_se3 = lambda x:(x,[0,0,0]) else: if len(klampt_path.milestones[0]) not in [2,3]: raise ValueError("Only 3D trajectories are valid") ident = so3.identity() if len(klampt_path.milestones[0]) == 2: milestone_to_se3 = lambda x:(ident,[x[0],x[1],0.0]) else: milestone_to_se3 = lambda x:(ident,x) for t,x in zip(klampt_path.times,klampt_path.milestones): T = milestone_to_se3(x) Ps = PoseStamped() Ps.pose = to_Pose(T) Ps.header.seq = len(rospath.poses) Ps.header.stamp = start_time + t Ps.header.frame_id = frame rospath.poses.append(Ps) return rospath
[ "def", "to_Path", "(", "klampt_path", ",", "start_time", "=", "'now'", ",", "frame", "=", "'1'", ")", ":", "from", "klampt", ".", "model", ".", "trajectory", "import", "SO3Trajectory", ",", "SE3Trajectory", "rospath", "=", "Path", "(", ")", "if", "start_ti...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/io/ros.py#L327-L366
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/tools/compatibility/tf_upgrade_v2.py
python
_dropout_transformer
(parent, node, full_name, name, logs)
Replace keep_prob with 1-rate.
Replace keep_prob with 1-rate.
[ "Replace", "keep_prob", "with", "1", "-", "rate", "." ]
def _dropout_transformer(parent, node, full_name, name, logs): """Replace keep_prob with 1-rate.""" def _replace_keep_prob_node(parent, old_value): """Replaces old_value with 1-(old_value).""" one = ast.Num(n=1) one.lineno = 0 one.col_offset = 0 new_value = ast.BinOp(left=one, op=ast.Sub(), right=old_value) # This copies the prefix and suffix on old_value to new_value. pasta.ast_utils.replace_child(parent, old_value, new_value) ast.copy_location(new_value, old_value) # Put parentheses around keep_prob.value (and remove the old prefix/ # suffix, they should only be around new_value). pasta.base.formatting.set(old_value, "prefix", "(") pasta.base.formatting.set(old_value, "suffix", ")") # Check if we have a keep_prob keyword arg for keep_prob in node.keywords: if keep_prob.arg == "keep_prob": logs.append((ast_edits.INFO, node.lineno, node.col_offset, "Changing keep_prob arg of tf.nn.dropout to rate\n")) keep_prob.arg = "rate" _replace_keep_prob_node(keep_prob, keep_prob.value) return node # Maybe it was a positional arg if len(node.args) < 2: logs.append((ast_edits.ERROR, node.lineno, node.col_offset, "tf.nn.dropout called without arguments, so " "automatic fix was disabled. tf.nn.dropout has changed " "the semantics of the second argument.")) else: rate_arg = ast.keyword(arg="rate", value=node.args[1]) _replace_keep_prob_node(rate_arg, rate_arg.value) node.keywords.append(rate_arg) del node.args[1] logs.append((ast_edits.INFO, node.lineno, node.col_offset, "Changing keep_prob arg of tf.nn.dropout to rate, and " "recomputing value.\n")) return node
[ "def", "_dropout_transformer", "(", "parent", ",", "node", ",", "full_name", ",", "name", ",", "logs", ")", ":", "def", "_replace_keep_prob_node", "(", "parent", ",", "old_value", ")", ":", "\"\"\"Replaces old_value with 1-(old_value).\"\"\"", "one", "=", "ast", "...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/tools/compatibility/tf_upgrade_v2.py#L1811-L1852
wesnoth/wesnoth
6ccac5a5e8ff75303c9190c0da60580925cb32c0
data/tools/wesnoth/wmldata.py
python
DataSub.get_ifdefs
(self, name)
return [ifdef for ifdef in self.get_all(name) if isinstance(ifdef, DataIfDef)]
Gets all ifdefs matching the name
Gets all ifdefs matching the name
[ "Gets", "all", "ifdefs", "matching", "the", "name" ]
def get_ifdefs(self, name): """Gets all ifdefs matching the name""" return [ifdef for ifdef in self.get_all(name) if isinstance(ifdef, DataIfDef)]
[ "def", "get_ifdefs", "(", "self", ",", "name", ")", ":", "return", "[", "ifdef", "for", "ifdef", "in", "self", ".", "get_all", "(", "name", ")", "if", "isinstance", "(", "ifdef", ",", "DataIfDef", ")", "]" ]
https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmldata.py#L512-L515
lukasmonk/lucaschess
13e2e5cb13b38a720ccf897af649054a64bcb914
Code/QT/PantallaPlayPGN.py
python
PlayPGNs.recnoHash
(self, xhash)
return None
Usado desde databases-partidas
Usado desde databases-partidas
[ "Usado", "desde", "databases", "-", "partidas" ]
def recnoHash(self, xhash): """Usado desde databases-partidas""" for recno, key in enumerate(self.regKeys): if "|" in key: h = int(key.split("|")[1]) if xhash == h: return recno return None
[ "def", "recnoHash", "(", "self", ",", "xhash", ")", ":", "for", "recno", ",", "key", "in", "enumerate", "(", "self", ".", "regKeys", ")", ":", "if", "\"|\"", "in", "key", ":", "h", "=", "int", "(", "key", ".", "split", "(", "\"|\"", ")", "[", "...
https://github.com/lukasmonk/lucaschess/blob/13e2e5cb13b38a720ccf897af649054a64bcb914/Code/QT/PantallaPlayPGN.py#L33-L40
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/docbook/__init__.py
python
DocbookSlidesPdf
(env, target, source=None, *args, **kw)
return result
A pseudo-Builder, providing a Docbook toolchain for PDF slides output.
A pseudo-Builder, providing a Docbook toolchain for PDF slides output.
[ "A", "pseudo", "-", "Builder", "providing", "a", "Docbook", "toolchain", "for", "PDF", "slides", "output", "." ]
def DocbookSlidesPdf(env, target, source=None, *args, **kw): """ A pseudo-Builder, providing a Docbook toolchain for PDF slides output. """ # Init list of targets/sources target, source = __extend_targets_sources(target, source) # Init XSL stylesheet __init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_SLIDESPDF', ['slides','fo','plain.xsl']) # Setup builder __builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder) # Create targets result = [] for t,s in zip(target,source): t, stem = __ensure_suffix_stem(t, '.pdf') xsl = __builder.__call__(env, stem+'.fo', s, **kw) env.Depends(xsl, kw['DOCBOOK_XSL']) result.extend(xsl) result.extend(__fop_builder.__call__(env, t, xsl, **kw)) return result
[ "def", "DocbookSlidesPdf", "(", "env", ",", "target", ",", "source", "=", "None", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "# Init list of targets/sources", "target", ",", "source", "=", "__extend_targets_sources", "(", "target", ",", "source", ")", ...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/docbook/__init__.py#L731-L753
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Configure.py
python
ConfigurationContext.prepare_env
(self, env)
Insert *PREFIX*, *BINDIR* and *LIBDIR* values into ``env`` :type env: :py:class:`waflib.ConfigSet.ConfigSet` :param env: a ConfigSet, usually ``conf.env``
Insert *PREFIX*, *BINDIR* and *LIBDIR* values into ``env``
[ "Insert", "*", "PREFIX", "*", "*", "BINDIR", "*", "and", "*", "LIBDIR", "*", "values", "into", "env" ]
def prepare_env(self, env): """ Insert *PREFIX*, *BINDIR* and *LIBDIR* values into ``env`` :type env: :py:class:`waflib.ConfigSet.ConfigSet` :param env: a ConfigSet, usually ``conf.env`` """ if not env.PREFIX: if Options.options.prefix or Utils.is_win32: env.PREFIX = Options.options.prefix else: env.PREFIX = '/' if not env.BINDIR: if Options.options.bindir: env.BINDIR = Options.options.bindir else: env.BINDIR = Utils.subst_vars('${PREFIX}/bin', env) if not env.LIBDIR: if Options.options.libdir: env.LIBDIR = Options.options.libdir else: env.LIBDIR = Utils.subst_vars('${PREFIX}/lib%s' % Utils.lib64(), env)
[ "def", "prepare_env", "(", "self", ",", "env", ")", ":", "if", "not", "env", ".", "PREFIX", ":", "if", "Options", ".", "options", ".", "prefix", "or", "Utils", ".", "is_win32", ":", "env", ".", "PREFIX", "=", "Options", ".", "options", ".", "prefix",...
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Configure.py#L192-L213
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/extras/review.py
python
ReviewContext.compare_review_set
(self, set1, set2)
return True
Return true if the review sets specified are equal.
Return true if the review sets specified are equal.
[ "Return", "true", "if", "the", "review", "sets", "specified", "are", "equal", "." ]
def compare_review_set(self, set1, set2): """ Return true if the review sets specified are equal. """ if len(list(set1.keys())) != len(list(set2.keys())): return False for key in list(set1.keys()): if not key in set2 or set1[key] != set2[key]: return False return True
[ "def", "compare_review_set", "(", "self", ",", "set1", ",", "set2", ")", ":", "if", "len", "(", "list", "(", "set1", ".", "keys", "(", ")", ")", ")", "!=", "len", "(", "list", "(", "set2", ".", "keys", "(", ")", ")", ")", ":", "return", "False"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/review.py#L247-L255
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/xmlrpc/server.py
python
SimpleXMLRPCDispatcher._dispatch
(self, method, params)
Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called.
Dispatches the XML-RPC method.
[ "Dispatches", "the", "XML", "-", "RPC", "method", "." ]
def _dispatch(self, method, params): """Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called. """ try: # call the matching registered function func = self.funcs[method] except KeyError: pass else: if func is not None: return func(*params) raise Exception('method "%s" is not supported' % method) if self.instance is not None: if hasattr(self.instance, '_dispatch'): # call the `_dispatch` method on the instance return self.instance._dispatch(method, params) # call the instance's method directly try: func = resolve_dotted_attribute( self.instance, method, self.allow_dotted_names ) except AttributeError: pass else: if func is not None: return func(*params) raise Exception('method "%s" is not supported' % method)
[ "def", "_dispatch", "(", "self", ",", "method", ",", "params", ")", ":", "try", ":", "# call the matching registered function", "func", "=", "self", ".", "funcs", "[", "method", "]", "except", "KeyError", ":", "pass", "else", ":", "if", "func", "is", "not"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xmlrpc/server.py#L383-L432
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/layers/utils.py
python
copy_mutable_vars
(structure)
return pack_sequence_as(structure, flat_structure)
Returns vars copied from sequence without mutable property.
Returns vars copied from sequence without mutable property.
[ "Returns", "vars", "copied", "from", "sequence", "without", "mutable", "property", "." ]
def copy_mutable_vars(structure): """ Returns vars copied from sequence without mutable property. """ flat_structure = copy.copy(flatten(structure)) return pack_sequence_as(structure, flat_structure)
[ "def", "copy_mutable_vars", "(", "structure", ")", ":", "flat_structure", "=", "copy", ".", "copy", "(", "flatten", "(", "structure", ")", ")", "return", "pack_sequence_as", "(", "structure", ",", "flat_structure", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/utils.py#L217-L222
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/third_party/jedi/jedi/dynamic.py
python
search_param_memoize
(func)
return wrapper
Is only good for search params memoize, respectively the closure, because it just caches the input, not the func, like normal memoize does.
Is only good for search params memoize, respectively the closure, because it just caches the input, not the func, like normal memoize does.
[ "Is", "only", "good", "for", "search", "params", "memoize", "respectively", "the", "closure", "because", "it", "just", "caches", "the", "input", "not", "the", "func", "like", "normal", "memoize", "does", "." ]
def search_param_memoize(func): """ Is only good for search params memoize, respectively the closure, because it just caches the input, not the func, like normal memoize does. """ def wrapper(*args, **kwargs): key = (args, frozenset(kwargs.items())) if key in search_param_cache: return search_param_cache[key] else: rv = func(*args, **kwargs) search_param_cache[key] = rv return rv return wrapper
[ "def", "search_param_memoize", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "key", "=", "(", "args", ",", "frozenset", "(", "kwargs", ".", "items", "(", ")", ")", ")", "if", "key", "in", "search_para...
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/jedi/jedi/dynamic.py#L119-L132
facebook/fboss
60063db1df37c2ec0e7dcd0955c54885ea9bf7f0
build/fbcode_builder/getdeps/platform.py
python
get_available_ram
()
Returns a platform-appropriate available RAM metric in MiB.
Returns a platform-appropriate available RAM metric in MiB.
[ "Returns", "a", "platform", "-", "appropriate", "available", "RAM", "metric", "in", "MiB", "." ]
def get_available_ram() -> int: """ Returns a platform-appropriate available RAM metric in MiB. """ if sys.platform == "linux": return _get_available_ram_linux() elif sys.platform == "darwin": return _get_available_ram_macos() elif sys.platform == "win32": return _get_available_ram_windows() else: raise NotImplementedError( f"platform {sys.platform} does not have an implementation of get_available_ram" )
[ "def", "get_available_ram", "(", ")", "->", "int", ":", "if", "sys", ".", "platform", "==", "\"linux\"", ":", "return", "_get_available_ram_linux", "(", ")", "elif", "sys", ".", "platform", "==", "\"darwin\"", ":", "return", "_get_available_ram_macos", "(", ")...
https://github.com/facebook/fboss/blob/60063db1df37c2ec0e7dcd0955c54885ea9bf7f0/build/fbcode_builder/getdeps/platform.py#L133-L146
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathGeom.py
python
combineHorizontalFaces
(faces)
return horizontal
combineHorizontalFaces(faces)... This function successfully identifies and combines multiple connected faces and works on multiple independent faces with multiple connected faces within the list. The return value is a list of simplified faces. The Adaptive op is not concerned with which hole edges belong to which face. Attempts to do the same shape connecting failed with TechDraw.findShapeOutline() and PathGeom.combineConnectedShapes(), so this algorithm was created.
combineHorizontalFaces(faces)... This function successfully identifies and combines multiple connected faces and works on multiple independent faces with multiple connected faces within the list. The return value is a list of simplified faces. The Adaptive op is not concerned with which hole edges belong to which face.
[ "combineHorizontalFaces", "(", "faces", ")", "...", "This", "function", "successfully", "identifies", "and", "combines", "multiple", "connected", "faces", "and", "works", "on", "multiple", "independent", "faces", "with", "multiple", "connected", "faces", "within", "...
def combineHorizontalFaces(faces): """combineHorizontalFaces(faces)... This function successfully identifies and combines multiple connected faces and works on multiple independent faces with multiple connected faces within the list. The return value is a list of simplified faces. The Adaptive op is not concerned with which hole edges belong to which face. Attempts to do the same shape connecting failed with TechDraw.findShapeOutline() and PathGeom.combineConnectedShapes(), so this algorithm was created. """ horizontal = list() offset = 10.0 topFace = None innerFaces = list() # Verify all incoming faces are at Z=0.0 for f in faces: if f.BoundBox.ZMin != 0.0: f.translate(FreeCAD.Vector(0.0, 0.0, 0.0 - f.BoundBox.ZMin)) # Make offset compound boundbox solid and cut incoming face extrusions from it allFaces = Part.makeCompound(faces) if hasattr(allFaces, "Area") and isRoughly(allFaces.Area, 0.0): msg = translate( "PathGeom", "Zero working area to process. Check your selection and settings.", ) PathLog.info(msg) return horizontal afbb = allFaces.BoundBox bboxFace = makeBoundBoxFace(afbb, offset, -5.0) bboxSolid = bboxFace.extrude(FreeCAD.Vector(0.0, 0.0, 10.0)) extrudedFaces = list() for f in faces: extrudedFaces.append(f.extrude(FreeCAD.Vector(0.0, 0.0, 6.0))) # Fuse all extruded faces together allFacesSolid = extrudedFaces.pop() for i in range(len(extrudedFaces)): temp = extrudedFaces.pop().fuse(allFacesSolid) allFacesSolid = temp cut = bboxSolid.cut(allFacesSolid) # Debug # Part.show(cut) # FreeCAD.ActiveDocument.ActiveObject.Label = "cut" # Identify top face and floating inner faces that are the holes in incoming faces for f in cut.Faces: fbb = f.BoundBox if isRoughly(fbb.ZMin, 5.0) and isRoughly(fbb.ZMax, 5.0): if ( isRoughly(afbb.XMin - offset, fbb.XMin) and isRoughly(afbb.XMax + offset, fbb.XMax) and isRoughly(afbb.YMin - offset, fbb.YMin) and isRoughly(afbb.YMax + offset, fbb.YMax) ): topFace = f else: innerFaces.append(f) if not topFace: return horizontal outer = [Part.Face(w) for w in topFace.Wires[1:]] if outer: for f in outer: f.translate(FreeCAD.Vector(0.0, 0.0, 0.0 - f.BoundBox.ZMin)) if innerFaces: # inner = [Part.Face(f.Wire1) for f in innerFaces] inner = innerFaces for f in inner: f.translate(FreeCAD.Vector(0.0, 0.0, 0.0 - f.BoundBox.ZMin)) innerComp = Part.makeCompound(inner) outerComp = Part.makeCompound(outer) cut = outerComp.cut(innerComp) for f in cut.Faces: horizontal.append(f) else: horizontal = outer return horizontal
[ "def", "combineHorizontalFaces", "(", "faces", ")", ":", "horizontal", "=", "list", "(", ")", "offset", "=", "10.0", "topFace", "=", "None", "innerFaces", "=", "list", "(", ")", "# Verify all incoming faces are at Z=0.0", "for", "f", "in", "faces", ":", "if", ...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathGeom.py#L714-L799
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py
python
search_labels
(query='', limit=None, offset=None, strict=False, **fields)
return _do_mb_search('label', query, fields, limit, offset, strict)
Search for labels and return a dict with a 'label-list' key. *Available search fields*: {fields}
Search for labels and return a dict with a 'label-list' key.
[ "Search", "for", "labels", "and", "return", "a", "dict", "with", "a", "label", "-", "list", "key", "." ]
def search_labels(query='', limit=None, offset=None, strict=False, **fields): """Search for labels and return a dict with a 'label-list' key. *Available search fields*: {fields}""" return _do_mb_search('label', query, fields, limit, offset, strict)
[ "def", "search_labels", "(", "query", "=", "''", ",", "limit", "=", "None", ",", "offset", "=", "None", ",", "strict", "=", "False", ",", "*", "*", "fields", ")", ":", "return", "_do_mb_search", "(", "'label'", ",", "query", ",", "fields", ",", "limi...
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py#L932-L936
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py
python
depthwise_conv_2d_nhwc_hwc
( I=TensorDef(T1, S.N, S.OH * S.SH + S.KH * S.DH, S.OW * S.SW + S.KW * S.DW, S.IC), K=TensorDef(T2, S.KH, S.KW, S.IC), O=TensorDef(U, S.N, S.OH, S.OW, S.IC, output=True), strides=IndexAttrDef(S.SH, S.SW), dilations=IndexAttrDef(S.DH, S.DW))
Performs depth-wise 2-D convolution. Numeric casting is performed on the operands to the inner multiply, promoting them to the same data type as the accumulator/output. Multiplier is set to 1 which is a special case for most depthwise convolutions.
Performs depth-wise 2-D convolution.
[ "Performs", "depth", "-", "wise", "2", "-", "D", "convolution", "." ]
def depthwise_conv_2d_nhwc_hwc( I=TensorDef(T1, S.N, S.OH * S.SH + S.KH * S.DH, S.OW * S.SW + S.KW * S.DW, S.IC), K=TensorDef(T2, S.KH, S.KW, S.IC), O=TensorDef(U, S.N, S.OH, S.OW, S.IC, output=True), strides=IndexAttrDef(S.SH, S.SW), dilations=IndexAttrDef(S.DH, S.DW)): """Performs depth-wise 2-D convolution. Numeric casting is performed on the operands to the inner multiply, promoting them to the same data type as the accumulator/output. Multiplier is set to 1 which is a special case for most depthwise convolutions. """ implements(ConvolutionOpInterface) domain(D.n, D.oh, D.ow, D.ic, D.kh, D.kw) O[D.n, D.oh, D.ow, D.ic] += TypeFn.cast( U, I[D.n, D.oh * S.SH + D.kh * S.DH, D.ow * S.SW + D.kw * S.DW, D.ic]) * TypeFn.cast(U, K[D.kh, D.kw, D.ic])
[ "def", "depthwise_conv_2d_nhwc_hwc", "(", "I", "=", "TensorDef", "(", "T1", ",", "S", ".", "N", ",", "S", ".", "OH", "*", "S", ".", "SH", "+", "S", ".", "KH", "*", "S", ".", "DH", ",", "S", ".", "OW", "*", "S", ".", "SW", "+", "S", ".", "...
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py#L360-L377
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
tools/coverage/cuda_clean.py
python
clean
(pull_id)
Args: pull_id (int): Pull id. Returns: None.
Args: pull_id (int): Pull id.
[ "Args", ":", "pull_id", "(", "int", ")", ":", "Pull", "id", "." ]
def clean(pull_id): """ Args: pull_id (int): Pull id. Returns: None. """ changed = [] for file in get_files(pull_id): #changed.append('/paddle/build/{}.gcda'.format(file)) changed.append(file) for parent, dirs, files in os.walk('/paddle/build/'): for gcda in files: if gcda.endswith('.gcda'): file_name = gcda.replace('.gcda', '') dir_name_list = parent.replace('/paddle/build/', '').split('/') dir_name_list = dir_name_list[:-2] dir_name = '/'.join(dir_name_list) src_name = dir_name + '/' + file_name # remove no changed gcda if src_name not in changed: unused_file = parent + '/' + gcda #print unused_file os.remove(gcda) else: print(src_name)
[ "def", "clean", "(", "pull_id", ")", ":", "changed", "=", "[", "]", "for", "file", "in", "get_files", "(", "pull_id", ")", ":", "#changed.append('/paddle/build/{}.gcda'.format(file))", "changed", ".", "append", "(", "file", ")", "for", "parent", ",", "dirs", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/tools/coverage/cuda_clean.py#L56-L87
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/cgi.py
python
FieldStorage.__contains__
(self, key)
return any(item.name == key for item in self.list)
Dictionary style __contains__ method.
Dictionary style __contains__ method.
[ "Dictionary", "style", "__contains__", "method", "." ]
def __contains__(self, key): """Dictionary style __contains__ method.""" if self.list is None: raise TypeError("not indexable") return any(item.name == key for item in self.list)
[ "def", "__contains__", "(", "self", ",", "key", ")", ":", "if", "self", ".", "list", "is", "None", ":", "raise", "TypeError", "(", "\"not indexable\"", ")", "return", "any", "(", "item", ".", "name", "==", "key", "for", "item", "in", "self", ".", "li...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/cgi.py#L587-L591
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/summary/event_accumulator.py
python
EventAccumulator.Tags
(self)
return {IMAGES: self._images.Keys(), AUDIO: self._audio.Keys(), HISTOGRAMS: self._histograms.Keys(), SCALARS: self._scalars.Keys(), COMPRESSED_HISTOGRAMS: self._compressed_histograms.Keys(), GRAPH: self._graph is not None, RUN_METADATA: list(self._tagged_metadata.keys())}
Return all tags found in the value stream. Returns: A `{tagType: ['list', 'of', 'tags']}` dictionary.
Return all tags found in the value stream.
[ "Return", "all", "tags", "found", "in", "the", "value", "stream", "." ]
def Tags(self): """Return all tags found in the value stream. Returns: A `{tagType: ['list', 'of', 'tags']}` dictionary. """ return {IMAGES: self._images.Keys(), AUDIO: self._audio.Keys(), HISTOGRAMS: self._histograms.Keys(), SCALARS: self._scalars.Keys(), COMPRESSED_HISTOGRAMS: self._compressed_histograms.Keys(), GRAPH: self._graph is not None, RUN_METADATA: list(self._tagged_metadata.keys())}
[ "def", "Tags", "(", "self", ")", ":", "return", "{", "IMAGES", ":", "self", ".", "_images", ".", "Keys", "(", ")", ",", "AUDIO", ":", "self", ".", "_audio", ".", "Keys", "(", ")", ",", "HISTOGRAMS", ":", "self", ".", "_histograms", ".", "Keys", "...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/summary/event_accumulator.py#L262-L274
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILL_common.py
python
WSCleanup.__init__
(self, cleanupMode, deleteAlgorithmLogging)
Initialize an instance of the class.
Initialize an instance of the class.
[ "Initialize", "an", "instance", "of", "the", "class", "." ]
def __init__(self, cleanupMode, deleteAlgorithmLogging): """Initialize an instance of the class.""" self._deleteAlgorithmLogging = deleteAlgorithmLogging self._doDelete = cleanupMode == self.ON self._protected = set() self._toBeDeleted = set()
[ "def", "__init__", "(", "self", ",", "cleanupMode", ",", "deleteAlgorithmLogging", ")", ":", "self", ".", "_deleteAlgorithmLogging", "=", "deleteAlgorithmLogging", "self", ".", "_doDelete", "=", "cleanupMode", "==", "self", ".", "ON", "self", ".", "_protected", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryILL_common.py#L202-L207
keyboardio/Kaleidoscope
d59604e98b2439d108647f15be52984a6837d360
bin/cpplint.py
python
_CppLintState.IncrementErrorCount
(self, category)
Bumps the module's error statistic.
Bumps the module's error statistic.
[ "Bumps", "the", "module", "s", "error", "statistic", "." ]
def IncrementErrorCount(self, category): """Bumps the module's error statistic.""" self.error_count += 1 if self.counting in ('toplevel', 'detailed'): if self.counting != 'detailed': category = category.split('/')[0] if category not in self.errors_by_category: self.errors_by_category[category] = 0 self.errors_by_category[category] += 1
[ "def", "IncrementErrorCount", "(", "self", ",", "category", ")", ":", "self", ".", "error_count", "+=", "1", "if", "self", ".", "counting", "in", "(", "'toplevel'", ",", "'detailed'", ")", ":", "if", "self", ".", "counting", "!=", "'detailed'", ":", "cat...
https://github.com/keyboardio/Kaleidoscope/blob/d59604e98b2439d108647f15be52984a6837d360/bin/cpplint.py#L1083-L1091
pgRouting/osm2pgrouting
8491929fc4037d308f271e84d59bb96da3c28aa2
tools/cpplint.py
python
FileInfo.BaseName
(self)
return self.Split()[1]
File base name - text after the final slash, before the final period.
File base name - text after the final slash, before the final period.
[ "File", "base", "name", "-", "text", "after", "the", "final", "slash", "before", "the", "final", "period", "." ]
def BaseName(self): """File base name - text after the final slash, before the final period.""" return self.Split()[1]
[ "def", "BaseName", "(", "self", ")", ":", "return", "self", ".", "Split", "(", ")", "[", "1", "]" ]
https://github.com/pgRouting/osm2pgrouting/blob/8491929fc4037d308f271e84d59bb96da3c28aa2/tools/cpplint.py#L1045-L1047
cathywu/Sentiment-Analysis
eb501fd1375c0c3f3ab430f963255f1bb858e659
PyML-0.7.9/PyML/evaluators/assess.py
python
stratifiedCV
(classifier, data, numFolds = 5, **args)
return cvFromFolds(classifier, data, trainingPatterns, testingPatterns, **args)
perform k-fold stratified cross-validation; in each fold the number of patterns from each class is proportional to the relative fraction of the class in the dataset :Parameters: - `classifier` - a classifier template - `data` - a dataset - `numFolds` - number of cross validation folds (default = 5) :Returns: a Results object. :Keywords: - `numFolds` - number of cross-validation folds -- overrides the numFolds parameter - `seed` - random number generator seed - `trainingAllFolds` - a list of patterns that are to be used as training examples in all CV folds. - `intermediateFile` - a file name to save intermediate results under if this argument is not given, not intermediate results are saved - `foldsToPerform` - number of folds to actually perform (in case you're doing n fold CV, and want to save time, and only do some of the folds)
perform k-fold stratified cross-validation; in each fold the number of patterns from each class is proportional to the relative fraction of the class in the dataset
[ "perform", "k", "-", "fold", "stratified", "cross", "-", "validation", ";", "in", "each", "fold", "the", "number", "of", "patterns", "from", "each", "class", "is", "proportional", "to", "the", "relative", "fraction", "of", "the", "class", "in", "the", "dat...
def stratifiedCV(classifier, data, numFolds = 5, **args) : """perform k-fold stratified cross-validation; in each fold the number of patterns from each class is proportional to the relative fraction of the class in the dataset :Parameters: - `classifier` - a classifier template - `data` - a dataset - `numFolds` - number of cross validation folds (default = 5) :Returns: a Results object. :Keywords: - `numFolds` - number of cross-validation folds -- overrides the numFolds parameter - `seed` - random number generator seed - `trainingAllFolds` - a list of patterns that are to be used as training examples in all CV folds. - `intermediateFile` - a file name to save intermediate results under if this argument is not given, not intermediate results are saved - `foldsToPerform` - number of folds to actually perform (in case you're doing n fold CV, and want to save time, and only do some of the folds) """ if 'numFolds' in args : numFolds = args['numFolds'] if 'seed' in args : random.seed(args['seed']) if 'trainingAllFolds' in args : trainingAllFolds = args['trainingAllFolds'] else : trainingAllFolds = [] foldsToPerform = numFolds if 'foldsToPerform' in args : foldsToPerform = args['foldsToPerform'] if foldsToPerform > numFolds : raise ValueError, 'foldsToPerform > numFolds' trainingAllFoldsDict = misc.list2dict(trainingAllFolds) labels = data.labels p = [[] for i in range(labels.numClasses)] classFoldSize = [int(labels.classSize[k] / numFolds) for k in range(labels.numClasses)] for i in range(len(data)): if i not in trainingAllFoldsDict : p[labels.Y[i]].append(i) for k in range(labels.numClasses): random.shuffle(p[k]) trainingPatterns = [[] for i in range(foldsToPerform)] testingPatterns = [[] for i in range(foldsToPerform)] for fold in range(foldsToPerform) : for k in range(labels.numClasses) : classFoldStart = classFoldSize[k] * fold if fold < numFolds-1: classFoldEnd = classFoldSize[k] * (fold + 1) else: classFoldEnd = labels.classSize[k] testingPatterns[fold].extend(p[k][classFoldStart:classFoldEnd]) if fold > 0: trainingPatterns[fold].extend(p[k][0:classFoldStart] + p[k][classFoldEnd:labels.classSize[k]]) else: trainingPatterns[fold].extend(p[k][classFoldEnd:labels.classSize[k]]) if len(trainingPatterns) > 0 : for fold in range(len(trainingPatterns)) : trainingPatterns[fold].extend(trainingAllFolds) return cvFromFolds(classifier, data, trainingPatterns, testingPatterns, **args)
[ "def", "stratifiedCV", "(", "classifier", ",", "data", ",", "numFolds", "=", "5", ",", "*", "*", "args", ")", ":", "if", "'numFolds'", "in", "args", ":", "numFolds", "=", "args", "[", "'numFolds'", "]", "if", "'seed'", "in", "args", ":", "random", "....
https://github.com/cathywu/Sentiment-Analysis/blob/eb501fd1375c0c3f3ab430f963255f1bb858e659/PyML-0.7.9/PyML/evaluators/assess.py#L205-L275
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
VarVScrollHelper.ScrollRows
(*args, **kwargs)
return _windows_.VarVScrollHelper_ScrollRows(*args, **kwargs)
ScrollRows(self, int rows) -> bool
ScrollRows(self, int rows) -> bool
[ "ScrollRows", "(", "self", "int", "rows", ")", "-", ">", "bool" ]
def ScrollRows(*args, **kwargs): """ScrollRows(self, int rows) -> bool""" return _windows_.VarVScrollHelper_ScrollRows(*args, **kwargs)
[ "def", "ScrollRows", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "VarVScrollHelper_ScrollRows", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L2281-L2283
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/compiler/pyassem.py
python
PyFlowGraph._lookupName
(self, name, list)
return end
Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before comparing the values.
Return index of name in list, appending if necessary
[ "Return", "index", "of", "name", "in", "list", "appending", "if", "necessary" ]
def _lookupName(self, name, list): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately, so it does an explicit type comparison before comparing the values. """ t = type(name) for i in range(len(list)): if t == type(list[i]) and list[i] == name: return i end = len(list) list.append(name) return end
[ "def", "_lookupName", "(", "self", ",", "name", ",", "list", ")", ":", "t", "=", "type", "(", "name", ")", "for", "i", "in", "range", "(", "len", "(", "list", ")", ")", ":", "if", "t", "==", "type", "(", "list", "[", "i", "]", ")", "and", "...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/compiler/pyassem.py#L432-L447
hunterlew/mstar_deeplearning_project
3761624dcbd7d44af257200542d13d1444dc634a
classification/caffe/examples/mstar/Log/parse_log.py
python
parse_log
(path_to_log)
return train_dict_list, test_dict_list
Parse log file Returns (train_dict_list, test_dict_list) train_dict_list and test_dict_list are lists of dicts that define the table rows
Parse log file Returns (train_dict_list, test_dict_list)
[ "Parse", "log", "file", "Returns", "(", "train_dict_list", "test_dict_list", ")" ]
def parse_log(path_to_log): """Parse log file Returns (train_dict_list, test_dict_list) train_dict_list and test_dict_list are lists of dicts that define the table rows """ regex_iteration = re.compile('Iteration (\d+)') regex_train_output = re.compile('Train net output #(\d+): (\S+) = ([\.\deE+-]+)') regex_test_output = re.compile('Test net output #(\d+): (\S+) = ([\.\deE+-]+)') regex_learning_rate = re.compile('lr = ([-+]?[0-9]*\.?[0-9]+([eE]?[-+]?[0-9]+)?)') # Pick out lines of interest iteration = -1 learning_rate = float('NaN') train_dict_list = [] test_dict_list = [] train_row = None test_row = None logfile_year = extract_seconds.get_log_created_year(path_to_log) with open(path_to_log) as f: start_time = extract_seconds.get_start_time(f, logfile_year) last_time = start_time for line in f: iteration_match = regex_iteration.search(line) if iteration_match: iteration = float(iteration_match.group(1)) if iteration == -1: # Only start parsing for other stuff if we've found the first # iteration continue try: time = extract_seconds.extract_datetime_from_line(line, logfile_year) except ValueError: # Skip lines with bad formatting, for example when resuming solver continue # if it's another year if time.month < last_time.month: logfile_year += 1 time = extract_seconds.extract_datetime_from_line(line, logfile_year) last_time = time seconds = (time - start_time).total_seconds() learning_rate_match = regex_learning_rate.search(line) if learning_rate_match: learning_rate = float(learning_rate_match.group(1)) train_dict_list, train_row = parse_line_for_net_output( regex_train_output, train_row, train_dict_list, line, iteration, seconds, learning_rate ) test_dict_list, test_row = parse_line_for_net_output( regex_test_output, test_row, test_dict_list, line, iteration, seconds, learning_rate ) fix_initial_nan_learning_rate(train_dict_list) fix_initial_nan_learning_rate(test_dict_list) return train_dict_list, test_dict_list
[ "def", "parse_log", "(", "path_to_log", ")", ":", "regex_iteration", "=", "re", ".", "compile", "(", "'Iteration (\\d+)'", ")", "regex_train_output", "=", "re", ".", "compile", "(", "'Train net output #(\\d+): (\\S+) = ([\\.\\deE+-]+)'", ")", "regex_test_output", "=", ...
https://github.com/hunterlew/mstar_deeplearning_project/blob/3761624dcbd7d44af257200542d13d1444dc634a/classification/caffe/examples/mstar/Log/parse_log.py#L17-L83
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/third_party/jinja2/environment.py
python
Environment.join_path
(self, template, parent)
return template
Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the `template` parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name. Subclasses may override this method and implement template path joining here.
Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the `template` parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name.
[ "Join", "a", "template", "with", "the", "parent", ".", "By", "default", "all", "the", "lookups", "are", "relative", "to", "the", "loader", "root", "so", "this", "method", "returns", "the", "template", "parameter", "unchanged", "but", "if", "the", "paths", ...
def join_path(self, template, parent): """Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the `template` parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name. Subclasses may override this method and implement template path joining here. """ return template
[ "def", "join_path", "(", "self", ",", "template", ",", "parent", ")", ":", "return", "template" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/environment.py#L782-L792
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/iam/connection.py
python
IAMConnection.delete_signing_cert
(self, cert_id, user_name=None)
return self.get_response('DeleteSigningCertificate', params)
Delete a signing certificate associated with a user. If the user_name is not specified, it is determined implicitly based on the AWS Access Key ID used to sign the request. :type user_name: string :param user_name: The username of the user :type cert_id: string :param cert_id: The ID of the certificate.
Delete a signing certificate associated with a user.
[ "Delete", "a", "signing", "certificate", "associated", "with", "a", "user", "." ]
def delete_signing_cert(self, cert_id, user_name=None): """ Delete a signing certificate associated with a user. If the user_name is not specified, it is determined implicitly based on the AWS Access Key ID used to sign the request. :type user_name: string :param user_name: The username of the user :type cert_id: string :param cert_id: The ID of the certificate. """ params = {'CertificateId': cert_id} if user_name: params['UserName'] = user_name return self.get_response('DeleteSigningCertificate', params)
[ "def", "delete_signing_cert", "(", "self", ",", "cert_id", ",", "user_name", "=", "None", ")", ":", "params", "=", "{", "'CertificateId'", ":", "cert_id", "}", "if", "user_name", ":", "params", "[", "'UserName'", "]", "=", "user_name", "return", "self", "....
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/iam/connection.py#L679-L696
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/configparser.py
python
ConfigParser.add_section
(self, section)
Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.
Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.
[ "Create", "a", "new", "section", "in", "the", "configuration", ".", "Extends", "RawConfigParser", ".", "add_section", "by", "validating", "if", "the", "section", "name", "is", "a", "string", "." ]
def add_section(self, section): """Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.""" self._validate_value_types(section=section) super().add_section(section)
[ "def", "add_section", "(", "self", ",", "section", ")", ":", "self", ".", "_validate_value_types", "(", "section", "=", "section", ")", "super", "(", ")", ".", "add_section", "(", "section", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/configparser.py#L1200-L1205
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/py/editor.py
python
EditorFrame._setup
(self)
Setup prior to first buffer creation. Useful for subclasses.
Setup prior to first buffer creation.
[ "Setup", "prior", "to", "first", "buffer", "creation", "." ]
def _setup(self): """Setup prior to first buffer creation. Useful for subclasses.""" pass
[ "def", "_setup", "(", "self", ")", ":", "pass" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/editor.py#L38-L42
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
chrome/common/extensions/docs/build/directory.py
python
Sample._uses_browser_action
(self)
return self._manifest.has_key('browser_action')
Returns true if the extension defines a browser action.
Returns true if the extension defines a browser action.
[ "Returns", "true", "if", "the", "extension", "defines", "a", "browser", "action", "." ]
def _uses_browser_action(self): """ Returns true if the extension defines a browser action. """ return self._manifest.has_key('browser_action')
[ "def", "_uses_browser_action", "(", "self", ")", ":", "return", "self", ".", "_manifest", ".", "has_key", "(", "'browser_action'", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/chrome/common/extensions/docs/build/directory.py#L731-L733
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
uCSIsBlock
(code, block)
return ret
Check whether the character is part of the UCS Block
Check whether the character is part of the UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "the", "UCS", "Block" ]
def uCSIsBlock(code, block): """Check whether the character is part of the UCS Block """ ret = libxml2mod.xmlUCSIsBlock(code, block) return ret
[ "def", "uCSIsBlock", "(", "code", ",", "block", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsBlock", "(", "code", ",", "block", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L2143-L2146
facebookresearch/habitat-sim
63b6c71d9ca8adaefb140b198196f5d0ca1f1e34
src_python/habitat_sim/robots/mobile_manipulator.py
python
MobileManipulator._update_motor_settings_cache
(self)
Updates the JointMotorSettings cache for cheaper future updates
Updates the JointMotorSettings cache for cheaper future updates
[ "Updates", "the", "JointMotorSettings", "cache", "for", "cheaper", "future", "updates" ]
def _update_motor_settings_cache(self): """Updates the JointMotorSettings cache for cheaper future updates""" self.joint_motors = {} for motor_id, joint_id in self.sim_obj.existing_joint_motor_ids.items(): self.joint_motors[joint_id] = ( motor_id, self.sim_obj.get_joint_motor_settings(motor_id), )
[ "def", "_update_motor_settings_cache", "(", "self", ")", ":", "self", ".", "joint_motors", "=", "{", "}", "for", "motor_id", ",", "joint_id", "in", "self", ".", "sim_obj", ".", "existing_joint_motor_ids", ".", "items", "(", ")", ":", "self", ".", "joint_moto...
https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/src_python/habitat_sim/robots/mobile_manipulator.py#L533-L540
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/binomial.py
python
Binomial.std
(self, name="std")
Standard deviation of the distribution.
Standard deviation of the distribution.
[ "Standard", "deviation", "of", "the", "distribution", "." ]
def std(self, name="std"): """Standard deviation of the distribution.""" with ops.name_scope(self.name): with ops.op_scope([self._n, self._p], name): return math_ops.sqrt(self.variance())
[ "def", "std", "(", "self", ",", "name", "=", "\"std\"", ")", ":", "with", "ops", ".", "name_scope", "(", "self", ".", "name", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "self", ".", "_n", ",", "self", ".", "_p", "]", ",", "name", ")", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/binomial.py#L245-L249
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
TranslationUnit.codeComplete
(self, path, line, column, unsaved_files=None, include_macros=False, include_code_patterns=False, include_brief_comments=False)
return None
Code complete in this translation unit. In-memory contents for files can be provided by passing a list of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects.
Code complete in this translation unit.
[ "Code", "complete", "in", "this", "translation", "unit", "." ]
def codeComplete(self, path, line, column, unsaved_files=None, include_macros=False, include_code_patterns=False, include_brief_comments=False): """ Code complete in this translation unit. In-memory contents for files can be provided by passing a list of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ options = 0 if include_macros: options += 1 if include_code_patterns: options += 2 if include_brief_comments: options += 4 if unsaved_files is None: unsaved_files = [] unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,value) in enumerate(unsaved_files): if not isinstance(value, str): # FIXME: It would be great to support an efficient version # of this, one day. value = value.read() print value if not isinstance(value, str): raise TypeError,'Unexpected unsaved file contents.' unsaved_files_array[i].name = name unsaved_files_array[i].contents = value unsaved_files_array[i].length = len(value) ptr = conf.lib.clang_codeCompleteAt(self, path, line, column, unsaved_files_array, len(unsaved_files), options) if ptr: return CodeCompletionResults(ptr) return None
[ "def", "codeComplete", "(", "self", ",", "path", ",", "line", ",", "column", ",", "unsaved_files", "=", "None", ",", "include_macros", "=", "False", ",", "include_code_patterns", "=", "False", ",", "include_brief_comments", "=", "False", ")", ":", "options", ...
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L2426-L2469
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/configdialog.py
python
HighPage.save_as_new_theme
(self)
Prompt for new theme name and create the theme. Methods: get_new_theme_name create_new
Prompt for new theme name and create the theme.
[ "Prompt", "for", "new", "theme", "name", "and", "create", "the", "theme", "." ]
def save_as_new_theme(self): """Prompt for new theme name and create the theme. Methods: get_new_theme_name create_new """ new_theme_name = self.get_new_theme_name('New Theme Name:') if new_theme_name: self.create_new(new_theme_name)
[ "def", "save_as_new_theme", "(", "self", ")", ":", "new_theme_name", "=", "self", ".", "get_new_theme_name", "(", "'New Theme Name:'", ")", "if", "new_theme_name", ":", "self", ".", "create_new", "(", "new_theme_name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/configdialog.py#L1137-L1146
zeroc-ice/ice
6df7df6039674d58fb5ab9a08e46f28591a210f7
python/python/Ice/__init__.py
python
Object.ice_staticId
()
return '::Ice::Object'
Obtains the type id of this Slice class or interface. Returns: The type id.
Obtains the type id of this Slice class or interface. Returns: The type id.
[ "Obtains", "the", "type", "id", "of", "this", "Slice", "class", "or", "interface", ".", "Returns", ":", "The", "type", "id", "." ]
def ice_staticId(): '''Obtains the type id of this Slice class or interface. Returns: The type id. ''' return '::Ice::Object'
[ "def", "ice_staticId", "(", ")", ":", "return", "'::Ice::Object'" ]
https://github.com/zeroc-ice/ice/blob/6df7df6039674d58fb5ab9a08e46f28591a210f7/python/python/Ice/__init__.py#L399-L404
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Tools/fc.py
python
fc_hook
(self, node)
return self.create_compiled_task('fc', node)
Bind the typical Fortran file extensions to the creation of a :py:class:`waflib.Tools.fc.fc` instance
Bind the typical Fortran file extensions to the creation of a :py:class:`waflib.Tools.fc.fc` instance
[ "Bind", "the", "typical", "Fortran", "file", "extensions", "to", "the", "creation", "of", "a", ":", "py", ":", "class", ":", "waflib", ".", "Tools", ".", "fc", ".", "fc", "instance" ]
def fc_hook(self, node): "Bind the typical Fortran file extensions to the creation of a :py:class:`waflib.Tools.fc.fc` instance" return self.create_compiled_task('fc', node)
[ "def", "fc_hook", "(", "self", ",", "node", ")", ":", "return", "self", ".", "create_compiled_task", "(", "'fc'", ",", "node", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/fc.py#L27-L29
xhzdeng/crpn
a5aef0f80dbe486103123f740c634fb01e6cc9a1
caffe-fast-rcnn/scripts/cpp_lint.py
python
GetPreviousNonBlankLine
(clean_lines, linenum)
return ('', -1)
Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line.
Return the most recent non-blank line and its line number.
[ "Return", "the", "most", "recent", "non", "-", "blank", "line", "and", "its", "line", "number", "." ]
def GetPreviousNonBlankLine(clean_lines, linenum): """Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line. """ prevlinenum = linenum - 1 while prevlinenum >= 0: prevline = clean_lines.elided[prevlinenum] if not IsBlankLine(prevline): # if not a blank line... return (prevline, prevlinenum) prevlinenum -= 1 return ('', -1)
[ "def", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", ":", "prevlinenum", "=", "linenum", "-", "1", "while", "prevlinenum", ">=", "0", ":", "prevline", "=", "clean_lines", ".", "elided", "[", "prevlinenum", "]", "if", "not", "IsBlankLine",...
https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/caffe-fast-rcnn/scripts/cpp_lint.py#L3050-L3070
redpony/cdec
f7c4899b174d86bc70b40b1cae68dcad364615cb
python/cdec/configobj.py
python
Section.update
(self, indict)
A version of update that uses our ``__setitem__``.
A version of update that uses our ``__setitem__``.
[ "A", "version", "of", "update", "that", "uses", "our", "__setitem__", "." ]
def update(self, indict): """ A version of update that uses our ``__setitem__``. """ for entry in indict: self[entry] = indict[entry]
[ "def", "update", "(", "self", ",", "indict", ")", ":", "for", "entry", "in", "indict", ":", "self", "[", "entry", "]", "=", "indict", "[", "entry", "]" ]
https://github.com/redpony/cdec/blob/f7c4899b174d86bc70b40b1cae68dcad364615cb/python/cdec/configobj.py#L660-L665
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Node/FS.py
python
Dir.get_found_includes
(self, env, scanner, path)
return scanner(self, env, path)
Return this directory's implicit dependencies. We don't bother caching the results because the scan typically shouldn't be requested more than once (as opposed to scanning .h file contents, which can be requested as many times as the files is #included by other files).
Return this directory's implicit dependencies.
[ "Return", "this", "directory", "s", "implicit", "dependencies", "." ]
def get_found_includes(self, env, scanner, path): """Return this directory's implicit dependencies. We don't bother caching the results because the scan typically shouldn't be requested more than once (as opposed to scanning .h file contents, which can be requested as many times as the files is #included by other files). """ if not scanner: return [] # Clear cached info for this Dir. If we already visited this # directory on our walk down the tree (because we didn't know at # that point it was being used as the source for another Node) # then we may have calculated build signature before realizing # we had to scan the disk. Now that we have to, though, we need # to invalidate the old calculated signature so that any node # dependent on our directory structure gets one that includes # info about everything on disk. self.clear() return scanner(self, env, path)
[ "def", "get_found_includes", "(", "self", ",", "env", ",", "scanner", ",", "path", ")", ":", "if", "not", "scanner", ":", "return", "[", "]", "# Clear cached info for this Dir. If we already visited this", "# directory on our walk down the tree (because we didn't know at", ...
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Node/FS.py#L1768-L1787
KhronosGroup/SPIRV-Tools
940127a77d3ad795a4a1422fbeaad50c9f19f2ea
utils/generate_grammar_tables.py
python
get_extension_array_name
(extensions)
Returns the name of the array containing all the given extensions. Args: - extensions: a sequence of extension names
Returns the name of the array containing all the given extensions.
[ "Returns", "the", "name", "of", "the", "array", "containing", "all", "the", "given", "extensions", "." ]
def get_extension_array_name(extensions): """Returns the name of the array containing all the given extensions. Args: - extensions: a sequence of extension names """ if not extensions: return 'nullptr' else: return '{}_exts_{}'.format( PYGEN_VARIABLE_PREFIX, ''.join(extensions))
[ "def", "get_extension_array_name", "(", "extensions", ")", ":", "if", "not", "extensions", ":", "return", "'nullptr'", "else", ":", "return", "'{}_exts_{}'", ".", "format", "(", "PYGEN_VARIABLE_PREFIX", ",", "''", ".", "join", "(", "extensions", ")", ")" ]
https://github.com/KhronosGroup/SPIRV-Tools/blob/940127a77d3ad795a4a1422fbeaad50c9f19f2ea/utils/generate_grammar_tables.py#L122-L132
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/make_archive.py
python
make_zip_archive
(opts)
Generate the zip archive. Given the parsed options, generates the 'opt.output_filename' zipfile containing all the files in 'opt.input_filename' renamed according to the mappings in 'opts.transformations'. All files in 'opt.output_filename' are renamed before being written into the zipfile.
Generate the zip archive.
[ "Generate", "the", "zip", "archive", "." ]
def make_zip_archive(opts): """Generate the zip archive. Given the parsed options, generates the 'opt.output_filename' zipfile containing all the files in 'opt.input_filename' renamed according to the mappings in 'opts.transformations'. All files in 'opt.output_filename' are renamed before being written into the zipfile. """ archive = open_zip_archive_for_write(opts.output_filename) try: for input_filename in opts.input_filenames: archive.add(input_filename, arcname=get_preferred_filename( input_filename, opts.transformations)) finally: archive.close()
[ "def", "make_zip_archive", "(", "opts", ")", ":", "archive", "=", "open_zip_archive_for_write", "(", "opts", ".", "output_filename", ")", "try", ":", "for", "input_filename", "in", "opts", ".", "input_filenames", ":", "archive", ".", "add", "(", "input_filename"...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/make_archive.py#L116-L132
Komnomnomnom/swigibpy
cfd307fdbfaffabc69a2dc037538d7e34a8b8daf
swigibpy.py
python
EClientSocketBase.checkMessages
(self)
return _swigibpy.EClientSocketBase_checkMessages(self)
checkMessages(EClientSocketBase self) -> bool
checkMessages(EClientSocketBase self) -> bool
[ "checkMessages", "(", "EClientSocketBase", "self", ")", "-", ">", "bool" ]
def checkMessages(self): """checkMessages(EClientSocketBase self) -> bool""" return _swigibpy.EClientSocketBase_checkMessages(self)
[ "def", "checkMessages", "(", "self", ")", ":", "return", "_swigibpy", ".", "EClientSocketBase_checkMessages", "(", "self", ")" ]
https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L1492-L1494
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/concurrent/futures/process.py
python
_process_chunk
(fn, chunk)
return [fn(*args) for args in chunk]
Processes a chunk of an iterable passed to map. Runs the function passed to map() on a chunk of the iterable passed to map. This function is run in a separate process.
Processes a chunk of an iterable passed to map.
[ "Processes", "a", "chunk", "of", "an", "iterable", "passed", "to", "map", "." ]
def _process_chunk(fn, chunk): """ Processes a chunk of an iterable passed to map. Runs the function passed to map() on a chunk of the iterable passed to map. This function is run in a separate process. """ return [fn(*args) for args in chunk]
[ "def", "_process_chunk", "(", "fn", ",", "chunk", ")", ":", "return", "[", "fn", "(", "*", "args", ")", "for", "args", "in", "chunk", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/concurrent/futures/process.py#L189-L198
nileshkulkarni/csm
0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc
csm/utils/bird_vis.py
python
vis_vert2kp
(verts, vert2kp, face, mvs=None)
verts: N x 3 vert2kp: K x N For each keypoint, visualize its weights on each vertex. Base color is white, pick a color for each kp. Using the weights, interpolate between base and color.
verts: N x 3 vert2kp: K x N
[ "verts", ":", "N", "x", "3", "vert2kp", ":", "K", "x", "N" ]
def vis_vert2kp(verts, vert2kp, face, mvs=None): """ verts: N x 3 vert2kp: K x N For each keypoint, visualize its weights on each vertex. Base color is white, pick a color for each kp. Using the weights, interpolate between base and color. """ from psbody.mesh.mesh import Mesh from psbody.mesh.meshviewer import MeshViewer, MeshViewers from psbody.mesh.sphere import Sphere num_kp = vert2kp.shape[0] if mvs is None: mvs = MeshViewers((4, 4)) # mv = MeshViewer() # Generate colors import pylab cm = pylab.get_cmap('gist_rainbow') cms = 255 * np.array([cm(1. * i / num_kp)[:3] for i in range(num_kp)]) base = np.zeros((1, 3)) * 255 # base = np.ones((1, 3)) * 255 verts = convert2np(verts) vert2kp = convert2np(vert2kp) num_row = len(mvs) num_col = len(mvs[0]) colors = [] for k in range(num_kp): # Nx1 for this kp. weights = vert2kp[k].reshape(-1, 1) # So we can see it,, weights = weights / weights.max() cm = cms[k, None] # Simple linear interpolation,, # cs = np.uint8((1-weights) * base + weights * cm) # In [0, 1] cs = ((1 - weights) * base + weights * cm) / 255. colors.append(cs) # sph = [Sphere(center=jc, radius=.03).to_mesh(c/255.) for jc, c in zip(vert,cs)] # mvs[int(k/4)][k%4].set_dynamic_meshes(sph) mvs[int(k % num_row)][int(k / num_row)].set_dynamic_meshes( [Mesh(verts, face, vc=cs)])
[ "def", "vis_vert2kp", "(", "verts", ",", "vert2kp", ",", "face", ",", "mvs", "=", "None", ")", ":", "from", "psbody", ".", "mesh", ".", "mesh", "import", "Mesh", "from", "psbody", ".", "mesh", ".", "meshviewer", "import", "MeshViewer", ",", "MeshViewers"...
https://github.com/nileshkulkarni/csm/blob/0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc/csm/utils/bird_vis.py#L636-L683
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/third_party/Python/module/pexpect-2.4/examples/rippy.py
python
compress_video
( video_source_filename, video_final_filename, video_target_size, audio_id=128, video_bitrate=1000, video_codec='mpeg4', audio_codec='mp3', video_fourcc_override='FMP4', video_gray_flag=0, video_crop_area=None, video_aspect_ratio='16/9', video_scale=None, video_encode_passes=2, video_deinterlace_flag=0, audio_volume_boost=None, audio_sample_rate=None, audio_bitrate=None, seek_skip=None, seek_length=None, video_chapter=None, verbose_flag=0, dry_run_flag=0)
return
This compresses the video and audio of the given source video filename to the transcoded filename. This does a two-pass compression (I'm assuming mpeg4, I should probably make this smarter for other formats).
This compresses the video and audio of the given source video filename to the transcoded filename. This does a two-pass compression (I'm assuming mpeg4, I should probably make this smarter for other formats).
[ "This", "compresses", "the", "video", "and", "audio", "of", "the", "given", "source", "video", "filename", "to", "the", "transcoded", "filename", ".", "This", "does", "a", "two", "-", "pass", "compression", "(", "I", "m", "assuming", "mpeg4", "I", "should"...
def compress_video( video_source_filename, video_final_filename, video_target_size, audio_id=128, video_bitrate=1000, video_codec='mpeg4', audio_codec='mp3', video_fourcc_override='FMP4', video_gray_flag=0, video_crop_area=None, video_aspect_ratio='16/9', video_scale=None, video_encode_passes=2, video_deinterlace_flag=0, audio_volume_boost=None, audio_sample_rate=None, audio_bitrate=None, seek_skip=None, seek_length=None, video_chapter=None, verbose_flag=0, dry_run_flag=0): """This compresses the video and audio of the given source video filename to the transcoded filename. This does a two-pass compression (I'm assuming mpeg4, I should probably make this smarter for other formats). """ # # do the first pass video compression # #cmd = "mencoder -quiet '%(video_source_filename)s' -ss 65 -endpos 20 -aid %(audio_id)s -o '%(video_final_filename)s' -ffourcc %(video_fourcc_override)s -ovc lavc -oac lavc %(lavcopts)s %(video_filter)s %(audio_filter)s" % locals() cmd = build_compression_command( video_source_filename, video_final_filename, video_target_size, audio_id, video_bitrate, video_codec, audio_codec, video_fourcc_override, video_gray_flag, video_crop_area, video_aspect_ratio, video_scale, video_encode_passes, video_deinterlace_flag, audio_volume_boost, audio_sample_rate, audio_bitrate, seek_skip, seek_length, video_chapter) if verbose_flag: print cmd if not dry_run_flag: run(cmd) print # If not doing two passes then return early. if video_encode_passes != '2': return if verbose_flag: video_actual_size = get_filesize(video_final_filename) if video_actual_size > video_target_size: print "=======================================================" print "WARNING!" print "First pass compression resulted in" print "actual file size greater than target size." print "Second pass will be too big." print "=======================================================" # # do the second pass video compression # cmd = cmd.replace('vpass=1', 'vpass=2') if verbose_flag: print cmd if not dry_run_flag: run(cmd) print return
[ "def", "compress_video", "(", "video_source_filename", ",", "video_final_filename", ",", "video_target_size", ",", "audio_id", "=", "128", ",", "video_bitrate", "=", "1000", ",", "video_codec", "=", "'mpeg4'", ",", "audio_codec", "=", "'mp3'", ",", "video_fourcc_ove...
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/examples/rippy.py#L854-L935
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/metrics/_classification.py
python
_check_set_wise_labels
(y_true, y_pred, average, labels, pos_label)
return labels
Validation associated with set-wise metrics Returns identified labels
Validation associated with set-wise metrics
[ "Validation", "associated", "with", "set", "-", "wise", "metrics" ]
def _check_set_wise_labels(y_true, y_pred, average, labels, pos_label): """Validation associated with set-wise metrics Returns identified labels """ average_options = (None, 'micro', 'macro', 'weighted', 'samples') if average not in average_options and average != 'binary': raise ValueError('average has to be one of ' + str(average_options)) y_type, y_true, y_pred = _check_targets(y_true, y_pred) present_labels = unique_labels(y_true, y_pred) if average == 'binary': if y_type == 'binary': if pos_label not in present_labels: if len(present_labels) >= 2: raise ValueError("pos_label=%r is not a valid label: " "%r" % (pos_label, present_labels)) labels = [pos_label] else: average_options = list(average_options) if y_type == 'multiclass': average_options.remove('samples') raise ValueError("Target is %s but average='binary'. Please " "choose another average setting, one of %r." % (y_type, average_options)) elif pos_label not in (None, 1): warnings.warn("Note that pos_label (set to %r) is ignored when " "average != 'binary' (got %r). You may use " "labels=[pos_label] to specify a single positive class." % (pos_label, average), UserWarning) return labels
[ "def", "_check_set_wise_labels", "(", "y_true", ",", "y_pred", ",", "average", ",", "labels", ",", "pos_label", ")", ":", "average_options", "=", "(", "None", ",", "'micro'", ",", "'macro'", ",", "'weighted'", ",", "'samples'", ")", "if", "average", "not", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/metrics/_classification.py#L1291-L1322
isc-projects/kea
c5836c791b63f42173bb604dd5f05d7110f3e716
tools/reorder_message_file.py
python
print_dict
(dictionary)
Prints the dictionary with a blank line between entries. Parameters: dictionary - Map holding the message dictionary
Prints the dictionary with a blank line between entries.
[ "Prints", "the", "dictionary", "with", "a", "blank", "line", "between", "entries", "." ]
def print_dict(dictionary): """ Prints the dictionary with a blank line between entries. Parameters: dictionary - Map holding the message dictionary """ count = 0 for msgid in sorted(dictionary): # Blank line before all entries but the first if count > 0: print("") count = count + 1 # ... and the entry itself. for l in dictionary[msgid]: print(l.strip())
[ "def", "print_dict", "(", "dictionary", ")", ":", "count", "=", "0", "for", "msgid", "in", "sorted", "(", "dictionary", ")", ":", "# Blank line before all entries but the first", "if", "count", ">", "0", ":", "print", "(", "\"\"", ")", "count", "=", "count",...
https://github.com/isc-projects/kea/blob/c5836c791b63f42173bb604dd5f05d7110f3e716/tools/reorder_message_file.py#L132-L149
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
PseudoDC.DrawLine
(*args, **kwargs)
return _gdi_.PseudoDC_DrawLine(*args, **kwargs)
DrawLine(self, int x1, int y1, int x2, int y2) Draws a line from the first point to the second. The current pen is used for drawing the line. Note that the second point is *not* part of the line and is not drawn by this function (this is consistent with the behaviour of many other toolkits).
DrawLine(self, int x1, int y1, int x2, int y2)
[ "DrawLine", "(", "self", "int", "x1", "int", "y1", "int", "x2", "int", "y2", ")" ]
def DrawLine(*args, **kwargs): """ DrawLine(self, int x1, int y1, int x2, int y2) Draws a line from the first point to the second. The current pen is used for drawing the line. Note that the second point is *not* part of the line and is not drawn by this function (this is consistent with the behaviour of many other toolkits). """ return _gdi_.PseudoDC_DrawLine(*args, **kwargs)
[ "def", "DrawLine", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "PseudoDC_DrawLine", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L7943-L7952
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Image.LoadMimeStream
(*args, **kwargs)
return _core_.Image_LoadMimeStream(*args, **kwargs)
LoadMimeStream(self, InputStream stream, String mimetype, int index=-1) -> bool Loads an image from an input stream or a readable Python file-like object, using a MIME type string to specify the image file format.
LoadMimeStream(self, InputStream stream, String mimetype, int index=-1) -> bool
[ "LoadMimeStream", "(", "self", "InputStream", "stream", "String", "mimetype", "int", "index", "=", "-", "1", ")", "-", ">", "bool" ]
def LoadMimeStream(*args, **kwargs): """ LoadMimeStream(self, InputStream stream, String mimetype, int index=-1) -> bool Loads an image from an input stream or a readable Python file-like object, using a MIME type string to specify the image file format. """ return _core_.Image_LoadMimeStream(*args, **kwargs)
[ "def", "LoadMimeStream", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_LoadMimeStream", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L3248-L3255
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/ma/extras.py
python
clump_masked
(a)
return _ezclump(mask)
Returns a list of slices corresponding to the masked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice The list of slices, one for each continuous region of masked elements in `a`. Notes ----- .. versionadded:: 1.4.0 See Also -------- flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, notmasked_contiguous, clump_unmasked Examples -------- >>> a = np.ma.masked_array(np.arange(10)) >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked >>> np.ma.clump_masked(a) [slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)]
Returns a list of slices corresponding to the masked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array).
[ "Returns", "a", "list", "of", "slices", "corresponding", "to", "the", "masked", "clumps", "of", "a", "1", "-", "D", "array", ".", "(", "A", "clump", "is", "defined", "as", "a", "contiguous", "region", "of", "the", "array", ")", "." ]
def clump_masked(a): """ Returns a list of slices corresponding to the masked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice The list of slices, one for each continuous region of masked elements in `a`. Notes ----- .. versionadded:: 1.4.0 See Also -------- flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, notmasked_contiguous, clump_unmasked Examples -------- >>> a = np.ma.masked_array(np.arange(10)) >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked >>> np.ma.clump_masked(a) [slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)] """ mask = ma.getmask(a) if mask is nomask: return [] return _ezclump(mask)
[ "def", "clump_masked", "(", "a", ")", ":", "mask", "=", "ma", ".", "getmask", "(", "a", ")", "if", "mask", "is", "nomask", ":", "return", "[", "]", "return", "_ezclump", "(", "mask", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/extras.py#L1809-L1845
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
SettableHeaderColumn.SetHidden
(*args, **kwargs)
return _core_.SettableHeaderColumn_SetHidden(*args, **kwargs)
SetHidden(self, bool hidden)
SetHidden(self, bool hidden)
[ "SetHidden", "(", "self", "bool", "hidden", ")" ]
def SetHidden(*args, **kwargs): """SetHidden(self, bool hidden)""" return _core_.SettableHeaderColumn_SetHidden(*args, **kwargs)
[ "def", "SetHidden", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "SettableHeaderColumn_SetHidden", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L16512-L16514
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBMemoryRegionInfo.Clear
(self)
return _lldb.SBMemoryRegionInfo_Clear(self)
Clear(SBMemoryRegionInfo self)
Clear(SBMemoryRegionInfo self)
[ "Clear", "(", "SBMemoryRegionInfo", "self", ")" ]
def Clear(self): """Clear(SBMemoryRegionInfo self)""" return _lldb.SBMemoryRegionInfo_Clear(self)
[ "def", "Clear", "(", "self", ")", ":", "return", "_lldb", ".", "SBMemoryRegionInfo_Clear", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L6929-L6931
google/tink
59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14
python/tink/jwt/_jwt_validator.py
python
new_validator
( *, expected_type_header: Optional[str] = None, expected_issuer: Optional[str] = None, expected_audience: Optional[str] = None, ignore_type_header: bool = False, ignore_issuer: bool = False, ignore_audiences: bool = False, allow_missing_expiration: bool = False, expect_issued_in_the_past: bool = False, clock_skew: Optional[datetime.timedelta] = None, fixed_now: Optional[datetime.datetime] = None)
return JwtValidator( expected_type_header=expected_type_header, expected_issuer=expected_issuer, expected_audience=expected_audience, ignore_type_header=ignore_type_header, ignore_issuer=ignore_issuer, ignore_audiences=ignore_audiences, allow_missing_expiration=allow_missing_expiration, expect_issued_in_the_past=expect_issued_in_the_past, clock_skew=clock_skew, fixed_now=fixed_now)
Creates a new JwtValidator.
Creates a new JwtValidator.
[ "Creates", "a", "new", "JwtValidator", "." ]
def new_validator( *, expected_type_header: Optional[str] = None, expected_issuer: Optional[str] = None, expected_audience: Optional[str] = None, ignore_type_header: bool = False, ignore_issuer: bool = False, ignore_audiences: bool = False, allow_missing_expiration: bool = False, expect_issued_in_the_past: bool = False, clock_skew: Optional[datetime.timedelta] = None, fixed_now: Optional[datetime.datetime] = None) -> JwtValidator: """Creates a new JwtValidator.""" return JwtValidator( expected_type_header=expected_type_header, expected_issuer=expected_issuer, expected_audience=expected_audience, ignore_type_header=ignore_type_header, ignore_issuer=ignore_issuer, ignore_audiences=ignore_audiences, allow_missing_expiration=allow_missing_expiration, expect_issued_in_the_past=expect_issued_in_the_past, clock_skew=clock_skew, fixed_now=fixed_now)
[ "def", "new_validator", "(", "*", ",", "expected_type_header", ":", "Optional", "[", "str", "]", "=", "None", ",", "expected_issuer", ":", "Optional", "[", "str", "]", "=", "None", ",", "expected_audience", ":", "Optional", "[", "str", "]", "=", "None", ...
https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/jwt/_jwt_validator.py#L119-L142
RobotLocomotion/drake
0e18a34604c45ed65bc9018a54f7610f91cdad5b
examples/acrobot/metrics.py
python
is_success
(x_tape)
return final_state_cost(x_tape) < 1e-3
Returns true if the final state in `x_tape` is close to the upright equilibrium.
Returns true if the final state in `x_tape` is close to the upright equilibrium.
[ "Returns", "true", "if", "the", "final", "state", "in", "x_tape", "is", "close", "to", "the", "upright", "equilibrium", "." ]
def is_success(x_tape): """ Returns true if the final state in `x_tape` is close to the upright equilibrium. """ return final_state_cost(x_tape) < 1e-3
[ "def", "is_success", "(", "x_tape", ")", ":", "return", "final_state_cost", "(", "x_tape", ")", "<", "1e-3" ]
https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/examples/acrobot/metrics.py#L37-L42
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings._ConvertConditionalKeys
(self, configname)
Converts or warns on conditional keys. Xcode supports conditional keys, such as CODE_SIGN_IDENTITY[sdk=iphoneos*]. This is a partial implementation with some keys converted while the rest force a warning.
Converts or warns on conditional keys. Xcode supports conditional keys, such as CODE_SIGN_IDENTITY[sdk=iphoneos*]. This is a partial implementation with some keys converted while the rest force a warning.
[ "Converts", "or", "warns", "on", "conditional", "keys", ".", "Xcode", "supports", "conditional", "keys", "such", "as", "CODE_SIGN_IDENTITY", "[", "sdk", "=", "iphoneos", "*", "]", ".", "This", "is", "a", "partial", "implementation", "with", "some", "keys", "...
def _ConvertConditionalKeys(self, configname): """Converts or warns on conditional keys. Xcode supports conditional keys, such as CODE_SIGN_IDENTITY[sdk=iphoneos*]. This is a partial implementation with some keys converted while the rest force a warning.""" settings = self.xcode_settings[configname] conditional_keys = [key for key in settings if key.endswith(']')] for key in conditional_keys: # If you need more, speak up at http://crbug.com/122592 if key.endswith("[sdk=iphoneos*]"): if configname.endswith("iphoneos"): new_key = key.split("[")[0] settings[new_key] = settings[key] else: print 'Warning: Conditional keys not implemented, ignoring:', \ ' '.join(conditional_keys) del settings[key]
[ "def", "_ConvertConditionalKeys", "(", "self", ",", "configname", ")", ":", "settings", "=", "self", ".", "xcode_settings", "[", "configname", "]", "conditional_keys", "=", "[", "key", "for", "key", "in", "settings", "if", "key", ".", "endswith", "(", "']'",...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L184-L199
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/processors.py
python
Processor.has_focus
(self, cli)
return False
Processors can override the focus. (Used for the reverse-i-search prefix in DefaultPrompt.)
Processors can override the focus. (Used for the reverse-i-search prefix in DefaultPrompt.)
[ "Processors", "can", "override", "the", "focus", ".", "(", "Used", "for", "the", "reverse", "-", "i", "-", "search", "prefix", "in", "DefaultPrompt", ".", ")" ]
def has_focus(self, cli): """ Processors can override the focus. (Used for the reverse-i-search prefix in DefaultPrompt.) """ return False
[ "def", "has_focus", "(", "self", ",", "cli", ")", ":", "return", "False" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/processors.py#L64-L69
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/util/queue_channel.py
python
QueueListener._monitor
(self)
Monitor the queue for records, and ask the handler to deal with them. This method runs on a separate, internal thread. The thread will terminate if it sees a sentinel object in the queue.
Monitor the queue for records, and ask the handler to deal with them.
[ "Monitor", "the", "queue", "for", "records", "and", "ask", "the", "handler", "to", "deal", "with", "them", "." ]
def _monitor(self): """ Monitor the queue for records, and ask the handler to deal with them. This method runs on a separate, internal thread. The thread will terminate if it sees a sentinel object in the queue. """ q = self.queue has_task_done = hasattr(q, 'task_done') while not self._stop.isSet(): try: record = self.dequeue(True) if record is self._sentinel: break self.handle(record) if has_task_done: q.task_done() except queue.Empty: pass # There might still be records in the queue. while True: try: record = self.dequeue(False) if record is self._sentinel: break self.handle(record) if has_task_done: q.task_done() except queue.Empty: break
[ "def", "_monitor", "(", "self", ")", ":", "q", "=", "self", ".", "queue", "has_task_done", "=", "hasattr", "(", "q", ",", "'task_done'", ")", "while", "not", "self", ".", "_stop", ".", "isSet", "(", ")", ":", "try", ":", "record", "=", "self", ".",...
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/util/queue_channel.py#L195-L225
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/training/supervisor.py
python
Supervisor.stop_on_exception
(self)
return self._coord.stop_on_exception()
Context handler to stop the supervisor when an exception is raised. See `Coordinator.stop_on_exception()`. Returns: A context handler.
Context handler to stop the supervisor when an exception is raised.
[ "Context", "handler", "to", "stop", "the", "supervisor", "when", "an", "exception", "is", "raised", "." ]
def stop_on_exception(self): """Context handler to stop the supervisor when an exception is raised. See `Coordinator.stop_on_exception()`. Returns: A context handler. """ return self._coord.stop_on_exception()
[ "def", "stop_on_exception", "(", "self", ")", ":", "return", "self", ".", "_coord", ".", "stop_on_exception", "(", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/supervisor.py#L791-L799
interpretml/interpret
29466bffc04505fe4f836a83fcfebfd313ac8454
python/interpret-core/interpret/ext/extension_utils.py
python
load_class_extensions
(current_module, extension_key, extension_class_validator)
Load all registered extensions under the `extension_key` namespace in entry_points. Attributes: current_module: The module itself where extension classes should be added. extension_key: The identifier as string for the entry_points to register within the current_module. extension_class_validator: A function(class) -> bool, that checks the class for correctness before it is registered.
Load all registered extensions under the `extension_key` namespace in entry_points.
[ "Load", "all", "registered", "extensions", "under", "the", "extension_key", "namespace", "in", "entry_points", "." ]
def load_class_extensions(current_module, extension_key, extension_class_validator): """ Load all registered extensions under the `extension_key` namespace in entry_points. Attributes: current_module: The module itself where extension classes should be added. extension_key: The identifier as string for the entry_points to register within the current_module. extension_class_validator: A function(class) -> bool, that checks the class for correctness before it is registered. """ for entrypoint in pkg_resources.iter_entry_points(extension_key): module_logger.debug("processing entrypoint {}".format(extension_key)) try: extension_class_name = entrypoint.name extension_class = entrypoint.load() module_logger.debug( "loading entrypoint key {} with name {} with object {}".format( extension_key, extension_class_name, extension_class ) ) _validate_class_name(extension_class_name) if not extension_class_validator(extension_class): raise ValueError("class {} failed validation.".format(extension_class)) if getattr(current_module, extension_class_name, None) is not None: raise ValueError( "class name {} already exists for module {}.".format( extension_class_name, current_module.__name__ ) ) setattr(current_module, extension_class_name, extension_class) except Exception as e: # pragma: no cover msg = "Failure while loading {}. Failed to load entrypoint {} with exception {}.".format( extension_key, entrypoint, "".join(traceback.format_exception(type(e), e, e.__traceback__)), ) module_logger.warning(msg) warn(msg)
[ "def", "load_class_extensions", "(", "current_module", ",", "extension_key", ",", "extension_class_validator", ")", ":", "for", "entrypoint", "in", "pkg_resources", ".", "iter_entry_points", "(", "extension_key", ")", ":", "module_logger", ".", "debug", "(", "\"proces...
https://github.com/interpretml/interpret/blob/29466bffc04505fe4f836a83fcfebfd313ac8454/python/interpret-core/interpret/ext/extension_utils.py#L33-L73
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/fancy_getopt.py
python
FancyGetopt.get_attr_name
(self, long_option)
return string.translate(long_option, longopt_xlate)
Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.
Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.
[ "Translate", "long", "option", "name", "long_option", "to", "the", "form", "it", "has", "as", "an", "attribute", "of", "some", "object", ":", "ie", ".", "translate", "hyphens", "to", "underscores", "." ]
def get_attr_name (self, long_option): """Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.""" return string.translate(long_option, longopt_xlate)
[ "def", "get_attr_name", "(", "self", ",", "long_option", ")", ":", "return", "string", ".", "translate", "(", "long_option", ",", "longopt_xlate", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/fancy_getopt.py#L113-L117
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py
python
KeysPage.var_changed_keyset_source
(self, *params)
Process toggle between builtin key set and custom key set.
Process toggle between builtin key set and custom key set.
[ "Process", "toggle", "between", "builtin", "key", "set", "and", "custom", "key", "set", "." ]
def var_changed_keyset_source(self, *params): "Process toggle between builtin key set and custom key set." value = self.keyset_source.get() changes.add_option('main', 'Keys', 'default', value) if value: self.var_changed_builtin_name() else: self.var_changed_custom_name()
[ "def", "var_changed_keyset_source", "(", "self", ",", "*", "params", ")", ":", "value", "=", "self", ".", "keyset_source", ".", "get", "(", ")", "changes", ".", "add_option", "(", "'main'", ",", "'Keys'", ",", "'default'", ",", "value", ")", "if", "value...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/configdialog.py#L1571-L1578
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
chrome/common/extensions/docs/server2/servlet.py
python
Servlet.Get
(self)
Returns a Response.
Returns a Response.
[ "Returns", "a", "Response", "." ]
def Get(self): '''Returns a Response. ''' raise NotImplemented()
[ "def", "Get", "(", "self", ")", ":", "raise", "NotImplemented", "(", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/servlet.py#L131-L134