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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py | python | SourceLocation.file | (self) | return self._get_instantiation()[0] | Get the file represented by this source location. | Get the file represented by this source location. | [
"Get",
"the",
"file",
"represented",
"by",
"this",
"source",
"location",
"."
] | def file(self):
"""Get the file represented by this source location."""
return self._get_instantiation()[0] | [
"def",
"file",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_instantiation",
"(",
")",
"[",
"0",
"]"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py#L270-L272 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mapreduce/mapreduce/api/map_job/map_job_config.py | python | JobConfig._get_mapper_params | (self) | return {"input_reader": reader_params,
"output_writer": self.output_writer_params} | Converts self to model.MapperSpec.params. | Converts self to model.MapperSpec.params. | [
"Converts",
"self",
"to",
"model",
".",
"MapperSpec",
".",
"params",
"."
] | def _get_mapper_params(self):
"""Converts self to model.MapperSpec.params."""
reader_params = self.input_reader_cls.params_to_json(
self.input_reader_params)
# TODO(user): Do the same for writer params.
return {"input_reader": reader_params,
"output_writer": self.output_writer_params} | [
"def",
"_get_mapper_params",
"(",
"self",
")",
":",
"reader_params",
"=",
"self",
".",
"input_reader_cls",
".",
"params_to_json",
"(",
"self",
".",
"input_reader_params",
")",
"# TODO(user): Do the same for writer params.",
"return",
"{",
"\"input_reader\"",
":",
"reade... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/api/map_job/map_job_config.py#L101-L107 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/jedi/jedi/parser_utils.py | python | get_call_signature | (funcdef, width=72, call_string=None) | return '\n'.join(textwrap.wrap(code, width)) | Generate call signature of this function.
:param width: Fold lines if a line is longer than this value.
:type width: int
:arg func_name: Override function name when given.
:type func_name: str
:rtype: str | Generate call signature of this function. | [
"Generate",
"call",
"signature",
"of",
"this",
"function",
"."
] | def get_call_signature(funcdef, width=72, call_string=None):
"""
Generate call signature of this function.
:param width: Fold lines if a line is longer than this value.
:type width: int
:arg func_name: Override function name when given.
:type func_name: str
:rtype: str
"""
# Lambdas have no name.
if call_string is None:
if funcdef.type == 'lambdef':
call_string = '<lambda>'
else:
call_string = funcdef.name.value
if funcdef.type == 'lambdef':
p = '(' + ''.join(param.get_code() for param in funcdef.get_params()).strip() + ')'
else:
p = funcdef.children[2].get_code()
p = re.sub(r'\s+', ' ', p)
if funcdef.annotation:
rtype = " ->" + funcdef.annotation.get_code()
else:
rtype = ""
code = call_string + p + rtype
return '\n'.join(textwrap.wrap(code, width)) | [
"def",
"get_call_signature",
"(",
"funcdef",
",",
"width",
"=",
"72",
",",
"call_string",
"=",
"None",
")",
":",
"# Lambdas have no name.",
"if",
"call_string",
"is",
"None",
":",
"if",
"funcdef",
".",
"type",
"==",
"'lambdef'",
":",
"call_string",
"=",
"'<l... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/jedi/jedi/parser_utils.py#L141-L169 | |
papyrussolution/OpenPapyrus | bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91 | Src/OSF/protobuf-3.19.1/python/google/protobuf/descriptor_pool.py | python | DescriptorPool._TryLoadExtensionFromDB | (self, message_descriptor, number) | Try to Load extensions from descriptor db.
Args:
message_descriptor: descriptor of the extended message.
number: the extension number that needs to be loaded. | Try to Load extensions from descriptor db. | [
"Try",
"to",
"Load",
"extensions",
"from",
"descriptor",
"db",
"."
] | def _TryLoadExtensionFromDB(self, message_descriptor, number):
"""Try to Load extensions from descriptor db.
Args:
message_descriptor: descriptor of the extended message.
number: the extension number that needs to be loaded.
"""
if not self._descriptor_db:
return
# Only supported when FindFileContainingExtension is provided.
if not hasattr(
self._descriptor_db, 'FindFileContainingExtension'):
return
full_name = message_descriptor.full_name
file_proto = self._descriptor_db.FindFileContainingExtension(
full_name, number)
if file_proto is None:
return
try:
self._ConvertFileProtoToFileDescriptor(file_proto)
except:
warn_msg = ('Unable to load proto file %s for extension number %d.' %
(file_proto.name, number))
warnings.warn(warn_msg, RuntimeWarning) | [
"def",
"_TryLoadExtensionFromDB",
"(",
"self",
",",
"message_descriptor",
",",
"number",
")",
":",
"if",
"not",
"self",
".",
"_descriptor_db",
":",
"return",
"# Only supported when FindFileContainingExtension is provided.",
"if",
"not",
"hasattr",
"(",
"self",
".",
"_... | https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/descriptor_pool.py#L648-L674 | ||
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | BucketPointerArgument.GetLogArg | (self) | return "static_cast<const void*>(%s)" % self.name | Overridden from Argument. | Overridden from Argument. | [
"Overridden",
"from",
"Argument",
"."
] | def GetLogArg(self):
"""Overridden from Argument."""
return "static_cast<const void*>(%s)" % self.name | [
"def",
"GetLogArg",
"(",
"self",
")",
":",
"return",
"\"static_cast<const void*>(%s)\"",
"%",
"self",
".",
"name"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L9023-L9025 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Rect2D.GetSize | (*args, **kwargs) | return _core_.Rect2D_GetSize(*args, **kwargs) | GetSize(self) -> Size | GetSize(self) -> Size | [
"GetSize",
"(",
"self",
")",
"-",
">",
"Size"
] | def GetSize(*args, **kwargs):
"""GetSize(self) -> Size"""
return _core_.Rect2D_GetSize(*args, **kwargs) | [
"def",
"GetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect2D_GetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L1851-L1853 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | SysErrorMsg | (*args, **kwargs) | return _misc_.SysErrorMsg(*args, **kwargs) | SysErrorMsg(unsigned long nErrCode=0) -> String | SysErrorMsg(unsigned long nErrCode=0) -> String | [
"SysErrorMsg",
"(",
"unsigned",
"long",
"nErrCode",
"=",
"0",
")",
"-",
">",
"String"
] | def SysErrorMsg(*args, **kwargs):
"""SysErrorMsg(unsigned long nErrCode=0) -> String"""
return _misc_.SysErrorMsg(*args, **kwargs) | [
"def",
"SysErrorMsg",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"SysErrorMsg",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1843-L1845 | |
RoboJackets/robocup-software | bce13ce53ddb2ecb9696266d980722c34617dc15 | rj_gameplay/stp/rc.py | python | WorldState.our_robots | (self) | return self.__our_robots | :return: A list of our robots | :return: A list of our robots | [
":",
"return",
":",
"A",
"list",
"of",
"our",
"robots"
] | def our_robots(self) -> List[Robot]:
"""
:return: A list of our robots
"""
return self.__our_robots | [
"def",
"our_robots",
"(",
"self",
")",
"->",
"List",
"[",
"Robot",
"]",
":",
"return",
"self",
".",
"__our_robots"
] | https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/stp/rc.py#L660-L664 | |
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/youtube/service.py | python | YouTubeService.AddPlaylist | (self, playlist_title, playlist_description,
playlist_private=None) | return self.Post(playlist_entry, playlist_post_uri,
converter=gdata.youtube.YouTubePlaylistEntryFromString) | Add a new playlist to the currently authenticated users account.
Needs authentication.
Args:
playlist_title: A string representing the title for the new playlist.
playlist_description: A string representing the description of the
playlist.
playlist_private: An optional boolean, set to True if the playlist is
to be private.
Returns:
The YouTubePlaylistEntry if successfully posted. | Add a new playlist to the currently authenticated users account. | [
"Add",
"a",
"new",
"playlist",
"to",
"the",
"currently",
"authenticated",
"users",
"account",
"."
] | def AddPlaylist(self, playlist_title, playlist_description,
playlist_private=None):
"""Add a new playlist to the currently authenticated users account.
Needs authentication.
Args:
playlist_title: A string representing the title for the new playlist.
playlist_description: A string representing the description of the
playlist.
playlist_private: An optional boolean, set to True if the playlist is
to be private.
Returns:
The YouTubePlaylistEntry if successfully posted.
"""
playlist_entry = gdata.youtube.YouTubePlaylistEntry(
title=atom.Title(text=playlist_title),
description=gdata.youtube.Description(text=playlist_description))
if playlist_private:
playlist_entry.private = gdata.youtube.Private()
playlist_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, 'default',
'playlists')
return self.Post(playlist_entry, playlist_post_uri,
converter=gdata.youtube.YouTubePlaylistEntryFromString) | [
"def",
"AddPlaylist",
"(",
"self",
",",
"playlist_title",
",",
"playlist_description",
",",
"playlist_private",
"=",
"None",
")",
":",
"playlist_entry",
"=",
"gdata",
".",
"youtube",
".",
"YouTubePlaylistEntry",
"(",
"title",
"=",
"atom",
".",
"Title",
"(",
"t... | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/youtube/service.py#L909-L934 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/input.py | python | ProcessListFiltersInDict | (name, the_dict) | Process regular expression and exclusion-based filters on lists.
An exclusion list is in a dict key named with a trailing "!", like
"sources!". Every item in such a list is removed from the associated
main list, which in this example, would be "sources". Removed items are
placed into a "sources_excluded" list in the dict.
Regular expression (regex) filters are contained in dict keys named with a
trailing "/", such as "sources/" to operate on the "sources" list. Regex
filters in a dict take the form:
'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'],
['include', '_mac\\.cc$'] ],
The first filter says to exclude all files ending in _linux.cc, _mac.cc, and
_win.cc. The second filter then includes all files ending in _mac.cc that
are now or were once in the "sources" list. Items matching an "exclude"
filter are subject to the same processing as would occur if they were listed
by name in an exclusion list (ending in "!"). Items matching an "include"
filter are brought back into the main list if previously excluded by an
exclusion list or exclusion regex filter. Subsequent matching "exclude"
patterns can still cause items to be excluded after matching an "include". | Process regular expression and exclusion-based filters on lists. | [
"Process",
"regular",
"expression",
"and",
"exclusion",
"-",
"based",
"filters",
"on",
"lists",
"."
] | def ProcessListFiltersInDict(name, the_dict):
"""Process regular expression and exclusion-based filters on lists.
An exclusion list is in a dict key named with a trailing "!", like
"sources!". Every item in such a list is removed from the associated
main list, which in this example, would be "sources". Removed items are
placed into a "sources_excluded" list in the dict.
Regular expression (regex) filters are contained in dict keys named with a
trailing "/", such as "sources/" to operate on the "sources" list. Regex
filters in a dict take the form:
'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'],
['include', '_mac\\.cc$'] ],
The first filter says to exclude all files ending in _linux.cc, _mac.cc, and
_win.cc. The second filter then includes all files ending in _mac.cc that
are now or were once in the "sources" list. Items matching an "exclude"
filter are subject to the same processing as would occur if they were listed
by name in an exclusion list (ending in "!"). Items matching an "include"
filter are brought back into the main list if previously excluded by an
exclusion list or exclusion regex filter. Subsequent matching "exclude"
patterns can still cause items to be excluded after matching an "include".
"""
# Look through the dictionary for any lists whose keys end in "!" or "/".
# These are lists that will be treated as exclude lists and regular
# expression-based exclude/include lists. Collect the lists that are
# needed first, looking for the lists that they operate on, and assemble
# then into |lists|. This is done in a separate loop up front, because
# the _included and _excluded keys need to be added to the_dict, and that
# can't be done while iterating through it.
lists = []
del_lists = []
for key, value in the_dict.iteritems():
operation = key[-1]
if operation != '!' and operation != '/':
continue
if type(value) is not list:
raise ValueError(name + ' key ' + key + ' must be list, not ' + \
value.__class__.__name__)
list_key = key[:-1]
if list_key not in the_dict:
# This happens when there's a list like "sources!" but no corresponding
# "sources" list. Since there's nothing for it to operate on, queue up
# the "sources!" list for deletion now.
del_lists.append(key)
continue
if type(the_dict[list_key]) is not list:
value = the_dict[list_key]
raise ValueError(name + ' key ' + list_key + \
' must be list, not ' + \
value.__class__.__name__ + ' when applying ' + \
{'!': 'exclusion', '/': 'regex'}[operation])
if not list_key in lists:
lists.append(list_key)
# Delete the lists that are known to be unneeded at this point.
for del_list in del_lists:
del the_dict[del_list]
for list_key in lists:
the_list = the_dict[list_key]
# Initialize the list_actions list, which is parallel to the_list. Each
# item in list_actions identifies whether the corresponding item in
# the_list should be excluded, unconditionally preserved (included), or
# whether no exclusion or inclusion has been applied. Items for which
# no exclusion or inclusion has been applied (yet) have value -1, items
# excluded have value 0, and items included have value 1. Includes and
# excludes override previous actions. All items in list_actions are
# initialized to -1 because no excludes or includes have been processed
# yet.
list_actions = list((-1,) * len(the_list))
exclude_key = list_key + '!'
if exclude_key in the_dict:
for exclude_item in the_dict[exclude_key]:
for index in xrange(0, len(the_list)):
if exclude_item == the_list[index]:
# This item matches the exclude_item, so set its action to 0
# (exclude).
list_actions[index] = 0
# The "whatever!" list is no longer needed, dump it.
del the_dict[exclude_key]
regex_key = list_key + '/'
if regex_key in the_dict:
for regex_item in the_dict[regex_key]:
[action, pattern] = regex_item
pattern_re = re.compile(pattern)
if action == 'exclude':
# This item matches an exclude regex, so set its value to 0 (exclude).
action_value = 0
elif action == 'include':
# This item matches an include regex, so set its value to 1 (include).
action_value = 1
else:
# This is an action that doesn't make any sense.
raise ValueError('Unrecognized action ' + action + ' in ' + name + \
' key ' + regex_key)
for index in xrange(0, len(the_list)):
list_item = the_list[index]
if list_actions[index] == action_value:
# Even if the regex matches, nothing will change so continue (regex
# searches are expensive).
continue
if pattern_re.search(list_item):
# Regular expression match.
list_actions[index] = action_value
# The "whatever/" list is no longer needed, dump it.
del the_dict[regex_key]
# Add excluded items to the excluded list.
#
# Note that exclude_key ("sources!") is different from excluded_key
# ("sources_excluded"). The exclude_key list is input and it was already
# processed and deleted; the excluded_key list is output and it's about
# to be created.
excluded_key = list_key + '_excluded'
if excluded_key in the_dict:
raise GypError(name + ' key ' + excluded_key +
' must not be present prior '
' to applying exclusion/regex filters for ' + list_key)
excluded_list = []
# Go backwards through the list_actions list so that as items are deleted,
# the indices of items that haven't been seen yet don't shift. That means
# that things need to be prepended to excluded_list to maintain them in the
# same order that they existed in the_list.
for index in xrange(len(list_actions) - 1, -1, -1):
if list_actions[index] == 0:
# Dump anything with action 0 (exclude). Keep anything with action 1
# (include) or -1 (no include or exclude seen for the item).
excluded_list.insert(0, the_list[index])
del the_list[index]
# If anything was excluded, put the excluded list into the_dict at
# excluded_key.
if len(excluded_list) > 0:
the_dict[excluded_key] = excluded_list
# Now recurse into subdicts and lists that may contain dicts.
for key, value in the_dict.iteritems():
if type(value) is dict:
ProcessListFiltersInDict(key, value)
elif type(value) is list:
ProcessListFiltersInList(key, value) | [
"def",
"ProcessListFiltersInDict",
"(",
"name",
",",
"the_dict",
")",
":",
"# Look through the dictionary for any lists whose keys end in \"!\" or \"/\".",
"# These are lists that will be treated as exclude lists and regular",
"# expression-based exclude/include lists. Collect the lists that ar... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/input.py#L2305-L2460 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/pycparser/plyparser.py | python | PLYParser._token_coord | (self, p, token_idx) | return self._coord(p.lineno(token_idx), column) | Returns the coordinates for the YaccProduction objet 'p' indexed
with 'token_idx'. The coordinate includes the 'lineno' and
'column'. Both follow the lex semantic, starting from 1. | Returns the coordinates for the YaccProduction objet 'p' indexed
with 'token_idx'. The coordinate includes the 'lineno' and
'column'. Both follow the lex semantic, starting from 1. | [
"Returns",
"the",
"coordinates",
"for",
"the",
"YaccProduction",
"objet",
"p",
"indexed",
"with",
"token_idx",
".",
"The",
"coordinate",
"includes",
"the",
"lineno",
"and",
"column",
".",
"Both",
"follow",
"the",
"lex",
"semantic",
"starting",
"from",
"1",
"."... | def _token_coord(self, p, token_idx):
""" Returns the coordinates for the YaccProduction objet 'p' indexed
with 'token_idx'. The coordinate includes the 'lineno' and
'column'. Both follow the lex semantic, starting from 1.
"""
last_cr = p.lexer.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
if last_cr < 0:
last_cr = -1
column = (p.lexpos(token_idx) - (last_cr))
return self._coord(p.lineno(token_idx), column) | [
"def",
"_token_coord",
"(",
"self",
",",
"p",
",",
"token_idx",
")",
":",
"last_cr",
"=",
"p",
".",
"lexer",
".",
"lexer",
".",
"lexdata",
".",
"rfind",
"(",
"'\\n'",
",",
"0",
",",
"p",
".",
"lexpos",
"(",
"token_idx",
")",
")",
"if",
"last_cr",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/pycparser/plyparser.py#L55-L64 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/queue-reconstruction-by-height.py | python | Solution2.reconstructQueue | (self, people) | return result | :type people: List[List[int]]
:rtype: List[List[int]] | :type people: List[List[int]]
:rtype: List[List[int]] | [
":",
"type",
"people",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"List",
"[",
"List",
"[",
"int",
"]]"
] | def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
people.sort(key=lambda h_k1: (-h_k1[0], h_k1[1]))
result = []
for p in people:
result.insert(p[1], p)
return result | [
"def",
"reconstructQueue",
"(",
"self",
",",
"people",
")",
":",
"people",
".",
"sort",
"(",
"key",
"=",
"lambda",
"h_k1",
":",
"(",
"-",
"h_k1",
"[",
"0",
"]",
",",
"h_k1",
"[",
"1",
"]",
")",
")",
"result",
"=",
"[",
"]",
"for",
"p",
"in",
... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/queue-reconstruction-by-height.py#L32-L41 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | outputBuffer.nodeDumpOutput | (self, doc, cur, level, format, encoding) | Dump an XML node, recursive behaviour, children are printed
too. Note that @format = 1 provide node indenting only if
xmlIndentTreeOutput = 1 or xmlKeepBlanksDefault(0) was
called | Dump an XML node, recursive behaviour, children are printed
too. Note that | [
"Dump",
"an",
"XML",
"node",
"recursive",
"behaviour",
"children",
"are",
"printed",
"too",
".",
"Note",
"that"
] | def nodeDumpOutput(self, doc, cur, level, format, encoding):
"""Dump an XML node, recursive behaviour, children are printed
too. Note that @format = 1 provide node indenting only if
xmlIndentTreeOutput = 1 or xmlKeepBlanksDefault(0) was
called """
if doc is None: doc__o = None
else: doc__o = doc._o
if cur is None: cur__o = None
else: cur__o = cur._o
libxml2mod.xmlNodeDumpOutput(self._o, doc__o, cur__o, level, format, encoding) | [
"def",
"nodeDumpOutput",
"(",
"self",
",",
"doc",
",",
"cur",
",",
"level",
",",
"format",
",",
"encoding",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"if",
"cur",
"is",
"None",
... | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L5285-L5294 | ||
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | Wrapping/Python/paraview/simple.py | python | Hide3DWidgets | (proxy=None) | If possible in the current environment, this method will
request the application to hide the 3D widget(s) for proxy | If possible in the current environment, this method will
request the application to hide the 3D widget(s) for proxy | [
"If",
"possible",
"in",
"the",
"current",
"environment",
"this",
"method",
"will",
"request",
"the",
"application",
"to",
"hide",
"the",
"3D",
"widget",
"(",
"s",
")",
"for",
"proxy"
] | def Hide3DWidgets(proxy=None):
"""If possible in the current environment, this method will
request the application to hide the 3D widget(s) for proxy"""
proxy = proxy if proxy else GetActiveSource()
if not proxy:
raise ValueError ("No 'proxy' was provided and no active source was found.")
_Invoke3DWidgetUserEvent(proxy, "HideWidget") | [
"def",
"Hide3DWidgets",
"(",
"proxy",
"=",
"None",
")",
":",
"proxy",
"=",
"proxy",
"if",
"proxy",
"else",
"GetActiveSource",
"(",
")",
"if",
"not",
"proxy",
":",
"raise",
"ValueError",
"(",
"\"No 'proxy' was provided and no active source was found.\"",
")",
"_Inv... | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/simple.py#L2481-L2487 | ||
emscripten-core/emscripten | 0d413d3c5af8b28349682496edc14656f5700c2f | tools/system_libs.py | python | Library.__init__ | (self) | Creates a variation of this library.
A variation is a specific combination of settings a library can have.
For example, libc++-mt-noexcept is a variation of libc++.
There might be only one variation of a library.
The constructor keyword arguments will define what variation to use.
Use the `variations` classmethod to get the list of all possible constructor
arguments for this library.
Use the `get_default_variation` classmethod to construct the variation
suitable for the current invocation of emscripten. | Creates a variation of this library. | [
"Creates",
"a",
"variation",
"of",
"this",
"library",
"."
] | def __init__(self):
"""
Creates a variation of this library.
A variation is a specific combination of settings a library can have.
For example, libc++-mt-noexcept is a variation of libc++.
There might be only one variation of a library.
The constructor keyword arguments will define what variation to use.
Use the `variations` classmethod to get the list of all possible constructor
arguments for this library.
Use the `get_default_variation` classmethod to construct the variation
suitable for the current invocation of emscripten.
"""
if not self.name:
raise NotImplementedError('Cannot instantiate an abstract library') | [
"def",
"__init__",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"name",
":",
"raise",
"NotImplementedError",
"(",
"'Cannot instantiate an abstract library'",
")"
] | https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/tools/system_libs.py#L201-L218 | ||
google/mysql-protobuf | 467cda676afaa49e762c5c9164a43f6ad31a1fbf | protobuf/python/google/protobuf/descriptor.py | python | EnumDescriptor.__init__ | (self, name, full_name, filename, values,
containing_type=None, options=None, file=None,
serialized_start=None, serialized_end=None) | Arguments are as described in the attribute description above.
Note that filename is an obsolete argument, that is not used anymore.
Please use file.name to access this as an attribute. | Arguments are as described in the attribute description above. | [
"Arguments",
"are",
"as",
"described",
"in",
"the",
"attribute",
"description",
"above",
"."
] | def __init__(self, name, full_name, filename, values,
containing_type=None, options=None, file=None,
serialized_start=None, serialized_end=None):
"""Arguments are as described in the attribute description above.
Note that filename is an obsolete argument, that is not used anymore.
Please use file.name to access this as an attribute.
"""
super(EnumDescriptor, self).__init__(
options, 'EnumOptions', name, full_name, file,
containing_type, serialized_start=serialized_start,
serialized_end=serialized_end)
self.values = values
for value in self.values:
value.type = self
self.values_by_name = dict((v.name, v) for v in values)
self.values_by_number = dict((v.number, v) for v in values) | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"full_name",
",",
"filename",
",",
"values",
",",
"containing_type",
"=",
"None",
",",
"options",
"=",
"None",
",",
"file",
"=",
"None",
",",
"serialized_start",
"=",
"None",
",",
"serialized_end",
"=",
"... | https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/google/protobuf/descriptor.py#L589-L606 | ||
fmtlib/fmt | ecd6022c24e4fed94e1ea09029c386f36da4a2b8 | support/manage.py | python | create_build_env | () | return env | Create a build environment. | Create a build environment. | [
"Create",
"a",
"build",
"environment",
"."
] | def create_build_env():
"""Create a build environment."""
class Env:
pass
env = Env()
# Import the documentation build module.
env.fmt_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(env.fmt_dir, 'doc'))
import build
env.build_dir = 'build'
env.versions = build.versions
# Virtualenv and repos are cached to speed up builds.
build.create_build_env(os.path.join(env.build_dir, 'virtualenv'))
env.fmt_repo = Git(os.path.join(env.build_dir, 'fmt'))
return env | [
"def",
"create_build_env",
"(",
")",
":",
"class",
"Env",
":",
"pass",
"env",
"=",
"Env",
"(",
")",
"# Import the documentation build module.",
"env",
".",
"fmt_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"o... | https://github.com/fmtlib/fmt/blob/ecd6022c24e4fed94e1ea09029c386f36da4a2b8/support/manage.py#L74-L92 | |
google/nucleus | 68d3947fafba1337f294c0668a6e1c7f3f1273e3 | nucleus/io/fasta.py | python | IndexedFastaReader.__init__ | (self, input_path, keep_true_case=False, cache_size=None) | Initializes an IndexedFastaReader.
Args:
input_path: string. A path to a resource containing FASTA records.
keep_true_case: bool. If False, casts all bases to uppercase before
returning them.
cache_size: integer. Number of bases to cache from previous queries.
Defaults to 64K. The cache can be disabled using cache_size=0. | Initializes an IndexedFastaReader. | [
"Initializes",
"an",
"IndexedFastaReader",
"."
] | def __init__(self, input_path, keep_true_case=False, cache_size=None):
"""Initializes an IndexedFastaReader.
Args:
input_path: string. A path to a resource containing FASTA records.
keep_true_case: bool. If False, casts all bases to uppercase before
returning them.
cache_size: integer. Number of bases to cache from previous queries.
Defaults to 64K. The cache can be disabled using cache_size=0.
"""
super(IndexedFastaReader, self).__init__()
options = fasta_pb2.FastaReaderOptions(keep_true_case=keep_true_case)
fasta_path = input_path
fai_path = fasta_path + '.fai'
if cache_size is None:
# Use the C++-defined default cache size.
self._reader = reference.IndexedFastaReader.from_file(
fasta_path, fai_path, options)
else:
self._reader = reference.IndexedFastaReader.from_file(
fasta_path, fai_path, options, cache_size)
# TODO(thomaswc): Define a RefFastaHeader proto, and use it instead of this.
self.header = RefFastaHeader(contigs=self._reader.contigs) | [
"def",
"__init__",
"(",
"self",
",",
"input_path",
",",
"keep_true_case",
"=",
"False",
",",
"cache_size",
"=",
"None",
")",
":",
"super",
"(",
"IndexedFastaReader",
",",
"self",
")",
".",
"__init__",
"(",
")",
"options",
"=",
"fasta_pb2",
".",
"FastaReade... | https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/io/fasta.py#L72-L97 | ||
dicecco1/fpga_caffe | 7a191704efd7873071cfef35772d7e7bf3e3cfd6 | tools/extra/extract_seconds.py | python | get_log_created_year | (input_file) | return log_created_year | Get year from log file system timestamp | Get year from log file system timestamp | [
"Get",
"year",
"from",
"log",
"file",
"system",
"timestamp"
] | def get_log_created_year(input_file):
"""Get year from log file system timestamp
"""
log_created_time = os.path.getctime(input_file)
log_created_year = datetime.datetime.fromtimestamp(log_created_time).year
return log_created_year | [
"def",
"get_log_created_year",
"(",
"input_file",
")",
":",
"log_created_time",
"=",
"os",
".",
"path",
".",
"getctime",
"(",
"input_file",
")",
"log_created_year",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"log_created_time",
")",
".",
"year"... | https://github.com/dicecco1/fpga_caffe/blob/7a191704efd7873071cfef35772d7e7bf3e3cfd6/tools/extra/extract_seconds.py#L22-L28 | |
nodejs/nan | 8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62 | cpplint.py | python | GetPreviousNonBlankLine | (clean_lines, linenum) | return ('', -1) | Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line. | Return the most recent non-blank line and its line number. | [
"Return",
"the",
"most",
"recent",
"non",
"-",
"blank",
"line",
"and",
"its",
"line",
"number",
"."
] | def GetPreviousNonBlankLine(clean_lines, linenum):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line.
"""
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline): # if not a blank line...
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1) | [
"def",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"prevlinenum",
"=",
"linenum",
"-",
"1",
"while",
"prevlinenum",
">=",
"0",
":",
"prevline",
"=",
"clean_lines",
".",
"elided",
"[",
"prevlinenum",
"]",
"if",
"not",
"IsBlankLine",... | https://github.com/nodejs/nan/blob/8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62/cpplint.py#L3949-L3969 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/multiply-strings.py | python | Solution.multiply | (self, num1, num2) | return "".join(map(lambda x: str(x), result[i:])) | :type num1: str
:type num2: str
:rtype: str | :type num1: str
:type num2: str
:rtype: str | [
":",
"type",
"num1",
":",
"str",
":",
"type",
"num2",
":",
"str",
":",
"rtype",
":",
"str"
] | def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
result = [0]*(len(num1)+len(num2))
for i in reversed(xrange(len(num1))):
for j in reversed(xrange(len(num2))):
result[i+j+1] += int(num1[i])*int(num2[j])
result[i+j] += result[i+j+1]//10
result[i+j+1] %= 10
for i in xrange(len(result)):
if result[i]:
break
return "".join(map(lambda x: str(x), result[i:])) | [
"def",
"multiply",
"(",
"self",
",",
"num1",
",",
"num2",
")",
":",
"result",
"=",
"[",
"0",
"]",
"*",
"(",
"len",
"(",
"num1",
")",
"+",
"len",
"(",
"num2",
")",
")",
"for",
"i",
"in",
"reversed",
"(",
"xrange",
"(",
"len",
"(",
"num1",
")",... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/multiply-strings.py#L5-L20 | |
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/harness-thci/OpenThread_WpanCtl.py | python | OpenThread_WpanCtl.MGMT_ANNOUNCE_BEGIN | (self, sAddr, xCommissionerSessionId, listChannelMask, xCount, xPeriod) | send MGMT_ANNOUNCE_BEGIN message to a given destination
Returns:
True: successful to send MGMT_ANNOUNCE_BEGIN message.
False: fail to send MGMT_ANNOUNCE_BEGIN message. | send MGMT_ANNOUNCE_BEGIN message to a given destination | [
"send",
"MGMT_ANNOUNCE_BEGIN",
"message",
"to",
"a",
"given",
"destination"
] | def MGMT_ANNOUNCE_BEGIN(self, sAddr, xCommissionerSessionId, listChannelMask, xCount, xPeriod):
"""send MGMT_ANNOUNCE_BEGIN message to a given destination
Returns:
True: successful to send MGMT_ANNOUNCE_BEGIN message.
False: fail to send MGMT_ANNOUNCE_BEGIN message.
"""
print('%s call MGMT_ANNOUNCE_BEGIN' % self.port)
channelMask = ''
channelMask = self.__ChannelMaskListToStr(listChannelMask)
try:
cmd = self.wpan_cmd_prefix + 'commissioner announce-begin %s %s %s %s' % (
channelMask,
xCount,
xPeriod,
sAddr,
)
print(cmd)
return self.__sendCommand(cmd) != 'Fail'
except Exception as e:
ModuleHelper.WriteIntoDebugLogger('MGMT_ANNOUNCE_BEGIN() error: ' + str(e)) | [
"def",
"MGMT_ANNOUNCE_BEGIN",
"(",
"self",
",",
"sAddr",
",",
"xCommissionerSessionId",
",",
"listChannelMask",
",",
"xCount",
",",
"xPeriod",
")",
":",
"print",
"(",
"'%s call MGMT_ANNOUNCE_BEGIN'",
"%",
"self",
".",
"port",
")",
"channelMask",
"=",
"''",
"chan... | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-thci/OpenThread_WpanCtl.py#L2233-L2253 | ||
arkenthera/electron-vibrancy | 383153ef9ccb23a6c7517150d6bb0794dff3115e | scripts/cpplint.py | python | IsDecltype | (clean_lines, linenum, column) | return False | Check if the token ending on (linenum, column) is decltype().
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: the number of the line to check.
column: end column of the token to check.
Returns:
True if this token is decltype() expression, False otherwise. | Check if the token ending on (linenum, column) is decltype(). | [
"Check",
"if",
"the",
"token",
"ending",
"on",
"(",
"linenum",
"column",
")",
"is",
"decltype",
"()",
"."
] | def IsDecltype(clean_lines, linenum, column):
"""Check if the token ending on (linenum, column) is decltype().
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: the number of the line to check.
column: end column of the token to check.
Returns:
True if this token is decltype() expression, False otherwise.
"""
(text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
if start_col < 0:
return False
if Search(r'\bdecltype\s*$', text[0:start_col]):
return True
return False | [
"def",
"IsDecltype",
"(",
"clean_lines",
",",
"linenum",
",",
"column",
")",
":",
"(",
"text",
",",
"_",
",",
"start_col",
")",
"=",
"ReverseCloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"column",
")",
"if",
"start_col",
"<",
"0",
":",
"retu... | https://github.com/arkenthera/electron-vibrancy/blob/383153ef9ccb23a6c7517150d6bb0794dff3115e/scripts/cpplint.py#L3052-L3067 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/inspect.py | python | getargvalues | (frame) | return ArgInfo(args, varargs, varkw, frame.f_locals) | Get information about arguments passed into a particular frame.
A tuple of four things is returned: (args, varargs, varkw, locals).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dictionary of the given frame. | Get information about arguments passed into a particular frame. | [
"Get",
"information",
"about",
"arguments",
"passed",
"into",
"a",
"particular",
"frame",
"."
] | def getargvalues(frame):
"""Get information about arguments passed into a particular frame.
A tuple of four things is returned: (args, varargs, varkw, locals).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dictionary of the given frame."""
args, varargs, varkw = getargs(frame.f_code)
return ArgInfo(args, varargs, varkw, frame.f_locals) | [
"def",
"getargvalues",
"(",
"frame",
")",
":",
"args",
",",
"varargs",
",",
"varkw",
"=",
"getargs",
"(",
"frame",
".",
"f_code",
")",
"return",
"ArgInfo",
"(",
"args",
",",
"varargs",
",",
"varkw",
",",
"frame",
".",
"f_locals",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/inspect.py#L821-L829 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/aui.py | python | AuiToolBar.GetToolShortHelp | (*args, **kwargs) | return _aui.AuiToolBar_GetToolShortHelp(*args, **kwargs) | GetToolShortHelp(self, int toolId) -> String | GetToolShortHelp(self, int toolId) -> String | [
"GetToolShortHelp",
"(",
"self",
"int",
"toolId",
")",
"-",
">",
"String"
] | def GetToolShortHelp(*args, **kwargs):
"""GetToolShortHelp(self, int toolId) -> String"""
return _aui.AuiToolBar_GetToolShortHelp(*args, **kwargs) | [
"def",
"GetToolShortHelp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_aui",
".",
"AuiToolBar_GetToolShortHelp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L2234-L2236 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py | python | obj_analysis.get_value | (self) | return self.value | Return the C++ value (type + name). | Return the C++ value (type + name). | [
"Return",
"the",
"C",
"++",
"value",
"(",
"type",
"+",
"name",
")",
"."
] | def get_value(self):
""" Return the C++ value (type + name). """
return self.value | [
"def",
"get_value",
"(",
"self",
")",
":",
"return",
"self",
".",
"value"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/CEF3/cef_source/tools/cef_parser.py#L1737-L1739 | |
BSVino/DoubleAction | c550b168a3e919926c198c30240f506538b92e75 | mp/src/thirdparty/protobuf-2.3.0/python/mox.py | python | MockAnything._Replay | (self) | Start replaying expected method calls. | Start replaying expected method calls. | [
"Start",
"replaying",
"expected",
"method",
"calls",
"."
] | def _Replay(self):
"""Start replaying expected method calls."""
self._replay_mode = True | [
"def",
"_Replay",
"(",
"self",
")",
":",
"self",
".",
"_replay_mode",
"=",
"True"
] | https://github.com/BSVino/DoubleAction/blob/c550b168a3e919926c198c30240f506538b92e75/mp/src/thirdparty/protobuf-2.3.0/python/mox.py#L326-L329 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/ceph_argparse.py | python | parse_json_funcsigs | (s: str,
consumer: str) | return sigdict | A function signature is mostly an array of argdesc; it's represented
in JSON as
{
"cmd001": {"sig":[ "type": type, "name": name, "n": num, "req":true|false <other param>], "help":helptext, "module":modulename, "perm":perms, "avail":availability}
.
.
.
]
A set of sigs is in an dict mapped by a unique number:
{
"cmd1": {
"sig": ["type.. ], "help":helptext...
}
"cmd2"{
"sig": [.. ], "help":helptext...
}
}
Parse the string s and return a dict of dicts, keyed by opcode;
each dict contains 'sig' with the array of descriptors, and 'help'
with the helptext, 'module' with the module name, 'perm' with a
string representing required permissions in that module to execute
this command (and also whether it is a read or write command from
the cluster state perspective), and 'avail' as a hint for
whether the command should be advertised by CLI, REST, or both.
If avail does not contain 'consumer', don't include the command
in the returned dict. | A function signature is mostly an array of argdesc; it's represented
in JSON as
{
"cmd001": {"sig":[ "type": type, "name": name, "n": num, "req":true|false <other param>], "help":helptext, "module":modulename, "perm":perms, "avail":availability}
.
.
.
] | [
"A",
"function",
"signature",
"is",
"mostly",
"an",
"array",
"of",
"argdesc",
";",
"it",
"s",
"represented",
"in",
"JSON",
"as",
"{",
"cmd001",
":",
"{",
"sig",
":",
"[",
"type",
":",
"type",
"name",
":",
"name",
"n",
":",
"num",
"req",
":",
"true|... | def parse_json_funcsigs(s: str,
consumer: str) -> Dict[str, Dict[str, List[argdesc]]]:
"""
A function signature is mostly an array of argdesc; it's represented
in JSON as
{
"cmd001": {"sig":[ "type": type, "name": name, "n": num, "req":true|false <other param>], "help":helptext, "module":modulename, "perm":perms, "avail":availability}
.
.
.
]
A set of sigs is in an dict mapped by a unique number:
{
"cmd1": {
"sig": ["type.. ], "help":helptext...
}
"cmd2"{
"sig": [.. ], "help":helptext...
}
}
Parse the string s and return a dict of dicts, keyed by opcode;
each dict contains 'sig' with the array of descriptors, and 'help'
with the helptext, 'module' with the module name, 'perm' with a
string representing required permissions in that module to execute
this command (and also whether it is a read or write command from
the cluster state perspective), and 'avail' as a hint for
whether the command should be advertised by CLI, REST, or both.
If avail does not contain 'consumer', don't include the command
in the returned dict.
"""
try:
overall = json.loads(s)
except Exception as e:
print("Couldn't parse JSON {0}: {1}".format(s, e), file=sys.stderr)
raise e
sigdict = {}
for cmdtag, cmd in overall.items():
if 'sig' not in cmd:
s = "JSON descriptor {0} has no 'sig'".format(cmdtag)
raise JsonFormat(s)
# check 'avail' and possibly ignore this command
if 'avail' in cmd:
if consumer not in cmd['avail']:
continue
# rewrite the 'sig' item with the argdesc-ized version, and...
cmd['sig'] = parse_funcsig(cmd['sig'])
# just take everything else as given
sigdict[cmdtag] = cmd
return sigdict | [
"def",
"parse_json_funcsigs",
"(",
"s",
":",
"str",
",",
"consumer",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"List",
"[",
"argdesc",
"]",
"]",
"]",
":",
"try",
":",
"overall",
"=",
"json",
".",
"loads",
"(",
"s",
... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/ceph_argparse.py#L957-L1007 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/numpy/math_ops.py | python | rint | (x, dtype=None) | return res | Rounds elements of the array to the nearest integer.
Note:
Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
not supported.
Ascend does not support dtype `float64` currently.
Args:
x (Union[float, list, tuple, Tensor]): Input tensor.
dtype (:class:`mindspore.dtype`, optional): Defaults to None. Overrides the dtype of the
output Tensor.
Returns:
Output tensor is same shape and type as x. This is a scalar if x is a scalar.
Raises:
TypeError: If `x` can not be converted to tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.numpy as np
>>> x = np.array([-1.7, -1.5, 0.2, 1.5, 1.7, 2.0])
>>> print(np.rint(x))
[-2. -2. 0. 2. 2. 2.] | Rounds elements of the array to the nearest integer. | [
"Rounds",
"elements",
"of",
"the",
"array",
"to",
"the",
"nearest",
"integer",
"."
] | def rint(x, dtype=None):
"""
Rounds elements of the array to the nearest integer.
Note:
Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
not supported.
Ascend does not support dtype `float64` currently.
Args:
x (Union[float, list, tuple, Tensor]): Input tensor.
dtype (:class:`mindspore.dtype`, optional): Defaults to None. Overrides the dtype of the
output Tensor.
Returns:
Output tensor is same shape and type as x. This is a scalar if x is a scalar.
Raises:
TypeError: If `x` can not be converted to tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore.numpy as np
>>> x = np.array([-1.7, -1.5, 0.2, 1.5, 1.7, 2.0])
>>> print(np.rint(x))
[-2. -2. 0. 2. 2. 2.]
"""
x = _to_tensor_origin_dtype(x)
res = _rint(x)
if dtype is not None and not _check_same_type(F.dtype(res), dtype):
res = F.cast(res, dtype)
return res | [
"def",
"rint",
"(",
"x",
",",
"dtype",
"=",
"None",
")",
":",
"x",
"=",
"_to_tensor_origin_dtype",
"(",
"x",
")",
"res",
"=",
"_rint",
"(",
"x",
")",
"if",
"dtype",
"is",
"not",
"None",
"and",
"not",
"_check_same_type",
"(",
"F",
".",
"dtype",
"(",... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/numpy/math_ops.py#L5753-L5786 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/compiler.py | python | CodeGenerator._output_child_pre | (
self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo
) | Output extra source code before visiting a child of an
``Output`` node. | Output extra source code before visiting a child of an
``Output`` node. | [
"Output",
"extra",
"source",
"code",
"before",
"visiting",
"a",
"child",
"of",
"an",
"Output",
"node",
"."
] | def _output_child_pre(
self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo
) -> None:
"""Output extra source code before visiting a child of an
``Output`` node.
"""
if frame.eval_ctx.volatile:
self.write("(escape if context.eval_ctx.autoescape else str)(")
elif frame.eval_ctx.autoescape:
self.write("escape(")
else:
self.write("str(")
if finalize.src is not None:
self.write(finalize.src) | [
"def",
"_output_child_pre",
"(",
"self",
",",
"node",
":",
"nodes",
".",
"Expr",
",",
"frame",
":",
"Frame",
",",
"finalize",
":",
"_FinalizeInfo",
")",
"->",
"None",
":",
"if",
"frame",
".",
"eval_ctx",
".",
"volatile",
":",
"self",
".",
"write",
"(",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/compiler.py#L1452-L1466 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/keras/python/keras/backend.py | python | constant | (value, dtype=None, shape=None, name=None) | return constant_op.constant(value, dtype=dtype, shape=shape, name=name) | Creates a constant tensor.
Arguments:
value: A constant value (or list)
dtype: The type of the elements of the resulting tensor.
shape: Optional dimensions of resulting tensor.
name: Optional name for the tensor.
Returns:
A Constant Tensor. | Creates a constant tensor. | [
"Creates",
"a",
"constant",
"tensor",
"."
] | def constant(value, dtype=None, shape=None, name=None):
"""Creates a constant tensor.
Arguments:
value: A constant value (or list)
dtype: The type of the elements of the resulting tensor.
shape: Optional dimensions of resulting tensor.
name: Optional name for the tensor.
Returns:
A Constant Tensor.
"""
if dtype is None:
dtype = floatx()
return constant_op.constant(value, dtype=dtype, shape=shape, name=name) | [
"def",
"constant",
"(",
"value",
",",
"dtype",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"floatx",
"(",
")",
"return",
"constant_op",
".",
"constant",
"(",
"value",
"... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/backend.py#L548-L562 | |
google/flatbuffers | b3006913369e0a7550795e477011ac5bebb93497 | python/flatbuffers/flexbuffers.py | python | Builder.Int | (self, value, byte_width=0) | Encodes signed integer value.
Args:
value: A signed integer value.
byte_width: Number of bytes to use: 1, 2, 4, or 8. | Encodes signed integer value. | [
"Encodes",
"signed",
"integer",
"value",
"."
] | def Int(self, value, byte_width=0):
"""Encodes signed integer value.
Args:
value: A signed integer value.
byte_width: Number of bytes to use: 1, 2, 4, or 8.
"""
bit_width = BitWidth.I(value) if byte_width == 0 else BitWidth.B(byte_width)
self._stack.append(Value.Int(value, bit_width)) | [
"def",
"Int",
"(",
"self",
",",
"value",
",",
"byte_width",
"=",
"0",
")",
":",
"bit_width",
"=",
"BitWidth",
".",
"I",
"(",
"value",
")",
"if",
"byte_width",
"==",
"0",
"else",
"BitWidth",
".",
"B",
"(",
"byte_width",
")",
"self",
".",
"_stack",
"... | https://github.com/google/flatbuffers/blob/b3006913369e0a7550795e477011ac5bebb93497/python/flatbuffers/flexbuffers.py#L1231-L1239 | ||
priyankchheda/algorithms | c361aa9071573fa9966d5b02d05e524815abcf2b | linked_list/reverse_doubly_list.py | python | DoublyLinkedList.print | (self) | prints entire linked list without changing underlying data | prints entire linked list without changing underlying data | [
"prints",
"entire",
"linked",
"list",
"without",
"changing",
"underlying",
"data"
] | def print(self):
""" prints entire linked list without changing underlying data """
current = self.head
while current is not None:
print(" <->", current.data, end="")
current = current.next
print() | [
"def",
"print",
"(",
"self",
")",
":",
"current",
"=",
"self",
".",
"head",
"while",
"current",
"is",
"not",
"None",
":",
"print",
"(",
"\" <->\"",
",",
"current",
".",
"data",
",",
"end",
"=",
"\"\"",
")",
"current",
"=",
"current",
".",
"next",
"... | https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/linked_list/reverse_doubly_list.py#L37-L43 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBDebugger.SetInternalVariable | (var_name, value, debugger_instance_name) | return _lldb.SBDebugger_SetInternalVariable(var_name, value, debugger_instance_name) | SetInternalVariable(char const * var_name, char const * value, char const * debugger_instance_name) -> SBError | SetInternalVariable(char const * var_name, char const * value, char const * debugger_instance_name) -> SBError | [
"SetInternalVariable",
"(",
"char",
"const",
"*",
"var_name",
"char",
"const",
"*",
"value",
"char",
"const",
"*",
"debugger_instance_name",
")",
"-",
">",
"SBError"
] | def SetInternalVariable(var_name, value, debugger_instance_name):
"""SetInternalVariable(char const * var_name, char const * value, char const * debugger_instance_name) -> SBError"""
return _lldb.SBDebugger_SetInternalVariable(var_name, value, debugger_instance_name) | [
"def",
"SetInternalVariable",
"(",
"var_name",
",",
"value",
",",
"debugger_instance_name",
")",
":",
"return",
"_lldb",
".",
"SBDebugger_SetInternalVariable",
"(",
"var_name",
",",
"value",
",",
"debugger_instance_name",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L4167-L4169 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/tbe/bn_inference.py | python | _bn_inference_tbe | () | return | BNInference TBE register | BNInference TBE register | [
"BNInference",
"TBE",
"register"
] | def _bn_inference_tbe():
"""BNInference TBE register"""
return | [
"def",
"_bn_inference_tbe",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/bn_inference.py#L48-L50 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/Utils/cgf_utils/aws_sts.py | python | AWSSTSUtils.client | (self, session=None) | Creates a new STS client in the current session if provided | Creates a new STS client in the current session if provided | [
"Creates",
"a",
"new",
"STS",
"client",
"in",
"the",
"current",
"session",
"if",
"provided"
] | def client(self, session=None):
"""Creates a new STS client in the current session if provided"""
if session is not None:
return session.client(self.STS_SERVICE_NAME, endpoint_url=self._endpoint_url)
else:
return boto3.client(self.STS_SERVICE_NAME, endpoint_url=self._endpoint_url, region_name=self._region) | [
"def",
"client",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"if",
"session",
"is",
"not",
"None",
":",
"return",
"session",
".",
"client",
"(",
"self",
".",
"STS_SERVICE_NAME",
",",
"endpoint_url",
"=",
"self",
".",
"_endpoint_url",
")",
"else",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/Utils/cgf_utils/aws_sts.py#L32-L37 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/traci/_vehicle.py | python | VehicleDomain.getNeighbors | (self, vehID, mode) | return self._getUniversal(tc.VAR_NEIGHBORS, vehID, "B", mode) | byte -> list(pair(string, double))
The parameter mode is a bitset (UBYTE), specifying the following:
bit 1: query lateral direction (left:0, right:1)
bit 2: query longitudinal direction (followers:0, leaders:1)
bit 3: blocking (return all:0, return only blockers:1)
The returned list contains pairs (ID, dist) for all lane change relevant neighboring leaders, resp. followers,
along with their longitudinal distance to the ego vehicle (egoFront - egoMinGap to leaderBack, resp.
followerFront - followerMinGap to egoBack. The value can be negative for overlapping neighs).
For the non-sublane case, the lists will contain at most one entry.
Note: The exact set of blockers in case blocking==1 is not determined for the sublane model,
but either all neighboring vehicles are returned (in case LCA_BLOCKED) or
none is returned (in case !LCA_BLOCKED). | byte -> list(pair(string, double)) | [
"byte",
"-",
">",
"list",
"(",
"pair",
"(",
"string",
"double",
"))"
] | def getNeighbors(self, vehID, mode):
""" byte -> list(pair(string, double))
The parameter mode is a bitset (UBYTE), specifying the following:
bit 1: query lateral direction (left:0, right:1)
bit 2: query longitudinal direction (followers:0, leaders:1)
bit 3: blocking (return all:0, return only blockers:1)
The returned list contains pairs (ID, dist) for all lane change relevant neighboring leaders, resp. followers,
along with their longitudinal distance to the ego vehicle (egoFront - egoMinGap to leaderBack, resp.
followerFront - followerMinGap to egoBack. The value can be negative for overlapping neighs).
For the non-sublane case, the lists will contain at most one entry.
Note: The exact set of blockers in case blocking==1 is not determined for the sublane model,
but either all neighboring vehicles are returned (in case LCA_BLOCKED) or
none is returned (in case !LCA_BLOCKED).
"""
return self._getUniversal(tc.VAR_NEIGHBORS, vehID, "B", mode) | [
"def",
"getNeighbors",
"(",
"self",
",",
"vehID",
",",
"mode",
")",
":",
"return",
"self",
".",
"_getUniversal",
"(",
"tc",
".",
"VAR_NEIGHBORS",
",",
"vehID",
",",
"\"B\"",
",",
"mode",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L769-L786 | |
Constellation/iv | 64c3a9c7c517063f29d90d449180ea8f6f4d946f | tools/cpplint.py | python | CheckSectionSpacing | (filename, clean_lines, class_info, linenum, error) | Checks for additional blank line issues related to sections.
Currently the only thing checked here is blank line before protected/private.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
class_info: A _ClassInfo objects.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for additional blank line issues related to sections. | [
"Checks",
"for",
"additional",
"blank",
"line",
"issues",
"related",
"to",
"sections",
"."
] | def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
"""Checks for additional blank line issues related to sections.
Currently the only thing checked here is blank line before protected/private.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
class_info: A _ClassInfo objects.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Skip checks if the class is small, where small means 25 lines or less.
# 25 lines seems like a good cutoff since that's the usual height of
# terminals, and any class that can't fit in one screen can't really
# be considered "small".
#
# Also skip checks if we are on the first line. This accounts for
# classes that look like
# class Foo { public: ... };
#
# If we didn't find the end of the class, last_line would be zero,
# and the check will be skipped by the first condition.
if (class_info.last_line - class_info.starting_linenum <= 24 or
linenum <= class_info.starting_linenum):
return
matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
if matched:
# Issue warning if the line before public/protected/private was
# not a blank line, but don't do this if the previous line contains
# "class" or "struct". This can happen two ways:
# - We are at the beginning of the class.
# - We are forward-declaring an inner class that is semantically
# private, but needed to be public for implementation reasons.
# Also ignores cases where the previous line ends with a backslash as can be
# common when defining classes in C macros.
prev_line = clean_lines.lines[linenum - 1]
if (not IsBlankLine(prev_line) and
not Search(r'\b(class|struct)\b', prev_line) and
not Search(r'\\$', prev_line)):
# Try a bit harder to find the beginning of the class. This is to
# account for multi-line base-specifier lists, e.g.:
# class Derived
# : public Base {
end_class_head = class_info.starting_linenum
for i in range(class_info.starting_linenum, linenum):
if Search(r'\{\s*$', clean_lines.lines[i]):
end_class_head = i
break
if end_class_head < linenum - 1:
error(filename, linenum, 'whitespace/blank_line', 3,
'"%s:" should be preceded by a blank line' % matched.group(1)) | [
"def",
"CheckSectionSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"class_info",
",",
"linenum",
",",
"error",
")",
":",
"# Skip checks if the class is small, where small means 25 lines or less.",
"# 25 lines seems like a good cutoff since that's the usual height of",
"# termina... | https://github.com/Constellation/iv/blob/64c3a9c7c517063f29d90d449180ea8f6f4d946f/tools/cpplint.py#L2879-L2931 | ||
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/ops/control_flow_ops.py | python | WhileContext.AddForwardLoopCounter | (self, outer_grad_state) | return total_iterations, next_n | Adds a loop that counts the number of iterations.
This is added to the forward loop at the time when we start to
create the loop for backprop gradient computation. Called in
the outer context of this forward context.
The pseudocode is:
`n = 0; while (_pivot) { n++; }`
Note that a control dependency is added to `n` to ensure the correct
execution order of stack push ops.
Args:
outer_grad_state: The outer grad state. None if not nested.
Returns:
The number of iterations taken by the forward loop and the loop index. | Adds a loop that counts the number of iterations. | [
"Adds",
"a",
"loop",
"that",
"counts",
"the",
"number",
"of",
"iterations",
"."
] | def AddForwardLoopCounter(self, outer_grad_state):
"""Adds a loop that counts the number of iterations.
This is added to the forward loop at the time when we start to
create the loop for backprop gradient computation. Called in
the outer context of this forward context.
The pseudocode is:
`n = 0; while (_pivot) { n++; }`
Note that a control dependency is added to `n` to ensure the correct
execution order of stack push ops.
Args:
outer_grad_state: The outer grad state. None if not nested.
Returns:
The number of iterations taken by the forward loop and the loop index.
"""
n = constant_op.constant(0, name="f_count")
if outer_grad_state is not None:
# Force the stack pushes of i-th execution of an inner loop to be ordered
# before the pushes of (i+1)-th execution of the same inner loop.
outer_add_op = outer_grad_state.forward_index.op.inputs[0].op
n.op._add_control_input(outer_add_op) # pylint: disable=protected-access
self.Enter()
self.AddName(n.name)
enter_n = _Enter(n, self._name, is_constant=False,
parallel_iterations=self._parallel_iterations,
name="f_count")
merge_n = merge([enter_n, enter_n])[0]
switch_n = switch(merge_n, self._pivot)
index = math_ops.add(switch_n[1], 1)
next_n = _NextIteration(index)
merge_n.op._update_input(1, next_n)
total_iterations = exit(switch_n[0], name="f_count")
self.ExitResult([total_iterations])
self.Exit()
return total_iterations, next_n | [
"def",
"AddForwardLoopCounter",
"(",
"self",
",",
"outer_grad_state",
")",
":",
"n",
"=",
"constant_op",
".",
"constant",
"(",
"0",
",",
"name",
"=",
"\"f_count\"",
")",
"if",
"outer_grad_state",
"is",
"not",
"None",
":",
"# Force the stack pushes of i-th executio... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/control_flow_ops.py#L2017-L2058 | |
google/mysql-protobuf | 467cda676afaa49e762c5c9164a43f6ad31a1fbf | storage/ndb/mcc/util.py | python | ConvertToPython.get_obj | (self) | return self._estack[0] | Returns the resulting object. Convenience method for accessing the only
remaining element on the element stack. | Returns the resulting object. Convenience method for accessing the only
remaining element on the element stack. | [
"Returns",
"the",
"resulting",
"object",
".",
"Convenience",
"method",
"for",
"accessing",
"the",
"only",
"remaining",
"element",
"on",
"the",
"element",
"stack",
"."
] | def get_obj(self):
"""Returns the resulting object. Convenience method for accessing the only
remaining element on the element stack."""
assert len(self._estack) == 1
return self._estack[0] | [
"def",
"get_obj",
"(",
"self",
")",
":",
"assert",
"len",
"(",
"self",
".",
"_estack",
")",
"==",
"1",
"return",
"self",
".",
"_estack",
"[",
"0",
"]"
] | https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/storage/ndb/mcc/util.py#L190-L195 | |
oracle/graaljs | 36a56e8e993d45fc40939a3a4d9c0c24990720f1 | graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py | python | _Replacement_write_data | (writer, data, is_attrib=False) | Writes datachars to writer. | Writes datachars to writer. | [
"Writes",
"datachars",
"to",
"writer",
"."
] | def _Replacement_write_data(writer, data, is_attrib=False):
"""Writes datachars to writer."""
data = data.replace("&", "&").replace("<", "<")
data = data.replace('"', """).replace(">", ">")
if is_attrib:
data = data.replace("\r", "
").replace("\n", "
").replace("\t", "	")
writer.write(data) | [
"def",
"_Replacement_write_data",
"(",
"writer",
",",
"data",
",",
"is_attrib",
"=",
"False",
")",
":",
"data",
"=",
"data",
".",
"replace",
"(",
"\"&\"",
",",
"\"&\"",
")",
".",
"replace",
"(",
"\"<\"",
",",
"\"<\"",
")",
"data",
"=",
"data",
"... | https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xml_fix.py#L16-L22 | ||
simsong/bulk_extractor | 738911df22b7066ca9e1662f4131fb44090a4196 | python/dfxml.py | python | fileobject.allocated | (self) | Returns True if the file is allocated, False if it was not
(that is, if it was deleted or is an orphan).
Note that we need to be tolerant of mixed case, as it was changed.
We also need to tolerate the case of the unalloc tag being used. | Returns True if the file is allocated, False if it was not
(that is, if it was deleted or is an orphan).
Note that we need to be tolerant of mixed case, as it was changed.
We also need to tolerate the case of the unalloc tag being used. | [
"Returns",
"True",
"if",
"the",
"file",
"is",
"allocated",
"False",
"if",
"it",
"was",
"not",
"(",
"that",
"is",
"if",
"it",
"was",
"deleted",
"or",
"is",
"an",
"orphan",
")",
".",
"Note",
"that",
"we",
"need",
"to",
"be",
"tolerant",
"of",
"mixed",
... | def allocated(self):
"""Returns True if the file is allocated, False if it was not
(that is, if it was deleted or is an orphan).
Note that we need to be tolerant of mixed case, as it was changed.
We also need to tolerate the case of the unalloc tag being used.
"""
if self.filename()=="$OrphanFiles": return False
if self.allocated_inode() and self.allocated_name():
return True
else:
return isone(self.tag("alloc")) or isone(self.tag("ALLOC")) or not isone(self.tag("unalloc")) | [
"def",
"allocated",
"(",
"self",
")",
":",
"if",
"self",
".",
"filename",
"(",
")",
"==",
"\"$OrphanFiles\"",
":",
"return",
"False",
"if",
"self",
".",
"allocated_inode",
"(",
")",
"and",
"self",
".",
"allocated_name",
"(",
")",
":",
"return",
"True",
... | https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/dfxml.py#L747-L757 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/optim/optimizer.py | python | Optimizer.state_dict | (self) | return {
'state': packed_state,
'param_groups': param_groups,
} | r"""Returns the state of the optimizer as a :class:`dict`.
It contains two entries:
* state - a dict holding current optimization state. Its content
differs between optimizer classes.
* param_groups - a list containing all parameter groups where each
parameter group is a dict | r"""Returns the state of the optimizer as a :class:`dict`. | [
"r",
"Returns",
"the",
"state",
"of",
"the",
"optimizer",
"as",
"a",
":",
"class",
":",
"dict",
"."
] | def state_dict(self):
r"""Returns the state of the optimizer as a :class:`dict`.
It contains two entries:
* state - a dict holding current optimization state. Its content
differs between optimizer classes.
* param_groups - a list containing all parameter groups where each
parameter group is a dict
"""
# Save order indices instead of Tensors
param_mappings = {}
start_index = 0
def pack_group(group):
nonlocal start_index
packed = {k: v for k, v in group.items() if k != 'params'}
param_mappings.update({id(p): i for i, p in enumerate(group['params'], start_index)
if id(p) not in param_mappings})
packed['params'] = [param_mappings[id(p)] for p in group['params']]
start_index += len(packed['params'])
return packed
param_groups = [pack_group(g) for g in self.param_groups]
# Remap state to use order indices as keys
packed_state = {(param_mappings[id(k)] if isinstance(k, torch.Tensor) else k): v
for k, v in self.state.items()}
return {
'state': packed_state,
'param_groups': param_groups,
} | [
"def",
"state_dict",
"(",
"self",
")",
":",
"# Save order indices instead of Tensors",
"param_mappings",
"=",
"{",
"}",
"start_index",
"=",
"0",
"def",
"pack_group",
"(",
"group",
")",
":",
"nonlocal",
"start_index",
"packed",
"=",
"{",
"k",
":",
"v",
"for",
... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/optim/optimizer.py#L96-L125 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | ci/build.py | python | default_ccache_dir | () | return os.path.join(os.path.expanduser("~"), ".ccache") | :return: ccache directory for the current platform | :return: ccache directory for the current platform | [
":",
"return",
":",
"ccache",
"directory",
"for",
"the",
"current",
"platform"
] | def default_ccache_dir() -> str:
""":return: ccache directory for the current platform"""
# Share ccache across containers
if 'CCACHE_DIR' in os.environ:
ccache_dir = os.path.realpath(os.environ['CCACHE_DIR'])
try:
os.makedirs(ccache_dir, exist_ok=True)
return ccache_dir
except PermissionError:
logging.info('Unable to make dirs at %s, falling back to local temp dir', ccache_dir)
# In osx tmpdir is not mountable by default
import platform
if platform.system() == 'Darwin':
ccache_dir = "/tmp/_mxnet_ccache"
os.makedirs(ccache_dir, exist_ok=True)
return ccache_dir
return os.path.join(os.path.expanduser("~"), ".ccache") | [
"def",
"default_ccache_dir",
"(",
")",
"->",
"str",
":",
"# Share ccache across containers",
"if",
"'CCACHE_DIR'",
"in",
"os",
".",
"environ",
":",
"ccache_dir",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"environ",
"[",
"'CCACHE_DIR'",
"]",
")... | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/ci/build.py#L87-L103 | |
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/grtzMarkerScopes.py | python | grtzMarkerScopes.OnGUINotify | (self,id,control,event) | Notifications from the vignette | Notifications from the vignette | [
"Notifications",
"from",
"the",
"vignette"
] | def OnGUINotify(self,id,control,event):
"Notifications from the vignette"
PtDebugPrint("grtzMarkerScope.GUI Notify id=%d, event=%d control=" % (id,event),control,level=kDebugDumpLevel)
if event == kDialogLoaded:
# if the dialog was just loaded then show it
control.show() | [
"def",
"OnGUINotify",
"(",
"self",
",",
"id",
",",
"control",
",",
"event",
")",
":",
"PtDebugPrint",
"(",
"\"grtzMarkerScope.GUI Notify id=%d, event=%d control=\"",
"%",
"(",
"id",
",",
"event",
")",
",",
"control",
",",
"level",
"=",
"kDebugDumpLevel",
")",
... | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/grtzMarkerScopes.py#L147-L152 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/grid.py | python | GridCellBoolEditor_IsTrueValue | (*args, **kwargs) | return _grid.GridCellBoolEditor_IsTrueValue(*args, **kwargs) | GridCellBoolEditor_IsTrueValue(String value) -> bool | GridCellBoolEditor_IsTrueValue(String value) -> bool | [
"GridCellBoolEditor_IsTrueValue",
"(",
"String",
"value",
")",
"-",
">",
"bool"
] | def GridCellBoolEditor_IsTrueValue(*args, **kwargs):
"""GridCellBoolEditor_IsTrueValue(String value) -> bool"""
return _grid.GridCellBoolEditor_IsTrueValue(*args, **kwargs) | [
"def",
"GridCellBoolEditor_IsTrueValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridCellBoolEditor_IsTrueValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L477-L479 | |
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/atoms/elementwise/exp.py | python | exp.is_atom_convex | (self) | return True | Is the atom convex? | Is the atom convex? | [
"Is",
"the",
"atom",
"convex?"
] | def is_atom_convex(self) -> bool:
"""Is the atom convex?
"""
return True | [
"def",
"is_atom_convex",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"True"
] | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/elementwise/exp.py#L42-L45 | |
tiny-dnn/tiny-dnn | c0f576f5cb7b35893f62127cb7aec18f77a3bcc5 | third_party/cpplint.py | python | FileInfo.Split | (self) | return (project,) + os.path.splitext(rest) | Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension). | Splits the file into the directory, basename, and extension. | [
"Splits",
"the",
"file",
"into",
"the",
"directory",
"basename",
"and",
"extension",
"."
] | def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest) | [
"def",
"Split",
"(",
"self",
")",
":",
"googlename",
"=",
"self",
".",
"RepositoryName",
"(",
")",
"project",
",",
"rest",
"=",
"os",
".",
"path",
".",
"split",
"(",
"googlename",
")",
"return",
"(",
"project",
",",
")",
"+",
"os",
".",
"path",
"."... | https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/cpplint.py#L1324-L1336 | |
TheLegendAli/DeepLab-Context | fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c | scripts/cpp_lint.py | python | _ShouldPrintError | (category, confidence, linenum) | return True | If confidence >= verbose, category passes filter and is not suppressed. | If confidence >= verbose, category passes filter and is not suppressed. | [
"If",
"confidence",
">",
"=",
"verbose",
"category",
"passes",
"filter",
"and",
"is",
"not",
"suppressed",
"."
] | def _ShouldPrintError(category, confidence, linenum):
"""If confidence >= verbose, category passes filter and is not suppressed."""
# There are three ways we might decide not to print an error message:
# a "NOLINT(category)" comment appears in the source,
# the verbosity level isn't high enough, or the filters filter it out.
if IsErrorSuppressedByNolint(category, linenum):
return False
if confidence < _cpplint_state.verbose_level:
return False
is_filtered = False
for one_filter in _Filters():
if one_filter.startswith('-'):
if category.startswith(one_filter[1:]):
is_filtered = True
elif one_filter.startswith('+'):
if category.startswith(one_filter[1:]):
is_filtered = False
else:
assert False # should have been checked for in SetFilter.
if is_filtered:
return False
return True | [
"def",
"_ShouldPrintError",
"(",
"category",
",",
"confidence",
",",
"linenum",
")",
":",
"# There are three ways we might decide not to print an error message:",
"# a \"NOLINT(category)\" comment appears in the source,",
"# the verbosity level isn't high enough, or the filters filter it out... | https://github.com/TheLegendAli/DeepLab-Context/blob/fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c/scripts/cpp_lint.py#L961-L985 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/physics/ert/ertModelling.py | python | ERTModellingReference.mixedBC | (self, boundary, userData) | Apply mixed boundary conditions. | Apply mixed boundary conditions. | [
"Apply",
"mixed",
"boundary",
"conditions",
"."
] | def mixedBC(self, boundary, userData):
"""Apply mixed boundary conditions."""
if boundary.marker() != pg.core.MARKER_BOUND_MIXED:
return 0
sourcePos = pg.center(userData['sourcePos'])
k = userData['k']
r1 = boundary.center() - sourcePos
# Mirror on surface at depth=0
r2 = boundary.center() - pg.RVector3(1.0, -1.0, 1.0) * sourcePos
r1A = r1.abs()
r2A = r2.abs()
rho = 1.
if self.resistivity is not None:
rho = self.resistivity[boundary.leftCell().id()]
n = boundary.norm()
if r1A > 1e-12 and r2A > 1e-12:
# see mod-dc-2d example for robin like BC and the negative sign
if (pg.math.besselK0(r1A * k) + pg.math.besselK0(r2A * k)) > 1e-12:
return k / rho * (r1.dot(n) / r1A * pg.math.besselK1(r1A * k) +
r2.dot(n) / r2A * pg.math.besselK1(r2A * k))\
/ (pg.math.besselK0(r1A * k) +
pg.math.besselK0(r2A * k))
else:
return 0.
else:
return 0. | [
"def",
"mixedBC",
"(",
"self",
",",
"boundary",
",",
"userData",
")",
":",
"if",
"boundary",
".",
"marker",
"(",
")",
"!=",
"pg",
".",
"core",
".",
"MARKER_BOUND_MIXED",
":",
"return",
"0",
"sourcePos",
"=",
"pg",
".",
"center",
"(",
"userData",
"[",
... | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/ert/ertModelling.py#L394-L427 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/managers.py | python | SingleBlockManager._blklocs | (self) | return None | compat with BlockManager | compat with BlockManager | [
"compat",
"with",
"BlockManager"
] | def _blklocs(self):
""" compat with BlockManager """
return None | [
"def",
"_blklocs",
"(",
"self",
")",
":",
"return",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/managers.py#L1534-L1536 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/io/idl.py | python | _read_tagdesc | (f) | return tagdesc | Function to read in a tag descriptor | Function to read in a tag descriptor | [
"Function",
"to",
"read",
"in",
"a",
"tag",
"descriptor"
] | def _read_tagdesc(f):
'''Function to read in a tag descriptor'''
tagdesc = {'offset': _read_long(f)}
if tagdesc['offset'] == -1:
tagdesc['offset'] = _read_uint64(f)
tagdesc['typecode'] = _read_long(f)
tagflags = _read_long(f)
tagdesc['array'] = tagflags & 4 == 4
tagdesc['structure'] = tagflags & 32 == 32
tagdesc['scalar'] = tagdesc['typecode'] in DTYPE_DICT
# Assume '10'x is scalar
return tagdesc | [
"def",
"_read_tagdesc",
"(",
"f",
")",
":",
"tagdesc",
"=",
"{",
"'offset'",
":",
"_read_long",
"(",
"f",
")",
"}",
"if",
"tagdesc",
"[",
"'offset'",
"]",
"==",
"-",
"1",
":",
"tagdesc",
"[",
"'offset'",
"]",
"=",
"_read_uint64",
"(",
"f",
")",
"ta... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/io/idl.py#L558-L574 | |
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ivy_transrel.py | python | frame_update | (update,in_scope,sig) | return (updated,and_clauses(clauses,Clauses([],dfns)),pre) | Modify an update so all symbols in "in_scope" are on the
update list, preserving semantics. | Modify an update so all symbols in "in_scope" are on the
update list, preserving semantics. | [
"Modify",
"an",
"update",
"so",
"all",
"symbols",
"in",
"in_scope",
"are",
"on",
"the",
"update",
"list",
"preserving",
"semantics",
"."
] | def frame_update(update,in_scope,sig):
""" Modify an update so all symbols in "in_scope" are on the
update list, preserving semantics.
"""
updated,clauses,pre = update
moded = set(updated)
dfns = []
for sym in in_scope:
if sym not in moded:
updated.append(sym)
dfns.append(frame_def(sym,new))
return (updated,and_clauses(clauses,Clauses([],dfns)),pre) | [
"def",
"frame_update",
"(",
"update",
",",
"in_scope",
",",
"sig",
")",
":",
"updated",
",",
"clauses",
",",
"pre",
"=",
"update",
"moded",
"=",
"set",
"(",
"updated",
")",
"dfns",
"=",
"[",
"]",
"for",
"sym",
"in",
"in_scope",
":",
"if",
"sym",
"n... | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_transrel.py#L165-L176 | |
nileshkulkarni/csm | 0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc | csm/utils/transformations.py | python | is_same_quaternion | (q0, q1) | return numpy.allclose(q0, q1) or numpy.allclose(q0, -q1) | Return True if two quaternions are equal. | Return True if two quaternions are equal. | [
"Return",
"True",
"if",
"two",
"quaternions",
"are",
"equal",
"."
] | def is_same_quaternion(q0, q1):
"""Return True if two quaternions are equal."""
q0 = numpy.array(q0)
q1 = numpy.array(q1)
return numpy.allclose(q0, q1) or numpy.allclose(q0, -q1) | [
"def",
"is_same_quaternion",
"(",
"q0",
",",
"q1",
")",
":",
"q0",
"=",
"numpy",
".",
"array",
"(",
"q0",
")",
"q1",
"=",
"numpy",
".",
"array",
"(",
"q1",
")",
"return",
"numpy",
".",
"allclose",
"(",
"q0",
",",
"q1",
")",
"or",
"numpy",
".",
... | https://github.com/nileshkulkarni/csm/blob/0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc/csm/utils/transformations.py#L1886-L1890 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/models/rnn/translate/data_utils.py | python | initialize_vocabulary | (vocabulary_path) | Initialize vocabulary from file.
We assume the vocabulary is stored one-item-per-line, so a file:
dog
cat
will result in a vocabulary {"dog": 0, "cat": 1}, and this function will
also return the reversed-vocabulary ["dog", "cat"].
Args:
vocabulary_path: path to the file containing the vocabulary.
Returns:
a pair: the vocabulary (a dictionary mapping string to integers), and
the reversed vocabulary (a list, which reverses the vocabulary mapping).
Raises:
ValueError: if the provided vocabulary_path does not exist. | Initialize vocabulary from file. | [
"Initialize",
"vocabulary",
"from",
"file",
"."
] | def initialize_vocabulary(vocabulary_path):
"""Initialize vocabulary from file.
We assume the vocabulary is stored one-item-per-line, so a file:
dog
cat
will result in a vocabulary {"dog": 0, "cat": 1}, and this function will
also return the reversed-vocabulary ["dog", "cat"].
Args:
vocabulary_path: path to the file containing the vocabulary.
Returns:
a pair: the vocabulary (a dictionary mapping string to integers), and
the reversed vocabulary (a list, which reverses the vocabulary mapping).
Raises:
ValueError: if the provided vocabulary_path does not exist.
"""
if gfile.Exists(vocabulary_path):
rev_vocab = []
with gfile.GFile(vocabulary_path, mode="rb") as f:
rev_vocab.extend(f.readlines())
rev_vocab = [line.strip() for line in rev_vocab]
vocab = dict([(x, y) for (y, x) in enumerate(rev_vocab)])
return vocab, rev_vocab
else:
raise ValueError("Vocabulary file %s not found.", vocabulary_path) | [
"def",
"initialize_vocabulary",
"(",
"vocabulary_path",
")",
":",
"if",
"gfile",
".",
"Exists",
"(",
"vocabulary_path",
")",
":",
"rev_vocab",
"=",
"[",
"]",
"with",
"gfile",
".",
"GFile",
"(",
"vocabulary_path",
",",
"mode",
"=",
"\"rb\"",
")",
"as",
"f",... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/models/rnn/translate/data_utils.py#L155-L182 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/client/session.py | python | _FetchHandler.fetches | (self) | return self._final_fetches | Return the unique names of tensors to fetch.
Returns:
A list of strings. | Return the unique names of tensors to fetch. | [
"Return",
"the",
"unique",
"names",
"of",
"tensors",
"to",
"fetch",
"."
] | def fetches(self):
"""Return the unique names of tensors to fetch.
Returns:
A list of strings.
"""
return self._final_fetches | [
"def",
"fetches",
"(",
"self",
")",
":",
"return",
"self",
".",
"_final_fetches"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/client/session.py#L507-L513 | |
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | src/third_party/protobuf/python/google/protobuf/descriptor.py | python | _NestedDescriptorBase.CopyToProto | (self, proto) | Copies this to the matching proto in descriptor_pb2.
Args:
proto: An empty proto instance from descriptor_pb2.
Raises:
Error: If self couldnt be serialized, due to to few constructor arguments. | Copies this to the matching proto in descriptor_pb2. | [
"Copies",
"this",
"to",
"the",
"matching",
"proto",
"in",
"descriptor_pb2",
"."
] | def CopyToProto(self, proto):
"""Copies this to the matching proto in descriptor_pb2.
Args:
proto: An empty proto instance from descriptor_pb2.
Raises:
Error: If self couldnt be serialized, due to to few constructor arguments.
"""
if (self.file is not None and
self._serialized_start is not None and
self._serialized_end is not None):
proto.ParseFromString(self.file.serialized_pb[
self._serialized_start:self._serialized_end])
else:
raise Error('Descriptor does not contain serialization.') | [
"def",
"CopyToProto",
"(",
"self",
",",
"proto",
")",
":",
"if",
"(",
"self",
".",
"file",
"is",
"not",
"None",
"and",
"self",
".",
"_serialized_start",
"is",
"not",
"None",
"and",
"self",
".",
"_serialized_end",
"is",
"not",
"None",
")",
":",
"proto",... | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/descriptor.py#L181-L196 | ||
android/app-bundle-samples | 437afcd38743663c43c56db60145699a438afcb5 | PlayAssetDelivery/BundletoolScriptSample/add_packs.py | python | purge_subdirs | (directory: str, pattern: str) | Purge the subdirectories inside a directory that match the given pattern. | Purge the subdirectories inside a directory that match the given pattern. | [
"Purge",
"the",
"subdirectories",
"inside",
"a",
"directory",
"that",
"match",
"the",
"given",
"pattern",
"."
] | def purge_subdirs(directory: str, pattern: str) -> None:
"""Purge the subdirectories inside a directory that match the given pattern."""
for root_dir, subdirs, _ in os.walk(directory):
for filename in fnmatch.filter(subdirs, pattern):
try:
shutil.rmtree(os.path.join(root_dir, filename))
except FileNotFoundError as e:
print(
"Error while deleting {filename}: {e}".format(
filename=filename, e=e),
file=sys.stderr) | [
"def",
"purge_subdirs",
"(",
"directory",
":",
"str",
",",
"pattern",
":",
"str",
")",
"->",
"None",
":",
"for",
"root_dir",
",",
"subdirs",
",",
"_",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"for",
"filename",
"in",
"fnmatch",
".",
"filt... | https://github.com/android/app-bundle-samples/blob/437afcd38743663c43c56db60145699a438afcb5/PlayAssetDelivery/BundletoolScriptSample/add_packs.py#L206-L216 | ||
OGRECave/ogre-next | 287307980e6de8910f04f3cc0994451b075071fd | Tools/BlenderExport/ogremeshesexporter.py | python | OgrePackageImporter.importPackage | (self) | return | Tries to import ogrepkg.
Tries to import ogrepkg with the PYTHONPATH based
on the optional constructor argument and the contents
of Blender's registry entry for "OgrePackage".
Raises an ImportError on failure. | Tries to import ogrepkg.
Tries to import ogrepkg with the PYTHONPATH based
on the optional constructor argument and the contents
of Blender's registry entry for "OgrePackage".
Raises an ImportError on failure. | [
"Tries",
"to",
"import",
"ogrepkg",
".",
"Tries",
"to",
"import",
"ogrepkg",
"with",
"the",
"PYTHONPATH",
"based",
"on",
"the",
"optional",
"constructor",
"argument",
"and",
"the",
"contents",
"of",
"Blender",
"s",
"registry",
"entry",
"for",
"OgrePackage",
".... | def importPackage(self):
"""Tries to import ogrepkg.
Tries to import ogrepkg with the PYTHONPATH based
on the optional constructor argument and the contents
of Blender's registry entry for "OgrePackage".
Raises an ImportError on failure.
"""
if not self.packagePath:
# load registry if packagePath is not given to constructor.
self._loadRegistry()
if self.packagePath:
# append patckagePath to PYTHONPATH
sys.path.append(self.packagePath)
# try importing ogrepkg
import ogrepkg #raises ImportError on failure
return | [
"def",
"importPackage",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"packagePath",
":",
"# load registry if packagePath is not given to constructor.",
"self",
".",
"_loadRegistry",
"(",
")",
"if",
"self",
".",
"packagePath",
":",
"# append patckagePath to PYTHONPAT... | https://github.com/OGRECave/ogre-next/blob/287307980e6de8910f04f3cc0994451b075071fd/Tools/BlenderExport/ogremeshesexporter.py#L59-L75 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/ircbot.py | python | SingleServerIRCBot._on_nick | (self, c, e) | [Internal] | [Internal] | [
"[",
"Internal",
"]"
] | def _on_nick(self, c, e):
"""[Internal]"""
before = nm_to_n(e.source())
after = e.target()
for ch in self.channels.values():
if ch.has_user(before):
ch.change_nick(before, after) | [
"def",
"_on_nick",
"(",
"self",
",",
"c",
",",
"e",
")",
":",
"before",
"=",
"nm_to_n",
"(",
"e",
".",
"source",
"(",
")",
")",
"after",
"=",
"e",
".",
"target",
"(",
")",
"for",
"ch",
"in",
"self",
".",
"channels",
".",
"values",
"(",
")",
"... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/ircbot.py#L159-L165 | ||
shader-slang/slang | b8982fcf43b86c1e39dcc3dd19bff2821633eda6 | external/vulkan/registry/vkconventions.py | python | VulkanConventions.unified_flag_refpages | (self) | return False | Return True if Flags/FlagBits refpages are unified, False if
they're separate. | Return True if Flags/FlagBits refpages are unified, False if
they're separate. | [
"Return",
"True",
"if",
"Flags",
"/",
"FlagBits",
"refpages",
"are",
"unified",
"False",
"if",
"they",
"re",
"separate",
"."
] | def unified_flag_refpages(self):
"""Return True if Flags/FlagBits refpages are unified, False if
they're separate.
"""
return False | [
"def",
"unified_flag_refpages",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/shader-slang/slang/blob/b8982fcf43b86c1e39dcc3dd19bff2821633eda6/external/vulkan/registry/vkconventions.py#L197-L201 | |
bulletphysics/bullet3 | f0f2a952e146f016096db6f85cf0c44ed75b0b9a | examples/pybullet/gym/pybullet_envs/minitaur/envs_v2/env_wrappers/walking_wrapper.py | python | _setup_controller | (robot: Any) | return controller | Creates the controller. | Creates the controller. | [
"Creates",
"the",
"controller",
"."
] | def _setup_controller(robot: Any) -> locomotion_controller.LocomotionController:
"""Creates the controller."""
desired_speed = (0, 0)
desired_twisting_speed = 0
gait_generator = openloop_gait_generator.OpenloopGaitGenerator(
robot,
stance_duration=_STANCE_DURATION_SECONDS,
duty_factor=_DUTY_FACTOR,
initial_leg_phase=_INIT_PHASE_FULL_CYCLE)
state_estimator = com_velocity_estimator.COMVelocityEstimator(robot)
sw_controller = raibert_swing_leg_controller.RaibertSwingLegController(
robot,
gait_generator,
state_estimator,
desired_speed=desired_speed,
desired_twisting_speed=desired_twisting_speed,
desired_height=_BODY_HEIGHT,
)
st_controller = torque_stance_leg_controller.TorqueStanceLegController(
robot,
gait_generator,
state_estimator,
desired_speed=desired_speed,
desired_twisting_speed=desired_twisting_speed,
desired_body_height=_BODY_HEIGHT,
body_mass=215 / 9.8,
body_inertia=(0.07335, 0, 0, 0, 0.25068, 0, 0, 0, 0.25447),
)
controller = locomotion_controller.LocomotionController(
robot=robot,
gait_generator=gait_generator,
state_estimator=state_estimator,
swing_leg_controller=sw_controller,
stance_leg_controller=st_controller,
clock=robot.GetTimeSinceReset)
return controller | [
"def",
"_setup_controller",
"(",
"robot",
":",
"Any",
")",
"->",
"locomotion_controller",
".",
"LocomotionController",
":",
"desired_speed",
"=",
"(",
"0",
",",
"0",
")",
"desired_twisting_speed",
"=",
"0",
"gait_generator",
"=",
"openloop_gait_generator",
".",
"O... | https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs_v2/env_wrappers/walking_wrapper.py#L25-L62 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/distributions/python/ops/normal_conjugate_posteriors.py | python | normal_conjugates_known_scale_predictive | (prior, scale, s, n) | return normal.Normal(
loc=(prior.loc/scale0_2 + s/scale_2) * scalep_2,
scale=math_ops.sqrt(scalep_2 + scale_2)) | Posterior predictive Normal distribution w. conjugate prior on the mean.
This model assumes that `n` observations (with sum `s`) come from a
Normal with unknown mean `loc` (described by the Normal `prior`)
and known variance `scale**2`. The "known scale predictive"
is the distribution of new observations, conditioned on the existing
observations and our prior.
Accepts a prior Normal distribution object, having parameters
`loc0` and `scale0`, as well as known `scale` values of the predictive
distribution(s) (also assumed Normal),
and statistical estimates `s` (the sum(s) of the observations) and
`n` (the number(s) of observations).
Calculates the Normal distribution(s) `p(x | sigma**2)`:
```
p(x | sigma**2) = int N(x | mu, sigma**2)N(mu | prior.loc, prior.scale**2) dmu
= N(x | prior.loc, 1 / (sigma**2 + prior.scale**2))
```
Returns the predictive posterior distribution object, with parameters
`(loc', scale'**2)`, where:
```
sigma_n**2 = 1/(1/sigma0**2 + n/sigma**2),
mu' = (mu0/sigma0**2 + s/sigma**2) * sigma_n**2.
sigma'**2 = sigma_n**2 + sigma**2,
```
Distribution parameters from `prior`, as well as `scale`, `s`, and `n`.
will broadcast in the case of multidimensional sets of parameters.
Args:
prior: `Normal` object of type `dtype`:
the prior distribution having parameters `(loc0, scale0)`.
scale: tensor of type `dtype`, taking values `scale > 0`.
The known stddev parameter(s).
s: Tensor of type `dtype`. The sum(s) of observations.
n: Tensor of type `int`. The number(s) of observations.
Returns:
A new Normal predictive distribution object.
Raises:
TypeError: if dtype of `s` does not match `dtype`, or `prior` is not a
Normal object. | Posterior predictive Normal distribution w. conjugate prior on the mean. | [
"Posterior",
"predictive",
"Normal",
"distribution",
"w",
".",
"conjugate",
"prior",
"on",
"the",
"mean",
"."
] | def normal_conjugates_known_scale_predictive(prior, scale, s, n):
"""Posterior predictive Normal distribution w. conjugate prior on the mean.
This model assumes that `n` observations (with sum `s`) come from a
Normal with unknown mean `loc` (described by the Normal `prior`)
and known variance `scale**2`. The "known scale predictive"
is the distribution of new observations, conditioned on the existing
observations and our prior.
Accepts a prior Normal distribution object, having parameters
`loc0` and `scale0`, as well as known `scale` values of the predictive
distribution(s) (also assumed Normal),
and statistical estimates `s` (the sum(s) of the observations) and
`n` (the number(s) of observations).
Calculates the Normal distribution(s) `p(x | sigma**2)`:
```
p(x | sigma**2) = int N(x | mu, sigma**2)N(mu | prior.loc, prior.scale**2) dmu
= N(x | prior.loc, 1 / (sigma**2 + prior.scale**2))
```
Returns the predictive posterior distribution object, with parameters
`(loc', scale'**2)`, where:
```
sigma_n**2 = 1/(1/sigma0**2 + n/sigma**2),
mu' = (mu0/sigma0**2 + s/sigma**2) * sigma_n**2.
sigma'**2 = sigma_n**2 + sigma**2,
```
Distribution parameters from `prior`, as well as `scale`, `s`, and `n`.
will broadcast in the case of multidimensional sets of parameters.
Args:
prior: `Normal` object of type `dtype`:
the prior distribution having parameters `(loc0, scale0)`.
scale: tensor of type `dtype`, taking values `scale > 0`.
The known stddev parameter(s).
s: Tensor of type `dtype`. The sum(s) of observations.
n: Tensor of type `int`. The number(s) of observations.
Returns:
A new Normal predictive distribution object.
Raises:
TypeError: if dtype of `s` does not match `dtype`, or `prior` is not a
Normal object.
"""
if not isinstance(prior, normal.Normal):
raise TypeError("Expected prior to be an instance of type Normal")
if s.dtype != prior.dtype:
raise TypeError(
"Observation sum s.dtype does not match prior dtype: %s vs. %s"
% (s.dtype, prior.dtype))
n = math_ops.cast(n, prior.dtype)
scale0_2 = math_ops.square(prior.scale)
scale_2 = math_ops.square(scale)
scalep_2 = 1.0/(1/scale0_2 + n/scale_2)
return normal.Normal(
loc=(prior.loc/scale0_2 + s/scale_2) * scalep_2,
scale=math_ops.sqrt(scalep_2 + scale_2)) | [
"def",
"normal_conjugates_known_scale_predictive",
"(",
"prior",
",",
"scale",
",",
"s",
",",
"n",
")",
":",
"if",
"not",
"isinstance",
"(",
"prior",
",",
"normal",
".",
"Normal",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected prior to be an instance of type Nor... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/normal_conjugate_posteriors.py#L84-L147 | |
zeakey/DeepSkeleton | dc70170f8fd2ec8ca1157484ce66129981104486 | scripts/cpp_lint.py | python | CleansedLines._CollapseStrings | (elided) | return elided | Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings. | Collapses strings and chars on a line to simple "" or '' blocks. | [
"Collapses",
"strings",
"and",
"chars",
"on",
"a",
"line",
"to",
"simple",
"or",
"blocks",
"."
] | def _CollapseStrings(elided):
"""Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
"""
if not _RE_PATTERN_INCLUDE.match(elided):
# Remove escaped characters first to make quote/single quote collapsing
# basic. Things that look like escaped characters shouldn't occur
# outside of strings and chars.
elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
return elided | [
"def",
"_CollapseStrings",
"(",
"elided",
")",
":",
"if",
"not",
"_RE_PATTERN_INCLUDE",
".",
"match",
"(",
"elided",
")",
":",
"# Remove escaped characters first to make quote/single quote collapsing",
"# basic. Things that look like escaped characters shouldn't occur",
"# outside... | https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/scripts/cpp_lint.py#L1209-L1227 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/polybond/lmpsdata.py | python | Lmpsmolecule.bondtoparticle | (self,particle,atomid,newid,newcharge) | Bonds molecule to particle. Particle is a particlesurface object.
Moves the molecule's atoms bonded to the particle to the particle's position.
Alters the atomtype of the molecule's atoms bonded to the particle to newid.
Alters the charge of the molecule's atoms bonded to the particle to newcharge
Because bonds have formed between the molecule's atoms and the particle's atoms,
atoms with atomid on the molecule need to be removed otherwise the molecule's atoms will have to many bonds.
self.deleteatoms will take care of deleting the atoms atomid and
atoms down the polymer chain in the direction away from the molecule/particle bond.
Now remove the bonded particle atoms from the particle surface becaused the bonded molecule atoms
have replaced those particle atoms and their bonds with the rest of the particle.
Newid must be a string. Atomid can now be a list or an integer.
The list is a list of atom's id values and the single integer is atom's atomtype | Bonds molecule to particle. Particle is a particlesurface object.
Moves the molecule's atoms bonded to the particle to the particle's position.
Alters the atomtype of the molecule's atoms bonded to the particle to newid.
Alters the charge of the molecule's atoms bonded to the particle to newcharge
Because bonds have formed between the molecule's atoms and the particle's atoms,
atoms with atomid on the molecule need to be removed otherwise the molecule's atoms will have to many bonds.
self.deleteatoms will take care of deleting the atoms atomid and
atoms down the polymer chain in the direction away from the molecule/particle bond.
Now remove the bonded particle atoms from the particle surface becaused the bonded molecule atoms
have replaced those particle atoms and their bonds with the rest of the particle.
Newid must be a string. Atomid can now be a list or an integer.
The list is a list of atom's id values and the single integer is atom's atomtype | [
"Bonds",
"molecule",
"to",
"particle",
".",
"Particle",
"is",
"a",
"particlesurface",
"object",
".",
"Moves",
"the",
"molecule",
"s",
"atoms",
"bonded",
"to",
"the",
"particle",
"to",
"the",
"particle",
"s",
"position",
".",
"Alters",
"the",
"atomtype",
"of"... | def bondtoparticle(self,particle,atomid,newid,newcharge):
"""Bonds molecule to particle. Particle is a particlesurface object.
Moves the molecule's atoms bonded to the particle to the particle's position.
Alters the atomtype of the molecule's atoms bonded to the particle to newid.
Alters the charge of the molecule's atoms bonded to the particle to newcharge
Because bonds have formed between the molecule's atoms and the particle's atoms,
atoms with atomid on the molecule need to be removed otherwise the molecule's atoms will have to many bonds.
self.deleteatoms will take care of deleting the atoms atomid and
atoms down the polymer chain in the direction away from the molecule/particle bond.
Now remove the bonded particle atoms from the particle surface becaused the bonded molecule atoms
have replaced those particle atoms and their bonds with the rest of the particle.
Newid must be a string. Atomid can now be a list or an integer.
The list is a list of atom's id values and the single integer is atom's atomtype"""
#moves the molecule's atoms bonded to the particle to the particle's position
#need to do this step first before the atom id's and row indexes get out of sync
#which will occur after atoms get deleted.
print 'modifying the bonded molecules atom information'
for i in range(len(self.bondinginformation)):
#patom=particle.getsurfatom(self.bondinginformation[i][1])
#if self.atomtype=='molecular':#3-5->x,y,z[molecular]
# for j in range(3,6):
# self.modifyatom(self.bondinginformation[i][0]+1,j,patom[j])#uses the atomid here
#elif self.atomtype=='full':#4-6->x,y,z[full]
# for j in range(4,7):
# self.modifyatom(self.bondinginformation[i][0]+1,j,patom[j])#uses the atomid here
#alters the atomtype to newid of the molecule's atoms bonded to the particle.
self.modifyatom(self.bondinginformation[i][0]+1,2,newid) #uses the atomid here
if self.atomtype=='full':
# Alters the charge of the molecule's atoms bonded to the particle to newcharge
self.modifyatom(self.bondinginformation[i][0]+1,3,newcharge)
#This is a separate loop so atom id's and row indexes for previous steps wont get out of sync
#create atomnumbers to begin deletion process.
atomnumbers=[]
for i in range(len(self.bondinginformation)):
atomnumbers.append(self.bondinginformation[i][0]+1)#using actual atomnumbers rather than the row index
#Call algorithm to find all atoms bonded to atomnumbers in the direction of atomid.
#Than delete those atoms and all molecule structures which contain those atoms.
self.deleteatoms(atomnumbers,atomid)
print 'beginning deletion process of the surface atoms for which the molecule atoms have replaced'
#Goes through the bondinginformation and superficially removes the surfaceatom
for i in range(len(self.bondinginformation)):
particle.removesurfatom(self.bondinginformation[i][1]) | [
"def",
"bondtoparticle",
"(",
"self",
",",
"particle",
",",
"atomid",
",",
"newid",
",",
"newcharge",
")",
":",
"#moves the molecule's atoms bonded to the particle to the particle's position",
"#need to do this step first before the atom id's and row indexes get out of sync ",
"#whic... | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/polybond/lmpsdata.py#L1868-L1912 | ||
Yelp/MOE | 5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c | moe/optimal_learning/python/python_version/covariance.py | python | SquareExponential.num_hyperparameters | (self) | return self._hyperparameters.size | Return the number of hyperparameters of this covariance function. | Return the number of hyperparameters of this covariance function. | [
"Return",
"the",
"number",
"of",
"hyperparameters",
"of",
"this",
"covariance",
"function",
"."
] | def num_hyperparameters(self):
"""Return the number of hyperparameters of this covariance function."""
return self._hyperparameters.size | [
"def",
"num_hyperparameters",
"(",
"self",
")",
":",
"return",
"self",
".",
"_hyperparameters",
".",
"size"
] | https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/python_version/covariance.py#L55-L57 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/ma/core.py | python | _DomainGreaterEqual.__init__ | (self, critical_value) | DomainGreaterEqual(v)(x) = true where x < v | DomainGreaterEqual(v)(x) = true where x < v | [
"DomainGreaterEqual",
"(",
"v",
")",
"(",
"x",
")",
"=",
"true",
"where",
"x",
"<",
"v"
] | def __init__(self, critical_value):
"DomainGreaterEqual(v)(x) = true where x < v"
self.critical_value = critical_value | [
"def",
"__init__",
"(",
"self",
",",
"critical_value",
")",
":",
"self",
".",
"critical_value",
"=",
"critical_value"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/core.py#L881-L883 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/timedeltas.py | python | TimedeltaArray._add_delta | (self, delta) | return type(self)._from_sequence(new_values, freq="infer") | Add a timedelta-like, Tick, or TimedeltaIndex-like object
to self, yielding a new TimedeltaArray.
Parameters
----------
other : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : TimedeltaArray | Add a timedelta-like, Tick, or TimedeltaIndex-like object
to self, yielding a new TimedeltaArray. | [
"Add",
"a",
"timedelta",
"-",
"like",
"Tick",
"or",
"TimedeltaIndex",
"-",
"like",
"object",
"to",
"self",
"yielding",
"a",
"new",
"TimedeltaArray",
"."
] | def _add_delta(self, delta):
"""
Add a timedelta-like, Tick, or TimedeltaIndex-like object
to self, yielding a new TimedeltaArray.
Parameters
----------
other : {timedelta, np.timedelta64, Tick,
TimedeltaIndex, ndarray[timedelta64]}
Returns
-------
result : TimedeltaArray
"""
new_values = super()._add_delta(delta)
return type(self)._from_sequence(new_values, freq="infer") | [
"def",
"_add_delta",
"(",
"self",
",",
"delta",
")",
":",
"new_values",
"=",
"super",
"(",
")",
".",
"_add_delta",
"(",
"delta",
")",
"return",
"type",
"(",
"self",
")",
".",
"_from_sequence",
"(",
"new_values",
",",
"freq",
"=",
"\"infer\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/timedeltas.py#L402-L417 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/lib2to3/patcomp.py | python | PatternCompiler.__init__ | (self, grammar_file=_PATTERN_GRAMMAR_FILE) | Initializer.
Takes an optional alternative filename for the pattern grammar. | Initializer. | [
"Initializer",
"."
] | def __init__(self, grammar_file=_PATTERN_GRAMMAR_FILE):
"""Initializer.
Takes an optional alternative filename for the pattern grammar.
"""
self.grammar = driver.load_grammar(grammar_file)
self.syms = pygram.Symbols(self.grammar)
self.pygrammar = pygram.python_grammar
self.pysyms = pygram.python_symbols
self.driver = driver.Driver(self.grammar, convert=pattern_convert) | [
"def",
"__init__",
"(",
"self",
",",
"grammar_file",
"=",
"_PATTERN_GRAMMAR_FILE",
")",
":",
"self",
".",
"grammar",
"=",
"driver",
".",
"load_grammar",
"(",
"grammar_file",
")",
"self",
".",
"syms",
"=",
"pygram",
".",
"Symbols",
"(",
"self",
".",
"gramma... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/lib2to3/patcomp.py#L44-L53 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/data_flow_ops.py | python | QueueBase.size | (self, name=None) | Compute the number of elements in this queue.
Args:
name: A name for the operation (optional).
Returns:
A scalar tensor containing the number of elements in this queue. | Compute the number of elements in this queue. | [
"Compute",
"the",
"number",
"of",
"elements",
"in",
"this",
"queue",
"."
] | def size(self, name=None):
"""Compute the number of elements in this queue.
Args:
name: A name for the operation (optional).
Returns:
A scalar tensor containing the number of elements in this queue.
"""
if name is None:
name = "%s_Size" % self._name
if self._queue_ref.dtype == _dtypes.resource:
return gen_data_flow_ops._queue_size_v2(self._queue_ref, name=name)
else:
return gen_data_flow_ops._queue_size(self._queue_ref, name=name) | [
"def",
"size",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"\"%s_Size\"",
"%",
"self",
".",
"_name",
"if",
"self",
".",
"_queue_ref",
".",
"dtype",
"==",
"_dtypes",
".",
"resource",
":",
"return",
... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/data_flow_ops.py#L576-L590 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/contrib/onnx/onnx2mx/_op_translations.py | python | _tan | (attrs, inputs, proto_obj) | return 'tan', attrs, inputs | Elementwise tan of input array. | Elementwise tan of input array. | [
"Elementwise",
"tan",
"of",
"input",
"array",
"."
] | def _tan(attrs, inputs, proto_obj):
"""Elementwise tan of input array."""
return 'tan', attrs, inputs | [
"def",
"_tan",
"(",
"attrs",
",",
"inputs",
",",
"proto_obj",
")",
":",
"return",
"'tan'",
",",
"attrs",
",",
"inputs"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L594-L596 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py | python | _NNTPBase.capabilities | (self) | return resp, caps | Process a CAPABILITIES command. Not supported by all servers.
Return:
- resp: server response if successful
- caps: a dictionary mapping capability names to lists of tokens
(for example {'VERSION': ['2'], 'OVER': [], LIST: ['ACTIVE', 'HEADERS'] }) | Process a CAPABILITIES command. Not supported by all servers.
Return:
- resp: server response if successful
- caps: a dictionary mapping capability names to lists of tokens
(for example {'VERSION': ['2'], 'OVER': [], LIST: ['ACTIVE', 'HEADERS'] }) | [
"Process",
"a",
"CAPABILITIES",
"command",
".",
"Not",
"supported",
"by",
"all",
"servers",
".",
"Return",
":",
"-",
"resp",
":",
"server",
"response",
"if",
"successful",
"-",
"caps",
":",
"a",
"dictionary",
"mapping",
"capability",
"names",
"to",
"lists",
... | def capabilities(self):
"""Process a CAPABILITIES command. Not supported by all servers.
Return:
- resp: server response if successful
- caps: a dictionary mapping capability names to lists of tokens
(for example {'VERSION': ['2'], 'OVER': [], LIST: ['ACTIVE', 'HEADERS'] })
"""
caps = {}
resp, lines = self._longcmdstring("CAPABILITIES")
for line in lines:
name, *tokens = line.split()
caps[name] = tokens
return resp, caps | [
"def",
"capabilities",
"(",
"self",
")",
":",
"caps",
"=",
"{",
"}",
"resp",
",",
"lines",
"=",
"self",
".",
"_longcmdstring",
"(",
"\"CAPABILITIES\"",
")",
"for",
"line",
"in",
"lines",
":",
"name",
",",
"",
"*",
"tokens",
"=",
"line",
".",
"split",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/nntplib.py#L550-L562 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | mlir/python/mlir/dialects/linalg/opdsl/lang/affine.py | python | AffineBuildState.get_symbol | (self, symname: str) | return pos | Geta a symbol position given a name. | Geta a symbol position given a name. | [
"Geta",
"a",
"symbol",
"position",
"given",
"a",
"name",
"."
] | def get_symbol(self, symname: str) -> int:
"""Geta a symbol position given a name."""
pos = self.all_symbols.get(symname)
if pos is None:
if not self.allow_new_symbols:
raise ValueError(
f"New symbols not allowed in the current affine expression: "
f"Requested '{symname}', Availble: {self.all_symbols}")
pos = len(self.all_symbols)
self.all_symbols[symname] = pos
self.local_symbols[symname] = pos
return pos | [
"def",
"get_symbol",
"(",
"self",
",",
"symname",
":",
"str",
")",
"->",
"int",
":",
"pos",
"=",
"self",
".",
"all_symbols",
".",
"get",
"(",
"symname",
")",
"if",
"pos",
"is",
"None",
":",
"if",
"not",
"self",
".",
"allow_new_symbols",
":",
"raise",... | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/mlir/python/mlir/dialects/linalg/opdsl/lang/affine.py#L113-L124 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftgeoutils/arcs.py | python | isWideAngle | (edge) | return False | Return True if the given edge is an arc with angle > 180 degrees. | Return True if the given edge is an arc with angle > 180 degrees. | [
"Return",
"True",
"if",
"the",
"given",
"edge",
"is",
"an",
"arc",
"with",
"angle",
">",
"180",
"degrees",
"."
] | def isWideAngle(edge):
"""Return True if the given edge is an arc with angle > 180 degrees."""
if geomType(edge) != "Circle":
return False
r = edge.Curve.Radius
total = 2*r*math.pi
if edge.Length > total/2:
return True
return False | [
"def",
"isWideAngle",
"(",
"edge",
")",
":",
"if",
"geomType",
"(",
"edge",
")",
"!=",
"\"Circle\"",
":",
"return",
"False",
"r",
"=",
"edge",
".",
"Curve",
".",
"Radius",
"total",
"=",
"2",
"*",
"r",
"*",
"math",
".",
"pi",
"if",
"edge",
".",
"L... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftgeoutils/arcs.py#L72-L83 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | uCSIsIPAExtensions | (code) | return ret | Check whether the character is part of IPAExtensions UCS
Block | Check whether the character is part of IPAExtensions UCS
Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"IPAExtensions",
"UCS",
"Block"
] | def uCSIsIPAExtensions(code):
"""Check whether the character is part of IPAExtensions UCS
Block """
ret = libxml2mod.xmlUCSIsIPAExtensions(code)
return ret | [
"def",
"uCSIsIPAExtensions",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsIPAExtensions",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1827-L1831 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/msvs.py | python | _generateGUID | (slnfile, name) | return solution | This generates a dummy GUID for the sln file to use. It is
based on the MD5 signatures of the sln filename plus the name of
the project. It basically just needs to be unique, and not
change with each invocation. | This generates a dummy GUID for the sln file to use. It is
based on the MD5 signatures of the sln filename plus the name of
the project. It basically just needs to be unique, and not
change with each invocation. | [
"This",
"generates",
"a",
"dummy",
"GUID",
"for",
"the",
"sln",
"file",
"to",
"use",
".",
"It",
"is",
"based",
"on",
"the",
"MD5",
"signatures",
"of",
"the",
"sln",
"filename",
"plus",
"the",
"name",
"of",
"the",
"project",
".",
"It",
"basically",
"jus... | def _generateGUID(slnfile, name):
"""This generates a dummy GUID for the sln file to use. It is
based on the MD5 signatures of the sln filename plus the name of
the project. It basically just needs to be unique, and not
change with each invocation."""
m = hashlib.md5()
# Normalize the slnfile path to a Windows path (\ separators) so
# the generated file has a consistent GUID even if we generate
# it on a non-Windows platform.
m.update(bytearray(ntpath.normpath(str(slnfile)) + str(name),'utf-8'))
solution = m.hexdigest().upper()
# convert most of the signature to GUID form (discard the rest)
solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}"
return solution | [
"def",
"_generateGUID",
"(",
"slnfile",
",",
"name",
")",
":",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"# Normalize the slnfile path to a Windows path (\\ separators) so",
"# the generated file has a consistent GUID even if we generate",
"# it on a non-Windows platform.",
"m",... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/msvs.py#L85-L98 | |
etternagame/etterna | 8775f74ac9c353320128609d4b4150672e9a6d04 | extern/crashpad/crashpad/build/ios/setup_ios_gn.py | python | GenerateGnBuildRules | (gn_path, root_dir, out_dir, settings) | Generates all template configurations for gn. | Generates all template configurations for gn. | [
"Generates",
"all",
"template",
"configurations",
"for",
"gn",
"."
] | def GenerateGnBuildRules(gn_path, root_dir, out_dir, settings):
'''Generates all template configurations for gn.'''
for config in SUPPORTED_CONFIGS:
for target in SUPPORTED_TARGETS:
build_dir = os.path.join(out_dir, '%s-%s' % (config, target))
generator = GnGenerator(settings, config, target)
generator.CreateGnRules(gn_path, root_dir, build_dir) | [
"def",
"GenerateGnBuildRules",
"(",
"gn_path",
",",
"root_dir",
",",
"out_dir",
",",
"settings",
")",
":",
"for",
"config",
"in",
"SUPPORTED_CONFIGS",
":",
"for",
"target",
"in",
"SUPPORTED_TARGETS",
":",
"build_dir",
"=",
"os",
".",
"path",
".",
"join",
"("... | https://github.com/etternagame/etterna/blob/8775f74ac9c353320128609d4b4150672e9a6d04/extern/crashpad/crashpad/build/ios/setup_ios_gn.py#L274-L280 | ||
funnyzhou/Adaptive_Feeding | 9c78182331d8c0ea28de47226e805776c638d46f | lib/roi_data_layer/minibatch.py | python | _project_im_rois | (im_rois, im_scale_factor) | return rois | Project image RoIs into the rescaled training image. | Project image RoIs into the rescaled training image. | [
"Project",
"image",
"RoIs",
"into",
"the",
"rescaled",
"training",
"image",
"."
] | def _project_im_rois(im_rois, im_scale_factor):
"""Project image RoIs into the rescaled training image."""
rois = im_rois * im_scale_factor
return rois | [
"def",
"_project_im_rois",
"(",
"im_rois",
",",
"im_scale_factor",
")",
":",
"rois",
"=",
"im_rois",
"*",
"im_scale_factor",
"return",
"rois"
] | https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/roi_data_layer/minibatch.py#L153-L156 | |
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/tools/pretty_vcproj.py | python | main | (argv) | return 0 | Main function of this vcproj prettifier. | Main function of this vcproj prettifier. | [
"Main",
"function",
"of",
"this",
"vcproj",
"prettifier",
"."
] | def main(argv):
"""Main function of this vcproj prettifier."""
global ARGUMENTS
ARGUMENTS = argv
# check if we have exactly 1 parameter.
if len(argv) < 2:
print ('Usage: %s "c:\\path\\to\\vcproj.vcproj" [key1=value1] '
'[key2=value2]' % argv[0])
return 1
# Parse the keys
for i in range(2, len(argv)):
(key, value) = argv[i].split('=')
REPLACEMENTS[key] = value
# Open the vcproj and parse the xml.
dom = parse(argv[1])
# First thing we need to do is find the Configuration Node and merge them
# with the vsprops they include.
for configuration_node in GetConfiguationNodes(dom.documentElement):
# Get the property sheets associated with this configuration.
vsprops = configuration_node.getAttribute('InheritedPropertySheets')
# Fix the filenames to be absolute.
vsprops_list = FixFilenames(vsprops.strip().split(';'),
os.path.dirname(argv[1]))
# Extend the list of vsprops with all vsprops contained in the current
# vsprops.
for current_vsprops in vsprops_list:
vsprops_list.extend(GetChildrenVsprops(current_vsprops))
# Now that we have all the vsprops, we need to merge them.
for current_vsprops in vsprops_list:
MergeProperties(configuration_node,
parse(current_vsprops).documentElement)
# Now that everything is merged, we need to cleanup the xml.
CleanupVcproj(dom.documentElement)
# Finally, we use the prett xml function to print the vcproj back to the
# user.
#print dom.toprettyxml(newl="\n")
PrettyPrintNode(dom.documentElement)
return 0 | [
"def",
"main",
"(",
"argv",
")",
":",
"global",
"ARGUMENTS",
"ARGUMENTS",
"=",
"argv",
"# check if we have exactly 1 parameter.",
"if",
"len",
"(",
"argv",
")",
"<",
"2",
":",
"print",
"(",
"'Usage: %s \"c:\\\\path\\\\to\\\\vcproj.vcproj\" [key1=value1] '",
"'[key2=valu... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/tools/pretty_vcproj.py#L279-L325 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | contrib/gizmos/gtk/gizmos.py | python | TreeListCtrl.SetItemHasChildren | (*args, **kwargs) | return _gizmos.TreeListCtrl_SetItemHasChildren(*args, **kwargs) | SetItemHasChildren(self, TreeItemId item, bool has=True) | SetItemHasChildren(self, TreeItemId item, bool has=True) | [
"SetItemHasChildren",
"(",
"self",
"TreeItemId",
"item",
"bool",
"has",
"=",
"True",
")"
] | def SetItemHasChildren(*args, **kwargs):
"""SetItemHasChildren(self, TreeItemId item, bool has=True)"""
return _gizmos.TreeListCtrl_SetItemHasChildren(*args, **kwargs) | [
"def",
"SetItemHasChildren",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gizmos",
".",
"TreeListCtrl_SetItemHasChildren",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/gtk/gizmos.py#L701-L703 | |
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/universe_generation/starsystems.py | python | generate_systems | (pos_list, gsd) | return sys_list | Generates and populates star systems at all positions in specified list. | Generates and populates star systems at all positions in specified list. | [
"Generates",
"and",
"populates",
"star",
"systems",
"at",
"all",
"positions",
"in",
"specified",
"list",
"."
] | def generate_systems(pos_list, gsd):
"""
Generates and populates star systems at all positions in specified list.
"""
sys_list = []
for position in pos_list:
star_type = pick_star_type(gsd.age)
system = fo.create_system(star_type, "", position[0], position[1])
if system == fo.invalid_object():
# create system failed, report an error and try to continue with next position
util.report_error(
"Python generate_systems: create system at position (%f, %f) failed" % (position[0], position[1])
)
continue
sys_list.append(system)
orbits = list(range(fo.sys_get_num_orbits(system)))
if not planets.can_have_planets(star_type, orbits, gsd.planet_density, gsd.shape):
continue
# Try to generate planets in each orbit.
# If after each orbit is tried once there are no planets then
# keep trying until a single planet is placed.
# Except for black hole systems, which can be empty.
at_least_one_planet = False
random.shuffle(orbits)
for orbit in orbits:
if planets.generate_a_planet(system, star_type, orbit, gsd.planet_density, gsd.shape):
at_least_one_planet = True
if at_least_one_planet or can_have_no_planets(star_type):
continue
recursion_limit = 1000
for _, orbit in product(range(recursion_limit), orbits):
if planets.generate_a_planet(system, star_type, orbit, gsd.planet_density, gsd.shape):
break
else:
# Intentionally non-modal. Should be a warning.
print(
(
"Python generate_systems: place planets in system %d at position (%.2f, %.2f) failed"
% (system, position[0], position[1])
),
file=sys.stderr,
)
return sys_list | [
"def",
"generate_systems",
"(",
"pos_list",
",",
"gsd",
")",
":",
"sys_list",
"=",
"[",
"]",
"for",
"position",
"in",
"pos_list",
":",
"star_type",
"=",
"pick_star_type",
"(",
"gsd",
".",
"age",
")",
"system",
"=",
"fo",
".",
"create_system",
"(",
"star_... | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/universe_generation/starsystems.py#L86-L135 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py | python | NeuralNetworkBuilder.add_loop_break | (self, name) | return spec_layer | Add a loop_break layer to the model that terminates the loop that
contains this layer. Must reside in the ``bodyNetwork`` of the loop layer.
Refer to the **LoopBreakLayerParams** message in specification (NeuralNetwork.proto) for more details.
Parameters
----------
name: str
The name of this layer.
See Also
--------
add_loop, add_loop_continue, add_branch | Add a loop_break layer to the model that terminates the loop that
contains this layer. Must reside in the ``bodyNetwork`` of the loop layer.
Refer to the **LoopBreakLayerParams** message in specification (NeuralNetwork.proto) for more details. | [
"Add",
"a",
"loop_break",
"layer",
"to",
"the",
"model",
"that",
"terminates",
"the",
"loop",
"that",
"contains",
"this",
"layer",
".",
"Must",
"reside",
"in",
"the",
"bodyNetwork",
"of",
"the",
"loop",
"layer",
".",
"Refer",
"to",
"the",
"**",
"LoopBreakL... | def add_loop_break(self, name):
"""
Add a loop_break layer to the model that terminates the loop that
contains this layer. Must reside in the ``bodyNetwork`` of the loop layer.
Refer to the **LoopBreakLayerParams** message in specification (NeuralNetwork.proto) for more details.
Parameters
----------
name: str
The name of this layer.
See Also
--------
add_loop, add_loop_continue, add_branch
"""
spec_layer = self.nn_spec.layers.add()
spec_layer.name = name
spec_layer.loopBreak.MergeFromString(b"")
return spec_layer | [
"def",
"add_loop_break",
"(",
"self",
",",
"name",
")",
":",
"spec_layer",
"=",
"self",
".",
"nn_spec",
".",
"layers",
".",
"add",
"(",
")",
"spec_layer",
".",
"name",
"=",
"name",
"spec_layer",
".",
"loopBreak",
".",
"MergeFromString",
"(",
"b\"\"",
")"... | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/builder.py#L5728-L5747 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/maximum-xor-of-two-numbers-in-an-array.py | python | Solution2.findMaximumXOR | (self, nums) | return result | :type nums: List[int]
:rtype: int | :type nums: List[int]
:rtype: int | [
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def findMaximumXOR(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
trie = Trie(max(nums).bit_length())
result = 0
for num in nums:
trie.insert(num)
result = max(result, trie.query(num))
return result | [
"def",
"findMaximumXOR",
"(",
"self",
",",
"nums",
")",
":",
"trie",
"=",
"Trie",
"(",
"max",
"(",
"nums",
")",
".",
"bit_length",
"(",
")",
")",
"result",
"=",
"0",
"for",
"num",
"in",
"nums",
":",
"trie",
".",
"insert",
"(",
"num",
")",
"result... | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-xor-of-two-numbers-in-an-array.py#L55-L65 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | RegionIterator.GetH | (*args, **kwargs) | return _gdi_.RegionIterator_GetH(*args, **kwargs) | GetH(self) -> int | GetH(self) -> int | [
"GetH",
"(",
"self",
")",
"-",
">",
"int"
] | def GetH(*args, **kwargs):
"""GetH(self) -> int"""
return _gdi_.RegionIterator_GetH(*args, **kwargs) | [
"def",
"GetH",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"RegionIterator_GetH",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L1686-L1688 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | PickerBase.GetInternalMargin | (*args, **kwargs) | return _controls_.PickerBase_GetInternalMargin(*args, **kwargs) | GetInternalMargin(self) -> int
Returns the margin (in pixels) between the picker and the text
control. | GetInternalMargin(self) -> int | [
"GetInternalMargin",
"(",
"self",
")",
"-",
">",
"int"
] | def GetInternalMargin(*args, **kwargs):
"""
GetInternalMargin(self) -> int
Returns the margin (in pixels) between the picker and the text
control.
"""
return _controls_.PickerBase_GetInternalMargin(*args, **kwargs) | [
"def",
"GetInternalMargin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"PickerBase_GetInternalMargin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L6747-L6754 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/boost_1_66_0/libs/mpl/preprocessed/boost_mpl_preprocess.py | python | create_more_container_files | (sourceDir, suffix, maxElements, containers, containers2) | Creates additional files for the individual MPL-containers. | Creates additional files for the individual MPL-containers. | [
"Creates",
"additional",
"files",
"for",
"the",
"individual",
"MPL",
"-",
"containers",
"."
] | def create_more_container_files(sourceDir, suffix, maxElements, containers, containers2):
"""Creates additional files for the individual MPL-containers."""
# Create files for each MPL-container with 20 to 'maxElements' elements
# which will be used during generation.
for container in containers:
for i in range(20, maxElements, 10):
# Create copy of "template"-file.
newFile = os.path.join( sourceDir, container, container + str(i+10) + suffix )
shutil.copyfile( os.path.join( sourceDir, container, container + "20" + suffix ), newFile )
# Adjust copy of "template"-file accordingly.
for line in fileinput.input( newFile, inplace=1, mode="rU" ):
line = re.sub(r'20', '%TWENTY%', line.rstrip())
line = re.sub(r'11', '%ELEVEN%', line.rstrip())
line = re.sub(r'10(?![0-9])', '%TEN%', line.rstrip())
line = re.sub(r'%TWENTY%', re.escape(str(i+10)), line.rstrip())
line = re.sub(r'%ELEVEN%', re.escape(str(i + 1)), line.rstrip())
line = re.sub(r'%TEN%', re.escape(str(i)), line.rstrip())
print(line)
for container in containers2:
for i in range(20, maxElements, 10):
# Create copy of "template"-file.
newFile = os.path.join( sourceDir, container, container + str(i+10) + "_c" + suffix )
shutil.copyfile( os.path.join( sourceDir, container, container + "20_c" + suffix ), newFile )
# Adjust copy of "template"-file accordingly.
for line in fileinput.input( newFile, inplace=1, mode="rU" ):
line = re.sub(r'20', '%TWENTY%', line.rstrip())
line = re.sub(r'11', '%ELEVEN%', line.rstrip())
line = re.sub(r'10(?![0-9])', '%TEN%', line.rstrip())
line = re.sub(r'%TWENTY%', re.escape(str(i+10)), line.rstrip())
line = re.sub(r'%ELEVEN%', re.escape(str(i + 1)), line.rstrip())
line = re.sub(r'%TEN%', re.escape(str(i)), line.rstrip())
print(line) | [
"def",
"create_more_container_files",
"(",
"sourceDir",
",",
"suffix",
",",
"maxElements",
",",
"containers",
",",
"containers2",
")",
":",
"# Create files for each MPL-container with 20 to 'maxElements' elements",
"# which will be used during generation.",
"for",
"container",
"i... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/boost_1_66_0/libs/mpl/preprocessed/boost_mpl_preprocess.py#L21-L53 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/importlib/metadata.py | python | files | (distribution_name) | return distribution(distribution_name).files | Return a list of files for the named package.
:param distribution_name: The name of the distribution package to query.
:return: List of files composing the distribution. | Return a list of files for the named package. | [
"Return",
"a",
"list",
"of",
"files",
"for",
"the",
"named",
"package",
"."
] | def files(distribution_name):
"""Return a list of files for the named package.
:param distribution_name: The name of the distribution package to query.
:return: List of files composing the distribution.
"""
return distribution(distribution_name).files | [
"def",
"files",
"(",
"distribution_name",
")",
":",
"return",
"distribution",
"(",
"distribution_name",
")",
".",
"files"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/importlib/metadata.py#L579-L585 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/tools/gyp/pylib/gyp/generator/android.py | python | AndroidMkWriter.NormalizeLdFlags | (self, ld_flags) | return clean_ldflags | Clean up ldflags from gyp file.
Remove any ldflags that contain android_top_dir.
Args:
ld_flags: ldflags from gyp files.
Returns:
clean ldflags | Clean up ldflags from gyp file.
Remove any ldflags that contain android_top_dir. | [
"Clean",
"up",
"ldflags",
"from",
"gyp",
"file",
".",
"Remove",
"any",
"ldflags",
"that",
"contain",
"android_top_dir",
"."
] | def NormalizeLdFlags(self, ld_flags):
""" Clean up ldflags from gyp file.
Remove any ldflags that contain android_top_dir.
Args:
ld_flags: ldflags from gyp files.
Returns:
clean ldflags
"""
clean_ldflags = []
for flag in ld_flags:
if self.android_top_dir in flag:
continue
clean_ldflags.append(flag)
return clean_ldflags | [
"def",
"NormalizeLdFlags",
"(",
"self",
",",
"ld_flags",
")",
":",
"clean_ldflags",
"=",
"[",
"]",
"for",
"flag",
"in",
"ld_flags",
":",
"if",
"self",
".",
"android_top_dir",
"in",
"flag",
":",
"continue",
"clean_ldflags",
".",
"append",
"(",
"flag",
")",
... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/android.py#L686-L701 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py2/google/protobuf/message.py | python | Message.HasExtension | (self, extension_handle) | Checks if a certain extension is present for this message.
Extensions are retrieved using the :attr:`Extensions` mapping (if present).
Args:
extension_handle: The handle for the extension to check.
Returns:
bool: Whether the extension is present for this message.
Raises:
KeyError: if the extension is repeated. Similar to repeated fields,
there is no separate notion of presence: a "not present" repeated
extension is an empty list. | Checks if a certain extension is present for this message. | [
"Checks",
"if",
"a",
"certain",
"extension",
"is",
"present",
"for",
"this",
"message",
"."
] | def HasExtension(self, extension_handle):
"""Checks if a certain extension is present for this message.
Extensions are retrieved using the :attr:`Extensions` mapping (if present).
Args:
extension_handle: The handle for the extension to check.
Returns:
bool: Whether the extension is present for this message.
Raises:
KeyError: if the extension is repeated. Similar to repeated fields,
there is no separate notion of presence: a "not present" repeated
extension is an empty list.
"""
raise NotImplementedError | [
"def",
"HasExtension",
"(",
"self",
",",
"extension_handle",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/message.py#L311-L327 | ||
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | util/gem5art/artifact/gem5art/artifact/_artifactdb.py | python | ArtifactMongoDB.__contains__ | (self, key: Union[UUID, str]) | return bool(count > 0) | Key can be a UUID or a string. Returns true if item in DB | Key can be a UUID or a string. Returns true if item in DB | [
"Key",
"can",
"be",
"a",
"UUID",
"or",
"a",
"string",
".",
"Returns",
"true",
"if",
"item",
"in",
"DB"
] | def __contains__(self, key: Union[UUID, str]) -> bool:
"""Key can be a UUID or a string. Returns true if item in DB"""
if isinstance(key, UUID):
count = self.artifacts.count_documents({"_id": key}, limit=1)
else:
# This is a hash. Count the number of matches
count = self.artifacts.count_documents({"hash": key}, limit=1)
return bool(count > 0) | [
"def",
"__contains__",
"(",
"self",
",",
"key",
":",
"Union",
"[",
"UUID",
",",
"str",
"]",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"key",
",",
"UUID",
")",
":",
"count",
"=",
"self",
".",
"artifacts",
".",
"count_documents",
"(",
"{",
"\"... | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/util/gem5art/artifact/gem5art/artifact/_artifactdb.py#L159-L167 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/protobuf/py2/google/protobuf/internal/containers.py | python | RepeatedScalarFieldContainer.__setitem__ | (self, key, value) | Sets the item on the specified position. | Sets the item on the specified position. | [
"Sets",
"the",
"item",
"on",
"the",
"specified",
"position",
"."
] | def __setitem__(self, key, value):
"""Sets the item on the specified position."""
if isinstance(key, slice): # PY3
if key.step is not None:
raise ValueError('Extended slices not supported')
self.__setslice__(key.start, key.stop, value)
else:
self._values[key] = self._type_checker.CheckValue(value)
self._message_listener.Modified() | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"slice",
")",
":",
"# PY3",
"if",
"key",
".",
"step",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Extended slices not supported'",
")"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/containers.py#L308-L316 | ||
su2code/SU2 | 72b2fa977b64b9683a388920f05298a40d39e5c5 | SU2_PY/SU2/io/filelock.py | python | filelock.acquire | (self) | Acquire the lock, if possible. If the lock is in use, it check again
every `wait` seconds. It does this until it either gets the lock or
exceeds `timeout` number of seconds, in which case it throws
an exception. | Acquire the lock, if possible. If the lock is in use, it check again
every `wait` seconds. It does this until it either gets the lock or
exceeds `timeout` number of seconds, in which case it throws
an exception. | [
"Acquire",
"the",
"lock",
"if",
"possible",
".",
"If",
"the",
"lock",
"is",
"in",
"use",
"it",
"check",
"again",
"every",
"wait",
"seconds",
".",
"It",
"does",
"this",
"until",
"it",
"either",
"gets",
"the",
"lock",
"or",
"exceeds",
"timeout",
"number",
... | def acquire(self):
""" Acquire the lock, if possible. If the lock is in use, it check again
every `wait` seconds. It does this until it either gets the lock or
exceeds `timeout` number of seconds, in which case it throws
an exception.
"""
start_time = time.time()
while True:
try:
self.fd = os.open(self.lockfile, os.O_CREAT|os.O_EXCL|os.O_RDWR)
break;
except OSError as e:
if e.errno != errno.EEXIST:
raise
if (time.time() - start_time) >= self.timeout:
raise FileLockException("FileLock timeout occured for %s" % self.lockfile)
delay = self.delay*( 1. + 0.2*random() )
time.sleep(delay)
self.is_locked = True | [
"def",
"acquire",
"(",
"self",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"try",
":",
"self",
".",
"fd",
"=",
"os",
".",
"open",
"(",
"self",
".",
"lockfile",
",",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_... | https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/SU2/io/filelock.py#L64-L82 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/spec.py | python | AbstractFileSystem._open | (
self,
path,
mode="rb",
block_size=None,
autocommit=True,
cache_options=None,
**kwargs
) | return AbstractBufferedFile(
self,
path,
mode,
block_size,
autocommit,
cache_options=cache_options,
**kwargs
) | Return raw bytes-mode file-like from the file-system | Return raw bytes-mode file-like from the file-system | [
"Return",
"raw",
"bytes",
"-",
"mode",
"file",
"-",
"like",
"from",
"the",
"file",
"-",
"system"
] | def _open(
self,
path,
mode="rb",
block_size=None,
autocommit=True,
cache_options=None,
**kwargs
):
"""Return raw bytes-mode file-like from the file-system"""
return AbstractBufferedFile(
self,
path,
mode,
block_size,
autocommit,
cache_options=cache_options,
**kwargs
) | [
"def",
"_open",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"\"rb\"",
",",
"block_size",
"=",
"None",
",",
"autocommit",
"=",
"True",
",",
"cache_options",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"AbstractBufferedFile",
"(",
"self",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/spec.py#L713-L731 | |
google/usd_from_gltf | 6d288cce8b68744494a226574ae1d7ba6a9c46eb | tools/ufgbatch/ufgcommon/diff.py | python | find_exe | (name) | return None | Find executable in path. | Find executable in path. | [
"Find",
"executable",
"in",
"path",
"."
] | def find_exe(name):
"""Find executable in path."""
paths = os.environ['PATH'].split(os.pathsep)
for path in paths:
exe_path = get_exe_path(os.path.join(path, name))
if exe_path:
return exe_path
return None | [
"def",
"find_exe",
"(",
"name",
")",
":",
"paths",
"=",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"for",
"path",
"in",
"paths",
":",
"exe_path",
"=",
"get_exe_path",
"(",
"os",
".",
"path",
".",
"join",... | https://github.com/google/usd_from_gltf/blob/6d288cce8b68744494a226574ae1d7ba6a9c46eb/tools/ufgbatch/ufgcommon/diff.py#L43-L50 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/sparse_ops.py | python | serialize_sparse_v2 | (sp_input, out_type=dtypes.string, name=None) | return gen_sparse_ops.serialize_sparse(
sp_input.indices,
sp_input.values,
sp_input.dense_shape,
name=name,
out_type=out_type) | Serialize a `SparseTensor` into a 3-vector (1-D `Tensor`) object.
Args:
sp_input: The input `SparseTensor`.
out_type: The `dtype` to use for serialization.
name: A name prefix for the returned tensors (optional).
Returns:
A 3-vector (1-D `Tensor`), with each column representing the serialized
`SparseTensor`'s indices, values, and shape (respectively).
Raises:
TypeError: If `sp_input` is not a `SparseTensor`. | Serialize a `SparseTensor` into a 3-vector (1-D `Tensor`) object. | [
"Serialize",
"a",
"SparseTensor",
"into",
"a",
"3",
"-",
"vector",
"(",
"1",
"-",
"D",
"Tensor",
")",
"object",
"."
] | def serialize_sparse_v2(sp_input, out_type=dtypes.string, name=None):
"""Serialize a `SparseTensor` into a 3-vector (1-D `Tensor`) object.
Args:
sp_input: The input `SparseTensor`.
out_type: The `dtype` to use for serialization.
name: A name prefix for the returned tensors (optional).
Returns:
A 3-vector (1-D `Tensor`), with each column representing the serialized
`SparseTensor`'s indices, values, and shape (respectively).
Raises:
TypeError: If `sp_input` is not a `SparseTensor`.
"""
sp_input = _convert_to_sparse_tensor(sp_input)
return gen_sparse_ops.serialize_sparse(
sp_input.indices,
sp_input.values,
sp_input.dense_shape,
name=name,
out_type=out_type) | [
"def",
"serialize_sparse_v2",
"(",
"sp_input",
",",
"out_type",
"=",
"dtypes",
".",
"string",
",",
"name",
"=",
"None",
")",
":",
"sp_input",
"=",
"_convert_to_sparse_tensor",
"(",
"sp_input",
")",
"return",
"gen_sparse_ops",
".",
"serialize_sparse",
"(",
"sp_in... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/sparse_ops.py#L2181-L2203 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/MimeWriter.py | python | MimeWriter.flushheaders | (self) | Writes out and forgets all headers accumulated so far.
This is useful if you don't need a body part at all; for example,
for a subpart of type message/rfc822 that's (mis)used to store some
header-like information. | Writes out and forgets all headers accumulated so far. | [
"Writes",
"out",
"and",
"forgets",
"all",
"headers",
"accumulated",
"so",
"far",
"."
] | def flushheaders(self):
"""Writes out and forgets all headers accumulated so far.
This is useful if you don't need a body part at all; for example,
for a subpart of type message/rfc822 that's (mis)used to store some
header-like information.
"""
self._fp.writelines(self._headers)
self._headers = [] | [
"def",
"flushheaders",
"(",
"self",
")",
":",
"self",
".",
"_fp",
".",
"writelines",
"(",
"self",
".",
"_headers",
")",
"self",
".",
"_headers",
"=",
"[",
"]"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/MimeWriter.py#L117-L126 | ||
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | mlir/utils/spirv/gen_spirv_dialect.py | python | update_td_op_definitions | (path, instructions, docs, filter_list,
inst_category, capability_mapping, settings) | Updates SPIRVOps.td with newly generated op definition.
Arguments:
- path: path to SPIRVOps.td
- instructions: SPIR-V JSON grammar for all instructions
- docs: SPIR-V HTML doc for all instructions
- filter_list: a list containing new opnames to include
- capability_mapping: mapping from duplicated capability symbols to the
canonicalized symbol chosen for SPIRVBase.td.
Returns:
- A string containing all the TableGen op definitions | Updates SPIRVOps.td with newly generated op definition. | [
"Updates",
"SPIRVOps",
".",
"td",
"with",
"newly",
"generated",
"op",
"definition",
"."
] | def update_td_op_definitions(path, instructions, docs, filter_list,
inst_category, capability_mapping, settings):
"""Updates SPIRVOps.td with newly generated op definition.
Arguments:
- path: path to SPIRVOps.td
- instructions: SPIR-V JSON grammar for all instructions
- docs: SPIR-V HTML doc for all instructions
- filter_list: a list containing new opnames to include
- capability_mapping: mapping from duplicated capability symbols to the
canonicalized symbol chosen for SPIRVBase.td.
Returns:
- A string containing all the TableGen op definitions
"""
with open(path, 'r') as f:
content = f.read()
# Split the file into chunks, each containing one op.
ops = content.split(AUTOGEN_OP_DEF_SEPARATOR)
header = ops[0]
footer = ops[-1]
ops = ops[1:-1]
# For each existing op, extract the manually-written sections out to retain
# them when re-generating the ops. Also append the existing ops to filter
# list.
name_op_map = {} # Map from opname to its existing ODS definition
op_info_dict = {}
for op in ops:
info_dict = extract_td_op_info(op)
opname = info_dict['opname']
name_op_map[opname] = op
op_info_dict[opname] = info_dict
filter_list.append(opname)
filter_list = sorted(list(set(filter_list)))
op_defs = []
if settings.gen_ocl_ops:
fix_opname = lambda src: src.replace('OCL','').lower()
else:
fix_opname = lambda src: src
for opname in filter_list:
# Find the grammar spec for this op
try:
fixed_opname = fix_opname(opname)
instruction = next(
inst for inst in instructions if inst['opname'] == fixed_opname)
op_defs.append(
get_op_definition(
instruction, opname, docs[fixed_opname],
op_info_dict.get(opname, {'inst_category': inst_category}),
capability_mapping, settings))
except StopIteration:
# This is an op added by us; use the existing ODS definition.
op_defs.append(name_op_map[opname])
# Substitute the old op definitions
op_defs = [header] + op_defs + [footer]
content = AUTOGEN_OP_DEF_SEPARATOR.join(op_defs)
with open(path, 'w') as f:
f.write(content) | [
"def",
"update_td_op_definitions",
"(",
"path",
",",
"instructions",
",",
"docs",
",",
"filter_list",
",",
"inst_category",
",",
"capability_mapping",
",",
"settings",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"content",
"=",
... | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/mlir/utils/spirv/gen_spirv_dialect.py#L923-L988 | ||
facebook/openr | ed38bdfd6bf290084bfab4821b59f83e7b59315d | openr/py/openr/cli/utils/utils.py | python | sprint_prefixes_db_delta | (
global_prefixes_db: Dict,
prefix_db: openr_types.PrefixDatabase,
key: Optional[str] = None,
) | return strs | given serialzied prefixes for a single node, output the delta
between those prefixes and global prefixes snapshot
prefix could be entire prefix DB or per prefix key
entire prefix DB: prefix:<node name>
per prefix key: prefix:<node name>:<area>:<[IP addr/prefix len]
:global_prefixes_db map(node, set([str])): global prefixes
:prefix_db openr_types.PrefixDatabase: latest from kv store
:return [str]: the array of prefix strings | given serialzied prefixes for a single node, output the delta
between those prefixes and global prefixes snapshot | [
"given",
"serialzied",
"prefixes",
"for",
"a",
"single",
"node",
"output",
"the",
"delta",
"between",
"those",
"prefixes",
"and",
"global",
"prefixes",
"snapshot"
] | def sprint_prefixes_db_delta(
global_prefixes_db: Dict,
prefix_db: openr_types.PrefixDatabase,
key: Optional[str] = None,
):
"""given serialzied prefixes for a single node, output the delta
between those prefixes and global prefixes snapshot
prefix could be entire prefix DB or per prefix key
entire prefix DB: prefix:<node name>
per prefix key: prefix:<node name>:<area>:<[IP addr/prefix len]
:global_prefixes_db map(node, set([str])): global prefixes
:prefix_db openr_types.PrefixDatabase: latest from kv store
:return [str]: the array of prefix strings
"""
this_node_name = prefix_db.thisNodeName
prev_prefixes = global_prefixes_db.get(this_node_name, set())
added_prefixes = set()
removed_prefixes = set()
cur_prefixes = set()
for prefix_entry in prefix_db.prefixEntries:
cur_prefixes.add(ipnetwork.sprint_prefix(prefix_entry.prefix))
# per prefix key format contains only one key, it can be an 'add' or 'delete'
if key and re.match(Consts.PER_PREFIX_KEY_REGEX, key):
if prefix_db.deletePrefix:
removed_prefixes = cur_prefixes
else:
added_prefixes = cur_prefixes
else:
added_prefixes = cur_prefixes - prev_prefixes
removed_prefixes = prev_prefixes - cur_prefixes
strs = ["+ {}".format(prefix) for prefix in added_prefixes]
strs.extend(["- {}".format(prefix) for prefix in removed_prefixes])
return strs | [
"def",
"sprint_prefixes_db_delta",
"(",
"global_prefixes_db",
":",
"Dict",
",",
"prefix_db",
":",
"openr_types",
".",
"PrefixDatabase",
",",
"key",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
":",
"this_node_name",
"=",
"prefix_db",
".",
"thisNode... | https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/utils/utils.py#L1142-L1183 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/third_party/Python/module/pexpect-2.4/pexpect.py | python | spawn.__fork_pty | (self) | return pid, parent_fd | This implements a substitute for the forkpty system call. This
should be more portable than the pty.fork() function. Specifically,
this should work on Solaris.
Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
resolve the issue with Python's pty.fork() not supporting Solaris,
particularly ssh. Based on patch to posixmodule.c authored by Noah
Spurrier::
http://mail.python.org/pipermail/python-dev/2003-May/035281.html | This implements a substitute for the forkpty system call. This
should be more portable than the pty.fork() function. Specifically,
this should work on Solaris. | [
"This",
"implements",
"a",
"substitute",
"for",
"the",
"forkpty",
"system",
"call",
".",
"This",
"should",
"be",
"more",
"portable",
"than",
"the",
"pty",
".",
"fork",
"()",
"function",
".",
"Specifically",
"this",
"should",
"work",
"on",
"Solaris",
"."
] | def __fork_pty(self):
"""This implements a substitute for the forkpty system call. This
should be more portable than the pty.fork() function. Specifically,
this should work on Solaris.
Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
resolve the issue with Python's pty.fork() not supporting Solaris,
particularly ssh. Based on patch to posixmodule.c authored by Noah
Spurrier::
http://mail.python.org/pipermail/python-dev/2003-May/035281.html
"""
parent_fd, child_fd = os.openpty()
if parent_fd < 0 or child_fd < 0:
raise ExceptionPexpect(
"Error! Could not open pty with os.openpty().")
pid = os.fork()
if pid < 0:
raise ExceptionPexpect("Error! Failed os.fork().")
elif pid == 0:
# Child.
os.close(parent_fd)
self.__pty_make_controlling_tty(child_fd)
os.dup2(child_fd, 0)
os.dup2(child_fd, 1)
os.dup2(child_fd, 2)
if child_fd > 2:
os.close(child_fd)
else:
# Parent.
os.close(child_fd)
return pid, parent_fd | [
"def",
"__fork_pty",
"(",
"self",
")",
":",
"parent_fd",
",",
"child_fd",
"=",
"os",
".",
"openpty",
"(",
")",
"if",
"parent_fd",
"<",
"0",
"or",
"child_fd",
"<",
"0",
":",
"raise",
"ExceptionPexpect",
"(",
"\"Error! Could not open pty with os.openpty().\"",
"... | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/third_party/Python/module/pexpect-2.4/pexpect.py#L607-L644 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/command/build_py.py | python | build_py.exclude_data_files | (self, package, src_dir, files) | return list(_unique_everseen(keepers)) | Filter filenames for package's data files in 'src_dir | Filter filenames for package's data files in 'src_dir | [
"Filter",
"filenames",
"for",
"package",
"s",
"data",
"files",
"in",
"src_dir"
] | def exclude_data_files(self, package, src_dir, files):
"""Filter filenames for package's data files in 'src_dir'"""
files = list(files)
patterns = self._get_platform_patterns(
self.exclude_package_data,
package,
src_dir,
)
match_groups = (
fnmatch.filter(files, pattern)
for pattern in patterns
)
# flatten the groups of matches into an iterable of matches
matches = itertools.chain.from_iterable(match_groups)
bad = set(matches)
keepers = (
fn
for fn in files
if fn not in bad
)
# ditch dupes
return list(_unique_everseen(keepers)) | [
"def",
"exclude_data_files",
"(",
"self",
",",
"package",
",",
"src_dir",
",",
"files",
")",
":",
"files",
"=",
"list",
"(",
"files",
")",
"patterns",
"=",
"self",
".",
"_get_platform_patterns",
"(",
"self",
".",
"exclude_package_data",
",",
"package",
",",
... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/command/build_py.py#L196-L217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.