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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
su2code/SU2 | 72b2fa977b64b9683a388920f05298a40d39e5c5 | SU2_PY/SU2/util/ordered_dict.py | python | OrderedDict.__reduce__ | (self) | return self.__class__, (items,) | Return state information for pickling | Return state information for pickling | [
"Return",
"state",
"information",
"for",
"pickling"
] | def __reduce__(self):
'Return state information for pickling'
items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,) | [
"def",
"__reduce__",
"(",
"self",
")",
":",
"items",
"=",
"[",
"[",
"k",
",",
"self",
"[",
"k",
"]",
"]",
"for",
"k",
"in",
"self",
"]",
"inst_dict",
"=",
"vars",
"(",
"self",
")",
".",
"copy",
"(",
")",
"for",
"k",
"in",
"vars",
"(",
"OrderedDict",
"(",
")",
")",
":",
"inst_dict",
".",
"pop",
"(",
"k",
",",
"None",
")",
"if",
"inst_dict",
":",
"return",
"(",
"self",
".",
"__class__",
",",
"(",
"items",
",",
")",
",",
"inst_dict",
")",
"return",
"self",
".",
"__class__",
",",
"(",
"items",
",",
")"
] | https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/SU2/util/ordered_dict.py#L216-L224 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/weakref.py | python | WeakKeyDictionary.iterkeyrefs | (self) | return self.data.iterkeys() | Return an iterator that yields the weak references to the keys.
The references are not guaranteed to be 'live' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the keys around longer than needed. | Return an iterator that yields the weak references to the keys. | [
"Return",
"an",
"iterator",
"that",
"yields",
"the",
"weak",
"references",
"to",
"the",
"keys",
"."
] | def iterkeyrefs(self):
"""Return an iterator that yields the weak references to the keys.
The references are not guaranteed to be 'live' at the time
they are used, so the result of calling the references needs
to be checked before being used. This can be used to avoid
creating references that will cause the garbage collector to
keep the keys around longer than needed.
"""
return self.data.iterkeys() | [
"def",
"iterkeyrefs",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"iterkeys",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/weakref.py#L314-L324 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py | python | OverrideEnvironment.Dictionary | (self) | return d | Emulates the items() method of dictionaries. | Emulates the items() method of dictionaries. | [
"Emulates",
"the",
"items",
"()",
"method",
"of",
"dictionaries",
"."
] | def Dictionary(self):
"""Emulates the items() method of dictionaries."""
d = self.__dict__['__subject'].Dictionary().copy()
d.update(self.__dict__['overrides'])
return d | [
"def",
"Dictionary",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"__dict__",
"[",
"'__subject'",
"]",
".",
"Dictionary",
"(",
")",
".",
"copy",
"(",
")",
"d",
".",
"update",
"(",
"self",
".",
"__dict__",
"[",
"'overrides'",
"]",
")",
"return",
"d"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Environment.py#L2334-L2338 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_vim.py | python | EditraCommander._GetSelectedLines | (self) | return start_line, end_line | Get the first and last line (exclusive) of selection | Get the first and last line (exclusive) of selection | [
"Get",
"the",
"first",
"and",
"last",
"line",
"(",
"exclusive",
")",
"of",
"selection"
] | def _GetSelectedLines(self):
"""Get the first and last line (exclusive) of selection"""
start, end = self._GetSelectionRange()
start_line, end_line = (self.stc.LineFromPosition(start),
self.stc.LineFromPosition(end - 1) + 1)
return start_line, end_line | [
"def",
"_GetSelectedLines",
"(",
"self",
")",
":",
"start",
",",
"end",
"=",
"self",
".",
"_GetSelectionRange",
"(",
")",
"start_line",
",",
"end_line",
"=",
"(",
"self",
".",
"stc",
".",
"LineFromPosition",
"(",
"start",
")",
",",
"self",
".",
"stc",
".",
"LineFromPosition",
"(",
"end",
"-",
"1",
")",
"+",
"1",
")",
"return",
"start_line",
",",
"end_line"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_vim.py#L811-L816 | |
google/shaka-packager | e1b0c7c45431327fd3ce193514a5407d07b39b22 | packager/third_party/protobuf/python/google/protobuf/descriptor.py | python | FieldDescriptor.__init__ | (self, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
has_default_value=True, containing_oneof=None, json_name=None) | The arguments are as described in the description of FieldDescriptor
attributes above.
Note that containing_type may be None, and may be set later if necessary
(to deal with circular references between message types, for example).
Likewise for extension_scope. | The arguments are as described in the description of FieldDescriptor
attributes above. | [
"The",
"arguments",
"are",
"as",
"described",
"in",
"the",
"description",
"of",
"FieldDescriptor",
"attributes",
"above",
"."
] | def __init__(self, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
has_default_value=True, containing_oneof=None, json_name=None):
"""The arguments are as described in the description of FieldDescriptor
attributes above.
Note that containing_type may be None, and may be set later if necessary
(to deal with circular references between message types, for example).
Likewise for extension_scope.
"""
super(FieldDescriptor, self).__init__(options, 'FieldOptions')
self.name = name
self.full_name = full_name
self._camelcase_name = None
if json_name is None:
self.json_name = _ToJsonName(name)
else:
self.json_name = json_name
self.index = index
self.number = number
self.type = type
self.cpp_type = cpp_type
self.label = label
self.has_default_value = has_default_value
self.default_value = default_value
self.containing_type = containing_type
self.message_type = message_type
self.enum_type = enum_type
self.is_extension = is_extension
self.extension_scope = extension_scope
self.containing_oneof = containing_oneof
if api_implementation.Type() == 'cpp':
if is_extension:
self._cdescriptor = _message.default_pool.FindExtensionByName(full_name)
else:
self._cdescriptor = _message.default_pool.FindFieldByName(full_name)
else:
self._cdescriptor = None | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"full_name",
",",
"index",
",",
"number",
",",
"type",
",",
"cpp_type",
",",
"label",
",",
"default_value",
",",
"message_type",
",",
"enum_type",
",",
"containing_type",
",",
"is_extension",
",",
"extension_scope",
",",
"options",
"=",
"None",
",",
"has_default_value",
"=",
"True",
",",
"containing_oneof",
"=",
"None",
",",
"json_name",
"=",
"None",
")",
":",
"super",
"(",
"FieldDescriptor",
",",
"self",
")",
".",
"__init__",
"(",
"options",
",",
"'FieldOptions'",
")",
"self",
".",
"name",
"=",
"name",
"self",
".",
"full_name",
"=",
"full_name",
"self",
".",
"_camelcase_name",
"=",
"None",
"if",
"json_name",
"is",
"None",
":",
"self",
".",
"json_name",
"=",
"_ToJsonName",
"(",
"name",
")",
"else",
":",
"self",
".",
"json_name",
"=",
"json_name",
"self",
".",
"index",
"=",
"index",
"self",
".",
"number",
"=",
"number",
"self",
".",
"type",
"=",
"type",
"self",
".",
"cpp_type",
"=",
"cpp_type",
"self",
".",
"label",
"=",
"label",
"self",
".",
"has_default_value",
"=",
"has_default_value",
"self",
".",
"default_value",
"=",
"default_value",
"self",
".",
"containing_type",
"=",
"containing_type",
"self",
".",
"message_type",
"=",
"message_type",
"self",
".",
"enum_type",
"=",
"enum_type",
"self",
".",
"is_extension",
"=",
"is_extension",
"self",
".",
"extension_scope",
"=",
"extension_scope",
"self",
".",
"containing_oneof",
"=",
"containing_oneof",
"if",
"api_implementation",
".",
"Type",
"(",
")",
"==",
"'cpp'",
":",
"if",
"is_extension",
":",
"self",
".",
"_cdescriptor",
"=",
"_message",
".",
"default_pool",
".",
"FindExtensionByName",
"(",
"full_name",
")",
"else",
":",
"self",
".",
"_cdescriptor",
"=",
"_message",
".",
"default_pool",
".",
"FindFieldByName",
"(",
"full_name",
")",
"else",
":",
"self",
".",
"_cdescriptor",
"=",
"None"
] | https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/descriptor.py#L500-L538 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | build/android/pylib/utils/isolator.py | python | Isolator.Clear | (self) | Deletes the isolate dependency directory. | Deletes the isolate dependency directory. | [
"Deletes",
"the",
"isolate",
"dependency",
"directory",
"."
] | def Clear(self):
"""Deletes the isolate dependency directory."""
if os.path.exists(self._isolate_deps_dir):
shutil.rmtree(self._isolate_deps_dir) | [
"def",
"Clear",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_isolate_deps_dir",
")",
":",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"_isolate_deps_dir",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/build/android/pylib/utils/isolator.py#L73-L76 | ||
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/optim/lr_scheduler.py | python | CosineAnnealingWarmRestarts.step | (self, epoch=None) | Step could be called after every batch update
Example:
>>> scheduler = CosineAnnealingWarmRestarts(optimizer, T_0, T_mult)
>>> iters = len(dataloader)
>>> for epoch in range(20):
>>> for i, sample in enumerate(dataloader):
>>> inputs, labels = sample['inputs'], sample['labels']
>>> optimizer.zero_grad()
>>> outputs = net(inputs)
>>> loss = criterion(outputs, labels)
>>> loss.backward()
>>> optimizer.step()
>>> scheduler.step(epoch + i / iters)
This function can be called in an interleaved way.
Example:
>>> scheduler = CosineAnnealingWarmRestarts(optimizer, T_0, T_mult)
>>> for epoch in range(20):
>>> scheduler.step()
>>> scheduler.step(26)
>>> scheduler.step() # scheduler.step(27), instead of scheduler(20) | Step could be called after every batch update | [
"Step",
"could",
"be",
"called",
"after",
"every",
"batch",
"update"
] | def step(self, epoch=None):
"""Step could be called after every batch update
Example:
>>> scheduler = CosineAnnealingWarmRestarts(optimizer, T_0, T_mult)
>>> iters = len(dataloader)
>>> for epoch in range(20):
>>> for i, sample in enumerate(dataloader):
>>> inputs, labels = sample['inputs'], sample['labels']
>>> optimizer.zero_grad()
>>> outputs = net(inputs)
>>> loss = criterion(outputs, labels)
>>> loss.backward()
>>> optimizer.step()
>>> scheduler.step(epoch + i / iters)
This function can be called in an interleaved way.
Example:
>>> scheduler = CosineAnnealingWarmRestarts(optimizer, T_0, T_mult)
>>> for epoch in range(20):
>>> scheduler.step()
>>> scheduler.step(26)
>>> scheduler.step() # scheduler.step(27), instead of scheduler(20)
"""
if epoch is None and self.last_epoch < 0:
epoch = 0
if epoch is None:
epoch = self.last_epoch + 1
self.T_cur = self.T_cur + 1
if self.T_cur >= self.T_i:
self.T_cur = self.T_cur - self.T_i
self.T_i = self.T_i * self.T_mult
else:
if epoch < 0:
raise ValueError("Expected non-negative epoch, but got {}".format(epoch))
if epoch >= self.T_0:
if self.T_mult == 1:
self.T_cur = epoch % self.T_0
else:
n = int(math.log((epoch / self.T_0 * (self.T_mult - 1) + 1), self.T_mult))
self.T_cur = epoch - self.T_0 * (self.T_mult ** n - 1) / (self.T_mult - 1)
self.T_i = self.T_0 * self.T_mult ** (n)
else:
self.T_i = self.T_0
self.T_cur = epoch
self.last_epoch = math.floor(epoch)
class _enable_get_lr_call:
def __init__(self, o):
self.o = o
def __enter__(self):
self.o._get_lr_called_within_step = True
return self
def __exit__(self, type, value, traceback):
self.o._get_lr_called_within_step = False
return self
with _enable_get_lr_call(self):
for i, data in enumerate(zip(self.optimizer.param_groups, self.get_lr())):
param_group, lr = data
param_group['lr'] = lr
self.print_lr(self.verbose, i, lr, epoch)
self._last_lr = [group['lr'] for group in self.optimizer.param_groups] | [
"def",
"step",
"(",
"self",
",",
"epoch",
"=",
"None",
")",
":",
"if",
"epoch",
"is",
"None",
"and",
"self",
".",
"last_epoch",
"<",
"0",
":",
"epoch",
"=",
"0",
"if",
"epoch",
"is",
"None",
":",
"epoch",
"=",
"self",
".",
"last_epoch",
"+",
"1",
"self",
".",
"T_cur",
"=",
"self",
".",
"T_cur",
"+",
"1",
"if",
"self",
".",
"T_cur",
">=",
"self",
".",
"T_i",
":",
"self",
".",
"T_cur",
"=",
"self",
".",
"T_cur",
"-",
"self",
".",
"T_i",
"self",
".",
"T_i",
"=",
"self",
".",
"T_i",
"*",
"self",
".",
"T_mult",
"else",
":",
"if",
"epoch",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Expected non-negative epoch, but got {}\"",
".",
"format",
"(",
"epoch",
")",
")",
"if",
"epoch",
">=",
"self",
".",
"T_0",
":",
"if",
"self",
".",
"T_mult",
"==",
"1",
":",
"self",
".",
"T_cur",
"=",
"epoch",
"%",
"self",
".",
"T_0",
"else",
":",
"n",
"=",
"int",
"(",
"math",
".",
"log",
"(",
"(",
"epoch",
"/",
"self",
".",
"T_0",
"*",
"(",
"self",
".",
"T_mult",
"-",
"1",
")",
"+",
"1",
")",
",",
"self",
".",
"T_mult",
")",
")",
"self",
".",
"T_cur",
"=",
"epoch",
"-",
"self",
".",
"T_0",
"*",
"(",
"self",
".",
"T_mult",
"**",
"n",
"-",
"1",
")",
"/",
"(",
"self",
".",
"T_mult",
"-",
"1",
")",
"self",
".",
"T_i",
"=",
"self",
".",
"T_0",
"*",
"self",
".",
"T_mult",
"**",
"(",
"n",
")",
"else",
":",
"self",
".",
"T_i",
"=",
"self",
".",
"T_0",
"self",
".",
"T_cur",
"=",
"epoch",
"self",
".",
"last_epoch",
"=",
"math",
".",
"floor",
"(",
"epoch",
")",
"class",
"_enable_get_lr_call",
":",
"def",
"__init__",
"(",
"self",
",",
"o",
")",
":",
"self",
".",
"o",
"=",
"o",
"def",
"__enter__",
"(",
"self",
")",
":",
"self",
".",
"o",
".",
"_get_lr_called_within_step",
"=",
"True",
"return",
"self",
"def",
"__exit__",
"(",
"self",
",",
"type",
",",
"value",
",",
"traceback",
")",
":",
"self",
".",
"o",
".",
"_get_lr_called_within_step",
"=",
"False",
"return",
"self",
"with",
"_enable_get_lr_call",
"(",
"self",
")",
":",
"for",
"i",
",",
"data",
"in",
"enumerate",
"(",
"zip",
"(",
"self",
".",
"optimizer",
".",
"param_groups",
",",
"self",
".",
"get_lr",
"(",
")",
")",
")",
":",
"param_group",
",",
"lr",
"=",
"data",
"param_group",
"[",
"'lr'",
"]",
"=",
"lr",
"self",
".",
"print_lr",
"(",
"self",
".",
"verbose",
",",
"i",
",",
"lr",
",",
"epoch",
")",
"self",
".",
"_last_lr",
"=",
"[",
"group",
"[",
"'lr'",
"]",
"for",
"group",
"in",
"self",
".",
"optimizer",
".",
"param_groups",
"]"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/optim/lr_scheduler.py#L1269-L1338 | ||
rodeofx/OpenWalter | 6116fbe3f04f1146c854afbfbdbe944feaee647e | walter/common/walterWidgets/walterBaseTreeView.py | python | BaseItem.insertChild | (self, child, rowNumber) | Insert a child item. | Insert a child item. | [
"Insert",
"a",
"child",
"item",
"."
] | def insertChild(self, child, rowNumber):
"""Insert a child item."""
child.parentItem = self
self.childItems.insert(rowNumber, child) | [
"def",
"insertChild",
"(",
"self",
",",
"child",
",",
"rowNumber",
")",
":",
"child",
".",
"parentItem",
"=",
"self",
"self",
".",
"childItems",
".",
"insert",
"(",
"rowNumber",
",",
"child",
")"
] | https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/common/walterWidgets/walterBaseTreeView.py#L505-L508 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/html.py | python | HtmlPrintout.SetHeader | (*args, **kwargs) | return _html.HtmlPrintout_SetHeader(*args, **kwargs) | SetHeader(self, String header, int pg=PAGE_ALL) | SetHeader(self, String header, int pg=PAGE_ALL) | [
"SetHeader",
"(",
"self",
"String",
"header",
"int",
"pg",
"=",
"PAGE_ALL",
")"
] | def SetHeader(*args, **kwargs):
"""SetHeader(self, String header, int pg=PAGE_ALL)"""
return _html.HtmlPrintout_SetHeader(*args, **kwargs) | [
"def",
"SetHeader",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlPrintout_SetHeader",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L1284-L1286 | |
timi-liuliang/echo | 40a5a24d430eee4118314459ab7e03afcb3b8719 | thirdparty/protobuf/python/mox.py | python | MockMethod.MultipleTimes | (self, group_name="default") | return self._CheckAndCreateNewGroup(group_name, MultipleTimesGroup) | Move this method into group of calls which may be called multiple times.
A group of repeating calls must be defined together, and must be executed in
full before the next expected mehtod can be called.
Args:
group_name: the name of the unordered group.
Returns:
self | Move this method into group of calls which may be called multiple times. | [
"Move",
"this",
"method",
"into",
"group",
"of",
"calls",
"which",
"may",
"be",
"called",
"multiple",
"times",
"."
] | def MultipleTimes(self, group_name="default"):
"""Move this method into group of calls which may be called multiple times.
A group of repeating calls must be defined together, and must be executed in
full before the next expected mehtod can be called.
Args:
group_name: the name of the unordered group.
Returns:
self
"""
return self._CheckAndCreateNewGroup(group_name, MultipleTimesGroup) | [
"def",
"MultipleTimes",
"(",
"self",
",",
"group_name",
"=",
"\"default\"",
")",
":",
"return",
"self",
".",
"_CheckAndCreateNewGroup",
"(",
"group_name",
",",
"MultipleTimesGroup",
")"
] | https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/mox.py#L704-L716 | |
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/__init__.py | python | GDataEntry.IsMedia | (self) | Determines whether or not an entry is a GData Media entry. | Determines whether or not an entry is a GData Media entry. | [
"Determines",
"whether",
"or",
"not",
"an",
"entry",
"is",
"a",
"GData",
"Media",
"entry",
"."
] | def IsMedia(self):
"""Determines whether or not an entry is a GData Media entry.
"""
if (self.GetEditMediaLink()):
return True
else:
return False | [
"def",
"IsMedia",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"GetEditMediaLink",
"(",
")",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/__init__.py#L351-L357 | ||
Slicer/Slicer | ba9fadf332cb0303515b68d8d06a344c82e3e3e5 | Modules/Scripted/SegmentStatistics/SegmentStatistics.py | python | SegmentStatisticsLogic.exportToTable | (self, table, nonEmptyKeysOnly = True) | Export statistics to table node | Export statistics to table node | [
"Export",
"statistics",
"to",
"table",
"node"
] | def exportToTable(self, table, nonEmptyKeysOnly = True):
"""
Export statistics to table node
"""
tableWasModified = table.StartModify()
table.RemoveAllColumns()
keys = self.getNonEmptyKeys() if nonEmptyKeysOnly else self.keys
columnHeaderNames, uniqueColumnHeaderNames = self.getHeaderNames(nonEmptyKeysOnly)
# Define table columns
statistics = self.getStatistics()
for key in keys:
# create table column appropriate for data type; currently supported: float, int, long, string
measurements = [statistics[segmentID, key] for segmentID in statistics["SegmentIDs"] if
(segmentID, key) in statistics]
if len(measurements)==0: # there were not measurements and therefore use the default "string" representation
col = table.AddColumn()
elif isinstance(measurements[0], int):
col = table.AddColumn(vtk.vtkLongArray())
elif isinstance(measurements[0], float):
col = table.AddColumn(vtk.vtkDoubleArray())
elif isinstance(measurements[0], list):
length = len(measurements[0])
if length == 0:
col = table.AddColumn()
else:
value = measurements[0][0]
if isinstance(value, int):
array = vtk.vtkLongArray()
array.SetNumberOfComponents(length)
col = table.AddColumn(array)
elif isinstance(value, float):
array = vtk.vtkDoubleArray()
array.SetNumberOfComponents(length)
col = table.AddColumn(array)
else:
col = table.AddColumn()
else: # default
col = table.AddColumn()
plugin = self.getPluginByKey(key)
columnName = uniqueColumnHeaderNames[key]
longColumnName = columnHeaderNames[key]
col.SetName( columnName )
if plugin:
table.SetColumnProperty(columnName, "Plugin", plugin.name)
longColumnName += '<br>Computed by '+plugin.name+' Statistics plugin'
table.SetColumnLongName(columnName, longColumnName)
measurementInfo = statistics["MeasurementInfo"][key] if key in statistics["MeasurementInfo"] else {}
if measurementInfo:
for mik, miv in measurementInfo.items():
if mik=='description':
table.SetColumnDescription(columnName, str(miv))
elif mik=='units':
table.SetColumnUnitLabel(columnName, str(miv))
elif mik == 'componentNames':
componentNames = miv
array = table.GetTable().GetColumnByName(columnName)
componentIndex = 0
for componentName in miv:
array.SetComponentName(componentIndex, componentName)
componentIndex += 1
else:
table.SetColumnProperty(columnName, str(mik), str(miv))
# Fill columns
for segmentID in statistics["SegmentIDs"]:
rowIndex = table.AddEmptyRow()
columnIndex = 0
for key in keys:
value = statistics[segmentID, key] if (segmentID, key) in statistics else None
if value is None and key!='Segment':
value = float('nan')
if isinstance(value, list):
for i in range(len(value)):
table.GetTable().GetColumn(columnIndex).SetComponent(rowIndex, i, value[i])
else:
table.GetTable().GetColumn(columnIndex).SetValue(rowIndex, value)
columnIndex += 1
table.Modified()
table.EndModify(tableWasModified) | [
"def",
"exportToTable",
"(",
"self",
",",
"table",
",",
"nonEmptyKeysOnly",
"=",
"True",
")",
":",
"tableWasModified",
"=",
"table",
".",
"StartModify",
"(",
")",
"table",
".",
"RemoveAllColumns",
"(",
")",
"keys",
"=",
"self",
".",
"getNonEmptyKeys",
"(",
")",
"if",
"nonEmptyKeysOnly",
"else",
"self",
".",
"keys",
"columnHeaderNames",
",",
"uniqueColumnHeaderNames",
"=",
"self",
".",
"getHeaderNames",
"(",
"nonEmptyKeysOnly",
")",
"# Define table columns",
"statistics",
"=",
"self",
".",
"getStatistics",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"# create table column appropriate for data type; currently supported: float, int, long, string",
"measurements",
"=",
"[",
"statistics",
"[",
"segmentID",
",",
"key",
"]",
"for",
"segmentID",
"in",
"statistics",
"[",
"\"SegmentIDs\"",
"]",
"if",
"(",
"segmentID",
",",
"key",
")",
"in",
"statistics",
"]",
"if",
"len",
"(",
"measurements",
")",
"==",
"0",
":",
"# there were not measurements and therefore use the default \"string\" representation",
"col",
"=",
"table",
".",
"AddColumn",
"(",
")",
"elif",
"isinstance",
"(",
"measurements",
"[",
"0",
"]",
",",
"int",
")",
":",
"col",
"=",
"table",
".",
"AddColumn",
"(",
"vtk",
".",
"vtkLongArray",
"(",
")",
")",
"elif",
"isinstance",
"(",
"measurements",
"[",
"0",
"]",
",",
"float",
")",
":",
"col",
"=",
"table",
".",
"AddColumn",
"(",
"vtk",
".",
"vtkDoubleArray",
"(",
")",
")",
"elif",
"isinstance",
"(",
"measurements",
"[",
"0",
"]",
",",
"list",
")",
":",
"length",
"=",
"len",
"(",
"measurements",
"[",
"0",
"]",
")",
"if",
"length",
"==",
"0",
":",
"col",
"=",
"table",
".",
"AddColumn",
"(",
")",
"else",
":",
"value",
"=",
"measurements",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"array",
"=",
"vtk",
".",
"vtkLongArray",
"(",
")",
"array",
".",
"SetNumberOfComponents",
"(",
"length",
")",
"col",
"=",
"table",
".",
"AddColumn",
"(",
"array",
")",
"elif",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"array",
"=",
"vtk",
".",
"vtkDoubleArray",
"(",
")",
"array",
".",
"SetNumberOfComponents",
"(",
"length",
")",
"col",
"=",
"table",
".",
"AddColumn",
"(",
"array",
")",
"else",
":",
"col",
"=",
"table",
".",
"AddColumn",
"(",
")",
"else",
":",
"# default",
"col",
"=",
"table",
".",
"AddColumn",
"(",
")",
"plugin",
"=",
"self",
".",
"getPluginByKey",
"(",
"key",
")",
"columnName",
"=",
"uniqueColumnHeaderNames",
"[",
"key",
"]",
"longColumnName",
"=",
"columnHeaderNames",
"[",
"key",
"]",
"col",
".",
"SetName",
"(",
"columnName",
")",
"if",
"plugin",
":",
"table",
".",
"SetColumnProperty",
"(",
"columnName",
",",
"\"Plugin\"",
",",
"plugin",
".",
"name",
")",
"longColumnName",
"+=",
"'<br>Computed by '",
"+",
"plugin",
".",
"name",
"+",
"' Statistics plugin'",
"table",
".",
"SetColumnLongName",
"(",
"columnName",
",",
"longColumnName",
")",
"measurementInfo",
"=",
"statistics",
"[",
"\"MeasurementInfo\"",
"]",
"[",
"key",
"]",
"if",
"key",
"in",
"statistics",
"[",
"\"MeasurementInfo\"",
"]",
"else",
"{",
"}",
"if",
"measurementInfo",
":",
"for",
"mik",
",",
"miv",
"in",
"measurementInfo",
".",
"items",
"(",
")",
":",
"if",
"mik",
"==",
"'description'",
":",
"table",
".",
"SetColumnDescription",
"(",
"columnName",
",",
"str",
"(",
"miv",
")",
")",
"elif",
"mik",
"==",
"'units'",
":",
"table",
".",
"SetColumnUnitLabel",
"(",
"columnName",
",",
"str",
"(",
"miv",
")",
")",
"elif",
"mik",
"==",
"'componentNames'",
":",
"componentNames",
"=",
"miv",
"array",
"=",
"table",
".",
"GetTable",
"(",
")",
".",
"GetColumnByName",
"(",
"columnName",
")",
"componentIndex",
"=",
"0",
"for",
"componentName",
"in",
"miv",
":",
"array",
".",
"SetComponentName",
"(",
"componentIndex",
",",
"componentName",
")",
"componentIndex",
"+=",
"1",
"else",
":",
"table",
".",
"SetColumnProperty",
"(",
"columnName",
",",
"str",
"(",
"mik",
")",
",",
"str",
"(",
"miv",
")",
")",
"# Fill columns",
"for",
"segmentID",
"in",
"statistics",
"[",
"\"SegmentIDs\"",
"]",
":",
"rowIndex",
"=",
"table",
".",
"AddEmptyRow",
"(",
")",
"columnIndex",
"=",
"0",
"for",
"key",
"in",
"keys",
":",
"value",
"=",
"statistics",
"[",
"segmentID",
",",
"key",
"]",
"if",
"(",
"segmentID",
",",
"key",
")",
"in",
"statistics",
"else",
"None",
"if",
"value",
"is",
"None",
"and",
"key",
"!=",
"'Segment'",
":",
"value",
"=",
"float",
"(",
"'nan'",
")",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"value",
")",
")",
":",
"table",
".",
"GetTable",
"(",
")",
".",
"GetColumn",
"(",
"columnIndex",
")",
".",
"SetComponent",
"(",
"rowIndex",
",",
"i",
",",
"value",
"[",
"i",
"]",
")",
"else",
":",
"table",
".",
"GetTable",
"(",
")",
".",
"GetColumn",
"(",
"columnIndex",
")",
".",
"SetValue",
"(",
"rowIndex",
",",
"value",
")",
"columnIndex",
"+=",
"1",
"table",
".",
"Modified",
"(",
")",
"table",
".",
"EndModify",
"(",
"tableWasModified",
")"
] | https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/SegmentStatistics/SegmentStatistics.py#L565-L646 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/signal/ltisys.py | python | LinearTimeInvariant.poles | (self) | return self.to_zpk().poles | Poles of the system. | Poles of the system. | [
"Poles",
"of",
"the",
"system",
"."
] | def poles(self):
"""Poles of the system."""
return self.to_zpk().poles | [
"def",
"poles",
"(",
"self",
")",
":",
"return",
"self",
".",
"to_zpk",
"(",
")",
".",
"poles"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/ltisys.py#L90-L92 | |
shader-slang/slang | b8982fcf43b86c1e39dcc3dd19bff2821633eda6 | external/vulkan/registry/conventions.py | python | ConventionsBase.generate_enum_table | (self) | return False | Return True if asciidoctor tables describing enumerants in a
group should be generated as part of group generation. | Return True if asciidoctor tables describing enumerants in a
group should be generated as part of group generation. | [
"Return",
"True",
"if",
"asciidoctor",
"tables",
"describing",
"enumerants",
"in",
"a",
"group",
"should",
"be",
"generated",
"as",
"part",
"of",
"group",
"generation",
"."
] | def generate_enum_table(self):
"""Return True if asciidoctor tables describing enumerants in a
group should be generated as part of group generation."""
return False | [
"def",
"generate_enum_table",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/shader-slang/slang/blob/b8982fcf43b86c1e39dcc3dd19bff2821633eda6/external/vulkan/registry/conventions.py#L321-L324 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/arrayprint.py | python | array_str | (a, max_line_width=None, precision=None, suppress_small=None) | return _array_str_implementation(
a, max_line_width, precision, suppress_small) | Return a string representation of the data in an array.
The data in the array is returned as a single string. This function is
similar to `array_repr`, the difference being that `array_repr` also
returns information on the kind of array and its data type.
Parameters
----------
a : ndarray
Input array.
max_line_width : int, optional
Inserts newlines if text is longer than `max_line_width`.
Defaults to ``numpy.get_printoptions()['linewidth']``.
precision : int, optional
Floating point precision.
Defaults to ``numpy.get_printoptions()['precision']``.
suppress_small : bool, optional
Represent numbers "very close" to zero as zero; default is False.
Very close is defined by precision: if the precision is 8, e.g.,
numbers smaller (in absolute value) than 5e-9 are represented as
zero.
Defaults to ``numpy.get_printoptions()['suppress']``.
See Also
--------
array2string, array_repr, set_printoptions
Examples
--------
>>> np.array_str(np.arange(3))
'[0 1 2]' | Return a string representation of the data in an array. | [
"Return",
"a",
"string",
"representation",
"of",
"the",
"data",
"in",
"an",
"array",
"."
] | def array_str(a, max_line_width=None, precision=None, suppress_small=None):
"""
Return a string representation of the data in an array.
The data in the array is returned as a single string. This function is
similar to `array_repr`, the difference being that `array_repr` also
returns information on the kind of array and its data type.
Parameters
----------
a : ndarray
Input array.
max_line_width : int, optional
Inserts newlines if text is longer than `max_line_width`.
Defaults to ``numpy.get_printoptions()['linewidth']``.
precision : int, optional
Floating point precision.
Defaults to ``numpy.get_printoptions()['precision']``.
suppress_small : bool, optional
Represent numbers "very close" to zero as zero; default is False.
Very close is defined by precision: if the precision is 8, e.g.,
numbers smaller (in absolute value) than 5e-9 are represented as
zero.
Defaults to ``numpy.get_printoptions()['suppress']``.
See Also
--------
array2string, array_repr, set_printoptions
Examples
--------
>>> np.array_str(np.arange(3))
'[0 1 2]'
"""
return _array_str_implementation(
a, max_line_width, precision, suppress_small) | [
"def",
"array_str",
"(",
"a",
",",
"max_line_width",
"=",
"None",
",",
"precision",
"=",
"None",
",",
"suppress_small",
"=",
"None",
")",
":",
"return",
"_array_str_implementation",
"(",
"a",
",",
"max_line_width",
",",
"precision",
",",
"suppress_small",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/core/arrayprint.py#L1515-L1551 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/autograph/pyct/cfg.py | python | GraphBuilder.enter_except_section | (self, section_id) | Enters an except section. | Enters an except section. | [
"Enters",
"an",
"except",
"section",
"."
] | def enter_except_section(self, section_id):
"""Enters an except section."""
if section_id in self.raises:
self.leaves.update(self.raises[section_id]) | [
"def",
"enter_except_section",
"(",
"self",
",",
"section_id",
")",
":",
"if",
"section_id",
"in",
"self",
".",
"raises",
":",
"self",
".",
"leaves",
".",
"update",
"(",
"self",
".",
"raises",
"[",
"section_id",
"]",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/pyct/cfg.py#L570-L573 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/search.py | python | do_incremental_search | (direction: SearchDirection, count: int = 1) | Apply search, but keep search buffer focused. | Apply search, but keep search buffer focused. | [
"Apply",
"search",
"but",
"keep",
"search",
"buffer",
"focused",
"."
] | def do_incremental_search(direction: SearchDirection, count: int = 1) -> None:
"""
Apply search, but keep search buffer focused.
"""
assert is_searching()
layout = get_app().layout
# Only search if the current control is a `BufferControl`.
from prompt_toolkit.layout.controls import BufferControl
search_control = layout.current_control
if not isinstance(search_control, BufferControl):
return
prev_control = layout.search_target_buffer_control
if prev_control is None:
return
search_state = prev_control.search_state
# Update search_state.
direction_changed = search_state.direction != direction
search_state.text = search_control.buffer.text
search_state.direction = direction
# Apply search to current buffer.
if not direction_changed:
prev_control.buffer.apply_search(
search_state, include_current_position=False, count=count
) | [
"def",
"do_incremental_search",
"(",
"direction",
":",
"SearchDirection",
",",
"count",
":",
"int",
"=",
"1",
")",
"->",
"None",
":",
"assert",
"is_searching",
"(",
")",
"layout",
"=",
"get_app",
"(",
")",
".",
"layout",
"# Only search if the current control is a `BufferControl`.",
"from",
"prompt_toolkit",
".",
"layout",
".",
"controls",
"import",
"BufferControl",
"search_control",
"=",
"layout",
".",
"current_control",
"if",
"not",
"isinstance",
"(",
"search_control",
",",
"BufferControl",
")",
":",
"return",
"prev_control",
"=",
"layout",
".",
"search_target_buffer_control",
"if",
"prev_control",
"is",
"None",
":",
"return",
"search_state",
"=",
"prev_control",
".",
"search_state",
"# Update search_state.",
"direction_changed",
"=",
"search_state",
".",
"direction",
"!=",
"direction",
"search_state",
".",
"text",
"=",
"search_control",
".",
"buffer",
".",
"text",
"search_state",
".",
"direction",
"=",
"direction",
"# Apply search to current buffer.",
"if",
"not",
"direction_changed",
":",
"prev_control",
".",
"buffer",
".",
"apply_search",
"(",
"search_state",
",",
"include_current_position",
"=",
"False",
",",
"count",
"=",
"count",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/search.py#L153-L183 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/groupby/groupby.py | python | GroupBy.cummin | (self, axis=0, **kwargs) | return self._cython_transform("cummin", numeric_only=False) | Cumulative min for each group.
Returns
-------
Series or DataFrame | Cumulative min for each group. | [
"Cumulative",
"min",
"for",
"each",
"group",
"."
] | def cummin(self, axis=0, **kwargs):
"""
Cumulative min for each group.
Returns
-------
Series or DataFrame
"""
if axis != 0:
return self.apply(lambda x: np.minimum.accumulate(x, axis))
return self._cython_transform("cummin", numeric_only=False) | [
"def",
"cummin",
"(",
"self",
",",
"axis",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"axis",
"!=",
"0",
":",
"return",
"self",
".",
"apply",
"(",
"lambda",
"x",
":",
"np",
".",
"minimum",
".",
"accumulate",
"(",
"x",
",",
"axis",
")",
")",
"return",
"self",
".",
"_cython_transform",
"(",
"\"cummin\"",
",",
"numeric_only",
"=",
"False",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/groupby/groupby.py#L2165-L2176 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | EnumBaseArgument.GetValidGLArg | (self, func, offset, index) | return self.GetValidArg(func, offset, index) | Gets a valid value for this argument. | Gets a valid value for this argument. | [
"Gets",
"a",
"valid",
"value",
"for",
"this",
"argument",
"."
] | def GetValidGLArg(self, func, offset, index):
"""Gets a valid value for this argument."""
return self.GetValidArg(func, offset, index) | [
"def",
"GetValidGLArg",
"(",
"self",
",",
"func",
",",
"offset",
",",
"index",
")",
":",
"return",
"self",
".",
"GetValidArg",
"(",
"func",
",",
"offset",
",",
"index",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L6007-L6009 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/training/optimizer.py | python | Optimizer.__init__ | (self, use_locking, name) | Create a new Optimizer.
This must be called by the constructors of subclasses.
Args:
use_locking: Bool. If True apply use locks to prevent concurrent updates
to variables.
name: A non-empty string. The name to use for accumulators created
for the optimizer.
Raises:
ValueError: If name is malformed. | Create a new Optimizer. | [
"Create",
"a",
"new",
"Optimizer",
"."
] | def __init__(self, use_locking, name):
"""Create a new Optimizer.
This must be called by the constructors of subclasses.
Args:
use_locking: Bool. If True apply use locks to prevent concurrent updates
to variables.
name: A non-empty string. The name to use for accumulators created
for the optimizer.
Raises:
ValueError: If name is malformed.
"""
if not name:
raise ValueError("Must specify the optimizer name")
self._use_locking = use_locking
self._name = name
# Dictionary of slots.
# {slot_name : { variable_to_train: slot_for_the_variable, ...}, ... }
self._slots = {} | [
"def",
"__init__",
"(",
"self",
",",
"use_locking",
",",
"name",
")",
":",
"if",
"not",
"name",
":",
"raise",
"ValueError",
"(",
"\"Must specify the optimizer name\"",
")",
"self",
".",
"_use_locking",
"=",
"use_locking",
"self",
".",
"_name",
"=",
"name",
"# Dictionary of slots.",
"# {slot_name : { variable_to_train: slot_for_the_variable, ...}, ... }",
"self",
".",
"_slots",
"=",
"{",
"}"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/training/optimizer.py#L133-L153 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/operations/other_ops.py | python | PullWeight.__init__ | (self) | Initialize PullWeight | Initialize PullWeight | [
"Initialize",
"PullWeight"
] | def __init__(self):
"""Initialize PullWeight"""
self.add_prim_attr("primitive_target", "CPU")
self.init_prim_io_names(inputs=['weight', "name", "index"], outputs=['output']) | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"add_prim_attr",
"(",
"\"primitive_target\"",
",",
"\"CPU\"",
")",
"self",
".",
"init_prim_io_names",
"(",
"inputs",
"=",
"[",
"'weight'",
",",
"\"name\"",
",",
"\"index\"",
"]",
",",
"outputs",
"=",
"[",
"'output'",
"]",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/other_ops.py#L731-L734 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/timeit.py | python | Timer.__init__ | (self, stmt="pass", setup="pass", timer=default_timer) | Constructor. See class doc string. | Constructor. See class doc string. | [
"Constructor",
".",
"See",
"class",
"doc",
"string",
"."
] | def __init__(self, stmt="pass", setup="pass", timer=default_timer):
"""Constructor. See class doc string."""
self.timer = timer
ns = {}
if isinstance(stmt, basestring):
stmt = reindent(stmt, 8)
if isinstance(setup, basestring):
setup = reindent(setup, 4)
src = template % {'stmt': stmt, 'setup': setup}
elif hasattr(setup, '__call__'):
src = template % {'stmt': stmt, 'setup': '_setup()'}
ns['_setup'] = setup
else:
raise ValueError("setup is neither a string nor callable")
self.src = src # Save for traceback display
code = compile(src, dummy_src_name, "exec")
exec code in globals(), ns
self.inner = ns["inner"]
elif hasattr(stmt, '__call__'):
self.src = None
if isinstance(setup, basestring):
_setup = setup
def setup():
exec _setup in globals(), ns
elif not hasattr(setup, '__call__'):
raise ValueError("setup is neither a string nor callable")
self.inner = _template_func(setup, stmt)
else:
raise ValueError("stmt is neither a string nor callable") | [
"def",
"__init__",
"(",
"self",
",",
"stmt",
"=",
"\"pass\"",
",",
"setup",
"=",
"\"pass\"",
",",
"timer",
"=",
"default_timer",
")",
":",
"self",
".",
"timer",
"=",
"timer",
"ns",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"stmt",
",",
"basestring",
")",
":",
"stmt",
"=",
"reindent",
"(",
"stmt",
",",
"8",
")",
"if",
"isinstance",
"(",
"setup",
",",
"basestring",
")",
":",
"setup",
"=",
"reindent",
"(",
"setup",
",",
"4",
")",
"src",
"=",
"template",
"%",
"{",
"'stmt'",
":",
"stmt",
",",
"'setup'",
":",
"setup",
"}",
"elif",
"hasattr",
"(",
"setup",
",",
"'__call__'",
")",
":",
"src",
"=",
"template",
"%",
"{",
"'stmt'",
":",
"stmt",
",",
"'setup'",
":",
"'_setup()'",
"}",
"ns",
"[",
"'_setup'",
"]",
"=",
"setup",
"else",
":",
"raise",
"ValueError",
"(",
"\"setup is neither a string nor callable\"",
")",
"self",
".",
"src",
"=",
"src",
"# Save for traceback display",
"code",
"=",
"compile",
"(",
"src",
",",
"dummy_src_name",
",",
"\"exec\"",
")",
"exec",
"code",
"in",
"globals",
"(",
")",
",",
"ns",
"self",
".",
"inner",
"=",
"ns",
"[",
"\"inner\"",
"]",
"elif",
"hasattr",
"(",
"stmt",
",",
"'__call__'",
")",
":",
"self",
".",
"src",
"=",
"None",
"if",
"isinstance",
"(",
"setup",
",",
"basestring",
")",
":",
"_setup",
"=",
"setup",
"def",
"setup",
"(",
")",
":",
"exec",
"_setup",
"in",
"globals",
"(",
")",
",",
"ns",
"elif",
"not",
"hasattr",
"(",
"setup",
",",
"'__call__'",
")",
":",
"raise",
"ValueError",
"(",
"\"setup is neither a string nor callable\"",
")",
"self",
".",
"inner",
"=",
"_template_func",
"(",
"setup",
",",
"stmt",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"stmt is neither a string nor callable\"",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/timeit.py#L121-L149 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathGeom.py | python | cmdsForEdge | (edge, flip=False, useHelixForBSpline=True, segm=50, hSpeed=0, vSpeed=0) | return commands | cmdsForEdge(edge, flip=False, useHelixForBSpline=True, segm=50) -> List(Path.Command)
Returns a list of Path.Command representing the given edge.
If flip is True the edge is considered to be backwards.
If useHelixForBSpline is True an Edge based on a BSplineCurve is considered
to represent a helix and results in G2 or G3 command. Otherwise edge has
no direct Path.Command mapping and will be approximated by straight segments.
segm is a factor for the segmentation of arbitrary curves not mapped to G1/2/3
commands. The higher the value the more segments will be used. | cmdsForEdge(edge, flip=False, useHelixForBSpline=True, segm=50) -> List(Path.Command)
Returns a list of Path.Command representing the given edge.
If flip is True the edge is considered to be backwards.
If useHelixForBSpline is True an Edge based on a BSplineCurve is considered
to represent a helix and results in G2 or G3 command. Otherwise edge has
no direct Path.Command mapping and will be approximated by straight segments.
segm is a factor for the segmentation of arbitrary curves not mapped to G1/2/3
commands. The higher the value the more segments will be used. | [
"cmdsForEdge",
"(",
"edge",
"flip",
"=",
"False",
"useHelixForBSpline",
"=",
"True",
"segm",
"=",
"50",
")",
"-",
">",
"List",
"(",
"Path",
".",
"Command",
")",
"Returns",
"a",
"list",
"of",
"Path",
".",
"Command",
"representing",
"the",
"given",
"edge",
".",
"If",
"flip",
"is",
"True",
"the",
"edge",
"is",
"considered",
"to",
"be",
"backwards",
".",
"If",
"useHelixForBSpline",
"is",
"True",
"an",
"Edge",
"based",
"on",
"a",
"BSplineCurve",
"is",
"considered",
"to",
"represent",
"a",
"helix",
"and",
"results",
"in",
"G2",
"or",
"G3",
"command",
".",
"Otherwise",
"edge",
"has",
"no",
"direct",
"Path",
".",
"Command",
"mapping",
"and",
"will",
"be",
"approximated",
"by",
"straight",
"segments",
".",
"segm",
"is",
"a",
"factor",
"for",
"the",
"segmentation",
"of",
"arbitrary",
"curves",
"not",
"mapped",
"to",
"G1",
"/",
"2",
"/",
"3",
"commands",
".",
"The",
"higher",
"the",
"value",
"the",
"more",
"segments",
"will",
"be",
"used",
"."
] | def cmdsForEdge(edge, flip=False, useHelixForBSpline=True, segm=50, hSpeed=0, vSpeed=0):
"""cmdsForEdge(edge, flip=False, useHelixForBSpline=True, segm=50) -> List(Path.Command)
Returns a list of Path.Command representing the given edge.
If flip is True the edge is considered to be backwards.
If useHelixForBSpline is True an Edge based on a BSplineCurve is considered
to represent a helix and results in G2 or G3 command. Otherwise edge has
no direct Path.Command mapping and will be approximated by straight segments.
segm is a factor for the segmentation of arbitrary curves not mapped to G1/2/3
commands. The higher the value the more segments will be used."""
pt = (
edge.valueAt(edge.LastParameter)
if not flip
else edge.valueAt(edge.FirstParameter)
)
params = {"X": pt.x, "Y": pt.y, "Z": pt.z}
if type(edge.Curve) == Part.Line or type(edge.Curve) == Part.LineSegment:
if hSpeed > 0 and vSpeed > 0:
pt2 = (
edge.valueAt(edge.FirstParameter)
if not flip
else edge.valueAt(edge.LastParameter)
)
params.update({"F": speedBetweenPoints(pt, pt2, hSpeed, vSpeed)})
commands = [Path.Command("G1", params)]
else:
p1 = (
edge.valueAt(edge.FirstParameter)
if not flip
else edge.valueAt(edge.LastParameter)
)
p2 = edge.valueAt((edge.FirstParameter + edge.LastParameter) / 2)
p3 = pt
if hasattr(edge.Curve, "Axis") and (
(
type(edge.Curve) == Part.Circle
and isRoughly(edge.Curve.Axis.x, 0)
and isRoughly(edge.Curve.Axis.y, 0)
)
or (useHelixForBSpline and type(edge.Curve) == Part.BSplineCurve)
):
# This is an arc or a helix and it should be represented by a simple G2/G3 command
if edge.Curve.Axis.z < 0:
cmd = "G2" if not flip else "G3"
else:
cmd = "G3" if not flip else "G2"
if pointsCoincide(p1, p3):
# A full circle
offset = edge.Curve.Center - pt
else:
pd = Part.Circle(xy(p1), xy(p2), xy(p3)).Center
PathLog.debug(
"**** %s.%d: (%.2f, %.2f, %.2f) - (%.2f, %.2f, %.2f) - (%.2f, %.2f, %.2f) -> center=(%.2f, %.2f)"
% (
cmd,
flip,
p1.x,
p1.y,
p1.z,
p2.x,
p2.y,
p2.z,
p3.x,
p3.y,
p3.z,
pd.x,
pd.y,
)
)
# Have to calculate the center in the XY plane, using pd leads to an error if this is a helix
pa = xy(p1)
pb = xy(p2)
pc = xy(p3)
offset = Part.Circle(pa, pb, pc).Center - pa
PathLog.debug(
"**** (%.2f, %.2f, %.2f) - (%.2f, %.2f, %.2f)"
% (pa.x, pa.y, pa.z, pc.x, pc.y, pc.z)
)
PathLog.debug(
"**** (%.2f, %.2f, %.2f) - (%.2f, %.2f, %.2f)"
% (pb.x, pb.y, pb.z, pd.x, pd.y, pd.z)
)
PathLog.debug("**** (%.2f, %.2f, %.2f)" % (offset.x, offset.y, offset.z))
params.update({"I": offset.x, "J": offset.y, "K": (p3.z - p1.z) / 2})
# G2/G3 commands are always performed at hSpeed
if hSpeed > 0:
params.update({"F": hSpeed})
commands = [Path.Command(cmd, params)]
else:
# We're dealing with a helix or a more complex shape and it has to get approximated
# by a number of straight segments
points = edge.discretize(Deflection=0.01)
if flip:
points = points[::-1]
commands = []
if points:
p0 = points[0]
for p in points[1:]:
params = {"X": p.x, "Y": p.y, "Z": p.z}
if hSpeed > 0 and vSpeed > 0:
params["F"] = speedBetweenPoints(p0, p, hSpeed, vSpeed)
cmd = Path.Command("G1", params)
# print("***** {}".format(cmd))
commands.append(cmd)
p0 = p
# print commands
return commands | [
"def",
"cmdsForEdge",
"(",
"edge",
",",
"flip",
"=",
"False",
",",
"useHelixForBSpline",
"=",
"True",
",",
"segm",
"=",
"50",
",",
"hSpeed",
"=",
"0",
",",
"vSpeed",
"=",
"0",
")",
":",
"pt",
"=",
"(",
"edge",
".",
"valueAt",
"(",
"edge",
".",
"LastParameter",
")",
"if",
"not",
"flip",
"else",
"edge",
".",
"valueAt",
"(",
"edge",
".",
"FirstParameter",
")",
")",
"params",
"=",
"{",
"\"X\"",
":",
"pt",
".",
"x",
",",
"\"Y\"",
":",
"pt",
".",
"y",
",",
"\"Z\"",
":",
"pt",
".",
"z",
"}",
"if",
"type",
"(",
"edge",
".",
"Curve",
")",
"==",
"Part",
".",
"Line",
"or",
"type",
"(",
"edge",
".",
"Curve",
")",
"==",
"Part",
".",
"LineSegment",
":",
"if",
"hSpeed",
">",
"0",
"and",
"vSpeed",
">",
"0",
":",
"pt2",
"=",
"(",
"edge",
".",
"valueAt",
"(",
"edge",
".",
"FirstParameter",
")",
"if",
"not",
"flip",
"else",
"edge",
".",
"valueAt",
"(",
"edge",
".",
"LastParameter",
")",
")",
"params",
".",
"update",
"(",
"{",
"\"F\"",
":",
"speedBetweenPoints",
"(",
"pt",
",",
"pt2",
",",
"hSpeed",
",",
"vSpeed",
")",
"}",
")",
"commands",
"=",
"[",
"Path",
".",
"Command",
"(",
"\"G1\"",
",",
"params",
")",
"]",
"else",
":",
"p1",
"=",
"(",
"edge",
".",
"valueAt",
"(",
"edge",
".",
"FirstParameter",
")",
"if",
"not",
"flip",
"else",
"edge",
".",
"valueAt",
"(",
"edge",
".",
"LastParameter",
")",
")",
"p2",
"=",
"edge",
".",
"valueAt",
"(",
"(",
"edge",
".",
"FirstParameter",
"+",
"edge",
".",
"LastParameter",
")",
"/",
"2",
")",
"p3",
"=",
"pt",
"if",
"hasattr",
"(",
"edge",
".",
"Curve",
",",
"\"Axis\"",
")",
"and",
"(",
"(",
"type",
"(",
"edge",
".",
"Curve",
")",
"==",
"Part",
".",
"Circle",
"and",
"isRoughly",
"(",
"edge",
".",
"Curve",
".",
"Axis",
".",
"x",
",",
"0",
")",
"and",
"isRoughly",
"(",
"edge",
".",
"Curve",
".",
"Axis",
".",
"y",
",",
"0",
")",
")",
"or",
"(",
"useHelixForBSpline",
"and",
"type",
"(",
"edge",
".",
"Curve",
")",
"==",
"Part",
".",
"BSplineCurve",
")",
")",
":",
"# This is an arc or a helix and it should be represented by a simple G2/G3 command",
"if",
"edge",
".",
"Curve",
".",
"Axis",
".",
"z",
"<",
"0",
":",
"cmd",
"=",
"\"G2\"",
"if",
"not",
"flip",
"else",
"\"G3\"",
"else",
":",
"cmd",
"=",
"\"G3\"",
"if",
"not",
"flip",
"else",
"\"G2\"",
"if",
"pointsCoincide",
"(",
"p1",
",",
"p3",
")",
":",
"# A full circle",
"offset",
"=",
"edge",
".",
"Curve",
".",
"Center",
"-",
"pt",
"else",
":",
"pd",
"=",
"Part",
".",
"Circle",
"(",
"xy",
"(",
"p1",
")",
",",
"xy",
"(",
"p2",
")",
",",
"xy",
"(",
"p3",
")",
")",
".",
"Center",
"PathLog",
".",
"debug",
"(",
"\"**** %s.%d: (%.2f, %.2f, %.2f) - (%.2f, %.2f, %.2f) - (%.2f, %.2f, %.2f) -> center=(%.2f, %.2f)\"",
"%",
"(",
"cmd",
",",
"flip",
",",
"p1",
".",
"x",
",",
"p1",
".",
"y",
",",
"p1",
".",
"z",
",",
"p2",
".",
"x",
",",
"p2",
".",
"y",
",",
"p2",
".",
"z",
",",
"p3",
".",
"x",
",",
"p3",
".",
"y",
",",
"p3",
".",
"z",
",",
"pd",
".",
"x",
",",
"pd",
".",
"y",
",",
")",
")",
"# Have to calculate the center in the XY plane, using pd leads to an error if this is a helix",
"pa",
"=",
"xy",
"(",
"p1",
")",
"pb",
"=",
"xy",
"(",
"p2",
")",
"pc",
"=",
"xy",
"(",
"p3",
")",
"offset",
"=",
"Part",
".",
"Circle",
"(",
"pa",
",",
"pb",
",",
"pc",
")",
".",
"Center",
"-",
"pa",
"PathLog",
".",
"debug",
"(",
"\"**** (%.2f, %.2f, %.2f) - (%.2f, %.2f, %.2f)\"",
"%",
"(",
"pa",
".",
"x",
",",
"pa",
".",
"y",
",",
"pa",
".",
"z",
",",
"pc",
".",
"x",
",",
"pc",
".",
"y",
",",
"pc",
".",
"z",
")",
")",
"PathLog",
".",
"debug",
"(",
"\"**** (%.2f, %.2f, %.2f) - (%.2f, %.2f, %.2f)\"",
"%",
"(",
"pb",
".",
"x",
",",
"pb",
".",
"y",
",",
"pb",
".",
"z",
",",
"pd",
".",
"x",
",",
"pd",
".",
"y",
",",
"pd",
".",
"z",
")",
")",
"PathLog",
".",
"debug",
"(",
"\"**** (%.2f, %.2f, %.2f)\"",
"%",
"(",
"offset",
".",
"x",
",",
"offset",
".",
"y",
",",
"offset",
".",
"z",
")",
")",
"params",
".",
"update",
"(",
"{",
"\"I\"",
":",
"offset",
".",
"x",
",",
"\"J\"",
":",
"offset",
".",
"y",
",",
"\"K\"",
":",
"(",
"p3",
".",
"z",
"-",
"p1",
".",
"z",
")",
"/",
"2",
"}",
")",
"# G2/G3 commands are always performed at hSpeed",
"if",
"hSpeed",
">",
"0",
":",
"params",
".",
"update",
"(",
"{",
"\"F\"",
":",
"hSpeed",
"}",
")",
"commands",
"=",
"[",
"Path",
".",
"Command",
"(",
"cmd",
",",
"params",
")",
"]",
"else",
":",
"# We're dealing with a helix or a more complex shape and it has to get approximated",
"# by a number of straight segments",
"points",
"=",
"edge",
".",
"discretize",
"(",
"Deflection",
"=",
"0.01",
")",
"if",
"flip",
":",
"points",
"=",
"points",
"[",
":",
":",
"-",
"1",
"]",
"commands",
"=",
"[",
"]",
"if",
"points",
":",
"p0",
"=",
"points",
"[",
"0",
"]",
"for",
"p",
"in",
"points",
"[",
"1",
":",
"]",
":",
"params",
"=",
"{",
"\"X\"",
":",
"p",
".",
"x",
",",
"\"Y\"",
":",
"p",
".",
"y",
",",
"\"Z\"",
":",
"p",
".",
"z",
"}",
"if",
"hSpeed",
">",
"0",
"and",
"vSpeed",
">",
"0",
":",
"params",
"[",
"\"F\"",
"]",
"=",
"speedBetweenPoints",
"(",
"p0",
",",
"p",
",",
"hSpeed",
",",
"vSpeed",
")",
"cmd",
"=",
"Path",
".",
"Command",
"(",
"\"G1\"",
",",
"params",
")",
"# print(\"***** {}\".format(cmd))",
"commands",
".",
"append",
"(",
"cmd",
")",
"p0",
"=",
"p",
"# print commands",
"return",
"commands"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathGeom.py#L273-L385 | |
microsoft/CNTK | e9396480025b9ca457d26b6f33dd07c474c6aa04 | bindings/python/cntk/contrib/deeprl/agent/shared/replay_memory.py | python | ReplayMemory._next_position_then_increment | (self) | return position | Similar to position++. | Similar to position++. | [
"Similar",
"to",
"position",
"++",
"."
] | def _next_position_then_increment(self):
"""Similar to position++."""
start = self._capacity - 1 \
if self._use_prioritized_replay \
else 0
position = start + self._position
self._position = (self._position + 1) % self._capacity
return position | [
"def",
"_next_position_then_increment",
"(",
"self",
")",
":",
"start",
"=",
"self",
".",
"_capacity",
"-",
"1",
"if",
"self",
".",
"_use_prioritized_replay",
"else",
"0",
"position",
"=",
"start",
"+",
"self",
".",
"_position",
"self",
".",
"_position",
"=",
"(",
"self",
".",
"_position",
"+",
"1",
")",
"%",
"self",
".",
"_capacity",
"return",
"position"
] | https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/contrib/deeprl/agent/shared/replay_memory.py#L99-L106 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/python/google/platform_utils_mac.py | python | PlatformUtility.GetTempDirectory | (self) | return os.getenv("TMPDIR", "/tmp") | Returns the file system temp directory
Note that this does not use a random subdirectory, so it's not
intrinsically secure. If you need a secure subdir, use the tempfile
package. | Returns the file system temp directory | [
"Returns",
"the",
"file",
"system",
"temp",
"directory"
] | def GetTempDirectory(self):
"""Returns the file system temp directory
Note that this does not use a random subdirectory, so it's not
intrinsically secure. If you need a secure subdir, use the tempfile
package.
"""
return os.getenv("TMPDIR", "/tmp") | [
"def",
"GetTempDirectory",
"(",
"self",
")",
":",
"return",
"os",
".",
"getenv",
"(",
"\"TMPDIR\"",
",",
"\"/tmp\"",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/python/google/platform_utils_mac.py#L30-L37 | |
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | modules/tools/record_parse_save/parse_camera.py | python | parse_data | (channelname, msg, out_folder) | return tstamp | parser images from Apollo record file | parser images from Apollo record file | [
"parser",
"images",
"from",
"Apollo",
"record",
"file"
] | def parse_data(channelname, msg, out_folder):
"""
parser images from Apollo record file
"""
msg_camera = CompressedImage()
msg_camera.ParseFromString(str(msg))
tstamp = msg_camera.measurement_time
temp_time = str(tstamp).split('.')
if len(temp_time[1]) == 1:
temp_time1_adj = temp_time[1] + '0'
else:
temp_time1_adj = temp_time[1]
image_time = temp_time[0] + '_' + temp_time1_adj
image_filename = "image_" + image_time + ".jpeg"
f = open(out_folder + image_filename, 'w+b')
f.write(msg_camera.data)
f.close()
return tstamp | [
"def",
"parse_data",
"(",
"channelname",
",",
"msg",
",",
"out_folder",
")",
":",
"msg_camera",
"=",
"CompressedImage",
"(",
")",
"msg_camera",
".",
"ParseFromString",
"(",
"str",
"(",
"msg",
")",
")",
"tstamp",
"=",
"msg_camera",
".",
"measurement_time",
"temp_time",
"=",
"str",
"(",
"tstamp",
")",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"temp_time",
"[",
"1",
"]",
")",
"==",
"1",
":",
"temp_time1_adj",
"=",
"temp_time",
"[",
"1",
"]",
"+",
"'0'",
"else",
":",
"temp_time1_adj",
"=",
"temp_time",
"[",
"1",
"]",
"image_time",
"=",
"temp_time",
"[",
"0",
"]",
"+",
"'_'",
"+",
"temp_time1_adj",
"image_filename",
"=",
"\"image_\"",
"+",
"image_time",
"+",
"\".jpeg\"",
"f",
"=",
"open",
"(",
"out_folder",
"+",
"image_filename",
",",
"'w+b'",
")",
"f",
".",
"write",
"(",
"msg_camera",
".",
"data",
")",
"f",
".",
"close",
"(",
")",
"return",
"tstamp"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/record_parse_save/parse_camera.py#L34-L55 | |
gimli-org/gimli | 17aa2160de9b15ababd9ef99e89b1bc3277bbb23 | pygimli/utils/utils.py | python | ProgressBar._setbar | (self, elapsed_it) | Reset pBar based on current iteration number. | Reset pBar based on current iteration number. | [
"Reset",
"pBar",
"based",
"on",
"current",
"iteration",
"number",
"."
] | def _setbar(self, elapsed_it):
"""Reset pBar based on current iteration number."""
self._amount((elapsed_it / float(self.its)) * 100.0)
self.pBar += " %d of %s complete" % (elapsed_it, self.its) | [
"def",
"_setbar",
"(",
"self",
",",
"elapsed_it",
")",
":",
"self",
".",
"_amount",
"(",
"(",
"elapsed_it",
"/",
"float",
"(",
"self",
".",
"its",
")",
")",
"*",
"100.0",
")",
"self",
".",
"pBar",
"+=",
"\" %d of %s complete\"",
"%",
"(",
"elapsed_it",
",",
"self",
".",
"its",
")"
] | https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/utils/utils.py#L62-L65 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/ccompiler.py | python | CCompiler._fix_object_args | (self, objects, output_dir) | return (objects, output_dir) | Typecheck and fix up some arguments supplied to various methods.
Specifically: ensure that 'objects' is a list; if output_dir is
None, replace with self.output_dir. Return fixed versions of
'objects' and 'output_dir'. | Typecheck and fix up some arguments supplied to various methods.
Specifically: ensure that 'objects' is a list; if output_dir is
None, replace with self.output_dir. Return fixed versions of
'objects' and 'output_dir'. | [
"Typecheck",
"and",
"fix",
"up",
"some",
"arguments",
"supplied",
"to",
"various",
"methods",
".",
"Specifically",
":",
"ensure",
"that",
"objects",
"is",
"a",
"list",
";",
"if",
"output_dir",
"is",
"None",
"replace",
"with",
"self",
".",
"output_dir",
".",
"Return",
"fixed",
"versions",
"of",
"objects",
"and",
"output_dir",
"."
] | def _fix_object_args(self, objects, output_dir):
"""Typecheck and fix up some arguments supplied to various methods.
Specifically: ensure that 'objects' is a list; if output_dir is
None, replace with self.output_dir. Return fixed versions of
'objects' and 'output_dir'.
"""
if not isinstance(objects, (list, tuple)):
raise TypeError, \
"'objects' must be a list or tuple of strings"
objects = list (objects)
if output_dir is None:
output_dir = self.output_dir
elif not isinstance(output_dir, str):
raise TypeError, "'output_dir' must be a string or None"
return (objects, output_dir) | [
"def",
"_fix_object_args",
"(",
"self",
",",
"objects",
",",
"output_dir",
")",
":",
"if",
"not",
"isinstance",
"(",
"objects",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
",",
"\"'objects' must be a list or tuple of strings\"",
"objects",
"=",
"list",
"(",
"objects",
")",
"if",
"output_dir",
"is",
"None",
":",
"output_dir",
"=",
"self",
".",
"output_dir",
"elif",
"not",
"isinstance",
"(",
"output_dir",
",",
"str",
")",
":",
"raise",
"TypeError",
",",
"\"'output_dir' must be a string or None\"",
"return",
"(",
"objects",
",",
"output_dir",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/ccompiler.py#L408-L424 | |
MythTV/mythtv | d282a209cb8be85d036f85a62a8ec971b67d45f4 | mythplugins/mytharchive/mythburn/scripts/mythburn.py | python | doProcessFileProjectX | (file, folder, count) | Process a single video/recording file ready for burning. | Process a single video/recording file ready for burning. | [
"Process",
"a",
"single",
"video",
"/",
"recording",
"file",
"ready",
"for",
"burning",
"."
] | def doProcessFileProjectX(file, folder, count):
"""Process a single video/recording file ready for burning."""
write( "*************************************************************")
write( "Processing %s %d: '%s'" % (file.attributes["type"].value, count, file.attributes["filename"].value))
write( "*************************************************************")
#As part of this routine we need to pre-process the video this MAY mean:
#1. encoding to mpeg2 (if its an avi for instance or isn't DVD compatible)
#2. removing commercials/cleaning up mpeg2 stream
#3. selecting audio track(s) to use and encoding audio from mp2 into ac3
#4. de-multiplexing into video and audio steams
mediafile=""
if file.hasAttribute("localfilename"):
mediafile=file.attributes["localfilename"].value
elif file.attributes["type"].value=="recording":
mediafile = file.attributes["filename"].value
elif file.attributes["type"].value=="video":
mediafile=os.path.join(videopath, file.attributes["filename"].value)
elif file.attributes["type"].value=="file":
mediafile=file.attributes["filename"].value
else:
fatalError("Unknown type of video file it must be 'recording', 'video' or 'file'.")
#Get the XML containing information about this item
infoDOM = xml.dom.minidom.parse( os.path.join(folder,"info.xml") )
#Error out if its the wrong XML
if infoDOM.documentElement.tagName != "fileinfo":
fatalError("The info.xml file (%s) doesn't look right" % os.path.join(folder,"info.xml"))
#do we need to re-encode the file to make it DVD compliant?
if not isFileOkayForDVD(file, folder):
if getFileType(folder) == 'nuv':
#file is a nuv file which mythffmpeg has problems reading so use mythtranscode to pass
#the video and audio streams to mythffmpeg to do the reencode
#we need to re-encode the file, make sure we get the right video/audio streams
#would be good if we could also split the file at the same time
getStreamInformation(mediafile, os.path.join(folder, "streaminfo.xml"), 0)
#choose which streams we need
video, audio1, audio2 = selectStreams(folder)
#choose which aspect ratio we should use
aspectratio = selectAspectRatio(folder)
write("Re-encoding audio and video from nuv file")
# what encoding profile should we use
if file.hasAttribute("encodingprofile"):
profile = file.attributes["encodingprofile"].value
else:
profile = defaultEncodingProfile
if file.hasAttribute("localfilename"):
mediafile = file.attributes["localfilename"].value
chanid = -1
starttime = -1
usecutlist = -1
elif file.attributes["type"].value == "recording":
mediafile = -1
chanid = getText(infoDOM.getElementsByTagName("chanid")[0])
starttime = getText(infoDOM.getElementsByTagName("starttime")[0])
usecutlist = (file.attributes["usecutlist"].value == "1" and
getText(infoDOM.getElementsByTagName("hascutlist")[0]) == "yes")
else:
chanid = -1
starttime = -1
usecutlist = -1
encodeNuvToMPEG2(chanid, starttime, mediafile, os.path.join(folder, "newfile2.mpg"), folder,
profile, usecutlist)
mediafile = os.path.join(folder, 'newfile2.mpg')
else:
#we need to re-encode the file, make sure we get the right video/audio streams
#would be good if we could also split the file at the same time
getStreamInformation(mediafile, os.path.join(folder, "streaminfo.xml"), 0)
#choose which streams we need
video, audio1, audio2 = selectStreams(folder)
#choose which aspect ratio we should use
aspectratio = selectAspectRatio(folder)
write("Re-encoding audio and video")
# Run from local file?
if file.hasAttribute("localfilename"):
mediafile = file.attributes["localfilename"].value
# what encoding profile should we use
if file.hasAttribute("encodingprofile"):
profile = file.attributes["encodingprofile"].value
else:
profile = defaultEncodingProfile
#do the re-encode
encodeVideoToMPEG2(mediafile, os.path.join(folder, "newfile2.mpg"), video,
audio1, audio2, aspectratio, profile)
mediafile = os.path.join(folder, 'newfile2.mpg')
#remove an intermediate file
if os.path.exists(os.path.join(folder, "newfile1.mpg")):
os.remove(os.path.join(folder,'newfile1.mpg'))
# the file is now DVD compliant now we need to remove commercials
# and split it into video, audio, subtitle parts
# find out what streams we have available now
getStreamInformation(mediafile, os.path.join(folder, "streaminfo.xml"), 1)
# choose which streams we need
video, audio1, audio2 = selectStreams(folder)
# now attempt to split the source file into video and audio parts
# using projectX
# If this is an mpeg2 myth recording and there is a cut list available and the
# user wants to use it run projectx to cut out commercials etc
if file.attributes["type"].value == "recording":
if file.attributes["usecutlist"].value == "1" and getText(infoDOM.getElementsByTagName("hascutlist")[0]) == "yes":
chanid = getText(infoDOM.getElementsByTagName("chanid")[0])
starttime = getText(infoDOM.getElementsByTagName("starttime")[0])
write("File has a cut list - running Project-X to remove unwanted segments")
if not runProjectX(chanid, starttime, folder, True, mediafile):
fatalError("Failed to run Project-X to remove unwanted segments and demux")
else:
# no cutlist so just demux this file
chanid = getText(infoDOM.getElementsByTagName("chanid")[0])
starttime = getText(infoDOM.getElementsByTagName("starttime")[0])
write("Using Project-X to demux file")
if not runProjectX(chanid, starttime, folder, False, mediafile):
fatalError("Failed to run Project-X to demux file")
else:
# just demux this file
chanid = -1
starttime = -1
write("Running Project-X to demux file")
if not runProjectX(chanid, starttime, folder, False, mediafile):
fatalError("Failed to run Project-X to demux file")
# we now have a video stream and one or more audio streams
# check if we need to convert any of the audio streams to ac3
processAudio(folder)
# if we don't already have one find a title thumbnail image
titleImage = os.path.join(folder, "title.jpg")
if not os.path.exists(titleImage):
# if the file is a recording try to use its preview image for the thumb
if file.attributes["type"].value == "recording":
previewImage = file.attributes["filename"].value + ".png"
if usebookmark == True and os.path.exists(previewImage):
copy(previewImage, titleImage)
else:
extractVideoFrame(os.path.join(folder, "stream.mv2"), titleImage, thumboffset)
else:
extractVideoFrame(os.path.join(folder, "stream.mv2"), titleImage, thumboffset)
write( "*************************************************************")
write( "Finished processing file '%s'" % file.attributes["filename"].value)
write( "*************************************************************") | [
"def",
"doProcessFileProjectX",
"(",
"file",
",",
"folder",
",",
"count",
")",
":",
"write",
"(",
"\"*************************************************************\"",
")",
"write",
"(",
"\"Processing %s %d: '%s'\"",
"%",
"(",
"file",
".",
"attributes",
"[",
"\"type\"",
"]",
".",
"value",
",",
"count",
",",
"file",
".",
"attributes",
"[",
"\"filename\"",
"]",
".",
"value",
")",
")",
"write",
"(",
"\"*************************************************************\"",
")",
"#As part of this routine we need to pre-process the video this MAY mean:",
"#1. encoding to mpeg2 (if its an avi for instance or isn't DVD compatible)",
"#2. removing commercials/cleaning up mpeg2 stream",
"#3. selecting audio track(s) to use and encoding audio from mp2 into ac3",
"#4. de-multiplexing into video and audio steams",
"mediafile",
"=",
"\"\"",
"if",
"file",
".",
"hasAttribute",
"(",
"\"localfilename\"",
")",
":",
"mediafile",
"=",
"file",
".",
"attributes",
"[",
"\"localfilename\"",
"]",
".",
"value",
"elif",
"file",
".",
"attributes",
"[",
"\"type\"",
"]",
".",
"value",
"==",
"\"recording\"",
":",
"mediafile",
"=",
"file",
".",
"attributes",
"[",
"\"filename\"",
"]",
".",
"value",
"elif",
"file",
".",
"attributes",
"[",
"\"type\"",
"]",
".",
"value",
"==",
"\"video\"",
":",
"mediafile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"videopath",
",",
"file",
".",
"attributes",
"[",
"\"filename\"",
"]",
".",
"value",
")",
"elif",
"file",
".",
"attributes",
"[",
"\"type\"",
"]",
".",
"value",
"==",
"\"file\"",
":",
"mediafile",
"=",
"file",
".",
"attributes",
"[",
"\"filename\"",
"]",
".",
"value",
"else",
":",
"fatalError",
"(",
"\"Unknown type of video file it must be 'recording', 'video' or 'file'.\"",
")",
"#Get the XML containing information about this item",
"infoDOM",
"=",
"xml",
".",
"dom",
".",
"minidom",
".",
"parse",
"(",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"\"info.xml\"",
")",
")",
"#Error out if its the wrong XML",
"if",
"infoDOM",
".",
"documentElement",
".",
"tagName",
"!=",
"\"fileinfo\"",
":",
"fatalError",
"(",
"\"The info.xml file (%s) doesn't look right\"",
"%",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"\"info.xml\"",
")",
")",
"#do we need to re-encode the file to make it DVD compliant?",
"if",
"not",
"isFileOkayForDVD",
"(",
"file",
",",
"folder",
")",
":",
"if",
"getFileType",
"(",
"folder",
")",
"==",
"'nuv'",
":",
"#file is a nuv file which mythffmpeg has problems reading so use mythtranscode to pass",
"#the video and audio streams to mythffmpeg to do the reencode",
"#we need to re-encode the file, make sure we get the right video/audio streams",
"#would be good if we could also split the file at the same time",
"getStreamInformation",
"(",
"mediafile",
",",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"\"streaminfo.xml\"",
")",
",",
"0",
")",
"#choose which streams we need",
"video",
",",
"audio1",
",",
"audio2",
"=",
"selectStreams",
"(",
"folder",
")",
"#choose which aspect ratio we should use",
"aspectratio",
"=",
"selectAspectRatio",
"(",
"folder",
")",
"write",
"(",
"\"Re-encoding audio and video from nuv file\"",
")",
"# what encoding profile should we use",
"if",
"file",
".",
"hasAttribute",
"(",
"\"encodingprofile\"",
")",
":",
"profile",
"=",
"file",
".",
"attributes",
"[",
"\"encodingprofile\"",
"]",
".",
"value",
"else",
":",
"profile",
"=",
"defaultEncodingProfile",
"if",
"file",
".",
"hasAttribute",
"(",
"\"localfilename\"",
")",
":",
"mediafile",
"=",
"file",
".",
"attributes",
"[",
"\"localfilename\"",
"]",
".",
"value",
"chanid",
"=",
"-",
"1",
"starttime",
"=",
"-",
"1",
"usecutlist",
"=",
"-",
"1",
"elif",
"file",
".",
"attributes",
"[",
"\"type\"",
"]",
".",
"value",
"==",
"\"recording\"",
":",
"mediafile",
"=",
"-",
"1",
"chanid",
"=",
"getText",
"(",
"infoDOM",
".",
"getElementsByTagName",
"(",
"\"chanid\"",
")",
"[",
"0",
"]",
")",
"starttime",
"=",
"getText",
"(",
"infoDOM",
".",
"getElementsByTagName",
"(",
"\"starttime\"",
")",
"[",
"0",
"]",
")",
"usecutlist",
"=",
"(",
"file",
".",
"attributes",
"[",
"\"usecutlist\"",
"]",
".",
"value",
"==",
"\"1\"",
"and",
"getText",
"(",
"infoDOM",
".",
"getElementsByTagName",
"(",
"\"hascutlist\"",
")",
"[",
"0",
"]",
")",
"==",
"\"yes\"",
")",
"else",
":",
"chanid",
"=",
"-",
"1",
"starttime",
"=",
"-",
"1",
"usecutlist",
"=",
"-",
"1",
"encodeNuvToMPEG2",
"(",
"chanid",
",",
"starttime",
",",
"mediafile",
",",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"\"newfile2.mpg\"",
")",
",",
"folder",
",",
"profile",
",",
"usecutlist",
")",
"mediafile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"'newfile2.mpg'",
")",
"else",
":",
"#we need to re-encode the file, make sure we get the right video/audio streams",
"#would be good if we could also split the file at the same time",
"getStreamInformation",
"(",
"mediafile",
",",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"\"streaminfo.xml\"",
")",
",",
"0",
")",
"#choose which streams we need",
"video",
",",
"audio1",
",",
"audio2",
"=",
"selectStreams",
"(",
"folder",
")",
"#choose which aspect ratio we should use",
"aspectratio",
"=",
"selectAspectRatio",
"(",
"folder",
")",
"write",
"(",
"\"Re-encoding audio and video\"",
")",
"# Run from local file?",
"if",
"file",
".",
"hasAttribute",
"(",
"\"localfilename\"",
")",
":",
"mediafile",
"=",
"file",
".",
"attributes",
"[",
"\"localfilename\"",
"]",
".",
"value",
"# what encoding profile should we use",
"if",
"file",
".",
"hasAttribute",
"(",
"\"encodingprofile\"",
")",
":",
"profile",
"=",
"file",
".",
"attributes",
"[",
"\"encodingprofile\"",
"]",
".",
"value",
"else",
":",
"profile",
"=",
"defaultEncodingProfile",
"#do the re-encode",
"encodeVideoToMPEG2",
"(",
"mediafile",
",",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"\"newfile2.mpg\"",
")",
",",
"video",
",",
"audio1",
",",
"audio2",
",",
"aspectratio",
",",
"profile",
")",
"mediafile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"'newfile2.mpg'",
")",
"#remove an intermediate file",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"\"newfile1.mpg\"",
")",
")",
":",
"os",
".",
"remove",
"(",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"'newfile1.mpg'",
")",
")",
"# the file is now DVD compliant now we need to remove commercials",
"# and split it into video, audio, subtitle parts",
"# find out what streams we have available now",
"getStreamInformation",
"(",
"mediafile",
",",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"\"streaminfo.xml\"",
")",
",",
"1",
")",
"# choose which streams we need",
"video",
",",
"audio1",
",",
"audio2",
"=",
"selectStreams",
"(",
"folder",
")",
"# now attempt to split the source file into video and audio parts",
"# using projectX",
"# If this is an mpeg2 myth recording and there is a cut list available and the",
"# user wants to use it run projectx to cut out commercials etc",
"if",
"file",
".",
"attributes",
"[",
"\"type\"",
"]",
".",
"value",
"==",
"\"recording\"",
":",
"if",
"file",
".",
"attributes",
"[",
"\"usecutlist\"",
"]",
".",
"value",
"==",
"\"1\"",
"and",
"getText",
"(",
"infoDOM",
".",
"getElementsByTagName",
"(",
"\"hascutlist\"",
")",
"[",
"0",
"]",
")",
"==",
"\"yes\"",
":",
"chanid",
"=",
"getText",
"(",
"infoDOM",
".",
"getElementsByTagName",
"(",
"\"chanid\"",
")",
"[",
"0",
"]",
")",
"starttime",
"=",
"getText",
"(",
"infoDOM",
".",
"getElementsByTagName",
"(",
"\"starttime\"",
")",
"[",
"0",
"]",
")",
"write",
"(",
"\"File has a cut list - running Project-X to remove unwanted segments\"",
")",
"if",
"not",
"runProjectX",
"(",
"chanid",
",",
"starttime",
",",
"folder",
",",
"True",
",",
"mediafile",
")",
":",
"fatalError",
"(",
"\"Failed to run Project-X to remove unwanted segments and demux\"",
")",
"else",
":",
"# no cutlist so just demux this file",
"chanid",
"=",
"getText",
"(",
"infoDOM",
".",
"getElementsByTagName",
"(",
"\"chanid\"",
")",
"[",
"0",
"]",
")",
"starttime",
"=",
"getText",
"(",
"infoDOM",
".",
"getElementsByTagName",
"(",
"\"starttime\"",
")",
"[",
"0",
"]",
")",
"write",
"(",
"\"Using Project-X to demux file\"",
")",
"if",
"not",
"runProjectX",
"(",
"chanid",
",",
"starttime",
",",
"folder",
",",
"False",
",",
"mediafile",
")",
":",
"fatalError",
"(",
"\"Failed to run Project-X to demux file\"",
")",
"else",
":",
"# just demux this file",
"chanid",
"=",
"-",
"1",
"starttime",
"=",
"-",
"1",
"write",
"(",
"\"Running Project-X to demux file\"",
")",
"if",
"not",
"runProjectX",
"(",
"chanid",
",",
"starttime",
",",
"folder",
",",
"False",
",",
"mediafile",
")",
":",
"fatalError",
"(",
"\"Failed to run Project-X to demux file\"",
")",
"# we now have a video stream and one or more audio streams",
"# check if we need to convert any of the audio streams to ac3",
"processAudio",
"(",
"folder",
")",
"# if we don't already have one find a title thumbnail image",
"titleImage",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"\"title.jpg\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"titleImage",
")",
":",
"# if the file is a recording try to use its preview image for the thumb",
"if",
"file",
".",
"attributes",
"[",
"\"type\"",
"]",
".",
"value",
"==",
"\"recording\"",
":",
"previewImage",
"=",
"file",
".",
"attributes",
"[",
"\"filename\"",
"]",
".",
"value",
"+",
"\".png\"",
"if",
"usebookmark",
"==",
"True",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"previewImage",
")",
":",
"copy",
"(",
"previewImage",
",",
"titleImage",
")",
"else",
":",
"extractVideoFrame",
"(",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"\"stream.mv2\"",
")",
",",
"titleImage",
",",
"thumboffset",
")",
"else",
":",
"extractVideoFrame",
"(",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"\"stream.mv2\"",
")",
",",
"titleImage",
",",
"thumboffset",
")",
"write",
"(",
"\"*************************************************************\"",
")",
"write",
"(",
"\"Finished processing file '%s'\"",
"%",
"file",
".",
"attributes",
"[",
"\"filename\"",
"]",
".",
"value",
")",
"write",
"(",
"\"*************************************************************\"",
")"
] | https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythplugins/mytharchive/mythburn/scripts/mythburn.py#L4720-L4882 | ||
VelsonWang/HmiFuncDesigner | 439265da17bd3424e678932cbfbc0237b52630f3 | HmiFuncDesigner/libs/qscintilla/Python/configure.py | python | _HostPythonConfiguration.__init__ | (self) | Initialise the configuration. | Initialise the configuration. | [
"Initialise",
"the",
"configuration",
"."
] | def __init__(self):
""" Initialise the configuration. """
self.platform = sys.platform
self.version = sys.hexversion >> 8
self.inc_dir = sysconfig.get_python_inc()
self.venv_inc_dir = sysconfig.get_python_inc(prefix=sys.prefix)
self.module_dir = sysconfig.get_python_lib(plat_specific=1)
self.debug = hasattr(sys, 'gettotalrefcount')
if sys.platform == 'win32':
self.data_dir = sys.prefix
self.lib_dir = sys.prefix + '\\libs'
else:
self.data_dir = sys.prefix + '/share'
self.lib_dir = sys.prefix + '/lib' | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"platform",
"=",
"sys",
".",
"platform",
"self",
".",
"version",
"=",
"sys",
".",
"hexversion",
">>",
"8",
"self",
".",
"inc_dir",
"=",
"sysconfig",
".",
"get_python_inc",
"(",
")",
"self",
".",
"venv_inc_dir",
"=",
"sysconfig",
".",
"get_python_inc",
"(",
"prefix",
"=",
"sys",
".",
"prefix",
")",
"self",
".",
"module_dir",
"=",
"sysconfig",
".",
"get_python_lib",
"(",
"plat_specific",
"=",
"1",
")",
"self",
".",
"debug",
"=",
"hasattr",
"(",
"sys",
",",
"'gettotalrefcount'",
")",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"self",
".",
"data_dir",
"=",
"sys",
".",
"prefix",
"self",
".",
"lib_dir",
"=",
"sys",
".",
"prefix",
"+",
"'\\\\libs'",
"else",
":",
"self",
".",
"data_dir",
"=",
"sys",
".",
"prefix",
"+",
"'/share'",
"self",
".",
"lib_dir",
"=",
"sys",
".",
"prefix",
"+",
"'/lib'"
] | https://github.com/VelsonWang/HmiFuncDesigner/blob/439265da17bd3424e678932cbfbc0237b52630f3/HmiFuncDesigner/libs/qscintilla/Python/configure.py#L637-L653 | ||
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/sping/PDF/pdfutils.py | python | preProcessImages | (spec) | r"""accepts either a filespec ('C:\mydir\*.jpg') or a list
of image filenames, crunches them all to save time. Run this
to save huge amounts of time when repeatedly building image
documents. | r"""accepts either a filespec ('C:\mydir\*.jpg') or a list
of image filenames, crunches them all to save time. Run this
to save huge amounts of time when repeatedly building image
documents. | [
"r",
"accepts",
"either",
"a",
"filespec",
"(",
"C",
":",
"\\",
"mydir",
"\\",
"*",
".",
"jpg",
")",
"or",
"a",
"list",
"of",
"image",
"filenames",
"crunches",
"them",
"all",
"to",
"save",
"time",
".",
"Run",
"this",
"to",
"save",
"huge",
"amounts",
"of",
"time",
"when",
"repeatedly",
"building",
"image",
"documents",
"."
] | def preProcessImages(spec):
r"""accepts either a filespec ('C:\mydir\*.jpg') or a list
of image filenames, crunches them all to save time. Run this
to save huge amounts of time when repeatedly building image
documents."""
if isinstance(spec, str):
filelist = glob.glob(spec)
else: # list or tuple OK
filelist = spec
for filename in filelist:
if cachedImageExists(filename):
print('cached version of %s already exists' % filename)
else:
cacheImageFile(filename) | [
"def",
"preProcessImages",
"(",
"spec",
")",
":",
"if",
"isinstance",
"(",
"spec",
",",
"str",
")",
":",
"filelist",
"=",
"glob",
".",
"glob",
"(",
"spec",
")",
"else",
":",
"# list or tuple OK",
"filelist",
"=",
"spec",
"for",
"filename",
"in",
"filelist",
":",
"if",
"cachedImageExists",
"(",
"filename",
")",
":",
"print",
"(",
"'cached version of %s already exists'",
"%",
"filename",
")",
"else",
":",
"cacheImageFile",
"(",
"filename",
")"
] | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/PDF/pdfutils.py#L53-L67 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/command/easy_install.py | python | easy_install.check_conflicts | (self, dist) | return dist | Verify that there are no conflicting "old-style" packages | Verify that there are no conflicting "old-style" packages | [
"Verify",
"that",
"there",
"are",
"no",
"conflicting",
"old",
"-",
"style",
"packages"
] | def check_conflicts(self, dist):
"""Verify that there are no conflicting "old-style" packages"""
return dist # XXX temporarily disable until new strategy is stable
from imp import find_module, get_suffixes
from glob import glob
blockers = []
names = dict.fromkeys(dist._get_metadata('top_level.txt')) # XXX private attr
exts = {'.pyc':1, '.pyo':1} # get_suffixes() might leave one out
for ext,mode,typ in get_suffixes():
exts[ext] = 1
for path,files in expand_paths([self.install_dir]+self.all_site_dirs):
for filename in files:
base,ext = os.path.splitext(filename)
if base in names:
if not ext:
# no extension, check for package
try:
f, filename, descr = find_module(base, [path])
except ImportError:
continue
else:
if f: f.close()
if filename not in blockers:
blockers.append(filename)
elif ext in exts and base!='site': # XXX ugh
blockers.append(os.path.join(path,filename))
if blockers:
self.found_conflicts(dist, blockers)
return dist | [
"def",
"check_conflicts",
"(",
"self",
",",
"dist",
")",
":",
"return",
"dist",
"# XXX temporarily disable until new strategy is stable",
"from",
"imp",
"import",
"find_module",
",",
"get_suffixes",
"from",
"glob",
"import",
"glob",
"blockers",
"=",
"[",
"]",
"names",
"=",
"dict",
".",
"fromkeys",
"(",
"dist",
".",
"_get_metadata",
"(",
"'top_level.txt'",
")",
")",
"# XXX private attr",
"exts",
"=",
"{",
"'.pyc'",
":",
"1",
",",
"'.pyo'",
":",
"1",
"}",
"# get_suffixes() might leave one out",
"for",
"ext",
",",
"mode",
",",
"typ",
"in",
"get_suffixes",
"(",
")",
":",
"exts",
"[",
"ext",
"]",
"=",
"1",
"for",
"path",
",",
"files",
"in",
"expand_paths",
"(",
"[",
"self",
".",
"install_dir",
"]",
"+",
"self",
".",
"all_site_dirs",
")",
":",
"for",
"filename",
"in",
"files",
":",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"base",
"in",
"names",
":",
"if",
"not",
"ext",
":",
"# no extension, check for package",
"try",
":",
"f",
",",
"filename",
",",
"descr",
"=",
"find_module",
"(",
"base",
",",
"[",
"path",
"]",
")",
"except",
"ImportError",
":",
"continue",
"else",
":",
"if",
"f",
":",
"f",
".",
"close",
"(",
")",
"if",
"filename",
"not",
"in",
"blockers",
":",
"blockers",
".",
"append",
"(",
"filename",
")",
"elif",
"ext",
"in",
"exts",
"and",
"base",
"!=",
"'site'",
":",
"# XXX ugh",
"blockers",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
")",
"if",
"blockers",
":",
"self",
".",
"found_conflicts",
"(",
"dist",
",",
"blockers",
")",
"return",
"dist"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/setuptools/command/easy_install.py#L957-L990 | |
ComputationalRadiationPhysics/picongpu | 59e9b53605f9a5c1bf271eeb055bc74370a99052 | lib/python/picongpu/plugins/plot_mpl/base_visualizer.py | python | Visualizer.__init__ | (self, reader_cls, run_directories=None, ax=None) | Initialize the reader and data as member parameters.
Parameters
----------
run_directories : list of tuples of length 2
or single tuple of length 2
or list of strings or string.
If tuples are specified, they have to be
of the following form (sim_label, sim_path) and consist
of strings with 'sim_label' being a short string
used e.g. in plot legends and 'sim_path'
leading to the run directory of PIConGPU
(the path before ``simOutput/``).
If only a string or list of strings is given,
labels are generated by enumeration.
If None, the user is responsible for providing run_directories
later on via set_run_directories() before calling visualize().
reader_cls: class
handle of a PIConGPU Data reader class (not string!)
which inherited from BaseReader in plugins.data.base_reader.
ax: matplotlib.axes | Initialize the reader and data as member parameters. | [
"Initialize",
"the",
"reader",
"and",
"data",
"as",
"member",
"parameters",
"."
] | def __init__(self, reader_cls, run_directories=None, ax=None):
"""
Initialize the reader and data as member parameters.
Parameters
----------
run_directories : list of tuples of length 2
or single tuple of length 2
or list of strings or string.
If tuples are specified, they have to be
of the following form (sim_label, sim_path) and consist
of strings with 'sim_label' being a short string
used e.g. in plot legends and 'sim_path'
leading to the run directory of PIConGPU
(the path before ``simOutput/``).
If only a string or list of strings is given,
labels are generated by enumeration.
If None, the user is responsible for providing run_directories
later on via set_run_directories() before calling visualize().
reader_cls: class
handle of a PIConGPU Data reader class (not string!)
which inherited from BaseReader in plugins.data.base_reader.
ax: matplotlib.axes
"""
self.reader_cls = reader_cls
if ax is None:
warn("No axes was given, using plt.gca() instead!")
ax = plt.gca()
self.ax = ax
# they will only be set when run_directories are provided
self.data_reader = None
self.data = None
self.plt_obj = None
self.sim_labels = None
self.colors = None
if run_directories is not None:
self.set_run_directories(run_directories) | [
"def",
"__init__",
"(",
"self",
",",
"reader_cls",
",",
"run_directories",
"=",
"None",
",",
"ax",
"=",
"None",
")",
":",
"self",
".",
"reader_cls",
"=",
"reader_cls",
"if",
"ax",
"is",
"None",
":",
"warn",
"(",
"\"No axes was given, using plt.gca() instead!\"",
")",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"self",
".",
"ax",
"=",
"ax",
"# they will only be set when run_directories are provided",
"self",
".",
"data_reader",
"=",
"None",
"self",
".",
"data",
"=",
"None",
"self",
".",
"plt_obj",
"=",
"None",
"self",
".",
"sim_labels",
"=",
"None",
"self",
".",
"colors",
"=",
"None",
"if",
"run_directories",
"is",
"not",
"None",
":",
"self",
".",
"set_run_directories",
"(",
"run_directories",
")"
] | https://github.com/ComputationalRadiationPhysics/picongpu/blob/59e9b53605f9a5c1bf271eeb055bc74370a99052/lib/python/picongpu/plugins/plot_mpl/base_visualizer.py#L29-L68 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py2/jinja2/sandbox.py | python | SandboxedEnvironment.intercept_unop | (self, operator) | return False | Called during template compilation with the name of a unary
operator to check if it should be intercepted at runtime. If this
method returns `True`, :meth:`call_unop` is executed for this unary
operator. The default implementation of :meth:`call_unop` will use
the :attr:`unop_table` dictionary to perform the operator with the
same logic as the builtin one.
The following unary operators are interceptable: ``+`` and ``-``
Intercepted calls are always slower than the native operator call,
so make sure only to intercept the ones you are interested in.
.. versionadded:: 2.6 | Called during template compilation with the name of a unary
operator to check if it should be intercepted at runtime. If this
method returns `True`, :meth:`call_unop` is executed for this unary
operator. The default implementation of :meth:`call_unop` will use
the :attr:`unop_table` dictionary to perform the operator with the
same logic as the builtin one. | [
"Called",
"during",
"template",
"compilation",
"with",
"the",
"name",
"of",
"a",
"unary",
"operator",
"to",
"check",
"if",
"it",
"should",
"be",
"intercepted",
"at",
"runtime",
".",
"If",
"this",
"method",
"returns",
"True",
":",
"meth",
":",
"call_unop",
"is",
"executed",
"for",
"this",
"unary",
"operator",
".",
"The",
"default",
"implementation",
"of",
":",
"meth",
":",
"call_unop",
"will",
"use",
"the",
":",
"attr",
":",
"unop_table",
"dictionary",
"to",
"perform",
"the",
"operator",
"with",
"the",
"same",
"logic",
"as",
"the",
"builtin",
"one",
"."
] | def intercept_unop(self, operator):
"""Called during template compilation with the name of a unary
operator to check if it should be intercepted at runtime. If this
method returns `True`, :meth:`call_unop` is executed for this unary
operator. The default implementation of :meth:`call_unop` will use
the :attr:`unop_table` dictionary to perform the operator with the
same logic as the builtin one.
The following unary operators are interceptable: ``+`` and ``-``
Intercepted calls are always slower than the native operator call,
so make sure only to intercept the ones you are interested in.
.. versionadded:: 2.6
"""
return False | [
"def",
"intercept_unop",
"(",
"self",
",",
"operator",
")",
":",
"return",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/sandbox.py#L321-L336 | |
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | thirdparty/fluid/modules/gapi/misc/python/samples/gaze_estimation.py | python | intersection | (surface, rect) | return (l_x, l_y, width, height) | Remove zone of out of bound from ROI
Params:
surface: image bounds is rect representation (top left coordinates and width and height)
rect: region of interest is also has rect representation
Return:
Modified ROI with correct bounds | Remove zone of out of bound from ROI | [
"Remove",
"zone",
"of",
"out",
"of",
"bound",
"from",
"ROI"
] | def intersection(surface, rect):
""" Remove zone of out of bound from ROI
Params:
surface: image bounds is rect representation (top left coordinates and width and height)
rect: region of interest is also has rect representation
Return:
Modified ROI with correct bounds
"""
l_x = max(surface[0], rect[0])
l_y = max(surface[1], rect[1])
width = min(surface[0] + surface[2], rect[0] + rect[2]) - l_x
height = min(surface[1] + surface[3], rect[1] + rect[3]) - l_y
if width < 0 or height < 0:
return (0, 0, 0, 0)
return (l_x, l_y, width, height) | [
"def",
"intersection",
"(",
"surface",
",",
"rect",
")",
":",
"l_x",
"=",
"max",
"(",
"surface",
"[",
"0",
"]",
",",
"rect",
"[",
"0",
"]",
")",
"l_y",
"=",
"max",
"(",
"surface",
"[",
"1",
"]",
",",
"rect",
"[",
"1",
"]",
")",
"width",
"=",
"min",
"(",
"surface",
"[",
"0",
"]",
"+",
"surface",
"[",
"2",
"]",
",",
"rect",
"[",
"0",
"]",
"+",
"rect",
"[",
"2",
"]",
")",
"-",
"l_x",
"height",
"=",
"min",
"(",
"surface",
"[",
"1",
"]",
"+",
"surface",
"[",
"3",
"]",
",",
"rect",
"[",
"1",
"]",
"+",
"rect",
"[",
"3",
"]",
")",
"-",
"l_y",
"if",
"width",
"<",
"0",
"or",
"height",
"<",
"0",
":",
"return",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"return",
"(",
"l_x",
",",
"l_y",
",",
"width",
",",
"height",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/thirdparty/fluid/modules/gapi/misc/python/samples/gaze_estimation.py#L70-L86 | |
p4lang/p4c | 3272e79369f20813cc1a555a5eb26f44432f84a4 | tools/cpplint.py | python | CheckHeaderFileIncluded | (filename, include_state, error) | Logs an error if a source file does not include its header. | Logs an error if a source file does not include its header. | [
"Logs",
"an",
"error",
"if",
"a",
"source",
"file",
"does",
"not",
"include",
"its",
"header",
"."
] | def CheckHeaderFileIncluded(filename, include_state, error):
"""Logs an error if a source file does not include its header."""
# Do not check test files
fileinfo = FileInfo(filename)
if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
return
for ext in GetHeaderExtensions():
basefilename = filename[0:len(filename) - len(fileinfo.Extension())]
headerfile = basefilename + '.' + ext
if not os.path.exists(headerfile):
continue
headername = FileInfo(headerfile).RepositoryName()
first_include = None
include_uses_unix_dir_aliases = False
for section_list in include_state.include_list:
for f in section_list:
include_text = f[0]
if "./" in include_text:
include_uses_unix_dir_aliases = True
if headername in include_text or include_text in headername:
return
if not first_include:
first_include = f[1]
message = '%s should include its header file %s' % (fileinfo.RepositoryName(), headername)
if include_uses_unix_dir_aliases:
message += ". Relative paths like . and .. are not allowed."
error(filename, first_include, 'build/include', 5, message) | [
"def",
"CheckHeaderFileIncluded",
"(",
"filename",
",",
"include_state",
",",
"error",
")",
":",
"# Do not check test files",
"fileinfo",
"=",
"FileInfo",
"(",
"filename",
")",
"if",
"Search",
"(",
"_TEST_FILE_SUFFIX",
",",
"fileinfo",
".",
"BaseName",
"(",
")",
")",
":",
"return",
"for",
"ext",
"in",
"GetHeaderExtensions",
"(",
")",
":",
"basefilename",
"=",
"filename",
"[",
"0",
":",
"len",
"(",
"filename",
")",
"-",
"len",
"(",
"fileinfo",
".",
"Extension",
"(",
")",
")",
"]",
"headerfile",
"=",
"basefilename",
"+",
"'.'",
"+",
"ext",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"headerfile",
")",
":",
"continue",
"headername",
"=",
"FileInfo",
"(",
"headerfile",
")",
".",
"RepositoryName",
"(",
")",
"first_include",
"=",
"None",
"include_uses_unix_dir_aliases",
"=",
"False",
"for",
"section_list",
"in",
"include_state",
".",
"include_list",
":",
"for",
"f",
"in",
"section_list",
":",
"include_text",
"=",
"f",
"[",
"0",
"]",
"if",
"\"./\"",
"in",
"include_text",
":",
"include_uses_unix_dir_aliases",
"=",
"True",
"if",
"headername",
"in",
"include_text",
"or",
"include_text",
"in",
"headername",
":",
"return",
"if",
"not",
"first_include",
":",
"first_include",
"=",
"f",
"[",
"1",
"]",
"message",
"=",
"'%s should include its header file %s'",
"%",
"(",
"fileinfo",
".",
"RepositoryName",
"(",
")",
",",
"headername",
")",
"if",
"include_uses_unix_dir_aliases",
":",
"message",
"+=",
"\". Relative paths like . and .. are not allowed.\"",
"error",
"(",
"filename",
",",
"first_include",
",",
"'build/include'",
",",
"5",
",",
"message",
")"
] | https://github.com/p4lang/p4c/blob/3272e79369f20813cc1a555a5eb26f44432f84a4/tools/cpplint.py#L2474-L2504 | ||
Smorodov/Multitarget-tracker | bee300e8bfd660c86cbeb6892c65a5b7195c9381 | thirdparty/pybind11/tools/clang/cindex.py | python | Token.location | (self) | return conf.lib.clang_getTokenLocation(self._tu, self) | The SourceLocation this Token occurs at. | The SourceLocation this Token occurs at. | [
"The",
"SourceLocation",
"this",
"Token",
"occurs",
"at",
"."
] | def location(self):
"""The SourceLocation this Token occurs at."""
return conf.lib.clang_getTokenLocation(self._tu, self) | [
"def",
"location",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getTokenLocation",
"(",
"self",
".",
"_tu",
",",
"self",
")"
] | https://github.com/Smorodov/Multitarget-tracker/blob/bee300e8bfd660c86cbeb6892c65a5b7195c9381/thirdparty/pybind11/tools/clang/cindex.py#L3005-L3007 | |
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Part/AttachmentEditor/TaskAttachmentEditor.py | python | StrListFromRefs | (references) | return [StrFromLink(feature,subelement) for (feature, subelement) in references_oldstyle] | input: PropertyLinkSubList. Output: list of strings for UI. | input: PropertyLinkSubList. Output: list of strings for UI. | [
"input",
":",
"PropertyLinkSubList",
".",
"Output",
":",
"list",
"of",
"strings",
"for",
"UI",
"."
] | def StrListFromRefs(references):
'''input: PropertyLinkSubList. Output: list of strings for UI.'''
references_oldstyle = linkSubList_convertToOldStyle(references)
return [StrFromLink(feature,subelement) for (feature, subelement) in references_oldstyle] | [
"def",
"StrListFromRefs",
"(",
"references",
")",
":",
"references_oldstyle",
"=",
"linkSubList_convertToOldStyle",
"(",
"references",
")",
"return",
"[",
"StrFromLink",
"(",
"feature",
",",
"subelement",
")",
"for",
"(",
"feature",
",",
"subelement",
")",
"in",
"references_oldstyle",
"]"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Part/AttachmentEditor/TaskAttachmentEditor.py#L101-L104 | |
swift/swift | 12d031cf8177fdec0137f9aa7e2912fa23c4416b | 3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/mwcc.py | python | find_versions | () | return versions | Return a list of MWVersion objects representing installed versions | Return a list of MWVersion objects representing installed versions | [
"Return",
"a",
"list",
"of",
"MWVersion",
"objects",
"representing",
"installed",
"versions"
] | def find_versions():
"""Return a list of MWVersion objects representing installed versions"""
versions = []
### This function finds CodeWarrior by reading from the registry on
### Windows. Some other method needs to be implemented for other
### platforms, maybe something that calls env.WhereIs('mwcc')
if SCons.Util.can_read_reg:
try:
HLM = SCons.Util.HKEY_LOCAL_MACHINE
product = 'SOFTWARE\\Metrowerks\\CodeWarrior\\Product Versions'
product_key = SCons.Util.RegOpenKeyEx(HLM, product)
i = 0
while True:
name = product + '\\' + SCons.Util.RegEnumKey(product_key, i)
name_key = SCons.Util.RegOpenKeyEx(HLM, name)
try:
version = SCons.Util.RegQueryValueEx(name_key, 'VERSION')
path = SCons.Util.RegQueryValueEx(name_key, 'PATH')
mwv = MWVersion(version[0], path[0], 'Win32-X86')
versions.append(mwv)
except SCons.Util.RegError:
pass
i = i + 1
except SCons.Util.RegError:
pass
return versions | [
"def",
"find_versions",
"(",
")",
":",
"versions",
"=",
"[",
"]",
"### This function finds CodeWarrior by reading from the registry on",
"### Windows. Some other method needs to be implemented for other",
"### platforms, maybe something that calls env.WhereIs('mwcc')",
"if",
"SCons",
".",
"Util",
".",
"can_read_reg",
":",
"try",
":",
"HLM",
"=",
"SCons",
".",
"Util",
".",
"HKEY_LOCAL_MACHINE",
"product",
"=",
"'SOFTWARE\\\\Metrowerks\\\\CodeWarrior\\\\Product Versions'",
"product_key",
"=",
"SCons",
".",
"Util",
".",
"RegOpenKeyEx",
"(",
"HLM",
",",
"product",
")",
"i",
"=",
"0",
"while",
"True",
":",
"name",
"=",
"product",
"+",
"'\\\\'",
"+",
"SCons",
".",
"Util",
".",
"RegEnumKey",
"(",
"product_key",
",",
"i",
")",
"name_key",
"=",
"SCons",
".",
"Util",
".",
"RegOpenKeyEx",
"(",
"HLM",
",",
"name",
")",
"try",
":",
"version",
"=",
"SCons",
".",
"Util",
".",
"RegQueryValueEx",
"(",
"name_key",
",",
"'VERSION'",
")",
"path",
"=",
"SCons",
".",
"Util",
".",
"RegQueryValueEx",
"(",
"name_key",
",",
"'PATH'",
")",
"mwv",
"=",
"MWVersion",
"(",
"version",
"[",
"0",
"]",
",",
"path",
"[",
"0",
"]",
",",
"'Win32-X86'",
")",
"versions",
".",
"append",
"(",
"mwv",
")",
"except",
"SCons",
".",
"Util",
".",
"RegError",
":",
"pass",
"i",
"=",
"i",
"+",
"1",
"except",
"SCons",
".",
"Util",
".",
"RegError",
":",
"pass",
"return",
"versions"
] | https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/mwcc.py#L87-L119 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/errors.py | python | ParserContext.add_bindata_no_default | (self, location, ast_type, ast_parent) | Add an error about a bindata type with a default value. | Add an error about a bindata type with a default value. | [
"Add",
"an",
"error",
"about",
"a",
"bindata",
"type",
"with",
"a",
"default",
"value",
"."
] | def add_bindata_no_default(self, location, ast_type, ast_parent):
# type: (common.SourceLocation, str, str) -> None
# pylint: disable=invalid-name
"""Add an error about a bindata type with a default value."""
self._add_error(location, ERROR_ID_BAD_BINDATA_DEFAULT,
("Default values are not allowed for %s '%s'") % (ast_type, ast_parent)) | [
"def",
"add_bindata_no_default",
"(",
"self",
",",
"location",
",",
"ast_type",
",",
"ast_parent",
")",
":",
"# type: (common.SourceLocation, str, str) -> None",
"# pylint: disable=invalid-name",
"self",
".",
"_add_error",
"(",
"location",
",",
"ERROR_ID_BAD_BINDATA_DEFAULT",
",",
"(",
"\"Default values are not allowed for %s '%s'\"",
")",
"%",
"(",
"ast_type",
",",
"ast_parent",
")",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/errors.py#L525-L530 | ||
MVIG-SJTU/RMPE | 5188c230ec800c12be7369c3619615bc9b020aa4 | scripts/cpp_lint.py | python | ReverseCloseExpression | (clean_lines, linenum, pos) | return (line, 0, -1) | If input points to ) or } or ] or >, finds the position that opens it.
If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
linenum/pos that correspond to the opening of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *at* the opening brace, or
(line, 0, -1) if we never find the matching opening brace. Note
we ignore strings and comments when matching; and the line we
return is the 'cleansed' line at linenum. | If input points to ) or } or ] or >, finds the position that opens it. | [
"If",
"input",
"points",
"to",
")",
"or",
"}",
"or",
"]",
"or",
">",
"finds",
"the",
"position",
"that",
"opens",
"it",
"."
] | def ReverseCloseExpression(clean_lines, linenum, pos):
"""If input points to ) or } or ] or >, finds the position that opens it.
If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
linenum/pos that correspond to the opening of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *at* the opening brace, or
(line, 0, -1) if we never find the matching opening brace. Note
we ignore strings and comments when matching; and the line we
return is the 'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
endchar = line[pos]
if endchar not in ')}]>':
return (line, 0, -1)
if endchar == ')': startchar = '('
if endchar == ']': startchar = '['
if endchar == '}': startchar = '{'
if endchar == '>': startchar = '<'
# Check last line
(start_pos, num_open) = FindStartOfExpressionInLine(
line, pos, 0, startchar, endchar)
if start_pos > -1:
return (line, linenum, start_pos)
# Continue scanning backward
while linenum > 0:
linenum -= 1
line = clean_lines.elided[linenum]
(start_pos, num_open) = FindStartOfExpressionInLine(
line, len(line) - 1, num_open, startchar, endchar)
if start_pos > -1:
return (line, linenum, start_pos)
# Did not find startchar before beginning of file, give up
return (line, 0, -1) | [
"def",
"ReverseCloseExpression",
"(",
"clean_lines",
",",
"linenum",
",",
"pos",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"endchar",
"=",
"line",
"[",
"pos",
"]",
"if",
"endchar",
"not",
"in",
"')}]>'",
":",
"return",
"(",
"line",
",",
"0",
",",
"-",
"1",
")",
"if",
"endchar",
"==",
"')'",
":",
"startchar",
"=",
"'('",
"if",
"endchar",
"==",
"']'",
":",
"startchar",
"=",
"'['",
"if",
"endchar",
"==",
"'}'",
":",
"startchar",
"=",
"'{'",
"if",
"endchar",
"==",
"'>'",
":",
"startchar",
"=",
"'<'",
"# Check last line",
"(",
"start_pos",
",",
"num_open",
")",
"=",
"FindStartOfExpressionInLine",
"(",
"line",
",",
"pos",
",",
"0",
",",
"startchar",
",",
"endchar",
")",
"if",
"start_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"start_pos",
")",
"# Continue scanning backward",
"while",
"linenum",
">",
"0",
":",
"linenum",
"-=",
"1",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"(",
"start_pos",
",",
"num_open",
")",
"=",
"FindStartOfExpressionInLine",
"(",
"line",
",",
"len",
"(",
"line",
")",
"-",
"1",
",",
"num_open",
",",
"startchar",
",",
"endchar",
")",
"if",
"start_pos",
">",
"-",
"1",
":",
"return",
"(",
"line",
",",
"linenum",
",",
"start_pos",
")",
"# Did not find startchar before beginning of file, give up",
"return",
"(",
"line",
",",
"0",
",",
"-",
"1",
")"
] | https://github.com/MVIG-SJTU/RMPE/blob/5188c230ec800c12be7369c3619615bc9b020aa4/scripts/cpp_lint.py#L1327-L1369 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py | python | crossed_column | (columns, hash_bucket_size, combiner="sum",
ckpt_to_load_from=None,
tensor_name_in_ckpt=None) | return _CrossedColumn(columns, hash_bucket_size, combiner=combiner,
ckpt_to_load_from=ckpt_to_load_from,
tensor_name_in_ckpt=tensor_name_in_ckpt) | Creates a _CrossedColumn.
Args:
columns: An iterable of _FeatureColumn. Items can be an instance of
_SparseColumn, _CrossedColumn, or _BucketizedColumn.
hash_bucket_size: An int that is > 1. The number of buckets.
combiner: A combiner string, supports sum, mean, sqrtn.
ckpt_to_load_from: (Optional). String representing checkpoint name/pattern
to restore the column weights. Required if `tensor_name_in_ckpt` is not
None.
tensor_name_in_ckpt: (Optional). Name of the `Tensor` in the provided
checkpoint from which to restore the column weights. Required if
`ckpt_to_load_from` is not None.
Returns:
A _CrossedColumn.
Raises:
TypeError: if any item in columns is not an instance of _SparseColumn,
_CrossedColumn, or _BucketizedColumn, or
hash_bucket_size is not an int.
ValueError: if hash_bucket_size is not > 1 or
len(columns) is not > 1. | Creates a _CrossedColumn. | [
"Creates",
"a",
"_CrossedColumn",
"."
] | def crossed_column(columns, hash_bucket_size, combiner="sum",
ckpt_to_load_from=None,
tensor_name_in_ckpt=None):
"""Creates a _CrossedColumn.
Args:
columns: An iterable of _FeatureColumn. Items can be an instance of
_SparseColumn, _CrossedColumn, or _BucketizedColumn.
hash_bucket_size: An int that is > 1. The number of buckets.
combiner: A combiner string, supports sum, mean, sqrtn.
ckpt_to_load_from: (Optional). String representing checkpoint name/pattern
to restore the column weights. Required if `tensor_name_in_ckpt` is not
None.
tensor_name_in_ckpt: (Optional). Name of the `Tensor` in the provided
checkpoint from which to restore the column weights. Required if
`ckpt_to_load_from` is not None.
Returns:
A _CrossedColumn.
Raises:
TypeError: if any item in columns is not an instance of _SparseColumn,
_CrossedColumn, or _BucketizedColumn, or
hash_bucket_size is not an int.
ValueError: if hash_bucket_size is not > 1 or
len(columns) is not > 1.
"""
return _CrossedColumn(columns, hash_bucket_size, combiner=combiner,
ckpt_to_load_from=ckpt_to_load_from,
tensor_name_in_ckpt=tensor_name_in_ckpt) | [
"def",
"crossed_column",
"(",
"columns",
",",
"hash_bucket_size",
",",
"combiner",
"=",
"\"sum\"",
",",
"ckpt_to_load_from",
"=",
"None",
",",
"tensor_name_in_ckpt",
"=",
"None",
")",
":",
"return",
"_CrossedColumn",
"(",
"columns",
",",
"hash_bucket_size",
",",
"combiner",
"=",
"combiner",
",",
"ckpt_to_load_from",
"=",
"ckpt_to_load_from",
",",
"tensor_name_in_ckpt",
"=",
"tensor_name_in_ckpt",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py#L1326-L1355 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/imaplib.py | python | IMAP4.open | (self, host = '', port = IMAP4_PORT) | Setup connection to remote server on "host:port"
(default: localhost:standard IMAP4 port).
This connection will be used by the routines:
read, readline, send, shutdown. | Setup connection to remote server on "host:port"
(default: localhost:standard IMAP4 port).
This connection will be used by the routines:
read, readline, send, shutdown. | [
"Setup",
"connection",
"to",
"remote",
"server",
"on",
"host",
":",
"port",
"(",
"default",
":",
"localhost",
":",
"standard",
"IMAP4",
"port",
")",
".",
"This",
"connection",
"will",
"be",
"used",
"by",
"the",
"routines",
":",
"read",
"readline",
"send",
"shutdown",
"."
] | def open(self, host = '', port = IMAP4_PORT):
"""Setup connection to remote server on "host:port"
(default: localhost:standard IMAP4 port).
This connection will be used by the routines:
read, readline, send, shutdown.
"""
self.host = host
self.port = port
self.sock = socket.create_connection((host, port))
self.file = self.sock.makefile('rb') | [
"def",
"open",
"(",
"self",
",",
"host",
"=",
"''",
",",
"port",
"=",
"IMAP4_PORT",
")",
":",
"self",
".",
"host",
"=",
"host",
"self",
".",
"port",
"=",
"port",
"self",
".",
"sock",
"=",
"socket",
".",
"create_connection",
"(",
"(",
"host",
",",
"port",
")",
")",
"self",
".",
"file",
"=",
"self",
".",
"sock",
".",
"makefile",
"(",
"'rb'",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/imaplib.py#L221-L230 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/frame.py | python | DataFrame.drop_duplicates | (
self,
subset: Hashable | Sequence[Hashable] | None = None,
keep: Literal["first"] | Literal["last"] | Literal[False] = "first",
inplace: bool = False,
ignore_index: bool = False,
) | Return DataFrame with duplicate rows removed.
Considering certain columns is optional. Indexes, including time indexes
are ignored.
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying duplicates, by
default use all of the columns.
keep : {'first', 'last', False}, default 'first'
Determines which duplicates (if any) to keep.
- ``first`` : Drop duplicates except for the first occurrence.
- ``last`` : Drop duplicates except for the last occurrence.
- False : Drop all duplicates.
inplace : bool, default False
Whether to drop duplicates in place or to return a copy.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.0.0
Returns
-------
DataFrame or None
DataFrame with duplicates removed or None if ``inplace=True``.
See Also
--------
DataFrame.value_counts: Count unique combinations of columns.
Examples
--------
Consider dataset containing ramen rating.
>>> df = pd.DataFrame({
... 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
... 'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
... 'rating': [4, 4, 3.5, 15, 5]
... })
>>> df
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
By default, it removes duplicate rows based on all columns.
>>> df.drop_duplicates()
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
To remove duplicates on specific column(s), use ``subset``.
>>> df.drop_duplicates(subset=['brand'])
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
To remove duplicates and keep last occurrences, use ``keep``.
>>> df.drop_duplicates(subset=['brand', 'style'], keep='last')
brand style rating
1 Yum Yum cup 4.0
2 Indomie cup 3.5
4 Indomie pack 5.0 | Return DataFrame with duplicate rows removed. | [
"Return",
"DataFrame",
"with",
"duplicate",
"rows",
"removed",
"."
] | def drop_duplicates(
self,
subset: Hashable | Sequence[Hashable] | None = None,
keep: Literal["first"] | Literal["last"] | Literal[False] = "first",
inplace: bool = False,
ignore_index: bool = False,
) -> DataFrame | None:
"""
Return DataFrame with duplicate rows removed.
Considering certain columns is optional. Indexes, including time indexes
are ignored.
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying duplicates, by
default use all of the columns.
keep : {'first', 'last', False}, default 'first'
Determines which duplicates (if any) to keep.
- ``first`` : Drop duplicates except for the first occurrence.
- ``last`` : Drop duplicates except for the last occurrence.
- False : Drop all duplicates.
inplace : bool, default False
Whether to drop duplicates in place or to return a copy.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.0.0
Returns
-------
DataFrame or None
DataFrame with duplicates removed or None if ``inplace=True``.
See Also
--------
DataFrame.value_counts: Count unique combinations of columns.
Examples
--------
Consider dataset containing ramen rating.
>>> df = pd.DataFrame({
... 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
... 'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
... 'rating': [4, 4, 3.5, 15, 5]
... })
>>> df
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
By default, it removes duplicate rows based on all columns.
>>> df.drop_duplicates()
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
To remove duplicates on specific column(s), use ``subset``.
>>> df.drop_duplicates(subset=['brand'])
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
To remove duplicates and keep last occurrences, use ``keep``.
>>> df.drop_duplicates(subset=['brand', 'style'], keep='last')
brand style rating
1 Yum Yum cup 4.0
2 Indomie cup 3.5
4 Indomie pack 5.0
"""
if self.empty:
return self.copy()
inplace = validate_bool_kwarg(inplace, "inplace")
ignore_index = validate_bool_kwarg(ignore_index, "ignore_index")
duplicated = self.duplicated(subset, keep=keep)
result = self[-duplicated]
if ignore_index:
result.index = ibase.default_index(len(result))
if inplace:
self._update_inplace(result)
return None
else:
return result | [
"def",
"drop_duplicates",
"(",
"self",
",",
"subset",
":",
"Hashable",
"|",
"Sequence",
"[",
"Hashable",
"]",
"|",
"None",
"=",
"None",
",",
"keep",
":",
"Literal",
"[",
"\"first\"",
"]",
"|",
"Literal",
"[",
"\"last\"",
"]",
"|",
"Literal",
"[",
"False",
"]",
"=",
"\"first\"",
",",
"inplace",
":",
"bool",
"=",
"False",
",",
"ignore_index",
":",
"bool",
"=",
"False",
",",
")",
"->",
"DataFrame",
"|",
"None",
":",
"if",
"self",
".",
"empty",
":",
"return",
"self",
".",
"copy",
"(",
")",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"\"inplace\"",
")",
"ignore_index",
"=",
"validate_bool_kwarg",
"(",
"ignore_index",
",",
"\"ignore_index\"",
")",
"duplicated",
"=",
"self",
".",
"duplicated",
"(",
"subset",
",",
"keep",
"=",
"keep",
")",
"result",
"=",
"self",
"[",
"-",
"duplicated",
"]",
"if",
"ignore_index",
":",
"result",
".",
"index",
"=",
"ibase",
".",
"default_index",
"(",
"len",
"(",
"result",
")",
")",
"if",
"inplace",
":",
"self",
".",
"_update_inplace",
"(",
"result",
")",
"return",
"None",
"else",
":",
"return",
"result"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/frame.py#L5978-L6073 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/framemanager.py | python | CheckEdgeDrop | (window, docks, pt) | return -1 | Checks on which edge of a window the drop action has taken place.
:param `window`: a :class:`Window` derived window;
:param `docks`: a list of :class:`AuiDockInfo` structures;
:param `pt`: a :class:`Point` object. | Checks on which edge of a window the drop action has taken place. | [
"Checks",
"on",
"which",
"edge",
"of",
"a",
"window",
"the",
"drop",
"action",
"has",
"taken",
"place",
"."
] | def CheckEdgeDrop(window, docks, pt):
"""
Checks on which edge of a window the drop action has taken place.
:param `window`: a :class:`Window` derived window;
:param `docks`: a list of :class:`AuiDockInfo` structures;
:param `pt`: a :class:`Point` object.
"""
screenPt = window.ClientToScreen(pt)
clientSize = window.GetClientSize()
frameRect = GetInternalFrameRect(window, docks)
if screenPt.y >= frameRect.GetTop() and screenPt.y < frameRect.GetBottom():
if pt.x < auiLayerInsertOffset and pt.x > auiLayerInsertOffset - auiLayerInsertPixels:
return wx.LEFT
if pt.x >= clientSize.x - auiLayerInsertOffset and \
pt.x < clientSize.x - auiLayerInsertOffset + auiLayerInsertPixels:
return wx.RIGHT
if screenPt.x >= frameRect.GetLeft() and screenPt.x < frameRect.GetRight():
if pt.y < auiLayerInsertOffset and pt.y > auiLayerInsertOffset - auiLayerInsertPixels:
return wx.TOP
if pt.y >= clientSize.y - auiLayerInsertOffset and \
pt.y < clientSize.y - auiLayerInsertOffset + auiLayerInsertPixels:
return wx.BOTTOM
return -1 | [
"def",
"CheckEdgeDrop",
"(",
"window",
",",
"docks",
",",
"pt",
")",
":",
"screenPt",
"=",
"window",
".",
"ClientToScreen",
"(",
"pt",
")",
"clientSize",
"=",
"window",
".",
"GetClientSize",
"(",
")",
"frameRect",
"=",
"GetInternalFrameRect",
"(",
"window",
",",
"docks",
")",
"if",
"screenPt",
".",
"y",
">=",
"frameRect",
".",
"GetTop",
"(",
")",
"and",
"screenPt",
".",
"y",
"<",
"frameRect",
".",
"GetBottom",
"(",
")",
":",
"if",
"pt",
".",
"x",
"<",
"auiLayerInsertOffset",
"and",
"pt",
".",
"x",
">",
"auiLayerInsertOffset",
"-",
"auiLayerInsertPixels",
":",
"return",
"wx",
".",
"LEFT",
"if",
"pt",
".",
"x",
">=",
"clientSize",
".",
"x",
"-",
"auiLayerInsertOffset",
"and",
"pt",
".",
"x",
"<",
"clientSize",
".",
"x",
"-",
"auiLayerInsertOffset",
"+",
"auiLayerInsertPixels",
":",
"return",
"wx",
".",
"RIGHT",
"if",
"screenPt",
".",
"x",
">=",
"frameRect",
".",
"GetLeft",
"(",
")",
"and",
"screenPt",
".",
"x",
"<",
"frameRect",
".",
"GetRight",
"(",
")",
":",
"if",
"pt",
".",
"y",
"<",
"auiLayerInsertOffset",
"and",
"pt",
".",
"y",
">",
"auiLayerInsertOffset",
"-",
"auiLayerInsertPixels",
":",
"return",
"wx",
".",
"TOP",
"if",
"pt",
".",
"y",
">=",
"clientSize",
".",
"y",
"-",
"auiLayerInsertOffset",
"and",
"pt",
".",
"y",
"<",
"clientSize",
".",
"y",
"-",
"auiLayerInsertOffset",
"+",
"auiLayerInsertPixels",
":",
"return",
"wx",
".",
"BOTTOM",
"return",
"-",
"1"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L3786-L3815 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/fitting_context.py | python | FittingContext.remove_fit_by_name | (fits_history: list, workspace_name: str) | Remove a Fit from the history when an ADS delete event happens on one of its output workspaces. | Remove a Fit from the history when an ADS delete event happens on one of its output workspaces. | [
"Remove",
"a",
"Fit",
"from",
"the",
"history",
"when",
"an",
"ADS",
"delete",
"event",
"happens",
"on",
"one",
"of",
"its",
"output",
"workspaces",
"."
] | def remove_fit_by_name(fits_history: list, workspace_name: str) -> None:
"""Remove a Fit from the history when an ADS delete event happens on one of its output workspaces."""
for fit in reversed(fits_history):
if workspace_name in fit.output_workspace_names() or workspace_name == fit.parameter_workspace_name:
fits_history.remove(fit) | [
"def",
"remove_fit_by_name",
"(",
"fits_history",
":",
"list",
",",
"workspace_name",
":",
"str",
")",
"->",
"None",
":",
"for",
"fit",
"in",
"reversed",
"(",
"fits_history",
")",
":",
"if",
"workspace_name",
"in",
"fit",
".",
"output_workspace_names",
"(",
")",
"or",
"workspace_name",
"==",
"fit",
".",
"parameter_workspace_name",
":",
"fits_history",
".",
"remove",
"(",
"fit",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/fitting_context.py#L372-L376 | ||
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/p4util/text.py | python | Table.format_values | (self, values) | return " ".join(map(str, values)) | Function to pad the width of Table object data cells. | Function to pad the width of Table object data cells. | [
"Function",
"to",
"pad",
"the",
"width",
"of",
"Table",
"object",
"data",
"cells",
"."
] | def format_values(self, values):
"""Function to pad the width of Table object data cells."""
str = lambda x: (('%%%d.%df' % (self.width, self.precision)) % x)
return " ".join(map(str, values)) | [
"def",
"format_values",
"(",
"self",
",",
"values",
")",
":",
"str",
"=",
"lambda",
"x",
":",
"(",
"(",
"'%%%d.%df'",
"%",
"(",
"self",
".",
"width",
",",
"self",
".",
"precision",
")",
")",
"%",
"x",
")",
"return",
"\" \"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"values",
")",
")"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/p4util/text.py#L68-L71 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/dataset/engine/datasets.py | python | Dataset.output_types | (self) | return self.saved_output_types | Get the types of output data.
Returns:
list, list of data types.
Examples:
>>> # dataset is an instance object of Dataset
>>> output_types = dataset.output_types() | Get the types of output data. | [
"Get",
"the",
"types",
"of",
"output",
"data",
"."
] | def output_types(self):
"""
Get the types of output data.
Returns:
list, list of data types.
Examples:
>>> # dataset is an instance object of Dataset
>>> output_types = dataset.output_types()
"""
if self.saved_output_types is None:
runtime_getter = self._init_tree_getters()
self.saved_output_shapes = runtime_getter[0].GetOutputShapes()
self.saved_output_types = runtime_getter[0].GetOutputTypes()
self.close_pool()
runtime_getter[2].notify_watchdog()
if self.dynamic_setting[0]:
self.saved_output_shapes, self.saved_min_shapes, self.saved_max_shapes = self._dynamic_output_shapes()
return self.saved_output_types | [
"def",
"output_types",
"(",
"self",
")",
":",
"if",
"self",
".",
"saved_output_types",
"is",
"None",
":",
"runtime_getter",
"=",
"self",
".",
"_init_tree_getters",
"(",
")",
"self",
".",
"saved_output_shapes",
"=",
"runtime_getter",
"[",
"0",
"]",
".",
"GetOutputShapes",
"(",
")",
"self",
".",
"saved_output_types",
"=",
"runtime_getter",
"[",
"0",
"]",
".",
"GetOutputTypes",
"(",
")",
"self",
".",
"close_pool",
"(",
")",
"runtime_getter",
"[",
"2",
"]",
".",
"notify_watchdog",
"(",
")",
"if",
"self",
".",
"dynamic_setting",
"[",
"0",
"]",
":",
"self",
".",
"saved_output_shapes",
",",
"self",
".",
"saved_min_shapes",
",",
"self",
".",
"saved_max_shapes",
"=",
"self",
".",
"_dynamic_output_shapes",
"(",
")",
"return",
"self",
".",
"saved_output_types"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/datasets.py#L1501-L1520 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/tseries/frequencies.py | python | get_offset | (name: str) | return _get_offset(name) | Return DateOffset object associated with rule name.
.. deprecated:: 1.0.0
Examples
--------
get_offset('EOM') --> BMonthEnd(1) | Return DateOffset object associated with rule name. | [
"Return",
"DateOffset",
"object",
"associated",
"with",
"rule",
"name",
"."
] | def get_offset(name: str) -> DateOffset:
"""
Return DateOffset object associated with rule name.
.. deprecated:: 1.0.0
Examples
--------
get_offset('EOM') --> BMonthEnd(1)
"""
warnings.warn(
"get_offset is deprecated and will be removed in a future version, "
"use to_offset instead",
FutureWarning,
stacklevel=2,
)
return _get_offset(name) | [
"def",
"get_offset",
"(",
"name",
":",
"str",
")",
"->",
"DateOffset",
":",
"warnings",
".",
"warn",
"(",
"\"get_offset is deprecated and will be removed in a future version, \"",
"\"use to_offset instead\"",
",",
"FutureWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"return",
"_get_offset",
"(",
"name",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/tseries/frequencies.py#L185-L201 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | StockGDI.instance | (*args, **kwargs) | return _gdi_.StockGDI_instance(*args, **kwargs) | instance() -> StockGDI | instance() -> StockGDI | [
"instance",
"()",
"-",
">",
"StockGDI"
] | def instance(*args, **kwargs):
"""instance() -> StockGDI"""
return _gdi_.StockGDI_instance(*args, **kwargs) | [
"def",
"instance",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"StockGDI_instance",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L6862-L6864 | |
goldeneye-source/ges-code | 2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d | thirdparty/protobuf-2.3.0/python/mox.py | python | MockAnything.__getattr__ | (self, method_name) | return self._CreateMockMethod(method_name) | Intercept method calls on this object.
A new MockMethod is returned that is aware of the MockAnything's
state (record or replay). The call will be recorded or replayed
by the MockMethod's __call__.
Args:
# method name: the name of the method being called.
method_name: str
Returns:
A new MockMethod aware of MockAnything's state (record or replay). | Intercept method calls on this object. | [
"Intercept",
"method",
"calls",
"on",
"this",
"object",
"."
] | def __getattr__(self, method_name):
"""Intercept method calls on this object.
A new MockMethod is returned that is aware of the MockAnything's
state (record or replay). The call will be recorded or replayed
by the MockMethod's __call__.
Args:
# method name: the name of the method being called.
method_name: str
Returns:
A new MockMethod aware of MockAnything's state (record or replay).
"""
return self._CreateMockMethod(method_name) | [
"def",
"__getattr__",
"(",
"self",
",",
"method_name",
")",
":",
"return",
"self",
".",
"_CreateMockMethod",
"(",
"method_name",
")"
] | https://github.com/goldeneye-source/ges-code/blob/2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d/thirdparty/protobuf-2.3.0/python/mox.py#L278-L293 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/ops/array_grad.py | python | _TileGrad | (op, grad) | return [input_grad, None] | Sum reduces grad along the tiled dimensions. | Sum reduces grad along the tiled dimensions. | [
"Sum",
"reduces",
"grad",
"along",
"the",
"tiled",
"dimensions",
"."
] | def _TileGrad(op, grad):
"""Sum reduces grad along the tiled dimensions."""
assert isinstance(grad, ops.Tensor)
input_shape = array_ops.shape(op.inputs[0])
# We interleave multiples and input_shape to get split_shape,
# reshape grad to split_shape, and reduce along all even
# dimensions (the tiled dimensions) to get the result
# with shape input_shape. For example
# input_shape = [20, 30, 40]
# multiples = [2, 3, 4]
# split_shape = [2, 20, 3, 30, 4, 40]
# axes = [0, 2, 4]
split_shape = array_ops.reshape(array_ops.transpose(
array_ops.pack([op.inputs[1], input_shape])), [-1])
axes = math_ops.range(0, array_ops.size(split_shape), 2)
input_grad = math_ops.reduce_sum(array_ops.reshape(grad, split_shape), axes)
# Fix shape inference
input_grad.set_shape(op.inputs[0].get_shape())
return [input_grad, None] | [
"def",
"_TileGrad",
"(",
"op",
",",
"grad",
")",
":",
"assert",
"isinstance",
"(",
"grad",
",",
"ops",
".",
"Tensor",
")",
"input_shape",
"=",
"array_ops",
".",
"shape",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
")",
"# We interleave multiples and input_shape to get split_shape,",
"# reshape grad to split_shape, and reduce along all even",
"# dimensions (the tiled dimensions) to get the result",
"# with shape input_shape. For example",
"# input_shape = [20, 30, 40]",
"# multiples = [2, 3, 4]",
"# split_shape = [2, 20, 3, 30, 4, 40]",
"# axes = [0, 2, 4]",
"split_shape",
"=",
"array_ops",
".",
"reshape",
"(",
"array_ops",
".",
"transpose",
"(",
"array_ops",
".",
"pack",
"(",
"[",
"op",
".",
"inputs",
"[",
"1",
"]",
",",
"input_shape",
"]",
")",
")",
",",
"[",
"-",
"1",
"]",
")",
"axes",
"=",
"math_ops",
".",
"range",
"(",
"0",
",",
"array_ops",
".",
"size",
"(",
"split_shape",
")",
",",
"2",
")",
"input_grad",
"=",
"math_ops",
".",
"reduce_sum",
"(",
"array_ops",
".",
"reshape",
"(",
"grad",
",",
"split_shape",
")",
",",
"axes",
")",
"# Fix shape inference",
"input_grad",
".",
"set_shape",
"(",
"op",
".",
"inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
")",
"return",
"[",
"input_grad",
",",
"None",
"]"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/array_grad.py#L339-L357 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/pubsub/core/publisherbase.py | python | PublisherBase.sendMessage | (self, topicName, *args, **kwargs) | Send a message for topic name with given data (args and kwargs).
This will be overridden by derived classes that implement
message-sending for different messaging protocols; not all
parameters may be accepted. | Send a message for topic name with given data (args and kwargs).
This will be overridden by derived classes that implement
message-sending for different messaging protocols; not all
parameters may be accepted. | [
"Send",
"a",
"message",
"for",
"topic",
"name",
"with",
"given",
"data",
"(",
"args",
"and",
"kwargs",
")",
".",
"This",
"will",
"be",
"overridden",
"by",
"derived",
"classes",
"that",
"implement",
"message",
"-",
"sending",
"for",
"different",
"messaging",
"protocols",
";",
"not",
"all",
"parameters",
"may",
"be",
"accepted",
"."
] | def sendMessage(self, topicName, *args, **kwargs):
"""Send a message for topic name with given data (args and kwargs).
This will be overridden by derived classes that implement
message-sending for different messaging protocols; not all
parameters may be accepted."""
raise NotImplementedError | [
"def",
"sendMessage",
"(",
"self",
",",
"topicName",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pubsub/core/publisherbase.py#L126-L131 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBStructuredData.Clear | (self) | return _lldb.SBStructuredData_Clear(self) | Clear(self) | Clear(self) | [
"Clear",
"(",
"self",
")"
] | def Clear(self):
"""Clear(self)"""
return _lldb.SBStructuredData_Clear(self) | [
"def",
"Clear",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBStructuredData_Clear",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L8054-L8056 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | compiler-rt/lib/sanitizer_common/scripts/cpplint.py | python | CheckRedundantOverrideOrFinal | (filename, clean_lines, linenum, error) | Check if line contains a redundant "override" or "final" virt-specifier.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Check if line contains a redundant "override" or "final" virt-specifier. | [
"Check",
"if",
"line",
"contains",
"a",
"redundant",
"override",
"or",
"final",
"virt",
"-",
"specifier",
"."
] | def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
"""Check if line contains a redundant "override" or "final" virt-specifier.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Look for closing parenthesis nearby. We need one to confirm where
# the declarator ends and where the virt-specifier starts to avoid
# false positives.
line = clean_lines.elided[linenum]
declarator_end = line.rfind(')')
if declarator_end >= 0:
fragment = line[declarator_end:]
else:
if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
fragment = line
else:
return
# Check that at most one of "override" or "final" is present, not both
if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
error(filename, linenum, 'readability/inheritance', 4,
('"override" is redundant since function is '
'already declared as "final"')) | [
"def",
"CheckRedundantOverrideOrFinal",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"# Look for closing parenthesis nearby. We need one to confirm where",
"# the declarator ends and where the virt-specifier starts to avoid",
"# false positives.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"declarator_end",
"=",
"line",
".",
"rfind",
"(",
"')'",
")",
"if",
"declarator_end",
">=",
"0",
":",
"fragment",
"=",
"line",
"[",
"declarator_end",
":",
"]",
"else",
":",
"if",
"linenum",
">",
"1",
"and",
"clean_lines",
".",
"elided",
"[",
"linenum",
"-",
"1",
"]",
".",
"rfind",
"(",
"')'",
")",
">=",
"0",
":",
"fragment",
"=",
"line",
"else",
":",
"return",
"# Check that at most one of \"override\" or \"final\" is present, not both",
"if",
"Search",
"(",
"r'\\boverride\\b'",
",",
"fragment",
")",
"and",
"Search",
"(",
"r'\\bfinal\\b'",
",",
"fragment",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/inheritance'",
",",
"4",
",",
"(",
"'\"override\" is redundant since function is '",
"'already declared as \"final\"'",
")",
")"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L5685-L5711 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Path/PathScripts/PathFeatureExtensions.py | python | Extension.getWire | (self) | getWire()... Public method to retrieve the extension area, pertaining to the feature
and sub element provided at class instantiation, as a closed wire. If no closed wire
is possible, a `None` value is returned. | getWire()... Public method to retrieve the extension area, pertaining to the feature
and sub element provided at class instantiation, as a closed wire. If no closed wire
is possible, a `None` value is returned. | [
"getWire",
"()",
"...",
"Public",
"method",
"to",
"retrieve",
"the",
"extension",
"area",
"pertaining",
"to",
"the",
"feature",
"and",
"sub",
"element",
"provided",
"at",
"class",
"instantiation",
"as",
"a",
"closed",
"wire",
".",
"If",
"no",
"closed",
"wire",
"is",
"possible",
"a",
"None",
"value",
"is",
"returned",
"."
] | def getWire(self):
"""getWire()... Public method to retrieve the extension area, pertaining to the feature
and sub element provided at class instantiation, as a closed wire. If no closed wire
is possible, a `None` value is returned."""
if self.sub[:6] == "Avoid_":
feature = self.obj.Shape.getElement(self.feature)
self.extFaces = [Part.Face(feature.Wires[0])]
return feature.Wires[0]
if self.sub[:7] == "Extend_":
rtn = self._getOutlineWire()
if rtn:
return rtn
else:
PathLog.debug("no Outline Wire")
return None
if self.sub[:10] == "Waterline_":
rtn = self._getWaterlineWire()
if rtn:
return rtn
else:
PathLog.debug("no Waterline Wire")
return None
else:
return self._getRegularWire() | [
"def",
"getWire",
"(",
"self",
")",
":",
"if",
"self",
".",
"sub",
"[",
":",
"6",
"]",
"==",
"\"Avoid_\"",
":",
"feature",
"=",
"self",
".",
"obj",
".",
"Shape",
".",
"getElement",
"(",
"self",
".",
"feature",
")",
"self",
".",
"extFaces",
"=",
"[",
"Part",
".",
"Face",
"(",
"feature",
".",
"Wires",
"[",
"0",
"]",
")",
"]",
"return",
"feature",
".",
"Wires",
"[",
"0",
"]",
"if",
"self",
".",
"sub",
"[",
":",
"7",
"]",
"==",
"\"Extend_\"",
":",
"rtn",
"=",
"self",
".",
"_getOutlineWire",
"(",
")",
"if",
"rtn",
":",
"return",
"rtn",
"else",
":",
"PathLog",
".",
"debug",
"(",
"\"no Outline Wire\"",
")",
"return",
"None",
"if",
"self",
".",
"sub",
"[",
":",
"10",
"]",
"==",
"\"Waterline_\"",
":",
"rtn",
"=",
"self",
".",
"_getWaterlineWire",
"(",
")",
"if",
"rtn",
":",
"return",
"rtn",
"else",
":",
"PathLog",
".",
"debug",
"(",
"\"no Waterline Wire\"",
")",
"return",
"None",
"else",
":",
"return",
"self",
".",
"_getRegularWire",
"(",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathFeatureExtensions.py#L279-L303 | ||
yyzybb537/libgo | 4af17b7c67643c4d54aa354dcc77963ea07847d0 | third_party/boost.context/tools/build/src/build/targets.py | python | TargetRegistry.main_target_sources | (self, sources, main_target_name, no_renaming=0) | return result | Return the list of sources to use, if main target rule is invoked
with 'sources'. If there are any objects in 'sources', they are treated
as main target instances, and the name of such targets are adjusted to
be '<name_of_this_target>__<name_of_source_target>'. Such renaming
is disabled is non-empty value is passed for 'no-renaming' parameter. | Return the list of sources to use, if main target rule is invoked
with 'sources'. If there are any objects in 'sources', they are treated
as main target instances, and the name of such targets are adjusted to
be '<name_of_this_target>__<name_of_source_target>'. Such renaming
is disabled is non-empty value is passed for 'no-renaming' parameter. | [
"Return",
"the",
"list",
"of",
"sources",
"to",
"use",
"if",
"main",
"target",
"rule",
"is",
"invoked",
"with",
"sources",
".",
"If",
"there",
"are",
"any",
"objects",
"in",
"sources",
"they",
"are",
"treated",
"as",
"main",
"target",
"instances",
"and",
"the",
"name",
"of",
"such",
"targets",
"are",
"adjusted",
"to",
"be",
"<name_of_this_target",
">",
"__<name_of_source_target",
">",
".",
"Such",
"renaming",
"is",
"disabled",
"is",
"non",
"-",
"empty",
"value",
"is",
"passed",
"for",
"no",
"-",
"renaming",
"parameter",
"."
] | def main_target_sources (self, sources, main_target_name, no_renaming=0):
"""Return the list of sources to use, if main target rule is invoked
with 'sources'. If there are any objects in 'sources', they are treated
as main target instances, and the name of such targets are adjusted to
be '<name_of_this_target>__<name_of_source_target>'. Such renaming
is disabled is non-empty value is passed for 'no-renaming' parameter."""
assert is_iterable_typed(sources, basestring)
assert isinstance(main_target_name, basestring)
assert isinstance(no_renaming, (int, bool))
result = []
for t in sources:
t = b2.util.jam_to_value_maybe(t)
if isinstance (t, AbstractTarget):
name = t.name ()
if not no_renaming:
name = main_target_name + '__' + name
t.rename (name)
# Inline targets are not built by default.
p = t.project()
p.mark_targets_as_explicit([name])
result.append(name)
else:
result.append (t)
return result | [
"def",
"main_target_sources",
"(",
"self",
",",
"sources",
",",
"main_target_name",
",",
"no_renaming",
"=",
"0",
")",
":",
"assert",
"is_iterable_typed",
"(",
"sources",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"main_target_name",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"no_renaming",
",",
"(",
"int",
",",
"bool",
")",
")",
"result",
"=",
"[",
"]",
"for",
"t",
"in",
"sources",
":",
"t",
"=",
"b2",
".",
"util",
".",
"jam_to_value_maybe",
"(",
"t",
")",
"if",
"isinstance",
"(",
"t",
",",
"AbstractTarget",
")",
":",
"name",
"=",
"t",
".",
"name",
"(",
")",
"if",
"not",
"no_renaming",
":",
"name",
"=",
"main_target_name",
"+",
"'__'",
"+",
"name",
"t",
".",
"rename",
"(",
"name",
")",
"# Inline targets are not built by default.",
"p",
"=",
"t",
".",
"project",
"(",
")",
"p",
".",
"mark_targets_as_explicit",
"(",
"[",
"name",
"]",
")",
"result",
".",
"append",
"(",
"name",
")",
"else",
":",
"result",
".",
"append",
"(",
"t",
")",
"return",
"result"
] | https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/targets.py#L114-L144 | |
dmlc/treelite | df56babb6a4a2d7c29d719c28ce53acfa7dbab3c | python/treelite/sklearn/rf_regressor.py | python | SKLRFRegressorMixin.process_leaf_node | (cls, treelite_tree, sklearn_tree, node_id, sklearn_model) | Process a test node with a given node ID | Process a test node with a given node ID | [
"Process",
"a",
"test",
"node",
"with",
"a",
"given",
"node",
"ID"
] | def process_leaf_node(cls, treelite_tree, sklearn_tree, node_id, sklearn_model):
# pylint: disable=W0613
"""Process a test node with a given node ID"""
# The `value` attribute stores the output for every leaf node.
leaf_value = sklearn_tree.value[node_id].squeeze()
# Initialize the leaf node with given node ID
treelite_tree[node_id].set_leaf_node(leaf_value, leaf_value_type='float64') | [
"def",
"process_leaf_node",
"(",
"cls",
",",
"treelite_tree",
",",
"sklearn_tree",
",",
"node_id",
",",
"sklearn_model",
")",
":",
"# pylint: disable=W0613",
"# The `value` attribute stores the output for every leaf node.",
"leaf_value",
"=",
"sklearn_tree",
".",
"value",
"[",
"node_id",
"]",
".",
"squeeze",
"(",
")",
"# Initialize the leaf node with given node ID",
"treelite_tree",
"[",
"node_id",
"]",
".",
"set_leaf_node",
"(",
"leaf_value",
",",
"leaf_value_type",
"=",
"'float64'",
")"
] | https://github.com/dmlc/treelite/blob/df56babb6a4a2d7c29d719c28ce53acfa7dbab3c/python/treelite/sklearn/rf_regressor.py#L28-L34 | ||
metashell/metashell | f4177e4854ea00c8dbc722cadab26ef413d798ea | 3rd/templight/compiler-rt/lib/asan/scripts/asan_symbolize.py | python | AsanSymbolizerPlugIn.filter_module_desc | (self, module_desc) | return module_desc | Given a ModuleDesc object (`module_desc`) return
a ModuleDesc suitable for symbolication.
Implementations should return `None` if symbolication of this binary
should be skipped. | Given a ModuleDesc object (`module_desc`) return
a ModuleDesc suitable for symbolication. | [
"Given",
"a",
"ModuleDesc",
"object",
"(",
"module_desc",
")",
"return",
"a",
"ModuleDesc",
"suitable",
"for",
"symbolication",
"."
] | def filter_module_desc(self, module_desc):
"""
Given a ModuleDesc object (`module_desc`) return
a ModuleDesc suitable for symbolication.
Implementations should return `None` if symbolication of this binary
should be skipped.
"""
return module_desc | [
"def",
"filter_module_desc",
"(",
"self",
",",
"module_desc",
")",
":",
"return",
"module_desc"
] | https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/compiler-rt/lib/asan/scripts/asan_symbolize.py#L700-L708 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/pytree.py | python | BasePattern.__new__ | (cls, *args, **kwds) | return object.__new__(cls) | Constructor that prevents BasePattern from being instantiated. | Constructor that prevents BasePattern from being instantiated. | [
"Constructor",
"that",
"prevents",
"BasePattern",
"from",
"being",
"instantiated",
"."
] | def __new__(cls, *args, **kwds):
"""Constructor that prevents BasePattern from being instantiated."""
assert cls is not BasePattern, "Cannot instantiate BasePattern"
return object.__new__(cls) | [
"def",
"__new__",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"assert",
"cls",
"is",
"not",
"BasePattern",
",",
"\"Cannot instantiate BasePattern\"",
"return",
"object",
".",
"__new__",
"(",
"cls",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/pytree.py#L435-L438 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros/roslib/src/roslib/launcher.py | python | _generate_python_path | (pkg, rospack) | return paths | Recursive subroutine for building dependency list and python path
:raises: :exc:`rospkg.ResourceNotFound` If an error occurs while attempting to load package or dependencies | Recursive subroutine for building dependency list and python path
:raises: :exc:`rospkg.ResourceNotFound` If an error occurs while attempting to load package or dependencies | [
"Recursive",
"subroutine",
"for",
"building",
"dependency",
"list",
"and",
"python",
"path",
":",
"raises",
":",
":",
"exc",
":",
"rospkg",
".",
"ResourceNotFound",
"If",
"an",
"error",
"occurs",
"while",
"attempting",
"to",
"load",
"package",
"or",
"dependencies"
] | def _generate_python_path(pkg, rospack):
"""
Recursive subroutine for building dependency list and python path
:raises: :exc:`rospkg.ResourceNotFound` If an error occurs while attempting to load package or dependencies
"""
if pkg in _bootstrapped:
return []
# short-circuit if this is a catkin-ized package
m = rospack.get_manifest(pkg)
if m.is_catkin:
_bootstrapped.append(pkg)
return []
packages = get_depends(pkg, rospack)
packages.append(pkg)
paths = []
try:
for p in packages:
m = rospack.get_manifest(p)
d = rospack.get_path(p)
_append_package_paths(m, paths, d)
_bootstrapped.append(p)
except:
if pkg in _bootstrapped:
_bootstrapped.remove(pkg)
raise
return paths | [
"def",
"_generate_python_path",
"(",
"pkg",
",",
"rospack",
")",
":",
"if",
"pkg",
"in",
"_bootstrapped",
":",
"return",
"[",
"]",
"# short-circuit if this is a catkin-ized package",
"m",
"=",
"rospack",
".",
"get_manifest",
"(",
"pkg",
")",
"if",
"m",
".",
"is_catkin",
":",
"_bootstrapped",
".",
"append",
"(",
"pkg",
")",
"return",
"[",
"]",
"packages",
"=",
"get_depends",
"(",
"pkg",
",",
"rospack",
")",
"packages",
".",
"append",
"(",
"pkg",
")",
"paths",
"=",
"[",
"]",
"try",
":",
"for",
"p",
"in",
"packages",
":",
"m",
"=",
"rospack",
".",
"get_manifest",
"(",
"p",
")",
"d",
"=",
"rospack",
".",
"get_path",
"(",
"p",
")",
"_append_package_paths",
"(",
"m",
",",
"paths",
",",
"d",
")",
"_bootstrapped",
".",
"append",
"(",
"p",
")",
"except",
":",
"if",
"pkg",
"in",
"_bootstrapped",
":",
"_bootstrapped",
".",
"remove",
"(",
"pkg",
")",
"raise",
"return",
"paths"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/roslib/src/roslib/launcher.py#L84-L112 | |
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | clang/bindings/python/clang/cindex.py | python | CursorKind.is_translation_unit | (self) | return conf.lib.clang_isTranslationUnit(self) | Test if this is a translation unit kind. | Test if this is a translation unit kind. | [
"Test",
"if",
"this",
"is",
"a",
"translation",
"unit",
"kind",
"."
] | def is_translation_unit(self):
"""Test if this is a translation unit kind."""
return conf.lib.clang_isTranslationUnit(self) | [
"def",
"is_translation_unit",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_isTranslationUnit",
"(",
"self",
")"
] | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/bindings/python/clang/cindex.py#L695-L697 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | remoting/tools/build/remoting_copy_locales.py | python | calc_output | (locale) | Determine the file that will be generated for the given locale. | Determine the file that will be generated for the given locale. | [
"Determine",
"the",
"file",
"that",
"will",
"be",
"generated",
"for",
"the",
"given",
"locale",
"."
] | def calc_output(locale):
"""Determine the file that will be generated for the given locale."""
#e.g. '<(INTERMEDIATE_DIR)/remoting_locales/da.pak',
if OS == 'mac' or OS == 'ios':
# For Cocoa to find the locale at runtime, it needs to use '_' instead
# of '-' (http://crbug.com/20441).
return os.path.join(INT_DIR, 'remoting', 'resources',
'%s.lproj' % locale.replace('-', '_'), 'locale.pak')
else:
return os.path.join(INT_DIR, 'remoting_locales', locale + '.pak') | [
"def",
"calc_output",
"(",
"locale",
")",
":",
"#e.g. '<(INTERMEDIATE_DIR)/remoting_locales/da.pak',",
"if",
"OS",
"==",
"'mac'",
"or",
"OS",
"==",
"'ios'",
":",
"# For Cocoa to find the locale at runtime, it needs to use '_' instead",
"# of '-' (http://crbug.com/20441).",
"return",
"os",
".",
"path",
".",
"join",
"(",
"INT_DIR",
",",
"'remoting'",
",",
"'resources'",
",",
"'%s.lproj'",
"%",
"locale",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
",",
"'locale.pak'",
")",
"else",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"INT_DIR",
",",
"'remoting_locales'",
",",
"locale",
"+",
"'.pak'",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/remoting/tools/build/remoting_copy_locales.py#L36-L45 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/generic.py | python | NDFrame.asof | (self, where, subset=None) | return data if is_list else data.iloc[-1] | Return the last row(s) without any NaNs before `where`.
The last row (for each element in `where`, if list) without any
NaN is taken.
In case of a :class:`~pandas.DataFrame`, the last row without NaN
considering only the subset of columns (if not `None`)
If there is no good value, NaN is returned for a Series or
a Series of NaN values for a DataFrame
Parameters
----------
where : date or array-like of dates
Date(s) before which the last row(s) are returned.
subset : str or array-like of str, default `None`
For DataFrame, if not `None`, only use these columns to
check for NaNs.
Returns
-------
scalar, Series, or DataFrame
The return can be:
* scalar : when `self` is a Series and `where` is a scalar
* Series: when `self` is a Series and `where` is an array-like,
or when `self` is a DataFrame and `where` is a scalar
* DataFrame : when `self` is a DataFrame and `where` is an
array-like
Return scalar, Series, or DataFrame.
See Also
--------
merge_asof : Perform an asof merge. Similar to left join.
Notes
-----
Dates are assumed to be sorted. Raises if this is not the case.
Examples
--------
A Series and a scalar `where`.
>>> s = pd.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40])
>>> s
10 1.0
20 2.0
30 NaN
40 4.0
dtype: float64
>>> s.asof(20)
2.0
For a sequence `where`, a Series is returned. The first value is
NaN, because the first element of `where` is before the first
index value.
>>> s.asof([5, 20])
5 NaN
20 2.0
dtype: float64
Missing values are not considered. The following is ``2.0``, not
NaN, even though NaN is at the index location for ``30``.
>>> s.asof(30)
2.0
Take all columns into consideration
>>> df = pd.DataFrame({'a': [10, 20, 30, 40, 50],
... 'b': [None, None, None, None, 500]},
... index=pd.DatetimeIndex(['2018-02-27 09:01:00',
... '2018-02-27 09:02:00',
... '2018-02-27 09:03:00',
... '2018-02-27 09:04:00',
... '2018-02-27 09:05:00']))
>>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',
... '2018-02-27 09:04:30']))
a b
2018-02-27 09:03:30 NaN NaN
2018-02-27 09:04:30 NaN NaN
Take a single column into consideration
>>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',
... '2018-02-27 09:04:30']),
... subset=['a'])
a b
2018-02-27 09:03:30 30.0 NaN
2018-02-27 09:04:30 40.0 NaN | Return the last row(s) without any NaNs before `where`. | [
"Return",
"the",
"last",
"row",
"(",
"s",
")",
"without",
"any",
"NaNs",
"before",
"where",
"."
] | def asof(self, where, subset=None):
"""
Return the last row(s) without any NaNs before `where`.
The last row (for each element in `where`, if list) without any
NaN is taken.
In case of a :class:`~pandas.DataFrame`, the last row without NaN
considering only the subset of columns (if not `None`)
If there is no good value, NaN is returned for a Series or
a Series of NaN values for a DataFrame
Parameters
----------
where : date or array-like of dates
Date(s) before which the last row(s) are returned.
subset : str or array-like of str, default `None`
For DataFrame, if not `None`, only use these columns to
check for NaNs.
Returns
-------
scalar, Series, or DataFrame
The return can be:
* scalar : when `self` is a Series and `where` is a scalar
* Series: when `self` is a Series and `where` is an array-like,
or when `self` is a DataFrame and `where` is a scalar
* DataFrame : when `self` is a DataFrame and `where` is an
array-like
Return scalar, Series, or DataFrame.
See Also
--------
merge_asof : Perform an asof merge. Similar to left join.
Notes
-----
Dates are assumed to be sorted. Raises if this is not the case.
Examples
--------
A Series and a scalar `where`.
>>> s = pd.Series([1, 2, np.nan, 4], index=[10, 20, 30, 40])
>>> s
10 1.0
20 2.0
30 NaN
40 4.0
dtype: float64
>>> s.asof(20)
2.0
For a sequence `where`, a Series is returned. The first value is
NaN, because the first element of `where` is before the first
index value.
>>> s.asof([5, 20])
5 NaN
20 2.0
dtype: float64
Missing values are not considered. The following is ``2.0``, not
NaN, even though NaN is at the index location for ``30``.
>>> s.asof(30)
2.0
Take all columns into consideration
>>> df = pd.DataFrame({'a': [10, 20, 30, 40, 50],
... 'b': [None, None, None, None, 500]},
... index=pd.DatetimeIndex(['2018-02-27 09:01:00',
... '2018-02-27 09:02:00',
... '2018-02-27 09:03:00',
... '2018-02-27 09:04:00',
... '2018-02-27 09:05:00']))
>>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',
... '2018-02-27 09:04:30']))
a b
2018-02-27 09:03:30 NaN NaN
2018-02-27 09:04:30 NaN NaN
Take a single column into consideration
>>> df.asof(pd.DatetimeIndex(['2018-02-27 09:03:30',
... '2018-02-27 09:04:30']),
... subset=['a'])
a b
2018-02-27 09:03:30 30.0 NaN
2018-02-27 09:04:30 40.0 NaN
"""
if isinstance(where, str):
where = Timestamp(where)
if not self.index.is_monotonic:
raise ValueError("asof requires a sorted index")
is_series = isinstance(self, ABCSeries)
if is_series:
if subset is not None:
raise ValueError("subset is not valid for Series")
else:
if subset is None:
subset = self.columns
if not is_list_like(subset):
subset = [subset]
is_list = is_list_like(where)
if not is_list:
start = self.index[0]
if isinstance(self.index, PeriodIndex):
where = Period(where, freq=self.index.freq)
if where < start:
if not is_series:
return self._constructor_sliced(
index=self.columns, name=where, dtype=np.float64
)
return np.nan
# It's always much faster to use a *while* loop here for
# Series than pre-computing all the NAs. However a
# *while* loop is extremely expensive for DataFrame
# so we later pre-compute all the NAs and use the same
# code path whether *where* is a scalar or list.
# See PR: https://github.com/pandas-dev/pandas/pull/14476
if is_series:
loc = self.index.searchsorted(where, side="right")
if loc > 0:
loc -= 1
values = self._values
while loc > 0 and isna(values[loc]):
loc -= 1
return values[loc]
if not isinstance(where, Index):
where = Index(where) if is_list else Index([where])
nulls = self.isna() if is_series else self[subset].isna().any(1)
if nulls.all():
if is_series:
self = cast("Series", self)
return self._constructor(np.nan, index=where, name=self.name)
elif is_list:
self = cast("DataFrame", self)
return self._constructor(np.nan, index=where, columns=self.columns)
else:
self = cast("DataFrame", self)
return self._constructor_sliced(
np.nan, index=self.columns, name=where[0]
)
locs = self.index.asof_locs(where, ~(nulls._values))
# mask the missing
missing = locs == -1
data = self.take(locs)
data.index = where
data.loc[missing] = np.nan
return data if is_list else data.iloc[-1] | [
"def",
"asof",
"(",
"self",
",",
"where",
",",
"subset",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"where",
",",
"str",
")",
":",
"where",
"=",
"Timestamp",
"(",
"where",
")",
"if",
"not",
"self",
".",
"index",
".",
"is_monotonic",
":",
"raise",
"ValueError",
"(",
"\"asof requires a sorted index\"",
")",
"is_series",
"=",
"isinstance",
"(",
"self",
",",
"ABCSeries",
")",
"if",
"is_series",
":",
"if",
"subset",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"subset is not valid for Series\"",
")",
"else",
":",
"if",
"subset",
"is",
"None",
":",
"subset",
"=",
"self",
".",
"columns",
"if",
"not",
"is_list_like",
"(",
"subset",
")",
":",
"subset",
"=",
"[",
"subset",
"]",
"is_list",
"=",
"is_list_like",
"(",
"where",
")",
"if",
"not",
"is_list",
":",
"start",
"=",
"self",
".",
"index",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"self",
".",
"index",
",",
"PeriodIndex",
")",
":",
"where",
"=",
"Period",
"(",
"where",
",",
"freq",
"=",
"self",
".",
"index",
".",
"freq",
")",
"if",
"where",
"<",
"start",
":",
"if",
"not",
"is_series",
":",
"return",
"self",
".",
"_constructor_sliced",
"(",
"index",
"=",
"self",
".",
"columns",
",",
"name",
"=",
"where",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"return",
"np",
".",
"nan",
"# It's always much faster to use a *while* loop here for",
"# Series than pre-computing all the NAs. However a",
"# *while* loop is extremely expensive for DataFrame",
"# so we later pre-compute all the NAs and use the same",
"# code path whether *where* is a scalar or list.",
"# See PR: https://github.com/pandas-dev/pandas/pull/14476",
"if",
"is_series",
":",
"loc",
"=",
"self",
".",
"index",
".",
"searchsorted",
"(",
"where",
",",
"side",
"=",
"\"right\"",
")",
"if",
"loc",
">",
"0",
":",
"loc",
"-=",
"1",
"values",
"=",
"self",
".",
"_values",
"while",
"loc",
">",
"0",
"and",
"isna",
"(",
"values",
"[",
"loc",
"]",
")",
":",
"loc",
"-=",
"1",
"return",
"values",
"[",
"loc",
"]",
"if",
"not",
"isinstance",
"(",
"where",
",",
"Index",
")",
":",
"where",
"=",
"Index",
"(",
"where",
")",
"if",
"is_list",
"else",
"Index",
"(",
"[",
"where",
"]",
")",
"nulls",
"=",
"self",
".",
"isna",
"(",
")",
"if",
"is_series",
"else",
"self",
"[",
"subset",
"]",
".",
"isna",
"(",
")",
".",
"any",
"(",
"1",
")",
"if",
"nulls",
".",
"all",
"(",
")",
":",
"if",
"is_series",
":",
"self",
"=",
"cast",
"(",
"\"Series\"",
",",
"self",
")",
"return",
"self",
".",
"_constructor",
"(",
"np",
".",
"nan",
",",
"index",
"=",
"where",
",",
"name",
"=",
"self",
".",
"name",
")",
"elif",
"is_list",
":",
"self",
"=",
"cast",
"(",
"\"DataFrame\"",
",",
"self",
")",
"return",
"self",
".",
"_constructor",
"(",
"np",
".",
"nan",
",",
"index",
"=",
"where",
",",
"columns",
"=",
"self",
".",
"columns",
")",
"else",
":",
"self",
"=",
"cast",
"(",
"\"DataFrame\"",
",",
"self",
")",
"return",
"self",
".",
"_constructor_sliced",
"(",
"np",
".",
"nan",
",",
"index",
"=",
"self",
".",
"columns",
",",
"name",
"=",
"where",
"[",
"0",
"]",
")",
"locs",
"=",
"self",
".",
"index",
".",
"asof_locs",
"(",
"where",
",",
"~",
"(",
"nulls",
".",
"_values",
")",
")",
"# mask the missing",
"missing",
"=",
"locs",
"==",
"-",
"1",
"data",
"=",
"self",
".",
"take",
"(",
"locs",
")",
"data",
".",
"index",
"=",
"where",
"data",
".",
"loc",
"[",
"missing",
"]",
"=",
"np",
".",
"nan",
"return",
"data",
"if",
"is_list",
"else",
"data",
".",
"iloc",
"[",
"-",
"1",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/generic.py#L6923-L7088 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/timeseries/python/timeseries/model.py | python | SequentialTimeSeriesModel.predict | (self, features) | return predictions | Calls self._prediction_step in a loop. See TimeSeriesModel.predict. | Calls self._prediction_step in a loop. See TimeSeriesModel.predict. | [
"Calls",
"self",
".",
"_prediction_step",
"in",
"a",
"loop",
".",
"See",
"TimeSeriesModel",
".",
"predict",
"."
] | def predict(self, features):
"""Calls self._prediction_step in a loop. See TimeSeriesModel.predict."""
predict_times = ops.convert_to_tensor(features[PredictionFeatures.TIMES],
dtypes.int64)
start_state = features[PredictionFeatures.STATE_TUPLE]
exogenous_regressors = self._process_exogenous_features(
times=predict_times,
features={
key: value
for key, value in features.items()
if key not in
[PredictionFeatures.TIMES, PredictionFeatures.STATE_TUPLE]
})
def _call_prediction_step(step_number, current_times, state):
state = self._apply_exogenous_update(
step_number=step_number, current_times=current_times, state=state,
raw_features=features,
embedded_exogenous_regressors=exogenous_regressors)
state, outputs = self._prediction_step(
current_times=current_times, state=state)
return state, outputs
_, predictions = self._state_update_loop(
times=predict_times, state=start_state,
state_update_fn=_call_prediction_step,
outputs=self._predict_output_names)
return predictions | [
"def",
"predict",
"(",
"self",
",",
"features",
")",
":",
"predict_times",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"features",
"[",
"PredictionFeatures",
".",
"TIMES",
"]",
",",
"dtypes",
".",
"int64",
")",
"start_state",
"=",
"features",
"[",
"PredictionFeatures",
".",
"STATE_TUPLE",
"]",
"exogenous_regressors",
"=",
"self",
".",
"_process_exogenous_features",
"(",
"times",
"=",
"predict_times",
",",
"features",
"=",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"features",
".",
"items",
"(",
")",
"if",
"key",
"not",
"in",
"[",
"PredictionFeatures",
".",
"TIMES",
",",
"PredictionFeatures",
".",
"STATE_TUPLE",
"]",
"}",
")",
"def",
"_call_prediction_step",
"(",
"step_number",
",",
"current_times",
",",
"state",
")",
":",
"state",
"=",
"self",
".",
"_apply_exogenous_update",
"(",
"step_number",
"=",
"step_number",
",",
"current_times",
"=",
"current_times",
",",
"state",
"=",
"state",
",",
"raw_features",
"=",
"features",
",",
"embedded_exogenous_regressors",
"=",
"exogenous_regressors",
")",
"state",
",",
"outputs",
"=",
"self",
".",
"_prediction_step",
"(",
"current_times",
"=",
"current_times",
",",
"state",
"=",
"state",
")",
"return",
"state",
",",
"outputs",
"_",
",",
"predictions",
"=",
"self",
".",
"_state_update_loop",
"(",
"times",
"=",
"predict_times",
",",
"state",
"=",
"start_state",
",",
"state_update_fn",
"=",
"_call_prediction_step",
",",
"outputs",
"=",
"self",
".",
"_predict_output_names",
")",
"return",
"predictions"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/timeseries/python/timeseries/model.py#L562-L587 | |
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/ceph-volume/ceph_volume/util/system.py | python | mkdir_p | (path, chown=True) | A `mkdir -p` that defaults to chown the path to the ceph user | A `mkdir -p` that defaults to chown the path to the ceph user | [
"A",
"mkdir",
"-",
"p",
"that",
"defaults",
"to",
"chown",
"the",
"path",
"to",
"the",
"ceph",
"user"
] | def mkdir_p(path, chown=True):
"""
A `mkdir -p` that defaults to chown the path to the ceph user
"""
try:
os.mkdir(path)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
if chown:
uid, gid = get_ceph_user_ids()
os.chown(path, uid, gid) | [
"def",
"mkdir_p",
"(",
"path",
",",
"chown",
"=",
"True",
")",
":",
"try",
":",
"os",
".",
"mkdir",
"(",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
":",
"pass",
"else",
":",
"raise",
"if",
"chown",
":",
"uid",
",",
"gid",
"=",
"get_ceph_user_ids",
"(",
")",
"os",
".",
"chown",
"(",
"path",
",",
"uid",
",",
"gid",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/ceph-volume/ceph_volume/util/system.py#L131-L144 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/resmokelib/logging/formatters.py | python | TimestampFormatter.formatTime | (self, record, datefmt=None) | return "%s.%03dZ" % (formatted_time, record.msecs) | Return formatted time. | Return formatted time. | [
"Return",
"formatted",
"time",
"."
] | def formatTime(self, record, datefmt=None):
"""Return formatted time."""
converted_time = self.converter(record.created)
if datefmt is not None:
return time.strftime(datefmt, converted_time)
formatted_time = time.strftime("%H:%M:%S", converted_time)
return "%s.%03dZ" % (formatted_time, record.msecs) | [
"def",
"formatTime",
"(",
"self",
",",
"record",
",",
"datefmt",
"=",
"None",
")",
":",
"converted_time",
"=",
"self",
".",
"converter",
"(",
"record",
".",
"created",
")",
"if",
"datefmt",
"is",
"not",
"None",
":",
"return",
"time",
".",
"strftime",
"(",
"datefmt",
",",
"converted_time",
")",
"formatted_time",
"=",
"time",
".",
"strftime",
"(",
"\"%H:%M:%S\"",
",",
"converted_time",
")",
"return",
"\"%s.%03dZ\"",
"%",
"(",
"formatted_time",
",",
"record",
".",
"msecs",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/logging/formatters.py#L13-L21 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Diffraction/isis_powder/routines/common.py | python | load_current_normalised_ws_list | (run_number_string, instrument, input_batching=None) | return normalised_ws_list | Loads a workspace using Mantid and then performs current normalisation on it. Additionally it will either
load a range of runs individually or summed depending on the user specified behaviour queried from the instrument.
This can behaviour can be overridden by using the optional parameter input_batching. For
example if the caller must have the workspaces summed regardless of user selection. The input_batching must be
from common_enums.InputBatchingEnum
:param run_number_string: The run number string to turn into a list of run(s) to load
:param instrument: The instrument to query for the behaviour regarding summing workspaces
:param input_batching: (Optional) Used to override the user specified choice where a specific batching is required
:return: The normalised workspace(s) as a list. | Loads a workspace using Mantid and then performs current normalisation on it. Additionally it will either
load a range of runs individually or summed depending on the user specified behaviour queried from the instrument.
This can behaviour can be overridden by using the optional parameter input_batching. For
example if the caller must have the workspaces summed regardless of user selection. The input_batching must be
from common_enums.InputBatchingEnum
:param run_number_string: The run number string to turn into a list of run(s) to load
:param instrument: The instrument to query for the behaviour regarding summing workspaces
:param input_batching: (Optional) Used to override the user specified choice where a specific batching is required
:return: The normalised workspace(s) as a list. | [
"Loads",
"a",
"workspace",
"using",
"Mantid",
"and",
"then",
"performs",
"current",
"normalisation",
"on",
"it",
".",
"Additionally",
"it",
"will",
"either",
"load",
"a",
"range",
"of",
"runs",
"individually",
"or",
"summed",
"depending",
"on",
"the",
"user",
"specified",
"behaviour",
"queried",
"from",
"the",
"instrument",
".",
"This",
"can",
"behaviour",
"can",
"be",
"overridden",
"by",
"using",
"the",
"optional",
"parameter",
"input_batching",
".",
"For",
"example",
"if",
"the",
"caller",
"must",
"have",
"the",
"workspaces",
"summed",
"regardless",
"of",
"user",
"selection",
".",
"The",
"input_batching",
"must",
"be",
"from",
"common_enums",
".",
"InputBatchingEnum",
":",
"param",
"run_number_string",
":",
"The",
"run",
"number",
"string",
"to",
"turn",
"into",
"a",
"list",
"of",
"run",
"(",
"s",
")",
"to",
"load",
":",
"param",
"instrument",
":",
"The",
"instrument",
"to",
"query",
"for",
"the",
"behaviour",
"regarding",
"summing",
"workspaces",
":",
"param",
"input_batching",
":",
"(",
"Optional",
")",
"Used",
"to",
"override",
"the",
"user",
"specified",
"choice",
"where",
"a",
"specific",
"batching",
"is",
"required",
":",
"return",
":",
"The",
"normalised",
"workspace",
"(",
"s",
")",
"as",
"a",
"list",
"."
] | def load_current_normalised_ws_list(run_number_string, instrument, input_batching=None):
"""
Loads a workspace using Mantid and then performs current normalisation on it. Additionally it will either
load a range of runs individually or summed depending on the user specified behaviour queried from the instrument.
This can behaviour can be overridden by using the optional parameter input_batching. For
example if the caller must have the workspaces summed regardless of user selection. The input_batching must be
from common_enums.InputBatchingEnum
:param run_number_string: The run number string to turn into a list of run(s) to load
:param instrument: The instrument to query for the behaviour regarding summing workspaces
:param input_batching: (Optional) Used to override the user specified choice where a specific batching is required
:return: The normalised workspace(s) as a list.
"""
if not input_batching:
input_batching = instrument._get_input_batching_mode()
run_information = instrument._get_run_details(run_number_string=run_number_string)
file_ext = run_information.file_extension
raw_ws_list = _load_raw_files(run_number_string=run_number_string, instrument=instrument, file_ext=file_ext)
if input_batching == INPUT_BATCHING.Summed and len(raw_ws_list) > 1:
summed_ws = _sum_ws_range(ws_list=raw_ws_list)
remove_intermediate_workspace(raw_ws_list)
raw_ws_list = [summed_ws]
instrument.mask_prompt_pulses_if_necessary(raw_ws_list)
normalised_ws_list = _normalise_workspaces(ws_list=raw_ws_list, run_details=run_information,
instrument=instrument)
return normalised_ws_list | [
"def",
"load_current_normalised_ws_list",
"(",
"run_number_string",
",",
"instrument",
",",
"input_batching",
"=",
"None",
")",
":",
"if",
"not",
"input_batching",
":",
"input_batching",
"=",
"instrument",
".",
"_get_input_batching_mode",
"(",
")",
"run_information",
"=",
"instrument",
".",
"_get_run_details",
"(",
"run_number_string",
"=",
"run_number_string",
")",
"file_ext",
"=",
"run_information",
".",
"file_extension",
"raw_ws_list",
"=",
"_load_raw_files",
"(",
"run_number_string",
"=",
"run_number_string",
",",
"instrument",
"=",
"instrument",
",",
"file_ext",
"=",
"file_ext",
")",
"if",
"input_batching",
"==",
"INPUT_BATCHING",
".",
"Summed",
"and",
"len",
"(",
"raw_ws_list",
")",
">",
"1",
":",
"summed_ws",
"=",
"_sum_ws_range",
"(",
"ws_list",
"=",
"raw_ws_list",
")",
"remove_intermediate_workspace",
"(",
"raw_ws_list",
")",
"raw_ws_list",
"=",
"[",
"summed_ws",
"]",
"instrument",
".",
"mask_prompt_pulses_if_necessary",
"(",
"raw_ws_list",
")",
"normalised_ws_list",
"=",
"_normalise_workspaces",
"(",
"ws_list",
"=",
"raw_ws_list",
",",
"run_details",
"=",
"run_information",
",",
"instrument",
"=",
"instrument",
")",
"return",
"normalised_ws_list"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Diffraction/isis_powder/routines/common.py#L335-L364 | |
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/db_manager/db_plugins/oracle/connector.py | python | OracleDBConnector.getTableMainGeomType | (self, table, geomCol) | return wkbType, srid | Return the best wkbType for a table by requesting geometry
column. | Return the best wkbType for a table by requesting geometry
column. | [
"Return",
"the",
"best",
"wkbType",
"for",
"a",
"table",
"by",
"requesting",
"geometry",
"column",
"."
] | def getTableMainGeomType(self, table, geomCol):
"""Return the best wkbType for a table by requesting geometry
column.
"""
geomTypes, srids = self.getTableGeomTypes(table, geomCol)
# Make the decision:
wkbType = QgsWkbTypes.Unknown
srid = -1
order = [QgsWkbTypes.MultiPolygon25D, QgsWkbTypes.Polygon25D,
QgsWkbTypes.MultiPolygon, QgsWkbTypes.Polygon,
QgsWkbTypes.MultiLineString25D, QgsWkbTypes.LineString25D,
QgsWkbTypes.MultiLineString, QgsWkbTypes.LineString,
QgsWkbTypes.MultiPoint25D, QgsWkbTypes.Point25D,
QgsWkbTypes.MultiPoint, QgsWkbTypes.Point]
for geomType in order:
if geomType in geomTypes:
wkbType = geomType
srid = srids[geomTypes.index(geomType)]
break
return wkbType, srid | [
"def",
"getTableMainGeomType",
"(",
"self",
",",
"table",
",",
"geomCol",
")",
":",
"geomTypes",
",",
"srids",
"=",
"self",
".",
"getTableGeomTypes",
"(",
"table",
",",
"geomCol",
")",
"# Make the decision:",
"wkbType",
"=",
"QgsWkbTypes",
".",
"Unknown",
"srid",
"=",
"-",
"1",
"order",
"=",
"[",
"QgsWkbTypes",
".",
"MultiPolygon25D",
",",
"QgsWkbTypes",
".",
"Polygon25D",
",",
"QgsWkbTypes",
".",
"MultiPolygon",
",",
"QgsWkbTypes",
".",
"Polygon",
",",
"QgsWkbTypes",
".",
"MultiLineString25D",
",",
"QgsWkbTypes",
".",
"LineString25D",
",",
"QgsWkbTypes",
".",
"MultiLineString",
",",
"QgsWkbTypes",
".",
"LineString",
",",
"QgsWkbTypes",
".",
"MultiPoint25D",
",",
"QgsWkbTypes",
".",
"Point25D",
",",
"QgsWkbTypes",
".",
"MultiPoint",
",",
"QgsWkbTypes",
".",
"Point",
"]",
"for",
"geomType",
"in",
"order",
":",
"if",
"geomType",
"in",
"geomTypes",
":",
"wkbType",
"=",
"geomType",
"srid",
"=",
"srids",
"[",
"geomTypes",
".",
"index",
"(",
"geomType",
")",
"]",
"break",
"return",
"wkbType",
",",
"srid"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/db_plugins/oracle/connector.py#L797-L819 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_op_impl/akg/ascend/reduce_max.py | python | _reduce_max_akg | () | return | ReduceMax Akg register | ReduceMax Akg register | [
"ReduceMax",
"Akg",
"register"
] | def _reduce_max_akg():
"""ReduceMax Akg register"""
return | [
"def",
"_reduce_max_akg",
"(",
")",
":",
"return"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/akg/ascend/reduce_max.py#L30-L32 | |
UDST/pandana | 3e3d35ca2d57428714b89ed8fc7020bc55067e1d | pandana/network.py | python | reserve_num_graphs | (num) | return None | This function was previously used to reserve memory space for multiple
graphs. It is no longer needed in Pandana 0.4+, and will be removed in a
future version.
Parameters
----------
num : int
Number of graphs to be reserved in memory | This function was previously used to reserve memory space for multiple
graphs. It is no longer needed in Pandana 0.4+, and will be removed in a
future version. | [
"This",
"function",
"was",
"previously",
"used",
"to",
"reserve",
"memory",
"space",
"for",
"multiple",
"graphs",
".",
"It",
"is",
"no",
"longer",
"needed",
"in",
"Pandana",
"0",
".",
"4",
"+",
"and",
"will",
"be",
"removed",
"in",
"a",
"future",
"version",
"."
] | def reserve_num_graphs(num):
"""
This function was previously used to reserve memory space for multiple
graphs. It is no longer needed in Pandana 0.4+, and will be removed in a
future version.
Parameters
----------
num : int
Number of graphs to be reserved in memory
"""
warnings.warn(
"Function reserve_num_graphs() is no longer needed in Pandana 0.4+\
and will be removed in a future version",
DeprecationWarning
)
return None | [
"def",
"reserve_num_graphs",
"(",
"num",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Function reserve_num_graphs() is no longer needed in Pandana 0.4+\\\n and will be removed in a future version\"",
",",
"DeprecationWarning",
")",
"return",
"None"
] | https://github.com/UDST/pandana/blob/3e3d35ca2d57428714b89ed8fc7020bc55067e1d/pandana/network.py#L12-L29 | |
hakuna-m/wubiuefi | caec1af0a09c78fd5a345180ada1fe45e0c63493 | src/pypack/modulegraph/pkg_resources.py | python | file_ns_handler | (importer, path_item, packageName, module) | Compute an ns-package subpath for a filesystem or zipfile importer | Compute an ns-package subpath for a filesystem or zipfile importer | [
"Compute",
"an",
"ns",
"-",
"package",
"subpath",
"for",
"a",
"filesystem",
"or",
"zipfile",
"importer"
] | def file_ns_handler(importer, path_item, packageName, module):
"""Compute an ns-package subpath for a filesystem or zipfile importer"""
subpath = os.path.join(path_item, packageName.split('.')[-1])
normalized = _normalize_cached(subpath)
for item in module.__path__:
if _normalize_cached(item)==normalized:
break
else:
# Only return the path if it's not already there
return subpath | [
"def",
"file_ns_handler",
"(",
"importer",
",",
"path_item",
",",
"packageName",
",",
"module",
")",
":",
"subpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"packageName",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
")",
"normalized",
"=",
"_normalize_cached",
"(",
"subpath",
")",
"for",
"item",
"in",
"module",
".",
"__path__",
":",
"if",
"_normalize_cached",
"(",
"item",
")",
"==",
"normalized",
":",
"break",
"else",
":",
"# Only return the path if it's not already there",
"return",
"subpath"
] | https://github.com/hakuna-m/wubiuefi/blob/caec1af0a09c78fd5a345180ada1fe45e0c63493/src/pypack/modulegraph/pkg_resources.py#L1536-L1546 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_misc.py | python | DateTime.GetHour | (*args, **kwargs) | return _misc_.DateTime_GetHour(*args, **kwargs) | GetHour(self, wxDateTime::TimeZone tz=LOCAL_TZ) -> int | GetHour(self, wxDateTime::TimeZone tz=LOCAL_TZ) -> int | [
"GetHour",
"(",
"self",
"wxDateTime",
"::",
"TimeZone",
"tz",
"=",
"LOCAL_TZ",
")",
"-",
">",
"int"
] | def GetHour(*args, **kwargs):
"""GetHour(self, wxDateTime::TimeZone tz=LOCAL_TZ) -> int"""
return _misc_.DateTime_GetHour(*args, **kwargs) | [
"def",
"GetHour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_GetHour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3993-L3995 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/start_try_job.py | python | StartBisectHandler.post | (self) | Performs one of several bisect-related actions depending on parameters.
The only required parameter is "step", which indicates what to do.
This end-point should always output valid JSON with different contents
depending on the value of "step". | Performs one of several bisect-related actions depending on parameters. | [
"Performs",
"one",
"of",
"several",
"bisect",
"-",
"related",
"actions",
"depending",
"on",
"parameters",
"."
] | def post(self):
"""Performs one of several bisect-related actions depending on parameters.
The only required parameter is "step", which indicates what to do.
This end-point should always output valid JSON with different contents
depending on the value of "step".
"""
user = users.get_current_user()
if not utils.IsValidSheriffUser():
message = 'User "%s" not authorized.' % user
self.response.out.write(json.dumps({'error': message}))
return
step = self.request.get('step')
if step == 'prefill-info':
result = _PrefillInfo(self.request.get('test_path'))
elif step == 'perform-bisect':
result = self._PerformBisectStep(user)
elif step == 'perform-perf-try':
result = self._PerformPerfTryStep(user)
else:
result = {'error': 'Invalid parameters.'}
self.response.write(json.dumps(result)) | [
"def",
"post",
"(",
"self",
")",
":",
"user",
"=",
"users",
".",
"get_current_user",
"(",
")",
"if",
"not",
"utils",
".",
"IsValidSheriffUser",
"(",
")",
":",
"message",
"=",
"'User \"%s\" not authorized.'",
"%",
"user",
"self",
".",
"response",
".",
"out",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"{",
"'error'",
":",
"message",
"}",
")",
")",
"return",
"step",
"=",
"self",
".",
"request",
".",
"get",
"(",
"'step'",
")",
"if",
"step",
"==",
"'prefill-info'",
":",
"result",
"=",
"_PrefillInfo",
"(",
"self",
".",
"request",
".",
"get",
"(",
"'test_path'",
")",
")",
"elif",
"step",
"==",
"'perform-bisect'",
":",
"result",
"=",
"self",
".",
"_PerformBisectStep",
"(",
"user",
")",
"elif",
"step",
"==",
"'perform-perf-try'",
":",
"result",
"=",
"self",
".",
"_PerformPerfTryStep",
"(",
"user",
")",
"else",
":",
"result",
"=",
"{",
"'error'",
":",
"'Invalid parameters.'",
"}",
"self",
".",
"response",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"result",
")",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/start_try_job.py#L98-L123 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py | python | PlotValMinMaxTrkC.UpdateMinMaxToUse | (self) | assumes we have obtained this callback (ThisCb) mins and maxes; uses\n Initial settings and locks to determine what mins and maxes are\n now in force | assumes we have obtained this callback (ThisCb) mins and maxes; uses\n Initial settings and locks to determine what mins and maxes are\n now in force | [
"assumes",
"we",
"have",
"obtained",
"this",
"callback",
"(",
"ThisCb",
")",
"mins",
"and",
"maxes",
";",
"uses",
"\\",
"n",
"Initial",
"settings",
"and",
"locks",
"to",
"determine",
"what",
"mins",
"and",
"maxes",
"are",
"\\",
"n",
"now",
"in",
"force"
] | def UpdateMinMaxToUse(self):
"assumes we have obtained this callback (ThisCb) mins and maxes; uses\n Initial settings and locks to determine what mins and maxes are\n now in force"
if self.mUseCumulativeRange:
localMin = self.mAllMin
else:
localMin = self.mThisCbMin
if self.mUseHighestBot:
if localMin > self.mHighestBot:
localMin = self.mHighestBot
if self.mUseLowestBot:
if localMin < self.mLowestBot:
localMin = self.mLowestBot
if self.mUseCumulativeRange:
localMax = self.mAllMax
else:
localMax = self.mThisCbMax
if self.mUseHighestTop:
if localMax > self.mHighestTop:
localMax = self.mHighestTop
if self.mUseLowestTop:
if localMax < self.mLowestTop:
localMax = self.mLowestTop
if localMin > localMax:
if self.mUseLowestBot:
localMax = localMin
if self.mUseHighestTop:
localMin = localMax
if localMin > localMax:
if PhactoriDbg():
myDebugPrint3("UpdateMinMaxToUse: weird case with min/max\n")
localMin = localMax
self.mMinToUse = localMin
self.mMaxToUse = localMax | [
"def",
"UpdateMinMaxToUse",
"(",
"self",
")",
":",
"if",
"self",
".",
"mUseCumulativeRange",
":",
"localMin",
"=",
"self",
".",
"mAllMin",
"else",
":",
"localMin",
"=",
"self",
".",
"mThisCbMin",
"if",
"self",
".",
"mUseHighestBot",
":",
"if",
"localMin",
">",
"self",
".",
"mHighestBot",
":",
"localMin",
"=",
"self",
".",
"mHighestBot",
"if",
"self",
".",
"mUseLowestBot",
":",
"if",
"localMin",
"<",
"self",
".",
"mLowestBot",
":",
"localMin",
"=",
"self",
".",
"mLowestBot",
"if",
"self",
".",
"mUseCumulativeRange",
":",
"localMax",
"=",
"self",
".",
"mAllMax",
"else",
":",
"localMax",
"=",
"self",
".",
"mThisCbMax",
"if",
"self",
".",
"mUseHighestTop",
":",
"if",
"localMax",
">",
"self",
".",
"mHighestTop",
":",
"localMax",
"=",
"self",
".",
"mHighestTop",
"if",
"self",
".",
"mUseLowestTop",
":",
"if",
"localMax",
"<",
"self",
".",
"mLowestTop",
":",
"localMax",
"=",
"self",
".",
"mLowestTop",
"if",
"localMin",
">",
"localMax",
":",
"if",
"self",
".",
"mUseLowestBot",
":",
"localMax",
"=",
"localMin",
"if",
"self",
".",
"mUseHighestTop",
":",
"localMin",
"=",
"localMax",
"if",
"localMin",
">",
"localMax",
":",
"if",
"PhactoriDbg",
"(",
")",
":",
"myDebugPrint3",
"(",
"\"UpdateMinMaxToUse: weird case with min/max\\n\"",
")",
"localMin",
"=",
"localMax",
"self",
".",
"mMinToUse",
"=",
"localMin",
"self",
".",
"mMaxToUse",
"=",
"localMax"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/PhactoriDriver.py#L22869-L22904 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Hash/CMAC.py | python | CMAC.hexdigest | (self) | return "".join(["%02x" % bord(x)
for x in tuple(self.digest())]) | Return the **printable** MAC tag of the message authenticated so far.
:return: The MAC tag, computed over the data processed so far.
Hexadecimal encoded.
:rtype: string | Return the **printable** MAC tag of the message authenticated so far. | [
"Return",
"the",
"**",
"printable",
"**",
"MAC",
"tag",
"of",
"the",
"message",
"authenticated",
"so",
"far",
"."
] | def hexdigest(self):
"""Return the **printable** MAC tag of the message authenticated so far.
:return: The MAC tag, computed over the data processed so far.
Hexadecimal encoded.
:rtype: string
"""
return "".join(["%02x" % bord(x)
for x in tuple(self.digest())]) | [
"def",
"hexdigest",
"(",
"self",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"[",
"\"%02x\"",
"%",
"bord",
"(",
"x",
")",
"for",
"x",
"in",
"tuple",
"(",
"self",
".",
"digest",
"(",
")",
")",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Hash/CMAC.py#L216-L225 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/rnn_cell_impl.py | python | _zero_state_tensors | (state_size, batch_size, dtype) | return nest.map_structure(get_state_shape, state_size) | Create tensors of zeros based on state_size, batch_size, and dtype. | Create tensors of zeros based on state_size, batch_size, and dtype. | [
"Create",
"tensors",
"of",
"zeros",
"based",
"on",
"state_size",
"batch_size",
"and",
"dtype",
"."
] | def _zero_state_tensors(state_size, batch_size, dtype):
"""Create tensors of zeros based on state_size, batch_size, and dtype."""
def get_state_shape(s):
"""Combine s with batch_size to get a proper tensor shape."""
c = _concat(batch_size, s)
size = array_ops.zeros(c, dtype=dtype)
if context.in_graph_mode():
c_static = _concat(batch_size, s, static=True)
size.set_shape(c_static)
return size
return nest.map_structure(get_state_shape, state_size) | [
"def",
"_zero_state_tensors",
"(",
"state_size",
",",
"batch_size",
",",
"dtype",
")",
":",
"def",
"get_state_shape",
"(",
"s",
")",
":",
"\"\"\"Combine s with batch_size to get a proper tensor shape.\"\"\"",
"c",
"=",
"_concat",
"(",
"batch_size",
",",
"s",
")",
"size",
"=",
"array_ops",
".",
"zeros",
"(",
"c",
",",
"dtype",
"=",
"dtype",
")",
"if",
"context",
".",
"in_graph_mode",
"(",
")",
":",
"c_static",
"=",
"_concat",
"(",
"batch_size",
",",
"s",
",",
"static",
"=",
"True",
")",
"size",
".",
"set_shape",
"(",
"c_static",
")",
"return",
"size",
"return",
"nest",
".",
"map_structure",
"(",
"get_state_shape",
",",
"state_size",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/rnn_cell_impl.py#L123-L133 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/base/android/jni_generator/jni_registration_generator.py | python | HeaderGenerator._AddProxyNativeMethodKStrings | (self) | Returns KMethodString for wrapped native methods in all_classes | Returns KMethodString for wrapped native methods in all_classes | [
"Returns",
"KMethodString",
"for",
"wrapped",
"native",
"methods",
"in",
"all_classes"
] | def _AddProxyNativeMethodKStrings(self):
"""Returns KMethodString for wrapped native methods in all_classes """
if self.main_dex:
key = 'PROXY_NATIVE_METHOD_ARRAY_MAIN_DEX'
else:
key = 'PROXY_NATIVE_METHOD_ARRAY'
proxy_k_strings = ('\n'.join(
self._GetKMethodArrayEntry(p) for p in self.proxy_natives))
self._SetDictValue(key, proxy_k_strings) | [
"def",
"_AddProxyNativeMethodKStrings",
"(",
"self",
")",
":",
"if",
"self",
".",
"main_dex",
":",
"key",
"=",
"'PROXY_NATIVE_METHOD_ARRAY_MAIN_DEX'",
"else",
":",
"key",
"=",
"'PROXY_NATIVE_METHOD_ARRAY'",
"proxy_k_strings",
"=",
"(",
"'\\n'",
".",
"join",
"(",
"self",
".",
"_GetKMethodArrayEntry",
"(",
"p",
")",
"for",
"p",
"in",
"self",
".",
"proxy_natives",
")",
")",
"self",
".",
"_SetDictValue",
"(",
"key",
",",
"proxy_k_strings",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/base/android/jni_generator/jni_registration_generator.py#L449-L460 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TStr_PutFExt | (*args) | return _snap.TStr_PutFExt(*args) | TStr_PutFExt(TStr FNm, TStr FExt) -> TStr
Parameters:
FNm: TStr const &
FExt: TStr const & | TStr_PutFExt(TStr FNm, TStr FExt) -> TStr | [
"TStr_PutFExt",
"(",
"TStr",
"FNm",
"TStr",
"FExt",
")",
"-",
">",
"TStr"
] | def TStr_PutFExt(*args):
"""
TStr_PutFExt(TStr FNm, TStr FExt) -> TStr
Parameters:
FNm: TStr const &
FExt: TStr const &
"""
return _snap.TStr_PutFExt(*args) | [
"def",
"TStr_PutFExt",
"(",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TStr_PutFExt",
"(",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L11213-L11222 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | DC.DrawSpline | (*args, **kwargs) | return _gdi_.DC_DrawSpline(*args, **kwargs) | DrawSpline(self, List points)
Draws a spline between all given control points, (a list of `wx.Point`
objects) using the current pen. The spline is drawn using a series of
lines, using an algorithm taken from the X drawing program 'XFIG'. | DrawSpline(self, List points) | [
"DrawSpline",
"(",
"self",
"List",
"points",
")"
] | def DrawSpline(*args, **kwargs):
"""
DrawSpline(self, List points)
Draws a spline between all given control points, (a list of `wx.Point`
objects) using the current pen. The spline is drawn using a series of
lines, using an algorithm taken from the X drawing program 'XFIG'.
"""
return _gdi_.DC_DrawSpline(*args, **kwargs) | [
"def",
"DrawSpline",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_DrawSpline",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L3955-L3963 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/ctrlbox.py | python | ControlBar.SetMargins | (self, param1, param2) | Setup the margins on the edges of the ControlBar
@param param1: left/top margin depending on orientation
@param param2: right/bottom margin depending on orientation | Setup the margins on the edges of the ControlBar
@param param1: left/top margin depending on orientation
@param param2: right/bottom margin depending on orientation | [
"Setup",
"the",
"margins",
"on",
"the",
"edges",
"of",
"the",
"ControlBar",
"@param",
"param1",
":",
"left",
"/",
"top",
"margin",
"depending",
"on",
"orientation",
"@param",
"param2",
":",
"right",
"/",
"bottom",
"margin",
"depending",
"on",
"orientation"
] | def SetMargins(self, param1, param2):
"""Setup the margins on the edges of the ControlBar
@param param1: left/top margin depending on orientation
@param param2: right/bottom margin depending on orientation
"""
sizer = self.GetSizer()
if wx.VERSION < (2, 9, 0, 0, ''):
sizer.GetItem(0).SetSpacer((param1, param1))
sizer.GetItem(2).SetSpacer((param2, param2))
else:
sizer.GetItem(0).AssignSpacer((param1, param1))
sizer.GetItem(2).AssignSpacer((param2, param2))
sizer.Layout() | [
"def",
"SetMargins",
"(",
"self",
",",
"param1",
",",
"param2",
")",
":",
"sizer",
"=",
"self",
".",
"GetSizer",
"(",
")",
"if",
"wx",
".",
"VERSION",
"<",
"(",
"2",
",",
"9",
",",
"0",
",",
"0",
",",
"''",
")",
":",
"sizer",
".",
"GetItem",
"(",
"0",
")",
".",
"SetSpacer",
"(",
"(",
"param1",
",",
"param1",
")",
")",
"sizer",
".",
"GetItem",
"(",
"2",
")",
".",
"SetSpacer",
"(",
"(",
"param2",
",",
"param2",
")",
")",
"else",
":",
"sizer",
".",
"GetItem",
"(",
"0",
")",
".",
"AssignSpacer",
"(",
"(",
"param1",
",",
"param1",
")",
")",
"sizer",
".",
"GetItem",
"(",
"2",
")",
".",
"AssignSpacer",
"(",
"(",
"param2",
",",
"param2",
")",
")",
"sizer",
".",
"Layout",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/ctrlbox.py#L583-L596 | ||
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/external/pydot.py | python | graph_from_adjacency_matrix | (matrix, node_prefix="", directed=False) | return graph | Creates a basic graph out of an adjacency matrix.
The matrix has to be a list of rows of values
representing an adjacency matrix.
The values can be anything: bool, int, float, as long
as they can evaluate to True or False. | Creates a basic graph out of an adjacency matrix.
The matrix has to be a list of rows of values
representing an adjacency matrix.
The values can be anything: bool, int, float, as long
as they can evaluate to True or False. | [
"Creates",
"a",
"basic",
"graph",
"out",
"of",
"an",
"adjacency",
"matrix",
".",
"The",
"matrix",
"has",
"to",
"be",
"a",
"list",
"of",
"rows",
"of",
"values",
"representing",
"an",
"adjacency",
"matrix",
".",
"The",
"values",
"can",
"be",
"anything",
":",
"bool",
"int",
"float",
"as",
"long",
"as",
"they",
"can",
"evaluate",
"to",
"True",
"or",
"False",
"."
] | def graph_from_adjacency_matrix(matrix, node_prefix="", directed=False):
"""Creates a basic graph out of an adjacency matrix.
The matrix has to be a list of rows of values
representing an adjacency matrix.
The values can be anything: bool, int, float, as long
as they can evaluate to True or False.
"""
node_orig = 1
if directed:
graph = Dot(graph_type='digraph')
else:
graph = Dot(graph_type='graph')
for row in matrix:
if not directed:
skip = matrix.index(row)
r = row[skip:]
else:
skip = 0
r = row
node_dest = skip + 1
for e in r:
if e:
graph.add_edge(
Edge(node_prefix + node_orig,
node_prefix + node_dest))
node_dest += 1
node_orig += 1
return graph | [
"def",
"graph_from_adjacency_matrix",
"(",
"matrix",
",",
"node_prefix",
"=",
"\"\"",
",",
"directed",
"=",
"False",
")",
":",
"node_orig",
"=",
"1",
"if",
"directed",
":",
"graph",
"=",
"Dot",
"(",
"graph_type",
"=",
"'digraph'",
")",
"else",
":",
"graph",
"=",
"Dot",
"(",
"graph_type",
"=",
"'graph'",
")",
"for",
"row",
"in",
"matrix",
":",
"if",
"not",
"directed",
":",
"skip",
"=",
"matrix",
".",
"index",
"(",
"row",
")",
"r",
"=",
"row",
"[",
"skip",
":",
"]",
"else",
":",
"skip",
"=",
"0",
"r",
"=",
"row",
"node_dest",
"=",
"skip",
"+",
"1",
"for",
"e",
"in",
"r",
":",
"if",
"e",
":",
"graph",
".",
"add_edge",
"(",
"Edge",
"(",
"node_prefix",
"+",
"node_orig",
",",
"node_prefix",
"+",
"node_dest",
")",
")",
"node_dest",
"+=",
"1",
"node_orig",
"+=",
"1",
"return",
"graph"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/pydot.py#L260-L293 | |
microsoft/LightGBM | 904b2d5158703c4900b68008617951dd2f9ff21b | python-package/lightgbm/basic.py | python | Dataset.set_weight | (self, weight) | return self | Set weight of each instance.
Parameters
----------
weight : list, numpy 1-D array, pandas Series or None
Weight to be set for each data point.
Returns
-------
self : Dataset
Dataset with set weight. | Set weight of each instance. | [
"Set",
"weight",
"of",
"each",
"instance",
"."
] | def set_weight(self, weight):
"""Set weight of each instance.
Parameters
----------
weight : list, numpy 1-D array, pandas Series or None
Weight to be set for each data point.
Returns
-------
self : Dataset
Dataset with set weight.
"""
if weight is not None and np.all(weight == 1):
weight = None
self.weight = weight
if self.handle is not None and weight is not None:
weight = list_to_1d_numpy(weight, name='weight')
self.set_field('weight', weight)
self.weight = self.get_field('weight') # original values can be modified at cpp side
return self | [
"def",
"set_weight",
"(",
"self",
",",
"weight",
")",
":",
"if",
"weight",
"is",
"not",
"None",
"and",
"np",
".",
"all",
"(",
"weight",
"==",
"1",
")",
":",
"weight",
"=",
"None",
"self",
".",
"weight",
"=",
"weight",
"if",
"self",
".",
"handle",
"is",
"not",
"None",
"and",
"weight",
"is",
"not",
"None",
":",
"weight",
"=",
"list_to_1d_numpy",
"(",
"weight",
",",
"name",
"=",
"'weight'",
")",
"self",
".",
"set_field",
"(",
"'weight'",
",",
"weight",
")",
"self",
".",
"weight",
"=",
"self",
".",
"get_field",
"(",
"'weight'",
")",
"# original values can be modified at cpp side",
"return",
"self"
] | https://github.com/microsoft/LightGBM/blob/904b2d5158703c4900b68008617951dd2f9ff21b/python-package/lightgbm/basic.py#L2150-L2170 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/types/containers.py | python | DictType.refine | (cls, keyty, valty) | return res | Refine to a precise dictionary type | Refine to a precise dictionary type | [
"Refine",
"to",
"a",
"precise",
"dictionary",
"type"
] | def refine(cls, keyty, valty):
"""Refine to a precise dictionary type
"""
res = cls(keyty, valty)
res.is_precise()
return res | [
"def",
"refine",
"(",
"cls",
",",
"keyty",
",",
"valty",
")",
":",
"res",
"=",
"cls",
"(",
"keyty",
",",
"valty",
")",
"res",
".",
"is_precise",
"(",
")",
"return",
"res"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/types/containers.py#L603-L608 | |
ONLYOFFICE/core | 1f976ae79a2593fc22ee78e9fdbb76090e83785c | DesktopEditor/xml/libxml2/python/libxml.py | python | SAXCallback.notationDecl | (self, name, externalID, systemID) | called when an NOTATION declaration has been found, name is the
notation name and externalID, systemID are the notation public and
system identifier for that notation if available | called when an NOTATION declaration has been found, name is the
notation name and externalID, systemID are the notation public and
system identifier for that notation if available | [
"called",
"when",
"an",
"NOTATION",
"declaration",
"has",
"been",
"found",
"name",
"is",
"the",
"notation",
"name",
"and",
"externalID",
"systemID",
"are",
"the",
"notation",
"public",
"and",
"system",
"identifier",
"for",
"that",
"notation",
"if",
"available"
] | def notationDecl(self, name, externalID, systemID):
"""called when an NOTATION declaration has been found, name is the
notation name and externalID, systemID are the notation public and
system identifier for that notation if available"""
pass | [
"def",
"notationDecl",
"(",
"self",
",",
"name",
",",
"externalID",
",",
"systemID",
")",
":",
"pass"
] | https://github.com/ONLYOFFICE/core/blob/1f976ae79a2593fc22ee78e9fdbb76090e83785c/DesktopEditor/xml/libxml2/python/libxml.py#L230-L234 | ||
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/decoder.py | python | MessageSetItemDecoder | (extensions_by_number) | return DecodeItem | Returns a decoder for a MessageSet item.
The parameter is the _extensions_by_number map for the message class.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
} | Returns a decoder for a MessageSet item. | [
"Returns",
"a",
"decoder",
"for",
"a",
"MessageSet",
"item",
"."
] | def MessageSetItemDecoder(extensions_by_number):
"""Returns a decoder for a MessageSet item.
The parameter is the _extensions_by_number map for the message class.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
}
"""
type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT)
message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)
item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP)
local_ReadTag = ReadTag
local_DecodeVarint = _DecodeVarint
local_SkipField = SkipField
def DecodeItem(buffer, pos, end, message, field_dict):
message_set_item_start = pos
type_id = -1
message_start = -1
message_end = -1
# Technically, type_id and message can appear in any order, so we need
# a little loop here.
while 1:
(tag_bytes, pos) = local_ReadTag(buffer, pos)
if tag_bytes == type_id_tag_bytes:
(type_id, pos) = local_DecodeVarint(buffer, pos)
elif tag_bytes == message_tag_bytes:
(size, message_start) = local_DecodeVarint(buffer, pos)
pos = message_end = message_start + size
elif tag_bytes == item_end_tag_bytes:
break
else:
pos = SkipField(buffer, pos, end, tag_bytes)
if pos == -1:
raise _DecodeError('Missing group end tag.')
if pos > end:
raise _DecodeError('Truncated message.')
if type_id == -1:
raise _DecodeError('MessageSet item missing type_id.')
if message_start == -1:
raise _DecodeError('MessageSet item missing message.')
extension = extensions_by_number.get(type_id)
if extension is not None:
value = field_dict.get(extension)
if value is None:
value = field_dict.setdefault(
extension, extension.message_type._concrete_class())
if value._InternalParse(buffer, message_start,message_end) != message_end:
# The only reason _InternalParse would return early is if it encountered
# an end-group tag.
raise _DecodeError('Unexpected end-group tag.')
else:
if not message._unknown_fields:
message._unknown_fields = []
message._unknown_fields.append((MESSAGE_SET_ITEM_TAG,
buffer[message_set_item_start:pos]))
return pos
return DecodeItem | [
"def",
"MessageSetItemDecoder",
"(",
"extensions_by_number",
")",
":",
"type_id_tag_bytes",
"=",
"encoder",
".",
"TagBytes",
"(",
"2",
",",
"wire_format",
".",
"WIRETYPE_VARINT",
")",
"message_tag_bytes",
"=",
"encoder",
".",
"TagBytes",
"(",
"3",
",",
"wire_format",
".",
"WIRETYPE_LENGTH_DELIMITED",
")",
"item_end_tag_bytes",
"=",
"encoder",
".",
"TagBytes",
"(",
"1",
",",
"wire_format",
".",
"WIRETYPE_END_GROUP",
")",
"local_ReadTag",
"=",
"ReadTag",
"local_DecodeVarint",
"=",
"_DecodeVarint",
"local_SkipField",
"=",
"SkipField",
"def",
"DecodeItem",
"(",
"buffer",
",",
"pos",
",",
"end",
",",
"message",
",",
"field_dict",
")",
":",
"message_set_item_start",
"=",
"pos",
"type_id",
"=",
"-",
"1",
"message_start",
"=",
"-",
"1",
"message_end",
"=",
"-",
"1",
"# Technically, type_id and message can appear in any order, so we need",
"# a little loop here.",
"while",
"1",
":",
"(",
"tag_bytes",
",",
"pos",
")",
"=",
"local_ReadTag",
"(",
"buffer",
",",
"pos",
")",
"if",
"tag_bytes",
"==",
"type_id_tag_bytes",
":",
"(",
"type_id",
",",
"pos",
")",
"=",
"local_DecodeVarint",
"(",
"buffer",
",",
"pos",
")",
"elif",
"tag_bytes",
"==",
"message_tag_bytes",
":",
"(",
"size",
",",
"message_start",
")",
"=",
"local_DecodeVarint",
"(",
"buffer",
",",
"pos",
")",
"pos",
"=",
"message_end",
"=",
"message_start",
"+",
"size",
"elif",
"tag_bytes",
"==",
"item_end_tag_bytes",
":",
"break",
"else",
":",
"pos",
"=",
"SkipField",
"(",
"buffer",
",",
"pos",
",",
"end",
",",
"tag_bytes",
")",
"if",
"pos",
"==",
"-",
"1",
":",
"raise",
"_DecodeError",
"(",
"'Missing group end tag.'",
")",
"if",
"pos",
">",
"end",
":",
"raise",
"_DecodeError",
"(",
"'Truncated message.'",
")",
"if",
"type_id",
"==",
"-",
"1",
":",
"raise",
"_DecodeError",
"(",
"'MessageSet item missing type_id.'",
")",
"if",
"message_start",
"==",
"-",
"1",
":",
"raise",
"_DecodeError",
"(",
"'MessageSet item missing message.'",
")",
"extension",
"=",
"extensions_by_number",
".",
"get",
"(",
"type_id",
")",
"if",
"extension",
"is",
"not",
"None",
":",
"value",
"=",
"field_dict",
".",
"get",
"(",
"extension",
")",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"field_dict",
".",
"setdefault",
"(",
"extension",
",",
"extension",
".",
"message_type",
".",
"_concrete_class",
"(",
")",
")",
"if",
"value",
".",
"_InternalParse",
"(",
"buffer",
",",
"message_start",
",",
"message_end",
")",
"!=",
"message_end",
":",
"# The only reason _InternalParse would return early is if it encountered",
"# an end-group tag.",
"raise",
"_DecodeError",
"(",
"'Unexpected end-group tag.'",
")",
"else",
":",
"if",
"not",
"message",
".",
"_unknown_fields",
":",
"message",
".",
"_unknown_fields",
"=",
"[",
"]",
"message",
".",
"_unknown_fields",
".",
"append",
"(",
"(",
"MESSAGE_SET_ITEM_TAG",
",",
"buffer",
"[",
"message_set_item_start",
":",
"pos",
"]",
")",
")",
"return",
"pos",
"return",
"DecodeItem"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/decoder.py#L556-L626 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/LargeScaleStructures/geometry_writer.py | python | MantidGeom.addSamplePosition | (self, location=None, coord_type="cartesian") | Adds the sample position to the file. The coordinates should be passed
as a tuple of (x, y, z) or (r, t, p). Default location is (0, 0, 0) in
cartesian coordinates. | Adds the sample position to the file. The coordinates should be passed
as a tuple of (x, y, z) or (r, t, p). Default location is (0, 0, 0) in
cartesian coordinates. | [
"Adds",
"the",
"sample",
"position",
"to",
"the",
"file",
".",
"The",
"coordinates",
"should",
"be",
"passed",
"as",
"a",
"tuple",
"of",
"(",
"x",
"y",
"z",
")",
"or",
"(",
"r",
"t",
"p",
")",
".",
"Default",
"location",
"is",
"(",
"0",
"0",
"0",
")",
"in",
"cartesian",
"coordinates",
"."
] | def addSamplePosition(self, location=None, coord_type="cartesian"):
"""
Adds the sample position to the file. The coordinates should be passed
as a tuple of (x, y, z) or (r, t, p). Default location is (0, 0, 0) in
cartesian coordinates.
"""
sample = self._append_child("component", self._root, type="sample-position")
if location is None:
self._append_child("location", sample, x="0.0", y="0.0", z="0.0")
else:
if coord_type == "cartesian":
self._append_child("location", sample,
x=location[0],
y=location[1],
z=location[2])
if coord_type == "spherical":
self._append_child("location", sample,
r=location[0],
t=location[1],
p=location[2])
child = self._append_child("type", self._root, name="sample-position")
child.setAttribute("is", "SamplePos") | [
"def",
"addSamplePosition",
"(",
"self",
",",
"location",
"=",
"None",
",",
"coord_type",
"=",
"\"cartesian\"",
")",
":",
"sample",
"=",
"self",
".",
"_append_child",
"(",
"\"component\"",
",",
"self",
".",
"_root",
",",
"type",
"=",
"\"sample-position\"",
")",
"if",
"location",
"is",
"None",
":",
"self",
".",
"_append_child",
"(",
"\"location\"",
",",
"sample",
",",
"x",
"=",
"\"0.0\"",
",",
"y",
"=",
"\"0.0\"",
",",
"z",
"=",
"\"0.0\"",
")",
"else",
":",
"if",
"coord_type",
"==",
"\"cartesian\"",
":",
"self",
".",
"_append_child",
"(",
"\"location\"",
",",
"sample",
",",
"x",
"=",
"location",
"[",
"0",
"]",
",",
"y",
"=",
"location",
"[",
"1",
"]",
",",
"z",
"=",
"location",
"[",
"2",
"]",
")",
"if",
"coord_type",
"==",
"\"spherical\"",
":",
"self",
".",
"_append_child",
"(",
"\"location\"",
",",
"sample",
",",
"r",
"=",
"location",
"[",
"0",
"]",
",",
"t",
"=",
"location",
"[",
"1",
"]",
",",
"p",
"=",
"location",
"[",
"2",
"]",
")",
"child",
"=",
"self",
".",
"_append_child",
"(",
"\"type\"",
",",
"self",
".",
"_root",
",",
"name",
"=",
"\"sample-position\"",
")",
"child",
".",
"setAttribute",
"(",
"\"is\"",
",",
"\"SamplePos\"",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/LargeScaleStructures/geometry_writer.py#L97-L119 | ||
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/column/column.py | python | __setitem__ | (self, key: Any, value: Any) | Set the value of self[key] to value.
If value and self are of different types,
value is coerced to self.dtype | Set the value of self[key] to value. | [
"Set",
"the",
"value",
"of",
"self",
"[",
"key",
"]",
"to",
"value",
"."
] | def __setitem__(self, key: Any, value: Any):
"""
Set the value of self[key] to value.
If value and self are of different types,
value is coerced to self.dtype
"""
if isinstance(key, slice):
key_start, key_stop, key_stride = key.indices(len(self))
if key_start < 0:
key_start = key_start + len(self)
if key_stop < 0:
key_stop = key_stop + len(self)
if key_start >= key_stop:
return self.copy()
if (key_stride is None or key_stride == 1) and is_scalar(value):
return self._fill(value, key_start, key_stop, inplace=True)
if key_stride != 1 or key_stride is not None or is_scalar(value):
key = arange(
start=key_start,
stop=key_stop,
step=key_stride,
dtype=cudf.dtype(np.int32),
)
nelem = len(key)
else:
nelem = abs(key_stop - key_start)
else:
key = as_column(key)
if is_bool_dtype(key.dtype):
if not len(key) == len(self):
raise ValueError(
"Boolean mask must be of same length as column"
)
key = arange(len(self))[key]
if hasattr(value, "__len__") and len(value) == len(self):
value = as_column(value)[key]
nelem = len(key)
if is_scalar(value):
value = cudf.Scalar(value, dtype=self.dtype)
else:
if len(value) != nelem:
msg = (
f"Size mismatch: cannot set value "
f"of size {len(value)} to indexing result of size "
f"{nelem}"
)
raise ValueError(msg)
value = as_column(value).astype(self.dtype)
if (
isinstance(key, slice)
and (key_stride == 1 or key_stride is None)
and not is_scalar(value)
):
out = libcudf.copying.copy_range(
value, self, 0, nelem, key_start, key_stop, False
)
else:
try:
if not isinstance(key, Column):
key = as_column(key)
if not is_scalar(value) and not isinstance(value, Column):
value = as_column(value)
out = libcudf.copying.scatter(
value, key, self
)._with_type_metadata(self.dtype)
except RuntimeError as e:
if "out of bounds" in str(e):
raise IndexError(
f"index out of bounds for column of size {len(self)}"
) from e
raise
self._mimic_inplace(out, inplace=True) | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
":",
"Any",
",",
"value",
":",
"Any",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"slice",
")",
":",
"key_start",
",",
"key_stop",
",",
"key_stride",
"=",
"key",
".",
"indices",
"(",
"len",
"(",
"self",
")",
")",
"if",
"key_start",
"<",
"0",
":",
"key_start",
"=",
"key_start",
"+",
"len",
"(",
"self",
")",
"if",
"key_stop",
"<",
"0",
":",
"key_stop",
"=",
"key_stop",
"+",
"len",
"(",
"self",
")",
"if",
"key_start",
">=",
"key_stop",
":",
"return",
"self",
".",
"copy",
"(",
")",
"if",
"(",
"key_stride",
"is",
"None",
"or",
"key_stride",
"==",
"1",
")",
"and",
"is_scalar",
"(",
"value",
")",
":",
"return",
"self",
".",
"_fill",
"(",
"value",
",",
"key_start",
",",
"key_stop",
",",
"inplace",
"=",
"True",
")",
"if",
"key_stride",
"!=",
"1",
"or",
"key_stride",
"is",
"not",
"None",
"or",
"is_scalar",
"(",
"value",
")",
":",
"key",
"=",
"arange",
"(",
"start",
"=",
"key_start",
",",
"stop",
"=",
"key_stop",
",",
"step",
"=",
"key_stride",
",",
"dtype",
"=",
"cudf",
".",
"dtype",
"(",
"np",
".",
"int32",
")",
",",
")",
"nelem",
"=",
"len",
"(",
"key",
")",
"else",
":",
"nelem",
"=",
"abs",
"(",
"key_stop",
"-",
"key_start",
")",
"else",
":",
"key",
"=",
"as_column",
"(",
"key",
")",
"if",
"is_bool_dtype",
"(",
"key",
".",
"dtype",
")",
":",
"if",
"not",
"len",
"(",
"key",
")",
"==",
"len",
"(",
"self",
")",
":",
"raise",
"ValueError",
"(",
"\"Boolean mask must be of same length as column\"",
")",
"key",
"=",
"arange",
"(",
"len",
"(",
"self",
")",
")",
"[",
"key",
"]",
"if",
"hasattr",
"(",
"value",
",",
"\"__len__\"",
")",
"and",
"len",
"(",
"value",
")",
"==",
"len",
"(",
"self",
")",
":",
"value",
"=",
"as_column",
"(",
"value",
")",
"[",
"key",
"]",
"nelem",
"=",
"len",
"(",
"key",
")",
"if",
"is_scalar",
"(",
"value",
")",
":",
"value",
"=",
"cudf",
".",
"Scalar",
"(",
"value",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"else",
":",
"if",
"len",
"(",
"value",
")",
"!=",
"nelem",
":",
"msg",
"=",
"(",
"f\"Size mismatch: cannot set value \"",
"f\"of size {len(value)} to indexing result of size \"",
"f\"{nelem}\"",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"value",
"=",
"as_column",
"(",
"value",
")",
".",
"astype",
"(",
"self",
".",
"dtype",
")",
"if",
"(",
"isinstance",
"(",
"key",
",",
"slice",
")",
"and",
"(",
"key_stride",
"==",
"1",
"or",
"key_stride",
"is",
"None",
")",
"and",
"not",
"is_scalar",
"(",
"value",
")",
")",
":",
"out",
"=",
"libcudf",
".",
"copying",
".",
"copy_range",
"(",
"value",
",",
"self",
",",
"0",
",",
"nelem",
",",
"key_start",
",",
"key_stop",
",",
"False",
")",
"else",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"Column",
")",
":",
"key",
"=",
"as_column",
"(",
"key",
")",
"if",
"not",
"is_scalar",
"(",
"value",
")",
"and",
"not",
"isinstance",
"(",
"value",
",",
"Column",
")",
":",
"value",
"=",
"as_column",
"(",
"value",
")",
"out",
"=",
"libcudf",
".",
"copying",
".",
"scatter",
"(",
"value",
",",
"key",
",",
"self",
")",
".",
"_with_type_metadata",
"(",
"self",
".",
"dtype",
")",
"except",
"RuntimeError",
"as",
"e",
":",
"if",
"\"out of bounds\"",
"in",
"str",
"(",
"e",
")",
":",
"raise",
"IndexError",
"(",
"f\"index out of bounds for column of size {len(self)}\"",
")",
"from",
"e",
"raise",
"self",
".",
"_mimic_inplace",
"(",
"out",
",",
"inplace",
"=",
"True",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column/column.py#L488-L565 | ||
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py | python | _FindDirectXInstallation | () | return dxsdk_dir | Try to find an installation location for the DirectX SDK. Check for the
standard environment variable, and if that doesn't exist, try to find
via the registry. May return None if not found in either location. | Try to find an installation location for the DirectX SDK. Check for the
standard environment variable, and if that doesn't exist, try to find
via the registry. May return None if not found in either location. | [
"Try",
"to",
"find",
"an",
"installation",
"location",
"for",
"the",
"DirectX",
"SDK",
".",
"Check",
"for",
"the",
"standard",
"environment",
"variable",
"and",
"if",
"that",
"doesn",
"t",
"exist",
"try",
"to",
"find",
"via",
"the",
"registry",
".",
"May",
"return",
"None",
"if",
"not",
"found",
"in",
"either",
"location",
"."
] | def _FindDirectXInstallation():
"""Try to find an installation location for the DirectX SDK. Check for the
standard environment variable, and if that doesn't exist, try to find
via the registry. May return None if not found in either location."""
# Return previously calculated value, if there is one
if hasattr(_FindDirectXInstallation, 'dxsdk_dir'):
return _FindDirectXInstallation.dxsdk_dir
dxsdk_dir = os.environ.get('DXSDK_DIR')
if not dxsdk_dir:
# Setup params to pass to and attempt to launch reg.exe.
cmd = ['reg.exe', 'query', r'HKLM\Software\Microsoft\DirectX', '/s']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in p.communicate()[0].splitlines():
if 'InstallPath' in line:
dxsdk_dir = line.split(' ')[3] + "\\"
# Cache return value
_FindDirectXInstallation.dxsdk_dir = dxsdk_dir
return dxsdk_dir | [
"def",
"_FindDirectXInstallation",
"(",
")",
":",
"# Return previously calculated value, if there is one",
"if",
"hasattr",
"(",
"_FindDirectXInstallation",
",",
"'dxsdk_dir'",
")",
":",
"return",
"_FindDirectXInstallation",
".",
"dxsdk_dir",
"dxsdk_dir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'DXSDK_DIR'",
")",
"if",
"not",
"dxsdk_dir",
":",
"# Setup params to pass to and attempt to launch reg.exe.",
"cmd",
"=",
"[",
"'reg.exe'",
",",
"'query'",
",",
"r'HKLM\\Software\\Microsoft\\DirectX'",
",",
"'/s'",
"]",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"for",
"line",
"in",
"p",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"splitlines",
"(",
")",
":",
"if",
"'InstallPath'",
"in",
"line",
":",
"dxsdk_dir",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"[",
"3",
"]",
"+",
"\"\\\\\"",
"# Cache return value",
"_FindDirectXInstallation",
".",
"dxsdk_dir",
"=",
"dxsdk_dir",
"return",
"dxsdk_dir"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py#L120-L139 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/xrc.py | python | XmlResourceHandler.__init__ | (self, *args, **kwargs) | __init__(self) -> XmlResourceHandler | __init__(self) -> XmlResourceHandler | [
"__init__",
"(",
"self",
")",
"-",
">",
"XmlResourceHandler"
] | def __init__(self, *args, **kwargs):
"""__init__(self) -> XmlResourceHandler"""
_xrc.XmlResourceHandler_swiginit(self,_xrc.new_XmlResourceHandler(*args, **kwargs))
XmlResourceHandler._setCallbackInfo(self, self, XmlResourceHandler) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_xrc",
".",
"XmlResourceHandler_swiginit",
"(",
"self",
",",
"_xrc",
".",
"new_XmlResourceHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"XmlResourceHandler",
".",
"_setCallbackInfo",
"(",
"self",
",",
"self",
",",
"XmlResourceHandler",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/xrc.py#L584-L587 | ||
openmm/openmm | cb293447c4fc8b03976dfe11399f107bab70f3d9 | wrappers/python/openmm/unit/unit_math.py | python | norm | (x) | return sqrt(dot(x, x)) | >>> norm((3, 4)*meter)
Quantity(value=5.0, unit=meter) | >>> norm((3, 4)*meter)
Quantity(value=5.0, unit=meter) | [
">>>",
"norm",
"((",
"3",
"4",
")",
"*",
"meter",
")",
"Quantity",
"(",
"value",
"=",
"5",
".",
"0",
"unit",
"=",
"meter",
")"
] | def norm(x):
"""
>>> norm((3, 4)*meter)
Quantity(value=5.0, unit=meter)
"""
return sqrt(dot(x, x)) | [
"def",
"norm",
"(",
"x",
")",
":",
"return",
"sqrt",
"(",
"dot",
"(",
"x",
",",
"x",
")",
")"
] | https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/unit/unit_math.py#L183-L188 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/numpy_ops/np_utils.py | python | greater_equal | (a, b) | return _maybe_static(a) >= _maybe_static(b) | A version of tf.greater_equal that eagerly evaluates if possible. | A version of tf.greater_equal that eagerly evaluates if possible. | [
"A",
"version",
"of",
"tf",
".",
"greater_equal",
"that",
"eagerly",
"evaluates",
"if",
"possible",
"."
] | def greater_equal(a, b):
"""A version of tf.greater_equal that eagerly evaluates if possible."""
return _maybe_static(a) >= _maybe_static(b) | [
"def",
"greater_equal",
"(",
"a",
",",
"b",
")",
":",
"return",
"_maybe_static",
"(",
"a",
")",
">=",
"_maybe_static",
"(",
"b",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/numpy_ops/np_utils.py#L622-L624 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/wiredtiger/src/docs/tools/doxypy.py | python | Doxypy.__flushBuffer | (self) | Flushes the current outputbuffer to the outstream. | Flushes the current outputbuffer to the outstream. | [
"Flushes",
"the",
"current",
"outputbuffer",
"to",
"the",
"outstream",
"."
] | def __flushBuffer(self):
"""Flushes the current outputbuffer to the outstream."""
if self.output:
try:
if options.debug:
print >>sys.stderr, "# OUTPUT: ", self.output
print >>self.outstream, "\n".join(self.output)
self.outstream.flush()
except IOError:
# Fix for FS#33. Catches "broken pipe" when doxygen closes
# stdout prematurely upon usage of INPUT_FILTER, INLINE_SOURCES
# and FILTER_SOURCE_FILES.
pass
self.output = [] | [
"def",
"__flushBuffer",
"(",
"self",
")",
":",
"if",
"self",
".",
"output",
":",
"try",
":",
"if",
"options",
".",
"debug",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"# OUTPUT: \"",
",",
"self",
".",
"output",
"print",
">>",
"self",
".",
"outstream",
",",
"\"\\n\"",
".",
"join",
"(",
"self",
".",
"output",
")",
"self",
".",
"outstream",
".",
"flush",
"(",
")",
"except",
"IOError",
":",
"# Fix for FS#33. Catches \"broken pipe\" when doxygen closes ",
"# stdout prematurely upon usage of INPUT_FILTER, INLINE_SOURCES ",
"# and FILTER_SOURCE_FILES.",
"pass",
"self",
".",
"output",
"=",
"[",
"]"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/wiredtiger/src/docs/tools/doxypy.py#L206-L219 | ||
msftguy/ssh-rd | a5f3a79daeac5844edebf01916c9613563f1c390 | _3rd/boost_1_48_0/tools/build/v2/build/generators.py | python | Generator.convert_multiple_sources_to_consumable_types | (self, project, prop_set, sources) | return (consumed, bypassed) | Converts several files to consumable types. | Converts several files to consumable types. | [
"Converts",
"several",
"files",
"to",
"consumable",
"types",
"."
] | def convert_multiple_sources_to_consumable_types (self, project, prop_set, sources):
""" Converts several files to consumable types.
"""
consumed = []
bypassed = []
# We process each source one-by-one, trying to convert it to
# a usable type.
for s in sources:
# TODO: need to check for failure on each source.
(c, b) = self.convert_to_consumable_types (project, None, prop_set, [s], True)
if not c:
project.manager ().logger ().log (__name__, " failed to convert ", s)
consumed.extend (c)
bypassed.extend (b)
return (consumed, bypassed) | [
"def",
"convert_multiple_sources_to_consumable_types",
"(",
"self",
",",
"project",
",",
"prop_set",
",",
"sources",
")",
":",
"consumed",
"=",
"[",
"]",
"bypassed",
"=",
"[",
"]",
"# We process each source one-by-one, trying to convert it to",
"# a usable type.",
"for",
"s",
"in",
"sources",
":",
"# TODO: need to check for failure on each source.",
"(",
"c",
",",
"b",
")",
"=",
"self",
".",
"convert_to_consumable_types",
"(",
"project",
",",
"None",
",",
"prop_set",
",",
"[",
"s",
"]",
",",
"True",
")",
"if",
"not",
"c",
":",
"project",
".",
"manager",
"(",
")",
".",
"logger",
"(",
")",
".",
"log",
"(",
"__name__",
",",
"\" failed to convert \"",
",",
"s",
")",
"consumed",
".",
"extend",
"(",
"c",
")",
"bypassed",
".",
"extend",
"(",
"b",
")",
"return",
"(",
"consumed",
",",
"bypassed",
")"
] | https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/generators.py#L561-L578 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextCtrl.IndicatorClearRange | (*args, **kwargs) | return _stc.StyledTextCtrl_IndicatorClearRange(*args, **kwargs) | IndicatorClearRange(self, int position, int clearLength)
Turn a indicator off over a range. | IndicatorClearRange(self, int position, int clearLength) | [
"IndicatorClearRange",
"(",
"self",
"int",
"position",
"int",
"clearLength",
")"
] | def IndicatorClearRange(*args, **kwargs):
"""
IndicatorClearRange(self, int position, int clearLength)
Turn a indicator off over a range.
"""
return _stc.StyledTextCtrl_IndicatorClearRange(*args, **kwargs) | [
"def",
"IndicatorClearRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_IndicatorClearRange",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L5687-L5693 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py | python | MainWindow.menu_pre_process | (self) | handling action to trigger menu pre-process
:return: | handling action to trigger menu pre-process
:return: | [
"handling",
"action",
"to",
"trigger",
"menu",
"pre",
"-",
"process",
":",
"return",
":"
] | def menu_pre_process(self):
""" handling action to trigger menu pre-process
:return:
"""
# initialize the pre processing window if it is not initialized
reset_pre_process_window = False
if self._preProcessWindow is None:
# initialize the instance
self._preProcessWindow = PreprocessWindow.ScanPreProcessWindow(self)
self._preProcessWindow.setup(self._myControl)
reset_pre_process_window = True
# show the window
self._preProcessWindow.show()
# setup the parameters
# TODO/FUTURE - Add a push button somewhere to force pre-processing menu to synchronize with main UI for
# TODO instrument calibration
if reset_pre_process_window:
exp_number = int(str(self.ui.lineEdit_exp.text()))
# detector size/pixel numbers
det_size_str = str(self.ui.comboBox_detectorSize.currentText())
det_size = int(det_size_str.split()[0])
# detector center
det_center = str(self.ui.lineEdit_infoDetCenter.text())
# sample detector distance
det_sample_dist = str(self.ui.lineEdit_infoDetSampleDistance.text())
try:
det_sample_dist = float(det_sample_dist)
except ValueError:
det_sample_dist = None
# wave length
wave_length = str(self.ui.lineEdit_infoWavelength.text())
try:
wave_length = float(wave_length)
except ValueError:
wave_length = None
# set up the other calibration parameters
self._preProcessWindow.set_instrument_calibration(exp_number=exp_number, det_size=det_size,
det_center=det_center,
det_sample_distance=det_sample_dist,
wave_length=wave_length) | [
"def",
"menu_pre_process",
"(",
"self",
")",
":",
"# initialize the pre processing window if it is not initialized",
"reset_pre_process_window",
"=",
"False",
"if",
"self",
".",
"_preProcessWindow",
"is",
"None",
":",
"# initialize the instance",
"self",
".",
"_preProcessWindow",
"=",
"PreprocessWindow",
".",
"ScanPreProcessWindow",
"(",
"self",
")",
"self",
".",
"_preProcessWindow",
".",
"setup",
"(",
"self",
".",
"_myControl",
")",
"reset_pre_process_window",
"=",
"True",
"# show the window",
"self",
".",
"_preProcessWindow",
".",
"show",
"(",
")",
"# setup the parameters",
"# TODO/FUTURE - Add a push button somewhere to force pre-processing menu to synchronize with main UI for",
"# TODO instrument calibration",
"if",
"reset_pre_process_window",
":",
"exp_number",
"=",
"int",
"(",
"str",
"(",
"self",
".",
"ui",
".",
"lineEdit_exp",
".",
"text",
"(",
")",
")",
")",
"# detector size/pixel numbers",
"det_size_str",
"=",
"str",
"(",
"self",
".",
"ui",
".",
"comboBox_detectorSize",
".",
"currentText",
"(",
")",
")",
"det_size",
"=",
"int",
"(",
"det_size_str",
".",
"split",
"(",
")",
"[",
"0",
"]",
")",
"# detector center",
"det_center",
"=",
"str",
"(",
"self",
".",
"ui",
".",
"lineEdit_infoDetCenter",
".",
"text",
"(",
")",
")",
"# sample detector distance",
"det_sample_dist",
"=",
"str",
"(",
"self",
".",
"ui",
".",
"lineEdit_infoDetSampleDistance",
".",
"text",
"(",
")",
")",
"try",
":",
"det_sample_dist",
"=",
"float",
"(",
"det_sample_dist",
")",
"except",
"ValueError",
":",
"det_sample_dist",
"=",
"None",
"# wave length",
"wave_length",
"=",
"str",
"(",
"self",
".",
"ui",
".",
"lineEdit_infoWavelength",
".",
"text",
"(",
")",
")",
"try",
":",
"wave_length",
"=",
"float",
"(",
"wave_length",
")",
"except",
"ValueError",
":",
"wave_length",
"=",
"None",
"# set up the other calibration parameters",
"self",
".",
"_preProcessWindow",
".",
"set_instrument_calibration",
"(",
"exp_number",
"=",
"exp_number",
",",
"det_size",
"=",
"det_size",
",",
"det_center",
"=",
"det_center",
",",
"det_sample_distance",
"=",
"det_sample_dist",
",",
"wave_length",
"=",
"wave_length",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleGUI.py#L3660-L3702 | ||
NVIDIAGameWorks/kaolin | e5148d05e9c1e2ce92a07881ce3593b1c5c3f166 | kaolin/ops/mesh/trianglemesh.py | python | face_areas | (vertices, faces) | return areas.squeeze(-1) | Compute the areas of each face of triangle meshes.
Args:
vertices (torch.Tensor):
The vertices of the meshes,
of shape :math:`(\\text{batch_size}, \\text{num_vertices}, 3)`.
faces (torch.LongTensor):
the faces of the meshes, of shape :math:`(\\text{num_faces}, 3)`.
Returns:
(torch.Tensor):
the face areas of same type as vertices and of shape
:math:`(\\text{batch_size}, \\text{num_faces})`. | Compute the areas of each face of triangle meshes. | [
"Compute",
"the",
"areas",
"of",
"each",
"face",
"of",
"triangle",
"meshes",
"."
] | def face_areas(vertices, faces):
"""Compute the areas of each face of triangle meshes.
Args:
vertices (torch.Tensor):
The vertices of the meshes,
of shape :math:`(\\text{batch_size}, \\text{num_vertices}, 3)`.
faces (torch.LongTensor):
the faces of the meshes, of shape :math:`(\\text{num_faces}, 3)`.
Returns:
(torch.Tensor):
the face areas of same type as vertices and of shape
:math:`(\\text{batch_size}, \\text{num_faces})`.
"""
if faces.shape[-1] != 3:
raise NotImplementedError("face_areas is only implemented for triangle meshes")
faces_0, faces_1, faces_2 = torch.split(faces, 1, dim=1)
face_v_0 = torch.index_select(vertices, 1, faces_0.reshape(-1))
face_v_1 = torch.index_select(vertices, 1, faces_1.reshape(-1))
face_v_2 = torch.index_select(vertices, 1, faces_2.reshape(-1))
areas = _base_face_areas(face_v_0, face_v_1, face_v_2)
return areas.squeeze(-1) | [
"def",
"face_areas",
"(",
"vertices",
",",
"faces",
")",
":",
"if",
"faces",
".",
"shape",
"[",
"-",
"1",
"]",
"!=",
"3",
":",
"raise",
"NotImplementedError",
"(",
"\"face_areas is only implemented for triangle meshes\"",
")",
"faces_0",
",",
"faces_1",
",",
"faces_2",
"=",
"torch",
".",
"split",
"(",
"faces",
",",
"1",
",",
"dim",
"=",
"1",
")",
"face_v_0",
"=",
"torch",
".",
"index_select",
"(",
"vertices",
",",
"1",
",",
"faces_0",
".",
"reshape",
"(",
"-",
"1",
")",
")",
"face_v_1",
"=",
"torch",
".",
"index_select",
"(",
"vertices",
",",
"1",
",",
"faces_1",
".",
"reshape",
"(",
"-",
"1",
")",
")",
"face_v_2",
"=",
"torch",
".",
"index_select",
"(",
"vertices",
",",
"1",
",",
"faces_2",
".",
"reshape",
"(",
"-",
"1",
")",
")",
"areas",
"=",
"_base_face_areas",
"(",
"face_v_0",
",",
"face_v_1",
",",
"face_v_2",
")",
"return",
"areas",
".",
"squeeze",
"(",
"-",
"1",
")"
] | https://github.com/NVIDIAGameWorks/kaolin/blob/e5148d05e9c1e2ce92a07881ce3593b1c5c3f166/kaolin/ops/mesh/trianglemesh.py#L93-L117 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/dockart.py | python | AuiDefaultDockArt.DrawGripper | (self, dc, window, rect, pane) | Draws a gripper on the pane.
:param `dc`: a :class:`DC` device context;
:param `window`: an instance of :class:`Window`;
:param Rect `rect`: the pane caption rectangle;
:param `pane`: the pane for which the gripper is drawn. | Draws a gripper on the pane. | [
"Draws",
"a",
"gripper",
"on",
"the",
"pane",
"."
] | def DrawGripper(self, dc, window, rect, pane):
"""
Draws a gripper on the pane.
:param `dc`: a :class:`DC` device context;
:param `window`: an instance of :class:`Window`;
:param Rect `rect`: the pane caption rectangle;
:param `pane`: the pane for which the gripper is drawn.
"""
dc.SetPen(wx.TRANSPARENT_PEN)
dc.SetBrush(self._gripper_brush)
dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)
if not pane.HasGripperTop():
y = 4
while 1:
dc.SetPen(self._gripper_pen1)
dc.DrawPoint(rect.x+3, rect.y+y)
dc.SetPen(self._gripper_pen2)
dc.DrawPoint(rect.x+3, rect.y+y+1)
dc.DrawPoint(rect.x+4, rect.y+y)
dc.SetPen(self._gripper_pen3)
dc.DrawPoint(rect.x+5, rect.y+y+1)
dc.DrawPoint(rect.x+5, rect.y+y+2)
dc.DrawPoint(rect.x+4, rect.y+y+2)
y = y + 4
if y > rect.GetHeight() - 4:
break
else:
x = 4
while 1:
dc.SetPen(self._gripper_pen1)
dc.DrawPoint(rect.x+x, rect.y+3)
dc.SetPen(self._gripper_pen2)
dc.DrawPoint(rect.x+x+1, rect.y+3)
dc.DrawPoint(rect.x+x, rect.y+4)
dc.SetPen(self._gripper_pen3)
dc.DrawPoint(rect.x+x+1, rect.y+5)
dc.DrawPoint(rect.x+x+2, rect.y+5)
dc.DrawPoint(rect.x+x+2, rect.y+4)
x = x + 4
if x > rect.GetWidth() - 4:
break | [
"def",
"DrawGripper",
"(",
"self",
",",
"dc",
",",
"window",
",",
"rect",
",",
"pane",
")",
":",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"TRANSPARENT_PEN",
")",
"dc",
".",
"SetBrush",
"(",
"self",
".",
"_gripper_brush",
")",
"dc",
".",
"DrawRectangle",
"(",
"rect",
".",
"x",
",",
"rect",
".",
"y",
",",
"rect",
".",
"width",
",",
"rect",
".",
"height",
")",
"if",
"not",
"pane",
".",
"HasGripperTop",
"(",
")",
":",
"y",
"=",
"4",
"while",
"1",
":",
"dc",
".",
"SetPen",
"(",
"self",
".",
"_gripper_pen1",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"3",
",",
"rect",
".",
"y",
"+",
"y",
")",
"dc",
".",
"SetPen",
"(",
"self",
".",
"_gripper_pen2",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"3",
",",
"rect",
".",
"y",
"+",
"y",
"+",
"1",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"4",
",",
"rect",
".",
"y",
"+",
"y",
")",
"dc",
".",
"SetPen",
"(",
"self",
".",
"_gripper_pen3",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"5",
",",
"rect",
".",
"y",
"+",
"y",
"+",
"1",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"5",
",",
"rect",
".",
"y",
"+",
"y",
"+",
"2",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"4",
",",
"rect",
".",
"y",
"+",
"y",
"+",
"2",
")",
"y",
"=",
"y",
"+",
"4",
"if",
"y",
">",
"rect",
".",
"GetHeight",
"(",
")",
"-",
"4",
":",
"break",
"else",
":",
"x",
"=",
"4",
"while",
"1",
":",
"dc",
".",
"SetPen",
"(",
"self",
".",
"_gripper_pen1",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"x",
",",
"rect",
".",
"y",
"+",
"3",
")",
"dc",
".",
"SetPen",
"(",
"self",
".",
"_gripper_pen2",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"x",
"+",
"1",
",",
"rect",
".",
"y",
"+",
"3",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"x",
",",
"rect",
".",
"y",
"+",
"4",
")",
"dc",
".",
"SetPen",
"(",
"self",
".",
"_gripper_pen3",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"x",
"+",
"1",
",",
"rect",
".",
"y",
"+",
"5",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"x",
"+",
"2",
",",
"rect",
".",
"y",
"+",
"5",
")",
"dc",
".",
"DrawPoint",
"(",
"rect",
".",
"x",
"+",
"x",
"+",
"2",
",",
"rect",
".",
"y",
"+",
"4",
")",
"x",
"=",
"x",
"+",
"4",
"if",
"x",
">",
"rect",
".",
"GetWidth",
"(",
")",
"-",
"4",
":",
"break"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/dockart.py#L636-L680 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/ultimatelistctrl.py | python | UltimateListMainWindow.GetNextActiveItem | (self, item, down=True) | Returns the next active item. Used Internally at present.
:param `item`: an instance of :class:`UltimateListItem`;
:param `down`: ``True`` to search downwards for an active item, ``False``
to search upwards. | Returns the next active item. Used Internally at present. | [
"Returns",
"the",
"next",
"active",
"item",
".",
"Used",
"Internally",
"at",
"present",
"."
] | def GetNextActiveItem(self, item, down=True):
"""
Returns the next active item. Used Internally at present.
:param `item`: an instance of :class:`UltimateListItem`;
:param `down`: ``True`` to search downwards for an active item, ``False``
to search upwards.
"""
count = self.GetItemCount()
initialItem = item
while 1:
if item >= count or item < 0:
return initialItem
listItem = CreateListItem(item, 0)
listItem = self.GetItem(listItem, 0)
if listItem.IsEnabled():
return item
item = (down and [item+1] or [item-1])[0] | [
"def",
"GetNextActiveItem",
"(",
"self",
",",
"item",
",",
"down",
"=",
"True",
")",
":",
"count",
"=",
"self",
".",
"GetItemCount",
"(",
")",
"initialItem",
"=",
"item",
"while",
"1",
":",
"if",
"item",
">=",
"count",
"or",
"item",
"<",
"0",
":",
"return",
"initialItem",
"listItem",
"=",
"CreateListItem",
"(",
"item",
",",
"0",
")",
"listItem",
"=",
"self",
".",
"GetItem",
"(",
"listItem",
",",
"0",
")",
"if",
"listItem",
".",
"IsEnabled",
"(",
")",
":",
"return",
"item",
"item",
"=",
"(",
"down",
"and",
"[",
"item",
"+",
"1",
"]",
"or",
"[",
"item",
"-",
"1",
"]",
")",
"[",
"0",
"]"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L7956-L7977 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/sdb/db/sequence.py | python | Sequence.__init__ | (self, id=None, domain_name=None, fnc=increment_by_one, init_val=None) | Create a new Sequence, using an optional function to
increment to the next number, by default we just increment by one.
Every parameter here is optional, if you don't specify any options
then you'll get a new SequenceGenerator with a random ID stored in the
default domain that increments by one and uses the default botoweb
environment
:param id: Optional ID (name) for this counter
:type id: str
:param domain_name: Optional domain name to use, by default we get this out of the
environment configuration
:type domain_name:str
:param fnc: Optional function to use for the incrementation, by default we just increment by one
There are several functions defined in this module.
Your function must accept "None" to get the initial value
:type fnc: function, str
:param init_val: Initial value, by default this is the first element in your sequence,
but you can pass in any value, even a string if you pass in a function that uses
strings instead of ints to increment | Create a new Sequence, using an optional function to
increment to the next number, by default we just increment by one.
Every parameter here is optional, if you don't specify any options
then you'll get a new SequenceGenerator with a random ID stored in the
default domain that increments by one and uses the default botoweb
environment | [
"Create",
"a",
"new",
"Sequence",
"using",
"an",
"optional",
"function",
"to",
"increment",
"to",
"the",
"next",
"number",
"by",
"default",
"we",
"just",
"increment",
"by",
"one",
".",
"Every",
"parameter",
"here",
"is",
"optional",
"if",
"you",
"don",
"t",
"specify",
"any",
"options",
"then",
"you",
"ll",
"get",
"a",
"new",
"SequenceGenerator",
"with",
"a",
"random",
"ID",
"stored",
"in",
"the",
"default",
"domain",
"that",
"increments",
"by",
"one",
"and",
"uses",
"the",
"default",
"botoweb",
"environment"
] | def __init__(self, id=None, domain_name=None, fnc=increment_by_one, init_val=None):
"""Create a new Sequence, using an optional function to
increment to the next number, by default we just increment by one.
Every parameter here is optional, if you don't specify any options
then you'll get a new SequenceGenerator with a random ID stored in the
default domain that increments by one and uses the default botoweb
environment
:param id: Optional ID (name) for this counter
:type id: str
:param domain_name: Optional domain name to use, by default we get this out of the
environment configuration
:type domain_name:str
:param fnc: Optional function to use for the incrementation, by default we just increment by one
There are several functions defined in this module.
Your function must accept "None" to get the initial value
:type fnc: function, str
:param init_val: Initial value, by default this is the first element in your sequence,
but you can pass in any value, even a string if you pass in a function that uses
strings instead of ints to increment
"""
self._db = None
self._value = None
self.last_value = None
self.domain_name = domain_name
self.id = id
if init_val is None:
init_val = fnc(init_val)
if self.id is None:
import uuid
self.id = str(uuid.uuid4())
self.item_type = type(fnc(None))
self.timestamp = None
# Allow us to pass in a full name to a function
if isinstance(fnc, six.string_types):
from boto.utils import find_class
fnc = find_class(fnc)
self.fnc = fnc
# Bootstrap the value last
if not self.val:
self.val = init_val | [
"def",
"__init__",
"(",
"self",
",",
"id",
"=",
"None",
",",
"domain_name",
"=",
"None",
",",
"fnc",
"=",
"increment_by_one",
",",
"init_val",
"=",
"None",
")",
":",
"self",
".",
"_db",
"=",
"None",
"self",
".",
"_value",
"=",
"None",
"self",
".",
"last_value",
"=",
"None",
"self",
".",
"domain_name",
"=",
"domain_name",
"self",
".",
"id",
"=",
"id",
"if",
"init_val",
"is",
"None",
":",
"init_val",
"=",
"fnc",
"(",
"init_val",
")",
"if",
"self",
".",
"id",
"is",
"None",
":",
"import",
"uuid",
"self",
".",
"id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"self",
".",
"item_type",
"=",
"type",
"(",
"fnc",
"(",
"None",
")",
")",
"self",
".",
"timestamp",
"=",
"None",
"# Allow us to pass in a full name to a function",
"if",
"isinstance",
"(",
"fnc",
",",
"six",
".",
"string_types",
")",
":",
"from",
"boto",
".",
"utils",
"import",
"find_class",
"fnc",
"=",
"find_class",
"(",
"fnc",
")",
"self",
".",
"fnc",
"=",
"fnc",
"# Bootstrap the value last",
"if",
"not",
"self",
".",
"val",
":",
"self",
".",
"val",
"=",
"init_val"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/sdb/db/sequence.py#L108-L154 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.