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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ispc/ispc | 0a7ee59b6ec50e54d545eb2a31056e54c4891d51 | utils/lit/lit/LitConfig.py | python | LitConfig.load_config | (self, config, path) | return config | load_config(config, path) - Load a config object from an alternate
path. | load_config(config, path) - Load a config object from an alternate
path. | [
"load_config",
"(",
"config",
"path",
")",
"-",
"Load",
"a",
"config",
"object",
"from",
"an",
"alternate",
"path",
"."
] | def load_config(self, config, path):
"""load_config(config, path) - Load a config object from an alternate
path."""
if self.debug:
self.note('load_config from %r' % path)
config.load_from_path(path, self)
return config | [
"def",
"load_config",
"(",
"self",
",",
"config",
",",
"path",
")",
":",
"if",
"self",
".",
"debug",
":",
"self",
".",
"note",
"(",
"'load_config from %r'",
"%",
"path",
")",
"config",
".",
"load_from_path",
"(",
"path",
",",
"self",
")",
"return",
"config"
] | https://github.com/ispc/ispc/blob/0a7ee59b6ec50e54d545eb2a31056e54c4891d51/utils/lit/lit/LitConfig.py#L103-L109 | |
baidu/bigflow | 449245016c0df7d1252e85581e588bfc60cefad3 | bigflow_python/python/bigflow/output.py | python | SequenceFile.as_type | (self, kv_serializer) | return self | 通过kv_serializer将数据序列化为(Key, Value)
Args:
kv_serializer (callable): 序列化函数
Returns:
SequenceFile: 返回self
.. note:: kv_deserializer的期望签名为:
kv_deserializer(object) => (str, str) | 通过kv_serializer将数据序列化为(Key, Value) | [
"通过kv_serializer将数据序列化为",
"(",
"Key",
"Value",
")"
] | def as_type(self, kv_serializer):
"""
通过kv_serializer将数据序列化为(Key, Value)
Args:
kv_serializer (callable): 序列化函数
Returns:
SequenceFile: 返回self
.. note:: kv_deserializer的期望签名为:
kv_deserializer(object) => (str, str)
"""
self.kv_serializer = kv_serializer
return self | [
"def",
"as_type",
"(",
"self",
",",
"kv_serializer",
")",
":",
"self",
".",
"kv_serializer",
"=",
"kv_serializer",
"return",
"self"
] | https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/output.py#L387-L402 | |
zeakey/DeepSkeleton | dc70170f8fd2ec8ca1157484ce66129981104486 | scripts/cpp_lint.py | python | _GetTextInside | (text, start_pattern) | return text[start_position:position - 1] | r"""Retrieves all the text between matching open and close parentheses.
Given a string of lines and a regular expression string, retrieve all the text
following the expression and between opening punctuation symbols like
(, [, or {, and the matching close-punctuation symbol. This properly nested
occurrences of the punctuations, so for the text like
printf(a(), b(c()));
a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
start_pattern must match string having an open punctuation symbol at the end.
Args:
text: The lines to extract text. Its comments and strings must be elided.
It can be single line and can span multiple lines.
start_pattern: The regexp string indicating where to start extracting
the text.
Returns:
The extracted text.
None if either the opening string or ending punctuation could not be found. | r"""Retrieves all the text between matching open and close parentheses. | [
"r",
"Retrieves",
"all",
"the",
"text",
"between",
"matching",
"open",
"and",
"close",
"parentheses",
"."
] | def _GetTextInside(text, start_pattern):
r"""Retrieves all the text between matching open and close parentheses.
Given a string of lines and a regular expression string, retrieve all the text
following the expression and between opening punctuation symbols like
(, [, or {, and the matching close-punctuation symbol. This properly nested
occurrences of the punctuations, so for the text like
printf(a(), b(c()));
a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
start_pattern must match string having an open punctuation symbol at the end.
Args:
text: The lines to extract text. Its comments and strings must be elided.
It can be single line and can span multiple lines.
start_pattern: The regexp string indicating where to start extracting
the text.
Returns:
The extracted text.
None if either the opening string or ending punctuation could not be found.
"""
# TODO(sugawarayu): Audit cpplint.py to see what places could be profitably
# rewritten to use _GetTextInside (and use inferior regexp matching today).
# Give opening punctuations to get the matching close-punctuations.
matching_punctuation = {'(': ')', '{': '}', '[': ']'}
closing_punctuation = set(matching_punctuation.itervalues())
# Find the position to start extracting text.
match = re.search(start_pattern, text, re.M)
if not match: # start_pattern not found in text.
return None
start_position = match.end(0)
assert start_position > 0, (
'start_pattern must ends with an opening punctuation.')
assert text[start_position - 1] in matching_punctuation, (
'start_pattern must ends with an opening punctuation.')
# Stack of closing punctuations we expect to have in text after position.
punctuation_stack = [matching_punctuation[text[start_position - 1]]]
position = start_position
while punctuation_stack and position < len(text):
if text[position] == punctuation_stack[-1]:
punctuation_stack.pop()
elif text[position] in closing_punctuation:
# A closing punctuation without matching opening punctuations.
return None
elif text[position] in matching_punctuation:
punctuation_stack.append(matching_punctuation[text[position]])
position += 1
if punctuation_stack:
# Opening punctuations left without matching close-punctuations.
return None
# punctuations match.
return text[start_position:position - 1] | [
"def",
"_GetTextInside",
"(",
"text",
",",
"start_pattern",
")",
":",
"# TODO(sugawarayu): Audit cpplint.py to see what places could be profitably",
"# rewritten to use _GetTextInside (and use inferior regexp matching today).",
"# Give opening punctuations to get the matching close-punctuations.",
"matching_punctuation",
"=",
"{",
"'('",
":",
"')'",
",",
"'{'",
":",
"'}'",
",",
"'['",
":",
"']'",
"}",
"closing_punctuation",
"=",
"set",
"(",
"matching_punctuation",
".",
"itervalues",
"(",
")",
")",
"# Find the position to start extracting text.",
"match",
"=",
"re",
".",
"search",
"(",
"start_pattern",
",",
"text",
",",
"re",
".",
"M",
")",
"if",
"not",
"match",
":",
"# start_pattern not found in text.",
"return",
"None",
"start_position",
"=",
"match",
".",
"end",
"(",
"0",
")",
"assert",
"start_position",
">",
"0",
",",
"(",
"'start_pattern must ends with an opening punctuation.'",
")",
"assert",
"text",
"[",
"start_position",
"-",
"1",
"]",
"in",
"matching_punctuation",
",",
"(",
"'start_pattern must ends with an opening punctuation.'",
")",
"# Stack of closing punctuations we expect to have in text after position.",
"punctuation_stack",
"=",
"[",
"matching_punctuation",
"[",
"text",
"[",
"start_position",
"-",
"1",
"]",
"]",
"]",
"position",
"=",
"start_position",
"while",
"punctuation_stack",
"and",
"position",
"<",
"len",
"(",
"text",
")",
":",
"if",
"text",
"[",
"position",
"]",
"==",
"punctuation_stack",
"[",
"-",
"1",
"]",
":",
"punctuation_stack",
".",
"pop",
"(",
")",
"elif",
"text",
"[",
"position",
"]",
"in",
"closing_punctuation",
":",
"# A closing punctuation without matching opening punctuations.",
"return",
"None",
"elif",
"text",
"[",
"position",
"]",
"in",
"matching_punctuation",
":",
"punctuation_stack",
".",
"append",
"(",
"matching_punctuation",
"[",
"text",
"[",
"position",
"]",
"]",
")",
"position",
"+=",
"1",
"if",
"punctuation_stack",
":",
"# Opening punctuations left without matching close-punctuations.",
"return",
"None",
"# punctuations match.",
"return",
"text",
"[",
"start_position",
":",
"position",
"-",
"1",
"]"
] | https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/scripts/cpp_lint.py#L3752-L3805 | |
timi-liuliang/echo | 40a5a24d430eee4118314459ab7e03afcb3b8719 | thirdparty/protobuf/python/google/protobuf/internal/decoder.py | python | _StructPackDecoder | (wire_type, format) | return _SimpleDecoder(wire_type, InnerDecode) | Return a constructor for a decoder for a fixed-width field.
Args:
wire_type: The field's wire type.
format: The format string to pass to struct.unpack(). | Return a constructor for a decoder for a fixed-width field. | [
"Return",
"a",
"constructor",
"for",
"a",
"decoder",
"for",
"a",
"fixed",
"-",
"width",
"field",
"."
] | def _StructPackDecoder(wire_type, format):
"""Return a constructor for a decoder for a fixed-width field.
Args:
wire_type: The field's wire type.
format: The format string to pass to struct.unpack().
"""
value_size = struct.calcsize(format)
local_unpack = struct.unpack
# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
# not enough to make a significant difference.
# Note that we expect someone up-stack to catch struct.error and convert
# it to _DecodeError -- this way we don't have to set up exception-
# handling blocks every time we parse one value.
def InnerDecode(buffer, pos):
new_pos = pos + value_size
result = local_unpack(format, buffer[pos:new_pos])[0]
return (result, new_pos)
return _SimpleDecoder(wire_type, InnerDecode) | [
"def",
"_StructPackDecoder",
"(",
"wire_type",
",",
"format",
")",
":",
"value_size",
"=",
"struct",
".",
"calcsize",
"(",
"format",
")",
"local_unpack",
"=",
"struct",
".",
"unpack",
"# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but",
"# not enough to make a significant difference.",
"# Note that we expect someone up-stack to catch struct.error and convert",
"# it to _DecodeError -- this way we don't have to set up exception-",
"# handling blocks every time we parse one value.",
"def",
"InnerDecode",
"(",
"buffer",
",",
"pos",
")",
":",
"new_pos",
"=",
"pos",
"+",
"value_size",
"result",
"=",
"local_unpack",
"(",
"format",
",",
"buffer",
"[",
"pos",
":",
"new_pos",
"]",
")",
"[",
"0",
"]",
"return",
"(",
"result",
",",
"new_pos",
")",
"return",
"_SimpleDecoder",
"(",
"wire_type",
",",
"InnerDecode",
")"
] | https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/internal/decoder.py#L271-L293 | |
qt/qt | 0a2f2382541424726168804be2c90b91381608c6 | src/3rdparty/freetype/src/tools/docmaker/content.py | python | ContentProcessor.__init__ | ( self ) | initialize a block content processor | initialize a block content processor | [
"initialize",
"a",
"block",
"content",
"processor"
] | def __init__( self ):
"""initialize a block content processor"""
self.reset()
self.sections = {} # dictionary of documentation sections
self.section = None # current documentation section
self.chapters = [] # list of chapters
self.headers = {} | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"reset",
"(",
")",
"self",
".",
"sections",
"=",
"{",
"}",
"# dictionary of documentation sections",
"self",
".",
"section",
"=",
"None",
"# current documentation section",
"self",
".",
"chapters",
"=",
"[",
"]",
"# list of chapters",
"self",
".",
"headers",
"=",
"{",
"}"
] | https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/freetype/src/tools/docmaker/content.py#L342-L351 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | parserCtxt.htmlParseDocument | (self) | return ret | parse an HTML document (and build a tree if using the
standard SAX interface). | parse an HTML document (and build a tree if using the
standard SAX interface). | [
"parse",
"an",
"HTML",
"document",
"(",
"and",
"build",
"a",
"tree",
"if",
"using",
"the",
"standard",
"SAX",
"interface",
")",
"."
] | def htmlParseDocument(self):
"""parse an HTML document (and build a tree if using the
standard SAX interface). """
ret = libxml2mod.htmlParseDocument(self._o)
return ret | [
"def",
"htmlParseDocument",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlParseDocument",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L5010-L5014 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/webencodings/__init__.py | python | IncrementalDecoder.decode | (self, input, final=False) | return decoder(input, final) | Decode one chunk of the input.
:param input: A byte string.
:param final:
Indicate that no more input is available.
Must be :obj:`True` if this is the last call.
:returns: An Unicode string. | Decode one chunk of the input. | [
"Decode",
"one",
"chunk",
"of",
"the",
"input",
"."
] | def decode(self, input, final=False):
"""Decode one chunk of the input.
:param input: A byte string.
:param final:
Indicate that no more input is available.
Must be :obj:`True` if this is the last call.
:returns: An Unicode string.
"""
decoder = self._decoder
if decoder is not None:
return decoder(input, final)
input = self._buffer + input
encoding, input = _detect_bom(input)
if encoding is None:
if len(input) < 3 and not final: # Not enough data yet.
self._buffer = input
return ''
else: # No BOM
encoding = self._fallback_encoding
decoder = encoding.codec_info.incrementaldecoder(self._errors).decode
self._decoder = decoder
self.encoding = encoding
return decoder(input, final) | [
"def",
"decode",
"(",
"self",
",",
"input",
",",
"final",
"=",
"False",
")",
":",
"decoder",
"=",
"self",
".",
"_decoder",
"if",
"decoder",
"is",
"not",
"None",
":",
"return",
"decoder",
"(",
"input",
",",
"final",
")",
"input",
"=",
"self",
".",
"_buffer",
"+",
"input",
"encoding",
",",
"input",
"=",
"_detect_bom",
"(",
"input",
")",
"if",
"encoding",
"is",
"None",
":",
"if",
"len",
"(",
"input",
")",
"<",
"3",
"and",
"not",
"final",
":",
"# Not enough data yet.",
"self",
".",
"_buffer",
"=",
"input",
"return",
"''",
"else",
":",
"# No BOM",
"encoding",
"=",
"self",
".",
"_fallback_encoding",
"decoder",
"=",
"encoding",
".",
"codec_info",
".",
"incrementaldecoder",
"(",
"self",
".",
"_errors",
")",
".",
"decode",
"self",
".",
"_decoder",
"=",
"decoder",
"self",
".",
"encoding",
"=",
"encoding",
"return",
"decoder",
"(",
"input",
",",
"final",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/webencodings/__init__.py#L295-L320 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Event.WasProcessed | (*args, **kwargs) | return _core_.Event_WasProcessed(*args, **kwargs) | WasProcessed(self) -> bool | WasProcessed(self) -> bool | [
"WasProcessed",
"(",
"self",
")",
"-",
">",
"bool"
] | def WasProcessed(*args, **kwargs):
"""WasProcessed(self) -> bool"""
return _core_.Event_WasProcessed(*args, **kwargs) | [
"def",
"WasProcessed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Event_WasProcessed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L5100-L5102 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/utils.py | python | get_encodings_from_content | (content) | return (charset_re.findall(content) +
pragma_re.findall(content) +
xml_re.findall(content)) | Returns encodings from given content string.
:param content: bytestring to extract encodings from. | Returns encodings from given content string. | [
"Returns",
"encodings",
"from",
"given",
"content",
"string",
"."
] | def get_encodings_from_content(content):
"""Returns encodings from given content string.
:param content: bytestring to extract encodings from.
"""
warnings.warn((
'In requests 3.0, get_encodings_from_content will be removed. For '
'more information, please see the discussion on issue #2266. (This'
' warning should only appear once.)'),
DeprecationWarning)
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
return (charset_re.findall(content) +
pragma_re.findall(content) +
xml_re.findall(content)) | [
"def",
"get_encodings_from_content",
"(",
"content",
")",
":",
"warnings",
".",
"warn",
"(",
"(",
"'In requests 3.0, get_encodings_from_content will be removed. For '",
"'more information, please see the discussion on issue #2266. (This'",
"' warning should only appear once.)'",
")",
",",
"DeprecationWarning",
")",
"charset_re",
"=",
"re",
".",
"compile",
"(",
"r'<meta.*?charset=[\"\\']*(.+?)[\"\\'>]'",
",",
"flags",
"=",
"re",
".",
"I",
")",
"pragma_re",
"=",
"re",
".",
"compile",
"(",
"r'<meta.*?content=[\"\\']*;?charset=(.+?)[\"\\'>]'",
",",
"flags",
"=",
"re",
".",
"I",
")",
"xml_re",
"=",
"re",
".",
"compile",
"(",
"r'^<\\?xml.*?encoding=[\"\\']*(.+?)[\"\\'>]'",
")",
"return",
"(",
"charset_re",
".",
"findall",
"(",
"content",
")",
"+",
"pragma_re",
".",
"findall",
"(",
"content",
")",
"+",
"xml_re",
".",
"findall",
"(",
"content",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/utils.py#L881-L915 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/loaders.py | python | Loader.load_service_model | (self, service_name, type_name, api_version=None) | return model | Load a botocore service model
This is the main method for loading botocore models (e.g. a service
model, pagination configs, waiter configs, etc.).
:type service_name: str
:param service_name: The name of the service (e.g ``ec2``, ``s3``).
:type type_name: str
:param type_name: The model type. Valid types include, but are not
limited to: ``service-2``, ``paginators-1``, ``waiters-2``.
:type api_version: str
:param api_version: The API version to load. If this is not
provided, then the latest API version will be used.
:type load_extras: bool
:param load_extras: Whether or not to load the tool extras which
contain additional data to be added to the model.
:raises: UnknownServiceError if there is no known service with
the provided service_name.
:raises: DataNotFoundError if no data could be found for the
service_name/type_name/api_version.
:return: The loaded data, as a python type (e.g. dict, list, etc). | Load a botocore service model | [
"Load",
"a",
"botocore",
"service",
"model"
] | def load_service_model(self, service_name, type_name, api_version=None):
"""Load a botocore service model
This is the main method for loading botocore models (e.g. a service
model, pagination configs, waiter configs, etc.).
:type service_name: str
:param service_name: The name of the service (e.g ``ec2``, ``s3``).
:type type_name: str
:param type_name: The model type. Valid types include, but are not
limited to: ``service-2``, ``paginators-1``, ``waiters-2``.
:type api_version: str
:param api_version: The API version to load. If this is not
provided, then the latest API version will be used.
:type load_extras: bool
:param load_extras: Whether or not to load the tool extras which
contain additional data to be added to the model.
:raises: UnknownServiceError if there is no known service with
the provided service_name.
:raises: DataNotFoundError if no data could be found for the
service_name/type_name/api_version.
:return: The loaded data, as a python type (e.g. dict, list, etc).
"""
# Wrapper around the load_data. This will calculate the path
# to call load_data with.
known_services = self.list_available_services(type_name)
if service_name not in known_services:
raise UnknownServiceError(
service_name=service_name,
known_service_names=', '.join(sorted(known_services)))
if api_version is None:
api_version = self.determine_latest_version(
service_name, type_name)
full_path = os.path.join(service_name, api_version, type_name)
model = self.load_data(full_path)
# Load in all the extras
extras_data = self._find_extras(service_name, type_name, api_version)
self._extras_processor.process(model, extras_data)
return model | [
"def",
"load_service_model",
"(",
"self",
",",
"service_name",
",",
"type_name",
",",
"api_version",
"=",
"None",
")",
":",
"# Wrapper around the load_data. This will calculate the path",
"# to call load_data with.",
"known_services",
"=",
"self",
".",
"list_available_services",
"(",
"type_name",
")",
"if",
"service_name",
"not",
"in",
"known_services",
":",
"raise",
"UnknownServiceError",
"(",
"service_name",
"=",
"service_name",
",",
"known_service_names",
"=",
"', '",
".",
"join",
"(",
"sorted",
"(",
"known_services",
")",
")",
")",
"if",
"api_version",
"is",
"None",
":",
"api_version",
"=",
"self",
".",
"determine_latest_version",
"(",
"service_name",
",",
"type_name",
")",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"service_name",
",",
"api_version",
",",
"type_name",
")",
"model",
"=",
"self",
".",
"load_data",
"(",
"full_path",
")",
"# Load in all the extras",
"extras_data",
"=",
"self",
".",
"_find_extras",
"(",
"service_name",
",",
"type_name",
",",
"api_version",
")",
"self",
".",
"_extras_processor",
".",
"process",
"(",
"model",
",",
"extras_data",
")",
"return",
"model"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/loaders.py#L343-L389 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/metrics/cluster/_unsupervised.py | python | silhouette_samples | (X, labels, metric='euclidean', **kwds) | return np.nan_to_num(sil_samples) | Compute the Silhouette Coefficient for each sample.
The Silhouette Coefficient is a measure of how well samples are clustered
with samples that are similar to themselves. Clustering models with a high
Silhouette Coefficient are said to be dense, where samples in the same
cluster are similar to each other, and well separated, where samples in
different clusters are not very similar to each other.
The Silhouette Coefficient is calculated using the mean intra-cluster
distance (``a``) and the mean nearest-cluster distance (``b``) for each
sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a,
b)``.
Note that Silhouette Coefficient is only defined if number of labels
is 2 <= n_labels <= n_samples - 1.
This function returns the Silhouette Coefficient for each sample.
The best value is 1 and the worst value is -1. Values near 0 indicate
overlapping clusters.
Read more in the :ref:`User Guide <silhouette_coefficient>`.
Parameters
----------
X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \
[n_samples_a, n_features] otherwise
Array of pairwise distances between samples, or a feature array.
labels : array, shape = [n_samples]
label values for each sample
metric : string, or callable
The metric to use when calculating distance between instances in a
feature array. If metric is a string, it must be one of the options
allowed by :func:`sklearn.metrics.pairwise.pairwise_distances`. If X is
the distance array itself, use "precomputed" as the metric. Precomputed
distance matrices must have 0 along the diagonal.
`**kwds` : optional keyword parameters
Any further parameters are passed directly to the distance function.
If using a ``scipy.spatial.distance`` metric, the parameters are still
metric dependent. See the scipy docs for usage examples.
Returns
-------
silhouette : array, shape = [n_samples]
Silhouette Coefficient for each samples.
References
----------
.. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the
Interpretation and Validation of Cluster Analysis". Computational
and Applied Mathematics 20: 53-65.
<https://www.sciencedirect.com/science/article/pii/0377042787901257>`_
.. [2] `Wikipedia entry on the Silhouette Coefficient
<https://en.wikipedia.org/wiki/Silhouette_(clustering)>`_ | Compute the Silhouette Coefficient for each sample. | [
"Compute",
"the",
"Silhouette",
"Coefficient",
"for",
"each",
"sample",
"."
] | def silhouette_samples(X, labels, metric='euclidean', **kwds):
"""Compute the Silhouette Coefficient for each sample.
The Silhouette Coefficient is a measure of how well samples are clustered
with samples that are similar to themselves. Clustering models with a high
Silhouette Coefficient are said to be dense, where samples in the same
cluster are similar to each other, and well separated, where samples in
different clusters are not very similar to each other.
The Silhouette Coefficient is calculated using the mean intra-cluster
distance (``a``) and the mean nearest-cluster distance (``b``) for each
sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a,
b)``.
Note that Silhouette Coefficient is only defined if number of labels
is 2 <= n_labels <= n_samples - 1.
This function returns the Silhouette Coefficient for each sample.
The best value is 1 and the worst value is -1. Values near 0 indicate
overlapping clusters.
Read more in the :ref:`User Guide <silhouette_coefficient>`.
Parameters
----------
X : array [n_samples_a, n_samples_a] if metric == "precomputed", or, \
[n_samples_a, n_features] otherwise
Array of pairwise distances between samples, or a feature array.
labels : array, shape = [n_samples]
label values for each sample
metric : string, or callable
The metric to use when calculating distance between instances in a
feature array. If metric is a string, it must be one of the options
allowed by :func:`sklearn.metrics.pairwise.pairwise_distances`. If X is
the distance array itself, use "precomputed" as the metric. Precomputed
distance matrices must have 0 along the diagonal.
`**kwds` : optional keyword parameters
Any further parameters are passed directly to the distance function.
If using a ``scipy.spatial.distance`` metric, the parameters are still
metric dependent. See the scipy docs for usage examples.
Returns
-------
silhouette : array, shape = [n_samples]
Silhouette Coefficient for each samples.
References
----------
.. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the
Interpretation and Validation of Cluster Analysis". Computational
and Applied Mathematics 20: 53-65.
<https://www.sciencedirect.com/science/article/pii/0377042787901257>`_
.. [2] `Wikipedia entry on the Silhouette Coefficient
<https://en.wikipedia.org/wiki/Silhouette_(clustering)>`_
"""
X, labels = check_X_y(X, labels, accept_sparse=['csc', 'csr'])
# Check for non-zero diagonal entries in precomputed distance matrix
if metric == 'precomputed':
atol = np.finfo(X.dtype).eps * 100
if np.any(np.abs(np.diagonal(X)) > atol):
raise ValueError(
'The precomputed distance matrix contains non-zero '
'elements on the diagonal. Use np.fill_diagonal(X, 0).'
)
le = LabelEncoder()
labels = le.fit_transform(labels)
n_samples = len(labels)
label_freqs = np.bincount(labels)
check_number_of_labels(len(le.classes_), n_samples)
kwds['metric'] = metric
reduce_func = functools.partial(_silhouette_reduce,
labels=labels, label_freqs=label_freqs)
results = zip(*pairwise_distances_chunked(X, reduce_func=reduce_func,
**kwds))
intra_clust_dists, inter_clust_dists = results
intra_clust_dists = np.concatenate(intra_clust_dists)
inter_clust_dists = np.concatenate(inter_clust_dists)
denom = (label_freqs - 1).take(labels, mode='clip')
with np.errstate(divide="ignore", invalid="ignore"):
intra_clust_dists /= denom
sil_samples = inter_clust_dists - intra_clust_dists
with np.errstate(divide="ignore", invalid="ignore"):
sil_samples /= np.maximum(intra_clust_dists, inter_clust_dists)
# nan values are for clusters of size 1, and should be 0
return np.nan_to_num(sil_samples) | [
"def",
"silhouette_samples",
"(",
"X",
",",
"labels",
",",
"metric",
"=",
"'euclidean'",
",",
"*",
"*",
"kwds",
")",
":",
"X",
",",
"labels",
"=",
"check_X_y",
"(",
"X",
",",
"labels",
",",
"accept_sparse",
"=",
"[",
"'csc'",
",",
"'csr'",
"]",
")",
"# Check for non-zero diagonal entries in precomputed distance matrix",
"if",
"metric",
"==",
"'precomputed'",
":",
"atol",
"=",
"np",
".",
"finfo",
"(",
"X",
".",
"dtype",
")",
".",
"eps",
"*",
"100",
"if",
"np",
".",
"any",
"(",
"np",
".",
"abs",
"(",
"np",
".",
"diagonal",
"(",
"X",
")",
")",
">",
"atol",
")",
":",
"raise",
"ValueError",
"(",
"'The precomputed distance matrix contains non-zero '",
"'elements on the diagonal. Use np.fill_diagonal(X, 0).'",
")",
"le",
"=",
"LabelEncoder",
"(",
")",
"labels",
"=",
"le",
".",
"fit_transform",
"(",
"labels",
")",
"n_samples",
"=",
"len",
"(",
"labels",
")",
"label_freqs",
"=",
"np",
".",
"bincount",
"(",
"labels",
")",
"check_number_of_labels",
"(",
"len",
"(",
"le",
".",
"classes_",
")",
",",
"n_samples",
")",
"kwds",
"[",
"'metric'",
"]",
"=",
"metric",
"reduce_func",
"=",
"functools",
".",
"partial",
"(",
"_silhouette_reduce",
",",
"labels",
"=",
"labels",
",",
"label_freqs",
"=",
"label_freqs",
")",
"results",
"=",
"zip",
"(",
"*",
"pairwise_distances_chunked",
"(",
"X",
",",
"reduce_func",
"=",
"reduce_func",
",",
"*",
"*",
"kwds",
")",
")",
"intra_clust_dists",
",",
"inter_clust_dists",
"=",
"results",
"intra_clust_dists",
"=",
"np",
".",
"concatenate",
"(",
"intra_clust_dists",
")",
"inter_clust_dists",
"=",
"np",
".",
"concatenate",
"(",
"inter_clust_dists",
")",
"denom",
"=",
"(",
"label_freqs",
"-",
"1",
")",
".",
"take",
"(",
"labels",
",",
"mode",
"=",
"'clip'",
")",
"with",
"np",
".",
"errstate",
"(",
"divide",
"=",
"\"ignore\"",
",",
"invalid",
"=",
"\"ignore\"",
")",
":",
"intra_clust_dists",
"/=",
"denom",
"sil_samples",
"=",
"inter_clust_dists",
"-",
"intra_clust_dists",
"with",
"np",
".",
"errstate",
"(",
"divide",
"=",
"\"ignore\"",
",",
"invalid",
"=",
"\"ignore\"",
")",
":",
"sil_samples",
"/=",
"np",
".",
"maximum",
"(",
"intra_clust_dists",
",",
"inter_clust_dists",
")",
"# nan values are for clusters of size 1, and should be 0",
"return",
"np",
".",
"nan_to_num",
"(",
"sil_samples",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/metrics/cluster/_unsupervised.py#L152-L247 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | HyperlinkCtrl.SetVisited | (*args, **kwargs) | return _controls_.HyperlinkCtrl_SetVisited(*args, **kwargs) | SetVisited(self, bool visited=True) | SetVisited(self, bool visited=True) | [
"SetVisited",
"(",
"self",
"bool",
"visited",
"=",
"True",
")"
] | def SetVisited(*args, **kwargs):
"""SetVisited(self, bool visited=True)"""
return _controls_.HyperlinkCtrl_SetVisited(*args, **kwargs) | [
"def",
"SetVisited",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"HyperlinkCtrl_SetVisited",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L6662-L6664 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TDbStr.__eq__ | (self, *args) | return _snap.TDbStr___eq__(self, *args) | __eq__(TDbStr self, TDbStr DbStr) -> bool
Parameters:
DbStr: TDbStr const & | __eq__(TDbStr self, TDbStr DbStr) -> bool | [
"__eq__",
"(",
"TDbStr",
"self",
"TDbStr",
"DbStr",
")",
"-",
">",
"bool"
] | def __eq__(self, *args):
"""
__eq__(TDbStr self, TDbStr DbStr) -> bool
Parameters:
DbStr: TDbStr const &
"""
return _snap.TDbStr___eq__(self, *args) | [
"def",
"__eq__",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TDbStr___eq__",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L11445-L11453 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/commands/rsync.py | python | _DecodeUrl | (enc_url_string) | return urllib.unquote_plus(enc_url_string).decode(UTF8) | Inverts encoding from EncodeUrl.
Args:
enc_url_string: String URL to decode.
Returns:
decoded URL. | Inverts encoding from EncodeUrl. | [
"Inverts",
"encoding",
"from",
"EncodeUrl",
"."
] | def _DecodeUrl(enc_url_string):
"""Inverts encoding from EncodeUrl.
Args:
enc_url_string: String URL to decode.
Returns:
decoded URL.
"""
return urllib.unquote_plus(enc_url_string).decode(UTF8) | [
"def",
"_DecodeUrl",
"(",
"enc_url_string",
")",
":",
"return",
"urllib",
".",
"unquote_plus",
"(",
"enc_url_string",
")",
".",
"decode",
"(",
"UTF8",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/commands/rsync.py#L598-L607 | |
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | llvm/bindings/python/llvm/core.py | python | Module.target | (self, new_target) | new_target is a string. | new_target is a string. | [
"new_target",
"is",
"a",
"string",
"."
] | def target(self, new_target):
"""new_target is a string."""
lib.LLVMSetTarget(self, new_target) | [
"def",
"target",
"(",
"self",
",",
"new_target",
")",
":",
"lib",
".",
"LLVMSetTarget",
"(",
"self",
",",
"new_target",
")"
] | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/llvm/bindings/python/llvm/core.py#L221-L223 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py | python | ParserElement.__mul__ | (self,other) | return ret | Implementation of * operator, allows use of C{expr * 3} in place of
C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
may also include C{None} as in:
- C{expr*(n,None)} or C{expr*(n,)} is equivalent
to C{expr*n + L{ZeroOrMore}(expr)}
(read as "at least n instances of C{expr}")
- C{expr*(None,n)} is equivalent to C{expr*(0,n)}
(read as "0 to n instances of C{expr}")
- C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
- C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)}
Note that C{expr*(None,n)} does not raise an exception if
more than n exprs exist in the input stream; that is,
C{expr*(None,n)} does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
C{expr*(None,n) + ~expr} | [] | def __mul__(self,other):
"""
Implementation of * operator, allows use of C{expr * 3} in place of
C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
may also include C{None} as in:
- C{expr*(n,None)} or C{expr*(n,)} is equivalent
to C{expr*n + L{ZeroOrMore}(expr)}
(read as "at least n instances of C{expr}")
- C{expr*(None,n)} is equivalent to C{expr*(0,n)}
(read as "0 to n instances of C{expr}")
- C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
- C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)}
Note that C{expr*(None,n)} does not raise an exception if
more than n exprs exist in the input stream; that is,
C{expr*(None,n)} does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
C{expr*(None,n) + ~expr}
"""
if isinstance(other,int):
minElements, optElements = other,0
elif isinstance(other,tuple):
other = (other + (None, None))[:2]
if other[0] is None:
other = (0, other[1])
if isinstance(other[0],int) and other[1] is None:
if other[0] == 0:
return ZeroOrMore(self)
if other[0] == 1:
return OneOrMore(self)
else:
return self*other[0] + ZeroOrMore(self)
elif isinstance(other[0],int) and isinstance(other[1],int):
minElements, optElements = other
optElements -= minElements
else:
raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1]))
else:
raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
if minElements < 0:
raise ValueError("cannot multiply ParserElement by negative value")
if optElements < 0:
raise ValueError("second tuple value must be greater or equal to first tuple value")
if minElements == optElements == 0:
raise ValueError("cannot multiply ParserElement by 0 or (0,0)")
if (optElements):
def makeOptionalList(n):
if n>1:
return Optional(self + makeOptionalList(n-1))
else:
return Optional(self)
if minElements:
if minElements == 1:
ret = self + makeOptionalList(optElements)
else:
ret = And([self]*minElements) + makeOptionalList(optElements)
else:
ret = makeOptionalList(optElements)
else:
if minElements == 1:
ret = self
else:
ret = And([self]*minElements)
return ret | [
"def",
"__mul__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"int",
")",
":",
"minElements",
",",
"optElements",
"=",
"other",
",",
"0",
"elif",
"isinstance",
"(",
"other",
",",
"tuple",
")",
":",
"other",
"=",
"(",
"other",
"+",
"(",
"None",
",",
"None",
")",
")",
"[",
":",
"2",
"]",
"if",
"other",
"[",
"0",
"]",
"is",
"None",
":",
"other",
"=",
"(",
"0",
",",
"other",
"[",
"1",
"]",
")",
"if",
"isinstance",
"(",
"other",
"[",
"0",
"]",
",",
"int",
")",
"and",
"other",
"[",
"1",
"]",
"is",
"None",
":",
"if",
"other",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"ZeroOrMore",
"(",
"self",
")",
"if",
"other",
"[",
"0",
"]",
"==",
"1",
":",
"return",
"OneOrMore",
"(",
"self",
")",
"else",
":",
"return",
"self",
"*",
"other",
"[",
"0",
"]",
"+",
"ZeroOrMore",
"(",
"self",
")",
"elif",
"isinstance",
"(",
"other",
"[",
"0",
"]",
",",
"int",
")",
"and",
"isinstance",
"(",
"other",
"[",
"1",
"]",
",",
"int",
")",
":",
"minElements",
",",
"optElements",
"=",
"other",
"optElements",
"-=",
"minElements",
"else",
":",
"raise",
"TypeError",
"(",
"\"cannot multiply 'ParserElement' and ('%s','%s') objects\"",
",",
"type",
"(",
"other",
"[",
"0",
"]",
")",
",",
"type",
"(",
"other",
"[",
"1",
"]",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"cannot multiply 'ParserElement' and '%s' objects\"",
",",
"type",
"(",
"other",
")",
")",
"if",
"minElements",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"cannot multiply ParserElement by negative value\"",
")",
"if",
"optElements",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"second tuple value must be greater or equal to first tuple value\"",
")",
"if",
"minElements",
"==",
"optElements",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"cannot multiply ParserElement by 0 or (0,0)\"",
")",
"if",
"(",
"optElements",
")",
":",
"def",
"makeOptionalList",
"(",
"n",
")",
":",
"if",
"n",
">",
"1",
":",
"return",
"Optional",
"(",
"self",
"+",
"makeOptionalList",
"(",
"n",
"-",
"1",
")",
")",
"else",
":",
"return",
"Optional",
"(",
"self",
")",
"if",
"minElements",
":",
"if",
"minElements",
"==",
"1",
":",
"ret",
"=",
"self",
"+",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"ret",
"=",
"And",
"(",
"[",
"self",
"]",
"*",
"minElements",
")",
"+",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"ret",
"=",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"if",
"minElements",
"==",
"1",
":",
"ret",
"=",
"self",
"else",
":",
"ret",
"=",
"And",
"(",
"[",
"self",
"]",
"*",
"minElements",
")",
"return",
"ret"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing.py#L3753-L3885 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/code_coverage/croc_html.py | python | HtmlElement.Text | (self, text) | return self | Adds a text node.
Args:
text: Text to add.
Returns:
self. | Adds a text node. | [
"Adds",
"a",
"text",
"node",
"."
] | def Text(self, text):
"""Adds a text node.
Args:
text: Text to add.
Returns:
self.
"""
t = self.doc.createTextNode(str(text))
self.element.appendChild(t)
return self | [
"def",
"Text",
"(",
"self",
",",
"text",
")",
":",
"t",
"=",
"self",
".",
"doc",
".",
"createTextNode",
"(",
"str",
"(",
"text",
")",
")",
"self",
".",
"element",
".",
"appendChild",
"(",
"t",
")",
"return",
"self"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/code_coverage/croc_html.py#L54-L65 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/numpy/multiarray.py | python | hamming | (M, dtype=None, device=None) | return _mx_nd_np.hamming(M, dtype=dtype, device=device) | r"""Return the hamming window.
The hamming window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
device : Device, optional
Device context on which the memory is allocated. Default is
`mxnet.device.current_device()`.
Returns
-------
out : ndarray, shape(M,)
The window, with the maximum value normalized to one (the value
one appears only if `M` is odd).
When npx.is_np_default_dtype() returns False, default dtype is float32;
When npx.is_np_default_dtype() returns True, default dtype is float64.
Note that you need select numpy.float32 or float64 in this operator.
See Also
--------
blackman, hanning
Notes
-----
The Hamming window is defined as
.. math:: w(n) = 0.54 - 0.46cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The Hamming was named for R. W. Hamming, an associate of J. W. Tukey
and is described in Blackman and Tukey. It was recommended for
smoothing the truncated autocovariance function in the time domain.
Most references to the Hamming window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
University of Alberta Press, 1975, pp. 109-110.
.. [3] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> np.hamming(12)
array([0.08000001, 0.15302339, 0.34890914, 0.6054648 , 0.841236 ,
0.9813669 , 0.9813668 , 0.8412359 , 0.6054647 , 0.34890908,
0.15302327, 0.08000001])
Plot the window and its frequency response:
>>> import matplotlib.pyplot as plt
>>> window = np.hamming(51)
>>> plt.plot(window.asnumpy())
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("hamming window")
Text(0.5, 1.0, 'hamming window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show() | r"""Return the hamming window. | [
"r",
"Return",
"the",
"hamming",
"window",
"."
] | def hamming(M, dtype=None, device=None):
r"""Return the hamming window.
The hamming window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
device : Device, optional
Device context on which the memory is allocated. Default is
`mxnet.device.current_device()`.
Returns
-------
out : ndarray, shape(M,)
The window, with the maximum value normalized to one (the value
one appears only if `M` is odd).
When npx.is_np_default_dtype() returns False, default dtype is float32;
When npx.is_np_default_dtype() returns True, default dtype is float64.
Note that you need select numpy.float32 or float64 in this operator.
See Also
--------
blackman, hanning
Notes
-----
The Hamming window is defined as
.. math:: w(n) = 0.54 - 0.46cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The Hamming was named for R. W. Hamming, an associate of J. W. Tukey
and is described in Blackman and Tukey. It was recommended for
smoothing the truncated autocovariance function in the time domain.
Most references to the Hamming window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
University of Alberta Press, 1975, pp. 109-110.
.. [3] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> np.hamming(12)
array([0.08000001, 0.15302339, 0.34890914, 0.6054648 , 0.841236 ,
0.9813669 , 0.9813668 , 0.8412359 , 0.6054647 , 0.34890908,
0.15302327, 0.08000001])
Plot the window and its frequency response:
>>> import matplotlib.pyplot as plt
>>> window = np.hamming(51)
>>> plt.plot(window.asnumpy())
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("hamming window")
Text(0.5, 1.0, 'hamming window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
"""
return _mx_nd_np.hamming(M, dtype=dtype, device=device) | [
"def",
"hamming",
"(",
"M",
",",
"dtype",
"=",
"None",
",",
"device",
"=",
"None",
")",
":",
"return",
"_mx_nd_np",
".",
"hamming",
"(",
"M",
",",
"dtype",
"=",
"dtype",
",",
"device",
"=",
"device",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L9041-L9116 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/engine/training_utils_v1.py | python | SliceAggregator._slice_assign | (self, batch_element, batch_start, batch_end, is_finished) | Legacy utility method to slice input arrays. | Legacy utility method to slice input arrays. | [
"Legacy",
"utility",
"method",
"to",
"slice",
"input",
"arrays",
"."
] | def _slice_assign(self, batch_element, batch_start, batch_end, is_finished):
"""Legacy utility method to slice input arrays."""
try:
self.results[batch_start:batch_end] = batch_element
except Exception as e: # pylint: disable=broad-except
# `_slice_assign` should only be called in threads and exceptions raised
# in threads do not carry over to the main thread. So instead we perform a
# a broad catch in the thread and then store the exception to be re-raised
# in the main thread.
self._errors.append(e)
finally:
is_finished.set() | [
"def",
"_slice_assign",
"(",
"self",
",",
"batch_element",
",",
"batch_start",
",",
"batch_end",
",",
"is_finished",
")",
":",
"try",
":",
"self",
".",
"results",
"[",
"batch_start",
":",
"batch_end",
"]",
"=",
"batch_element",
"except",
"Exception",
"as",
"e",
":",
"# pylint: disable=broad-except",
"# `_slice_assign` should only be called in threads and exceptions raised",
"# in threads do not carry over to the main thread. So instead we perform a",
"# a broad catch in the thread and then store the exception to be re-raised",
"# in the main thread.",
"self",
".",
"_errors",
".",
"append",
"(",
"e",
")",
"finally",
":",
"is_finished",
".",
"set",
"(",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/training_utils_v1.py#L399-L412 | ||
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Build.py | python | BuildContext.get_targets | (self) | return (min_grp, to_post) | This method returns a pair containing the index of the last build group to post,
and the list of task generator objects corresponding to the target names.
This is used internally by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
to perform partial builds::
$ waf --targets=myprogram,myshlib
:return: the minimum build group index, and list of task generators
:rtype: tuple | This method returns a pair containing the index of the last build group to post,
and the list of task generator objects corresponding to the target names. | [
"This",
"method",
"returns",
"a",
"pair",
"containing",
"the",
"index",
"of",
"the",
"last",
"build",
"group",
"to",
"post",
"and",
"the",
"list",
"of",
"task",
"generator",
"objects",
"corresponding",
"to",
"the",
"target",
"names",
"."
] | def get_targets(self):
"""
This method returns a pair containing the index of the last build group to post,
and the list of task generator objects corresponding to the target names.
This is used internally by :py:meth:`waflib.Build.BuildContext.get_build_iterator`
to perform partial builds::
$ waf --targets=myprogram,myshlib
:return: the minimum build group index, and list of task generators
:rtype: tuple
"""
to_post = []
min_grp = 0
for name in self.targets.split(','):
tg = self.get_tgen_by_name(name)
m = self.get_group_idx(tg)
if m > min_grp:
min_grp = m
to_post = [tg]
elif m == min_grp:
to_post.append(tg)
return (min_grp, to_post) | [
"def",
"get_targets",
"(",
"self",
")",
":",
"to_post",
"=",
"[",
"]",
"min_grp",
"=",
"0",
"for",
"name",
"in",
"self",
".",
"targets",
".",
"split",
"(",
"','",
")",
":",
"tg",
"=",
"self",
".",
"get_tgen_by_name",
"(",
"name",
")",
"m",
"=",
"self",
".",
"get_group_idx",
"(",
"tg",
")",
"if",
"m",
">",
"min_grp",
":",
"min_grp",
"=",
"m",
"to_post",
"=",
"[",
"tg",
"]",
"elif",
"m",
"==",
"min_grp",
":",
"to_post",
".",
"append",
"(",
"tg",
")",
"return",
"(",
"min_grp",
",",
"to_post",
")"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Build.py#L696-L719 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/isis_reduction_steps.py | python | ConvertToQISIS._set_up_q_resolution_parameters | (self) | Prepare the parameters which need preparing | Prepare the parameters which need preparing | [
"Prepare",
"the",
"parameters",
"which",
"need",
"preparing"
] | def _set_up_q_resolution_parameters(self):
'''
Prepare the parameters which need preparing
'''
# If we have values for H1 and W1 then set A1 to the correct value
if self._q_resolution_h1 and self._q_resolution_w1 and self._q_resolution_h2 and self._q_resolution_w2:
self._q_resolution_a1 = self._set_up_diameter(self._q_resolution_h1, self._q_resolution_w1)
self._q_resolution_a2 = self._set_up_diameter(self._q_resolution_h2, self._q_resolution_w2) | [
"def",
"_set_up_q_resolution_parameters",
"(",
"self",
")",
":",
"# If we have values for H1 and W1 then set A1 to the correct value",
"if",
"self",
".",
"_q_resolution_h1",
"and",
"self",
".",
"_q_resolution_w1",
"and",
"self",
".",
"_q_resolution_h2",
"and",
"self",
".",
"_q_resolution_w2",
":",
"self",
".",
"_q_resolution_a1",
"=",
"self",
".",
"_set_up_diameter",
"(",
"self",
".",
"_q_resolution_h1",
",",
"self",
".",
"_q_resolution_w1",
")",
"self",
".",
"_q_resolution_a2",
"=",
"self",
".",
"_set_up_diameter",
"(",
"self",
".",
"_q_resolution_h2",
",",
"self",
".",
"_q_resolution_w2",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/isis_reduction_steps.py#L2994-L3001 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py | python | Context.is_qnan | (self, a) | return a.is_qnan() | Return True if the operand is a quiet NaN; otherwise return False.
>>> ExtendedContext.is_qnan(Decimal('2.50'))
False
>>> ExtendedContext.is_qnan(Decimal('NaN'))
True
>>> ExtendedContext.is_qnan(Decimal('sNaN'))
False
>>> ExtendedContext.is_qnan(1)
False | Return True if the operand is a quiet NaN; otherwise return False. | [
"Return",
"True",
"if",
"the",
"operand",
"is",
"a",
"quiet",
"NaN",
";",
"otherwise",
"return",
"False",
"."
] | def is_qnan(self, a):
"""Return True if the operand is a quiet NaN; otherwise return False.
>>> ExtendedContext.is_qnan(Decimal('2.50'))
False
>>> ExtendedContext.is_qnan(Decimal('NaN'))
True
>>> ExtendedContext.is_qnan(Decimal('sNaN'))
False
>>> ExtendedContext.is_qnan(1)
False
"""
a = _convert_other(a, raiseit=True)
return a.is_qnan() | [
"def",
"is_qnan",
"(",
"self",
",",
"a",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"is_qnan",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L4399-L4412 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_snaps.py | python | Draft_Snap_Angle.Activated | (self) | Execute when the command is called. | Execute when the command is called. | [
"Execute",
"when",
"the",
"command",
"is",
"called",
"."
] | def Activated(self):
"""Execute when the command is called."""
super(Draft_Snap_Angle, self).Activated()
if hasattr(Gui, "Snapper"):
status = Gui.Snapper.toggle_snap('Angle')
# change interface consistently
sync_snap_toolbar_button("Draft_Snap_Angle"+"_Button", status)
sync_snap_statusbar_button("Draft_Snap_Angle_Statusbutton", status) | [
"def",
"Activated",
"(",
"self",
")",
":",
"super",
"(",
"Draft_Snap_Angle",
",",
"self",
")",
".",
"Activated",
"(",
")",
"if",
"hasattr",
"(",
"Gui",
",",
"\"Snapper\"",
")",
":",
"status",
"=",
"Gui",
".",
"Snapper",
".",
"toggle_snap",
"(",
"'Angle'",
")",
"# change interface consistently",
"sync_snap_toolbar_button",
"(",
"\"Draft_Snap_Angle\"",
"+",
"\"_Button\"",
",",
"status",
")",
"sync_snap_statusbar_button",
"(",
"\"Draft_Snap_Angle_Statusbutton\"",
",",
"status",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_snaps.py#L347-L355 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/sparse_ops.py | python | sparse_merge | (sp_ids, sp_values, vocab_size, name=None,
already_sorted=False) | Combines a batch of feature ids and values into a single `SparseTensor`.
The most common use case for this function occurs when feature ids and
their corresponding values are stored in `Example` protos on disk.
`parse_example` will return a batch of ids and a batch of values, and this
function joins them into a single logical `SparseTensor` for use in
functions such as `sparse_tensor_dense_matmul`, `sparse_to_dense`, etc.
The `SparseTensor` returned by this function has the following properties:
- `indices` is equivalent to `sp_ids.indices` with the last
dimension discarded and replaced with `sp_ids.values`.
- `values` is simply `sp_values.values`.
- If `sp_ids.shape = [D0, D1, ..., Dn, K]`, then
`output.shape = [D0, D1, ..., Dn, vocab_size]`.
For example, consider the following feature vectors:
```python
vector1 = [-3, 0, 0, 0, 0, 0]
vector2 = [ 0, 1, 0, 4, 1, 0]
vector3 = [ 5, 0, 0, 9, 0, 0]
```
These might be stored sparsely in the following Example protos by storing
only the feature ids (column number if the vectors are treated as a matrix)
of the non-zero elements and the corresponding values:
```python
examples = [Example(features={
"ids": Feature(int64_list=Int64List(value=[0])),
"values": Feature(float_list=FloatList(value=[-3]))}),
Example(features={
"ids": Feature(int64_list=Int64List(value=[1, 4, 3])),
"values": Feature(float_list=FloatList(value=[1, 1, 4]))}),
Example(features={
"ids": Feature(int64_list=Int64List(value=[0, 3])),
"values": Feature(float_list=FloatList(value=[5, 9]))})]
```
The result of calling parse_example on these examples will produce a
dictionary with entries for "ids" and "values". Passing those two objects
to this function along with vocab_size=6, will produce a `SparseTensor` that
sparsely represents all three instances. Namely, the `indices` property will
contain the coordinates of the non-zero entries in the feature matrix (the
first dimension is the row number in the matrix, i.e., the index within the
batch, and the second dimension is the column number, i.e., the feature id);
`values` will contain the actual values. `shape` will be the shape of the
original matrix, i.e., (3, 6). For our example above, the output will be
equal to:
```python
SparseTensor(indices=[[0, 0], [1, 1], [1, 3], [1, 4], [2, 0], [2, 3]],
values=[-3, 1, 4, 1, 5, 9],
shape=[3, 6])
```
Args:
sp_ids: A `SparseTensor` with `values` property of type `int32`
or `int64`.
sp_values: A`SparseTensor` of any type.
vocab_size: A scalar `int64` Tensor (or Python int) containing the new size
of the last dimension, `all(0 <= sp_ids.values < vocab_size)`.
name: A name prefix for the returned tensors (optional)
already_sorted: A boolean to specify whether the per-batch values in
`sp_values` are already sorted. If so skip sorting, False by default
(optional).
Returns:
A `SparseTensor` compactly representing a batch of feature ids and values,
useful for passing to functions that expect such a `SparseTensor`.
Raises:
TypeError: If `sp_ids` or `sp_values` are not a `SparseTensor`. | Combines a batch of feature ids and values into a single `SparseTensor`. | [
"Combines",
"a",
"batch",
"of",
"feature",
"ids",
"and",
"values",
"into",
"a",
"single",
"SparseTensor",
"."
] | def sparse_merge(sp_ids, sp_values, vocab_size, name=None,
already_sorted=False):
"""Combines a batch of feature ids and values into a single `SparseTensor`.
The most common use case for this function occurs when feature ids and
their corresponding values are stored in `Example` protos on disk.
`parse_example` will return a batch of ids and a batch of values, and this
function joins them into a single logical `SparseTensor` for use in
functions such as `sparse_tensor_dense_matmul`, `sparse_to_dense`, etc.
The `SparseTensor` returned by this function has the following properties:
- `indices` is equivalent to `sp_ids.indices` with the last
dimension discarded and replaced with `sp_ids.values`.
- `values` is simply `sp_values.values`.
- If `sp_ids.shape = [D0, D1, ..., Dn, K]`, then
`output.shape = [D0, D1, ..., Dn, vocab_size]`.
For example, consider the following feature vectors:
```python
vector1 = [-3, 0, 0, 0, 0, 0]
vector2 = [ 0, 1, 0, 4, 1, 0]
vector3 = [ 5, 0, 0, 9, 0, 0]
```
These might be stored sparsely in the following Example protos by storing
only the feature ids (column number if the vectors are treated as a matrix)
of the non-zero elements and the corresponding values:
```python
examples = [Example(features={
"ids": Feature(int64_list=Int64List(value=[0])),
"values": Feature(float_list=FloatList(value=[-3]))}),
Example(features={
"ids": Feature(int64_list=Int64List(value=[1, 4, 3])),
"values": Feature(float_list=FloatList(value=[1, 1, 4]))}),
Example(features={
"ids": Feature(int64_list=Int64List(value=[0, 3])),
"values": Feature(float_list=FloatList(value=[5, 9]))})]
```
The result of calling parse_example on these examples will produce a
dictionary with entries for "ids" and "values". Passing those two objects
to this function along with vocab_size=6, will produce a `SparseTensor` that
sparsely represents all three instances. Namely, the `indices` property will
contain the coordinates of the non-zero entries in the feature matrix (the
first dimension is the row number in the matrix, i.e., the index within the
batch, and the second dimension is the column number, i.e., the feature id);
`values` will contain the actual values. `shape` will be the shape of the
original matrix, i.e., (3, 6). For our example above, the output will be
equal to:
```python
SparseTensor(indices=[[0, 0], [1, 1], [1, 3], [1, 4], [2, 0], [2, 3]],
values=[-3, 1, 4, 1, 5, 9],
shape=[3, 6])
```
Args:
sp_ids: A `SparseTensor` with `values` property of type `int32`
or `int64`.
sp_values: A`SparseTensor` of any type.
vocab_size: A scalar `int64` Tensor (or Python int) containing the new size
of the last dimension, `all(0 <= sp_ids.values < vocab_size)`.
name: A name prefix for the returned tensors (optional)
already_sorted: A boolean to specify whether the per-batch values in
`sp_values` are already sorted. If so skip sorting, False by default
(optional).
Returns:
A `SparseTensor` compactly representing a batch of feature ids and values,
useful for passing to functions that expect such a `SparseTensor`.
Raises:
TypeError: If `sp_ids` or `sp_values` are not a `SparseTensor`.
"""
if not isinstance(sp_ids, ops.SparseTensor):
raise TypeError("sp_ids must be a SparseTensor")
if not isinstance(sp_values, ops.SparseTensor):
raise TypeError("sp_values must be a SparseTensor")
with ops.op_scope([sp_ids, sp_values], name, "SparseMerge"):
indices_shape = array_ops.shape(sp_ids.indices)
rank = indices_shape[1]
ids = sp_ids.values
if ids.dtype != dtypes.int64:
ids = math_ops.cast(ids, dtypes.int64)
# Slice off the last dimension of indices, then tack on the ids
indices_columns_to_preserve = array_ops.slice(
sp_ids.indices, [0, 0], array_ops.pack([-1, rank - 1]))
new_indices = array_ops.concat(1, [indices_columns_to_preserve,
array_ops.reshape(ids, [-1, 1])])
new_values = sp_values.values
new_shape = array_ops.concat(
0,
[array_ops.slice(sp_ids.shape, [0], array_ops.expand_dims(rank - 1, 0)),
math_ops.cast(array_ops.pack([vocab_size]), dtypes.int64)])
result = ops.SparseTensor(new_indices, new_values, new_shape)
return result if already_sorted else sparse_reorder(result) | [
"def",
"sparse_merge",
"(",
"sp_ids",
",",
"sp_values",
",",
"vocab_size",
",",
"name",
"=",
"None",
",",
"already_sorted",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"sp_ids",
",",
"ops",
".",
"SparseTensor",
")",
":",
"raise",
"TypeError",
"(",
"\"sp_ids must be a SparseTensor\"",
")",
"if",
"not",
"isinstance",
"(",
"sp_values",
",",
"ops",
".",
"SparseTensor",
")",
":",
"raise",
"TypeError",
"(",
"\"sp_values must be a SparseTensor\"",
")",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"sp_ids",
",",
"sp_values",
"]",
",",
"name",
",",
"\"SparseMerge\"",
")",
":",
"indices_shape",
"=",
"array_ops",
".",
"shape",
"(",
"sp_ids",
".",
"indices",
")",
"rank",
"=",
"indices_shape",
"[",
"1",
"]",
"ids",
"=",
"sp_ids",
".",
"values",
"if",
"ids",
".",
"dtype",
"!=",
"dtypes",
".",
"int64",
":",
"ids",
"=",
"math_ops",
".",
"cast",
"(",
"ids",
",",
"dtypes",
".",
"int64",
")",
"# Slice off the last dimension of indices, then tack on the ids",
"indices_columns_to_preserve",
"=",
"array_ops",
".",
"slice",
"(",
"sp_ids",
".",
"indices",
",",
"[",
"0",
",",
"0",
"]",
",",
"array_ops",
".",
"pack",
"(",
"[",
"-",
"1",
",",
"rank",
"-",
"1",
"]",
")",
")",
"new_indices",
"=",
"array_ops",
".",
"concat",
"(",
"1",
",",
"[",
"indices_columns_to_preserve",
",",
"array_ops",
".",
"reshape",
"(",
"ids",
",",
"[",
"-",
"1",
",",
"1",
"]",
")",
"]",
")",
"new_values",
"=",
"sp_values",
".",
"values",
"new_shape",
"=",
"array_ops",
".",
"concat",
"(",
"0",
",",
"[",
"array_ops",
".",
"slice",
"(",
"sp_ids",
".",
"shape",
",",
"[",
"0",
"]",
",",
"array_ops",
".",
"expand_dims",
"(",
"rank",
"-",
"1",
",",
"0",
")",
")",
",",
"math_ops",
".",
"cast",
"(",
"array_ops",
".",
"pack",
"(",
"[",
"vocab_size",
"]",
")",
",",
"dtypes",
".",
"int64",
")",
"]",
")",
"result",
"=",
"ops",
".",
"SparseTensor",
"(",
"new_indices",
",",
"new_values",
",",
"new_shape",
")",
"return",
"result",
"if",
"already_sorted",
"else",
"sparse_reorder",
"(",
"result",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/sparse_ops.py#L778-L882 | ||
telefonicaid/fiware-orion | 27c3202b9ddcfb9e3635a0af8d373f76e89b1d24 | scripts/cpplint.py | python | RemoveMultiLineComments | (filename, lines, error) | Removes multiline (c-style) comments from lines. | Removes multiline (c-style) comments from lines. | [
"Removes",
"multiline",
"(",
"c",
"-",
"style",
")",
"comments",
"from",
"lines",
"."
] | def RemoveMultiLineComments(filename, lines, error):
"""Removes multiline (c-style) comments from lines."""
lineix = 0
while lineix < len(lines):
lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
if lineix_begin >= len(lines):
return
lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
if lineix_end >= len(lines):
error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
'Could not find end of multi-line comment')
return
RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
lineix = lineix_end + 1 | [
"def",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"lineix",
"=",
"0",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"lineix_begin",
"=",
"FindNextMultiLineCommentStart",
"(",
"lines",
",",
"lineix",
")",
"if",
"lineix_begin",
">=",
"len",
"(",
"lines",
")",
":",
"return",
"lineix_end",
"=",
"FindNextMultiLineCommentEnd",
"(",
"lines",
",",
"lineix_begin",
")",
"if",
"lineix_end",
">=",
"len",
"(",
"lines",
")",
":",
"error",
"(",
"filename",
",",
"lineix_begin",
"+",
"1",
",",
"'readability/multiline_comment'",
",",
"5",
",",
"'Could not find end of multi-line comment'",
")",
"return",
"RemoveMultiLineCommentsFromRange",
"(",
"lines",
",",
"lineix_begin",
",",
"lineix_end",
"+",
"1",
")",
"lineix",
"=",
"lineix_end",
"+",
"1"
] | https://github.com/telefonicaid/fiware-orion/blob/27c3202b9ddcfb9e3635a0af8d373f76e89b1d24/scripts/cpplint.py#L891-L904 | ||
jubatus/jubatus | 1251ce551bac980488a6313728e72b3fe0b79a9f | tools/codestyle/cpplint/cpplint.py | python | CheckForNonStandardConstructs | (filename, clean_lines, linenum,
class_state, error) | Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
- classes with virtual methods need virtual destructors (compiler warning
available, but not turned on yet.)
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
class_state: A _ClassState instance which maintains information about
the current stack of nested class declarations being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message | Logs an error if we see certain non-ANSI constructs ignored by gcc-2. | [
"Logs",
"an",
"error",
"if",
"we",
"see",
"certain",
"non",
"-",
"ANSI",
"constructs",
"ignored",
"by",
"gcc",
"-",
"2",
"."
] | def CheckForNonStandardConstructs(filename, clean_lines, linenum,
class_state, error):
"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
- classes with virtual methods need virtual destructors (compiler warning
available, but not turned on yet.)
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
class_state: A _ClassState instance which maintains information about
the current stack of nested class declarations being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(auto|register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage class (static, extern, typedef, etc) should be first.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Track class entry and exit, and attempt to find cases within the
# class declaration that don't meet the C++ style
# guidelines. Tracking is very dependent on the code matching Google
# style guidelines, but it seems to perform well enough in testing
# to be a worthwhile addition to the checks.
classinfo_stack = class_state.classinfo_stack
# Look for a class declaration. The regexp accounts for decorated classes
# such as in:
# class LOCKABLE API Object {
# };
class_decl_match = Match(
r'\s*(template\s*<[\w\s<>,:]*>\s*)?'
'(class|struct)\s+([A-Z_]+\s+)*(\w+(::\w+)*)', line)
if class_decl_match:
classinfo_stack.append(_ClassInfo(
class_decl_match.group(4), clean_lines, linenum))
# Everything else in this function uses the top of the stack if it's
# not empty.
if not classinfo_stack:
return
classinfo = classinfo_stack[-1]
# If the opening brace hasn't been seen look for it and also
# parent class declarations.
if not classinfo.seen_open_brace:
# If the line has a ';' in it, assume it's a forward declaration or
# a single-line class declaration, which we won't process.
if line.find(';') != -1:
classinfo_stack.pop()
return
classinfo.seen_open_brace = (line.find('{') != -1)
# Look for a bare ':'
if Search('(^|[^:]):($|[^:])', line):
classinfo.is_derived = True
if not classinfo.seen_open_brace:
return # Everything else in this function is for after open brace
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
% re.escape(base_classname),
line)
if (args and
args.group(1) != 'void' and
not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname),
args.group(1).strip())):
error(filename, linenum, 'runtime/explicit', 5,
'Single-argument constructors should be marked explicit.')
# Look for methods declared virtual.
if Search(r'\bvirtual\b', line):
classinfo.virtual_method_linenumber = linenum
# Only look for a destructor declaration on the same line. It would
# be extremely unlikely for the destructor declaration to occupy
# more than one line.
if Search(r'~%s\s*\(' % base_classname, line):
classinfo.has_virtual_destructor = True
# Look for class end.
brace_depth = classinfo.brace_depth
brace_depth = brace_depth + line.count('{') - line.count('}')
if brace_depth <= 0:
classinfo = classinfo_stack.pop()
# Try to detect missing virtual destructor declarations.
# For now, only warn if a non-derived class with virtual methods lacks
# a virtual destructor. This is to make it less likely that people will
# declare derived virtual destructors without declaring the base
# destructor virtual.
if ((classinfo.virtual_method_linenumber is not None) and
(not classinfo.has_virtual_destructor) and
(not classinfo.is_derived)): # Only warn for base classes
error(filename, classinfo.linenum, 'runtime/virtual', 4,
'The class %s probably needs a virtual destructor due to '
'having virtual method(s), one declared at line %d.'
% (classinfo.name, classinfo.virtual_method_linenumber))
else:
classinfo.brace_depth = brace_depth | [
"def",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"class_state",
",",
"error",
")",
":",
"# Remove comments from the line, but leave in strings for now.",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%[-+ ]?\\d*q'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"3",
",",
"'%q in format strings is deprecated. Use %ll instead.'",
")",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%\\d+\\$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"2",
",",
"'%N$ formats are unconventional. Try rewriting to avoid them.'",
")",
"# Remove escaped backslashes before looking for undefined escapes.",
"line",
"=",
"line",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"''",
")",
"if",
"Search",
"(",
"r'(\"|\\').*\\\\(%|\\[|\\(|{)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/printf_format'",
",",
"3",
",",
"'%, [, (, and { are undefined character escapes. Unescape them.'",
")",
"# For the rest, work with both comments and strings removed.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'\\b(const|volatile|void|char|short|int|long'",
"r'|float|double|signed|unsigned'",
"r'|schar|u?int8|u?int16|u?int32|u?int64)'",
"r'\\s+(auto|register|static|extern|typedef)\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/storage_class'",
",",
"5",
",",
"'Storage class (static, extern, typedef, etc) should be first.'",
")",
"if",
"Match",
"(",
"r'\\s*#\\s*endif\\s*[^/\\s]+'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/endif_comment'",
",",
"5",
",",
"'Uncommented text after #endif is non-standard. Use a comment.'",
")",
"if",
"Match",
"(",
"r'\\s*class\\s+(\\w+\\s*::\\s*)+\\w+\\s*;'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/forward_decl'",
",",
"5",
",",
"'Inner-style forward declarations are invalid. Remove this line.'",
")",
"if",
"Search",
"(",
"r'(\\w+|[+-]?\\d+(\\.\\d*)?)\\s*(<|>)\\?=?\\s*(\\w+|[+-]?\\d+)(\\.\\d*)?'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/deprecated'",
",",
"3",
",",
"'>? and <? (max and min) operators are non-standard and deprecated.'",
")",
"if",
"Search",
"(",
"r'^\\s*const\\s*string\\s*&\\s*\\w+\\s*;'",
",",
"line",
")",
":",
"# TODO(unknown): Could it be expanded safely to arbitrary references,",
"# without triggering too many false positives? The first",
"# attempt triggered 5 warnings for mostly benign code in the regtest, hence",
"# the restriction.",
"# Here's the original regexp, for the reference:",
"# type_name = r'\\w+((\\s*::\\s*\\w+)|(\\s*<\\s*\\w+?\\s*>))?'",
"# r'\\s*const\\s*' + type_name + '\\s*&\\s*\\w+\\s*;'",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/member_string_references'",
",",
"2",
",",
"'const string& members are dangerous. It is much better to use '",
"'alternatives, such as pointers or simple constants.'",
")",
"# Track class entry and exit, and attempt to find cases within the",
"# class declaration that don't meet the C++ style",
"# guidelines. Tracking is very dependent on the code matching Google",
"# style guidelines, but it seems to perform well enough in testing",
"# to be a worthwhile addition to the checks.",
"classinfo_stack",
"=",
"class_state",
".",
"classinfo_stack",
"# Look for a class declaration. The regexp accounts for decorated classes",
"# such as in:",
"# class LOCKABLE API Object {",
"# };",
"class_decl_match",
"=",
"Match",
"(",
"r'\\s*(template\\s*<[\\w\\s<>,:]*>\\s*)?'",
"'(class|struct)\\s+([A-Z_]+\\s+)*(\\w+(::\\w+)*)'",
",",
"line",
")",
"if",
"class_decl_match",
":",
"classinfo_stack",
".",
"append",
"(",
"_ClassInfo",
"(",
"class_decl_match",
".",
"group",
"(",
"4",
")",
",",
"clean_lines",
",",
"linenum",
")",
")",
"# Everything else in this function uses the top of the stack if it's",
"# not empty.",
"if",
"not",
"classinfo_stack",
":",
"return",
"classinfo",
"=",
"classinfo_stack",
"[",
"-",
"1",
"]",
"# If the opening brace hasn't been seen look for it and also",
"# parent class declarations.",
"if",
"not",
"classinfo",
".",
"seen_open_brace",
":",
"# If the line has a ';' in it, assume it's a forward declaration or",
"# a single-line class declaration, which we won't process.",
"if",
"line",
".",
"find",
"(",
"';'",
")",
"!=",
"-",
"1",
":",
"classinfo_stack",
".",
"pop",
"(",
")",
"return",
"classinfo",
".",
"seen_open_brace",
"=",
"(",
"line",
".",
"find",
"(",
"'{'",
")",
"!=",
"-",
"1",
")",
"# Look for a bare ':'",
"if",
"Search",
"(",
"'(^|[^:]):($|[^:])'",
",",
"line",
")",
":",
"classinfo",
".",
"is_derived",
"=",
"True",
"if",
"not",
"classinfo",
".",
"seen_open_brace",
":",
"return",
"# Everything else in this function is for after open brace",
"# The class may have been declared with namespace or classname qualifiers.",
"# The constructor and destructor will not have those qualifiers.",
"base_classname",
"=",
"classinfo",
".",
"name",
".",
"split",
"(",
"'::'",
")",
"[",
"-",
"1",
"]",
"# Look for single-argument constructors that aren't marked explicit.",
"# Technically a valid construct, but against style.",
"args",
"=",
"Match",
"(",
"r'\\s+(?:inline\\s+)?%s\\s*\\(([^,()]+)\\)'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"line",
")",
"if",
"(",
"args",
"and",
"args",
".",
"group",
"(",
"1",
")",
"!=",
"'void'",
"and",
"not",
"Match",
"(",
"r'(const\\s+)?%s\\s*(?:<\\w+>\\s*)?&'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"args",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Single-argument constructors should be marked explicit.'",
")",
"# Look for methods declared virtual.",
"if",
"Search",
"(",
"r'\\bvirtual\\b'",
",",
"line",
")",
":",
"classinfo",
".",
"virtual_method_linenumber",
"=",
"linenum",
"# Only look for a destructor declaration on the same line. It would",
"# be extremely unlikely for the destructor declaration to occupy",
"# more than one line.",
"if",
"Search",
"(",
"r'~%s\\s*\\('",
"%",
"base_classname",
",",
"line",
")",
":",
"classinfo",
".",
"has_virtual_destructor",
"=",
"True",
"# Look for class end.",
"brace_depth",
"=",
"classinfo",
".",
"brace_depth",
"brace_depth",
"=",
"brace_depth",
"+",
"line",
".",
"count",
"(",
"'{'",
")",
"-",
"line",
".",
"count",
"(",
"'}'",
")",
"if",
"brace_depth",
"<=",
"0",
":",
"classinfo",
"=",
"classinfo_stack",
".",
"pop",
"(",
")",
"# Try to detect missing virtual destructor declarations.",
"# For now, only warn if a non-derived class with virtual methods lacks",
"# a virtual destructor. This is to make it less likely that people will",
"# declare derived virtual destructors without declaring the base",
"# destructor virtual.",
"if",
"(",
"(",
"classinfo",
".",
"virtual_method_linenumber",
"is",
"not",
"None",
")",
"and",
"(",
"not",
"classinfo",
".",
"has_virtual_destructor",
")",
"and",
"(",
"not",
"classinfo",
".",
"is_derived",
")",
")",
":",
"# Only warn for base classes",
"error",
"(",
"filename",
",",
"classinfo",
".",
"linenum",
",",
"'runtime/virtual'",
",",
"4",
",",
"'The class %s probably needs a virtual destructor due to '",
"'having virtual method(s), one declared at line %d.'",
"%",
"(",
"classinfo",
".",
"name",
",",
"classinfo",
".",
"virtual_method_linenumber",
")",
")",
"else",
":",
"classinfo",
".",
"brace_depth",
"=",
"brace_depth"
] | https://github.com/jubatus/jubatus/blob/1251ce551bac980488a6313728e72b3fe0b79a9f/tools/codestyle/cpplint/cpplint.py#L1333-L1500 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/utils/generic_utils.py | python | has_arg | (fn, name, accept_all=False) | return name in arg_spec.args | Checks if a callable accepts a given keyword argument.
Arguments:
fn: Callable to inspect.
name: Check if `fn` can be called with `name` as a keyword argument.
accept_all: What to return if there is no parameter called `name`
but the function accepts a `**kwargs` argument.
Returns:
bool, whether `fn` accepts a `name` keyword argument. | Checks if a callable accepts a given keyword argument. | [
"Checks",
"if",
"a",
"callable",
"accepts",
"a",
"given",
"keyword",
"argument",
"."
] | def has_arg(fn, name, accept_all=False):
"""Checks if a callable accepts a given keyword argument.
Arguments:
fn: Callable to inspect.
name: Check if `fn` can be called with `name` as a keyword argument.
accept_all: What to return if there is no parameter called `name`
but the function accepts a `**kwargs` argument.
Returns:
bool, whether `fn` accepts a `name` keyword argument.
"""
arg_spec = tf_inspect.getargspec(fn)
if accept_all and arg_spec.keywords is not None:
return True
return name in arg_spec.args | [
"def",
"has_arg",
"(",
"fn",
",",
"name",
",",
"accept_all",
"=",
"False",
")",
":",
"arg_spec",
"=",
"tf_inspect",
".",
"getargspec",
"(",
"fn",
")",
"if",
"accept_all",
"and",
"arg_spec",
".",
"keywords",
"is",
"not",
"None",
":",
"return",
"True",
"return",
"name",
"in",
"arg_spec",
".",
"args"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/utils/generic_utils.py#L230-L245 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/hang_analyzer/process_list.py | python | _WindowsProcessList.__find_ps | () | return os.path.join(os.environ["WINDIR"], "system32", "tasklist.exe") | Find tasklist. | Find tasklist. | [
"Find",
"tasklist",
"."
] | def __find_ps():
"""Find tasklist."""
return os.path.join(os.environ["WINDIR"], "system32", "tasklist.exe") | [
"def",
"__find_ps",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"\"WINDIR\"",
"]",
",",
"\"system32\"",
",",
"\"tasklist.exe\"",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/hang_analyzer/process_list.py#L112-L114 | |
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | tools/blade/src/blade/console.py | python | colors | (name) | return '' | Return ansi console control sequence from color name | Return ansi console control sequence from color name | [
"Return",
"ansi",
"console",
"control",
"sequence",
"from",
"color",
"name"
] | def colors(name):
"""Return ansi console control sequence from color name"""
if color_enabled:
return _colors[name]
return '' | [
"def",
"colors",
"(",
"name",
")",
":",
"if",
"color_enabled",
":",
"return",
"_colors",
"[",
"name",
"]",
"return",
"''"
] | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/console.py#L29-L33 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/msvc.py | python | _augment_exception | (exc, version, arch='') | Add details to the exception message to help guide the user
as to what action will resolve it. | Add details to the exception message to help guide the user
as to what action will resolve it. | [
"Add",
"details",
"to",
"the",
"exception",
"message",
"to",
"help",
"guide",
"the",
"user",
"as",
"to",
"what",
"action",
"will",
"resolve",
"it",
"."
] | def _augment_exception(exc, version, arch=''):
"""
Add details to the exception message to help guide the user
as to what action will resolve it.
"""
# Error if MSVC++ directory not found or environment not set
message = exc.args[0]
if "vcvarsall" in message.lower() or "visual c" in message.lower():
# Special error message if MSVC++ not installed
tmpl = 'Microsoft Visual C++ {version:0.1f} or greater is required.'
message = tmpl.format(**locals())
msdownload = 'www.microsoft.com/download/details.aspx?id=%d'
if version == 9.0:
if arch.lower().find('ia64') > -1:
# For VC++ 9.0, if IA64 support is needed, redirect user
# to Windows SDK 7.0.
# Note: No download link available from Microsoft.
message += ' Get it with "Microsoft Windows SDK 7.0"'
else:
# For VC++ 9.0 redirect user to Vc++ for Python 2.7 :
# This redirection link is maintained by Microsoft.
# Contact vspython@microsoft.com if it needs updating.
message += ' Get it from http://aka.ms/vcpython27'
elif version == 10.0:
# For VC++ 10.0 Redirect user to Windows SDK 7.1
message += ' Get it with "Microsoft Windows SDK 7.1": '
message += msdownload % 8279
elif version >= 14.0:
# For VC++ 14.X Redirect user to latest Visual C++ Build Tools
message += (' Get it with "Microsoft C++ Build Tools": '
r'https://visualstudio.microsoft.com'
r'/visual-cpp-build-tools/')
exc.args = (message, ) | [
"def",
"_augment_exception",
"(",
"exc",
",",
"version",
",",
"arch",
"=",
"''",
")",
":",
"# Error if MSVC++ directory not found or environment not set",
"message",
"=",
"exc",
".",
"args",
"[",
"0",
"]",
"if",
"\"vcvarsall\"",
"in",
"message",
".",
"lower",
"(",
")",
"or",
"\"visual c\"",
"in",
"message",
".",
"lower",
"(",
")",
":",
"# Special error message if MSVC++ not installed",
"tmpl",
"=",
"'Microsoft Visual C++ {version:0.1f} or greater is required.'",
"message",
"=",
"tmpl",
".",
"format",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"msdownload",
"=",
"'www.microsoft.com/download/details.aspx?id=%d'",
"if",
"version",
"==",
"9.0",
":",
"if",
"arch",
".",
"lower",
"(",
")",
".",
"find",
"(",
"'ia64'",
")",
">",
"-",
"1",
":",
"# For VC++ 9.0, if IA64 support is needed, redirect user",
"# to Windows SDK 7.0.",
"# Note: No download link available from Microsoft.",
"message",
"+=",
"' Get it with \"Microsoft Windows SDK 7.0\"'",
"else",
":",
"# For VC++ 9.0 redirect user to Vc++ for Python 2.7 :",
"# This redirection link is maintained by Microsoft.",
"# Contact vspython@microsoft.com if it needs updating.",
"message",
"+=",
"' Get it from http://aka.ms/vcpython27'",
"elif",
"version",
"==",
"10.0",
":",
"# For VC++ 10.0 Redirect user to Windows SDK 7.1",
"message",
"+=",
"' Get it with \"Microsoft Windows SDK 7.1\": '",
"message",
"+=",
"msdownload",
"%",
"8279",
"elif",
"version",
">=",
"14.0",
":",
"# For VC++ 14.X Redirect user to latest Visual C++ Build Tools",
"message",
"+=",
"(",
"' Get it with \"Microsoft C++ Build Tools\": '",
"r'https://visualstudio.microsoft.com'",
"r'/visual-cpp-build-tools/'",
")",
"exc",
".",
"args",
"=",
"(",
"message",
",",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/msvc.py#L335-L369 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/linter/git.py | python | Repo.get_my_candidate_files | (self, filter_function, origin_branch) | return list(file_set) | Query git to get a list of files in the repo from a diff. | Query git to get a list of files in the repo from a diff. | [
"Query",
"git",
"to",
"get",
"a",
"list",
"of",
"files",
"in",
"the",
"repo",
"from",
"a",
"diff",
"."
] | def get_my_candidate_files(self, filter_function, origin_branch):
# type: (Callable[[str], bool], str) -> List[str]
"""Query git to get a list of files in the repo from a diff."""
# There are 3 diffs we run:
# 1. List of commits between origin/master and HEAD of current branch
# 2. Cached/Staged files (--cached)
# 3. Working Tree files git tracks
fork_point = self.get_merge_base(["HEAD", origin_branch])
diff_files = self.git_diff(["--name-only", "%s..HEAD" % (fork_point)])
diff_files += self.git_diff(["--name-only", "--cached"])
diff_files += self.git_diff(["--name-only"])
file_set = {
os.path.normpath(os.path.join(self.directory, line.rstrip()))
for line in diff_files.splitlines() if filter_function(line.rstrip())
}
return list(file_set) | [
"def",
"get_my_candidate_files",
"(",
"self",
",",
"filter_function",
",",
"origin_branch",
")",
":",
"# type: (Callable[[str], bool], str) -> List[str]",
"# There are 3 diffs we run:",
"# 1. List of commits between origin/master and HEAD of current branch",
"# 2. Cached/Staged files (--cached)",
"# 3. Working Tree files git tracks",
"fork_point",
"=",
"self",
".",
"get_merge_base",
"(",
"[",
"\"HEAD\"",
",",
"origin_branch",
"]",
")",
"diff_files",
"=",
"self",
".",
"git_diff",
"(",
"[",
"\"--name-only\"",
",",
"\"%s..HEAD\"",
"%",
"(",
"fork_point",
")",
"]",
")",
"diff_files",
"+=",
"self",
".",
"git_diff",
"(",
"[",
"\"--name-only\"",
",",
"\"--cached\"",
"]",
")",
"diff_files",
"+=",
"self",
".",
"git_diff",
"(",
"[",
"\"--name-only\"",
"]",
")",
"file_set",
"=",
"{",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"line",
".",
"rstrip",
"(",
")",
")",
")",
"for",
"line",
"in",
"diff_files",
".",
"splitlines",
"(",
")",
"if",
"filter_function",
"(",
"line",
".",
"rstrip",
"(",
")",
")",
"}",
"return",
"list",
"(",
"file_set",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/linter/git.py#L102-L121 | |
OpenChemistry/tomviz | 0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a | tomviz/python/tomviz/io/dm.py | python | FileDM._readTagEntry | (self) | Read one entry in a tag group. | Read one entry in a tag group. | [
"Read",
"one",
"entry",
"in",
"a",
"tag",
"group",
"."
] | def _readTagEntry(self):
"""Read one entry in a tag group.
"""
dataType = self.fromfile(self.fid, dtype=np.dtype('>u1'), count=1)[0]
# Record tag at this level
self._curTagAtLevelX[self._curGroupLevel] += 1
# get the tag
lenTagLabel = self.fromfile(self.fid, dtype='>u2', count=1)[0]
if self._v:
print('_readTagEntry: dataType = {}, \
lenTagLabel = {}'.format(dataType, lenTagLabel))
if lenTagLabel > 0:
tagLabelBinary = self.fromfile(self.fid, dtype='<u1',
count=lenTagLabel) # read as binary
tagLabel = self._bin2str(tagLabelBinary)
if self._v:
print('_readTagEntry: tagLabel = {}'.format(tagLabel))
else: # unlabeled tag.
tagLabel = str(self._curTagAtLevelX[self._curGroupLevel])
# Save the current group name in case this is needed
oldGroupName = self._curGroupNameAtLevelX
if dataType == 21:
# This tag entry contains data
self._curTagName = tagLabel # save its name
self._readTagType()
else:
# This is a nested tag group
self._curGroupNameAtLevelX += '.' + tagLabel # add to group names
# An unknown part of the DM4 tags
if self._dmType == 4:
_ = self.fromfile(self.fid, dtype=self._specialType,
count=1)[0]
self._readTagGroup()
self._curGroupNameAtLevelX = oldGroupName | [
"def",
"_readTagEntry",
"(",
"self",
")",
":",
"dataType",
"=",
"self",
".",
"fromfile",
"(",
"self",
".",
"fid",
",",
"dtype",
"=",
"np",
".",
"dtype",
"(",
"'>u1'",
")",
",",
"count",
"=",
"1",
")",
"[",
"0",
"]",
"# Record tag at this level",
"self",
".",
"_curTagAtLevelX",
"[",
"self",
".",
"_curGroupLevel",
"]",
"+=",
"1",
"# get the tag",
"lenTagLabel",
"=",
"self",
".",
"fromfile",
"(",
"self",
".",
"fid",
",",
"dtype",
"=",
"'>u2'",
",",
"count",
"=",
"1",
")",
"[",
"0",
"]",
"if",
"self",
".",
"_v",
":",
"print",
"(",
"'_readTagEntry: dataType = {}, \\\n lenTagLabel = {}'",
".",
"format",
"(",
"dataType",
",",
"lenTagLabel",
")",
")",
"if",
"lenTagLabel",
">",
"0",
":",
"tagLabelBinary",
"=",
"self",
".",
"fromfile",
"(",
"self",
".",
"fid",
",",
"dtype",
"=",
"'<u1'",
",",
"count",
"=",
"lenTagLabel",
")",
"# read as binary",
"tagLabel",
"=",
"self",
".",
"_bin2str",
"(",
"tagLabelBinary",
")",
"if",
"self",
".",
"_v",
":",
"print",
"(",
"'_readTagEntry: tagLabel = {}'",
".",
"format",
"(",
"tagLabel",
")",
")",
"else",
":",
"# unlabeled tag.",
"tagLabel",
"=",
"str",
"(",
"self",
".",
"_curTagAtLevelX",
"[",
"self",
".",
"_curGroupLevel",
"]",
")",
"# Save the current group name in case this is needed",
"oldGroupName",
"=",
"self",
".",
"_curGroupNameAtLevelX",
"if",
"dataType",
"==",
"21",
":",
"# This tag entry contains data",
"self",
".",
"_curTagName",
"=",
"tagLabel",
"# save its name",
"self",
".",
"_readTagType",
"(",
")",
"else",
":",
"# This is a nested tag group",
"self",
".",
"_curGroupNameAtLevelX",
"+=",
"'.'",
"+",
"tagLabel",
"# add to group names",
"# An unknown part of the DM4 tags",
"if",
"self",
".",
"_dmType",
"==",
"4",
":",
"_",
"=",
"self",
".",
"fromfile",
"(",
"self",
".",
"fid",
",",
"dtype",
"=",
"self",
".",
"_specialType",
",",
"count",
"=",
"1",
")",
"[",
"0",
"]",
"self",
".",
"_readTagGroup",
"(",
")",
"self",
".",
"_curGroupNameAtLevelX",
"=",
"oldGroupName"
] | https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/tomviz/io/dm.py#L460-L503 | ||
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/wms/ogc/common/tilecalcs.py | python | TotalTilepixelExtent | (zoom) | return total | Number of pixels on a side, at a given zoom.
Args:
zoom: zoom level.
Returns:
Whole tilepixel space extent for this zoom level.
Height == width so, just one number is returned. | Number of pixels on a side, at a given zoom. | [
"Number",
"of",
"pixels",
"on",
"a",
"side",
"at",
"a",
"given",
"zoom",
"."
] | def TotalTilepixelExtent(zoom):
"""Number of pixels on a side, at a given zoom.
Args:
zoom: zoom level.
Returns:
Whole tilepixel space extent for this zoom level.
Height == width so, just one number is returned.
"""
utils.Assert(geom.IsNumber(zoom))
total = _TILE_PIXEL_SIZE * (2 ** zoom)
logger.debug("Total pixels:%d", total)
return total | [
"def",
"TotalTilepixelExtent",
"(",
"zoom",
")",
":",
"utils",
".",
"Assert",
"(",
"geom",
".",
"IsNumber",
"(",
"zoom",
")",
")",
"total",
"=",
"_TILE_PIXEL_SIZE",
"*",
"(",
"2",
"**",
"zoom",
")",
"logger",
".",
"debug",
"(",
"\"Total pixels:%d\"",
",",
"total",
")",
"return",
"total"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/wms/ogc/common/tilecalcs.py#L104-L118 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | Dialog.CreateStdDialogButtonSizer | (*args, **kwargs) | return _windows_.Dialog_CreateStdDialogButtonSizer(*args, **kwargs) | CreateStdDialogButtonSizer(self, long flags) -> StdDialogButtonSizer | CreateStdDialogButtonSizer(self, long flags) -> StdDialogButtonSizer | [
"CreateStdDialogButtonSizer",
"(",
"self",
"long",
"flags",
")",
"-",
">",
"StdDialogButtonSizer"
] | def CreateStdDialogButtonSizer(*args, **kwargs):
"""CreateStdDialogButtonSizer(self, long flags) -> StdDialogButtonSizer"""
return _windows_.Dialog_CreateStdDialogButtonSizer(*args, **kwargs) | [
"def",
"CreateStdDialogButtonSizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"Dialog_CreateStdDialogButtonSizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L795-L797 | |
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/nyan/nyan_structs.py | python | NyanPatch.is_abstract | (self) | return super().is_abstract() or not self._target | Returns True if unique or inherited members were
not initialized or the patch target is not set. | Returns True if unique or inherited members were
not initialized or the patch target is not set. | [
"Returns",
"True",
"if",
"unique",
"or",
"inherited",
"members",
"were",
"not",
"initialized",
"or",
"the",
"patch",
"target",
"is",
"not",
"set",
"."
] | def is_abstract(self):
"""
Returns True if unique or inherited members were
not initialized or the patch target is not set.
"""
return super().is_abstract() or not self._target | [
"def",
"is_abstract",
"(",
"self",
")",
":",
"return",
"super",
"(",
")",
".",
"is_abstract",
"(",
")",
"or",
"not",
"self",
".",
"_target"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/nyan/nyan_structs.py#L493-L498 | |
opengm/opengm | decdacf4caad223b0ab5478d38a855f8767a394f | src/interfaces/python/opengm/__init__.py | python | saveGm | (gm, f, d='gm') | save a graphical model to a hdf5 file:
Args:
gm : graphical model to save
f : filepath
g : dataset (defaut : 'gm') | save a graphical model to a hdf5 file:
Args:
gm : graphical model to save
f : filepath
g : dataset (defaut : 'gm') | [
"save",
"a",
"graphical",
"model",
"to",
"a",
"hdf5",
"file",
":",
"Args",
":",
"gm",
":",
"graphical",
"model",
"to",
"save",
"f",
":",
"filepath",
"g",
":",
"dataset",
"(",
"defaut",
":",
"gm",
")"
] | def saveGm(gm, f, d='gm'):
""" save a graphical model to a hdf5 file:
Args:
gm : graphical model to save
f : filepath
g : dataset (defaut : 'gm')
"""
hdf5.saveGraphicalModel(gm, f, d) | [
"def",
"saveGm",
"(",
"gm",
",",
"f",
",",
"d",
"=",
"'gm'",
")",
":",
"hdf5",
".",
"saveGraphicalModel",
"(",
"gm",
",",
"f",
",",
"d",
")"
] | https://github.com/opengm/opengm/blob/decdacf4caad223b0ab5478d38a855f8767a394f/src/interfaces/python/opengm/__init__.py#L72-L79 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_gdi.py | python | Bitmap.CopyFromBufferRGBA | (self, buffer) | Copy data from a RGBA buffer object to replace the bitmap pixel
data. This method is now just a compatibility wrapper around
CopyFromBuffer. | Copy data from a RGBA buffer object to replace the bitmap pixel
data. This method is now just a compatibility wrapper around
CopyFromBuffer. | [
"Copy",
"data",
"from",
"a",
"RGBA",
"buffer",
"object",
"to",
"replace",
"the",
"bitmap",
"pixel",
"data",
".",
"This",
"method",
"is",
"now",
"just",
"a",
"compatibility",
"wrapper",
"around",
"CopyFromBuffer",
"."
] | def CopyFromBufferRGBA(self, buffer):
"""
Copy data from a RGBA buffer object to replace the bitmap pixel
data. This method is now just a compatibility wrapper around
CopyFromBuffer.
"""
self.CopyFromBuffer(buffer, wx.BitmapBufferFormat_RGBA) | [
"def",
"CopyFromBufferRGBA",
"(",
"self",
",",
"buffer",
")",
":",
"self",
".",
"CopyFromBuffer",
"(",
"buffer",
",",
"wx",
".",
"BitmapBufferFormat_RGBA",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L841-L847 | ||
linyouhappy/kongkongxiyou | 7a69b2913eb29f4be77f9a62fb90cdd72c4160f1 | cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | File.time | (self) | return conf.lib.clang_getFileTime(self) | Return the last modification time of the file. | Return the last modification time of the file. | [
"Return",
"the",
"last",
"modification",
"time",
"of",
"the",
"file",
"."
] | def time(self):
"""Return the last modification time of the file."""
return conf.lib.clang_getFileTime(self) | [
"def",
"time",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getFileTime",
"(",
"self",
")"
] | https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L2501-L2503 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/generic.py | python | NDFrame.to_hdf | (
self,
path_or_buf,
key: str,
mode: str = "a",
complevel: int | None = None,
complib: str | None = None,
append: bool_t = False,
format: str | None = None,
index: bool_t = True,
min_itemsize: int | dict[str, int] | None = None,
nan_rep=None,
dropna: bool_t | None = None,
data_columns: bool_t | list[str] | None = None,
errors: str = "strict",
encoding: str = "UTF-8",
) | Write the contained data to an HDF5 file using HDFStore.
Hierarchical Data Format (HDF) is self-describing, allowing an
application to interpret the structure and contents of a file with
no outside information. One HDF file can hold a mix of related objects
which can be accessed as a group or as individual objects.
In order to add another DataFrame or Series to an existing HDF file
please use append mode and a different a key.
.. warning::
One can store a subclass of ``DataFrame`` or ``Series`` to HDF5,
but the type of the subclass is lost upon storing.
For more information see the :ref:`user guide <io.hdf5>`.
Parameters
----------
path_or_buf : str or pandas.HDFStore
File path or HDFStore object.
key : str
Identifier for the group in the store.
mode : {'a', 'w', 'r+'}, default 'a'
Mode to open file:
- 'w': write, a new file is created (an existing file with
the same name would be deleted).
- 'a': append, an existing file is opened for reading and
writing, and if the file does not exist it is created.
- 'r+': similar to 'a', but the file must already exist.
complevel : {0-9}, optional
Specifies a compression level for data.
A value of 0 disables compression.
complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
Specifies the compression library to be used.
As of v0.20.2 these additional compressors for Blosc are supported
(default if no compressor specified: 'blosc:blosclz'):
{'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',
'blosc:zlib', 'blosc:zstd'}.
Specifying a compression library which is not available issues
a ValueError.
append : bool, default False
For Table formats, append the input data to the existing.
format : {'fixed', 'table', None}, default 'fixed'
Possible values:
- 'fixed': Fixed format. Fast writing/reading. Not-appendable,
nor searchable.
- 'table': Table format. Write as a PyTables Table structure
which may perform worse but allow more flexible operations
like searching / selecting subsets of the data.
- If None, pd.get_option('io.hdf.default_format') is checked,
followed by fallback to "fixed"
errors : str, default 'strict'
Specifies how encoding and decoding errors are to be handled.
See the errors argument for :func:`open` for a full list
of options.
encoding : str, default "UTF-8"
min_itemsize : dict or int, optional
Map column names to minimum string sizes for columns.
nan_rep : Any, optional
How to represent null values as str.
Not allowed with append=True.
data_columns : list of columns or True, optional
List of columns to create as indexed data columns for on-disk
queries, or True to use all columns. By default only the axes
of the object are indexed. See :ref:`io.hdf5-query-data-columns`.
Applicable only to format='table'.
See Also
--------
read_hdf : Read from HDF file.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
DataFrame.to_sql : Write to a SQL table.
DataFrame.to_feather : Write out feather-format for DataFrames.
DataFrame.to_csv : Write out to a csv file.
Examples
--------
>>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
... index=['a', 'b', 'c'])
>>> df.to_hdf('data.h5', key='df', mode='w')
We can add another object to the same file:
>>> s = pd.Series([1, 2, 3, 4])
>>> s.to_hdf('data.h5', key='s')
Reading from HDF file:
>>> pd.read_hdf('data.h5', 'df')
A B
a 1 4
b 2 5
c 3 6
>>> pd.read_hdf('data.h5', 's')
0 1
1 2
2 3
3 4
dtype: int64
Deleting file with data:
>>> import os
>>> os.remove('data.h5') | Write the contained data to an HDF5 file using HDFStore. | [
"Write",
"the",
"contained",
"data",
"to",
"an",
"HDF5",
"file",
"using",
"HDFStore",
"."
] | def to_hdf(
self,
path_or_buf,
key: str,
mode: str = "a",
complevel: int | None = None,
complib: str | None = None,
append: bool_t = False,
format: str | None = None,
index: bool_t = True,
min_itemsize: int | dict[str, int] | None = None,
nan_rep=None,
dropna: bool_t | None = None,
data_columns: bool_t | list[str] | None = None,
errors: str = "strict",
encoding: str = "UTF-8",
) -> None:
"""
Write the contained data to an HDF5 file using HDFStore.
Hierarchical Data Format (HDF) is self-describing, allowing an
application to interpret the structure and contents of a file with
no outside information. One HDF file can hold a mix of related objects
which can be accessed as a group or as individual objects.
In order to add another DataFrame or Series to an existing HDF file
please use append mode and a different a key.
.. warning::
One can store a subclass of ``DataFrame`` or ``Series`` to HDF5,
but the type of the subclass is lost upon storing.
For more information see the :ref:`user guide <io.hdf5>`.
Parameters
----------
path_or_buf : str or pandas.HDFStore
File path or HDFStore object.
key : str
Identifier for the group in the store.
mode : {'a', 'w', 'r+'}, default 'a'
Mode to open file:
- 'w': write, a new file is created (an existing file with
the same name would be deleted).
- 'a': append, an existing file is opened for reading and
writing, and if the file does not exist it is created.
- 'r+': similar to 'a', but the file must already exist.
complevel : {0-9}, optional
Specifies a compression level for data.
A value of 0 disables compression.
complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
Specifies the compression library to be used.
As of v0.20.2 these additional compressors for Blosc are supported
(default if no compressor specified: 'blosc:blosclz'):
{'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',
'blosc:zlib', 'blosc:zstd'}.
Specifying a compression library which is not available issues
a ValueError.
append : bool, default False
For Table formats, append the input data to the existing.
format : {'fixed', 'table', None}, default 'fixed'
Possible values:
- 'fixed': Fixed format. Fast writing/reading. Not-appendable,
nor searchable.
- 'table': Table format. Write as a PyTables Table structure
which may perform worse but allow more flexible operations
like searching / selecting subsets of the data.
- If None, pd.get_option('io.hdf.default_format') is checked,
followed by fallback to "fixed"
errors : str, default 'strict'
Specifies how encoding and decoding errors are to be handled.
See the errors argument for :func:`open` for a full list
of options.
encoding : str, default "UTF-8"
min_itemsize : dict or int, optional
Map column names to minimum string sizes for columns.
nan_rep : Any, optional
How to represent null values as str.
Not allowed with append=True.
data_columns : list of columns or True, optional
List of columns to create as indexed data columns for on-disk
queries, or True to use all columns. By default only the axes
of the object are indexed. See :ref:`io.hdf5-query-data-columns`.
Applicable only to format='table'.
See Also
--------
read_hdf : Read from HDF file.
DataFrame.to_parquet : Write a DataFrame to the binary parquet format.
DataFrame.to_sql : Write to a SQL table.
DataFrame.to_feather : Write out feather-format for DataFrames.
DataFrame.to_csv : Write out to a csv file.
Examples
--------
>>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]},
... index=['a', 'b', 'c'])
>>> df.to_hdf('data.h5', key='df', mode='w')
We can add another object to the same file:
>>> s = pd.Series([1, 2, 3, 4])
>>> s.to_hdf('data.h5', key='s')
Reading from HDF file:
>>> pd.read_hdf('data.h5', 'df')
A B
a 1 4
b 2 5
c 3 6
>>> pd.read_hdf('data.h5', 's')
0 1
1 2
2 3
3 4
dtype: int64
Deleting file with data:
>>> import os
>>> os.remove('data.h5')
"""
from pandas.io import pytables
pytables.to_hdf(
path_or_buf,
key,
self,
mode=mode,
complevel=complevel,
complib=complib,
append=append,
format=format,
index=index,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
dropna=dropna,
data_columns=data_columns,
errors=errors,
encoding=encoding,
) | [
"def",
"to_hdf",
"(",
"self",
",",
"path_or_buf",
",",
"key",
":",
"str",
",",
"mode",
":",
"str",
"=",
"\"a\"",
",",
"complevel",
":",
"int",
"|",
"None",
"=",
"None",
",",
"complib",
":",
"str",
"|",
"None",
"=",
"None",
",",
"append",
":",
"bool_t",
"=",
"False",
",",
"format",
":",
"str",
"|",
"None",
"=",
"None",
",",
"index",
":",
"bool_t",
"=",
"True",
",",
"min_itemsize",
":",
"int",
"|",
"dict",
"[",
"str",
",",
"int",
"]",
"|",
"None",
"=",
"None",
",",
"nan_rep",
"=",
"None",
",",
"dropna",
":",
"bool_t",
"|",
"None",
"=",
"None",
",",
"data_columns",
":",
"bool_t",
"|",
"list",
"[",
"str",
"]",
"|",
"None",
"=",
"None",
",",
"errors",
":",
"str",
"=",
"\"strict\"",
",",
"encoding",
":",
"str",
"=",
"\"UTF-8\"",
",",
")",
"->",
"None",
":",
"from",
"pandas",
".",
"io",
"import",
"pytables",
"pytables",
".",
"to_hdf",
"(",
"path_or_buf",
",",
"key",
",",
"self",
",",
"mode",
"=",
"mode",
",",
"complevel",
"=",
"complevel",
",",
"complib",
"=",
"complib",
",",
"append",
"=",
"append",
",",
"format",
"=",
"format",
",",
"index",
"=",
"index",
",",
"min_itemsize",
"=",
"min_itemsize",
",",
"nan_rep",
"=",
"nan_rep",
",",
"dropna",
"=",
"dropna",
",",
"data_columns",
"=",
"data_columns",
",",
"errors",
"=",
"errors",
",",
"encoding",
"=",
"encoding",
",",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/generic.py#L2575-L2719 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PGProperty.SetFlagsFromString | (*args, **kwargs) | return _propgrid.PGProperty_SetFlagsFromString(*args, **kwargs) | SetFlagsFromString(self, String str) | SetFlagsFromString(self, String str) | [
"SetFlagsFromString",
"(",
"self",
"String",
"str",
")"
] | def SetFlagsFromString(*args, **kwargs):
"""SetFlagsFromString(self, String str)"""
return _propgrid.PGProperty_SetFlagsFromString(*args, **kwargs) | [
"def",
"SetFlagsFromString",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PGProperty_SetFlagsFromString",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L710-L712 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/tensorflow_dataframe.py | python | TensorFlowDataFrame.from_csv_with_feature_spec | (cls,
filepatterns,
feature_spec,
has_header=True,
column_names=None,
num_threads=1,
enqueue_size=None,
batch_size=32,
queue_capacity=None,
min_after_dequeue=None,
shuffle=True,
seed=None) | return dataframe | Create a `DataFrame` from CSV files, given a feature_spec.
If `has_header` is false, then `column_names` must be specified. If
`has_header` is true and `column_names` are specified, then `column_names`
overrides the names in the header.
Args:
filepatterns: a list of file patterns that resolve to CSV files.
feature_spec: a dict mapping column names to `FixedLenFeature` or
`VarLenFeature`.
has_header: whether or not the CSV files have headers.
column_names: a list of names for the columns in the CSV files.
num_threads: the number of readers that will work in parallel.
enqueue_size: block size for each read operation.
batch_size: desired batch size.
queue_capacity: capacity of the queue that will store parsed lines.
min_after_dequeue: minimum number of elements that can be left by a
dequeue operation. Only used if `shuffle` is true.
shuffle: whether records should be shuffled. Defaults to true.
seed: passed to random shuffle operations. Only used if `shuffle` is true.
Returns:
A `DataFrame` that has columns corresponding to `features` and is filled
with examples from `filepatterns`.
Raises:
ValueError: no files match `filepatterns`.
ValueError: `features` contains the reserved name 'index'. | Create a `DataFrame` from CSV files, given a feature_spec. | [
"Create",
"a",
"DataFrame",
"from",
"CSV",
"files",
"given",
"a",
"feature_spec",
"."
] | def from_csv_with_feature_spec(cls,
filepatterns,
feature_spec,
has_header=True,
column_names=None,
num_threads=1,
enqueue_size=None,
batch_size=32,
queue_capacity=None,
min_after_dequeue=None,
shuffle=True,
seed=None):
"""Create a `DataFrame` from CSV files, given a feature_spec.
If `has_header` is false, then `column_names` must be specified. If
`has_header` is true and `column_names` are specified, then `column_names`
overrides the names in the header.
Args:
filepatterns: a list of file patterns that resolve to CSV files.
feature_spec: a dict mapping column names to `FixedLenFeature` or
`VarLenFeature`.
has_header: whether or not the CSV files have headers.
column_names: a list of names for the columns in the CSV files.
num_threads: the number of readers that will work in parallel.
enqueue_size: block size for each read operation.
batch_size: desired batch size.
queue_capacity: capacity of the queue that will store parsed lines.
min_after_dequeue: minimum number of elements that can be left by a
dequeue operation. Only used if `shuffle` is true.
shuffle: whether records should be shuffled. Defaults to true.
seed: passed to random shuffle operations. Only used if `shuffle` is true.
Returns:
A `DataFrame` that has columns corresponding to `features` and is filled
with examples from `filepatterns`.
Raises:
ValueError: no files match `filepatterns`.
ValueError: `features` contains the reserved name 'index'.
"""
def get_default_values(column_names):
return [_get_default_value(feature_spec[name]) for name in column_names]
dataframe = cls._from_csv_base(filepatterns, get_default_values, has_header,
column_names, num_threads,
enqueue_size, batch_size, queue_capacity,
min_after_dequeue, shuffle, seed)
# replace the dense columns with sparse ones in place in the dataframe
for name in dataframe.columns():
if name != "index" and isinstance(feature_spec[name],
parsing_ops.VarLenFeature):
strip_value = _get_default_value(feature_spec[name])
(dataframe[name],) = sparsify.Sparsify(strip_value)(dataframe[name])
return dataframe | [
"def",
"from_csv_with_feature_spec",
"(",
"cls",
",",
"filepatterns",
",",
"feature_spec",
",",
"has_header",
"=",
"True",
",",
"column_names",
"=",
"None",
",",
"num_threads",
"=",
"1",
",",
"enqueue_size",
"=",
"None",
",",
"batch_size",
"=",
"32",
",",
"queue_capacity",
"=",
"None",
",",
"min_after_dequeue",
"=",
"None",
",",
"shuffle",
"=",
"True",
",",
"seed",
"=",
"None",
")",
":",
"def",
"get_default_values",
"(",
"column_names",
")",
":",
"return",
"[",
"_get_default_value",
"(",
"feature_spec",
"[",
"name",
"]",
")",
"for",
"name",
"in",
"column_names",
"]",
"dataframe",
"=",
"cls",
".",
"_from_csv_base",
"(",
"filepatterns",
",",
"get_default_values",
",",
"has_header",
",",
"column_names",
",",
"num_threads",
",",
"enqueue_size",
",",
"batch_size",
",",
"queue_capacity",
",",
"min_after_dequeue",
",",
"shuffle",
",",
"seed",
")",
"# replace the dense columns with sparse ones in place in the dataframe",
"for",
"name",
"in",
"dataframe",
".",
"columns",
"(",
")",
":",
"if",
"name",
"!=",
"\"index\"",
"and",
"isinstance",
"(",
"feature_spec",
"[",
"name",
"]",
",",
"parsing_ops",
".",
"VarLenFeature",
")",
":",
"strip_value",
"=",
"_get_default_value",
"(",
"feature_spec",
"[",
"name",
"]",
")",
"(",
"dataframe",
"[",
"name",
"]",
",",
")",
"=",
"sparsify",
".",
"Sparsify",
"(",
"strip_value",
")",
"(",
"dataframe",
"[",
"name",
"]",
")",
"return",
"dataframe"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/tensorflow_dataframe.py#L381-L438 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/processing/tools/vector.py | python | convert_nulls | (values, replacement=None) | return [i if i != NULL else replacement for i in values] | Converts NULL items in a list of values to a replacement value (usually None)
:param values: list of values
:param replacement: value to use in place of NULL
:return: converted list | Converts NULL items in a list of values to a replacement value (usually None)
:param values: list of values
:param replacement: value to use in place of NULL
:return: converted list | [
"Converts",
"NULL",
"items",
"in",
"a",
"list",
"of",
"values",
"to",
"a",
"replacement",
"value",
"(",
"usually",
"None",
")",
":",
"param",
"values",
":",
"list",
"of",
"values",
":",
"param",
"replacement",
":",
"value",
"to",
"use",
"in",
"place",
"of",
"NULL",
":",
"return",
":",
"converted",
"list"
] | def convert_nulls(values, replacement=None):
"""
Converts NULL items in a list of values to a replacement value (usually None)
:param values: list of values
:param replacement: value to use in place of NULL
:return: converted list
"""
return [i if i != NULL else replacement for i in values] | [
"def",
"convert_nulls",
"(",
"values",
",",
"replacement",
"=",
"None",
")",
":",
"return",
"[",
"i",
"if",
"i",
"!=",
"NULL",
"else",
"replacement",
"for",
"i",
"in",
"values",
"]"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/processing/tools/vector.py#L87-L94 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/backend/base.py | python | BuildBackend._write_file | (self, path=None, fh=None) | Context manager to write a file.
This is a glorified wrapper around FileAvoidWrite with integration to
update the BackendConsumeSummary on this instance.
Example usage:
with self._write_file('foo.txt') as fh:
fh.write('hello world') | Context manager to write a file. | [
"Context",
"manager",
"to",
"write",
"a",
"file",
"."
] | def _write_file(self, path=None, fh=None):
"""Context manager to write a file.
This is a glorified wrapper around FileAvoidWrite with integration to
update the BackendConsumeSummary on this instance.
Example usage:
with self._write_file('foo.txt') as fh:
fh.write('hello world')
"""
if path is not None:
assert fh is None
fh = FileAvoidWrite(path, capture_diff=True)
else:
assert fh is not None
dirname = mozpath.dirname(fh.name)
try:
os.makedirs(dirname)
except OSError as error:
if error.errno != errno.EEXIST:
raise
yield fh
self._backend_output_files.add(mozpath.relpath(fh.name, self.environment.topobjdir))
existed, updated = fh.close()
if not existed:
self.summary.created_count += 1
elif updated:
self.summary.updated_count += 1
if fh.diff:
self.summary.file_diffs[fh.name] = fh.diff
else:
self.summary.unchanged_count += 1 | [
"def",
"_write_file",
"(",
"self",
",",
"path",
"=",
"None",
",",
"fh",
"=",
"None",
")",
":",
"if",
"path",
"is",
"not",
"None",
":",
"assert",
"fh",
"is",
"None",
"fh",
"=",
"FileAvoidWrite",
"(",
"path",
",",
"capture_diff",
"=",
"True",
")",
"else",
":",
"assert",
"fh",
"is",
"not",
"None",
"dirname",
"=",
"mozpath",
".",
"dirname",
"(",
"fh",
".",
"name",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"except",
"OSError",
"as",
"error",
":",
"if",
"error",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"yield",
"fh",
"self",
".",
"_backend_output_files",
".",
"add",
"(",
"mozpath",
".",
"relpath",
"(",
"fh",
".",
"name",
",",
"self",
".",
"environment",
".",
"topobjdir",
")",
")",
"existed",
",",
"updated",
"=",
"fh",
".",
"close",
"(",
")",
"if",
"not",
"existed",
":",
"self",
".",
"summary",
".",
"created_count",
"+=",
"1",
"elif",
"updated",
":",
"self",
".",
"summary",
".",
"updated_count",
"+=",
"1",
"if",
"fh",
".",
"diff",
":",
"self",
".",
"summary",
".",
"file_diffs",
"[",
"fh",
".",
"name",
"]",
"=",
"fh",
".",
"diff",
"else",
":",
"self",
".",
"summary",
".",
"unchanged_count",
"+=",
"1"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozbuild/backend/base.py#L249-L285 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/parser.py | python | ByteParser._all_arcs | (self) | return arcs | Get the set of all arcs in this code object and its children.
See `_arcs` for details. | Get the set of all arcs in this code object and its children. | [
"Get",
"the",
"set",
"of",
"all",
"arcs",
"in",
"this",
"code",
"object",
"and",
"its",
"children",
"."
] | def _all_arcs(self):
"""Get the set of all arcs in this code object and its children.
See `_arcs` for details.
"""
arcs = set()
for bp in self.child_parsers():
arcs.update(bp._arcs())
return arcs | [
"def",
"_all_arcs",
"(",
"self",
")",
":",
"arcs",
"=",
"set",
"(",
")",
"for",
"bp",
"in",
"self",
".",
"child_parsers",
"(",
")",
":",
"arcs",
".",
"update",
"(",
"bp",
".",
"_arcs",
"(",
")",
")",
"return",
"arcs"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/coverage/parser.py#L611-L621 | |
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/svrg_module/api_usage_example/example_inference.py | python | create_network | (batch_size, update_freq) | return di, val_iter, mod | Create a linear regression network for performing SVRG optimization.
:return: an instance of mx.io.NDArrayIter
:return: an instance of mx.mod.svrgmodule for performing SVRG optimization | Create a linear regression network for performing SVRG optimization.
:return: an instance of mx.io.NDArrayIter
:return: an instance of mx.mod.svrgmodule for performing SVRG optimization | [
"Create",
"a",
"linear",
"regression",
"network",
"for",
"performing",
"SVRG",
"optimization",
".",
":",
"return",
":",
"an",
"instance",
"of",
"mx",
".",
"io",
".",
"NDArrayIter",
":",
"return",
":",
"an",
"instance",
"of",
"mx",
".",
"mod",
".",
"svrgmodule",
"for",
"performing",
"SVRG",
"optimization"
] | def create_network(batch_size, update_freq):
"""Create a linear regression network for performing SVRG optimization.
:return: an instance of mx.io.NDArrayIter
:return: an instance of mx.mod.svrgmodule for performing SVRG optimization
"""
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.INFO, format=head)
data = np.random.randint(1, 5, [1000, 2])
#Test_Train data split
n_train = int(data.shape[0] * 0.8)
weights = np.array([1.0, 2.0])
label = data.dot(weights)
di = mx.io.NDArrayIter(data[:n_train, :], label[:n_train], batch_size=batch_size, shuffle=True, label_name='lin_reg_label')
val_iter = mx.io.NDArrayIter(data[n_train:, :], label[n_train:], batch_size=batch_size)
X = mx.sym.Variable('data')
Y = mx.symbol.Variable('lin_reg_label')
fully_connected_layer = mx.sym.FullyConnected(data=X, name='fc1', num_hidden=1)
lro = mx.sym.LinearRegressionOutput(data=fully_connected_layer, label=Y, name="lro")
mod = SVRGModule(
symbol=lro,
data_names=['data'],
label_names=['lin_reg_label'], update_freq=update_freq, logger=logging)
return di, val_iter, mod | [
"def",
"create_network",
"(",
"batch_size",
",",
"update_freq",
")",
":",
"head",
"=",
"'%(asctime)-15s %(message)s'",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"head",
")",
"data",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"1",
",",
"5",
",",
"[",
"1000",
",",
"2",
"]",
")",
"#Test_Train data split",
"n_train",
"=",
"int",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
"*",
"0.8",
")",
"weights",
"=",
"np",
".",
"array",
"(",
"[",
"1.0",
",",
"2.0",
"]",
")",
"label",
"=",
"data",
".",
"dot",
"(",
"weights",
")",
"di",
"=",
"mx",
".",
"io",
".",
"NDArrayIter",
"(",
"data",
"[",
":",
"n_train",
",",
":",
"]",
",",
"label",
"[",
":",
"n_train",
"]",
",",
"batch_size",
"=",
"batch_size",
",",
"shuffle",
"=",
"True",
",",
"label_name",
"=",
"'lin_reg_label'",
")",
"val_iter",
"=",
"mx",
".",
"io",
".",
"NDArrayIter",
"(",
"data",
"[",
"n_train",
":",
",",
":",
"]",
",",
"label",
"[",
"n_train",
":",
"]",
",",
"batch_size",
"=",
"batch_size",
")",
"X",
"=",
"mx",
".",
"sym",
".",
"Variable",
"(",
"'data'",
")",
"Y",
"=",
"mx",
".",
"symbol",
".",
"Variable",
"(",
"'lin_reg_label'",
")",
"fully_connected_layer",
"=",
"mx",
".",
"sym",
".",
"FullyConnected",
"(",
"data",
"=",
"X",
",",
"name",
"=",
"'fc1'",
",",
"num_hidden",
"=",
"1",
")",
"lro",
"=",
"mx",
".",
"sym",
".",
"LinearRegressionOutput",
"(",
"data",
"=",
"fully_connected_layer",
",",
"label",
"=",
"Y",
",",
"name",
"=",
"\"lro\"",
")",
"mod",
"=",
"SVRGModule",
"(",
"symbol",
"=",
"lro",
",",
"data_names",
"=",
"[",
"'data'",
"]",
",",
"label_names",
"=",
"[",
"'lin_reg_label'",
"]",
",",
"update_freq",
"=",
"update_freq",
",",
"logger",
"=",
"logging",
")",
"return",
"di",
",",
"val_iter",
",",
"mod"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/svrg_module/api_usage_example/example_inference.py#L64-L91 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | MessageDialog.SetHelpLabel | (*args, **kwargs) | return _windows_.MessageDialog_SetHelpLabel(*args, **kwargs) | SetHelpLabel(self, String help) -> bool | SetHelpLabel(self, String help) -> bool | [
"SetHelpLabel",
"(",
"self",
"String",
"help",
")",
"-",
">",
"bool"
] | def SetHelpLabel(*args, **kwargs):
"""SetHelpLabel(self, String help) -> bool"""
return _windows_.MessageDialog_SetHelpLabel(*args, **kwargs) | [
"def",
"SetHelpLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"MessageDialog_SetHelpLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L3650-L3652 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | JoystickEvent.__init__ | (self, *args, **kwargs) | __init__(self, EventType type=wxEVT_NULL, int state=0, int joystick=JOYSTICK1,
int change=0) -> JoystickEvent | __init__(self, EventType type=wxEVT_NULL, int state=0, int joystick=JOYSTICK1,
int change=0) -> JoystickEvent | [
"__init__",
"(",
"self",
"EventType",
"type",
"=",
"wxEVT_NULL",
"int",
"state",
"=",
"0",
"int",
"joystick",
"=",
"JOYSTICK1",
"int",
"change",
"=",
"0",
")",
"-",
">",
"JoystickEvent"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, EventType type=wxEVT_NULL, int state=0, int joystick=JOYSTICK1,
int change=0) -> JoystickEvent
"""
_misc_.JoystickEvent_swiginit(self,_misc_.new_JoystickEvent(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_misc_",
".",
"JoystickEvent_swiginit",
"(",
"self",
",",
"_misc_",
".",
"new_JoystickEvent",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L2336-L2341 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/cast.py | python | maybe_infer_dtype_type | (element) | return tipo | Try to infer an object's dtype, for use in arithmetic ops.
Uses `element.dtype` if that's available.
Objects implementing the iterator protocol are cast to a NumPy array,
and from there the array's type is used.
Parameters
----------
element : object
Possibly has a `.dtype` attribute, and possibly the iterator
protocol.
Returns
-------
tipo : type
Examples
--------
>>> from collections import namedtuple
>>> Foo = namedtuple("Foo", "dtype")
>>> maybe_infer_dtype_type(Foo(np.dtype("i8")))
numpy.int64 | Try to infer an object's dtype, for use in arithmetic ops. | [
"Try",
"to",
"infer",
"an",
"object",
"s",
"dtype",
"for",
"use",
"in",
"arithmetic",
"ops",
"."
] | def maybe_infer_dtype_type(element):
"""
Try to infer an object's dtype, for use in arithmetic ops.
Uses `element.dtype` if that's available.
Objects implementing the iterator protocol are cast to a NumPy array,
and from there the array's type is used.
Parameters
----------
element : object
Possibly has a `.dtype` attribute, and possibly the iterator
protocol.
Returns
-------
tipo : type
Examples
--------
>>> from collections import namedtuple
>>> Foo = namedtuple("Foo", "dtype")
>>> maybe_infer_dtype_type(Foo(np.dtype("i8")))
numpy.int64
"""
tipo = None
if hasattr(element, "dtype"):
tipo = element.dtype
elif is_list_like(element):
element = np.asarray(element)
tipo = element.dtype
return tipo | [
"def",
"maybe_infer_dtype_type",
"(",
"element",
")",
":",
"tipo",
"=",
"None",
"if",
"hasattr",
"(",
"element",
",",
"\"dtype\"",
")",
":",
"tipo",
"=",
"element",
".",
"dtype",
"elif",
"is_list_like",
"(",
"element",
")",
":",
"element",
"=",
"np",
".",
"asarray",
"(",
"element",
")",
"tipo",
"=",
"element",
".",
"dtype",
"return",
"tipo"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/dtypes/cast.py#L682-L713 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/server/wsgi/serve/publish/search/search_publish_handler.py | python | SearchPublishHandler.__init__ | (self) | Inits SearchPublishServlet. | Inits SearchPublishServlet. | [
"Inits",
"SearchPublishServlet",
"."
] | def __init__(self):
"""Inits SearchPublishServlet."""
try:
self._search_publish_manager = (
search_publish_manager.SearchPublishManager())
except exceptions.Error as e:
self._search_publish_manager = None
logger.error(e) | [
"def",
"__init__",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_search_publish_manager",
"=",
"(",
"search_publish_manager",
".",
"SearchPublishManager",
"(",
")",
")",
"except",
"exceptions",
".",
"Error",
"as",
"e",
":",
"self",
".",
"_search_publish_manager",
"=",
"None",
"logger",
".",
"error",
"(",
"e",
")"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/publish/search/search_publish_handler.py#L36-L43 | ||
plaidml/plaidml | f3c6681db21460e5fdc11ae651d6d7b6c27f8262 | cmake/git-clang-format.py | python | get_object_type | (value) | return convert_string(stdout.strip()) | Returns a string description of an object's type, or None if it is not
a valid git object. | Returns a string description of an object's type, or None if it is not
a valid git object. | [
"Returns",
"a",
"string",
"description",
"of",
"an",
"object",
"s",
"type",
"or",
"None",
"if",
"it",
"is",
"not",
"a",
"valid",
"git",
"object",
"."
] | def get_object_type(value):
"""Returns a string description of an object's type, or None if it is not
a valid git object."""
cmd = ['git', 'cat-file', '-t', value]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
return None
return convert_string(stdout.strip()) | [
"def",
"get_object_type",
"(",
"value",
")",
":",
"cmd",
"=",
"[",
"'git'",
",",
"'cat-file'",
",",
"'-t'",
",",
"value",
"]",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"stdout",
",",
"stderr",
"=",
"p",
".",
"communicate",
"(",
")",
"if",
"p",
".",
"returncode",
"!=",
"0",
":",
"return",
"None",
"return",
"convert_string",
"(",
"stdout",
".",
"strip",
"(",
")",
")"
] | https://github.com/plaidml/plaidml/blob/f3c6681db21460e5fdc11ae651d6d7b6c27f8262/cmake/git-clang-format.py#L264-L272 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/_extends/parse/parser.py | python | get_operation_symbol | (obj) | return ops_symbol | Get obj operation symbol. | Get obj operation symbol. | [
"Get",
"obj",
"operation",
"symbol",
"."
] | def get_operation_symbol(obj):
"""Get obj operation symbol."""
ops_symbol = ops_symbol_map.get(type(obj), SYMBOL_UNDEFINE)
logger.debug("ops symbol: %s", ops_symbol)
return ops_symbol | [
"def",
"get_operation_symbol",
"(",
"obj",
")",
":",
"ops_symbol",
"=",
"ops_symbol_map",
".",
"get",
"(",
"type",
"(",
"obj",
")",
",",
"SYMBOL_UNDEFINE",
")",
"logger",
".",
"debug",
"(",
"\"ops symbol: %s\"",
",",
"ops_symbol",
")",
"return",
"ops_symbol"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parse/parser.py#L467-L471 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_shapestrings.py | python | ShapeString.validSString | (self, sstring) | Validate the string value in the user interface.
This function is called by the toolbar or taskpanel interface
when a valid string value has been entered in the input field. | Validate the string value in the user interface. | [
"Validate",
"the",
"string",
"value",
"in",
"the",
"user",
"interface",
"."
] | def validSString(self, sstring):
"""Validate the string value in the user interface.
This function is called by the toolbar or taskpanel interface
when a valid string value has been entered in the input field.
"""
self.SString = sstring
self.ui.SSizeUi() | [
"def",
"validSString",
"(",
"self",
",",
"sstring",
")",
":",
"self",
".",
"SString",
"=",
"sstring",
"self",
".",
"ui",
".",
"SSizeUi",
"(",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_shapestrings.py#L201-L208 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | FileCtrl.SetFilterIndex | (*args, **kwargs) | return _controls_.FileCtrl_SetFilterIndex(*args, **kwargs) | SetFilterIndex(self, int filterindex) | SetFilterIndex(self, int filterindex) | [
"SetFilterIndex",
"(",
"self",
"int",
"filterindex",
")"
] | def SetFilterIndex(*args, **kwargs):
"""SetFilterIndex(self, int filterindex)"""
return _controls_.FileCtrl_SetFilterIndex(*args, **kwargs) | [
"def",
"SetFilterIndex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"FileCtrl_SetFilterIndex",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L7659-L7661 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/dateutil/tz/_common.py | python | _tzinfo._fromutc | (self, dt) | return dt + dtdst | Given a timezone-aware datetime in a given timezone, calculates a
timezone-aware datetime in a new timezone.
Since this is the one time that we *know* we have an unambiguous
datetime object, we take this opportunity to determine whether the
datetime is ambiguous and in a "fold" state (e.g. if it's the first
occurrence, chronologically, of the ambiguous datetime).
:param dt:
A timezone-aware :class:`datetime.datetime` object. | Given a timezone-aware datetime in a given timezone, calculates a
timezone-aware datetime in a new timezone. | [
"Given",
"a",
"timezone",
"-",
"aware",
"datetime",
"in",
"a",
"given",
"timezone",
"calculates",
"a",
"timezone",
"-",
"aware",
"datetime",
"in",
"a",
"new",
"timezone",
"."
] | def _fromutc(self, dt):
"""
Given a timezone-aware datetime in a given timezone, calculates a
timezone-aware datetime in a new timezone.
Since this is the one time that we *know* we have an unambiguous
datetime object, we take this opportunity to determine whether the
datetime is ambiguous and in a "fold" state (e.g. if it's the first
occurrence, chronologically, of the ambiguous datetime).
:param dt:
A timezone-aware :class:`datetime.datetime` object.
"""
# Re-implement the algorithm from Python's datetime.py
dtoff = dt.utcoffset()
if dtoff is None:
raise ValueError("fromutc() requires a non-None utcoffset() "
"result")
# The original datetime.py code assumes that `dst()` defaults to
# zero during ambiguous times. PEP 495 inverts this presumption, so
# for pre-PEP 495 versions of python, we need to tweak the algorithm.
dtdst = dt.dst()
if dtdst is None:
raise ValueError("fromutc() requires a non-None dst() result")
delta = dtoff - dtdst
dt += delta
# Set fold=1 so we can default to being in the fold for
# ambiguous dates.
dtdst = enfold(dt, fold=1).dst()
if dtdst is None:
raise ValueError("fromutc(): dt.dst gave inconsistent "
"results; cannot convert")
return dt + dtdst | [
"def",
"_fromutc",
"(",
"self",
",",
"dt",
")",
":",
"# Re-implement the algorithm from Python's datetime.py",
"dtoff",
"=",
"dt",
".",
"utcoffset",
"(",
")",
"if",
"dtoff",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"fromutc() requires a non-None utcoffset() \"",
"\"result\"",
")",
"# The original datetime.py code assumes that `dst()` defaults to",
"# zero during ambiguous times. PEP 495 inverts this presumption, so",
"# for pre-PEP 495 versions of python, we need to tweak the algorithm.",
"dtdst",
"=",
"dt",
".",
"dst",
"(",
")",
"if",
"dtdst",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"fromutc() requires a non-None dst() result\"",
")",
"delta",
"=",
"dtoff",
"-",
"dtdst",
"dt",
"+=",
"delta",
"# Set fold=1 so we can default to being in the fold for",
"# ambiguous dates.",
"dtdst",
"=",
"enfold",
"(",
"dt",
",",
"fold",
"=",
"1",
")",
".",
"dst",
"(",
")",
"if",
"dtdst",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"fromutc(): dt.dst gave inconsistent \"",
"\"results; cannot convert\"",
")",
"return",
"dt",
"+",
"dtdst"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/dateutil/tz/_common.py#L207-L242 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPMT_SYM_DEF.initFromTpm | (self, buf) | TpmMarshaller method | TpmMarshaller method | [
"TpmMarshaller",
"method"
] | def initFromTpm(self, buf):
""" TpmMarshaller method """
self.algorithm = buf.readShort()
if self.algorithm == TPM_ALG_ID.NULL: return
self.keyBits = buf.readShort()
self.mode = buf.readShort() | [
"def",
"initFromTpm",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"algorithm",
"=",
"buf",
".",
"readShort",
"(",
")",
"if",
"self",
".",
"algorithm",
"==",
"TPM_ALG_ID",
".",
"NULL",
":",
"return",
"self",
".",
"keyBits",
"=",
"buf",
".",
"readShort",
"(",
")",
"self",
".",
"mode",
"=",
"buf",
".",
"readShort",
"(",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L5817-L5822 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py | python | MaskedArray.__sub__ | (self, other) | return subtract(self, other) | Subtract other to self, and return a new masked array. | Subtract other to self, and return a new masked array. | [
"Subtract",
"other",
"to",
"self",
"and",
"return",
"a",
"new",
"masked",
"array",
"."
] | def __sub__(self, other):
"Subtract other to self, and return a new masked array."
return subtract(self, other) | [
"def",
"__sub__",
"(",
"self",
",",
"other",
")",
":",
"return",
"subtract",
"(",
"self",
",",
"other",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py#L3697-L3699 | |
OpenChemistry/tomviz | 0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a | tomviz/python/GradientMagnitude2D_Sobel.py | python | transform | (dataset) | Calculate gradient magnitude of each tilt image using Sobel operator | Calculate gradient magnitude of each tilt image using Sobel operator | [
"Calculate",
"gradient",
"magnitude",
"of",
"each",
"tilt",
"image",
"using",
"Sobel",
"operator"
] | def transform(dataset):
"""Calculate gradient magnitude of each tilt image using Sobel operator"""
import numpy as np
import scipy.ndimage.filters
array = dataset.active_scalars
array = array.astype(np.float32)
# Transform the dataset along the third axis.
aaSobelX = np.empty_like(array)
# 1D X-axis sobel
scipy.ndimage.filters.sobel(array, axis=0, output=aaSobelX)
aaSobelY = np.empty_like(array)
# 1D Y-axis sobel
scipy.ndimage.filters.sobel(array, axis=1, output=aaSobelY)
# Calculate 2D sobel for each image slice.
result = np.hypot(aaSobelX, aaSobelY)
# Set the result as the new scalars.
dataset.active_scalars = result | [
"def",
"transform",
"(",
"dataset",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"scipy",
".",
"ndimage",
".",
"filters",
"array",
"=",
"dataset",
".",
"active_scalars",
"array",
"=",
"array",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"# Transform the dataset along the third axis.",
"aaSobelX",
"=",
"np",
".",
"empty_like",
"(",
"array",
")",
"# 1D X-axis sobel",
"scipy",
".",
"ndimage",
".",
"filters",
".",
"sobel",
"(",
"array",
",",
"axis",
"=",
"0",
",",
"output",
"=",
"aaSobelX",
")",
"aaSobelY",
"=",
"np",
".",
"empty_like",
"(",
"array",
")",
"# 1D Y-axis sobel",
"scipy",
".",
"ndimage",
".",
"filters",
".",
"sobel",
"(",
"array",
",",
"axis",
"=",
"1",
",",
"output",
"=",
"aaSobelY",
")",
"# Calculate 2D sobel for each image slice.",
"result",
"=",
"np",
".",
"hypot",
"(",
"aaSobelX",
",",
"aaSobelY",
")",
"# Set the result as the new scalars.",
"dataset",
".",
"active_scalars",
"=",
"result"
] | https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/GradientMagnitude2D_Sobel.py#L1-L22 | ||
psnonis/FinBERT | c0c555d833a14e2316a3701e59c0b5156f804b4e | bert-gpu/fp16_utils.py | python | float32_variable_storage_getter | (getter, name, shape=None, dtype=None,
initializer=None, regularizer=None,
trainable=True,
*args, **kwargs) | return variable | Custom variable getter that forces trainable variables to be stored in
float32 precision and then casts them to the training precision. | Custom variable getter that forces trainable variables to be stored in
float32 precision and then casts them to the training precision. | [
"Custom",
"variable",
"getter",
"that",
"forces",
"trainable",
"variables",
"to",
"be",
"stored",
"in",
"float32",
"precision",
"and",
"then",
"casts",
"them",
"to",
"the",
"training",
"precision",
"."
] | def float32_variable_storage_getter(getter, name, shape=None, dtype=None,
initializer=None, regularizer=None,
trainable=True,
*args, **kwargs):
"""Custom variable getter that forces trainable variables to be stored in
float32 precision and then casts them to the training precision.
"""
storage_dtype = tf.float32 if trainable else dtype
variable = getter(name, shape, dtype=storage_dtype,
initializer=initializer, regularizer=regularizer,
trainable=trainable,
*args, **kwargs)
if trainable and dtype != tf.float32:
variable = tf.cast(variable, dtype)
return variable | [
"def",
"float32_variable_storage_getter",
"(",
"getter",
",",
"name",
",",
"shape",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"initializer",
"=",
"None",
",",
"regularizer",
"=",
"None",
",",
"trainable",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"storage_dtype",
"=",
"tf",
".",
"float32",
"if",
"trainable",
"else",
"dtype",
"variable",
"=",
"getter",
"(",
"name",
",",
"shape",
",",
"dtype",
"=",
"storage_dtype",
",",
"initializer",
"=",
"initializer",
",",
"regularizer",
"=",
"regularizer",
",",
"trainable",
"=",
"trainable",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"trainable",
"and",
"dtype",
"!=",
"tf",
".",
"float32",
":",
"variable",
"=",
"tf",
".",
"cast",
"(",
"variable",
",",
"dtype",
")",
"return",
"variable"
] | https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/fp16_utils.py#L20-L34 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py | python | Trace.message | (cls, message) | Show a trace message | Show a trace message | [
"Show",
"a",
"trace",
"message"
] | def message(cls, message):
"Show a trace message"
if Trace.quietmode:
return
if Trace.prefix and Trace.showlinesmode:
message = Trace.prefix + message
Trace.show(message, sys.stdout) | [
"def",
"message",
"(",
"cls",
",",
"message",
")",
":",
"if",
"Trace",
".",
"quietmode",
":",
"return",
"if",
"Trace",
".",
"prefix",
"and",
"Trace",
".",
"showlinesmode",
":",
"message",
"=",
"Trace",
".",
"prefix",
"+",
"message",
"Trace",
".",
"show",
"(",
"message",
",",
"sys",
".",
"stdout",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L43-L49 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/procrouting/response/scf_products.py | python | ProductCache.__init__ | (self, *product_types) | Creates a new Product Cache
Parameters
----------
*product_types, list of str
A list of product labels | Creates a new Product Cache | [
"Creates",
"a",
"new",
"Product",
"Cache"
] | def __init__(self, *product_types):
"""Creates a new Product Cache
Parameters
----------
*product_types, list of str
A list of product labels
"""
self._products = {p: [] for p in product_types} | [
"def",
"__init__",
"(",
"self",
",",
"*",
"product_types",
")",
":",
"self",
".",
"_products",
"=",
"{",
"p",
":",
"[",
"]",
"for",
"p",
"in",
"product_types",
"}"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/procrouting/response/scf_products.py#L122-L130 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | Appearance.setTexture2D_channels | (self, format: str, np_array3: "ndarray", topdown: bool=True) | return _robotsim.Appearance_setTexture2D_channels(self, format, np_array3, topdown) | r"""
Sets a 2D texture of the given width/height from a 3D array of channels. See
:func:`setTexture1D_channels` for valid format strings.
Args:
format (str)
np_array3 (:obj:`unsigned char *`)
topdown (bool, optional): default value True
The array is given in top to bottom order if `topdown==True`. Otherwise, it is
given in order bottom to top. | r"""
Sets a 2D texture of the given width/height from a 3D array of channels. See
:func:`setTexture1D_channels` for valid format strings. | [
"r",
"Sets",
"a",
"2D",
"texture",
"of",
"the",
"given",
"width",
"/",
"height",
"from",
"a",
"3D",
"array",
"of",
"channels",
".",
"See",
":",
"func",
":",
"setTexture1D_channels",
"for",
"valid",
"format",
"strings",
"."
] | def setTexture2D_channels(self, format: str, np_array3: "ndarray", topdown: bool=True) ->None:
r"""
Sets a 2D texture of the given width/height from a 3D array of channels. See
:func:`setTexture1D_channels` for valid format strings.
Args:
format (str)
np_array3 (:obj:`unsigned char *`)
topdown (bool, optional): default value True
The array is given in top to bottom order if `topdown==True`. Otherwise, it is
given in order bottom to top.
"""
return _robotsim.Appearance_setTexture2D_channels(self, format, np_array3, topdown) | [
"def",
"setTexture2D_channels",
"(",
"self",
",",
"format",
":",
"str",
",",
"np_array3",
":",
"\"ndarray\"",
",",
"topdown",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"return",
"_robotsim",
".",
"Appearance_setTexture2D_channels",
"(",
"self",
",",
"format",
",",
"np_array3",
",",
"topdown",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L3007-L3021 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/lib/io/tf_record.py | python | tf_record_iterator | (path, options=None) | An iterator that read the records from a TFRecords file.
Args:
path: The path to the TFRecords file.
options: (optional) A TFRecordOptions object.
Yields:
Strings.
Raises:
IOError: If `path` cannot be opened for reading. | An iterator that read the records from a TFRecords file. | [
"An",
"iterator",
"that",
"read",
"the",
"records",
"from",
"a",
"TFRecords",
"file",
"."
] | def tf_record_iterator(path, options=None):
"""An iterator that read the records from a TFRecords file.
Args:
path: The path to the TFRecords file.
options: (optional) A TFRecordOptions object.
Yields:
Strings.
Raises:
IOError: If `path` cannot be opened for reading.
"""
compression_type = TFRecordOptions.get_compression_type_string(options)
with errors.raise_exception_on_not_ok_status() as status:
reader = pywrap_tensorflow.PyRecordReader_New(
compat.as_bytes(path), 0, compat.as_bytes(compression_type), status)
if reader is None:
raise IOError("Could not open %s." % path)
while reader.GetNext():
yield reader.record()
reader.Close() | [
"def",
"tf_record_iterator",
"(",
"path",
",",
"options",
"=",
"None",
")",
":",
"compression_type",
"=",
"TFRecordOptions",
".",
"get_compression_type_string",
"(",
"options",
")",
"with",
"errors",
".",
"raise_exception_on_not_ok_status",
"(",
")",
"as",
"status",
":",
"reader",
"=",
"pywrap_tensorflow",
".",
"PyRecordReader_New",
"(",
"compat",
".",
"as_bytes",
"(",
"path",
")",
",",
"0",
",",
"compat",
".",
"as_bytes",
"(",
"compression_type",
")",
",",
"status",
")",
"if",
"reader",
"is",
"None",
":",
"raise",
"IOError",
"(",
"\"Could not open %s.\"",
"%",
"path",
")",
"while",
"reader",
".",
"GetNext",
"(",
")",
":",
"yield",
"reader",
".",
"record",
"(",
")",
"reader",
".",
"Close",
"(",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/lib/io/tf_record.py#L53-L75 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py | python | CheckSpacingForFunctionCall | (filename, line, linenum, error) | Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for the correctness of various spacing around function calls. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"around",
"function",
"calls",
"."
] | def CheckSpacingForFunctionCall(filename, line, linenum, error):
"""Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
line: The text of the line to check.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Since function calls often occur inside if/for/while/switch
# expressions - which have their own, more liberal conventions - we
# first see if we should be looking inside such an expression for a
# function call, to which we can apply more strict standards.
fncall = line # if there's no control flow construct, look at whole line
for pattern in (r'\bif\s*\((.*)\)\s*{',
r'\bfor\s*\((.*)\)\s*{',
r'\bwhile\s*\((.*)\)\s*[{;]',
r'\bswitch\s*\((.*)\)\s*{'):
match = Search(pattern, line)
if match:
fncall = match.group(1) # look inside the parens for function calls
break
# Except in if/for/while/switch, there should never be space
# immediately inside parens (eg "f( 3, 4 )"). We make an exception
# for nested parens ( (a+b) + c ). Likewise, there should never be
# a space before a ( when it's a function argument. I assume it's a
# function argument when the char before the whitespace is legal in
# a function name (alnum + _) and we're not starting a macro. Also ignore
# pointers and references to arrays and functions coz they're too tricky:
# we use a very simple way to recognize these:
# " (something)(maybe-something)" or
# " (something)(maybe-something," or
# " (something)[something]"
# Note that we assume the contents of [] to be short enough that
# they'll never need to wrap.
if ( # Ignore control structures.
not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
fncall) and
# Ignore pointers/references to functions.
not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
# Ignore pointers/references to arrays.
not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
error(filename, linenum, 'whitespace/parens', 4,
'Extra space after ( in function call')
elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Extra space after (')
if (Search(r'\w\s+\(', fncall) and
not Search(r'#\s*define|typedef', fncall) and
not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)):
error(filename, linenum, 'whitespace/parens', 4,
'Extra space before ( in function call')
# If the ) is followed only by a newline or a { + newline, assume it's
# part of a control statement (if/while/etc), and don't complain
if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
# If the closing parenthesis is preceded by only whitespaces,
# try to give a more descriptive error message.
if Search(r'^\s+\)', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Closing ) should be moved to the previous line')
else:
error(filename, linenum, 'whitespace/parens', 2,
'Extra space before )') | [
"def",
"CheckSpacingForFunctionCall",
"(",
"filename",
",",
"line",
",",
"linenum",
",",
"error",
")",
":",
"# Since function calls often occur inside if/for/while/switch",
"# expressions - which have their own, more liberal conventions - we",
"# first see if we should be looking inside such an expression for a",
"# function call, to which we can apply more strict standards.",
"fncall",
"=",
"line",
"# if there's no control flow construct, look at whole line",
"for",
"pattern",
"in",
"(",
"r'\\bif\\s*\\((.*)\\)\\s*{'",
",",
"r'\\bfor\\s*\\((.*)\\)\\s*{'",
",",
"r'\\bwhile\\s*\\((.*)\\)\\s*[{;]'",
",",
"r'\\bswitch\\s*\\((.*)\\)\\s*{'",
")",
":",
"match",
"=",
"Search",
"(",
"pattern",
",",
"line",
")",
"if",
"match",
":",
"fncall",
"=",
"match",
".",
"group",
"(",
"1",
")",
"# look inside the parens for function calls",
"break",
"# Except in if/for/while/switch, there should never be space",
"# immediately inside parens (eg \"f( 3, 4 )\"). We make an exception",
"# for nested parens ( (a+b) + c ). Likewise, there should never be",
"# a space before a ( when it's a function argument. I assume it's a",
"# function argument when the char before the whitespace is legal in",
"# a function name (alnum + _) and we're not starting a macro. Also ignore",
"# pointers and references to arrays and functions coz they're too tricky:",
"# we use a very simple way to recognize these:",
"# \" (something)(maybe-something)\" or",
"# \" (something)(maybe-something,\" or",
"# \" (something)[something]\"",
"# Note that we assume the contents of [] to be short enough that",
"# they'll never need to wrap.",
"if",
"(",
"# Ignore control structures.",
"not",
"Search",
"(",
"r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b'",
",",
"fncall",
")",
"and",
"# Ignore pointers/references to functions.",
"not",
"Search",
"(",
"r' \\([^)]+\\)\\([^)]*(\\)|,$)'",
",",
"fncall",
")",
"and",
"# Ignore pointers/references to arrays.",
"not",
"Search",
"(",
"r' \\([^)]+\\)\\[[^\\]]+\\]'",
",",
"fncall",
")",
")",
":",
"if",
"Search",
"(",
"r'\\w\\s*\\(\\s(?!\\s*\\\\$)'",
",",
"fncall",
")",
":",
"# a ( used for a fn call",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"4",
",",
"'Extra space after ( in function call'",
")",
"elif",
"Search",
"(",
"r'\\(\\s+(?!(\\s*\\\\)|\\()'",
",",
"fncall",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Extra space after ('",
")",
"if",
"(",
"Search",
"(",
"r'\\w\\s+\\('",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'#\\s*define|typedef'",
",",
"fncall",
")",
"and",
"not",
"Search",
"(",
"r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\('",
",",
"fncall",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"4",
",",
"'Extra space before ( in function call'",
")",
"# If the ) is followed only by a newline or a { + newline, assume it's",
"# part of a control statement (if/while/etc), and don't complain",
"if",
"Search",
"(",
"r'[^)]\\s+\\)\\s*[^{\\s]'",
",",
"fncall",
")",
":",
"# If the closing parenthesis is preceded by only whitespaces,",
"# try to give a more descriptive error message.",
"if",
"Search",
"(",
"r'^\\s+\\)'",
",",
"fncall",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Closing ) should be moved to the previous line'",
")",
"else",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'whitespace/parens'",
",",
"2",
",",
"'Extra space before )'",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py#L2301-L2366 | ||
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/fuzzbunch/pyreadline/modes/emacs.py | python | EmacsMode.overwrite_mode | (self, e) | Toggle overwrite mode. With an explicit positive numeric
argument, switches to overwrite mode. With an explicit non-positive
numeric argument, switches to insert mode. This command affects only
emacs mode; vi mode does overwrite differently. Each call to
readline() starts in insert mode. In overwrite mode, characters
bound to self-insert replace the text at point rather than pushing
the text to the right. Characters bound to backward-delete-char
replace the character before point with a space. | Toggle overwrite mode. With an explicit positive numeric
argument, switches to overwrite mode. With an explicit non-positive
numeric argument, switches to insert mode. This command affects only
emacs mode; vi mode does overwrite differently. Each call to
readline() starts in insert mode. In overwrite mode, characters
bound to self-insert replace the text at point rather than pushing
the text to the right. Characters bound to backward-delete-char
replace the character before point with a space. | [
"Toggle",
"overwrite",
"mode",
".",
"With",
"an",
"explicit",
"positive",
"numeric",
"argument",
"switches",
"to",
"overwrite",
"mode",
".",
"With",
"an",
"explicit",
"non",
"-",
"positive",
"numeric",
"argument",
"switches",
"to",
"insert",
"mode",
".",
"This",
"command",
"affects",
"only",
"emacs",
"mode",
";",
"vi",
"mode",
"does",
"overwrite",
"differently",
".",
"Each",
"call",
"to",
"readline",
"()",
"starts",
"in",
"insert",
"mode",
".",
"In",
"overwrite",
"mode",
"characters",
"bound",
"to",
"self",
"-",
"insert",
"replace",
"the",
"text",
"at",
"point",
"rather",
"than",
"pushing",
"the",
"text",
"to",
"the",
"right",
".",
"Characters",
"bound",
"to",
"backward",
"-",
"delete",
"-",
"char",
"replace",
"the",
"character",
"before",
"point",
"with",
"a",
"space",
"."
] | def overwrite_mode(self, e): # ()
'''Toggle overwrite mode. With an explicit positive numeric
argument, switches to overwrite mode. With an explicit non-positive
numeric argument, switches to insert mode. This command affects only
emacs mode; vi mode does overwrite differently. Each call to
readline() starts in insert mode. In overwrite mode, characters
bound to self-insert replace the text at point rather than pushing
the text to the right. Characters bound to backward-delete-char
replace the character before point with a space.'''
pass | [
"def",
"overwrite_mode",
"(",
"self",
",",
"e",
")",
":",
"# ()",
"pass"
] | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/modes/emacs.py#L298-L307 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/index/collector.py | python | _create_link_from_element | (
anchor, # type: HTMLElement
page_url, # type: str
base_url, # type: str
) | return link | Convert an anchor element in a simple repository page to a Link. | Convert an anchor element in a simple repository page to a Link. | [
"Convert",
"an",
"anchor",
"element",
"in",
"a",
"simple",
"repository",
"page",
"to",
"a",
"Link",
"."
] | def _create_link_from_element(
anchor, # type: HTMLElement
page_url, # type: str
base_url, # type: str
):
# type: (...) -> Optional[Link]
"""
Convert an anchor element in a simple repository page to a Link.
"""
href = anchor.get("href")
if not href:
return None
url = _clean_link(urllib.parse.urljoin(base_url, href))
pyrequire = anchor.get('data-requires-python')
pyrequire = unescape(pyrequire) if pyrequire else None
yanked_reason = anchor.get('data-yanked')
if yanked_reason:
# This is a unicode string in Python 2 (and 3).
yanked_reason = unescape(yanked_reason)
link = Link(
url,
comes_from=page_url,
requires_python=pyrequire,
yanked_reason=yanked_reason,
)
return link | [
"def",
"_create_link_from_element",
"(",
"anchor",
",",
"# type: HTMLElement",
"page_url",
",",
"# type: str",
"base_url",
",",
"# type: str",
")",
":",
"# type: (...) -> Optional[Link]",
"href",
"=",
"anchor",
".",
"get",
"(",
"\"href\"",
")",
"if",
"not",
"href",
":",
"return",
"None",
"url",
"=",
"_clean_link",
"(",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"base_url",
",",
"href",
")",
")",
"pyrequire",
"=",
"anchor",
".",
"get",
"(",
"'data-requires-python'",
")",
"pyrequire",
"=",
"unescape",
"(",
"pyrequire",
")",
"if",
"pyrequire",
"else",
"None",
"yanked_reason",
"=",
"anchor",
".",
"get",
"(",
"'data-yanked'",
")",
"if",
"yanked_reason",
":",
"# This is a unicode string in Python 2 (and 3).",
"yanked_reason",
"=",
"unescape",
"(",
"yanked_reason",
")",
"link",
"=",
"Link",
"(",
"url",
",",
"comes_from",
"=",
"page_url",
",",
"requires_python",
"=",
"pyrequire",
",",
"yanked_reason",
"=",
"yanked_reason",
",",
")",
"return",
"link"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/index/collector.py#L255-L284 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/pyshell.py | python | PyShellEditorWindow.update_breakpoints | (self) | Retrieves all the breakpoints in the current window | Retrieves all the breakpoints in the current window | [
"Retrieves",
"all",
"the",
"breakpoints",
"in",
"the",
"current",
"window"
] | def update_breakpoints(self):
"Retrieves all the breakpoints in the current window"
text = self.text
ranges = text.tag_ranges("BREAK")
linenumber_list = self.ranges_to_linenumbers(ranges)
self.breakpoints = linenumber_list | [
"def",
"update_breakpoints",
"(",
"self",
")",
":",
"text",
"=",
"self",
".",
"text",
"ranges",
"=",
"text",
".",
"tag_ranges",
"(",
"\"BREAK\"",
")",
"linenumber_list",
"=",
"self",
".",
"ranges_to_linenumbers",
"(",
"ranges",
")",
"self",
".",
"breakpoints",
"=",
"linenumber_list"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/pyshell.py#L286-L291 | ||
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | common/thrift/generate_metrics.py | python | generate_mdl | () | Generates the CM compatible metric definition (MDL) file. | Generates the CM compatible metric definition (MDL) file. | [
"Generates",
"the",
"CM",
"compatible",
"metric",
"definition",
"(",
"MDL",
")",
"file",
"."
] | def generate_mdl():
"""Generates the CM compatible metric definition (MDL) file."""
metrics = []
input_file = open(options.input_schema_path)
try:
metrics = json.load(input_file)
finally:
input_file.close()
# A map of entity type -> [metric dicts].
metrics_by_role = collections.defaultdict(lambda: [])
for m in metrics:
# Convert to the format that CM expects.
mdl_metric = metric_to_mdl(m)
if mdl_metric is None:
continue
for ctx in m['contexts']:
metrics_by_role[ctx].append(mdl_metric)
mdl = json.loads(MDL_BASE)
mdl['version'] = options.output_mdl_version
for role in mdl['roles']:
role_metrics = []
if metrics_by_role.has_key(role['name']):
role_metrics = metrics_by_role[role['name']]
role['metricDefinitions'] = role_metrics
target_file = options.output_mdl_path
fid = open(target_file, "w")
try:
fid.write(json.dumps(mdl, indent=4))
finally:
fid.close()
print("%s created." % target_file) | [
"def",
"generate_mdl",
"(",
")",
":",
"metrics",
"=",
"[",
"]",
"input_file",
"=",
"open",
"(",
"options",
".",
"input_schema_path",
")",
"try",
":",
"metrics",
"=",
"json",
".",
"load",
"(",
"input_file",
")",
"finally",
":",
"input_file",
".",
"close",
"(",
")",
"# A map of entity type -> [metric dicts].",
"metrics_by_role",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"[",
"]",
")",
"for",
"m",
"in",
"metrics",
":",
"# Convert to the format that CM expects.",
"mdl_metric",
"=",
"metric_to_mdl",
"(",
"m",
")",
"if",
"mdl_metric",
"is",
"None",
":",
"continue",
"for",
"ctx",
"in",
"m",
"[",
"'contexts'",
"]",
":",
"metrics_by_role",
"[",
"ctx",
"]",
".",
"append",
"(",
"mdl_metric",
")",
"mdl",
"=",
"json",
".",
"loads",
"(",
"MDL_BASE",
")",
"mdl",
"[",
"'version'",
"]",
"=",
"options",
".",
"output_mdl_version",
"for",
"role",
"in",
"mdl",
"[",
"'roles'",
"]",
":",
"role_metrics",
"=",
"[",
"]",
"if",
"metrics_by_role",
".",
"has_key",
"(",
"role",
"[",
"'name'",
"]",
")",
":",
"role_metrics",
"=",
"metrics_by_role",
"[",
"role",
"[",
"'name'",
"]",
"]",
"role",
"[",
"'metricDefinitions'",
"]",
"=",
"role_metrics",
"target_file",
"=",
"options",
".",
"output_mdl_path",
"fid",
"=",
"open",
"(",
"target_file",
",",
"\"w\"",
")",
"try",
":",
"fid",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"mdl",
",",
"indent",
"=",
"4",
")",
")",
"finally",
":",
"fid",
".",
"close",
"(",
")",
"print",
"(",
"\"%s created.\"",
"%",
"target_file",
")"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/common/thrift/generate_metrics.py#L210-L243 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/conv2d.py | python | _conv2d_tbe | () | return | Conv2D TBE register | Conv2D TBE register | [
"Conv2D",
"TBE",
"register"
] | def _conv2d_tbe():
"""Conv2D TBE register"""
return | [
"def",
"_conv2d_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/conv2d.py#L45-L47 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/distribution/exponential.py | python | Exponential._log_prob | (self, value, rate=None) | return self.select(comp, neginf, prob) | r"""
Log probability density function of Exponential distributions.
Args:
Args:
value (Tensor): The value to be evaluated.
rate (Tensor): The rate of the distribution. Default: self.rate.
Note:
`value` must be greater or equal to zero.
.. math::
log_pdf(x) = \log(rate) - rate * x if x >= 0 else 0 | r"""
Log probability density function of Exponential distributions. | [
"r",
"Log",
"probability",
"density",
"function",
"of",
"Exponential",
"distributions",
"."
] | def _log_prob(self, value, rate=None):
r"""
Log probability density function of Exponential distributions.
Args:
Args:
value (Tensor): The value to be evaluated.
rate (Tensor): The rate of the distribution. Default: self.rate.
Note:
`value` must be greater or equal to zero.
.. math::
log_pdf(x) = \log(rate) - rate * x if x >= 0 else 0
"""
value = self._check_value(value, "value")
value = self.cast(value, self.dtype)
rate = self._check_param_type(rate)
prob = self.log(rate) - rate * value
zeros = self.fill(self.dtypeop(prob), self.shape(prob), 0.0)
neginf = self.fill(self.dtypeop(prob), self.shape(prob), -np.inf)
comp = self.less(value, zeros)
return self.select(comp, neginf, prob) | [
"def",
"_log_prob",
"(",
"self",
",",
"value",
",",
"rate",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"_check_value",
"(",
"value",
",",
"\"value\"",
")",
"value",
"=",
"self",
".",
"cast",
"(",
"value",
",",
"self",
".",
"dtype",
")",
"rate",
"=",
"self",
".",
"_check_param_type",
"(",
"rate",
")",
"prob",
"=",
"self",
".",
"log",
"(",
"rate",
")",
"-",
"rate",
"*",
"value",
"zeros",
"=",
"self",
".",
"fill",
"(",
"self",
".",
"dtypeop",
"(",
"prob",
")",
",",
"self",
".",
"shape",
"(",
"prob",
")",
",",
"0.0",
")",
"neginf",
"=",
"self",
".",
"fill",
"(",
"self",
".",
"dtypeop",
"(",
"prob",
")",
",",
"self",
".",
"shape",
"(",
"prob",
")",
",",
"-",
"np",
".",
"inf",
")",
"comp",
"=",
"self",
".",
"less",
"(",
"value",
",",
"zeros",
")",
"return",
"self",
".",
"select",
"(",
"comp",
",",
"neginf",
",",
"prob",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/exponential.py#L254-L276 | |
ZhouWeikuan/DouDiZhu | 0d84ff6c0bc54dba6ae37955de9ae9307513dc99 | code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | CursorKind.get_all_kinds | () | return filter(None, CursorKind._kinds) | Return all CursorKind enumeration instances. | Return all CursorKind enumeration instances. | [
"Return",
"all",
"CursorKind",
"enumeration",
"instances",
"."
] | def get_all_kinds():
"""Return all CursorKind enumeration instances."""
return filter(None, CursorKind._kinds) | [
"def",
"get_all_kinds",
"(",
")",
":",
"return",
"filter",
"(",
"None",
",",
"CursorKind",
".",
"_kinds",
")"
] | https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L515-L517 | |
NervanaSystems/ngraph | f677a119765ca30636cf407009dabd118664951f | python/src/ngraph/ops.py | python | subtract | (
left_node: NodeInput,
right_node: NodeInput,
auto_broadcast: str = "NUMPY",
name: Optional[str] = None,
) | return _get_node_factory().create(
"Subtract", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
) | Return node which applies f(x) = A-B to the input nodes element-wise.
:param left_node: The node providing data for left hand side of operator.
:param right_node: The node providing data for right hand side of operator.
:param auto_broadcast: The type of broadcasting that specifies mapping of input tensor axes
to output shape axes. Range of values: numpy, explicit.
:param name: The optional name for output node.
:return: The new output node performing subtraction operation on both tensors element-wise. | Return node which applies f(x) = A-B to the input nodes element-wise. | [
"Return",
"node",
"which",
"applies",
"f",
"(",
"x",
")",
"=",
"A",
"-",
"B",
"to",
"the",
"input",
"nodes",
"element",
"-",
"wise",
"."
] | def subtract(
left_node: NodeInput,
right_node: NodeInput,
auto_broadcast: str = "NUMPY",
name: Optional[str] = None,
) -> Node:
"""Return node which applies f(x) = A-B to the input nodes element-wise.
:param left_node: The node providing data for left hand side of operator.
:param right_node: The node providing data for right hand side of operator.
:param auto_broadcast: The type of broadcasting that specifies mapping of input tensor axes
to output shape axes. Range of values: numpy, explicit.
:param name: The optional name for output node.
:return: The new output node performing subtraction operation on both tensors element-wise.
"""
return _get_node_factory().create(
"Subtract", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
) | [
"def",
"subtract",
"(",
"left_node",
":",
"NodeInput",
",",
"right_node",
":",
"NodeInput",
",",
"auto_broadcast",
":",
"str",
"=",
"\"NUMPY\"",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"Node",
":",
"return",
"_get_node_factory",
"(",
")",
".",
"create",
"(",
"\"Subtract\"",
",",
"[",
"left_node",
",",
"right_node",
"]",
",",
"{",
"\"auto_broadcast\"",
":",
"auto_broadcast",
".",
"upper",
"(",
")",
"}",
")"
] | https://github.com/NervanaSystems/ngraph/blob/f677a119765ca30636cf407009dabd118664951f/python/src/ngraph/ops.py#L1066-L1083 | |
DaFuCoding/MTCNN_Caffe | 09c30c3ff391bd9cb6b249c1910afaf147767ab3 | python/caffe/io.py | python | datum_to_array | (datum) | Converts a datum to an array. Note that the label is not returned,
as one can easily get it by calling datum.label. | Converts a datum to an array. Note that the label is not returned,
as one can easily get it by calling datum.label. | [
"Converts",
"a",
"datum",
"to",
"an",
"array",
".",
"Note",
"that",
"the",
"label",
"is",
"not",
"returned",
"as",
"one",
"can",
"easily",
"get",
"it",
"by",
"calling",
"datum",
".",
"label",
"."
] | def datum_to_array(datum):
"""Converts a datum to an array. Note that the label is not returned,
as one can easily get it by calling datum.label.
"""
if len(datum.data):
return np.fromstring(datum.data, dtype=np.uint8).reshape(
datum.channels, datum.height, datum.width)
else:
return np.array(datum.float_data).astype(float).reshape(
datum.channels, datum.height, datum.width) | [
"def",
"datum_to_array",
"(",
"datum",
")",
":",
"if",
"len",
"(",
"datum",
".",
"data",
")",
":",
"return",
"np",
".",
"fromstring",
"(",
"datum",
".",
"data",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
".",
"reshape",
"(",
"datum",
".",
"channels",
",",
"datum",
".",
"height",
",",
"datum",
".",
"width",
")",
"else",
":",
"return",
"np",
".",
"array",
"(",
"datum",
".",
"float_data",
")",
".",
"astype",
"(",
"float",
")",
".",
"reshape",
"(",
"datum",
".",
"channels",
",",
"datum",
".",
"height",
",",
"datum",
".",
"width",
")"
] | https://github.com/DaFuCoding/MTCNN_Caffe/blob/09c30c3ff391bd9cb6b249c1910afaf147767ab3/python/caffe/io.py#L84-L93 | ||
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/processor/conversion/swgbcc/upgrade_resource_subprocessor.py | python | SWGBCCUpgradeResourceSubprocessor.monk_conversion_upgrade | (converter_group, value, operator, team=False) | return patches | Creates a patch for the monk conversion effect (ID: 27).
:param converter_group: Tech/Civ that gets the patch.
:type converter_group: ...dataformat.converter_object.ConverterObjectGroup
:param value: Value used for patching the member.
:type value: MemberOperator
:param operator: Operator used for patching the member.
:type operator: MemberOperator
:returns: The forward references for the generated patches.
:rtype: list | Creates a patch for the monk conversion effect (ID: 27). | [
"Creates",
"a",
"patch",
"for",
"the",
"monk",
"conversion",
"effect",
"(",
"ID",
":",
"27",
")",
"."
] | def monk_conversion_upgrade(converter_group, value, operator, team=False):
"""
Creates a patch for the monk conversion effect (ID: 27).
:param converter_group: Tech/Civ that gets the patch.
:type converter_group: ...dataformat.converter_object.ConverterObjectGroup
:param value: Value used for patching the member.
:type value: MemberOperator
:param operator: Operator used for patching the member.
:type operator: MemberOperator
:returns: The forward references for the generated patches.
:rtype: list
"""
force_ids = [115, 180]
dataset = converter_group.data
patches = []
for force_id in force_ids:
line = dataset.unit_lines[force_id]
name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version)
obj_id = converter_group.get_id()
if isinstance(converter_group, GenieTechEffectBundleGroup):
tech_lookup_dict = internal_name_lookups.get_tech_lookups(dataset.game_version)
obj_name = tech_lookup_dict[obj_id][0]
else:
civ_lookup_dict = internal_name_lookups.get_civ_lookups(dataset.game_version)
obj_name = civ_lookup_dict[obj_id][0]
game_entity_name = name_lookup_dict[force_id][0]
patch_target_ref = f"{game_entity_name}.Convert"
patch_target_forward_ref = ForwardRef(line, patch_target_ref)
# Wrapper
wrapper_name = f"Enable{game_entity_name}ConversionWrapper"
wrapper_ref = f"{obj_name}.{wrapper_name}"
wrapper_location = ForwardRef(converter_group, obj_name)
wrapper_raw_api_object = RawAPIObject(wrapper_ref,
wrapper_name,
dataset.nyan_api_objects,
wrapper_location)
wrapper_raw_api_object.add_raw_parent("engine.util.patch.Patch")
# Nyan patch
nyan_patch_name = f"Enable{game_entity_name}Conversion"
nyan_patch_ref = f"{obj_name}.{wrapper_name}.{nyan_patch_name}"
nyan_patch_location = ForwardRef(converter_group, wrapper_ref)
nyan_patch_raw_api_object = RawAPIObject(nyan_patch_ref,
nyan_patch_name,
dataset.nyan_api_objects,
nyan_patch_location)
nyan_patch_raw_api_object.add_raw_parent("engine.util.patch.NyanPatch")
nyan_patch_raw_api_object.set_patch_target(patch_target_forward_ref)
monk_forward_ref = ForwardRef(line, game_entity_name)
nyan_patch_raw_api_object.add_raw_patch_member("blacklisted_entities",
[monk_forward_ref],
"engine.ability.type.ApplyDiscreteEffect",
MemberOperator.SUBTRACT)
patch_forward_ref = ForwardRef(converter_group, nyan_patch_ref)
wrapper_raw_api_object.add_raw_member("patch",
patch_forward_ref,
"engine.util.patch.Patch")
if team:
team_property = dataset.pregen_nyan_objects["util.patch.property.types.Team"].get_nyan_object()
properties = {
dataset.nyan_api_objects["engine.util.patch.property.type.Diplomatic"]: team_property
}
wrapper_raw_api_object.add_raw_member("properties",
properties,
"engine.util.patch.Patch")
converter_group.add_raw_api_object(wrapper_raw_api_object)
converter_group.add_raw_api_object(nyan_patch_raw_api_object)
wrapper_forward_ref = ForwardRef(converter_group, wrapper_ref)
patches.append(wrapper_forward_ref)
return patches | [
"def",
"monk_conversion_upgrade",
"(",
"converter_group",
",",
"value",
",",
"operator",
",",
"team",
"=",
"False",
")",
":",
"force_ids",
"=",
"[",
"115",
",",
"180",
"]",
"dataset",
"=",
"converter_group",
".",
"data",
"patches",
"=",
"[",
"]",
"for",
"force_id",
"in",
"force_ids",
":",
"line",
"=",
"dataset",
".",
"unit_lines",
"[",
"force_id",
"]",
"name_lookup_dict",
"=",
"internal_name_lookups",
".",
"get_entity_lookups",
"(",
"dataset",
".",
"game_version",
")",
"obj_id",
"=",
"converter_group",
".",
"get_id",
"(",
")",
"if",
"isinstance",
"(",
"converter_group",
",",
"GenieTechEffectBundleGroup",
")",
":",
"tech_lookup_dict",
"=",
"internal_name_lookups",
".",
"get_tech_lookups",
"(",
"dataset",
".",
"game_version",
")",
"obj_name",
"=",
"tech_lookup_dict",
"[",
"obj_id",
"]",
"[",
"0",
"]",
"else",
":",
"civ_lookup_dict",
"=",
"internal_name_lookups",
".",
"get_civ_lookups",
"(",
"dataset",
".",
"game_version",
")",
"obj_name",
"=",
"civ_lookup_dict",
"[",
"obj_id",
"]",
"[",
"0",
"]",
"game_entity_name",
"=",
"name_lookup_dict",
"[",
"force_id",
"]",
"[",
"0",
"]",
"patch_target_ref",
"=",
"f\"{game_entity_name}.Convert\"",
"patch_target_forward_ref",
"=",
"ForwardRef",
"(",
"line",
",",
"patch_target_ref",
")",
"# Wrapper",
"wrapper_name",
"=",
"f\"Enable{game_entity_name}ConversionWrapper\"",
"wrapper_ref",
"=",
"f\"{obj_name}.{wrapper_name}\"",
"wrapper_location",
"=",
"ForwardRef",
"(",
"converter_group",
",",
"obj_name",
")",
"wrapper_raw_api_object",
"=",
"RawAPIObject",
"(",
"wrapper_ref",
",",
"wrapper_name",
",",
"dataset",
".",
"nyan_api_objects",
",",
"wrapper_location",
")",
"wrapper_raw_api_object",
".",
"add_raw_parent",
"(",
"\"engine.util.patch.Patch\"",
")",
"# Nyan patch",
"nyan_patch_name",
"=",
"f\"Enable{game_entity_name}Conversion\"",
"nyan_patch_ref",
"=",
"f\"{obj_name}.{wrapper_name}.{nyan_patch_name}\"",
"nyan_patch_location",
"=",
"ForwardRef",
"(",
"converter_group",
",",
"wrapper_ref",
")",
"nyan_patch_raw_api_object",
"=",
"RawAPIObject",
"(",
"nyan_patch_ref",
",",
"nyan_patch_name",
",",
"dataset",
".",
"nyan_api_objects",
",",
"nyan_patch_location",
")",
"nyan_patch_raw_api_object",
".",
"add_raw_parent",
"(",
"\"engine.util.patch.NyanPatch\"",
")",
"nyan_patch_raw_api_object",
".",
"set_patch_target",
"(",
"patch_target_forward_ref",
")",
"monk_forward_ref",
"=",
"ForwardRef",
"(",
"line",
",",
"game_entity_name",
")",
"nyan_patch_raw_api_object",
".",
"add_raw_patch_member",
"(",
"\"blacklisted_entities\"",
",",
"[",
"monk_forward_ref",
"]",
",",
"\"engine.ability.type.ApplyDiscreteEffect\"",
",",
"MemberOperator",
".",
"SUBTRACT",
")",
"patch_forward_ref",
"=",
"ForwardRef",
"(",
"converter_group",
",",
"nyan_patch_ref",
")",
"wrapper_raw_api_object",
".",
"add_raw_member",
"(",
"\"patch\"",
",",
"patch_forward_ref",
",",
"\"engine.util.patch.Patch\"",
")",
"if",
"team",
":",
"team_property",
"=",
"dataset",
".",
"pregen_nyan_objects",
"[",
"\"util.patch.property.types.Team\"",
"]",
".",
"get_nyan_object",
"(",
")",
"properties",
"=",
"{",
"dataset",
".",
"nyan_api_objects",
"[",
"\"engine.util.patch.property.type.Diplomatic\"",
"]",
":",
"team_property",
"}",
"wrapper_raw_api_object",
".",
"add_raw_member",
"(",
"\"properties\"",
",",
"properties",
",",
"\"engine.util.patch.Patch\"",
")",
"converter_group",
".",
"add_raw_api_object",
"(",
"wrapper_raw_api_object",
")",
"converter_group",
".",
"add_raw_api_object",
"(",
"nyan_patch_raw_api_object",
")",
"wrapper_forward_ref",
"=",
"ForwardRef",
"(",
"converter_group",
",",
"wrapper_ref",
")",
"patches",
".",
"append",
"(",
"wrapper_forward_ref",
")",
"return",
"patches"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/swgbcc/upgrade_resource_subprocessor.py#L480-L564 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_shape2dview.py | python | Shape2DView.GetResources | (self) | return {'Pixmap': 'Draft_2DShapeView',
'MenuText': QT_TRANSLATE_NOOP("Draft_Shape2DView", "Shape 2D view"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Shape2DView", "Creates a 2D projection of the selected objects on the XY plane.\nThe initial projection direction is the negative of the current active view direction.\nYou can select individual faces to project, or the entire solid, and also include hidden lines.\nThese projections can be used to create technical drawings with the TechDraw Workbench.")} | Set icon, menu and tooltip. | Set icon, menu and tooltip. | [
"Set",
"icon",
"menu",
"and",
"tooltip",
"."
] | def GetResources(self):
"""Set icon, menu and tooltip."""
return {'Pixmap': 'Draft_2DShapeView',
'MenuText': QT_TRANSLATE_NOOP("Draft_Shape2DView", "Shape 2D view"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_Shape2DView", "Creates a 2D projection of the selected objects on the XY plane.\nThe initial projection direction is the negative of the current active view direction.\nYou can select individual faces to project, or the entire solid, and also include hidden lines.\nThese projections can be used to create technical drawings with the TechDraw Workbench.")} | [
"def",
"GetResources",
"(",
"self",
")",
":",
"return",
"{",
"'Pixmap'",
":",
"'Draft_2DShapeView'",
",",
"'MenuText'",
":",
"QT_TRANSLATE_NOOP",
"(",
"\"Draft_Shape2DView\"",
",",
"\"Shape 2D view\"",
")",
",",
"'ToolTip'",
":",
"QT_TRANSLATE_NOOP",
"(",
"\"Draft_Shape2DView\"",
",",
"\"Creates a 2D projection of the selected objects on the XY plane.\\nThe initial projection direction is the negative of the current active view direction.\\nYou can select individual faces to project, or the entire solid, and also include hidden lines.\\nThese projections can be used to create technical drawings with the TechDraw Workbench.\"",
")",
"}"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_shape2dview.py#L55-L60 | |
avast/retdec | b9879088a5f0278508185ec645494e6c5c57a455 | scripts/type_extractor/type_extractor/json_types.py | python | convert_func_types_to_type_for_json | (functions, types) | Converts parameters and return type of function declaration to json representation. | Converts parameters and return type of function declaration to json representation. | [
"Converts",
"parameters",
"and",
"return",
"type",
"of",
"function",
"declaration",
"to",
"json",
"representation",
"."
] | def convert_func_types_to_type_for_json(functions, types):
"""Converts parameters and return type of function declaration to json representation."""
for name, f_info in functions.items():
t = parse_type_to_type_for_json(f_info.ret_type_text, types)
if t.type_hash not in types:
types[t.type_hash] = t
f_info.ret_type = t.type_hash
parse_params_to_json_types(f_info.params_list, types) | [
"def",
"convert_func_types_to_type_for_json",
"(",
"functions",
",",
"types",
")",
":",
"for",
"name",
",",
"f_info",
"in",
"functions",
".",
"items",
"(",
")",
":",
"t",
"=",
"parse_type_to_type_for_json",
"(",
"f_info",
".",
"ret_type_text",
",",
"types",
")",
"if",
"t",
".",
"type_hash",
"not",
"in",
"types",
":",
"types",
"[",
"t",
".",
"type_hash",
"]",
"=",
"t",
"f_info",
".",
"ret_type",
"=",
"t",
".",
"type_hash",
"parse_params_to_json_types",
"(",
"f_info",
".",
"params_list",
",",
"types",
")"
] | https://github.com/avast/retdec/blob/b9879088a5f0278508185ec645494e6c5c57a455/scripts/type_extractor/type_extractor/json_types.py#L316-L323 | ||
google/fhir | d77f57706c1a168529b0b87ca7ccb1c0113e83c2 | py/google/fhir/r4/json_format.py | python | json_fhir_string_to_proto | (
raw_json: str,
proto_cls: Type[_T],
*,
validate: bool = True,
default_timezone: str = _primitive_time_utils.SIMPLE_ZULU) | return resource | Creates a resource of proto_cls and merges contents of raw_json into it.
Args:
raw_json: The raw FHIR JSON string to convert.
proto_cls: A subclass of message.Message to instantiate and return.
validate: A Boolean value indicating if validation should be performed on
the resultant Message. Validation takes the form of ensuring that basic
checks such as cardinality guarantees, required field adherence, etc. are
met. Defaults to True.
default_timezone: A string specifying the timezone string to use for time-
like FHIR data during parsing. Defaults to 'Z'.
Raises:
fhir_errors.InvalidFhirError: In the event that raw_json was not valid FHIR.
Returns:
An instance of proto_cls with FHIR JSON data from the raw_json
representation. | Creates a resource of proto_cls and merges contents of raw_json into it. | [
"Creates",
"a",
"resource",
"of",
"proto_cls",
"and",
"merges",
"contents",
"of",
"raw_json",
"into",
"it",
"."
] | def json_fhir_string_to_proto(
raw_json: str,
proto_cls: Type[_T],
*,
validate: bool = True,
default_timezone: str = _primitive_time_utils.SIMPLE_ZULU) -> _T:
"""Creates a resource of proto_cls and merges contents of raw_json into it.
Args:
raw_json: The raw FHIR JSON string to convert.
proto_cls: A subclass of message.Message to instantiate and return.
validate: A Boolean value indicating if validation should be performed on
the resultant Message. Validation takes the form of ensuring that basic
checks such as cardinality guarantees, required field adherence, etc. are
met. Defaults to True.
default_timezone: A string specifying the timezone string to use for time-
like FHIR data during parsing. Defaults to 'Z'.
Raises:
fhir_errors.InvalidFhirError: In the event that raw_json was not valid FHIR.
Returns:
An instance of proto_cls with FHIR JSON data from the raw_json
representation.
"""
resource = proto_cls()
merge_json_fhir_string_into_proto(
raw_json, resource, validate=validate, default_timezone=default_timezone)
return resource | [
"def",
"json_fhir_string_to_proto",
"(",
"raw_json",
":",
"str",
",",
"proto_cls",
":",
"Type",
"[",
"_T",
"]",
",",
"*",
",",
"validate",
":",
"bool",
"=",
"True",
",",
"default_timezone",
":",
"str",
"=",
"_primitive_time_utils",
".",
"SIMPLE_ZULU",
")",
"->",
"_T",
":",
"resource",
"=",
"proto_cls",
"(",
")",
"merge_json_fhir_string_into_proto",
"(",
"raw_json",
",",
"resource",
",",
"validate",
"=",
"validate",
",",
"default_timezone",
"=",
"default_timezone",
")",
"return",
"resource"
] | https://github.com/google/fhir/blob/d77f57706c1a168529b0b87ca7ccb1c0113e83c2/py/google/fhir/r4/json_format.py#L64-L92 | |
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/skype_api.py | python | SkypeAPI.poll_events | (self, wait = 0) | Polls for events from Skype | Polls for events from Skype | [
"Polls",
"for",
"events",
"from",
"Skype"
] | def poll_events(self, wait = 0):
"""Polls for events from Skype"""
# TODO disconnection handling
self.run_queue()
self.run_poll_for_events(wait)
self.run_queue() | [
"def",
"poll_events",
"(",
"self",
",",
"wait",
"=",
"0",
")",
":",
"# TODO disconnection handling",
"self",
".",
"run_queue",
"(",
")",
"self",
".",
"run_poll_for_events",
"(",
"wait",
")",
"self",
".",
"run_queue",
"(",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/skype_api.py#L165-L170 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Rect2D.MoveTopTo | (*args, **kwargs) | return _core_.Rect2D_MoveTopTo(*args, **kwargs) | MoveTopTo(self, Double n) | MoveTopTo(self, Double n) | [
"MoveTopTo",
"(",
"self",
"Double",
"n",
")"
] | def MoveTopTo(*args, **kwargs):
"""MoveTopTo(self, Double n)"""
return _core_.Rect2D_MoveTopTo(*args, **kwargs) | [
"def",
"MoveTopTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect2D_MoveTopTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L1875-L1877 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/telnetlib.py | python | Telnet.listener | (self) | Helper for mt_interact() -- this executes in the other thread. | Helper for mt_interact() -- this executes in the other thread. | [
"Helper",
"for",
"mt_interact",
"()",
"--",
"this",
"executes",
"in",
"the",
"other",
"thread",
"."
] | def listener(self):
"""Helper for mt_interact() -- this executes in the other thread."""
while 1:
try:
data = self.read_eager()
except EOFError:
print '*** Connection closed by remote host ***'
return
if data:
sys.stdout.write(data)
else:
sys.stdout.flush() | [
"def",
"listener",
"(",
"self",
")",
":",
"while",
"1",
":",
"try",
":",
"data",
"=",
"self",
".",
"read_eager",
"(",
")",
"except",
"EOFError",
":",
"print",
"'*** Connection closed by remote host ***'",
"return",
"if",
"data",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"data",
")",
"else",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/telnetlib.py#L614-L625 | ||
physercoe/starquant | c00cad64d1de2da05081b3dc320ef264c6295e08 | source/gui/ui_basic.py | python | BaseMonitor.init_table | (self) | Initialize table. | Initialize table. | [
"Initialize",
"table",
"."
] | def init_table(self):
"""
Initialize table.
"""
self.setColumnCount(len(self.headers))
labels = [d["display"] for d in self.headers.values()]
self.setHorizontalHeaderLabels(labels)
self.verticalHeader().setVisible(False)
self.setEditTriggers(self.NoEditTriggers)
self.setAlternatingRowColors(True)
self.setSortingEnabled(self.sorting) | [
"def",
"init_table",
"(",
"self",
")",
":",
"self",
".",
"setColumnCount",
"(",
"len",
"(",
"self",
".",
"headers",
")",
")",
"labels",
"=",
"[",
"d",
"[",
"\"display\"",
"]",
"for",
"d",
"in",
"self",
".",
"headers",
".",
"values",
"(",
")",
"]",
"self",
".",
"setHorizontalHeaderLabels",
"(",
"labels",
")",
"self",
".",
"verticalHeader",
"(",
")",
".",
"setVisible",
"(",
"False",
")",
"self",
".",
"setEditTriggers",
"(",
"self",
".",
"NoEditTriggers",
")",
"self",
".",
"setAlternatingRowColors",
"(",
"True",
")",
"self",
".",
"setSortingEnabled",
"(",
"self",
".",
"sorting",
")"
] | https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/source/gui/ui_basic.py#L256-L268 | ||
nest/nest-simulator | f2623eb78518cdbd55e77e0ed486bf1111bcb62f | pynest/examples/urbanczik_synapse_example.py | python | h | (U, nrn_params) | return 15.0 * beta / (1.0 + np.exp(-beta * (theta - U)) / k) | derivative of the rate function phi | derivative of the rate function phi | [
"derivative",
"of",
"the",
"rate",
"function",
"phi"
] | def h(U, nrn_params):
"""
derivative of the rate function phi
"""
k = nrn_params['rate_slope']
beta = nrn_params['beta']
theta = nrn_params['theta']
return 15.0 * beta / (1.0 + np.exp(-beta * (theta - U)) / k) | [
"def",
"h",
"(",
"U",
",",
"nrn_params",
")",
":",
"k",
"=",
"nrn_params",
"[",
"'rate_slope'",
"]",
"beta",
"=",
"nrn_params",
"[",
"'beta'",
"]",
"theta",
"=",
"nrn_params",
"[",
"'theta'",
"]",
"return",
"15.0",
"*",
"beta",
"/",
"(",
"1.0",
"+",
"np",
".",
"exp",
"(",
"-",
"beta",
"*",
"(",
"theta",
"-",
"U",
")",
")",
"/",
"k",
")"
] | https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/examples/urbanczik_synapse_example.py#L95-L102 | |
google/or-tools | 2cb85b4eead4c38e1c54b48044f92087cf165bce | ortools/sat/python/cp_model.py | python | CpSolver.SufficientAssumptionsForInfeasibility | (self) | return self.__solution.sufficient_assumptions_for_infeasibility | Returns the indices of the infeasible assumptions. | Returns the indices of the infeasible assumptions. | [
"Returns",
"the",
"indices",
"of",
"the",
"infeasible",
"assumptions",
"."
] | def SufficientAssumptionsForInfeasibility(self):
"""Returns the indices of the infeasible assumptions."""
return self.__solution.sufficient_assumptions_for_infeasibility | [
"def",
"SufficientAssumptionsForInfeasibility",
"(",
"self",
")",
":",
"return",
"self",
".",
"__solution",
".",
"sufficient_assumptions_for_infeasibility"
] | https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model.py#L2209-L2211 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py | python | _read_platforms_for_host | () | return validated_platforms_for_host, alias_to_platforms_map | Private initializer function to initialize the map of platform names to their PlatformDetails instance and a map of aliases to their platform names
:return: Tuple of : [0] Map of platform names to their PlatformDetails object
[1] Map of aliases to a list of platform names that belong in that alias | Private initializer function to initialize the map of platform names to their PlatformDetails instance and a map of aliases to their platform names
:return: Tuple of : [0] Map of platform names to their PlatformDetails object
[1] Map of aliases to a list of platform names that belong in that alias | [
"Private",
"initializer",
"function",
"to",
"initialize",
"the",
"map",
"of",
"platform",
"names",
"to",
"their",
"PlatformDetails",
"instance",
"and",
"a",
"map",
"of",
"aliases",
"to",
"their",
"platform",
"names",
":",
"return",
":",
"Tuple",
"of",
":",
"[",
"0",
"]",
"Map",
"of",
"platform",
"names",
"to",
"their",
"PlatformDetails",
"object",
"[",
"1",
"]",
"Map",
"of",
"aliases",
"to",
"a",
"list",
"of",
"platform",
"names",
"that",
"belong",
"in",
"that",
"alias"
] | def _read_platforms_for_host():
"""
Private initializer function to initialize the map of platform names to their PlatformDetails instance and a map of aliases to their platform names
:return: Tuple of : [0] Map of platform names to their PlatformDetails object
[1] Map of aliases to a list of platform names that belong in that alias
"""
validated_platforms_for_host = {}
alias_to_platforms_map = {}
for platform_setting in settings_manager.LUMBERYARD_SETTINGS.get_all_platform_settings():
# Apply the default aliases if any
for alias in platform_setting.aliases:
alias_to_platforms_map.setdefault(alias, set()).add(platform_setting.platform)
# Extract the base output folder for the platform
output_folder_key = 'out_folder_{}'.format(platform_setting.platform)
try:
output_folder = settings_manager.LUMBERYARD_SETTINGS.get_settings_value(output_folder_key)
except Errors.WafError:
raise Errors.WafError("Missing required 'out_folder' in the settings for platform settings {}".format(platform_setting.platform))
# Determine if the platform is monolithic-only
is_monolithic = platform_setting.is_monolithic
# Check if there are any platform-specific monolithic override flag
platform_check_list = [platform_setting.platform] + list(platform_setting.aliases)
# Special case: for darwin, the original override key was 'mac_monolithic_build', so also check for that
if platform_setting.platform == 'darwin_x64':
platform_check_list.append('mac')
for alias in platform_check_list:
monolithic_key = '{}_build_monolithic'.format(alias)
if not monolithic_key in settings_manager.LUMBERYARD_SETTINGS.settings_map:
continue
if is_value_true(settings_manager.LUMBERYARD_SETTINGS.settings_map[monolithic_key]):
is_monolithic = True
break
# Determine if the platform is enabled and available
is_enabled = platform_setting.enabled
# Create the base platform detail object from the platform settings
base_platform = PlatformDetail(platform=platform_setting.platform,
enabled=is_enabled,
has_server=platform_setting.has_server,
has_tests=platform_setting.has_test,
is_monolithic_value=is_monolithic,
output_folder=output_folder,
aliases=platform_setting.aliases,
attributes=platform_setting.attributes,
needs_java=platform_setting.needs_java,
platform_env_dict=platform_setting.env_dict)
validated_platforms_for_host[base_platform.name()] = base_platform
for platform_key in list(validated_platforms_for_host.keys()):
Logs.debug('settings: Initialized Target Platform: {}'.format(platform_key))
for alias_name, alias_values in list(alias_to_platforms_map.items()):
Logs.debug('settings: Platform Alias {}: {}'.format(alias_name, ','.join(alias_values)))
return validated_platforms_for_host, alias_to_platforms_map | [
"def",
"_read_platforms_for_host",
"(",
")",
":",
"validated_platforms_for_host",
"=",
"{",
"}",
"alias_to_platforms_map",
"=",
"{",
"}",
"for",
"platform_setting",
"in",
"settings_manager",
".",
"LUMBERYARD_SETTINGS",
".",
"get_all_platform_settings",
"(",
")",
":",
"# Apply the default aliases if any",
"for",
"alias",
"in",
"platform_setting",
".",
"aliases",
":",
"alias_to_platforms_map",
".",
"setdefault",
"(",
"alias",
",",
"set",
"(",
")",
")",
".",
"add",
"(",
"platform_setting",
".",
"platform",
")",
"# Extract the base output folder for the platform",
"output_folder_key",
"=",
"'out_folder_{}'",
".",
"format",
"(",
"platform_setting",
".",
"platform",
")",
"try",
":",
"output_folder",
"=",
"settings_manager",
".",
"LUMBERYARD_SETTINGS",
".",
"get_settings_value",
"(",
"output_folder_key",
")",
"except",
"Errors",
".",
"WafError",
":",
"raise",
"Errors",
".",
"WafError",
"(",
"\"Missing required 'out_folder' in the settings for platform settings {}\"",
".",
"format",
"(",
"platform_setting",
".",
"platform",
")",
")",
"# Determine if the platform is monolithic-only",
"is_monolithic",
"=",
"platform_setting",
".",
"is_monolithic",
"# Check if there are any platform-specific monolithic override flag",
"platform_check_list",
"=",
"[",
"platform_setting",
".",
"platform",
"]",
"+",
"list",
"(",
"platform_setting",
".",
"aliases",
")",
"# Special case: for darwin, the original override key was 'mac_monolithic_build', so also check for that",
"if",
"platform_setting",
".",
"platform",
"==",
"'darwin_x64'",
":",
"platform_check_list",
".",
"append",
"(",
"'mac'",
")",
"for",
"alias",
"in",
"platform_check_list",
":",
"monolithic_key",
"=",
"'{}_build_monolithic'",
".",
"format",
"(",
"alias",
")",
"if",
"not",
"monolithic_key",
"in",
"settings_manager",
".",
"LUMBERYARD_SETTINGS",
".",
"settings_map",
":",
"continue",
"if",
"is_value_true",
"(",
"settings_manager",
".",
"LUMBERYARD_SETTINGS",
".",
"settings_map",
"[",
"monolithic_key",
"]",
")",
":",
"is_monolithic",
"=",
"True",
"break",
"# Determine if the platform is enabled and available",
"is_enabled",
"=",
"platform_setting",
".",
"enabled",
"# Create the base platform detail object from the platform settings",
"base_platform",
"=",
"PlatformDetail",
"(",
"platform",
"=",
"platform_setting",
".",
"platform",
",",
"enabled",
"=",
"is_enabled",
",",
"has_server",
"=",
"platform_setting",
".",
"has_server",
",",
"has_tests",
"=",
"platform_setting",
".",
"has_test",
",",
"is_monolithic_value",
"=",
"is_monolithic",
",",
"output_folder",
"=",
"output_folder",
",",
"aliases",
"=",
"platform_setting",
".",
"aliases",
",",
"attributes",
"=",
"platform_setting",
".",
"attributes",
",",
"needs_java",
"=",
"platform_setting",
".",
"needs_java",
",",
"platform_env_dict",
"=",
"platform_setting",
".",
"env_dict",
")",
"validated_platforms_for_host",
"[",
"base_platform",
".",
"name",
"(",
")",
"]",
"=",
"base_platform",
"for",
"platform_key",
"in",
"list",
"(",
"validated_platforms_for_host",
".",
"keys",
"(",
")",
")",
":",
"Logs",
".",
"debug",
"(",
"'settings: Initialized Target Platform: {}'",
".",
"format",
"(",
"platform_key",
")",
")",
"for",
"alias_name",
",",
"alias_values",
"in",
"list",
"(",
"alias_to_platforms_map",
".",
"items",
"(",
")",
")",
":",
"Logs",
".",
"debug",
"(",
"'settings: Platform Alias {}: {}'",
".",
"format",
"(",
"alias_name",
",",
"','",
".",
"join",
"(",
"alias_values",
")",
")",
")",
"return",
"validated_platforms_for_host",
",",
"alias_to_platforms_map"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/build_configurations.py#L462-L523 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/datasets/base.py | python | load_csv_with_header | (filename,
target_dtype,
features_dtype,
target_column=-1) | return Dataset(data=data, target=target) | Load dataset from CSV file with a header row. | Load dataset from CSV file with a header row. | [
"Load",
"dataset",
"from",
"CSV",
"file",
"with",
"a",
"header",
"row",
"."
] | def load_csv_with_header(filename,
target_dtype,
features_dtype,
target_column=-1):
"""Load dataset from CSV file with a header row."""
with gfile.Open(filename) as csv_file:
data_file = csv.reader(csv_file)
header = next(data_file)
n_samples = int(header[0])
n_features = int(header[1])
data = np.zeros((n_samples, n_features), dtype=features_dtype)
target = np.zeros((n_samples,), dtype=target_dtype)
for i, row in enumerate(data_file):
target[i] = np.asarray(row.pop(target_column), dtype=target_dtype)
data[i] = np.asarray(row, dtype=features_dtype)
return Dataset(data=data, target=target) | [
"def",
"load_csv_with_header",
"(",
"filename",
",",
"target_dtype",
",",
"features_dtype",
",",
"target_column",
"=",
"-",
"1",
")",
":",
"with",
"gfile",
".",
"Open",
"(",
"filename",
")",
"as",
"csv_file",
":",
"data_file",
"=",
"csv",
".",
"reader",
"(",
"csv_file",
")",
"header",
"=",
"next",
"(",
"data_file",
")",
"n_samples",
"=",
"int",
"(",
"header",
"[",
"0",
"]",
")",
"n_features",
"=",
"int",
"(",
"header",
"[",
"1",
"]",
")",
"data",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_samples",
",",
"n_features",
")",
",",
"dtype",
"=",
"features_dtype",
")",
"target",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_samples",
",",
")",
",",
"dtype",
"=",
"target_dtype",
")",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"data_file",
")",
":",
"target",
"[",
"i",
"]",
"=",
"np",
".",
"asarray",
"(",
"row",
".",
"pop",
"(",
"target_column",
")",
",",
"dtype",
"=",
"target_dtype",
")",
"data",
"[",
"i",
"]",
"=",
"np",
".",
"asarray",
"(",
"row",
",",
"dtype",
"=",
"features_dtype",
")",
"return",
"Dataset",
"(",
"data",
"=",
"data",
",",
"target",
"=",
"target",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/datasets/base.py#L40-L56 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | SimpleHtmlListBox._Clear | (*args, **kwargs) | return _windows_.SimpleHtmlListBox__Clear(*args, **kwargs) | _Clear(self) | _Clear(self) | [
"_Clear",
"(",
"self",
")"
] | def _Clear(*args, **kwargs):
"""_Clear(self)"""
return _windows_.SimpleHtmlListBox__Clear(*args, **kwargs) | [
"def",
"_Clear",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"SimpleHtmlListBox__Clear",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L2788-L2790 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl_compatibility_errors.py | python | IDLCompatibilityContext.add_new_param_or_command_type_field_missing_error | (self, command_name: str, field_name: str,
file: str, type_name: str,
is_command_parameter: bool) | Add an error about a parameter or command type field that is missing in the new command. | Add an error about a parameter or command type field that is missing in the new command. | [
"Add",
"an",
"error",
"about",
"a",
"parameter",
"or",
"command",
"type",
"field",
"that",
"is",
"missing",
"in",
"the",
"new",
"command",
"."
] | def add_new_param_or_command_type_field_missing_error(self, command_name: str, field_name: str,
file: str, type_name: str,
is_command_parameter: bool) -> None:
# pylint: disable=too-many-arguments
"""Add an error about a parameter or command type field that is missing in the new command."""
if is_command_parameter:
self._add_error(
ERROR_ID_REMOVED_COMMAND_PARAMETER, command_name,
"Field or sub-field '%s' for old command '%s' was removed from the corresponding new"
"struct." % (field_name, command_name), file)
else:
self._add_error(
ERROR_ID_NEW_COMMAND_TYPE_FIELD_MISSING, command_name,
"The command '%s' or its sub-struct has type '%s' that is missing a "
"field '%s' that exists in the old struct type." % (command_name, type_name,
field_name), file) | [
"def",
"add_new_param_or_command_type_field_missing_error",
"(",
"self",
",",
"command_name",
":",
"str",
",",
"field_name",
":",
"str",
",",
"file",
":",
"str",
",",
"type_name",
":",
"str",
",",
"is_command_parameter",
":",
"bool",
")",
"->",
"None",
":",
"# pylint: disable=too-many-arguments",
"if",
"is_command_parameter",
":",
"self",
".",
"_add_error",
"(",
"ERROR_ID_REMOVED_COMMAND_PARAMETER",
",",
"command_name",
",",
"\"Field or sub-field '%s' for old command '%s' was removed from the corresponding new\"",
"\"struct.\"",
"%",
"(",
"field_name",
",",
"command_name",
")",
",",
"file",
")",
"else",
":",
"self",
".",
"_add_error",
"(",
"ERROR_ID_NEW_COMMAND_TYPE_FIELD_MISSING",
",",
"command_name",
",",
"\"The command '%s' or its sub-struct has type '%s' that is missing a \"",
"\"field '%s' that exists in the old struct type.\"",
"%",
"(",
"command_name",
",",
"type_name",
",",
"field_name",
")",
",",
"file",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl_compatibility_errors.py#L443-L458 | ||
indutny/candor | 48e7260618f5091c80a3416828e2808cad3ea22e | tools/gyp/pylib/gyp/generator/msvs.py | python | _AddActionStep | (actions_dict, inputs, outputs, description, command) | Merge action into an existing list of actions.
Care must be taken so that actions which have overlapping inputs either don't
get assigned to the same input, or get collapsed into one.
Arguments:
actions_dict: dictionary keyed on input name, which maps to a list of
dicts describing the actions attached to that input file.
inputs: list of inputs
outputs: list of outputs
description: description of the action
command: command line to execute | Merge action into an existing list of actions. | [
"Merge",
"action",
"into",
"an",
"existing",
"list",
"of",
"actions",
"."
] | def _AddActionStep(actions_dict, inputs, outputs, description, command):
"""Merge action into an existing list of actions.
Care must be taken so that actions which have overlapping inputs either don't
get assigned to the same input, or get collapsed into one.
Arguments:
actions_dict: dictionary keyed on input name, which maps to a list of
dicts describing the actions attached to that input file.
inputs: list of inputs
outputs: list of outputs
description: description of the action
command: command line to execute
"""
# Require there to be at least one input (call sites will ensure this).
assert inputs
action = {
'inputs': inputs,
'outputs': outputs,
'description': description,
'command': command,
}
# Pick where to stick this action.
# While less than optimal in terms of build time, attach them to the first
# input for now.
chosen_input = inputs[0]
# Add it there.
if chosen_input not in actions_dict:
actions_dict[chosen_input] = []
actions_dict[chosen_input].append(action) | [
"def",
"_AddActionStep",
"(",
"actions_dict",
",",
"inputs",
",",
"outputs",
",",
"description",
",",
"command",
")",
":",
"# Require there to be at least one input (call sites will ensure this).",
"assert",
"inputs",
"action",
"=",
"{",
"'inputs'",
":",
"inputs",
",",
"'outputs'",
":",
"outputs",
",",
"'description'",
":",
"description",
",",
"'command'",
":",
"command",
",",
"}",
"# Pick where to stick this action.",
"# While less than optimal in terms of build time, attach them to the first",
"# input for now.",
"chosen_input",
"=",
"inputs",
"[",
"0",
"]",
"# Add it there.",
"if",
"chosen_input",
"not",
"in",
"actions_dict",
":",
"actions_dict",
"[",
"chosen_input",
"]",
"=",
"[",
"]",
"actions_dict",
"[",
"chosen_input",
"]",
".",
"append",
"(",
"action",
")"
] | https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/generator/msvs.py#L334-L366 | ||
eric1688/sphinx | 514317761b35c07eb9f36db55a1ff365c4a9f0bc | api/sphinxapi.py | python | SphinxClient._GetResponse | (self, sock, client_ver) | return response | INTERNAL METHOD, DO NOT CALL. Gets and checks response packet from searchd server. | INTERNAL METHOD, DO NOT CALL. Gets and checks response packet from searchd server. | [
"INTERNAL",
"METHOD",
"DO",
"NOT",
"CALL",
".",
"Gets",
"and",
"checks",
"response",
"packet",
"from",
"searchd",
"server",
"."
] | def _GetResponse (self, sock, client_ver):
"""
INTERNAL METHOD, DO NOT CALL. Gets and checks response packet from searchd server.
"""
(status, ver, length) = unpack('>2HL', sock.recv(8))
response = ''
left = length
while left>0:
chunk = sock.recv(left)
if chunk:
response += chunk
left -= len(chunk)
else:
break
if not self._socket:
sock.close()
# check response
read = len(response)
if not response or read!=length:
if length:
self._error = 'failed to read searchd response (status=%s, ver=%s, len=%s, read=%s)' \
% (status, ver, length, read)
else:
self._error = 'received zero-sized searchd response'
return None
# check status
if status==SEARCHD_WARNING:
wend = 4 + unpack ( '>L', response[0:4] )[0]
self._warning = response[4:wend]
return response[wend:]
if status==SEARCHD_ERROR:
self._error = 'searchd error: '+response[4:]
return None
if status==SEARCHD_RETRY:
self._error = 'temporary searchd error: '+response[4:]
return None
if status!=SEARCHD_OK:
self._error = 'unknown status code %d' % status
return None
# check version
if ver<client_ver:
self._warning = 'searchd command v.%d.%d older than client\'s v.%d.%d, some options might not work' \
% (ver>>8, ver&0xff, client_ver>>8, client_ver&0xff)
return response | [
"def",
"_GetResponse",
"(",
"self",
",",
"sock",
",",
"client_ver",
")",
":",
"(",
"status",
",",
"ver",
",",
"length",
")",
"=",
"unpack",
"(",
"'>2HL'",
",",
"sock",
".",
"recv",
"(",
"8",
")",
")",
"response",
"=",
"''",
"left",
"=",
"length",
"while",
"left",
">",
"0",
":",
"chunk",
"=",
"sock",
".",
"recv",
"(",
"left",
")",
"if",
"chunk",
":",
"response",
"+=",
"chunk",
"left",
"-=",
"len",
"(",
"chunk",
")",
"else",
":",
"break",
"if",
"not",
"self",
".",
"_socket",
":",
"sock",
".",
"close",
"(",
")",
"# check response",
"read",
"=",
"len",
"(",
"response",
")",
"if",
"not",
"response",
"or",
"read",
"!=",
"length",
":",
"if",
"length",
":",
"self",
".",
"_error",
"=",
"'failed to read searchd response (status=%s, ver=%s, len=%s, read=%s)'",
"%",
"(",
"status",
",",
"ver",
",",
"length",
",",
"read",
")",
"else",
":",
"self",
".",
"_error",
"=",
"'received zero-sized searchd response'",
"return",
"None",
"# check status",
"if",
"status",
"==",
"SEARCHD_WARNING",
":",
"wend",
"=",
"4",
"+",
"unpack",
"(",
"'>L'",
",",
"response",
"[",
"0",
":",
"4",
"]",
")",
"[",
"0",
"]",
"self",
".",
"_warning",
"=",
"response",
"[",
"4",
":",
"wend",
"]",
"return",
"response",
"[",
"wend",
":",
"]",
"if",
"status",
"==",
"SEARCHD_ERROR",
":",
"self",
".",
"_error",
"=",
"'searchd error: '",
"+",
"response",
"[",
"4",
":",
"]",
"return",
"None",
"if",
"status",
"==",
"SEARCHD_RETRY",
":",
"self",
".",
"_error",
"=",
"'temporary searchd error: '",
"+",
"response",
"[",
"4",
":",
"]",
"return",
"None",
"if",
"status",
"!=",
"SEARCHD_OK",
":",
"self",
".",
"_error",
"=",
"'unknown status code %d'",
"%",
"status",
"return",
"None",
"# check version",
"if",
"ver",
"<",
"client_ver",
":",
"self",
".",
"_warning",
"=",
"'searchd command v.%d.%d older than client\\'s v.%d.%d, some options might not work'",
"%",
"(",
"ver",
">>",
"8",
",",
"ver",
"&",
"0xff",
",",
"client_ver",
">>",
"8",
",",
"client_ver",
"&",
"0xff",
")",
"return",
"response"
] | https://github.com/eric1688/sphinx/blob/514317761b35c07eb9f36db55a1ff365c4a9f0bc/api/sphinxapi.py#L255-L306 | |
CGRU/cgru | 1881a4128530e3d31ac6c25314c18314fc50c2c7 | afanasy/python/af.py | python | Cmd.getJobList | (self, verbose=False, ids=None) | return None | Missing DocString
:param bool verbose:
:return: | Missing DocString | [
"Missing",
"DocString"
] | def getJobList(self, verbose=False, ids=None):
"""Missing DocString
:param bool verbose:
:return:
"""
self.action = 'get'
self.data['type'] = 'jobs'
if ids is not None:
self.data['ids'] = ids
data = self._sendRequest(verbose)
if data is not None:
if 'jobs' in data:
return data['jobs']
return None | [
"def",
"getJobList",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"ids",
"=",
"None",
")",
":",
"self",
".",
"action",
"=",
"'get'",
"self",
".",
"data",
"[",
"'type'",
"]",
"=",
"'jobs'",
"if",
"ids",
"is",
"not",
"None",
":",
"self",
".",
"data",
"[",
"'ids'",
"]",
"=",
"ids",
"data",
"=",
"self",
".",
"_sendRequest",
"(",
"verbose",
")",
"if",
"data",
"is",
"not",
"None",
":",
"if",
"'jobs'",
"in",
"data",
":",
"return",
"data",
"[",
"'jobs'",
"]",
"return",
"None"
] | https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/afanasy/python/af.py#L930-L944 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetExtraPlistItems | (self, configname=None) | return items | Returns a dictionary with extra items to insert into Info.plist. | Returns a dictionary with extra items to insert into Info.plist. | [
"Returns",
"a",
"dictionary",
"with",
"extra",
"items",
"to",
"insert",
"into",
"Info",
".",
"plist",
"."
] | def GetExtraPlistItems(self, configname=None):
"""Returns a dictionary with extra items to insert into Info.plist."""
if configname not in XcodeSettings._plist_cache:
cache = {}
cache['BuildMachineOSBuild'] = self._BuildMachineOSBuild()
xcode, xcode_build = XcodeVersion()
cache['DTXcode'] = xcode
cache['DTXcodeBuild'] = xcode_build
compiler = self.xcode_settings[configname].get('GCC_VERSION')
if compiler is not None:
cache['DTCompiler'] = compiler
sdk_root = self._SdkRoot(configname)
if not sdk_root:
sdk_root = self._DefaultSdkRoot()
sdk_version = self._GetSdkVersionInfoItem(sdk_root, '--show-sdk-version')
cache['DTSDKName'] = sdk_root + (sdk_version or '')
if xcode >= '0720':
cache['DTSDKBuild'] = self._GetSdkVersionInfoItem(
sdk_root, '--show-sdk-build-version')
elif xcode >= '0430':
cache['DTSDKBuild'] = sdk_version
else:
cache['DTSDKBuild'] = cache['BuildMachineOSBuild']
if self.isIOS:
cache['MinimumOSVersion'] = self.xcode_settings[configname].get(
'IPHONEOS_DEPLOYMENT_TARGET')
cache['DTPlatformName'] = sdk_root
cache['DTPlatformVersion'] = sdk_version
if configname.endswith("iphoneos"):
cache['CFBundleSupportedPlatforms'] = ['iPhoneOS']
cache['DTPlatformBuild'] = cache['DTSDKBuild']
else:
cache['CFBundleSupportedPlatforms'] = ['iPhoneSimulator']
# This is weird, but Xcode sets DTPlatformBuild to an empty field
# for simulator builds.
cache['DTPlatformBuild'] = ""
XcodeSettings._plist_cache[configname] = cache
# Include extra plist items that are per-target, not per global
# XcodeSettings.
items = dict(XcodeSettings._plist_cache[configname])
if self.isIOS:
items['UIDeviceFamily'] = self._XcodeIOSDeviceFamily(configname)
return items | [
"def",
"GetExtraPlistItems",
"(",
"self",
",",
"configname",
"=",
"None",
")",
":",
"if",
"configname",
"not",
"in",
"XcodeSettings",
".",
"_plist_cache",
":",
"cache",
"=",
"{",
"}",
"cache",
"[",
"'BuildMachineOSBuild'",
"]",
"=",
"self",
".",
"_BuildMachineOSBuild",
"(",
")",
"xcode",
",",
"xcode_build",
"=",
"XcodeVersion",
"(",
")",
"cache",
"[",
"'DTXcode'",
"]",
"=",
"xcode",
"cache",
"[",
"'DTXcodeBuild'",
"]",
"=",
"xcode_build",
"compiler",
"=",
"self",
".",
"xcode_settings",
"[",
"configname",
"]",
".",
"get",
"(",
"'GCC_VERSION'",
")",
"if",
"compiler",
"is",
"not",
"None",
":",
"cache",
"[",
"'DTCompiler'",
"]",
"=",
"compiler",
"sdk_root",
"=",
"self",
".",
"_SdkRoot",
"(",
"configname",
")",
"if",
"not",
"sdk_root",
":",
"sdk_root",
"=",
"self",
".",
"_DefaultSdkRoot",
"(",
")",
"sdk_version",
"=",
"self",
".",
"_GetSdkVersionInfoItem",
"(",
"sdk_root",
",",
"'--show-sdk-version'",
")",
"cache",
"[",
"'DTSDKName'",
"]",
"=",
"sdk_root",
"+",
"(",
"sdk_version",
"or",
"''",
")",
"if",
"xcode",
">=",
"'0720'",
":",
"cache",
"[",
"'DTSDKBuild'",
"]",
"=",
"self",
".",
"_GetSdkVersionInfoItem",
"(",
"sdk_root",
",",
"'--show-sdk-build-version'",
")",
"elif",
"xcode",
">=",
"'0430'",
":",
"cache",
"[",
"'DTSDKBuild'",
"]",
"=",
"sdk_version",
"else",
":",
"cache",
"[",
"'DTSDKBuild'",
"]",
"=",
"cache",
"[",
"'BuildMachineOSBuild'",
"]",
"if",
"self",
".",
"isIOS",
":",
"cache",
"[",
"'MinimumOSVersion'",
"]",
"=",
"self",
".",
"xcode_settings",
"[",
"configname",
"]",
".",
"get",
"(",
"'IPHONEOS_DEPLOYMENT_TARGET'",
")",
"cache",
"[",
"'DTPlatformName'",
"]",
"=",
"sdk_root",
"cache",
"[",
"'DTPlatformVersion'",
"]",
"=",
"sdk_version",
"if",
"configname",
".",
"endswith",
"(",
"\"iphoneos\"",
")",
":",
"cache",
"[",
"'CFBundleSupportedPlatforms'",
"]",
"=",
"[",
"'iPhoneOS'",
"]",
"cache",
"[",
"'DTPlatformBuild'",
"]",
"=",
"cache",
"[",
"'DTSDKBuild'",
"]",
"else",
":",
"cache",
"[",
"'CFBundleSupportedPlatforms'",
"]",
"=",
"[",
"'iPhoneSimulator'",
"]",
"# This is weird, but Xcode sets DTPlatformBuild to an empty field",
"# for simulator builds.",
"cache",
"[",
"'DTPlatformBuild'",
"]",
"=",
"\"\"",
"XcodeSettings",
".",
"_plist_cache",
"[",
"configname",
"]",
"=",
"cache",
"# Include extra plist items that are per-target, not per global",
"# XcodeSettings.",
"items",
"=",
"dict",
"(",
"XcodeSettings",
".",
"_plist_cache",
"[",
"configname",
"]",
")",
"if",
"self",
".",
"isIOS",
":",
"items",
"[",
"'UIDeviceFamily'",
"]",
"=",
"self",
".",
"_XcodeIOSDeviceFamily",
"(",
"configname",
")",
"return",
"items"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/xcode_emulation.py#L1090-L1137 | |
tcpexmachina/remy | 687b5db29b81df7ae8737889c78b47e7f9788297 | scripts/plot_log.py | python | BaseSingleAnimationGenerator.get_plot_data | (self, run_data) | Must be impelemented by subclasses. Returns a tuple of two elements
(x, y) each being a list of data points. The two lists must have the
same length. | Must be impelemented by subclasses. Returns a tuple of two elements
(x, y) each being a list of data points. The two lists must have the
same length. | [
"Must",
"be",
"impelemented",
"by",
"subclasses",
".",
"Returns",
"a",
"tuple",
"of",
"two",
"elements",
"(",
"x",
"y",
")",
"each",
"being",
"a",
"list",
"of",
"data",
"points",
".",
"The",
"two",
"lists",
"must",
"have",
"the",
"same",
"length",
"."
] | def get_plot_data(self, run_data):
"""Must be impelemented by subclasses. Returns a tuple of two elements
(x, y) each being a list of data points. The two lists must have the
same length."""
raise NotImplementedError("Subclasses must implement get_plot_data()") | [
"def",
"get_plot_data",
"(",
"self",
",",
"run_data",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Subclasses must implement get_plot_data()\"",
")"
] | https://github.com/tcpexmachina/remy/blob/687b5db29b81df7ae8737889c78b47e7f9788297/scripts/plot_log.py#L197-L201 | ||
google/ion | ef47f3b824050499ce5c6f774b366f6c4dbce0af | ion/build.py | python | _PrintTestHeader | (test_target_name) | Print a unified test header to identify the start of a test.
Args:
test_target_name: The name of the test. | Print a unified test header to identify the start of a test. | [
"Print",
"a",
"unified",
"test",
"header",
"to",
"identify",
"the",
"start",
"of",
"a",
"test",
"."
] | def _PrintTestHeader(test_target_name):
"""Print a unified test header to identify the start of a test.
Args:
test_target_name: The name of the test.
"""
print '=' * 30, test_target_name, '=' * 30 | [
"def",
"_PrintTestHeader",
"(",
"test_target_name",
")",
":",
"print",
"'='",
"*",
"30",
",",
"test_target_name",
",",
"'='",
"*",
"30"
] | https://github.com/google/ion/blob/ef47f3b824050499ce5c6f774b366f6c4dbce0af/ion/build.py#L197-L203 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBStream.Print | (self, str) | return _lldb.SBStream_Print(self, str) | Print(SBStream self, char const * str) | Print(SBStream self, char const * str) | [
"Print",
"(",
"SBStream",
"self",
"char",
"const",
"*",
"str",
")"
] | def Print(self, str):
"""Print(SBStream self, char const * str)"""
return _lldb.SBStream_Print(self, str) | [
"def",
"Print",
"(",
"self",
",",
"str",
")",
":",
"return",
"_lldb",
".",
"SBStream_Print",
"(",
"self",
",",
"str",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L9538-L9540 | |
GJDuck/LowFat | ecf6a0f0fa1b73a27a626cf493cc39e477b6faea | llvm-4.0.0.src/examples/Kaleidoscope/MCJIT/cached/split-lib.py | python | TimingScriptGenerator.writeTimingCall | (self, irname, callname) | Echo some comments and invoke both versions of toy | Echo some comments and invoke both versions of toy | [
"Echo",
"some",
"comments",
"and",
"invoke",
"both",
"versions",
"of",
"toy"
] | def writeTimingCall(self, irname, callname):
"""Echo some comments and invoke both versions of toy"""
rootname = irname
if '.' in irname:
rootname = irname[:irname.rfind('.')]
self.shfile.write("echo \"%s: Calls %s\" >> %s\n" % (callname, irname, self.timeFile))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-mcjit -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT again\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-mcjit -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-jit -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"\" >> %s\n" % self.timeFile) | [
"def",
"writeTimingCall",
"(",
"self",
",",
"irname",
",",
"callname",
")",
":",
"rootname",
"=",
"irname",
"if",
"'.'",
"in",
"irname",
":",
"rootname",
"=",
"irname",
"[",
":",
"irname",
".",
"rfind",
"(",
"'.'",
")",
"]",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"%s: Calls %s\\\" >> %s\\n\"",
"%",
"(",
"callname",
",",
"irname",
",",
"self",
".",
"timeFile",
")",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"With MCJIT\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\" -o %s -a \"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"./toy-mcjit -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\\n\"",
"%",
"(",
"irname",
",",
"callname",
",",
"rootname",
",",
"rootname",
")",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"With MCJIT again\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\" -o %s -a \"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"./toy-mcjit -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\\n\"",
"%",
"(",
"irname",
",",
"callname",
",",
"rootname",
",",
"rootname",
")",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"With JIT\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"/usr/bin/time -f \\\"Command %C\\\\n\\\\tuser time: %U s\\\\n\\\\tsytem time: %S s\\\\n\\\\tmax set: %M kb\\\"\"",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\" -o %s -a \"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"./toy-jit -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\\n\"",
"%",
"(",
"irname",
",",
"callname",
",",
"rootname",
",",
"rootname",
")",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")",
"self",
".",
"shfile",
".",
"write",
"(",
"\"echo \\\"\\\" >> %s\\n\"",
"%",
"self",
".",
"timeFile",
")"
] | https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/examples/Kaleidoscope/MCJIT/cached/split-lib.py#L10-L32 | ||
ros/geometry2 | c0cb44e5315abc6067d7640cf58487e61d8d680a | tf2_ros/src/tf2_ros/buffer_interface.py | python | BufferInterface.can_transform_full | (self, target_frame, target_time, source_frame, source_time, fixed_frame, timeout=rospy.Duration(0.0)) | Check if a transform from the source frame to the target frame is possible (advanced API).
Must be implemented by a subclass of BufferInterface.
:param target_frame: Name of the frame to transform into.
:param target_time: The time to transform to. (0 will get the latest)
:param source_frame: Name of the input frame.
:param source_time: The time at which source_frame will be evaluated. (0 will get the latest)
:param fixed_frame: Name of the frame to consider constant in time.
:param timeout: (Optional) Time to wait for the target frame to become available.
:return: True if the transform is possible, false otherwise.
:rtype: bool | Check if a transform from the source frame to the target frame is possible (advanced API). | [
"Check",
"if",
"a",
"transform",
"from",
"the",
"source",
"frame",
"to",
"the",
"target",
"frame",
"is",
"possible",
"(",
"advanced",
"API",
")",
"."
] | def can_transform_full(self, target_frame, target_time, source_frame, source_time, fixed_frame, timeout=rospy.Duration(0.0)):
"""
Check if a transform from the source frame to the target frame is possible (advanced API).
Must be implemented by a subclass of BufferInterface.
:param target_frame: Name of the frame to transform into.
:param target_time: The time to transform to. (0 will get the latest)
:param source_frame: Name of the input frame.
:param source_time: The time at which source_frame will be evaluated. (0 will get the latest)
:param fixed_frame: Name of the frame to consider constant in time.
:param timeout: (Optional) Time to wait for the target frame to become available.
:return: True if the transform is possible, false otherwise.
:rtype: bool
"""
raise NotImplementedException() | [
"def",
"can_transform_full",
"(",
"self",
",",
"target_frame",
",",
"target_time",
",",
"source_frame",
",",
"source_time",
",",
"fixed_frame",
",",
"timeout",
"=",
"rospy",
".",
"Duration",
"(",
"0.0",
")",
")",
":",
"raise",
"NotImplementedException",
"(",
")"
] | https://github.com/ros/geometry2/blob/c0cb44e5315abc6067d7640cf58487e61d8d680a/tf2_ros/src/tf2_ros/buffer_interface.py#L151-L166 | ||
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/external/daemon/daemon.py | python | change_root_directory | (directory) | Change the root directory of this process.
Sets the current working directory, then the process root
directory, to the specified `directory`. Requires appropriate
OS privileges for this process. | Change the root directory of this process. | [
"Change",
"the",
"root",
"directory",
"of",
"this",
"process",
"."
] | def change_root_directory(directory):
""" Change the root directory of this process.
Sets the current working directory, then the process root
directory, to the specified `directory`. Requires appropriate
OS privileges for this process.
"""
try:
os.chdir(directory)
os.chroot(directory)
except:
error = DaemonOSEnvironmentError(
"Unable to change root directory (%(exc)s)"
% vars())
raise error | [
"def",
"change_root_directory",
"(",
"directory",
")",
":",
"try",
":",
"os",
".",
"chdir",
"(",
"directory",
")",
"os",
".",
"chroot",
"(",
"directory",
")",
"except",
":",
"error",
"=",
"DaemonOSEnvironmentError",
"(",
"\"Unable to change root directory (%(exc)s)\"",
"%",
"vars",
"(",
")",
")",
"raise",
"error"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/daemon/daemon.py#L512-L527 | ||
fatih/subvim | 241b6d170597857105da219c9b7d36059e9f11fb | vim/base/YouCompleteMe/third_party/jedi/jedi/parser/representation.py | python | Simple.get_parent_until | (self, classes=(), reverse=False,
include_current=True) | return scope | Takes always the parent, until one class (not a Class) | Takes always the parent, until one class (not a Class) | [
"Takes",
"always",
"the",
"parent",
"until",
"one",
"class",
"(",
"not",
"a",
"Class",
")"
] | def get_parent_until(self, classes=(), reverse=False,
include_current=True):
""" Takes always the parent, until one class (not a Class) """
if type(classes) not in (tuple, list):
classes = (classes,)
scope = self if include_current else self.parent
while scope.parent is not None:
if classes and reverse != scope.isinstance(*classes):
break
scope = scope.parent
return scope | [
"def",
"get_parent_until",
"(",
"self",
",",
"classes",
"=",
"(",
")",
",",
"reverse",
"=",
"False",
",",
"include_current",
"=",
"True",
")",
":",
"if",
"type",
"(",
"classes",
")",
"not",
"in",
"(",
"tuple",
",",
"list",
")",
":",
"classes",
"=",
"(",
"classes",
",",
")",
"scope",
"=",
"self",
"if",
"include_current",
"else",
"self",
".",
"parent",
"while",
"scope",
".",
"parent",
"is",
"not",
"None",
":",
"if",
"classes",
"and",
"reverse",
"!=",
"scope",
".",
"isinstance",
"(",
"*",
"classes",
")",
":",
"break",
"scope",
"=",
"scope",
".",
"parent",
"return",
"scope"
] | https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/jedi/jedi/parser/representation.py#L112-L122 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/tensorboard/backend/handler.py | python | TensorboardHandler._image_response_for_run | (self, run_images, run, tag) | return response | Builds a JSON-serializable object with information about run_images.
Args:
run_images: A list of event_accumulator.ImageValueEvent objects.
run: The name of the run.
tag: The name of the tag the images all belong to.
Returns:
A list of dictionaries containing the wall time, step, URL, width, and
height for each image. | Builds a JSON-serializable object with information about run_images. | [
"Builds",
"a",
"JSON",
"-",
"serializable",
"object",
"with",
"information",
"about",
"run_images",
"."
] | def _image_response_for_run(self, run_images, run, tag):
"""Builds a JSON-serializable object with information about run_images.
Args:
run_images: A list of event_accumulator.ImageValueEvent objects.
run: The name of the run.
tag: The name of the tag the images all belong to.
Returns:
A list of dictionaries containing the wall time, step, URL, width, and
height for each image.
"""
response = []
for index, run_image in enumerate(run_images):
response.append({
'wall_time': run_image.wall_time,
'step': run_image.step,
# We include the size so that the frontend can add that to the <img>
# tag so that the page layout doesn't change when the image loads.
'width': run_image.width,
'height': run_image.height,
'query': self._query_for_individual_image(run, tag, index)
})
return response | [
"def",
"_image_response_for_run",
"(",
"self",
",",
"run_images",
",",
"run",
",",
"tag",
")",
":",
"response",
"=",
"[",
"]",
"for",
"index",
",",
"run_image",
"in",
"enumerate",
"(",
"run_images",
")",
":",
"response",
".",
"append",
"(",
"{",
"'wall_time'",
":",
"run_image",
".",
"wall_time",
",",
"'step'",
":",
"run_image",
".",
"step",
",",
"# We include the size so that the frontend can add that to the <img>",
"# tag so that the page layout doesn't change when the image loads.",
"'width'",
":",
"run_image",
".",
"width",
",",
"'height'",
":",
"run_image",
".",
"height",
",",
"'query'",
":",
"self",
".",
"_query_for_individual_image",
"(",
"run",
",",
"tag",
",",
"index",
")",
"}",
")",
"return",
"response"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/tensorboard/backend/handler.py#L111-L134 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/ML/Data/MLData.py | python | MLQuantDataSet.GetResults | (self) | return res | Returns the result fields from each example | Returns the result fields from each example | [
"Returns",
"the",
"result",
"fields",
"from",
"each",
"example"
] | def GetResults(self):
""" Returns the result fields from each example
"""
if self.GetNResults() > 1:
v = self.GetNResults()
res = [x[-v:] for x in self.data]
else:
res = [x[-1] for x in self.data]
return res | [
"def",
"GetResults",
"(",
"self",
")",
":",
"if",
"self",
".",
"GetNResults",
"(",
")",
">",
"1",
":",
"v",
"=",
"self",
".",
"GetNResults",
"(",
")",
"res",
"=",
"[",
"x",
"[",
"-",
"v",
":",
"]",
"for",
"x",
"in",
"self",
".",
"data",
"]",
"else",
":",
"res",
"=",
"[",
"x",
"[",
"-",
"1",
"]",
"for",
"x",
"in",
"self",
".",
"data",
"]",
"return",
"res"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/ML/Data/MLData.py#L264-L273 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | Notebook.GetClassDefaultAttributes | (*args, **kwargs) | return _controls_.Notebook_GetClassDefaultAttributes(*args, **kwargs) | GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this. | GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes | [
"GetClassDefaultAttributes",
"(",
"int",
"variant",
"=",
"WINDOW_VARIANT_NORMAL",
")",
"-",
">",
"VisualAttributes"
] | def GetClassDefaultAttributes(*args, **kwargs):
"""
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
Get the default attributes for this class. This is useful if you want
to use the same font or colour in your own control as in a standard
control -- which is a much better idea than hard coding specific
colours or fonts which might look completely out of place on the
user's system, especially if it uses themes.
The variant parameter is only relevant under Mac currently and is
ignore under other platforms. Under Mac, it will change the size of
the returned font. See `wx.Window.SetWindowVariant` for more about
this.
"""
return _controls_.Notebook_GetClassDefaultAttributes(*args, **kwargs) | [
"def",
"GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"Notebook_GetClassDefaultAttributes",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L3116-L3131 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.