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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/changelog.py | python | Changelog.foreach_version | (self, reverse=False) | Creates a generator for iterating over the versions, dates and content
Versions are stored and iterated in order.
:param reverse: ``bool`` if True then the iteration is reversed
:returns: ``generator`` for iterating over versions, dates and content | Creates a generator for iterating over the versions, dates and content | [
"Creates",
"a",
"generator",
"for",
"iterating",
"over",
"the",
"versions",
"dates",
"and",
"content"
] | def foreach_version(self, reverse=False):
'''
Creates a generator for iterating over the versions, dates and content
Versions are stored and iterated in order.
:param reverse: ``bool`` if True then the iteration is reversed
:returns: ``generator`` for iterating over versions, dates and content
'''
for version in reversed(self.__versions) if reverse else self.__versions:
yield version, self.__dates[version], self.__content[version] | [
"def",
"foreach_version",
"(",
"self",
",",
"reverse",
"=",
"False",
")",
":",
"for",
"version",
"in",
"reversed",
"(",
"self",
".",
"__versions",
")",
"if",
"reverse",
"else",
"self",
".",
"__versions",
":",
"yield",
"version",
",",
"self",
".",
"__date... | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/changelog.py#L430-L440 | ||
LisaAnne/lisa-caffe-public | 49b8643ddef23a4f6120017968de30c45e693f59 | scripts/cpp_lint.py | python | _Filters | () | return _cpplint_state.filters | Returns the module's list of output filters, as a list. | Returns the module's list of output filters, as a list. | [
"Returns",
"the",
"module",
"s",
"list",
"of",
"output",
"filters",
"as",
"a",
"list",
"."
] | def _Filters():
"""Returns the module's list of output filters, as a list."""
return _cpplint_state.filters | [
"def",
"_Filters",
"(",
")",
":",
"return",
"_cpplint_state",
".",
"filters"
] | https://github.com/LisaAnne/lisa-caffe-public/blob/49b8643ddef23a4f6120017968de30c45e693f59/scripts/cpp_lint.py#L792-L794 | |
taichi-dev/taichi | 973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6 | python/taichi/ui/imgui.py | python | Gui.text | (self, text) | Declares a line of text. | Declares a line of text. | [
"Declares",
"a",
"line",
"of",
"text",
"."
] | def text(self, text):
"""Declares a line of text.
"""
self.gui.text(text) | [
"def",
"text",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"gui",
".",
"text",
"(",
"text",
")"
] | https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/ui/imgui.py#L51-L54 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/apiclient/googleapiclient/discovery.py | python | Resource._set_dynamic_attr | (self, attr_name, value) | Sets an instance attribute and tracks it in a list of dynamic attributes.
Args:
attr_name: string; The name of the attribute to be set
value: The value being set on the object and tracked in the dynamic cache. | Sets an instance attribute and tracks it in a list of dynamic attributes. | [
"Sets",
"an",
"instance",
"attribute",
"and",
"tracks",
"it",
"in",
"a",
"list",
"of",
"dynamic",
"attributes",
"."
] | def _set_dynamic_attr(self, attr_name, value):
"""Sets an instance attribute and tracks it in a list of dynamic attributes.
Args:
attr_name: string; The name of the attribute to be set
value: The value being set on the object and tracked in the dynamic cache.
"""
self._dynamic_attrs.append(attr_name)
self.__dict__[attr_name] = value | [
"def",
"_set_dynamic_attr",
"(",
"self",
",",
"attr_name",
",",
"value",
")",
":",
"self",
".",
"_dynamic_attrs",
".",
"append",
"(",
"attr_name",
")",
"self",
".",
"__dict__",
"[",
"attr_name",
"]",
"=",
"value"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/apiclient/googleapiclient/discovery.py#L915-L923 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/flatnotebook.py | python | PageContainer.CanFitToScreen | (self, page) | return True | Returns wheter a tab can fit in the left space in the screen or not.
:param `page`: an integer specifying the page index. | Returns wheter a tab can fit in the left space in the screen or not. | [
"Returns",
"wheter",
"a",
"tab",
"can",
"fit",
"in",
"the",
"left",
"space",
"in",
"the",
"screen",
"or",
"not",
"."
] | def CanFitToScreen(self, page):
"""
Returns wheter a tab can fit in the left space in the screen or not.
:param `page`: an integer specifying the page index.
"""
# Incase the from is greater than page,
# we need to reset the self._nFrom, so in order
# to force the caller to do so, we return false
if self._nFrom > page:
return False
agwStyle = self.GetParent().GetAGWWindowStyleFlag()
render = self._mgr.GetRenderer(agwStyle)
vTabInfo = render.NumberTabsCanFit(self)
if page - self._nFrom >= len(vTabInfo):
return False
return True | [
"def",
"CanFitToScreen",
"(",
"self",
",",
"page",
")",
":",
"# Incase the from is greater than page,",
"# we need to reset the self._nFrom, so in order",
"# to force the caller to do so, we return false",
"if",
"self",
".",
"_nFrom",
">",
"page",
":",
"return",
"False",
"agw... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatnotebook.py#L6210-L6231 | |
yyzybb537/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | third_party/boost.context/tools/build/src/build/targets.py | python | MainTarget.__select_alternatives | (self, property_set_, debug) | return best | Returns the best viable alternative for this property_set
See the documentation for selection rules.
# TODO: shouldn't this be 'alternative' (singular)? | Returns the best viable alternative for this property_set
See the documentation for selection rules.
# TODO: shouldn't this be 'alternative' (singular)? | [
"Returns",
"the",
"best",
"viable",
"alternative",
"for",
"this",
"property_set",
"See",
"the",
"documentation",
"for",
"selection",
"rules",
".",
"#",
"TODO",
":",
"shouldn",
"t",
"this",
"be",
"alternative",
"(",
"singular",
")",
"?"
] | def __select_alternatives (self, property_set_, debug):
""" Returns the best viable alternative for this property_set
See the documentation for selection rules.
# TODO: shouldn't this be 'alternative' (singular)?
"""
# When selecting alternatives we have to consider defaults,
# for example:
# lib l : l.cpp : <variant>debug ;
# lib l : l_opt.cpp : <variant>release ;
# won't work unless we add default value <variant>debug.
assert isinstance(property_set_, property_set.PropertySet)
assert isinstance(debug, int) # also matches bools
property_set_ = property_set_.add_defaults ()
# The algorithm: we keep the current best viable alternative.
# When we've got new best viable alternative, we compare it
# with the current one.
best = None
best_properties = None
if len (self.alternatives_) == 0:
return None
if len (self.alternatives_) == 1:
return self.alternatives_ [0]
if debug:
print "Property set for selection:", property_set_
for v in self.alternatives_:
properties = v.match (property_set_, debug)
if properties is not None:
if not best:
best = v
best_properties = properties
else:
if b2.util.set.equal (properties, best_properties):
return None
elif b2.util.set.contains (properties, best_properties):
# Do nothing, this alternative is worse
pass
elif b2.util.set.contains (best_properties, properties):
best = v
best_properties = properties
else:
return None
return best | [
"def",
"__select_alternatives",
"(",
"self",
",",
"property_set_",
",",
"debug",
")",
":",
"# When selecting alternatives we have to consider defaults,",
"# for example:",
"# lib l : l.cpp : <variant>debug ;",
"# lib l : l_opt.cpp : <variant>release ;",
"# won't work unless we add ... | https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/targets.py#L680-L733 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/idlelib/configHandler.py | python | IdleConf.GetSectionList | (self, configSet, configType) | return cfgParser.sections() | Return sections for configSet configType configuration.
configSet must be either 'user' or 'default'
configType must be in self.config_types. | Return sections for configSet configType configuration. | [
"Return",
"sections",
"for",
"configSet",
"configType",
"configuration",
"."
] | def GetSectionList(self, configSet, configType):
"""Return sections for configSet configType configuration.
configSet must be either 'user' or 'default'
configType must be in self.config_types.
"""
if not (configType in self.config_types):
raise InvalidConfigType('Invalid configType specified')
if configSet == 'user':
cfgParser = self.userCfg[configType]
elif configSet == 'default':
cfgParser=self.defaultCfg[configType]
else:
raise InvalidConfigSet('Invalid configSet specified')
return cfgParser.sections() | [
"def",
"GetSectionList",
"(",
"self",
",",
"configSet",
",",
"configType",
")",
":",
"if",
"not",
"(",
"configType",
"in",
"self",
".",
"config_types",
")",
":",
"raise",
"InvalidConfigType",
"(",
"'Invalid configType specified'",
")",
"if",
"configSet",
"==",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/configHandler.py#L266-L280 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/rfc822.py | python | AddrlistClass.getatom | (self, atomends=None) | return ''.join(atomlist) | Parse an RFC 2822 atom.
Optional atomends specifies a different set of end token delimiters
(the default is to use self.atomends). This is used e.g. in
getphraselist() since phrase endings must not include the `.' (which
is legal in phrases). | Parse an RFC 2822 atom. | [
"Parse",
"an",
"RFC",
"2822",
"atom",
"."
] | def getatom(self, atomends=None):
"""Parse an RFC 2822 atom.
Optional atomends specifies a different set of end token delimiters
(the default is to use self.atomends). This is used e.g. in
getphraselist() since phrase endings must not include the `.' (which
is legal in phrases)."""
atomlist = ['']
if atomends is None:
atomends = self.atomends
while self.pos < len(self.field):
if self.field[self.pos] in atomends:
break
else: atomlist.append(self.field[self.pos])
self.pos += 1
return ''.join(atomlist) | [
"def",
"getatom",
"(",
"self",
",",
"atomends",
"=",
"None",
")",
":",
"atomlist",
"=",
"[",
"''",
"]",
"if",
"atomends",
"is",
"None",
":",
"atomends",
"=",
"self",
".",
"atomends",
"while",
"self",
".",
"pos",
"<",
"len",
"(",
"self",
".",
"field... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/rfc822.py#L728-L745 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/contrib/crosstalk/__init__.py | python | Crosstalk.register_funcs | (self, var_type, setter=None, getter=None) | Register setter/getter functions for a given variable type
Args:
var_type: Type of the variable
setter: Lambda function to set value
getter: Lambda function to get value | Register setter/getter functions for a given variable type
Args:
var_type: Type of the variable
setter: Lambda function to set value
getter: Lambda function to get value | [
"Register",
"setter",
"/",
"getter",
"functions",
"for",
"a",
"given",
"variable",
"type",
"Args",
":",
"var_type",
":",
"Type",
"of",
"the",
"variable",
"setter",
":",
"Lambda",
"function",
"to",
"set",
"value",
"getter",
":",
"Lambda",
"function",
"to",
... | def register_funcs(self, var_type, setter=None, getter=None):
'''
Register setter/getter functions for a given variable type
Args:
var_type: Type of the variable
setter: Lambda function to set value
getter: Lambda function to get value
'''
self.funcs[var_type] = _FuncInfo(setter, getter) | [
"def",
"register_funcs",
"(",
"self",
",",
"var_type",
",",
"setter",
"=",
"None",
",",
"getter",
"=",
"None",
")",
":",
"self",
".",
"funcs",
"[",
"var_type",
"]",
"=",
"_FuncInfo",
"(",
"setter",
",",
"getter",
")"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/contrib/crosstalk/__init__.py#L171-L180 | ||
ZhouWeikuan/DouDiZhu | 0d84ff6c0bc54dba6ae37955de9ae9307513dc99 | code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | CursorKind.is_reference | (self) | return conf.lib.clang_isReference(self) | Test if this is a reference kind. | Test if this is a reference kind. | [
"Test",
"if",
"this",
"is",
"a",
"reference",
"kind",
"."
] | def is_reference(self):
"""Test if this is a reference kind."""
return conf.lib.clang_isReference(self) | [
"def",
"is_reference",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isReference",
"(",
"self",
")"
] | https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L636-L638 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/__init__.py | python | Process.cmdline | (self) | return self._proc.cmdline() | The command line this process has been called with. | The command line this process has been called with. | [
"The",
"command",
"line",
"this",
"process",
"has",
"been",
"called",
"with",
"."
] | def cmdline(self):
"""The command line this process has been called with."""
return self._proc.cmdline() | [
"def",
"cmdline",
"(",
"self",
")",
":",
"return",
"self",
".",
"_proc",
".",
"cmdline",
"(",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/psutil/psutil/__init__.py#L549-L551 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | NotificationMessage.SetFlags | (*args, **kwargs) | return _misc_.NotificationMessage_SetFlags(*args, **kwargs) | SetFlags(self, int flags) | SetFlags(self, int flags) | [
"SetFlags",
"(",
"self",
"int",
"flags",
")"
] | def SetFlags(*args, **kwargs):
"""SetFlags(self, int flags)"""
return _misc_.NotificationMessage_SetFlags(*args, **kwargs) | [
"def",
"SetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"NotificationMessage_SetFlags",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L1230-L1232 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | DC.DrawImageLabel | (*args, **kwargs) | return _gdi_.DC_DrawImageLabel(*args, **kwargs) | DrawImageLabel(self, String text, Bitmap image, Rect rect, int alignment=wxALIGN_LEFT|wxALIGN_TOP,
int indexAccel=-1) -> Rect
Draw *text* and an image (which may be ``wx.NullBitmap`` to skip
drawing it) within the specified rectangle, abiding by the alignment
flags. Will additionally emphasize the character at *indexAccel* if
it is not -1. Returns the bounding rectangle. | DrawImageLabel(self, String text, Bitmap image, Rect rect, int alignment=wxALIGN_LEFT|wxALIGN_TOP,
int indexAccel=-1) -> Rect | [
"DrawImageLabel",
"(",
"self",
"String",
"text",
"Bitmap",
"image",
"Rect",
"rect",
"int",
"alignment",
"=",
"wxALIGN_LEFT|wxALIGN_TOP",
"int",
"indexAccel",
"=",
"-",
"1",
")",
"-",
">",
"Rect"
] | def DrawImageLabel(*args, **kwargs):
"""
DrawImageLabel(self, String text, Bitmap image, Rect rect, int alignment=wxALIGN_LEFT|wxALIGN_TOP,
int indexAccel=-1) -> Rect
Draw *text* and an image (which may be ``wx.NullBitmap`` to skip
drawing it) within the specified rectangle, abiding by the alignment
flags. Will additionally emphasize the character at *indexAccel* if
it is not -1. Returns the bounding rectangle.
"""
return _gdi_.DC_DrawImageLabel(*args, **kwargs) | [
"def",
"DrawImageLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_DrawImageLabel",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L3943-L3953 | |
NVIDIA/DALI | bf16cc86ba8f091b145f91962f21fe1b6aff243d | docs/examples/frameworks/mxnet/demo/symbols/vgg.py | python | get_symbol | (num_classes, num_layers=11, batch_norm=False, dtype='float32', **kwargs) | return symbol | Parameters
----------
num_classes : int, default 1000
Number of classification classes.
num_layers : int
Number of layers for the variant of densenet. Options are 11, 13, 16, 19.
batch_norm : bool, default False
Use batch normalization.
dtype: str, float32 or float16
Data precision. | Parameters
----------
num_classes : int, default 1000
Number of classification classes.
num_layers : int
Number of layers for the variant of densenet. Options are 11, 13, 16, 19.
batch_norm : bool, default False
Use batch normalization.
dtype: str, float32 or float16
Data precision. | [
"Parameters",
"----------",
"num_classes",
":",
"int",
"default",
"1000",
"Number",
"of",
"classification",
"classes",
".",
"num_layers",
":",
"int",
"Number",
"of",
"layers",
"for",
"the",
"variant",
"of",
"densenet",
".",
"Options",
"are",
"11",
"13",
"16",
... | def get_symbol(num_classes, num_layers=11, batch_norm=False, dtype='float32', **kwargs):
"""
Parameters
----------
num_classes : int, default 1000
Number of classification classes.
num_layers : int
Number of layers for the variant of densenet. Options are 11, 13, 16, 19.
batch_norm : bool, default False
Use batch normalization.
dtype: str, float32 or float16
Data precision.
"""
vgg_spec = {11: ([1, 1, 2, 2, 2], [64, 128, 256, 512, 512]),
13: ([2, 2, 2, 2, 2], [64, 128, 256, 512, 512]),
16: ([2, 2, 3, 3, 3], [64, 128, 256, 512, 512]),
19: ([2, 2, 4, 4, 4], [64, 128, 256, 512, 512])}
if not vgg_spec.has_key(num_layers):
raise ValueError("Invalide num_layers {}. Possible choices are 11,13,16,19.".format(num_layers))
layers, filters = vgg_spec[num_layers]
data = mx.sym.Variable(name="data")
if dtype == 'float16':
data = mx.sym.Cast(data=data, dtype=np.float16)
feature = get_feature(data, layers, filters, batch_norm)
classifier = get_classifier(feature, num_classes)
if dtype == 'float16':
classifier = mx.sym.Cast(data=classifier, dtype=np.float32)
symbol = mx.sym.SoftmaxOutput(data=classifier, name='softmax')
return symbol | [
"def",
"get_symbol",
"(",
"num_classes",
",",
"num_layers",
"=",
"11",
",",
"batch_norm",
"=",
"False",
",",
"dtype",
"=",
"'float32'",
",",
"*",
"*",
"kwargs",
")",
":",
"vgg_spec",
"=",
"{",
"11",
":",
"(",
"[",
"1",
",",
"1",
",",
"2",
",",
"2... | https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/examples/frameworks/mxnet/demo/symbols/vgg.py#L48-L76 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/distributed/elastic/agent/server/api.py | python | ElasticAgent.run | (self, role: str = DEFAULT_ROLE) | Runs the agent, retrying the worker group on failures up to
``max_restarts``.
Returns:
The result of the execution, containing the return values or
failure details for each worker mapped by the worker's global rank.
Raises:
Exception - any other failures NOT related to worker process | Runs the agent, retrying the worker group on failures up to
``max_restarts``. | [
"Runs",
"the",
"agent",
"retrying",
"the",
"worker",
"group",
"on",
"failures",
"up",
"to",
"max_restarts",
"."
] | def run(self, role: str = DEFAULT_ROLE) -> RunResult:
"""
Runs the agent, retrying the worker group on failures up to
``max_restarts``.
Returns:
The result of the execution, containing the return values or
failure details for each worker mapped by the worker's global rank.
Raises:
Exception - any other failures NOT related to worker process
"""
raise NotImplementedError() | [
"def",
"run",
"(",
"self",
",",
"role",
":",
"str",
"=",
"DEFAULT_ROLE",
")",
"->",
"RunResult",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/agent/server/api.py#L424-L436 | ||
verilog-to-routing/vtr-verilog-to-routing | d9719cf7374821156c3cee31d66991cb85578562 | vpr/scripts/profile/parse_and_plot_detailed.py | python | plot_results | (param_names, param_options, results, params) | Create a directory based on key parameters and date and plot results vs iteration
Each of the parameter in results will receive its own plot, drawn by matplotlib | Create a directory based on key parameters and date and plot results vs iteration | [
"Create",
"a",
"directory",
"based",
"on",
"key",
"parameters",
"and",
"date",
"and",
"plot",
"results",
"vs",
"iteration"
] | def plot_results(param_names, param_options, results, params):
"""Create a directory based on key parameters and date and plot results vs iteration
Each of the parameter in results will receive its own plot, drawn by matplotlib"""
# circuit/run_num where run_num is one before the existing one
directory = params.circuit
if not os.path.isdir(directory):
os.mkdir(directory)
runs = immediate_subdir(directory)
latest_run = 0
if runs:
natural_sort(runs)
latest_run = get_trailing_num(runs[-1])
directory = os.path.join(directory, "run" + str(latest_run + 1))
print(directory)
if not os.path.isdir(directory):
os.mkdir(directory)
with Chdir(directory):
export_results_to_csv(param_names, results, params)
x = results.keys()
y = []
next_figure = True
p = 0
plt.figure()
while p < len(param_names):
print(param_names[p])
if param_options[p]:
nf = True
for option in param_options[p].split():
# stopping has veto power (must all be True to pass)
nf = nf and plot_options(option)
next_figure = nf
if not next_figure:
# y becomes list of lists (for use with stackable plots)
y.append([result[p] for result in results.values()])
p += 1
continue
elif not y:
y = [result[p] for result in results.values()]
lx = x[-1]
ly = y[-1]
plot_method(x, y)
plt.xlabel("iteration")
plt.xlim(xmin=0)
plt.ylabel(param_names[p])
# annotate the last value
annotate_last(lx, ly)
if next_figure:
plt.savefig(param_names[p])
plt.figure()
p += 1
# in case the last figure hasn't been shuffled onto file yet
if not next_figure:
plot_method(x, y)
plt.savefig(param_names[-1]) | [
"def",
"plot_results",
"(",
"param_names",
",",
"param_options",
",",
"results",
",",
"params",
")",
":",
"# circuit/run_num where run_num is one before the existing one",
"directory",
"=",
"params",
".",
"circuit",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",... | https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vpr/scripts/profile/parse_and_plot_detailed.py#L40-L107 | ||
sfzhang15/FaceBoxes | b52cc92f9362d3adc08d54666aeb9ebb62fdb7da | scripts/cpp_lint.py | python | CheckForCopyright | (filename, lines, error) | Logs an error if a Copyright message appears at the top of the file. | Logs an error if a Copyright message appears at the top of the file. | [
"Logs",
"an",
"error",
"if",
"a",
"Copyright",
"message",
"appears",
"at",
"the",
"top",
"of",
"the",
"file",
"."
] | def CheckForCopyright(filename, lines, error):
"""Logs an error if a Copyright message appears at the top of the file."""
# We'll check up to line 10. Don't forget there's a
# dummy line at the front.
for line in xrange(1, min(len(lines), 11)):
if _RE_COPYRIGHT.search(lines[line], re.I):
error(filename, 0, 'legal/copyright', 5,
'Copyright message found. '
'You should not include a copyright line.') | [
"def",
"CheckForCopyright",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"# We'll check up to line 10. Don't forget there's a",
"# dummy line at the front.",
"for",
"line",
"in",
"xrange",
"(",
"1",
",",
"min",
"(",
"len",
"(",
"lines",
")",
",",
"11",
... | https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/scripts/cpp_lint.py#L1372-L1381 | ||
cvxpy/cvxpy | 5165b4fb750dfd237de8659383ef24b4b2e33aaf | cvxpy/utilities/deterministic.py | python | unique_list | (duplicates_list) | return unique | Return unique list preserving the order.
https://stackoverflow.com/a/58666031/1002277 | Return unique list preserving the order.
https://stackoverflow.com/a/58666031/1002277 | [
"Return",
"unique",
"list",
"preserving",
"the",
"order",
".",
"https",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"58666031",
"/",
"1002277"
] | def unique_list(duplicates_list):
"""Return unique list preserving the order.
https://stackoverflow.com/a/58666031/1002277
"""
used = set()
unique = [x for x in duplicates_list
if x not in used and
(used.add(x) or True)]
return unique | [
"def",
"unique_list",
"(",
"duplicates_list",
")",
":",
"used",
"=",
"set",
"(",
")",
"unique",
"=",
"[",
"x",
"for",
"x",
"in",
"duplicates_list",
"if",
"x",
"not",
"in",
"used",
"and",
"(",
"used",
".",
"add",
"(",
"x",
")",
"or",
"True",
")",
... | https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/utilities/deterministic.py#L1-L9 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Fem/ObjectsFem.py | python | makeMaterialSolid | (
doc,
name="MaterialSolid"
) | return obj | makeMaterialSolid(document, [name]):
makes a FEM Material for solid | makeMaterialSolid(document, [name]):
makes a FEM Material for solid | [
"makeMaterialSolid",
"(",
"document",
"[",
"name",
"]",
")",
":",
"makes",
"a",
"FEM",
"Material",
"for",
"solid"
] | def makeMaterialSolid(
doc,
name="MaterialSolid"
):
"""makeMaterialSolid(document, [name]):
makes a FEM Material for solid"""
obj = doc.addObject("App::MaterialObjectPython", name)
from femobjects import material_common
material_common.MaterialCommon(obj)
obj.Category = "Solid"
if FreeCAD.GuiUp:
from femviewprovider import view_material_common
view_material_common.VPMaterialCommon(obj.ViewObject)
return obj | [
"def",
"makeMaterialSolid",
"(",
"doc",
",",
"name",
"=",
"\"MaterialSolid\"",
")",
":",
"obj",
"=",
"doc",
".",
"addObject",
"(",
"\"App::MaterialObjectPython\"",
",",
"name",
")",
"from",
"femobjects",
"import",
"material_common",
"material_common",
".",
"Materi... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/ObjectsFem.py#L476-L489 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/wrappers/framework.py | python | NonInteractiveDebugWrapperSession.on_run_start | (self, request) | return OnRunStartResponse(
OnRunStartAction.DEBUG_RUN,
debug_urls,
debug_ops=watch_opts.debug_ops,
node_name_regex_whitelist=watch_opts.node_name_regex_whitelist,
op_type_regex_whitelist=watch_opts.op_type_regex_whitelist,
tensor_dtype_regex_whitelist=watch_opts.tensor_dtype_regex_whitelist,
tolerate_debug_op_creation_failures=(
watch_opts.tolerate_debug_op_creation_failures)) | See doc of BaseDebugWrapperSession.on_run_start. | See doc of BaseDebugWrapperSession.on_run_start. | [
"See",
"doc",
"of",
"BaseDebugWrapperSession",
".",
"on_run_start",
"."
] | def on_run_start(self, request):
"""See doc of BaseDebugWrapperSession.on_run_start."""
debug_urls, watch_opts = self._prepare_run_watch_config(
request.fetches, request.feed_dict)
return OnRunStartResponse(
OnRunStartAction.DEBUG_RUN,
debug_urls,
debug_ops=watch_opts.debug_ops,
node_name_regex_whitelist=watch_opts.node_name_regex_whitelist,
op_type_regex_whitelist=watch_opts.op_type_regex_whitelist,
tensor_dtype_regex_whitelist=watch_opts.tensor_dtype_regex_whitelist,
tolerate_debug_op_creation_failures=(
watch_opts.tolerate_debug_op_creation_failures)) | [
"def",
"on_run_start",
"(",
"self",
",",
"request",
")",
":",
"debug_urls",
",",
"watch_opts",
"=",
"self",
".",
"_prepare_run_watch_config",
"(",
"request",
".",
"fetches",
",",
"request",
".",
"feed_dict",
")",
"return",
"OnRunStartResponse",
"(",
"OnRunStartA... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/debug/wrappers/framework.py#L945-L959 | |
stitchEm/stitchEm | 0f399501d41ab77933677f2907f41f80ceb704d7 | lib/bindings/samples/server/glfw.py | python | hide_window | (window) | Hides the specified window.
Wrapper for:
void glfwHideWindow(GLFWwindow* window); | Hides the specified window. | [
"Hides",
"the",
"specified",
"window",
"."
] | def hide_window(window):
"""
Hides the specified window.
Wrapper for:
void glfwHideWindow(GLFWwindow* window);
"""
_glfw.glfwHideWindow(window) | [
"def",
"hide_window",
"(",
"window",
")",
":",
"_glfw",
".",
"glfwHideWindow",
"(",
"window",
")"
] | https://github.com/stitchEm/stitchEm/blob/0f399501d41ab77933677f2907f41f80ceb704d7/lib/bindings/samples/server/glfw.py#L1146-L1153 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py | python | Index._reset_identity | (self) | return self | Initializes or resets ``_id`` attribute with new object. | Initializes or resets ``_id`` attribute with new object. | [
"Initializes",
"or",
"resets",
"_id",
"attribute",
"with",
"new",
"object",
"."
] | def _reset_identity(self):
"""
Initializes or resets ``_id`` attribute with new object.
"""
self._id = _Identity()
return self | [
"def",
"_reset_identity",
"(",
"self",
")",
":",
"self",
".",
"_id",
"=",
"_Identity",
"(",
")",
"return",
"self"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py#L592-L597 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/codecs.py | python | StreamReader.__next__ | (self) | Return the next decoded line from the input stream. | Return the next decoded line from the input stream. | [
"Return",
"the",
"next",
"decoded",
"line",
"from",
"the",
"input",
"stream",
"."
] | def __next__(self):
""" Return the next decoded line from the input stream."""
line = self.readline()
if line:
return line
raise StopIteration | [
"def",
"__next__",
"(",
"self",
")",
":",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"if",
"line",
":",
"return",
"line",
"raise",
"StopIteration"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/codecs.py#L642-L648 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/wrappers.py | python | UArrayArg.load_direct | (self, byteoffset) | return self.context.unpack_value(self.builder, self.fe_type, ptr) | Generic load from the given *byteoffset*. load_aligned() is
preferred if possible. | Generic load from the given *byteoffset*. load_aligned() is
preferred if possible. | [
"Generic",
"load",
"from",
"the",
"given",
"*",
"byteoffset",
"*",
".",
"load_aligned",
"()",
"is",
"preferred",
"if",
"possible",
"."
] | def load_direct(self, byteoffset):
"""
Generic load from the given *byteoffset*. load_aligned() is
preferred if possible.
"""
ptr = cgutils.pointer_add(self.builder, self.dataptr, byteoffset)
return self.context.unpack_value(self.builder, self.fe_type, ptr) | [
"def",
"load_direct",
"(",
"self",
",",
"byteoffset",
")",
":",
"ptr",
"=",
"cgutils",
".",
"pointer_add",
"(",
"self",
".",
"builder",
",",
"self",
".",
"dataptr",
",",
"byteoffset",
")",
"return",
"self",
".",
"context",
".",
"unpack_value",
"(",
"self... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/wrappers.py#L267-L273 | |
Z3Prover/z3 | d745d03afdfdf638d66093e2bfbacaf87187f35b | src/api/python/z3/z3.py | python | SortRef.cast | (self, val) | return val | Try to cast `val` as an element of sort `self`.
This method is used in Z3Py to convert Python objects such as integers,
floats, longs and strings into Z3 expressions.
>>> x = Int('x')
>>> RealSort().cast(x)
ToReal(x) | Try to cast `val` as an element of sort `self`. | [
"Try",
"to",
"cast",
"val",
"as",
"an",
"element",
"of",
"sort",
"self",
"."
] | def cast(self, val):
"""Try to cast `val` as an element of sort `self`.
This method is used in Z3Py to convert Python objects such as integers,
floats, longs and strings into Z3 expressions.
>>> x = Int('x')
>>> RealSort().cast(x)
ToReal(x)
"""
if z3_debug():
_z3_assert(is_expr(val), "Z3 expression expected")
_z3_assert(self.eq(val.sort()), "Sort mismatch")
return val | [
"def",
"cast",
"(",
"self",
",",
"val",
")",
":",
"if",
"z3_debug",
"(",
")",
":",
"_z3_assert",
"(",
"is_expr",
"(",
"val",
")",
",",
"\"Z3 expression expected\"",
")",
"_z3_assert",
"(",
"self",
".",
"eq",
"(",
"val",
".",
"sort",
"(",
")",
")",
... | https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L592-L605 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/tracer/function.py | python | traceConf.parseTableJson | (self) | return self.traceSections | Add and match functions to be traced get keys that starts with 'trace | Add and match functions to be traced get keys that starts with 'trace | [
"Add",
"and",
"match",
"functions",
"to",
"be",
"traced",
"get",
"keys",
"that",
"starts",
"with",
"trace"
] | def parseTableJson(self):
if self.parsed == True:
return self.traceSections
conf = self.traceList
"""Add and match functions to be traced get keys that starts with 'trace'"""
for section in [s for s in conf.keys() if s.startswith('trace')]:
if conf[section] is None:
continue
"""Remove duplicates"""
conf[section] = list(set(conf[section]))
sec = traceSection(section)
for func in conf[section]:
print("%d / %d" %
(conf[section].index(func) + 1, len(conf[section])), end="\r")
if conf[section].index(func) + 1 == len(conf[section]):
print("")
match = self.matchSymbol(func, self.symbolTable)
if len(match) > 0:
for s in match:
sec.functions.append(s)
else:
if self.debug:
ask("Function [%s] not found in symbol table" % func)
self.traceSections.append(sec)
self.parsed = True
return self.traceSections | [
"def",
"parseTableJson",
"(",
"self",
")",
":",
"if",
"self",
".",
"parsed",
"==",
"True",
":",
"return",
"self",
".",
"traceSections",
"conf",
"=",
"self",
".",
"traceList",
"for",
"section",
"in",
"[",
"s",
"for",
"s",
"in",
"conf",
".",
"keys",
"(... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/tracer/function.py#L296-L331 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/learn/python/learn/utils/export.py | python | generic_signature_fn | (examples, unused_features, predictions) | return default_signature, {} | Creates generic signature from given examples and predictions.
This is needed for backward compatibility with default behaviour of
export_estimator.
Args:
examples: `Tensor`.
unused_features: `dict` of `Tensor`s.
predictions: `Tensor` or `dict` of `Tensor`s.
Returns:
Tuple of default signature and empty named signatures.
Raises:
ValueError: If examples is `None`. | Creates generic signature from given examples and predictions. | [
"Creates",
"generic",
"signature",
"from",
"given",
"examples",
"and",
"predictions",
"."
] | def generic_signature_fn(examples, unused_features, predictions):
"""Creates generic signature from given examples and predictions.
This is needed for backward compatibility with default behaviour of
export_estimator.
Args:
examples: `Tensor`.
unused_features: `dict` of `Tensor`s.
predictions: `Tensor` or `dict` of `Tensor`s.
Returns:
Tuple of default signature and empty named signatures.
Raises:
ValueError: If examples is `None`.
"""
if examples is None:
raise ValueError('examples cannot be None when using this signature fn.')
tensors = {'inputs': examples}
if not isinstance(predictions, dict):
predictions = {'outputs': predictions}
tensors.update(predictions)
default_signature = exporter.generic_signature(tensors)
return default_signature, {} | [
"def",
"generic_signature_fn",
"(",
"examples",
",",
"unused_features",
",",
"predictions",
")",
":",
"if",
"examples",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'examples cannot be None when using this signature fn.'",
")",
"tensors",
"=",
"{",
"'inputs'",
":",... | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/utils/export.py#L84-L109 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/security/fuzzing/python_fuzzing.py | python | FuzzingHelper.get_tf_dtype | (self, allowed_set=None) | Return a random tensorflow dtype.
Args:
allowed_set: An allowlisted set of dtypes to choose from instead of all of
them.
Returns:
A random type from the list containing all TensorFlow types. | Return a random tensorflow dtype. | [
"Return",
"a",
"random",
"tensorflow",
"dtype",
"."
] | def get_tf_dtype(self, allowed_set=None):
"""Return a random tensorflow dtype.
Args:
allowed_set: An allowlisted set of dtypes to choose from instead of all of
them.
Returns:
A random type from the list containing all TensorFlow types.
"""
if allowed_set:
index = self.get_int(0, len(allowed_set) - 1)
if allowed_set[index] not in _TF_DTYPES:
raise tf.errors.InvalidArgumentError(
None, None,
'Given dtype {} is not accepted.'.format(allowed_set[index]))
return allowed_set[index]
else:
index = self.get_int(0, len(_TF_DTYPES) - 1)
return _TF_DTYPES[index] | [
"def",
"get_tf_dtype",
"(",
"self",
",",
"allowed_set",
"=",
"None",
")",
":",
"if",
"allowed_set",
":",
"index",
"=",
"self",
".",
"get_int",
"(",
"0",
",",
"len",
"(",
"allowed_set",
")",
"-",
"1",
")",
"if",
"allowed_set",
"[",
"index",
"]",
"not"... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/security/fuzzing/python_fuzzing.py#L137-L156 | ||
calamares/calamares | 9f6f82405b3074af7c99dc26487d2e46e4ece3e5 | src/modules/initcpiocfg/main.py | python | run | () | return None | Calls routine with given parameters to modify '/etc/mkinitcpio.conf'.
:return: | Calls routine with given parameters to modify '/etc/mkinitcpio.conf'. | [
"Calls",
"routine",
"with",
"given",
"parameters",
"to",
"modify",
"/",
"etc",
"/",
"mkinitcpio",
".",
"conf",
"."
] | def run():
"""
Calls routine with given parameters to modify '/etc/mkinitcpio.conf'.
:return:
"""
partitions = libcalamares.globalstorage.value("partitions")
root_mount_point = libcalamares.globalstorage.value("rootMountPoint")
if not partitions:
libcalamares.utils.warning("partitions is empty, {!s}".format(partitions))
return (_("Configuration Error"),
_("No partitions are defined for <pre>{!s}</pre> to use." ).format("initcpiocfg"))
if not root_mount_point:
libcalamares.utils.warning("rootMountPoint is empty, {!s}".format(root_mount_point))
return (_("Configuration Error"),
_("No root mount point is given for <pre>{!s}</pre> to use." ).format("initcpiocfg"))
hooks, modules, files = find_initcpio_features(partitions, root_mount_point)
write_mkinitcpio_lines(hooks, modules, files, root_mount_point)
return None | [
"def",
"run",
"(",
")",
":",
"partitions",
"=",
"libcalamares",
".",
"globalstorage",
".",
"value",
"(",
"\"partitions\"",
")",
"root_mount_point",
"=",
"libcalamares",
".",
"globalstorage",
".",
"value",
"(",
"\"rootMountPoint\"",
")",
"if",
"not",
"partitions"... | https://github.com/calamares/calamares/blob/9f6f82405b3074af7c99dc26487d2e46e4ece3e5/src/modules/initcpiocfg/main.py#L224-L245 | |
Ewenwan/MVision | 97b394dfa48cb21c82cd003b1a952745e413a17f | darknect/tensorflow/yolo_v1/yolo_v1_tf.py | python | Yolo._load_weights | (self, weights_file) | Load weights from file | Load weights from file | [
"Load",
"weights",
"from",
"file"
] | def _load_weights(self, weights_file):
"""Load weights from file"""
if self.verbose:
print("Start to load weights from file:%s" % (weights_file))
saver = tf.train.Saver()
saver.restore(self.sess, weights_file) | [
"def",
"_load_weights",
"(",
"self",
",",
"weights_file",
")",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"\"Start to load weights from file:%s\"",
"%",
"(",
"weights_file",
")",
")",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
"sa... | https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/darknect/tensorflow/yolo_v1/yolo_v1_tf.py#L208-L213 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/syntax.py | python | Struct.__init__ | (self, file_name, line, column) | Construct a Struct. | Construct a Struct. | [
"Construct",
"a",
"Struct",
"."
] | def __init__(self, file_name, line, column):
# type: (str, int, int) -> None
"""Construct a Struct."""
self.name = None # type: str
self.description = None # type: str
self.strict = True # type: bool
self.immutable = False # type: bool
self.inline_chained_structs = True # type: bool
self.generate_comparison_operators = False # type: bool
self.chained_types = None # type: List[ChainedType]
self.chained_structs = None # type: List[ChainedStruct]
self.fields = None # type: List[Field]
self.allow_global_collection_name = False # type: bool
self.non_const_getter = False # type: bool
# Command only property
self.cpp_name = None # type: str
# Internal property that is not represented as syntax. An imported struct is read from an
# imported file, and no code is generated for it.
self.imported = False # type: bool
# Internal property: cpp_namespace from globals section
self.cpp_namespace = None # type: str
super(Struct, self).__init__(file_name, line, column) | [
"def",
"__init__",
"(",
"self",
",",
"file_name",
",",
"line",
",",
"column",
")",
":",
"# type: (str, int, int) -> None",
"self",
".",
"name",
"=",
"None",
"# type: str",
"self",
".",
"description",
"=",
"None",
"# type: str",
"self",
".",
"strict",
"=",
"T... | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/syntax.py#L518-L543 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/botocore/session.py | python | Session.set_file_logger | (self, log_level, path, logger_name='botocore') | Convenience function to quickly configure any level of logging
to a file.
:type log_level: int
:param log_level: A log level as specified in the `logging` module
:type path: string
:param path: Path to the log file. The file will be created
if it doesn't already exist. | Convenience function to quickly configure any level of logging
to a file. | [
"Convenience",
"function",
"to",
"quickly",
"configure",
"any",
"level",
"of",
"logging",
"to",
"a",
"file",
"."
] | def set_file_logger(self, log_level, path, logger_name='botocore'):
"""
Convenience function to quickly configure any level of logging
to a file.
:type log_level: int
:param log_level: A log level as specified in the `logging` module
:type path: string
:param path: Path to the log file. The file will be created
if it doesn't already exist.
"""
log = logging.getLogger(logger_name)
log.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.FileHandler(path)
ch.setLevel(log_level)
# create formatter
formatter = logging.Formatter(self.LOG_FORMAT)
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
log.addHandler(ch) | [
"def",
"set_file_logger",
"(",
"self",
",",
"log_level",
",",
"path",
",",
"logger_name",
"=",
"'botocore'",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"logger_name",
")",
"log",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"# create co... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/session.py#L619-L645 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/filters.py | python | do_format | (value: str, *args: t.Any, **kwargs: t.Any) | return soft_str(value) % (kwargs or args) | Apply the given values to a `printf-style`_ format string, like
``string % values``.
.. sourcecode:: jinja
{{ "%s, %s!"|format(greeting, name) }}
Hello, World!
In most cases it should be more convenient and efficient to use the
``%`` operator or :meth:`str.format`.
.. code-block:: text
{{ "%s, %s!" % (greeting, name) }}
{{ "{}, {}!".format(greeting, name) }}
.. _printf-style: https://docs.python.org/library/stdtypes.html
#printf-style-string-formatting | Apply the given values to a `printf-style`_ format string, like
``string % values``. | [
"Apply",
"the",
"given",
"values",
"to",
"a",
"printf",
"-",
"style",
"_",
"format",
"string",
"like",
"string",
"%",
"values",
"."
] | def do_format(value: str, *args: t.Any, **kwargs: t.Any) -> str:
"""Apply the given values to a `printf-style`_ format string, like
``string % values``.
.. sourcecode:: jinja
{{ "%s, %s!"|format(greeting, name) }}
Hello, World!
In most cases it should be more convenient and efficient to use the
``%`` operator or :meth:`str.format`.
.. code-block:: text
{{ "%s, %s!" % (greeting, name) }}
{{ "{}, {}!".format(greeting, name) }}
.. _printf-style: https://docs.python.org/library/stdtypes.html
#printf-style-string-formatting
"""
if args and kwargs:
raise FilterArgumentError(
"can't handle positional and keyword arguments at the same time"
)
return soft_str(value) % (kwargs or args) | [
"def",
"do_format",
"(",
"value",
":",
"str",
",",
"*",
"args",
":",
"t",
".",
"Any",
",",
"*",
"*",
"kwargs",
":",
"t",
".",
"Any",
")",
"->",
"str",
":",
"if",
"args",
"and",
"kwargs",
":",
"raise",
"FilterArgumentError",
"(",
"\"can't handle posit... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/filters.py#L1000-L1025 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/node.py | python | Node.__init__ | (self) | Initialize a DNS node. | Initialize a DNS node. | [
"Initialize",
"a",
"DNS",
"node",
"."
] | def __init__(self):
"""Initialize a DNS node.
"""
self.rdatasets = []; | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"rdatasets",
"=",
"[",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/third_party/dns/node.py#L34-L38 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/tools/inspect_checkpoint.py | python | parse_numpy_printoption | (kv_str) | Sets a single numpy printoption from a string of the form 'x=y'.
See documentation on numpy.set_printoptions() for details about what values
x and y can take. x can be any option listed there other than 'formatter'.
Args:
kv_str: A string of the form 'x=y', such as 'threshold=100000'
Raises:
argparse.ArgumentTypeError: If the string couldn't be used to set any
nump printoption. | Sets a single numpy printoption from a string of the form 'x=y'. | [
"Sets",
"a",
"single",
"numpy",
"printoption",
"from",
"a",
"string",
"of",
"the",
"form",
"x",
"=",
"y",
"."
] | def parse_numpy_printoption(kv_str):
"""Sets a single numpy printoption from a string of the form 'x=y'.
See documentation on numpy.set_printoptions() for details about what values
x and y can take. x can be any option listed there other than 'formatter'.
Args:
kv_str: A string of the form 'x=y', such as 'threshold=100000'
Raises:
argparse.ArgumentTypeError: If the string couldn't be used to set any
nump printoption.
"""
k_v_str = kv_str.split("=", 1)
if len(k_v_str) != 2 or not k_v_str[0]:
raise argparse.ArgumentTypeError("'%s' is not in the form k=v." % kv_str)
k, v_str = k_v_str
printoptions = np.get_printoptions()
if k not in printoptions:
raise argparse.ArgumentTypeError("'%s' is not a valid printoption." % k)
v_type = type(printoptions[k])
if v_type is type(None):
raise argparse.ArgumentTypeError(
"Setting '%s' from the command line is not supported." % k)
try:
v = (v_type(v_str) if v_type is not bool
else flags.BooleanParser().parse(v_str))
except ValueError as e:
raise argparse.ArgumentTypeError(e.message)
np.set_printoptions(**{k: v}) | [
"def",
"parse_numpy_printoption",
"(",
"kv_str",
")",
":",
"k_v_str",
"=",
"kv_str",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"if",
"len",
"(",
"k_v_str",
")",
"!=",
"2",
"or",
"not",
"k_v_str",
"[",
"0",
"]",
":",
"raise",
"argparse",
".",
"Argume... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/tools/inspect_checkpoint.py#L72-L101 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewListCtrl.AppendColumn | (*args, **kwargs) | return _dataview.DataViewListCtrl_AppendColumn(*args, **kwargs) | AppendColumn(self, DataViewColumn column, String varianttype="string") -> bool | AppendColumn(self, DataViewColumn column, String varianttype="string") -> bool | [
"AppendColumn",
"(",
"self",
"DataViewColumn",
"column",
"String",
"varianttype",
"=",
"string",
")",
"-",
">",
"bool"
] | def AppendColumn(*args, **kwargs):
"""AppendColumn(self, DataViewColumn column, String varianttype="string") -> bool"""
return _dataview.DataViewListCtrl_AppendColumn(*args, **kwargs) | [
"def",
"AppendColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewListCtrl_AppendColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L2116-L2118 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/__init__.py | python | set_warn_always | (b) | r"""When this flag is False (default) then some PyTorch warnings may only
appear once per process. This helps avoid excessive warning information.
Setting it to True causes these warnings to always appear, which may be
helpful when debugging.
Args:
b (:class:`bool`): If True, force warnings to always be emitted
If False, set to the default behaviour | r"""When this flag is False (default) then some PyTorch warnings may only
appear once per process. This helps avoid excessive warning information.
Setting it to True causes these warnings to always appear, which may be
helpful when debugging. | [
"r",
"When",
"this",
"flag",
"is",
"False",
"(",
"default",
")",
"then",
"some",
"PyTorch",
"warnings",
"may",
"only",
"appear",
"once",
"per",
"process",
".",
"This",
"helps",
"avoid",
"excessive",
"warning",
"information",
".",
"Setting",
"it",
"to",
"Tr... | def set_warn_always(b):
r"""When this flag is False (default) then some PyTorch warnings may only
appear once per process. This helps avoid excessive warning information.
Setting it to True causes these warnings to always appear, which may be
helpful when debugging.
Args:
b (:class:`bool`): If True, force warnings to always be emitted
If False, set to the default behaviour
"""
_C._set_warnAlways(b) | [
"def",
"set_warn_always",
"(",
"b",
")",
":",
"_C",
".",
"_set_warnAlways",
"(",
"b",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/__init__.py#L565-L575 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.AnnotationGetText | (*args, **kwargs) | return _stc.StyledTextCtrl_AnnotationGetText(*args, **kwargs) | AnnotationGetText(self, int line) -> String
Get the annotation text for a line | AnnotationGetText(self, int line) -> String | [
"AnnotationGetText",
"(",
"self",
"int",
"line",
")",
"-",
">",
"String"
] | def AnnotationGetText(*args, **kwargs):
"""
AnnotationGetText(self, int line) -> String
Get the annotation text for a line
"""
return _stc.StyledTextCtrl_AnnotationGetText(*args, **kwargs) | [
"def",
"AnnotationGetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_AnnotationGetText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L5927-L5933 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/apiclient/googleapiclient/discovery.py | python | ResourceMethodParameters.set_parameters | (self, method_desc) | Populates maps and lists based on method description.
Iterates through each parameter for the method and parses the values from
the parameter dictionary.
Args:
method_desc: Dictionary with metadata describing an API method. Value
comes from the dictionary of methods stored in the 'methods' key in
the deserialized discovery document. | Populates maps and lists based on method description. | [
"Populates",
"maps",
"and",
"lists",
"based",
"on",
"method",
"description",
"."
] | def set_parameters(self, method_desc):
"""Populates maps and lists based on method description.
Iterates through each parameter for the method and parses the values from
the parameter dictionary.
Args:
method_desc: Dictionary with metadata describing an API method. Value
comes from the dictionary of methods stored in the 'methods' key in
the deserialized discovery document.
"""
for arg, desc in six.iteritems(method_desc.get('parameters', {})):
param = key2param(arg)
self.argmap[param] = arg
if desc.get('pattern'):
self.pattern_params[param] = desc['pattern']
if desc.get('enum'):
self.enum_params[param] = desc['enum']
if desc.get('required'):
self.required_params.append(param)
if desc.get('repeated'):
self.repeated_params.append(param)
if desc.get('location') == 'query':
self.query_params.append(param)
if desc.get('location') == 'path':
self.path_params.add(param)
self.param_types[param] = desc.get('type', 'string')
# TODO(dhermes): Determine if this is still necessary. Discovery based APIs
# should have all path parameters already marked with
# 'location: path'.
for match in URITEMPLATE.finditer(method_desc['path']):
for namematch in VARNAME.finditer(match.group(0)):
name = key2param(namematch.group(0))
self.path_params.add(name)
if name in self.query_params:
self.query_params.remove(name) | [
"def",
"set_parameters",
"(",
"self",
",",
"method_desc",
")",
":",
"for",
"arg",
",",
"desc",
"in",
"six",
".",
"iteritems",
"(",
"method_desc",
".",
"get",
"(",
"'parameters'",
",",
"{",
"}",
")",
")",
":",
"param",
"=",
"key2param",
"(",
"arg",
")... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/apiclient/googleapiclient/discovery.py#L563-L600 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/protobuf/python/mox.py | python | MockMethod._PopNextMethod | (self) | Pop the next method from our call queue. | Pop the next method from our call queue. | [
"Pop",
"the",
"next",
"method",
"from",
"our",
"call",
"queue",
"."
] | def _PopNextMethod(self):
"""Pop the next method from our call queue."""
try:
return self._call_queue.popleft()
except IndexError:
raise UnexpectedMethodCallError(self, None) | [
"def",
"_PopNextMethod",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_call_queue",
".",
"popleft",
"(",
")",
"except",
"IndexError",
":",
"raise",
"UnexpectedMethodCallError",
"(",
"self",
",",
"None",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/protobuf/python/mox.py#L581-L586 | ||
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/git.py | python | GitCommandResult.check_returncode | (self) | Raise GitException if the exit code is non-zero. | Raise GitException if the exit code is non-zero. | [
"Raise",
"GitException",
"if",
"the",
"exit",
"code",
"is",
"non",
"-",
"zero",
"."
] | def check_returncode(self):
"""Raise GitException if the exit code is non-zero."""
if self.returncode:
raise GitException(
"Command '{0}' failed with code '{1}'".format(" ".join(self.process_args),
self.returncode),
self.returncode, self.cmd, self.process_args, self.stdout, self.stderr) | [
"def",
"check_returncode",
"(",
"self",
")",
":",
"if",
"self",
".",
"returncode",
":",
"raise",
"GitException",
"(",
"\"Command '{0}' failed with code '{1}'\"",
".",
"format",
"(",
"\" \"",
".",
"join",
"(",
"self",
".",
"process_args",
")",
",",
"self",
".",... | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/git.py#L284-L290 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/ndarray/sparse.py | python | _prepare_src_array | (source_array, dtype) | return source_array | Prepare `source_array` so that it can be used to construct NDArray.
`source_array` is converted to a `np.ndarray` if it's neither an `NDArray` \
nor an `np.ndarray`. | Prepare `source_array` so that it can be used to construct NDArray.
`source_array` is converted to a `np.ndarray` if it's neither an `NDArray` \
nor an `np.ndarray`. | [
"Prepare",
"source_array",
"so",
"that",
"it",
"can",
"be",
"used",
"to",
"construct",
"NDArray",
".",
"source_array",
"is",
"converted",
"to",
"a",
"np",
".",
"ndarray",
"if",
"it",
"s",
"neither",
"an",
"NDArray",
"\\",
"nor",
"an",
"np",
".",
"ndarray... | def _prepare_src_array(source_array, dtype):
"""Prepare `source_array` so that it can be used to construct NDArray.
`source_array` is converted to a `np.ndarray` if it's neither an `NDArray` \
nor an `np.ndarray`.
"""
if not isinstance(source_array, NDArray) and not isinstance(source_array, np.ndarray):
try:
source_array = np.array(source_array, dtype=dtype)
except:
raise TypeError('values must be array like object')
return source_array | [
"def",
"_prepare_src_array",
"(",
"source_array",
",",
"dtype",
")",
":",
"if",
"not",
"isinstance",
"(",
"source_array",
",",
"NDArray",
")",
"and",
"not",
"isinstance",
"(",
"source_array",
",",
"np",
".",
"ndarray",
")",
":",
"try",
":",
"source_array",
... | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/sparse.py#L796-L806 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/ops.py | python | RegisterStatistics.__init__ | (self, op_type, statistic_type) | Saves the `op_type` as the `Operation` type. | Saves the `op_type` as the `Operation` type. | [
"Saves",
"the",
"op_type",
"as",
"the",
"Operation",
"type",
"."
] | def __init__(self, op_type, statistic_type):
"""Saves the `op_type` as the `Operation` type."""
if not isinstance(op_type, six.string_types):
raise TypeError("op_type must be a string.")
if "," in op_type:
raise TypeError("op_type must not contain a comma.")
self._op_type = op_type
if not isinstance(statistic_type, six.string_types):
raise TypeError("statistic_type must be a string.")
if "," in statistic_type:
raise TypeError("statistic_type must not contain a comma.")
self._statistic_type = statistic_type | [
"def",
"__init__",
"(",
"self",
",",
"op_type",
",",
"statistic_type",
")",
":",
"if",
"not",
"isinstance",
"(",
"op_type",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"op_type must be a string.\"",
")",
"if",
"\",\"",
"in",
"op_t... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/ops.py#L2367-L2378 | ||
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/core.py | python | CherryTree.get_textbuffer_from_tree_iter | (self, tree_iter) | return self.treestore[tree_iter][2] | Returns the text buffer given the tree iter | Returns the text buffer given the tree iter | [
"Returns",
"the",
"text",
"buffer",
"given",
"the",
"tree",
"iter"
] | def get_textbuffer_from_tree_iter(self, tree_iter):
"""Returns the text buffer given the tree iter"""
if not self.treestore[tree_iter][2]:
# we are using db storage and the buffer was not created yet
self.ctdb_handler.read_db_node_content(tree_iter, self.db)
return self.treestore[tree_iter][2] | [
"def",
"get_textbuffer_from_tree_iter",
"(",
"self",
",",
"tree_iter",
")",
":",
"if",
"not",
"self",
".",
"treestore",
"[",
"tree_iter",
"]",
"[",
"2",
"]",
":",
"# we are using db storage and the buffer was not created yet",
"self",
".",
"ctdb_handler",
".",
"read... | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/core.py#L3251-L3256 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/py/interpreter.py | python | Interpreter.getAutoCompleteList | (self, command='', *args, **kwds) | return l | Return list of auto-completion options for a command.
The list of options will be based on the locals namespace. | Return list of auto-completion options for a command.
The list of options will be based on the locals namespace. | [
"Return",
"list",
"of",
"auto",
"-",
"completion",
"options",
"for",
"a",
"command",
".",
"The",
"list",
"of",
"options",
"will",
"be",
"based",
"on",
"the",
"locals",
"namespace",
"."
] | def getAutoCompleteList(self, command='', *args, **kwds):
"""Return list of auto-completion options for a command.
The list of options will be based on the locals namespace."""
stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
sys.stdin, sys.stdout, sys.stderr = \
self.stdin, self.stdout, self.stderr
l = introspect.getAutoCompleteList(command, self.locals,
*args, **kwds)
sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
return l | [
"def",
"getAutoCompleteList",
"(",
"self",
",",
"command",
"=",
"''",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"stdin",
",",
"stdout",
",",
"stderr",
"=",
"sys",
".",
"stdin",
",",
"sys",
".",
"stdout",
",",
"sys",
".",
"stderr",
"sys",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/interpreter.py#L140-L150 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/array_grad.py | python | _StridedSliceGradGrad | (op, grad) | return None, None, None, None, array_ops.strided_slice(
grad,
begin,
end,
strides,
begin_mask=op.get_attr("begin_mask"),
end_mask=op.get_attr("end_mask"),
ellipsis_mask=op.get_attr("ellipsis_mask"),
new_axis_mask=op.get_attr("new_axis_mask"),
shrink_axis_mask=op.get_attr("shrink_axis_mask")) | Gradient for StridedSliceGrad op. | Gradient for StridedSliceGrad op. | [
"Gradient",
"for",
"StridedSliceGrad",
"op",
"."
] | def _StridedSliceGradGrad(op, grad):
"""Gradient for StridedSliceGrad op."""
begin = op.inputs[1]
end = op.inputs[2]
strides = op.inputs[3]
return None, None, None, None, array_ops.strided_slice(
grad,
begin,
end,
strides,
begin_mask=op.get_attr("begin_mask"),
end_mask=op.get_attr("end_mask"),
ellipsis_mask=op.get_attr("ellipsis_mask"),
new_axis_mask=op.get_attr("new_axis_mask"),
shrink_axis_mask=op.get_attr("shrink_axis_mask")) | [
"def",
"_StridedSliceGradGrad",
"(",
"op",
",",
"grad",
")",
":",
"begin",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
"end",
"=",
"op",
".",
"inputs",
"[",
"2",
"]",
"strides",
"=",
"op",
".",
"inputs",
"[",
"3",
"]",
"return",
"None",
",",
"None",... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/array_grad.py#L299-L314 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/command/easy_install.py | python | is_python_script | (script_text, filename) | return False | Is this text, as a whole, a Python script? (as opposed to shell/bat/etc. | Is this text, as a whole, a Python script? (as opposed to shell/bat/etc. | [
"Is",
"this",
"text",
"as",
"a",
"whole",
"a",
"Python",
"script?",
"(",
"as",
"opposed",
"to",
"shell",
"/",
"bat",
"/",
"etc",
"."
] | def is_python_script(script_text, filename):
"""Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
"""
if filename.endswith('.py') or filename.endswith('.pyw'):
return True # extension says it's Python
if is_python(script_text, filename):
return True # it's syntactically valid Python
if script_text.startswith('#!'):
# It begins with a '#!' line, so check if 'python' is in it somewhere
return 'python' in script_text.splitlines()[0].lower()
return False | [
"def",
"is_python_script",
"(",
"script_text",
",",
"filename",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.py'",
")",
"or",
"filename",
".",
"endswith",
"(",
"'.pyw'",
")",
":",
"return",
"True",
"# extension says it's Python",
"if",
"is_python",
"("... | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/command/easy_install.py#L1937-L1948 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/nntplib.py | python | NNTP.getresp | (self) | return resp | Internal: get a response from the server.
Raise various errors if the response indicates an error. | Internal: get a response from the server.
Raise various errors if the response indicates an error. | [
"Internal",
":",
"get",
"a",
"response",
"from",
"the",
"server",
".",
"Raise",
"various",
"errors",
"if",
"the",
"response",
"indicates",
"an",
"error",
"."
] | def getresp(self):
"""Internal: get a response from the server.
Raise various errors if the response indicates an error."""
resp = self.getline()
if self.debugging: print '*resp*', repr(resp)
c = resp[:1]
if c == '4':
raise NNTPTemporaryError(resp)
if c == '5':
raise NNTPPermanentError(resp)
if c not in '123':
raise NNTPProtocolError(resp)
return resp | [
"def",
"getresp",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"getline",
"(",
")",
"if",
"self",
".",
"debugging",
":",
"print",
"'*resp*'",
",",
"repr",
"(",
"resp",
")",
"c",
"=",
"resp",
"[",
":",
"1",
"]",
"if",
"c",
"==",
"'4'",
":",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/nntplib.py#L211-L223 | |
ukoethe/vigra | 093d57d15c8c237adf1704d96daa6393158ce299 | vigranumpy/lib/arraytypes.py | python | VigraArray.subarray | (self, p1, p2=None) | Construct a subarray view from a pair of points. The first point denotes the start
of the subarray (inclusive), the second its end (exclusive). For example,
a.subarray((1,2,3), (4,5,6)) # equivalent to a[1:4, 2:5, 3:6]
The given points must have the same dimension, otherwise an IndexError is raised.
If only one point is given, it refers to the subarray's end, and the start is set
to the point (0, 0, ...) with appropriate dimension, for example
a.subarray((4,5,6)) # equivalent to a[:4, :5, :6]
The function transforms the given point pair into a tuple of slices and calls
self.__getitem__() in it. If the points have lower dimension than the array, an
Ellipsis ('...') is implicitly appended to the slicing, so that missing axes
are left unaltered. | Construct a subarray view from a pair of points. The first point denotes the start
of the subarray (inclusive), the second its end (exclusive). For example, | [
"Construct",
"a",
"subarray",
"view",
"from",
"a",
"pair",
"of",
"points",
".",
"The",
"first",
"point",
"denotes",
"the",
"start",
"of",
"the",
"subarray",
"(",
"inclusive",
")",
"the",
"second",
"its",
"end",
"(",
"exclusive",
")",
".",
"For",
"example... | def subarray(self, p1, p2=None):
'''
Construct a subarray view from a pair of points. The first point denotes the start
of the subarray (inclusive), the second its end (exclusive). For example,
a.subarray((1,2,3), (4,5,6)) # equivalent to a[1:4, 2:5, 3:6]
The given points must have the same dimension, otherwise an IndexError is raised.
If only one point is given, it refers to the subarray's end, and the start is set
to the point (0, 0, ...) with appropriate dimension, for example
a.subarray((4,5,6)) # equivalent to a[:4, :5, :6]
The function transforms the given point pair into a tuple of slices and calls
self.__getitem__() in it. If the points have lower dimension than the array, an
Ellipsis ('...') is implicitly appended to the slicing, so that missing axes
are left unaltered.
'''
if p2 is not None:
if len(p1) != len(p2):
raise IndexError('VigraArray.subarray(): points must have the same dimension.')
return self.__getitem__(tuple(map(lambda x,y: slice(x.__int__(), y.__int__()), p1, p2)))
else:
return self.__getitem__(tuple(map(lambda x: slice(x.__int__()), p1))) | [
"def",
"subarray",
"(",
"self",
",",
"p1",
",",
"p2",
"=",
"None",
")",
":",
"if",
"p2",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"p1",
")",
"!=",
"len",
"(",
"p2",
")",
":",
"raise",
"IndexError",
"(",
"'VigraArray.subarray(): points must have the ... | https://github.com/ukoethe/vigra/blob/093d57d15c8c237adf1704d96daa6393158ce299/vigranumpy/lib/arraytypes.py#L1277-L1300 | ||
funnyzhou/Adaptive_Feeding | 9c78182331d8c0ea28de47226e805776c638d46f | AF/video_demo.py | python | get_labelname | (labelmap, labels) | return labelnames | Get Label Name from LabelMap | Get Label Name from LabelMap | [
"Get",
"Label",
"Name",
"from",
"LabelMap"
] | def get_labelname(labelmap, labels):
"""Get Label Name from LabelMap"""
num_labels = len(labelmap.item)
labelnames = []
if type(labels) is not list:
labels = [labels]
for label in labels:
found = False
for i in range(0, num_labels):
if label == labelmap.item[i].label:
found = True
labelnames.append(labelmap.item[i].display_name)
break
assert found == True
return labelnames | [
"def",
"get_labelname",
"(",
"labelmap",
",",
"labels",
")",
":",
"num_labels",
"=",
"len",
"(",
"labelmap",
".",
"item",
")",
"labelnames",
"=",
"[",
"]",
"if",
"type",
"(",
"labels",
")",
"is",
"not",
"list",
":",
"labels",
"=",
"[",
"labels",
"]",... | https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/AF/video_demo.py#L50-L65 | |
9miao/CrossApp | 1f5375e061bf69841eb19728598f5ae3f508d620 | tools/plugin_jscompile/__init__.py | python | CCPluginJSCompile.get_output_file_path | (self, jsfile) | return jsc_filepath | Gets output file path by source js file | Gets output file path by source js file | [
"Gets",
"output",
"file",
"path",
"by",
"source",
"js",
"file"
] | def get_output_file_path(self, jsfile):
"""
Gets output file path by source js file
"""
# create folder for generated file
jsc_filepath = ""
relative_path = self.get_relative_path(jsfile)+"c"
jsc_filepath = os.path.join(self._dst_dir, relative_path)
dst_rootpath = os.path.split(jsc_filepath)[0]
try:
# print "creating dir (%s)" % (dst_rootpath)
os.makedirs(dst_rootpath)
except OSError:
if os.path.exists(dst_rootpath) == False:
# There was an error on creation, so make sure we know about it
raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_MKDIR_FAILED_FMT', dst_rootpath),
cocos.CCPluginError.ERROR_PATH_NOT_FOUND)
# print "return jsc path: "+jsc_filepath
return jsc_filepath | [
"def",
"get_output_file_path",
"(",
"self",
",",
"jsfile",
")",
":",
"# create folder for generated file",
"jsc_filepath",
"=",
"\"\"",
"relative_path",
"=",
"self",
".",
"get_relative_path",
"(",
"jsfile",
")",
"+",
"\"c\"",
"jsc_filepath",
"=",
"os",
".",
"path"... | https://github.com/9miao/CrossApp/blob/1f5375e061bf69841eb19728598f5ae3f508d620/tools/plugin_jscompile/__init__.py#L101-L121 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/optimize/_minimize.py | python | standardize_bounds | (bounds, x0, meth) | return bounds | Converts bounds to the form required by the solver. | Converts bounds to the form required by the solver. | [
"Converts",
"bounds",
"to",
"the",
"form",
"required",
"by",
"the",
"solver",
"."
] | def standardize_bounds(bounds, x0, meth):
"""Converts bounds to the form required by the solver."""
if meth == 'trust-constr':
if not isinstance(bounds, Bounds):
lb, ub = old_bound_to_new(bounds)
bounds = Bounds(lb, ub)
elif meth in ('l-bfgs-b', 'tnc', 'slsqp'):
if isinstance(bounds, Bounds):
bounds = new_bounds_to_old(bounds.lb, bounds.ub, x0.shape[0])
return bounds | [
"def",
"standardize_bounds",
"(",
"bounds",
",",
"x0",
",",
"meth",
")",
":",
"if",
"meth",
"==",
"'trust-constr'",
":",
"if",
"not",
"isinstance",
"(",
"bounds",
",",
"Bounds",
")",
":",
"lb",
",",
"ub",
"=",
"old_bound_to_new",
"(",
"bounds",
")",
"b... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_minimize.py#L788-L797 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/TpmTypes.py | python | TPM2_EncryptDecrypt2_REQUEST.fromTpm | (buf) | return buf.createObj(TPM2_EncryptDecrypt2_REQUEST) | Returns new TPM2_EncryptDecrypt2_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | Returns new TPM2_EncryptDecrypt2_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer | [
"Returns",
"new",
"TPM2_EncryptDecrypt2_REQUEST",
"object",
"constructed",
"from",
"its",
"marshaled",
"representation",
"in",
"the",
"given",
"TpmBuffer",
"buffer"
] | def fromTpm(buf):
""" Returns new TPM2_EncryptDecrypt2_REQUEST object constructed from its
marshaled representation in the given TpmBuffer buffer
"""
return buf.createObj(TPM2_EncryptDecrypt2_REQUEST) | [
"def",
"fromTpm",
"(",
"buf",
")",
":",
"return",
"buf",
".",
"createObj",
"(",
"TPM2_EncryptDecrypt2_REQUEST",
")"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L11489-L11493 | |
google/skia | 82d65d0487bd72f5f7332d002429ec2dc61d2463 | tools/sanitize_source_files.py | python | TabReplacer | (line, file_path, line_number) | return line.replace('\t', ' ') | Replaces Tabs with 4 whitespaces. | Replaces Tabs with 4 whitespaces. | [
"Replaces",
"Tabs",
"with",
"4",
"whitespaces",
"."
] | def TabReplacer(line, file_path, line_number):
"""Replaces Tabs with 4 whitespaces."""
if '\t' in line:
print('Replacing Tab with whitespace in %s:%s' % (file_path, line_number))
return line.replace('\t', ' ') | [
"def",
"TabReplacer",
"(",
"line",
",",
"file_path",
",",
"line_number",
")",
":",
"if",
"'\\t'",
"in",
"line",
":",
"print",
"(",
"'Replacing Tab with whitespace in %s:%s'",
"%",
"(",
"file_path",
",",
"line_number",
")",
")",
"return",
"line",
".",
"replace"... | https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/tools/sanitize_source_files.py#L102-L106 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py | python | Block.set | (self, locs, values) | Modify Block in-place with new item value
Returns
-------
None | Modify Block in-place with new item value | [
"Modify",
"Block",
"in",
"-",
"place",
"with",
"new",
"item",
"value"
] | def set(self, locs, values):
"""
Modify Block in-place with new item value
Returns
-------
None
"""
self.values[locs] = values | [
"def",
"set",
"(",
"self",
",",
"locs",
",",
"values",
")",
":",
"self",
".",
"values",
"[",
"locs",
"]",
"=",
"values"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/blocks.py#L368-L376 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/specs/python/params_ops.py | python | Nt | (mu, sigma, limit=3.0) | return min(max(random.gauss(mu, sigma), mu-limit*sigma), mu+limit*sigma) | Normally distributed floating point number with truncation. | Normally distributed floating point number with truncation. | [
"Normally",
"distributed",
"floating",
"point",
"number",
"with",
"truncation",
"."
] | def Nt(mu, sigma, limit=3.0):
"""Normally distributed floating point number with truncation."""
return min(max(random.gauss(mu, sigma), mu-limit*sigma), mu+limit*sigma) | [
"def",
"Nt",
"(",
"mu",
",",
"sigma",
",",
"limit",
"=",
"3.0",
")",
":",
"return",
"min",
"(",
"max",
"(",
"random",
".",
"gauss",
"(",
"mu",
",",
"sigma",
")",
",",
"mu",
"-",
"limit",
"*",
"sigma",
")",
",",
"mu",
"+",
"limit",
"*",
"sigma... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/specs/python/params_ops.py#L82-L84 | |
evpo/EncryptPad | 156904860aaba8e7e8729b44e269b2992f9fe9f4 | deps/libencryptmsg/configure.py | python | configure_encryptmsg | (system_command, options) | Build the encryptmsg library and cli | Build the encryptmsg library and cli | [
"Build",
"the",
"encryptmsg",
"library",
"and",
"cli"
] | def configure_encryptmsg(system_command, options):
"""
Build the encryptmsg library and cli
"""
source_paths = SourcePaths(os.path.dirname(system_command))
info_arch = load_build_data_info_files(source_paths, 'CPU info', 'arch', ArchInfo)
info_os = load_build_data_info_files(source_paths, 'OS info', 'os', OsInfo)
info_cc = load_build_data_info_files(source_paths, 'compiler info', 'cc', CompilerInfo)
set_defaults_for_unset_options(options, info_arch, info_cc)
canonicalize_options(options, info_os, info_arch)
logging.info('Autodetected platform information: OS="%s" machine="%s" proc="%s"',
platform.system(), platform.machine(), platform.processor())
info_modules = load_info_files('src', 'Modules', 'info.txt', ModuleInfo)
# for mod in ['state_machine','botan_1_openpgp_codec','stlplus']:
for mod in ['state_machine','stlplus']:
info_modules.update(
load_info_files(os.path.join(options.deps_dir, mod),
'Modules', 'info.txt', ModuleInfo)
)
build_paths = BuildPaths(source_paths, options, info_modules.values())
cc = info_cc[options.compiler]
arch = info_arch[options.arch]
osinfo = info_os[options.os]
template_vars = create_template_vars(source_paths, build_paths, options, info_modules.values(),
cc, arch, osinfo)
template_vars['library_target'] = os.path.join(get_project_dir(), build_paths.build_dir, 'libencryptmsg.a')
if options.build_shared_lib:
template_vars['sharedso_target'] = os.path.join(get_project_dir(), build_paths.build_dir, template_vars['shared_lib_name'])
else:
template_vars['sharedso_target'] = ""
template_vars['cli_exe'] = os.path.join(build_paths.target_dir, 'encryptmsg')
template_vars['cli_exe_name'] = 'encryptmsg'
template_vars['test_exe'] = os.path.join(build_paths.target_dir, 'encryptmsg-test')
template_vars['with_documentation'] = False
include_paths = template_vars['include_paths']
include_paths += ' ' + cc.add_include_dir_option + build_paths.internal_include_dir
include_paths_items = [
(options.deps_dir,'stlplus','containers'),
(options.deps_dir,'plog','include'),
]
for item in include_paths_items:
include_paths += ' -isystem ' + os.path.join(get_project_dir(), *item)
template_vars['include_paths'] = include_paths
#qt build
template_vars['debug_mode'] = options.debug_mode
default_targets = ['libs']
if options.build_cli:
default_targets.append('cli')
if options.test:
default_targets.append('test')
if options.build_shared_lib:
default_targets.append('shared')
template_vars['default_targets'] = ' '.join(default_targets)
template_vars['deps_dir'] = options.deps_dir
set_botan_variables(options, template_vars, cc)
set_zlib_variables(options, template_vars, cc)
set_bzip2_variables(options, template_vars, cc)
do_io_for_build(cc, arch, osinfo, info_modules.values(), build_paths, source_paths, template_vars, options) | [
"def",
"configure_encryptmsg",
"(",
"system_command",
",",
"options",
")",
":",
"source_paths",
"=",
"SourcePaths",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"system_command",
")",
")",
"info_arch",
"=",
"load_build_data_info_files",
"(",
"source_paths",
",",
... | https://github.com/evpo/EncryptPad/blob/156904860aaba8e7e8729b44e269b2992f9fe9f4/deps/libencryptmsg/configure.py#L1908-L1979 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/abins/abinsalgorithm.py | python | AbinsAlgorithm.create_total_workspace | (self, workspaces: list) | Sum together elemental totals to make an additional Total workspace | Sum together elemental totals to make an additional Total workspace | [
"Sum",
"together",
"elemental",
"totals",
"to",
"make",
"an",
"additional",
"Total",
"workspace"
] | def create_total_workspace(self, workspaces: list) -> None:
"""Sum together elemental totals to make an additional Total workspace"""
total_atom_workspaces = []
for ws in workspaces:
if "total" in ws:
total_atom_workspaces.append(ws)
total_workspace = self._create_total_workspace(partial_workspaces=total_atom_workspaces)
workspaces.insert(0, total_workspace) | [
"def",
"create_total_workspace",
"(",
"self",
",",
"workspaces",
":",
"list",
")",
"->",
"None",
":",
"total_atom_workspaces",
"=",
"[",
"]",
"for",
"ws",
"in",
"workspaces",
":",
"if",
"\"total\"",
"in",
"ws",
":",
"total_atom_workspaces",
".",
"append",
"(... | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/abinsalgorithm.py#L487-L494 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/dataview.py | python | DataViewTreeCtrl.GetChildCount | (*args, **kwargs) | return _dataview.DataViewTreeCtrl_GetChildCount(*args, **kwargs) | GetChildCount(self, DataViewItem parent) -> int | GetChildCount(self, DataViewItem parent) -> int | [
"GetChildCount",
"(",
"self",
"DataViewItem",
"parent",
")",
"-",
">",
"int"
] | def GetChildCount(*args, **kwargs):
"""GetChildCount(self, DataViewItem parent) -> int"""
return _dataview.DataViewTreeCtrl_GetChildCount(*args, **kwargs) | [
"def",
"GetChildCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewTreeCtrl_GetChildCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L2529-L2531 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/util/timeout.py | python | Timeout.connect_timeout | (self) | return min(self._connect, self.total) | Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None | Get the value to use when setting a connection timeout. | [
"Get",
"the",
"value",
"to",
"use",
"when",
"setting",
"a",
"connection",
"timeout",
"."
] | def connect_timeout(self):
""" Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
"""
if self.total is None:
return self._connect
if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:
return self.total
return min(self._connect, self.total) | [
"def",
"connect_timeout",
"(",
"self",
")",
":",
"if",
"self",
".",
"total",
"is",
"None",
":",
"return",
"self",
".",
"_connect",
"if",
"self",
".",
"_connect",
"is",
"None",
"or",
"self",
".",
"_connect",
"is",
"self",
".",
"DEFAULT_TIMEOUT",
":",
"r... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/util/timeout.py#L211-L226 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | GraphicsContext.OffsetEnabled | (*args, **kwargs) | return _gdi_.GraphicsContext_OffsetEnabled(*args, **kwargs) | OffsetEnabled(self) -> bool | OffsetEnabled(self) -> bool | [
"OffsetEnabled",
"(",
"self",
")",
"-",
">",
"bool"
] | def OffsetEnabled(*args, **kwargs):
"""OffsetEnabled(self) -> bool"""
return _gdi_.GraphicsContext_OffsetEnabled(*args, **kwargs) | [
"def",
"OffsetEnabled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"GraphicsContext_OffsetEnabled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L6522-L6524 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/html.py | python | HelpControllerBase.DisplaySection | (*args) | return _html.HelpControllerBase_DisplaySection(*args) | DisplaySection(self, int sectionNo) -> bool
DisplaySection(self, String section) -> bool | DisplaySection(self, int sectionNo) -> bool
DisplaySection(self, String section) -> bool | [
"DisplaySection",
"(",
"self",
"int",
"sectionNo",
")",
"-",
">",
"bool",
"DisplaySection",
"(",
"self",
"String",
"section",
")",
"-",
">",
"bool"
] | def DisplaySection(*args):
"""
DisplaySection(self, int sectionNo) -> bool
DisplaySection(self, String section) -> bool
"""
return _html.HelpControllerBase_DisplaySection(*args) | [
"def",
"DisplaySection",
"(",
"*",
"args",
")",
":",
"return",
"_html",
".",
"HelpControllerBase_DisplaySection",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L1888-L1893 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | HeaderButtonParams.__init__ | (self, *args, **kwargs) | __init__(self) -> HeaderButtonParams
Extra (optional) parameters for `wx.RendererNative.DrawHeaderButton` | __init__(self) -> HeaderButtonParams | [
"__init__",
"(",
"self",
")",
"-",
">",
"HeaderButtonParams"
] | def __init__(self, *args, **kwargs):
"""
__init__(self) -> HeaderButtonParams
Extra (optional) parameters for `wx.RendererNative.DrawHeaderButton`
"""
_gdi_.HeaderButtonParams_swiginit(self,_gdi_.new_HeaderButtonParams(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_gdi_",
".",
"HeaderButtonParams_swiginit",
"(",
"self",
",",
"_gdi_",
".",
"new_HeaderButtonParams",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L7168-L7174 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py3/data.py | python | Manpages.dispatch | (cls, files) | return [cls(manpages, prefix=_posixpath.join(
'share', 'man', 'man%s' % section,
)) for section, manpages in list(mpmap.items())] | Automatically dispatch manpages to their target directories | Automatically dispatch manpages to their target directories | [
"Automatically",
"dispatch",
"manpages",
"to",
"their",
"target",
"directories"
] | def dispatch(cls, files):
""" Automatically dispatch manpages to their target directories """
mpmap = {}
for manpage in files:
normalized = _os.path.normpath(manpage)
_, ext = _os.path.splitext(normalized)
if ext.startswith(_os.path.extsep):
ext = ext[len(_os.path.extsep):]
mpmap.setdefault(ext, []).append(manpage)
return [cls(manpages, prefix=_posixpath.join(
'share', 'man', 'man%s' % section,
)) for section, manpages in list(mpmap.items())] | [
"def",
"dispatch",
"(",
"cls",
",",
"files",
")",
":",
"mpmap",
"=",
"{",
"}",
"for",
"manpage",
"in",
"files",
":",
"normalized",
"=",
"_os",
".",
"path",
".",
"normpath",
"(",
"manpage",
")",
"_",
",",
"ext",
"=",
"_os",
".",
"path",
".",
"spli... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rcssmin/_setup/py3/data.py#L147-L158 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/legendre.py | python | leggrid2d | (x, y, c) | return c | Evaluate a 2-D Legendre series on the Cartesian product of x and y.
This function returns the values:
.. math:: p(a,b) = \sum_{i,j} c_{i,j} * L_i(a) * L_j(b)
where the points `(a, b)` consist of all pairs formed by taking
`a` from `x` and `b` from `y`. The resulting points form a grid with
`x` in the first dimension and `y` in the second.
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars. In either
case, either `x` and `y` or their elements must support multiplication
and addition both with themselves and with the elements of `c`.
If `c` has fewer than two dimensions, ones are implicitly appended to
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
x.shape + y.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points in the
Cartesian product of `x` and `y`. If `x` or `y` is a list or
tuple, it is first converted to an ndarray, otherwise it is left
unchanged and, if it isn't an ndarray, it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term of
multi-degree i,j is contained in `c[i,j]`. If `c` has dimension
greater than two the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional Chebyshev series at points in the
Cartesian product of `x` and `y`.
See Also
--------
legval, legval2d, legval3d, leggrid3d
Notes
-----
.. versionadded::1.7.0 | Evaluate a 2-D Legendre series on the Cartesian product of x and y. | [
"Evaluate",
"a",
"2",
"-",
"D",
"Legendre",
"series",
"on",
"the",
"Cartesian",
"product",
"of",
"x",
"and",
"y",
"."
] | def leggrid2d(x, y, c):
"""
Evaluate a 2-D Legendre series on the Cartesian product of x and y.
This function returns the values:
.. math:: p(a,b) = \sum_{i,j} c_{i,j} * L_i(a) * L_j(b)
where the points `(a, b)` consist of all pairs formed by taking
`a` from `x` and `b` from `y`. The resulting points form a grid with
`x` in the first dimension and `y` in the second.
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars. In either
case, either `x` and `y` or their elements must support multiplication
and addition both with themselves and with the elements of `c`.
If `c` has fewer than two dimensions, ones are implicitly appended to
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
x.shape + y.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points in the
Cartesian product of `x` and `y`. If `x` or `y` is a list or
tuple, it is first converted to an ndarray, otherwise it is left
unchanged and, if it isn't an ndarray, it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term of
multi-degree i,j is contained in `c[i,j]`. If `c` has dimension
greater than two the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional Chebyshev series at points in the
Cartesian product of `x` and `y`.
See Also
--------
legval, legval2d, legval3d, leggrid3d
Notes
-----
.. versionadded::1.7.0
"""
c = legval(x, c)
c = legval(y, c)
return c | [
"def",
"leggrid2d",
"(",
"x",
",",
"y",
",",
"c",
")",
":",
"c",
"=",
"legval",
"(",
"x",
",",
"c",
")",
"c",
"=",
"legval",
"(",
"y",
",",
"c",
")",
"return",
"c"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/legendre.py#L1040-L1092 | |
martinmoene/expected-lite | 6284387cb117ea78d973fb5b1cbff1651a8d5d9a | conanfile.py | python | ExpectedLiteConan.package | (self) | Run CMake install | Run CMake install | [
"Run",
"CMake",
"install"
] | def package(self):
"""Run CMake install"""
cmake = CMake(self)
cmake.definitions["EXPECTED_LITE_OPT_BUILD_TESTS"] = "OFF"
cmake.definitions["EXPECTED_LITE_OPT_BUILD_EXAMPLES"] = "OFF"
cmake.configure()
cmake.install() | [
"def",
"package",
"(",
"self",
")",
":",
"cmake",
"=",
"CMake",
"(",
"self",
")",
"cmake",
".",
"definitions",
"[",
"\"EXPECTED_LITE_OPT_BUILD_TESTS\"",
"]",
"=",
"\"OFF\"",
"cmake",
".",
"definitions",
"[",
"\"EXPECTED_LITE_OPT_BUILD_EXAMPLES\"",
"]",
"=",
"\"O... | https://github.com/martinmoene/expected-lite/blob/6284387cb117ea78d973fb5b1cbff1651a8d5d9a/conanfile.py#L18-L24 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/cond_v2.py | python | _IfGrad | (op, *grads) | return [None] + outputs | The gradient of an If op produced by cond_v2. | The gradient of an If op produced by cond_v2. | [
"The",
"gradient",
"of",
"an",
"If",
"op",
"produced",
"by",
"cond_v2",
"."
] | def _IfGrad(op, *grads): # pylint: disable=invalid-name
"""The gradient of an If op produced by cond_v2."""
# Get the if operator (this logic handles the case where op is a MockOp)
if_op = op.outputs[0].op
true_graph, false_graph = get_func_graphs(if_op)
# Note: op.graph != ops.get_default_graph() when we are computing the gradient
# of a nested cond.
assert true_graph.outer_graph == if_op.graph
assert false_graph.outer_graph == if_op.graph
# Create grad functions that compute the gradient of the true/false forward
# graphs. These functions will capture tensors from the forward pass
# functions.
true_grad_graph = _create_grad_func(
true_graph, grads, util.unique_grad_fn_name(true_graph.name))
false_grad_graph = _create_grad_func(
false_graph, grads, util.unique_grad_fn_name(false_graph.name))
# Replaces output None grads with zeros if at least one branch has non-None
# grad at that index.
_create_zeros_for_none_grads([true_graph, false_graph],
[true_grad_graph, false_grad_graph])
if (true_grad_graph.op_needs_rewrite or false_grad_graph.op_needs_rewrite):
# Modify 'op' to output the intermediates needed by the grad functions. Note
# that all needed intermediates are wrapped in optionals. Each optional
# intermediate output will have a value iff its corresponding branch is
# taken.
# NOTE(skyewm): if there are any active sessions, this modification to `op`
# may make them unrunnable!
if control_flow_util.GraphOrParentsInXlaContext(ops.get_default_graph()):
# XLA does not yet support optionals, so output intermediates directly and
# make them match via FakeParams, which can be converted to zeros in XLA.
# TODO(skyewm,jpienaar): can XLA support optionals?
true_intermediates = true_grad_graph.xla_intermediates
false_intermediates = false_grad_graph.xla_intermediates
extra_true_outputs, extra_false_outputs = _make_intermediates_match_xla(
[true_graph, false_graph], [true_intermediates, false_intermediates])
else:
true_intermediates = true_grad_graph.wrapped_intermediates
false_intermediates = false_grad_graph.wrapped_intermediates
# Make outputs match by adding none optionals.
extra_true_outputs, extra_false_outputs = _make_intermediates_match(
[true_graph, false_graph], [true_intermediates, false_intermediates])
true_graph.outputs.extend(extra_true_outputs)
false_graph.outputs.extend(extra_false_outputs)
# TODO(skyewm): indicate it's an internal bug if this fails.
_check_same_outputs(_COND, [true_graph, false_graph])
true_graph.name += "_rewritten"
false_graph.name += "_rewritten"
if_op._set_func_attr("then_branch", util.create_new_tf_function(true_graph))
if_op._set_func_attr("else_branch",
util.create_new_tf_function(false_graph))
if_op._set_type_list_attr("Tout", true_graph.output_types)
if_op._set_shape_list_attr("output_shapes", true_graph.output_shapes)
if_op._add_outputs(
[t.dtype for t in extra_true_outputs],
[t.shape for t in extra_true_outputs])
# Resolve references to forward graph tensors in grad graphs and ensure
# they are in-scope, i.e., belong to one of outer graphs of the grad graph.
true_grad_inputs = _resolve_grad_inputs(true_graph, true_grad_graph)
false_grad_inputs = _resolve_grad_inputs(false_graph, false_grad_graph)
# This modifies true_grad_graph and false_grad_graph.
_make_output_composite_tensors_match(_COND,
[true_grad_graph, false_grad_graph])
outputs = _build_cond(
if_op.inputs[0],
true_grad_graph,
false_grad_graph,
true_grad_inputs,
false_grad_inputs,
building_gradient=True,
)
# The predicate has no gradient.
return [None] + outputs | [
"def",
"_IfGrad",
"(",
"op",
",",
"*",
"grads",
")",
":",
"# pylint: disable=invalid-name",
"# Get the if operator (this logic handles the case where op is a MockOp)",
"if_op",
"=",
"op",
".",
"outputs",
"[",
"0",
"]",
".",
"op",
"true_graph",
",",
"false_graph",
"=",... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/cond_v2.py#L108-L190 | |
etotheipi/BitcoinArmory | 2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98 | urllib3/response.py | python | HTTPResponse.read | (self, amt=None, decode_content=None, cache_content=False) | Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
:param cache_content:
If True, will save the returned data such that the same result is
returned despite of the state of the underlying file object. This
is useful if you want the ``.data`` property to continue working
after having ``.read()`` the file object. (Overridden if ``amt`` is
set.) | Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``. | [
"Similar",
"to",
":",
"meth",
":",
"httplib",
".",
"HTTPResponse",
".",
"read",
"but",
"with",
"two",
"additional",
"parameters",
":",
"decode_content",
"and",
"cache_content",
"."
] | def read(self, amt=None, decode_content=None, cache_content=False):
"""
Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
:param cache_content:
If True, will save the returned data such that the same result is
returned despite of the state of the underlying file object. This
is useful if you want the ``.data`` property to continue working
after having ``.read()`` the file object. (Overridden if ``amt`` is
set.)
"""
# Note: content-encoding value should be case-insensitive, per RFC 2616
# Section 3.5
content_encoding = self.headers.get('content-encoding', '').lower()
if self._decoder is None:
if content_encoding in self.CONTENT_DECODERS:
self._decoder = _get_decoder(content_encoding)
if decode_content is None:
decode_content = self.decode_content
if self._fp is None:
return
flush_decoder = False
try:
if amt is None:
# cStringIO doesn't like amt=None
data = self._fp.read()
flush_decoder = True
else:
cache_content = False
data = self._fp.read(amt)
if amt != 0 and not data: # Platform-specific: Buggy versions of Python.
# Close the connection when no data is returned
#
# This is redundant to what httplib/http.client _should_
# already do. However, versions of python released before
# December 15, 2012 (http://bugs.python.org/issue16298) do not
# properly close the connection in all cases. There is no harm
# in redundantly calling close.
self._fp.close()
flush_decoder = True
self._fp_bytes_read += len(data)
try:
if decode_content and self._decoder:
data = self._decoder.decompress(data)
except (IOError, zlib.error) as e:
raise DecodeError(
"Received response with content-encoding: %s, but "
"failed to decode it." % content_encoding,
e)
if flush_decoder and decode_content and self._decoder:
buf = self._decoder.decompress(binary_type())
data += buf + self._decoder.flush()
if cache_content:
self._body = data
return data
finally:
if self._original_response and self._original_response.isclosed():
self.release_conn() | [
"def",
"read",
"(",
"self",
",",
"amt",
"=",
"None",
",",
"decode_content",
"=",
"None",
",",
"cache_content",
"=",
"False",
")",
":",
"# Note: content-encoding value should be case-insensitive, per RFC 2616",
"# Section 3.5",
"content_encoding",
"=",
"self",
".",
"he... | https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/urllib3/response.py#L145-L221 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/chigger/exodus/ExodusReader.py | python | ExodusReaderErrorObserver.errors | (self) | return self._errors | Return the list of errors. | Return the list of errors. | [
"Return",
"the",
"list",
"of",
"errors",
"."
] | def errors(self):
"""
Return the list of errors.
"""
return self._errors | [
"def",
"errors",
"(",
"self",
")",
":",
"return",
"self",
".",
"_errors"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/chigger/exodus/ExodusReader.py#L54-L58 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_controls.py | python | Listbook.__init__ | (self, *args, **kwargs) | __init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=EmptyString) -> Listbook | __init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=EmptyString) -> Listbook | [
"__init__",
"(",
"self",
"Window",
"parent",
"int",
"id",
"=",
"-",
"1",
"Point",
"pos",
"=",
"DefaultPosition",
"Size",
"size",
"=",
"DefaultSize",
"long",
"style",
"=",
"0",
"String",
"name",
"=",
"EmptyString",
")",
"-",
">",
"Listbook"
] | def __init__(self, *args, **kwargs):
"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, long style=0, String name=EmptyString) -> Listbook
"""
_controls_.Listbook_swiginit(self,_controls_.new_Listbook(*args, **kwargs))
self._setOORInfo(self) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_controls_",
".",
"Listbook_swiginit",
"(",
"self",
",",
"_controls_",
".",
"new_Listbook",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_setO... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L3211-L3217 | ||
apache/impala | 8ddac48f3428c86f2cbd037ced89cfb903298b12 | bin/dump_breakpad_symbols.py | python | is_regular_file | (path) | return os.path.isfile(path) and not os.path.islink(path) | Check whether 'path' is a regular file, especially not a symlink. | Check whether 'path' is a regular file, especially not a symlink. | [
"Check",
"whether",
"path",
"is",
"a",
"regular",
"file",
"especially",
"not",
"a",
"symlink",
"."
] | def is_regular_file(path):
"""Check whether 'path' is a regular file, especially not a symlink."""
return os.path.isfile(path) and not os.path.islink(path) | [
"def",
"is_regular_file",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"and",
"not",
"os",
".",
"path",
".",
"islink",
"(",
"path",
")"
] | https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/bin/dump_breakpad_symbols.py#L146-L148 | |
nvdla/sw | 79538ba1b52b040a4a4645f630e457fa01839e90 | umd/external/protobuf-2.6/python/google/protobuf/internal/python_message.py | python | _AddPropertiesForNonRepeatedCompositeField | (field, cls) | Adds a public property for a nonrepeated, composite protocol message field.
A composite field is a "group" or "message" field.
Clients can use this property to get the value of the field, but cannot
assign to the property directly.
Args:
field: A FieldDescriptor for this field.
cls: The class we're constructing. | Adds a public property for a nonrepeated, composite protocol message field.
A composite field is a "group" or "message" field. | [
"Adds",
"a",
"public",
"property",
"for",
"a",
"nonrepeated",
"composite",
"protocol",
"message",
"field",
".",
"A",
"composite",
"field",
"is",
"a",
"group",
"or",
"message",
"field",
"."
] | def _AddPropertiesForNonRepeatedCompositeField(field, cls):
"""Adds a public property for a nonrepeated, composite protocol message field.
A composite field is a "group" or "message" field.
Clients can use this property to get the value of the field, but cannot
assign to the property directly.
Args:
field: A FieldDescriptor for this field.
cls: The class we're constructing.
"""
# TODO(robinson): Remove duplication with similar method
# for non-repeated scalars.
proto_field_name = field.name
property_name = _PropertyName(proto_field_name)
# TODO(komarek): Can anyone explain to me why we cache the message_type this
# way, instead of referring to field.message_type inside of getter(self)?
# What if someone sets message_type later on (which makes for simpler
# dyanmic proto descriptor and class creation code).
message_type = field.message_type
def getter(self):
field_value = self._fields.get(field)
if field_value is None:
# Construct a new object to represent this field.
field_value = message_type._concrete_class() # use field.message_type?
field_value._SetListener(
_OneofListener(self, field)
if field.containing_oneof is not None
else self._listener_for_children)
# Atomically check if another thread has preempted us and, if not, swap
# in the new object we just created. If someone has preempted us, we
# take that object and discard ours.
# WARNING: We are relying on setdefault() being atomic. This is true
# in CPython but we haven't investigated others. This warning appears
# in several other locations in this file.
field_value = self._fields.setdefault(field, field_value)
return field_value
getter.__module__ = None
getter.__doc__ = 'Getter for %s.' % proto_field_name
# We define a setter just so we can throw an exception with a more
# helpful error message.
def setter(self, new_value):
raise AttributeError('Assignment not allowed to composite field '
'"%s" in protocol message object.' % proto_field_name)
# Add a property to encapsulate the getter.
doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name
setattr(cls, property_name, property(getter, setter, doc=doc)) | [
"def",
"_AddPropertiesForNonRepeatedCompositeField",
"(",
"field",
",",
"cls",
")",
":",
"# TODO(robinson): Remove duplication with similar method",
"# for non-repeated scalars.",
"proto_field_name",
"=",
"field",
".",
"name",
"property_name",
"=",
"_PropertyName",
"(",
"proto_... | https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/internal/python_message.py#L492-L543 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Source/ThirdParty/FreeType2/FreeType2-2.4.12/src/tools/glnames.py | python | dump_encoding | ( file, encoding_name, encoding_list ) | dump a given encoding | dump a given encoding | [
"dump",
"a",
"given",
"encoding"
] | def dump_encoding( file, encoding_name, encoding_list ):
"""dump a given encoding"""
write = file.write
write( " /* the following are indices into the SID name table */\n" )
write( " static const unsigned short " + encoding_name +
"[" + repr( len( encoding_list ) ) + "] =\n" )
write( " {\n" )
line = " "
comma = ""
col = 0
for value in encoding_list:
line += comma
line += "%3d" % value
comma = ","
col += 1
if col == 16:
col = 0
comma = ",\n "
write( line + "\n };\n\n\n" ) | [
"def",
"dump_encoding",
"(",
"file",
",",
"encoding_name",
",",
"encoding_list",
")",
":",
"write",
"=",
"file",
".",
"write",
"write",
"(",
"\" /* the following are indices into the SID name table */\\n\"",
")",
"write",
"(",
"\" static const unsigned short \"",
"+",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/FreeType2/FreeType2-2.4.12/src/tools/glnames.py#L5186-L5207 | ||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | llvm/examples/Kaleidoscope/MCJIT/cached/split-lib.py | python | TimingScriptGenerator.writeTimingCall | (self, irname, callname) | Echo some comments and invoke both versions of toy | Echo some comments and invoke both versions of toy | [
"Echo",
"some",
"comments",
"and",
"invoke",
"both",
"versions",
"of",
"toy"
] | def writeTimingCall(self, irname, callname):
"""Echo some comments and invoke both versions of toy"""
rootname = irname
if '.' in irname:
rootname = irname[:irname.rfind('.')]
self.shfile.write("echo \"%s: Calls %s\" >> %s\n" % (callname, irname, self.timeFile))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-mcjit -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With MCJIT again\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-mcjit -use-object-cache -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"With JIT\" >> %s\n" % self.timeFile)
self.shfile.write("/usr/bin/time -f \"Command %C\\n\\tuser time: %U s\\n\\tsytem time: %S s\\n\\tmax set: %M kb\"")
self.shfile.write(" -o %s -a " % self.timeFile)
self.shfile.write("./toy-jit -input-IR=%s < %s > %s-mcjit.out 2> %s-mcjit.err\n" % (irname, callname, rootname, rootname))
self.shfile.write("echo \"\" >> %s\n" % self.timeFile)
self.shfile.write("echo \"\" >> %s\n" % self.timeFile) | [
"def",
"writeTimingCall",
"(",
"self",
",",
"irname",
",",
"callname",
")",
":",
"rootname",
"=",
"irname",
"if",
"'.'",
"in",
"irname",
":",
"rootname",
"=",
"irname",
"[",
":",
"irname",
".",
"rfind",
"(",
"'.'",
")",
"]",
"self",
".",
"shfile",
".... | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/llvm/examples/Kaleidoscope/MCJIT/cached/split-lib.py#L12-L34 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/ceph-volume/ceph_volume/api/lvm.py | python | Volume.set_tag | (self, key, value) | Set the key/value pair as an LVM tag. | Set the key/value pair as an LVM tag. | [
"Set",
"the",
"key",
"/",
"value",
"pair",
"as",
"an",
"LVM",
"tag",
"."
] | def set_tag(self, key, value):
"""
Set the key/value pair as an LVM tag.
"""
# remove it first if it exists
self.clear_tag(key)
process.call(
[
'lvchange',
'--addtag', '%s=%s' % (key, value), self.lv_path
],
run_on_host=True
)
self.tags[key] = value | [
"def",
"set_tag",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# remove it first if it exists",
"self",
".",
"clear_tag",
"(",
"key",
")",
"process",
".",
"call",
"(",
"[",
"'lvchange'",
",",
"'--addtag'",
",",
"'%s=%s'",
"%",
"(",
"key",
",",
"valu... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/ceph-volume/ceph_volume/api/lvm.py#L902-L916 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/fixer_util.py | python | Assign | (target, source) | return Node(syms.atom,
target + [Leaf(token.EQUAL, u"=", prefix=u" ")] + source) | Build an assignment statement | Build an assignment statement | [
"Build",
"an",
"assignment",
"statement"
] | def Assign(target, source):
"""Build an assignment statement"""
if not isinstance(target, list):
target = [target]
if not isinstance(source, list):
source.prefix = u" "
source = [source]
return Node(syms.atom,
target + [Leaf(token.EQUAL, u"=", prefix=u" ")] + source) | [
"def",
"Assign",
"(",
"target",
",",
"source",
")",
":",
"if",
"not",
"isinstance",
"(",
"target",
",",
"list",
")",
":",
"target",
"=",
"[",
"target",
"]",
"if",
"not",
"isinstance",
"(",
"source",
",",
"list",
")",
":",
"source",
".",
"prefix",
"... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/fixer_util.py#L27-L36 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/computation/expr.py | python | _replace_booleans | (tok) | return toknum, tokval | Replace ``&`` with ``and`` and ``|`` with ``or`` so that bitwise
precedence is changed to boolean precedence.
Parameters
----------
tok : tuple of int, str
ints correspond to the all caps constants in the tokenize module
Returns
-------
t : tuple of int, str
Either the input or token or the replacement values | Replace ``&`` with ``and`` and ``|`` with ``or`` so that bitwise
precedence is changed to boolean precedence. | [
"Replace",
"&",
"with",
"and",
"and",
"|",
"with",
"or",
"so",
"that",
"bitwise",
"precedence",
"is",
"changed",
"to",
"boolean",
"precedence",
"."
] | def _replace_booleans(tok):
"""Replace ``&`` with ``and`` and ``|`` with ``or`` so that bitwise
precedence is changed to boolean precedence.
Parameters
----------
tok : tuple of int, str
ints correspond to the all caps constants in the tokenize module
Returns
-------
t : tuple of int, str
Either the input or token or the replacement values
"""
toknum, tokval = tok
if toknum == tokenize.OP:
if tokval == '&':
return tokenize.NAME, 'and'
elif tokval == '|':
return tokenize.NAME, 'or'
return toknum, tokval
return toknum, tokval | [
"def",
"_replace_booleans",
"(",
"tok",
")",
":",
"toknum",
",",
"tokval",
"=",
"tok",
"if",
"toknum",
"==",
"tokenize",
".",
"OP",
":",
"if",
"tokval",
"==",
"'&'",
":",
"return",
"tokenize",
".",
"NAME",
",",
"'and'",
"elif",
"tokval",
"==",
"'|'",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/computation/expr.py#L56-L77 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/calendar.py | python | CalendarCtrlBase.EnableHolidayDisplay | (*args, **kwargs) | return _calendar.CalendarCtrlBase_EnableHolidayDisplay(*args, **kwargs) | EnableHolidayDisplay(self, bool display=True)
This function should be used instead of changing CAL_SHOW_HOLIDAYS
style bit directly. It enables or disables the special highlighting of
the holidays. | EnableHolidayDisplay(self, bool display=True) | [
"EnableHolidayDisplay",
"(",
"self",
"bool",
"display",
"=",
"True",
")"
] | def EnableHolidayDisplay(*args, **kwargs):
"""
EnableHolidayDisplay(self, bool display=True)
This function should be used instead of changing CAL_SHOW_HOLIDAYS
style bit directly. It enables or disables the special highlighting of
the holidays.
"""
return _calendar.CalendarCtrlBase_EnableHolidayDisplay(*args, **kwargs) | [
"def",
"EnableHolidayDisplay",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_calendar",
".",
"CalendarCtrlBase_EnableHolidayDisplay",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/calendar.py#L350-L358 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/utils/wildcard.py | python | list_namespace | (namespace, type_pattern, filter, ignore_case=False, show_all=False) | Return dictionary of all objects in a namespace dictionary that match
type_pattern and filter. | Return dictionary of all objects in a namespace dictionary that match
type_pattern and filter. | [
"Return",
"dictionary",
"of",
"all",
"objects",
"in",
"a",
"namespace",
"dictionary",
"that",
"match",
"type_pattern",
"and",
"filter",
"."
] | def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False):
"""Return dictionary of all objects in a namespace dictionary that match
type_pattern and filter."""
pattern_list=filter.split(".")
if len(pattern_list) == 1:
return filter_ns(namespace, name_pattern=pattern_list[0],
type_pattern=type_pattern,
ignore_case=ignore_case, show_all=show_all)
else:
# This is where we can change if all objects should be searched or
# only modules. Just change the type_pattern to module to search only
# modules
filtered = filter_ns(namespace, name_pattern=pattern_list[0],
type_pattern="all",
ignore_case=ignore_case, show_all=show_all)
results = {}
for name, obj in iteritems(filtered):
ns = list_namespace(dict_dir(obj), type_pattern,
".".join(pattern_list[1:]),
ignore_case=ignore_case, show_all=show_all)
for inner_name, inner_obj in iteritems(ns):
results["%s.%s"%(name,inner_name)] = inner_obj
return results | [
"def",
"list_namespace",
"(",
"namespace",
",",
"type_pattern",
",",
"filter",
",",
"ignore_case",
"=",
"False",
",",
"show_all",
"=",
"False",
")",
":",
"pattern_list",
"=",
"filter",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"pattern_list",
")",... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/utils/wildcard.py#L90-L112 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Pygments/py3/pygments/lexer.py | python | RegexLexerMeta._process_state | (cls, unprocessed, processed, state) | return tokens | Preprocess a single state definition. | Preprocess a single state definition. | [
"Preprocess",
"a",
"single",
"state",
"definition",
"."
] | def _process_state(cls, unprocessed, processed, state):
"""Preprocess a single state definition."""
assert type(state) is str, "wrong state name %r" % state
assert state[0] != '#', "invalid state name %r" % state
if state in processed:
return processed[state]
tokens = processed[state] = []
rflags = cls.flags
for tdef in unprocessed[state]:
if isinstance(tdef, include):
# it's a state reference
assert tdef != state, "circular state reference %r" % state
tokens.extend(cls._process_state(unprocessed, processed,
str(tdef)))
continue
if isinstance(tdef, _inherit):
# should be processed already, but may not in the case of:
# 1. the state has no counterpart in any parent
# 2. the state includes more than one 'inherit'
continue
if isinstance(tdef, default):
new_state = cls._process_new_state(tdef.state, unprocessed, processed)
tokens.append((re.compile('').match, None, new_state))
continue
assert type(tdef) is tuple, "wrong rule def %r" % tdef
try:
rex = cls._process_regex(tdef[0], rflags, state)
except Exception as err:
raise ValueError("uncompilable regex %r in state %r of %r: %s" %
(tdef[0], state, cls, err)) from err
token = cls._process_token(tdef[1])
if len(tdef) == 2:
new_state = None
else:
new_state = cls._process_new_state(tdef[2],
unprocessed, processed)
tokens.append((rex, token, new_state))
return tokens | [
"def",
"_process_state",
"(",
"cls",
",",
"unprocessed",
",",
"processed",
",",
"state",
")",
":",
"assert",
"type",
"(",
"state",
")",
"is",
"str",
",",
"\"wrong state name %r\"",
"%",
"state",
"assert",
"state",
"[",
"0",
"]",
"!=",
"'#'",
",",
"\"inva... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/lexer.py#L467-L509 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/android_platform/development/scripts/stack_core.py | python | ConvertTrace | (lines, more_info) | Convert strings containing native crash to a stack. | Convert strings containing native crash to a stack. | [
"Convert",
"strings",
"containing",
"native",
"crash",
"to",
"a",
"stack",
"."
] | def ConvertTrace(lines, more_info):
"""Convert strings containing native crash to a stack."""
process_info_line = re.compile("(pid: [0-9]+, tid: [0-9]+.*)")
signal_line = re.compile("(signal [0-9]+ \(.*\).*)")
register_line = re.compile("(([ ]*[0-9a-z]{2} [0-9a-f]{8}){4})")
thread_line = re.compile("(.*)(\-\-\- ){15}\-\-\-")
dalvik_jni_thread_line = re.compile("(\".*\" prio=[0-9]+ tid=[0-9]+ NATIVE.*)")
dalvik_native_thread_line = re.compile("(\".*\" sysTid=[0-9]+ nice=[0-9]+.*)")
# Note that both trace and value line matching allow for variable amounts of
# whitespace (e.g. \t). This is because the we want to allow for the stack
# tool to operate on AndroidFeedback provided system logs. AndroidFeedback
# strips out double spaces that are found in tombsone files and logcat output.
#
# Examples of matched trace lines include lines from tombstone files like:
# #00 pc 001cf42e /data/data/com.my.project/lib/libmyproject.so
# #00 pc 001cf42e /data/data/com.my.project/lib/libmyproject.so (symbol)
# Or lines from AndroidFeedback crash report system logs like:
# 03-25 00:51:05.520 I/DEBUG ( 65): #00 pc 001cf42e /data/data/com.my.project/lib/libmyproject.so
# Please note the spacing differences.
trace_line = re.compile("(.*)\#(?P<frame>[0-9]+)[ \t]+(..)[ \t]+(0x)?(?P<address>[0-9a-f]{0,8})[ \t]+(?P<lib>[^\r\n \t]*)(?P<symbol_present> \((?P<symbol_name>.*)\))?") # pylint: disable-msg=C6310
# Examples of matched value lines include:
# bea4170c 8018e4e9 /data/data/com.my.project/lib/libmyproject.so
# bea4170c 8018e4e9 /data/data/com.my.project/lib/libmyproject.so (symbol)
# 03-25 00:51:05.530 I/DEBUG ( 65): bea4170c 8018e4e9 /data/data/com.my.project/lib/libmyproject.so
# Again, note the spacing differences.
value_line = re.compile("(.*)([0-9a-f]{8})[ \t]+([0-9a-f]{8})[ \t]+([^\r\n \t]*)( \((.*)\))?")
# Lines from 'code around' sections of the output will be matched before
# value lines because otheriwse the 'code around' sections will be confused as
# value lines.
#
# Examples include:
# 801cf40c ffffc4cc 00b2f2c5 00b2f1c7 00c1e1a8
# 03-25 00:51:05.530 I/DEBUG ( 65): 801cf40c ffffc4cc 00b2f2c5 00b2f1c7 00c1e1a8
code_line = re.compile("(.*)[ \t]*[a-f0-9]{8}[ \t]*[a-f0-9]{8}[ \t]*[a-f0-9]{8}[ \t]*[a-f0-9]{8}[ \t]*[a-f0-9]{8}[ \t]*[ \r\n]") # pylint: disable-msg=C6310
trace_lines = []
value_lines = []
last_frame = -1
# It is faster to get symbol information with a single call rather than with
# separate calls for each line. Since symbol.SymbolInformation caches results,
# we can extract all the addresses that we will want symbol information for
# from the log and call symbol.SymbolInformation so that the results are
# cached in the following lookups.
code_addresses = {}
for ln in lines:
line = unicode(ln, errors='ignore')
lib, address = None, None
match = trace_line.match(line)
if match:
address, lib = match.group('address', 'lib')
match = value_line.match(line)
if match and not code_line.match(line):
(_0, _1, address, lib, _2, _3) = match.groups()
if lib:
code_addresses.setdefault(lib, set()).add(address)
for lib in code_addresses:
symbol.SymbolInformationForSet(
symbol.TranslateLibPath(lib), code_addresses[lib], more_info)
for ln in lines:
# AndroidFeedback adds zero width spaces into its crash reports. These
# should be removed or the regular expresssions will fail to match.
line = unicode(ln, errors='ignore')
process_header = process_info_line.search(line)
signal_header = signal_line.search(line)
register_header = register_line.search(line)
thread_header = thread_line.search(line)
dalvik_jni_thread_header = dalvik_jni_thread_line.search(line)
dalvik_native_thread_header = dalvik_native_thread_line.search(line)
if process_header or signal_header or register_header or thread_header \
or dalvik_jni_thread_header or dalvik_native_thread_header:
if trace_lines or value_lines:
PrintOutput(trace_lines, value_lines, more_info)
PrintDivider()
trace_lines = []
value_lines = []
last_frame = -1
if process_header:
print process_header.group(1)
if signal_header:
print signal_header.group(1)
if register_header:
print register_header.group(1)
if thread_header:
print thread_header.group(1)
if dalvik_jni_thread_header:
print dalvik_jni_thread_header.group(1)
if dalvik_native_thread_header:
print dalvik_native_thread_header.group(1)
continue
if trace_line.match(line):
match = trace_line.match(line)
frame, code_addr, area, symbol_present, symbol_name = match.group(
'frame', 'address', 'lib', 'symbol_present', 'symbol_name')
if frame <= last_frame and (trace_lines or value_lines):
PrintOutput(trace_lines, value_lines, more_info)
PrintDivider()
trace_lines = []
value_lines = []
last_frame = frame
if area == UNKNOWN or area == HEAP or area == STACK:
trace_lines.append((code_addr, "", area))
else:
# If a calls b which further calls c and c is inlined to b, we want to
# display "a -> b -> c" in the stack trace instead of just "a -> c"
info = symbol.SymbolInformation(area, code_addr, more_info)
nest_count = len(info) - 1
for (source_symbol, source_location, object_symbol_with_offset) in info:
if not source_symbol:
if symbol_present:
source_symbol = symbol.CallCppFilt(symbol_name)
else:
source_symbol = UNKNOWN
if not source_location:
source_location = area
if nest_count > 0:
nest_count = nest_count - 1
trace_lines.append(("v------>", source_symbol, source_location))
else:
if not object_symbol_with_offset:
object_symbol_with_offset = source_symbol
trace_lines.append((code_addr,
object_symbol_with_offset,
source_location))
if code_line.match(line):
# Code lines should be ignored. If this were exluded the 'code around'
# sections would trigger value_line matches.
continue;
if value_line.match(line):
match = value_line.match(line)
(unused_, addr, value, area, symbol_present, symbol_name) = match.groups()
if area == UNKNOWN or area == HEAP or area == STACK or not area:
value_lines.append((addr, value, "", area))
else:
info = symbol.SymbolInformation(area, value, more_info)
(source_symbol, source_location, object_symbol_with_offset) = info.pop()
if not source_symbol:
if symbol_present:
source_symbol = symbol.CallCppFilt(symbol_name)
else:
source_symbol = UNKNOWN
if not source_location:
source_location = area
if not object_symbol_with_offset:
object_symbol_with_offset = source_symbol
value_lines.append((addr,
value,
object_symbol_with_offset,
source_location))
PrintOutput(trace_lines, value_lines, more_info) | [
"def",
"ConvertTrace",
"(",
"lines",
",",
"more_info",
")",
":",
"process_info_line",
"=",
"re",
".",
"compile",
"(",
"\"(pid: [0-9]+, tid: [0-9]+.*)\"",
")",
"signal_line",
"=",
"re",
".",
"compile",
"(",
"\"(signal [0-9]+ \\(.*\\).*)\"",
")",
"register_line",
"=",... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/android_platform/development/scripts/stack_core.py#L67-L224 | ||
linyouhappy/kongkongxiyou | 7a69b2913eb29f4be77f9a62fb90cdd72c4160f1 | cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | TypeKind.spelling | (self) | return conf.lib.clang_getTypeKindSpelling(self.value) | Retrieve the spelling of this TypeKind. | Retrieve the spelling of this TypeKind. | [
"Retrieve",
"the",
"spelling",
"of",
"this",
"TypeKind",
"."
] | def spelling(self):
"""Retrieve the spelling of this TypeKind."""
return conf.lib.clang_getTypeKindSpelling(self.value) | [
"def",
"spelling",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTypeKindSpelling",
"(",
"self",
".",
"value",
")"
] | https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1570-L1572 | |
chuckcho/video-caffe | fc232b3e3a90ea22dd041b9fc5c542f170581f20 | tools/extra/parse_log.py | python | parse_line_for_net_output | (regex_obj, row, row_dict_list,
line, iteration, seconds, learning_rate) | return row_dict_list, row | Parse a single line for training or test output
Returns a a tuple with (row_dict_list, row)
row: may be either a new row or an augmented version of the current row
row_dict_list: may be either the current row_dict_list or an augmented
version of the current row_dict_list | Parse a single line for training or test output | [
"Parse",
"a",
"single",
"line",
"for",
"training",
"or",
"test",
"output"
] | def parse_line_for_net_output(regex_obj, row, row_dict_list,
line, iteration, seconds, learning_rate):
"""Parse a single line for training or test output
Returns a a tuple with (row_dict_list, row)
row: may be either a new row or an augmented version of the current row
row_dict_list: may be either the current row_dict_list or an augmented
version of the current row_dict_list
"""
output_match = regex_obj.search(line)
if output_match:
if not row or row['NumIters'] != iteration:
# Push the last row and start a new one
if row:
# If we're on a new iteration, push the last row
# This will probably only happen for the first row; otherwise
# the full row checking logic below will push and clear full
# rows
row_dict_list.append(row)
row = OrderedDict([
('NumIters', iteration),
('Seconds', seconds),
('LearningRate', learning_rate)
])
# output_num is not used; may be used in the future
# output_num = output_match.group(1)
output_name = output_match.group(2)
output_val = output_match.group(3)
row[output_name] = float(output_val)
if row and len(row_dict_list) >= 1 and len(row) == len(row_dict_list[0]):
# The row is full, based on the fact that it has the same number of
# columns as the first row; append it to the list
row_dict_list.append(row)
row = None
return row_dict_list, row | [
"def",
"parse_line_for_net_output",
"(",
"regex_obj",
",",
"row",
",",
"row_dict_list",
",",
"line",
",",
"iteration",
",",
"seconds",
",",
"learning_rate",
")",
":",
"output_match",
"=",
"regex_obj",
".",
"search",
"(",
"line",
")",
"if",
"output_match",
":",... | https://github.com/chuckcho/video-caffe/blob/fc232b3e3a90ea22dd041b9fc5c542f170581f20/tools/extra/parse_log.py#L86-L125 | |
Kitware/VTK | 5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8 | Wrapping/Python/vtkmodules/tk/vtkTkRenderWidget.py | python | vtkTkRenderWidget.GetDesiredUpdateRate | (self) | return self._DesiredUpdateRate | Mirrors the method with the same name in
vtkRenderWindowInteractor. | Mirrors the method with the same name in
vtkRenderWindowInteractor. | [
"Mirrors",
"the",
"method",
"with",
"the",
"same",
"name",
"in",
"vtkRenderWindowInteractor",
"."
] | def GetDesiredUpdateRate(self):
"""Mirrors the method with the same name in
vtkRenderWindowInteractor."""
return self._DesiredUpdateRate | [
"def",
"GetDesiredUpdateRate",
"(",
"self",
")",
":",
"return",
"self",
".",
"_DesiredUpdateRate"
] | https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/tk/vtkTkRenderWidget.py#L195-L198 | |
RoboJackets/robocup-software | bce13ce53ddb2ecb9696266d980722c34617dc15 | rj_gameplay/stp/rc.py | python | Field.center_field_loc | (self) | return np.array([0.0, self.length_m / 2]) | Conveniance function for getting the center field location
:return: the location of the center of the field | Conveniance function for getting the center field location
:return: the location of the center of the field | [
"Conveniance",
"function",
"for",
"getting",
"the",
"center",
"field",
"location",
":",
"return",
":",
"the",
"location",
"of",
"the",
"center",
"of",
"the",
"field"
] | def center_field_loc(self) -> np.ndarray:
"""
Conveniance function for getting the center field location
:return: the location of the center of the field
"""
return np.array([0.0, self.length_m / 2]) | [
"def",
"center_field_loc",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"np",
".",
"array",
"(",
"[",
"0.0",
",",
"self",
".",
"length_m",
"/",
"2",
"]",
")"
] | https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/stp/rc.py#L362-L367 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/composite/multitype_ops/_constexpr_utils.py | python | generate_broadcast_shape | (shapes, op_name) | return tuple(broadcast_shape) | Generate broadcast shape for a tuple of shape. | Generate broadcast shape for a tuple of shape. | [
"Generate",
"broadcast",
"shape",
"for",
"a",
"tuple",
"of",
"shape",
"."
] | def generate_broadcast_shape(shapes, op_name):
"""Generate broadcast shape for a tuple of shape."""
if not shapes:
return ()
broadcast_shape = shapes[0]
for i, shape in enumerate(shapes):
logger.debug(f"Broadcasts the {i}th tensor, the shape is {shape}.")
try:
broadcast_shape = op_utils.get_broadcast_shape(
broadcast_shape, shape, op_name)
except ValueError as ex:
raise IndexError(ex)
return tuple(broadcast_shape) | [
"def",
"generate_broadcast_shape",
"(",
"shapes",
",",
"op_name",
")",
":",
"if",
"not",
"shapes",
":",
"return",
"(",
")",
"broadcast_shape",
"=",
"shapes",
"[",
"0",
"]",
"for",
"i",
",",
"shape",
"in",
"enumerate",
"(",
"shapes",
")",
":",
"logger",
... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/_constexpr_utils.py#L442-L454 | |
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Modules/Scripted/EditorLib/EditUtil.py | python | EditUtil.structureVolume | (masterNode, structureName, mergeVolumePostfix="-label") | return slicer.util.getFirstNodeByName(structureVolumeName, className=masterNode.GetClassName()) | Return the per-structure volume associated with the master node for the given
structure name | Return the per-structure volume associated with the master node for the given
structure name | [
"Return",
"the",
"per",
"-",
"structure",
"volume",
"associated",
"with",
"the",
"master",
"node",
"for",
"the",
"given",
"structure",
"name"
] | def structureVolume(masterNode, structureName, mergeVolumePostfix="-label"):
"""Return the per-structure volume associated with the master node for the given
structure name"""
masterName = masterNode.GetName()
structureVolumeName = masterName+"-%s"%structureName + mergeVolumePostfix
return slicer.util.getFirstNodeByName(structureVolumeName, className=masterNode.GetClassName()) | [
"def",
"structureVolume",
"(",
"masterNode",
",",
"structureName",
",",
"mergeVolumePostfix",
"=",
"\"-label\"",
")",
":",
"masterName",
"=",
"masterNode",
".",
"GetName",
"(",
")",
"structureVolumeName",
"=",
"masterName",
"+",
"\"-%s\"",
"%",
"structureName",
"+... | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/EditorLib/EditUtil.py#L308-L313 | |
vmware/concord-bft | ec036a384b4c81be0423d4b429bd37900b13b864 | util/pyclient/bft_client.py | python | BftClient._process_received_msg | (self, data, sender, replicas_addr, required_replies, cancel_scope) | Called by child class to process a received message. At this point it's unknown if message is valid | Called by child class to process a received message. At this point it's unknown if message is valid | [
"Called",
"by",
"child",
"class",
"to",
"process",
"a",
"received",
"message",
".",
"At",
"this",
"point",
"it",
"s",
"unknown",
"if",
"message",
"is",
"valid"
] | def _process_received_msg(self, data, sender, replicas_addr, required_replies, cancel_scope):
"""Called by child class to process a received message. At this point it's unknown if message is valid"""
rsi_msg = RSI.MsgWithReplicaSpecificInfo(data, sender)
header, reply = rsi_msg.get_common_reply()
if self._valid_reply(header, rsi_msg.get_sender_id(), replicas_addr):
self.replies_manager.add_reply(rsi_msg)
if self.replies_manager.has_quorum_on_all(required_replies):
self.replies = self.replies_manager.get_all_replies()
rsi_replies = self.replies_manager.get_rsi_replies(rsi_msg.get_matched_reply_key())
for r in rsi_replies:
rsi_reply = rsi_replies[r]
self.rsi_replies[r] = rsi_reply.get_rsi_data()
if r not in self.ro_replicas:
self.primary = self.replicas[rsi_reply.get_primary()]
cancel_scope.cancel() | [
"def",
"_process_received_msg",
"(",
"self",
",",
"data",
",",
"sender",
",",
"replicas_addr",
",",
"required_replies",
",",
"cancel_scope",
")",
":",
"rsi_msg",
"=",
"RSI",
".",
"MsgWithReplicaSpecificInfo",
"(",
"data",
",",
"sender",
")",
"header",
",",
"re... | https://github.com/vmware/concord-bft/blob/ec036a384b4c81be0423d4b429bd37900b13b864/util/pyclient/bft_client.py#L332-L346 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | StandardPaths.GetExecutablePath | (*args, **kwargs) | return _misc_.StandardPaths_GetExecutablePath(*args, **kwargs) | GetExecutablePath(self) -> String
Return the path (directory+filename) of the running executable or an
empty string if it couldn't be determined. The path is returned as an
absolute path whenever possible. | GetExecutablePath(self) -> String | [
"GetExecutablePath",
"(",
"self",
")",
"-",
">",
"String"
] | def GetExecutablePath(*args, **kwargs):
"""
GetExecutablePath(self) -> String
Return the path (directory+filename) of the running executable or an
empty string if it couldn't be determined. The path is returned as an
absolute path whenever possible.
"""
return _misc_.StandardPaths_GetExecutablePath(*args, **kwargs) | [
"def",
"GetExecutablePath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"StandardPaths_GetExecutablePath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L6299-L6307 | |
arx/ArxLibertatis | 0313c51625f3f55016cdad43d2c7f7296d27949c | scripts/cpplint.py | python | FileInfo.IsSource | (self) | return self.Extension()[1:] in EXTENSIONS | File has a source file extension. | File has a source file extension. | [
"File",
"has",
"a",
"source",
"file",
"extension",
"."
] | def IsSource(self):
"""File has a source file extension."""
return self.Extension()[1:] in EXTENSIONS | [
"def",
"IsSource",
"(",
"self",
")",
":",
"return",
"self",
".",
"Extension",
"(",
")",
"[",
"1",
":",
"]",
"in",
"EXTENSIONS"
] | https://github.com/arx/ArxLibertatis/blob/0313c51625f3f55016cdad43d2c7f7296d27949c/scripts/cpplint.py#L802-L804 | |
perilouswithadollarsign/cstrike15_src | f82112a2388b841d72cb62ca48ab1846dfcc11c8 | thirdparty/protobuf-2.5.0/python/google/protobuf/message_factory.py | python | MessageFactory.__init__ | (self) | Initializes a new factory. | Initializes a new factory. | [
"Initializes",
"a",
"new",
"factory",
"."
] | def __init__(self):
"""Initializes a new factory."""
self._classes = {} | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"_classes",
"=",
"{",
"}"
] | https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/message_factory.py#L44-L46 | ||
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | panreas_hnn/hed-globalweight/python/caffe/draw.py | python | get_pydot_graph | (caffe_net, rankdir, label_edges=True) | return pydot_graph | Create a data structure which represents the `caffe_net`.
Parameters
----------
caffe_net : object
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
label_edges : boolean, optional
Label the edges (default is True).
Returns
-------
pydot graph object | Create a data structure which represents the `caffe_net`. | [
"Create",
"a",
"data",
"structure",
"which",
"represents",
"the",
"caffe_net",
"."
] | def get_pydot_graph(caffe_net, rankdir, label_edges=True):
"""Create a data structure which represents the `caffe_net`.
Parameters
----------
caffe_net : object
rankdir : {'LR', 'TB', 'BT'}
Direction of graph layout.
label_edges : boolean, optional
Label the edges (default is True).
Returns
-------
pydot graph object
"""
pydot_graph = pydot.Dot(caffe_net.name,
graph_type='digraph',
rankdir=rankdir)
pydot_nodes = {}
pydot_edges = []
for layer in caffe_net.layer:
node_label = get_layer_label(layer, rankdir)
node_name = "%s_%s" % (layer.name, layer.type)
if (len(layer.bottom) == 1 and len(layer.top) == 1 and
layer.bottom[0] == layer.top[0]):
# We have an in-place neuron layer.
pydot_nodes[node_name] = pydot.Node(node_label,
**NEURON_LAYER_STYLE)
else:
layer_style = LAYER_STYLE_DEFAULT
layer_style['fillcolor'] = choose_color_by_layertype(layer.type)
pydot_nodes[node_name] = pydot.Node(node_label, **layer_style)
for bottom_blob in layer.bottom:
pydot_nodes[bottom_blob + '_blob'] = pydot.Node('%s' % bottom_blob,
**BLOB_STYLE)
edge_label = '""'
pydot_edges.append({'src': bottom_blob + '_blob',
'dst': node_name,
'label': edge_label})
for top_blob in layer.top:
pydot_nodes[top_blob + '_blob'] = pydot.Node('%s' % (top_blob))
if label_edges:
edge_label = get_edge_label(layer)
else:
edge_label = '""'
pydot_edges.append({'src': node_name,
'dst': top_blob + '_blob',
'label': edge_label})
# Now, add the nodes and edges to the graph.
for node in pydot_nodes.values():
pydot_graph.add_node(node)
for edge in pydot_edges:
pydot_graph.add_edge(
pydot.Edge(pydot_nodes[edge['src']],
pydot_nodes[edge['dst']],
label=edge['label']))
return pydot_graph | [
"def",
"get_pydot_graph",
"(",
"caffe_net",
",",
"rankdir",
",",
"label_edges",
"=",
"True",
")",
":",
"pydot_graph",
"=",
"pydot",
".",
"Dot",
"(",
"caffe_net",
".",
"name",
",",
"graph_type",
"=",
"'digraph'",
",",
"rankdir",
"=",
"rankdir",
")",
"pydot_... | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/panreas_hnn/hed-globalweight/python/caffe/draw.py#L121-L177 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/apitools/samples/storage_sample/storage/storage_v1.py | python | BucketsGet.RunWithArgs | (self, bucket) | Returns metadata for the specified bucket.
Args:
bucket: Name of a bucket.
Flags:
ifMetagenerationMatch: Makes the return of the bucket metadata
conditional on whether the bucket's current metageneration matches the
given value.
ifMetagenerationNotMatch: Makes the return of the bucket metadata
conditional on whether the bucket's current metageneration does not
match the given value.
projection: Set of properties to return. Defaults to noAcl. | Returns metadata for the specified bucket. | [
"Returns",
"metadata",
"for",
"the",
"specified",
"bucket",
"."
] | def RunWithArgs(self, bucket):
"""Returns metadata for the specified bucket.
Args:
bucket: Name of a bucket.
Flags:
ifMetagenerationMatch: Makes the return of the bucket metadata
conditional on whether the bucket's current metageneration matches the
given value.
ifMetagenerationNotMatch: Makes the return of the bucket metadata
conditional on whether the bucket's current metageneration does not
match the given value.
projection: Set of properties to return. Defaults to noAcl.
"""
client = GetClientFromFlags()
global_params = GetGlobalParamsFromFlags()
request = messages.StorageBucketsGetRequest(
bucket=bucket.decode('utf8'),
)
if FLAGS['ifMetagenerationMatch'].present:
request.ifMetagenerationMatch = int(FLAGS.ifMetagenerationMatch)
if FLAGS['ifMetagenerationNotMatch'].present:
request.ifMetagenerationNotMatch = int(FLAGS.ifMetagenerationNotMatch)
if FLAGS['projection'].present:
request.projection = messages.StorageBucketsGetRequest.ProjectionValueValuesEnum(FLAGS.projection)
result = client.buckets.Get(
request, global_params=global_params)
print apitools_base_cli.FormatOutput(result) | [
"def",
"RunWithArgs",
"(",
"self",
",",
"bucket",
")",
":",
"client",
"=",
"GetClientFromFlags",
"(",
")",
"global_params",
"=",
"GetGlobalParamsFromFlags",
"(",
")",
"request",
"=",
"messages",
".",
"StorageBucketsGetRequest",
"(",
"bucket",
"=",
"bucket",
".",... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/apitools/samples/storage_sample/storage/storage_v1.py#L666-L694 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/package/package_exporter.py | python | PackageExporter._intern_module | (
self,
module_name: str,
dependencies: bool,
) | Adds the module to the dependency graph as an interned module,
along with any metadata needed to write it out to the zipfile at serialization time. | Adds the module to the dependency graph as an interned module,
along with any metadata needed to write it out to the zipfile at serialization time. | [
"Adds",
"the",
"module",
"to",
"the",
"dependency",
"graph",
"as",
"an",
"interned",
"module",
"along",
"with",
"any",
"metadata",
"needed",
"to",
"write",
"it",
"out",
"to",
"the",
"zipfile",
"at",
"serialization",
"time",
"."
] | def _intern_module(
self,
module_name: str,
dependencies: bool,
):
"""Adds the module to the dependency graph as an interned module,
along with any metadata needed to write it out to the zipfile at serialization time.
"""
module_obj = self._import_module(module_name)
# Subtle: if the import above succeeded, either:
# 1. The module name is not mangled, and this was just a regular import, or
# 2. The module name is mangled, but one of the importers was able to
# recognize the mangling and import it.
# Either way, it is now safe to demangle this name so that we don't
# serialize the mangled version to the package.
module_name = demangle(module_name)
# Find dependencies of this module and require them as well.
is_package = hasattr(module_obj, "__path__")
source = self._get_source_of_module(module_obj)
if source is None:
# Couldn't find a source! Add it to our dependency graph as broken
# and continue.
filename = getattr(module_obj, "__file__", None)
error_context = None
if filename is None:
packaging_error = PackagingErrorReason.NO_DUNDER_FILE
elif filename.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES)):
packaging_error = PackagingErrorReason.IS_EXTENSION_MODULE
else:
packaging_error = PackagingErrorReason.SOURCE_FILE_NOT_FOUND
error_context = f"filename: {filename}"
self.dependency_graph.add_node(
module_name,
action=_ModuleProviderAction.INTERN,
is_package=is_package,
error=packaging_error,
error_context=error_context,
provided=True,
)
return
self.dependency_graph.add_node(
module_name,
action=_ModuleProviderAction.INTERN,
is_package=is_package,
source=source,
provided=True,
)
if dependencies:
deps = self._get_dependencies(source, module_name, is_package)
for dep in deps:
self.dependency_graph.add_edge(module_name, dep)
self.add_dependency(dep) | [
"def",
"_intern_module",
"(",
"self",
",",
"module_name",
":",
"str",
",",
"dependencies",
":",
"bool",
",",
")",
":",
"module_obj",
"=",
"self",
".",
"_import_module",
"(",
"module_name",
")",
"# Subtle: if the import above succeeded, either:",
"# 1. The module nam... | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/package/package_exporter.py#L497-L551 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/timeseries/python/timeseries/model.py | python | SequentialTimeSeriesModel._filtering_step | (self, current_times, current_values, state, predictions) | Compute a single-step loss for a batch of data.
Args:
current_times: A [batch size] Tensor of times for each observation.
current_values: A [batch size] Tensor of values for each observaiton.
state: Model state, updated to current_times.
predictions: The outputs of _prediction_step
Returns:
A tuple of (updated state, outputs):
updated state: Model state taking current_values into account.
outputs: A dictionary of Tensors with keys corresponding to
self._train_output_names, plus a special "loss" key. The value
corresponding to "loss" is minimized during training. Other outputs
may include one-step-ahead predictions, for example a predicted
location and scale. | Compute a single-step loss for a batch of data. | [
"Compute",
"a",
"single",
"-",
"step",
"loss",
"for",
"a",
"batch",
"of",
"data",
"."
] | def _filtering_step(self, current_times, current_values, state, predictions):
"""Compute a single-step loss for a batch of data.
Args:
current_times: A [batch size] Tensor of times for each observation.
current_values: A [batch size] Tensor of values for each observaiton.
state: Model state, updated to current_times.
predictions: The outputs of _prediction_step
Returns:
A tuple of (updated state, outputs):
updated state: Model state taking current_values into account.
outputs: A dictionary of Tensors with keys corresponding to
self._train_output_names, plus a special "loss" key. The value
corresponding to "loss" is minimized during training. Other outputs
may include one-step-ahead predictions, for example a predicted
location and scale.
"""
pass | [
"def",
"_filtering_step",
"(",
"self",
",",
"current_times",
",",
"current_values",
",",
"state",
",",
"predictions",
")",
":",
"pass"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/timeseries/python/timeseries/model.py#L352-L369 | ||
schwehr/libais | 1e19605942c8e155cd02fde6d1acde75ecd15d75 | third_party/gmock/scripts/generator/cpp/ast.py | python | Node.Requires | (self, node) | return False | Does this AST node require the definition of the node passed in? | Does this AST node require the definition of the node passed in? | [
"Does",
"this",
"AST",
"node",
"require",
"the",
"definition",
"of",
"the",
"node",
"passed",
"in?"
] | def Requires(self, node):
"""Does this AST node require the definition of the node passed in?"""
return False | [
"def",
"Requires",
"(",
"self",
",",
"node",
")",
":",
"return",
"False"
] | https://github.com/schwehr/libais/blob/1e19605942c8e155cd02fde6d1acde75ecd15d75/third_party/gmock/scripts/generator/cpp/ast.py#L128-L130 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/pytorch/nfsp.py | python | NFSP.restore | (self, checkpoint_dir) | Restores the average policy network and the inner RL agent's q-network.
Note that this does not restore the experience replay buffers and should
only be used to restore the agent's policy, not resume training.
Args:
checkpoint_dir: directory from which checkpoints will be restored. | Restores the average policy network and the inner RL agent's q-network. | [
"Restores",
"the",
"average",
"policy",
"network",
"and",
"the",
"inner",
"RL",
"agent",
"s",
"q",
"-",
"network",
"."
] | def restore(self, checkpoint_dir):
"""Restores the average policy network and the inner RL agent's q-network.
Note that this does not restore the experience replay buffers and should
only be used to restore the agent's policy, not resume training.
Args:
checkpoint_dir: directory from which checkpoints will be restored.
"""
for name, model in self._savers:
full_checkpoint_dir = self._full_checkpoint_name(checkpoint_dir, name)
logging.info("Restoring checkpoint: %s", full_checkpoint_dir)
model.load_state_dict(torch.load(full_checkpoint_dir)) | [
"def",
"restore",
"(",
"self",
",",
"checkpoint_dir",
")",
":",
"for",
"name",
",",
"model",
"in",
"self",
".",
"_savers",
":",
"full_checkpoint_dir",
"=",
"self",
".",
"_full_checkpoint_name",
"(",
"checkpoint_dir",
",",
"name",
")",
"logging",
".",
"info",... | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/pytorch/nfsp.py#L274-L286 | ||
domino-team/openwrt-cc | 8b181297c34d14d3ca521cc9f31430d561dbc688 | package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.WriteSourcesForArch | (self, ninja_file, config_name, config, sources,
predepends, precompiled_header, spec, arch=None) | return outputs | Write build rules to compile all of |sources|. | Write build rules to compile all of |sources|. | [
"Write",
"build",
"rules",
"to",
"compile",
"all",
"of",
"|sources|",
"."
] | def WriteSourcesForArch(self, ninja_file, config_name, config, sources,
predepends, precompiled_header, spec, arch=None):
"""Write build rules to compile all of |sources|."""
extra_defines = []
if self.flavor == 'mac':
cflags = self.xcode_settings.GetCflags(config_name, arch=arch)
cflags_c = self.xcode_settings.GetCflagsC(config_name)
cflags_cc = self.xcode_settings.GetCflagsCC(config_name)
cflags_objc = ['$cflags_c'] + \
self.xcode_settings.GetCflagsObjC(config_name)
cflags_objcc = ['$cflags_cc'] + \
self.xcode_settings.GetCflagsObjCC(config_name)
elif self.flavor == 'win':
asmflags = self.msvs_settings.GetAsmflags(config_name)
cflags = self.msvs_settings.GetCflags(config_name)
cflags_c = self.msvs_settings.GetCflagsC(config_name)
cflags_cc = self.msvs_settings.GetCflagsCC(config_name)
extra_defines = self.msvs_settings.GetComputedDefines(config_name)
# See comment at cc_command for why there's two .pdb files.
pdbpath_c = pdbpath_cc = self.msvs_settings.GetCompilerPdbName(
config_name, self.ExpandSpecial)
if not pdbpath_c:
obj = 'obj'
if self.toolset != 'target':
obj += '.' + self.toolset
pdbpath = os.path.normpath(os.path.join(obj, self.base_dir, self.name))
pdbpath_c = pdbpath + '.c.pdb'
pdbpath_cc = pdbpath + '.cc.pdb'
self.WriteVariableList(ninja_file, 'pdbname_c', [pdbpath_c])
self.WriteVariableList(ninja_file, 'pdbname_cc', [pdbpath_cc])
self.WriteVariableList(ninja_file, 'pchprefix', [self.name])
else:
cflags = config.get('cflags', [])
cflags_c = config.get('cflags_c', [])
cflags_cc = config.get('cflags_cc', [])
# Respect environment variables related to build, but target-specific
# flags can still override them.
if self.toolset == 'target':
cflags_c = (os.environ.get('CPPFLAGS', '').split() +
os.environ.get('CFLAGS', '').split() + cflags_c)
cflags_cc = (os.environ.get('CPPFLAGS', '').split() +
os.environ.get('CXXFLAGS', '').split() + cflags_cc)
elif self.toolset == 'host':
cflags_c = (os.environ.get('CPPFLAGS_host', '').split() +
os.environ.get('CFLAGS_host', '').split() + cflags_c)
cflags_cc = (os.environ.get('CPPFLAGS_host', '').split() +
os.environ.get('CXXFLAGS_host', '').split() + cflags_cc)
defines = config.get('defines', []) + extra_defines
self.WriteVariableList(ninja_file, 'defines',
[Define(d, self.flavor) for d in defines])
if self.flavor == 'win':
self.WriteVariableList(ninja_file, 'asmflags',
map(self.ExpandSpecial, asmflags))
self.WriteVariableList(ninja_file, 'rcflags',
[QuoteShellArgument(self.ExpandSpecial(f), self.flavor)
for f in self.msvs_settings.GetRcflags(config_name,
self.GypPathToNinja)])
include_dirs = config.get('include_dirs', [])
env = self.GetToolchainEnv()
if self.flavor == 'win':
include_dirs = self.msvs_settings.AdjustIncludeDirs(include_dirs,
config_name)
self.WriteVariableList(ninja_file, 'includes',
[QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor)
for i in include_dirs])
if self.flavor == 'win':
midl_include_dirs = config.get('midl_include_dirs', [])
midl_include_dirs = self.msvs_settings.AdjustMidlIncludeDirs(
midl_include_dirs, config_name)
self.WriteVariableList(ninja_file, 'midl_includes',
[QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor)
for i in midl_include_dirs])
pch_commands = precompiled_header.GetPchBuildCommands(arch)
if self.flavor == 'mac':
# Most targets use no precompiled headers, so only write these if needed.
for ext, var in [('c', 'cflags_pch_c'), ('cc', 'cflags_pch_cc'),
('m', 'cflags_pch_objc'), ('mm', 'cflags_pch_objcc')]:
include = precompiled_header.GetInclude(ext, arch)
if include: ninja_file.variable(var, include)
arflags = config.get('arflags', [])
self.WriteVariableList(ninja_file, 'cflags',
map(self.ExpandSpecial, cflags))
self.WriteVariableList(ninja_file, 'cflags_c',
map(self.ExpandSpecial, cflags_c))
self.WriteVariableList(ninja_file, 'cflags_cc',
map(self.ExpandSpecial, cflags_cc))
if self.flavor == 'mac':
self.WriteVariableList(ninja_file, 'cflags_objc',
map(self.ExpandSpecial, cflags_objc))
self.WriteVariableList(ninja_file, 'cflags_objcc',
map(self.ExpandSpecial, cflags_objcc))
self.WriteVariableList(ninja_file, 'arflags',
map(self.ExpandSpecial, arflags))
ninja_file.newline()
outputs = []
has_rc_source = False
for source in sources:
filename, ext = os.path.splitext(source)
ext = ext[1:]
obj_ext = self.obj_ext
if ext in ('cc', 'cpp', 'cxx'):
command = 'cxx'
self.uses_cpp = True
elif ext == 'c' or (ext == 'S' and self.flavor != 'win'):
command = 'cc'
elif ext == 's' and self.flavor != 'win': # Doesn't generate .o.d files.
command = 'cc_s'
elif (self.flavor == 'win' and ext == 'asm' and
not self.msvs_settings.HasExplicitAsmRules(spec)):
command = 'asm'
# Add the _asm suffix as msvs is capable of handling .cc and
# .asm files of the same name without collision.
obj_ext = '_asm.obj'
elif self.flavor == 'mac' and ext == 'm':
command = 'objc'
elif self.flavor == 'mac' and ext == 'mm':
command = 'objcxx'
self.uses_cpp = True
elif self.flavor == 'win' and ext == 'rc':
command = 'rc'
obj_ext = '.res'
has_rc_source = True
else:
# Ignore unhandled extensions.
continue
input = self.GypPathToNinja(source)
output = self.GypPathToUniqueOutput(filename + obj_ext)
if arch is not None:
output = AddArch(output, arch)
implicit = precompiled_header.GetObjDependencies([input], [output], arch)
variables = []
if self.flavor == 'win':
variables, output, implicit = precompiled_header.GetFlagsModifications(
input, output, implicit, command, cflags_c, cflags_cc,
self.ExpandSpecial)
ninja_file.build(output, command, input,
implicit=[gch for _, _, gch in implicit],
order_only=predepends, variables=variables)
outputs.append(output)
if has_rc_source:
resource_include_dirs = config.get('resource_include_dirs', include_dirs)
self.WriteVariableList(ninja_file, 'resource_includes',
[QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor)
for i in resource_include_dirs])
self.WritePchTargets(ninja_file, pch_commands)
ninja_file.newline()
return outputs | [
"def",
"WriteSourcesForArch",
"(",
"self",
",",
"ninja_file",
",",
"config_name",
",",
"config",
",",
"sources",
",",
"predepends",
",",
"precompiled_header",
",",
"spec",
",",
"arch",
"=",
"None",
")",
":",
"extra_defines",
"=",
"[",
"]",
"if",
"self",
".... | https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L884-L1042 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/SocketServer.py | python | ForkingMixIn.process_request | (self, request, client_address) | Fork a new subprocess to process the request. | Fork a new subprocess to process the request. | [
"Fork",
"a",
"new",
"subprocess",
"to",
"process",
"the",
"request",
"."
] | def process_request(self, request, client_address):
"""Fork a new subprocess to process the request."""
self.collect_children()
pid = os.fork()
if pid:
# Parent process
if self.active_children is None:
self.active_children = []
self.active_children.append(pid)
self.close_request(request)
return
else:
# Child process.
# This must never return, hence os._exit()!
try:
self.finish_request(request, client_address)
os._exit(0)
except:
try:
self.handle_error(request, client_address)
finally:
os._exit(1) | [
"def",
"process_request",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"self",
".",
"collect_children",
"(",
")",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
":",
"# Parent process",
"if",
"self",
".",
"active_children",
"is",
... | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/SocketServer.py#L520-L541 | ||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | tools/mo/openvino/tools/mo/front/common/partial_infer/caffe_fallback.py | python | caffe_native_node_infer | (node: Node) | Infers shape of the unknown operation via Caffe if it is available.
Requires graph to contain paths to both prototxt and caffemodel files.
When it is visited for the first time, net object is created and written to graph.
Next time, it just takes the built net from graph.
Parameters
----------
node node to infer the shape for | Infers shape of the unknown operation via Caffe if it is available.
Requires graph to contain paths to both prototxt and caffemodel files.
When it is visited for the first time, net object is created and written to graph.
Next time, it just takes the built net from graph. | [
"Infers",
"shape",
"of",
"the",
"unknown",
"operation",
"via",
"Caffe",
"if",
"it",
"is",
"available",
".",
"Requires",
"graph",
"to",
"contain",
"paths",
"to",
"both",
"prototxt",
"and",
"caffemodel",
"files",
".",
"When",
"it",
"is",
"visited",
"for",
"t... | def caffe_native_node_infer(node: Node):
"""
Infers shape of the unknown operation via Caffe if it is available.
Requires graph to contain paths to both prototxt and caffemodel files.
When it is visited for the first time, net object is created and written to graph.
Next time, it just takes the built net from graph.
Parameters
----------
node node to infer the shape for
"""
log.error("Caffe fallback is deprecated. It will be removed in future releases. Please use extensions for unsupported layers.\n" +
"See more information in the \"Custom Layers in the Model Optimizer\" chapter of the Model Optimizer Developer Guide",
extra={'is_warning': True})
log.info('Called "caffe_native_node_infer" for node "{}"'.format(node.id))
graph = node.graph
net = get_net(graph)
if not net:
raise Error(
'Cannot infer shape for node "{}" because there is no Caffe available. ' +
'Please register python infer function for op = {} or use Caffe for shape inference. ' +
refer_to_faq_msg(14),
node.soft_get('name'),
node.soft_get('op')
)
for iout in range(len(node.out_nodes())):
output_shape = int64_array(net.blobs[node.top].data.shape)
node.out_node(iout).shape = output_shape | [
"def",
"caffe_native_node_infer",
"(",
"node",
":",
"Node",
")",
":",
"log",
".",
"error",
"(",
"\"Caffe fallback is deprecated. It will be removed in future releases. Please use extensions for unsupported layers.\\n\"",
"+",
"\"See more information in the \\\"Custom Layers in the Model ... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/common/partial_infer/caffe_fallback.py#L79-L109 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.