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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/foldpanelbar.py | python | FoldPanelItem.OnPressCaption | (self, event) | Handles the ``wx.EVT_CAPTIONBAR`` event for :class:`FoldPanelItem`.
:param `event`: a :class:`CaptionBarEvent` event to be processed. | Handles the ``wx.EVT_CAPTIONBAR`` event for :class:`FoldPanelItem`. | [
"Handles",
"the",
"wx",
".",
"EVT_CAPTIONBAR",
"event",
"for",
":",
"class",
":",
"FoldPanelItem",
"."
] | def OnPressCaption(self, event):
"""
Handles the ``wx.EVT_CAPTIONBAR`` event for :class:`FoldPanelItem`.
:param `event`: a :class:`CaptionBarEvent` event to be processed.
"""
# tell the upper container we are responsible
# for this event, so it can fold the panel item
# and do a refresh
event.SetTag(self)
event.Skip() | [
"def",
"OnPressCaption",
"(",
"self",
",",
"event",
")",
":",
"# tell the upper container we are responsible",
"# for this event, so it can fold the panel item",
"# and do a refresh",
"event",
".",
"SetTag",
"(",
"self",
")",
"event",
".",
"Skip",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/foldpanelbar.py#L1876-L1888 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/propgrid.py | python | PropertyGrid.AddToSelection | (*args, **kwargs) | return _propgrid.PropertyGrid_AddToSelection(*args, **kwargs) | AddToSelection(self, PGPropArg id) -> bool | AddToSelection(self, PGPropArg id) -> bool | [
"AddToSelection",
"(",
"self",
"PGPropArg",
"id",
")",
"-",
">",
"bool"
] | def AddToSelection(*args, **kwargs):
"""AddToSelection(self, PGPropArg id) -> bool"""
return _propgrid.PropertyGrid_AddToSelection(*args, **kwargs) | [
"def",
"AddToSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_AddToSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L2203-L2205 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/commands/search.py | python | transform_hits | (hits) | return list(packages.values()) | The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use. | The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use. | [
"The",
"list",
"from",
"pypi",
"is",
"really",
"a",
"list",
"of",
"versions",
".",
"We",
"want",
"a",
"list",
"of",
"packages",
"with",
"the",
"list",
"of",
"versions",
"stored",
"inline",
".",
"This",
"converts",
"the",
"list",
"from",
"pypi",
"into",
... | def transform_hits(hits):
"""
The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use.
"""
packages = OrderedDict()
for hit in hits:
name = hit['name']
summary = hit['summary']
version = hit['version']
if name not in packages.keys():
packages[name] = {
'name': name,
'summary': summary,
'versions': [version],
}
else:
packages[name]['versions'].append(version)
# if this is the highest version, replace summary and score
if version == highest_version(packages[name]['versions']):
packages[name]['summary'] = summary
return list(packages.values()) | [
"def",
"transform_hits",
"(",
"hits",
")",
":",
"packages",
"=",
"OrderedDict",
"(",
")",
"for",
"hit",
"in",
"hits",
":",
"name",
"=",
"hit",
"[",
"'name'",
"]",
"summary",
"=",
"hit",
"[",
"'summary'",
"]",
"version",
"=",
"hit",
"[",
"'version'",
... | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/commands/search.py#L69-L94 | |
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/processor/conversion/de2/nyan_subprocessor.py | python | DE2NyanSubprocessor.terrain_group_to_terrain | (terrain_group) | Creates raw API objects for a terrain group.
:param terrain_group: Terrain group that gets converted to a tech.
:type terrain_group: ..dataformat.converter_object.ConverterObjectGroup | Creates raw API objects for a terrain group. | [
"Creates",
"raw",
"API",
"objects",
"for",
"a",
"terrain",
"group",
"."
] | def terrain_group_to_terrain(terrain_group):
"""
Creates raw API objects for a terrain group.
:param terrain_group: Terrain group that gets converted to a tech.
:type terrain_group: ..dataformat.converter_object.ConverterObjectGroup
"""
terrain_index = terrain_group.get_id()
dataset = terrain_group.data
# name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version)
terrain_lookup_dict = internal_name_lookups.get_terrain_lookups(dataset.game_version)
terrain_type_lookup_dict = internal_name_lookups.get_terrain_type_lookups(dataset.game_version)
if terrain_index not in terrain_lookup_dict:
# TODO: Not all terrains are used in DE2; filter out the unused terrains
# in pre-processor
return
# Start with the Terrain object
terrain_name = terrain_lookup_dict[terrain_index][1]
raw_api_object = RawAPIObject(terrain_name, terrain_name,
dataset.nyan_api_objects)
raw_api_object.add_raw_parent("engine.util.terrain.Terrain")
obj_location = f"data/terrain/{terrain_lookup_dict[terrain_index][2]}/"
raw_api_object.set_location(obj_location)
raw_api_object.set_filename(terrain_lookup_dict[terrain_index][2])
terrain_group.add_raw_api_object(raw_api_object)
# =======================================================================
# Types
# =======================================================================
terrain_types = []
for terrain_type in terrain_type_lookup_dict.values():
if terrain_index in terrain_type[0]:
type_name = f"util.terrain_type.types.{terrain_type[2]}"
type_obj = dataset.pregen_nyan_objects[type_name].get_nyan_object()
terrain_types.append(type_obj)
raw_api_object.add_raw_member("types", terrain_types, "engine.util.terrain.Terrain")
# =======================================================================
# Name
# =======================================================================
name_ref = f"{terrain_name}.{terrain_name}Name"
name_raw_api_object = RawAPIObject(name_ref,
f"{terrain_name}Name",
dataset.nyan_api_objects)
name_raw_api_object.add_raw_parent("engine.util.language.translated.type.TranslatedString")
name_location = ForwardRef(terrain_group, terrain_name)
name_raw_api_object.set_location(name_location)
name_raw_api_object.add_raw_member("translations",
[],
"engine.util.language.translated.type.TranslatedString")
name_forward_ref = ForwardRef(terrain_group, name_ref)
raw_api_object.add_raw_member("name", name_forward_ref, "engine.util.terrain.Terrain")
terrain_group.add_raw_api_object(name_raw_api_object)
# =======================================================================
# Sound
# =======================================================================
sound_name = f"{terrain_name}.Sound"
sound_raw_api_object = RawAPIObject(sound_name, "Sound",
dataset.nyan_api_objects)
sound_raw_api_object.add_raw_parent("engine.util.sound.Sound")
sound_location = ForwardRef(terrain_group, terrain_name)
sound_raw_api_object.set_location(sound_location)
# TODO: Sounds
sounds = []
sound_raw_api_object.add_raw_member("play_delay",
0,
"engine.util.sound.Sound")
sound_raw_api_object.add_raw_member("sounds",
sounds,
"engine.util.sound.Sound")
sound_forward_ref = ForwardRef(terrain_group, sound_name)
raw_api_object.add_raw_member("sound",
sound_forward_ref,
"engine.util.terrain.Terrain")
terrain_group.add_raw_api_object(sound_raw_api_object)
# =======================================================================
# Ambience
# =======================================================================
terrain = terrain_group.get_terrain()
# ambients_count = terrain["terrain_units_used_count"].get_value()
ambience = []
# TODO: Ambience
# ===============================================================================
# for ambient_index in range(ambients_count):
# ambient_id = terrain["terrain_unit_id"][ambient_index].get_value()
#
# if ambient_id == -1:
# continue
#
# ambient_line = dataset.unit_ref[ambient_id]
# ambient_name = name_lookup_dict[ambient_line.get_head_unit_id()][0]
#
# ambient_ref = "%s.Ambient%s" % (terrain_name, str(ambient_index))
# ambient_raw_api_object = RawAPIObject(ambient_ref,
# "Ambient%s" % (str(ambient_index)),
# dataset.nyan_api_objects)
# ambient_raw_api_object.add_raw_parent("engine.util.terrain.TerrainAmbient")
# ambient_location = ForwardRef(terrain_group, terrain_name)
# ambient_raw_api_object.set_location(ambient_location)
#
# # Game entity reference
# ambient_line_forward_ref = ForwardRef(ambient_line, ambient_name)
# ambient_raw_api_object.add_raw_member("object",
# ambient_line_forward_ref,
# "engine.util.terrain.TerrainAmbient")
#
# # Max density
# max_density = terrain["terrain_unit_density"][ambient_index].get_value()
# ambient_raw_api_object.add_raw_member("max_density",
# max_density,
# "engine.util.terrain.TerrainAmbient")
#
# terrain_group.add_raw_api_object(ambient_raw_api_object)
# terrain_ambient_forward_ref = ForwardRef(terrain_group, ambient_ref)
# ambience.append(terrain_ambient_forward_ref)
# ===============================================================================
raw_api_object.add_raw_member("ambience", ambience, "engine.util.terrain.Terrain")
# =======================================================================
# Graphic
# =======================================================================
texture_id = terrain.get_id()
# Create animation object
graphic_name = f"{terrain_name}.TerrainTexture"
graphic_raw_api_object = RawAPIObject(graphic_name, "TerrainTexture",
dataset.nyan_api_objects)
graphic_raw_api_object.add_raw_parent("engine.util.graphics.Terrain")
graphic_location = ForwardRef(terrain_group, terrain_name)
graphic_raw_api_object.set_location(graphic_location)
if texture_id in dataset.combined_terrains.keys():
terrain_graphic = dataset.combined_terrains[texture_id]
else:
terrain_graphic = CombinedTerrain(texture_id,
f"texture_{terrain_lookup_dict[terrain_index][2]}",
dataset)
dataset.combined_terrains.update({terrain_graphic.get_id(): terrain_graphic})
terrain_graphic.add_reference(graphic_raw_api_object)
graphic_raw_api_object.add_raw_member("sprite", terrain_graphic,
"engine.util.graphics.Terrain")
terrain_group.add_raw_api_object(graphic_raw_api_object)
graphic_forward_ref = ForwardRef(terrain_group, graphic_name)
raw_api_object.add_raw_member("terrain_graphic", graphic_forward_ref,
"engine.util.terrain.Terrain") | [
"def",
"terrain_group_to_terrain",
"(",
"terrain_group",
")",
":",
"terrain_index",
"=",
"terrain_group",
".",
"get_id",
"(",
")",
"dataset",
"=",
"terrain_group",
".",
"data",
"# name_lookup_dict = internal_name_lookups.get_entity_lookups(dataset.game_version)",
"terrain_looku... | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/de2/nyan_subprocessor.py#L634-L798 | ||
borglab/gtsam | a5bee157efce6a0563704bce6a5d188c29817f39 | gtsam/3rdparty/GeographicLib/python/geographiclib/polygonarea.py | python | PolygonArea.Compute | (self, reverse = False, sign = True) | return self.num, perimeter, area | Compute the properties of the polygon
:param reverse: if true then clockwise (instead of
counter-clockwise) traversal counts as a positive area
:param sign: if true then return a signed result for the area if the
polygon is traversed in the "wrong" direction instead of returning
the area for the rest of the earth
:return: a tuple of number, perimeter (meters), area (meters^2)
If the object is a polygon (and not a polygon), the perimeter
includes the length of a final edge connecting the current point to
the initial point. If the object is a polyline, then area is nan.
More points can be added to the polygon after this call. | Compute the properties of the polygon | [
"Compute",
"the",
"properties",
"of",
"the",
"polygon"
] | def Compute(self, reverse = False, sign = True):
"""Compute the properties of the polygon
:param reverse: if true then clockwise (instead of
counter-clockwise) traversal counts as a positive area
:param sign: if true then return a signed result for the area if the
polygon is traversed in the "wrong" direction instead of returning
the area for the rest of the earth
:return: a tuple of number, perimeter (meters), area (meters^2)
If the object is a polygon (and not a polygon), the perimeter
includes the length of a final edge connecting the current point to
the initial point. If the object is a polyline, then area is nan.
More points can be added to the polygon after this call.
"""
if self.polyline: area = Math.nan
if self.num < 2:
perimeter = 0.0
if not self.polyline: area = 0.0
return self.num, perimeter, area
if self.polyline:
perimeter = self._perimetersum.Sum()
return self.num, perimeter, area
_, s12, _, _, _, _, _, _, _, S12 = self.earth._GenInverse(
self.lat1, self.lon1, self._lat0, self._lon0, self._mask)
perimeter = self._perimetersum.Sum(s12)
tempsum = Accumulator(self._areasum)
tempsum.Add(S12)
crossings = self._crossings + PolygonArea._transit(self.lon1, self._lon0)
if crossings & 1:
tempsum.Add( (1 if tempsum.Sum() < 0 else -1) * self.area0/2 )
# area is with the clockwise sense. If !reverse convert to
# counter-clockwise convention.
if not reverse: tempsum.Negate()
# If sign put area in (-area0/2, area0/2], else put area in [0, area0)
if sign:
if tempsum.Sum() > self.area0/2:
tempsum.Add( -self.area0 )
elif tempsum.Sum() <= -self.area0/2:
tempsum.Add( self.area0 )
else:
if tempsum.Sum() >= self.area0:
tempsum.Add( -self.area0 )
elif tempsum.Sum() < 0:
tempsum.Add( self.area0 )
area = 0.0 + tempsum.Sum()
return self.num, perimeter, area | [
"def",
"Compute",
"(",
"self",
",",
"reverse",
"=",
"False",
",",
"sign",
"=",
"True",
")",
":",
"if",
"self",
".",
"polyline",
":",
"area",
"=",
"Math",
".",
"nan",
"if",
"self",
".",
"num",
"<",
"2",
":",
"perimeter",
"=",
"0.0",
"if",
"not",
... | https://github.com/borglab/gtsam/blob/a5bee157efce6a0563704bce6a5d188c29817f39/gtsam/3rdparty/GeographicLib/python/geographiclib/polygonarea.py#L162-L213 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/ContactStructuralMechanicsApplication/python_scripts/custom_sympy_fe_utilities.py | python | DfjDxi | (DN,f) | return sympy_fe_utilities.DfjDxi(DN, f) | This method defines a gradient. This returns a matrix D such that D(i,j) = D(fj)/D(xi)
Keyword arguments:
DN -- The shape function derivatives
f-- The variable to compute the gradient | This method defines a gradient. This returns a matrix D such that D(i,j) = D(fj)/D(xi) | [
"This",
"method",
"defines",
"a",
"gradient",
".",
"This",
"returns",
"a",
"matrix",
"D",
"such",
"that",
"D",
"(",
"i",
"j",
")",
"=",
"D",
"(",
"fj",
")",
"/",
"D",
"(",
"xi",
")"
] | def DfjDxi(DN,f):
""" This method defines a gradient. This returns a matrix D such that D(i,j) = D(fj)/D(xi)
Keyword arguments:
DN -- The shape function derivatives
f-- The variable to compute the gradient
"""
return sympy_fe_utilities.DfjDxi(DN, f) | [
"def",
"DfjDxi",
"(",
"DN",
",",
"f",
")",
":",
"return",
"sympy_fe_utilities",
".",
"DfjDxi",
"(",
"DN",
",",
"f",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ContactStructuralMechanicsApplication/python_scripts/custom_sympy_fe_utilities.py#L131-L138 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/opsworks/layer1.py | python | OpsWorksConnection.describe_user_profiles | (self, iam_user_arns=None) | return self.make_request(action='DescribeUserProfiles',
body=json.dumps(params)) | Describe specified users.
**Required Permissions**: To use this action, an IAM user must
have an attached policy that explicitly grants permissions.
For more information on user permissions, see `Managing User
Permissions`_.
:type iam_user_arns: list
:param iam_user_arns: An array of IAM user ARNs that identify the users
to be described. | Describe specified users. | [
"Describe",
"specified",
"users",
"."
] | def describe_user_profiles(self, iam_user_arns=None):
"""
Describe specified users.
**Required Permissions**: To use this action, an IAM user must
have an attached policy that explicitly grants permissions.
For more information on user permissions, see `Managing User
Permissions`_.
:type iam_user_arns: list
:param iam_user_arns: An array of IAM user ARNs that identify the users
to be described.
"""
params = {}
if iam_user_arns is not None:
params['IamUserArns'] = iam_user_arns
return self.make_request(action='DescribeUserProfiles',
body=json.dumps(params)) | [
"def",
"describe_user_profiles",
"(",
"self",
",",
"iam_user_arns",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"iam_user_arns",
"is",
"not",
"None",
":",
"params",
"[",
"'IamUserArns'",
"]",
"=",
"iam_user_arns",
"return",
"self",
".",
"make_reque... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/opsworks/layer1.py#L1867-L1885 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py | python | RawTurtle.dot | (self, size=None, *color) | Draw a dot with diameter size, using color.
Optional arguments:
size -- an integer >= 1 (if given)
color -- a colorstring or a numeric color tuple
Draw a circular dot with diameter size, using color.
If size is not given, the maximum of pensize+4 and 2*pensize is used.
Example (for a Turtle instance named turtle):
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50) | Draw a dot with diameter size, using color. | [
"Draw",
"a",
"dot",
"with",
"diameter",
"size",
"using",
"color",
"."
] | def dot(self, size=None, *color):
"""Draw a dot with diameter size, using color.
Optional arguments:
size -- an integer >= 1 (if given)
color -- a colorstring or a numeric color tuple
Draw a circular dot with diameter size, using color.
If size is not given, the maximum of pensize+4 and 2*pensize is used.
Example (for a Turtle instance named turtle):
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
"""
#print "dot-1:", size, color
if not color:
if isinstance(size, (str, tuple)):
color = self._colorstr(size)
size = self._pensize + max(self._pensize, 4)
else:
color = self._pencolor
if not size:
size = self._pensize + max(self._pensize, 4)
else:
if size is None:
size = self._pensize + max(self._pensize, 4)
color = self._colorstr(color)
#print "dot-2:", size, color
if hasattr(self.screen, "_dot"):
item = self.screen._dot(self._position, size, color)
#print "dot:", size, color, "item:", item
self.items.append(item)
if self.undobuffer:
self.undobuffer.push(("dot", item))
else:
pen = self.pen()
if self.undobuffer:
self.undobuffer.push(["seq"])
self.undobuffer.cumulate = True
try:
if self.resizemode() == 'auto':
self.ht()
self.pendown()
self.pensize(size)
self.pencolor(color)
self.forward(0)
finally:
self.pen(pen)
if self.undobuffer:
self.undobuffer.cumulate = False | [
"def",
"dot",
"(",
"self",
",",
"size",
"=",
"None",
",",
"*",
"color",
")",
":",
"#print \"dot-1:\", size, color",
"if",
"not",
"color",
":",
"if",
"isinstance",
"(",
"size",
",",
"(",
"str",
",",
"tuple",
")",
")",
":",
"color",
"=",
"self",
".",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/turtle.py#L3215-L3264 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pathlib2/pathlib2/__init__.py | python | PurePath.as_uri | (self) | return self._flavour.make_uri(self) | Return the path as a 'file' URI. | Return the path as a 'file' URI. | [
"Return",
"the",
"path",
"as",
"a",
"file",
"URI",
"."
] | def as_uri(self):
"""Return the path as a 'file' URI."""
if not self.is_absolute():
raise ValueError("relative path can't be expressed as a file URI")
return self._flavour.make_uri(self) | [
"def",
"as_uri",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_absolute",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"relative path can't be expressed as a file URI\"",
")",
"return",
"self",
".",
"_flavour",
".",
"make_uri",
"(",
"self",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pathlib2/pathlib2/__init__.py#L971-L975 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Utilities/RelMon/python/utils.py | python | get_relval_version | (file) | Returns tuple (CMSSW version, run version) for specified file. | Returns tuple (CMSSW version, run version) for specified file. | [
"Returns",
"tuple",
"(",
"CMSSW",
"version",
"run",
"version",
")",
"for",
"specified",
"file",
"."
] | def get_relval_version(file):
"""Returns tuple (CMSSW version, run version) for specified file."""
cmssw_version = re.findall('DQM_V(\d*)_', file)
run_version = re.findall('CMSSW_\d*_\d*_\d*(?:_[\w\d]*)?-[\w\d]*_V\d*\w?(?:_[\w\d]*)?-v(\d*)__', file)
if cmssw_version and run_version:
return (int(cmssw_version[0]), int(run_version[0])) | [
"def",
"get_relval_version",
"(",
"file",
")",
":",
"cmssw_version",
"=",
"re",
".",
"findall",
"(",
"'DQM_V(\\d*)_'",
",",
"file",
")",
"run_version",
"=",
"re",
".",
"findall",
"(",
"'CMSSW_\\d*_\\d*_\\d*(?:_[\\w\\d]*)?-[\\w\\d]*_V\\d*\\w?(?:_[\\w\\d]*)?-v(\\d*)__'",
... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Utilities/RelMon/python/utils.py#L525-L530 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/grappler/controller.py | python | Controller.get_placements | (self, *args, **kwargs) | Returns: Two TF ops.
Args:
*args: "".
**kwargs: "".
Returns:
y_preds: tensor of size [batch_size, num_ops]
log_probs: python dict of at least two fields: "sample", "target" each
containing a tensor of size [batch_size], corresponding to the log_probs. | Returns: Two TF ops. | [
"Returns",
":",
"Two",
"TF",
"ops",
"."
] | def get_placements(self, *args, **kwargs):
"""Returns: Two TF ops.
Args:
*args: "".
**kwargs: "".
Returns:
y_preds: tensor of size [batch_size, num_ops]
log_probs: python dict of at least two fields: "sample", "target" each
containing a tensor of size [batch_size], corresponding to the log_probs.
"""
raise NotImplementedError | [
"def",
"get_placements",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/grappler/controller.py#L95-L107 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | current/deps/v8/third_party/jinja2/utils.py | python | LRUCache.setdefault | (self, key, default=None) | Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key. | Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key. | [
"Set",
"default",
"if",
"the",
"key",
"is",
"not",
"in",
"the",
"cache",
"otherwise",
"leave",
"unchanged",
".",
"Return",
"the",
"value",
"of",
"this",
"key",
"."
] | def setdefault(self, key, default=None):
"""Set `default` if the key is not in the cache otherwise
leave unchanged. Return the value of this key.
"""
self._wlock.acquire()
try:
try:
return self[key]
except KeyError:
self[key] = default
return default
finally:
self._wlock.release() | [
"def",
"setdefault",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"self",
".",
"_wlock",
".",
"acquire",
"(",
")",
"try",
":",
"try",
":",
"return",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"self",
"[",
"key",
"]",
"... | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/utils.py#L355-L367 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Script/SConsOptions.py | python | SConsIndentedHelpFormatter.format_heading | (self, heading) | return optparse.IndentedHelpFormatter.format_heading(self, heading) | This translates any heading of "options" or "Options" into
"SCons Options." Unfortunately, we have to do this here,
because those titles are hard-coded in the optparse calls. | This translates any heading of "options" or "Options" into
"SCons Options." Unfortunately, we have to do this here,
because those titles are hard-coded in the optparse calls. | [
"This",
"translates",
"any",
"heading",
"of",
"options",
"or",
"Options",
"into",
"SCons",
"Options",
".",
"Unfortunately",
"we",
"have",
"to",
"do",
"this",
"here",
"because",
"those",
"titles",
"are",
"hard",
"-",
"coded",
"in",
"the",
"optparse",
"calls",... | def format_heading(self, heading):
"""
This translates any heading of "options" or "Options" into
"SCons Options." Unfortunately, we have to do this here,
because those titles are hard-coded in the optparse calls.
"""
if heading == 'Options':
heading = "SCons Options"
return optparse.IndentedHelpFormatter.format_heading(self, heading) | [
"def",
"format_heading",
"(",
"self",
",",
"heading",
")",
":",
"if",
"heading",
"==",
"'Options'",
":",
"heading",
"=",
"\"SCons Options\"",
"return",
"optparse",
".",
"IndentedHelpFormatter",
".",
"format_heading",
"(",
"self",
",",
"heading",
")"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Script/SConsOptions.py#L430-L438 | |
bairdzhang/smallhardface | 76fa1d87a9602d9b13d7a7fe693fc7aec91cab80 | caffe/scripts/cpp_lint.py | python | CleanseComments | (line) | return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed. | Removes //-comments and single-line C-style /* */ comments. | [
"Removes",
"//",
"-",
"comments",
"and",
"single",
"-",
"line",
"C",
"-",
"style",
"/",
"*",
"*",
"/",
"comments",
"."
] | def CleanseComments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
commentpos = line.find('//')
if commentpos != -1 and not IsCppString(line[:commentpos]):
line = line[:commentpos].rstrip()
# get rid of /* ... */
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | [
"def",
"CleanseComments",
"(",
"line",
")",
":",
"commentpos",
"=",
"line",
".",
"find",
"(",
"'//'",
")",
"if",
"commentpos",
"!=",
"-",
"1",
"and",
"not",
"IsCppString",
"(",
"line",
"[",
":",
"commentpos",
"]",
")",
":",
"line",
"=",
"line",
"[",
... | https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/caffe/scripts/cpp_lint.py#L1171-L1184 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/compatibility/ast_edits.py | python | PastaAnalyzeVisitor.visit_ImportFrom | (self, node) | Handle visiting an import-from node in the AST.
Args:
node: Current Node | Handle visiting an import-from node in the AST. | [
"Handle",
"visiting",
"an",
"import",
"-",
"from",
"node",
"in",
"the",
"AST",
"."
] | def visit_ImportFrom(self, node): # pylint: disable=invalid-name
"""Handle visiting an import-from node in the AST.
Args:
node: Current Node
"""
if not node.module:
self.generic_visit(node)
return
from_import = node.module
for import_alias in node.names:
# Detect based on full import name(to & as)
full_module_name = "%s.%s" % (from_import, import_alias.name)
full_import = (full_module_name, import_alias.asname)
detection = (self._api_analysis_spec
.imports_to_detect.get(full_import, None))
if detection:
self.add_result(detection)
self.add_log(
detection.log_level, node.lineno, node.col_offset,
detection.log_message)
self.generic_visit(node) | [
"def",
"visit_ImportFrom",
"(",
"self",
",",
"node",
")",
":",
"# pylint: disable=invalid-name",
"if",
"not",
"node",
".",
"module",
":",
"self",
".",
"generic_visit",
"(",
"node",
")",
"return",
"from_import",
"=",
"node",
".",
"module",
"for",
"import_alias"... | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/compatibility/ast_edits.py#L849-L873 | ||
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | utils/vim-lldb/python-vim-lldb/vim_panes.py | python | FrameKeyValuePane.format_pair | (self, key, value, changed=False) | return "%s %s = %s\n" % (marker, key, value) | Formats a key/value pair. Appends a '*' if changed == True | Formats a key/value pair. Appends a '*' if changed == True | [
"Formats",
"a",
"key",
"/",
"value",
"pair",
".",
"Appends",
"a",
"*",
"if",
"changed",
"==",
"True"
] | def format_pair(self, key, value, changed=False):
""" Formats a key/value pair. Appends a '*' if changed == True """
marker = '*' if changed else ' '
return "%s %s = %s\n" % (marker, key, value) | [
"def",
"format_pair",
"(",
"self",
",",
"key",
",",
"value",
",",
"changed",
"=",
"False",
")",
":",
"marker",
"=",
"'*'",
"if",
"changed",
"else",
"' '",
"return",
"\"%s %s = %s\\n\"",
"%",
"(",
"marker",
",",
"key",
",",
"value",
")"
] | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/utils/vim-lldb/python-vim-lldb/vim_panes.py#L421-L424 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Image.SetAlphaData | (*args, **kwargs) | return _core_.Image_SetAlphaData(*args, **kwargs) | SetAlphaData(self, buffer alpha)
Resets the Image's alpha data from a buffer of bytes. Accepts either
a string or a buffer object holding the data and the length of the
data must be width*height. | SetAlphaData(self, buffer alpha) | [
"SetAlphaData",
"(",
"self",
"buffer",
"alpha",
")"
] | def SetAlphaData(*args, **kwargs):
"""
SetAlphaData(self, buffer alpha)
Resets the Image's alpha data from a buffer of bytes. Accepts either
a string or a buffer object holding the data and the length of the
data must be width*height.
"""
return _core_.Image_SetAlphaData(*args, **kwargs) | [
"def",
"SetAlphaData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Image_SetAlphaData",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L3403-L3411 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/shutil.py | python | copy | (src, dst) | Copy data and mode bits ("cp src dst").
The destination may be a directory. | Copy data and mode bits ("cp src dst"). | [
"Copy",
"data",
"and",
"mode",
"bits",
"(",
"cp",
"src",
"dst",
")",
"."
] | def copy(src, dst):
"""Copy data and mode bits ("cp src dst").
The destination may be a directory.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
copyfile(src, dst)
copymode(src, dst) | [
"def",
"copy",
"(",
"src",
",",
"dst",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dst",
")",
":",
"dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"os",
".",
"path",
".",
"basename",
"(",
"src",
")",
")",
"copyfile",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/shutil.py#L111-L120 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/gather/skeleton_gatherer.py | python | SkeletonGatherer._AddNontranslateableChunk | (self, chunk) | Adds a nontranslateable chunk. | Adds a nontranslateable chunk. | [
"Adds",
"a",
"nontranslateable",
"chunk",
"."
] | def _AddNontranslateableChunk(self, chunk):
'''Adds a nontranslateable chunk.'''
if self.single_message_:
ph = tclib.Placeholder('XX%02dXX' % self.ph_counter_, chunk, chunk)
self.ph_counter_ += 1
self.single_message_.AppendPlaceholder(ph)
else:
self.skeleton_.append(chunk) | [
"def",
"_AddNontranslateableChunk",
"(",
"self",
",",
"chunk",
")",
":",
"if",
"self",
".",
"single_message_",
":",
"ph",
"=",
"tclib",
".",
"Placeholder",
"(",
"'XX%02dXX'",
"%",
"self",
".",
"ph_counter_",
",",
"chunk",
",",
"chunk",
")",
"self",
".",
... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/gather/skeleton_gatherer.py#L104-L111 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/html.py | python | HtmlDCRenderer.__init__ | (self, *args, **kwargs) | __init__(self) -> HtmlDCRenderer | __init__(self) -> HtmlDCRenderer | [
"__init__",
"(",
"self",
")",
"-",
">",
"HtmlDCRenderer"
] | def __init__(self, *args, **kwargs):
"""__init__(self) -> HtmlDCRenderer"""
_html.HtmlDCRenderer_swiginit(self,_html.new_HtmlDCRenderer(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_html",
".",
"HtmlDCRenderer_swiginit",
"(",
"self",
",",
"_html",
".",
"new_HtmlDCRenderer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L1224-L1226 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | tools/sampcd_processor.py | python | get_api_md5 | (path) | return api_md5 | read the api spec file, and scratch the md5sum value of every api's docstring.
Args:
path: the api spec file. ATTENTION the path relative
Returns:
api_md5(dict): key is the api's real fullname, value is the md5sum. | read the api spec file, and scratch the md5sum value of every api's docstring. | [
"read",
"the",
"api",
"spec",
"file",
"and",
"scratch",
"the",
"md5sum",
"value",
"of",
"every",
"api",
"s",
"docstring",
"."
] | def get_api_md5(path):
"""
read the api spec file, and scratch the md5sum value of every api's docstring.
Args:
path: the api spec file. ATTENTION the path relative
Returns:
api_md5(dict): key is the api's real fullname, value is the md5sum.
"""
api_md5 = {}
API_spec = os.path.abspath(os.path.join(os.getcwd(), "..", path))
if not os.path.isfile(API_spec):
return api_md5
pat = re.compile(r'\((paddle[^,]+)\W*document\W*([0-9a-z]{32})')
patArgSpec = re.compile(
r'^(paddle[^,]+)\s+\(ArgSpec.*document\W*([0-9a-z]{32})')
with open(API_spec) as f:
for line in f.readlines():
mo = pat.search(line)
if not mo:
mo = patArgSpec.search(line)
if mo:
api_md5[mo.group(1)] = mo.group(2)
return api_md5 | [
"def",
"get_api_md5",
"(",
"path",
")",
":",
"api_md5",
"=",
"{",
"}",
"API_spec",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"\"..\"",
",",
"path",
")",
")",
"if",
"not... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/tools/sampcd_processor.py#L470-L494 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/grit/grit/tool/diff_structures.py | python | DiffStructures.MakeStaticTranslation | (self, original_filename, encoding) | return fname | Given the name of the structure type (self.structure_type), the filename
of the file holding the original structure, and optionally the "section" key
identifying the part of the file to look at (self.section), creates a
temporary file holding a "static" translation of the original structure
(i.e. one where all translateable parts have been replaced with "TTTTTT")
and returns the temporary file name. It is the caller's responsibility to
delete the file when finished.
Args:
original_filename: 'c:\\bingo\\bla.rc'
Return:
'c:\\temp\\werlkjsdf334.tmp' | Given the name of the structure type (self.structure_type), the filename
of the file holding the original structure, and optionally the "section" key
identifying the part of the file to look at (self.section), creates a
temporary file holding a "static" translation of the original structure
(i.e. one where all translateable parts have been replaced with "TTTTTT")
and returns the temporary file name. It is the caller's responsibility to
delete the file when finished. | [
"Given",
"the",
"name",
"of",
"the",
"structure",
"type",
"(",
"self",
".",
"structure_type",
")",
"the",
"filename",
"of",
"the",
"file",
"holding",
"the",
"original",
"structure",
"and",
"optionally",
"the",
"section",
"key",
"identifying",
"the",
"part",
... | def MakeStaticTranslation(self, original_filename, encoding):
"""Given the name of the structure type (self.structure_type), the filename
of the file holding the original structure, and optionally the "section" key
identifying the part of the file to look at (self.section), creates a
temporary file holding a "static" translation of the original structure
(i.e. one where all translateable parts have been replaced with "TTTTTT")
and returns the temporary file name. It is the caller's responsibility to
delete the file when finished.
Args:
original_filename: 'c:\\bingo\\bla.rc'
Return:
'c:\\temp\\werlkjsdf334.tmp'
"""
original = structure._GATHERERS[self.structure_type](original_filename,
extkey=self.section,
encoding=encoding)
original.Parse()
translated = original.Translate(constants.CONSTANT_LANGUAGE, False)
fname = tempfile.mktemp()
with util.WrapOutputStream(open(fname, 'w')) as writer:
writer.write("Original filename: %s\n=============\n\n"
% original_filename)
writer.write(translated) # write in UTF-8
return fname | [
"def",
"MakeStaticTranslation",
"(",
"self",
",",
"original_filename",
",",
"encoding",
")",
":",
"original",
"=",
"structure",
".",
"_GATHERERS",
"[",
"self",
".",
"structure_type",
"]",
"(",
"original_filename",
",",
"extkey",
"=",
"self",
".",
"section",
",... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/tool/diff_structures.py#L87-L114 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/closure_linter/closure_linter/statetracker.py | python | StateTracker.InObjectLiteralDescendant | (self) | return self.OBJECT_LITERAL in self._block_types | Returns true if the current token has an object literal ancestor.
Returns:
True if the current token has an object literal ancestor. | Returns true if the current token has an object literal ancestor. | [
"Returns",
"true",
"if",
"the",
"current",
"token",
"has",
"an",
"object",
"literal",
"ancestor",
"."
] | def InObjectLiteralDescendant(self):
"""Returns true if the current token has an object literal ancestor.
Returns:
True if the current token has an object literal ancestor.
"""
return self.OBJECT_LITERAL in self._block_types | [
"def",
"InObjectLiteralDescendant",
"(",
"self",
")",
":",
"return",
"self",
".",
"OBJECT_LITERAL",
"in",
"self",
".",
"_block_types"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/statetracker.py#L685-L691 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/settings_manager.py | python | apply_optional_callback | (default_value, attribute) | Given a default value, see if it references an attribute callback or not and apply the callback result if so.
Otherwise accept the default value as is
:param default_value: The default value to return or apply the callback for the result
:param attribute: The name of the attribute to apply the value to
:return: The processed value | Given a default value, see if it references an attribute callback or not and apply the callback result if so.
Otherwise accept the default value as is
:param default_value: The default value to return or apply the callback for the result
:param attribute: The name of the attribute to apply the value to
:return: The processed value | [
"Given",
"a",
"default",
"value",
"see",
"if",
"it",
"references",
"an",
"attribute",
"callback",
"or",
"not",
"and",
"apply",
"the",
"callback",
"result",
"if",
"so",
".",
"Otherwise",
"accept",
"the",
"default",
"value",
"as",
"is",
":",
"param",
"defaul... | def apply_optional_callback(default_value, attribute):
"""
Given a default value, see if it references an attribute callback or not and apply the callback result if so.
Otherwise accept the default value as is
:param default_value: The default value to return or apply the callback for the result
:param attribute: The name of the attribute to apply the value to
:return: The processed value
"""
if isinstance(default_value, str) and default_value.startswith('@'):
value = default_value[1:].strip()
if not value.startswith('@'):
value_callback = value
if value_callback not in AUTO_DEFAULT_VALUE_CALLBACKS:
raise Errors.WafError("Attribute '{}' in the default settings file does not have a registered callback function '{}}'".format(attribute, value_callback))
value = AUTO_DEFAULT_VALUE_CALLBACKS[value_callback](attribute)
return value
else:
return default_value | [
"def",
"apply_optional_callback",
"(",
"default_value",
",",
"attribute",
")",
":",
"if",
"isinstance",
"(",
"default_value",
",",
"str",
")",
"and",
"default_value",
".",
"startswith",
"(",
"'@'",
")",
":",
"value",
"=",
"default_value",
"[",
"1",
":",
"]",... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/settings_manager.py#L87-L104 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py3/setuptools/package_index.py | python | PackageIndex.fetch | (self, requirement, tmpdir, force_scan=False, source=False) | return None | Obtain a file suitable for fulfilling `requirement`
DEPRECATED; use the ``fetch_distribution()`` method now instead. For
backward compatibility, this routine is identical but returns the
``location`` of the downloaded distribution instead of a distribution
object. | Obtain a file suitable for fulfilling `requirement` | [
"Obtain",
"a",
"file",
"suitable",
"for",
"fulfilling",
"requirement"
] | def fetch(self, requirement, tmpdir, force_scan=False, source=False):
"""Obtain a file suitable for fulfilling `requirement`
DEPRECATED; use the ``fetch_distribution()`` method now instead. For
backward compatibility, this routine is identical but returns the
``location`` of the downloaded distribution instead of a distribution
object.
"""
dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
if dist is not None:
return dist.location
return None | [
"def",
"fetch",
"(",
"self",
",",
"requirement",
",",
"tmpdir",
",",
"force_scan",
"=",
"False",
",",
"source",
"=",
"False",
")",
":",
"dist",
"=",
"self",
".",
"fetch_distribution",
"(",
"requirement",
",",
"tmpdir",
",",
"force_scan",
",",
"source",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/package_index.py#L657-L668 | |
rdkit/rdkit | ede860ae316d12d8568daf5ee800921c3389c84e | rdkit/Chem/PyMol.py | python | MolViewer.GetSelectedAtoms | (self, whichSelection=None) | return items | returns the selected atoms | returns the selected atoms | [
"returns",
"the",
"selected",
"atoms"
] | def GetSelectedAtoms(self, whichSelection=None):
" returns the selected atoms "
if not whichSelection:
sels = self.server.getNames('selections')
if sels:
whichSelection = sels[-1]
else:
whichSelection = None
if whichSelection:
items = self.server.index(whichSelection)
else:
items = []
return items | [
"def",
"GetSelectedAtoms",
"(",
"self",
",",
"whichSelection",
"=",
"None",
")",
":",
"if",
"not",
"whichSelection",
":",
"sels",
"=",
"self",
".",
"server",
".",
"getNames",
"(",
"'selections'",
")",
"if",
"sels",
":",
"whichSelection",
"=",
"sels",
"[",
... | https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/PyMol.py#L112-L124 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/src/robotsim.py | python | Appearance.set | (self, arg2) | return _robotsim.Appearance_set(self, arg2) | set(Appearance self, Appearance arg2)
Copies the appearance of the argument into this appearance. | set(Appearance self, Appearance arg2) | [
"set",
"(",
"Appearance",
"self",
"Appearance",
"arg2",
")"
] | def set(self, arg2):
"""
set(Appearance self, Appearance arg2)
Copies the appearance of the argument into this appearance.
"""
return _robotsim.Appearance_set(self, arg2) | [
"def",
"set",
"(",
"self",
",",
"arg2",
")",
":",
"return",
"_robotsim",
".",
"Appearance_set",
"(",
"self",
",",
"arg2",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/robotsim.py#L2561-L2570 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | distrib/all/subprocess.py | python | Popen.__init__ | (self, args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0) | Create new Popen instance. | Create new Popen instance. | [
"Create",
"new",
"Popen",
"instance",
"."
] | def __init__(self, args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0):
"""Create new Popen instance."""
_cleanup()
if mswindows:
if preexec_fn is not None:
raise ValueError("preexec_fn is not supported on Windows "
"platforms")
if close_fds:
raise ValueError("close_fds is not supported on Windows "
"platforms")
else:
# POSIX
if startupinfo is not None:
raise ValueError("startupinfo is only supported on Windows "
"platforms")
if creationflags != 0:
raise ValueError("creationflags is only supported on Windows "
"platforms")
self.stdin = None
self.stdout = None
self.stderr = None
self.pid = None
self.returncode = None
self.universal_newlines = universal_newlines
# Input and output objects. The general principle is like
# this:
#
# Parent Child
# ------ -----
# p2cwrite ---stdin---> p2cread
# c2pread <--stdout--- c2pwrite
# errread <--stderr--- errwrite
#
# On POSIX, the child objects are file descriptors. On
# Windows, these are Windows file handles. The parent objects
# are file descriptors on both platforms. The parent objects
# are None when not using PIPEs. The child objects are None
# when not redirecting.
(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
self._execute_child(args, executable, preexec_fn, close_fds,
cwd, env, universal_newlines,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
if p2cwrite:
self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
if c2pread:
if universal_newlines:
self.stdout = os.fdopen(c2pread, 'rU', bufsize)
else:
self.stdout = os.fdopen(c2pread, 'rb', bufsize)
if errread:
if universal_newlines:
self.stderr = os.fdopen(errread, 'rU', bufsize)
else:
self.stderr = os.fdopen(errread, 'rb', bufsize)
_active.append(self) | [
"def",
"__init__",
"(",
"self",
",",
"args",
",",
"bufsize",
"=",
"0",
",",
"executable",
"=",
"None",
",",
"stdin",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"preexec_fn",
"=",
"None",
",",
"close_fds",
"=",
"False",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/distrib/all/subprocess.py#L500-L570 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/ops/_grad/grad_nn_ops.py | python | get_bprop_prelu | (self) | return bprop | Grad definition for `PReLU` operation. | Grad definition for `PReLU` operation. | [
"Grad",
"definition",
"for",
"PReLU",
"operation",
"."
] | def get_bprop_prelu(self):
"""Grad definition for `PReLU` operation."""
grad = G.PReLUGrad()
def bprop(x, w, out, dout):
dx, dw = grad(dout, x, w)
return dx, dw
return bprop | [
"def",
"get_bprop_prelu",
"(",
"self",
")",
":",
"grad",
"=",
"G",
".",
"PReLUGrad",
"(",
")",
"def",
"bprop",
"(",
"x",
",",
"w",
",",
"out",
",",
"dout",
")",
":",
"dx",
",",
"dw",
"=",
"grad",
"(",
"dout",
",",
"x",
",",
"w",
")",
"return"... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_grad/grad_nn_ops.py#L899-L907 | |
jubatus/jubatus | 1251ce551bac980488a6313728e72b3fe0b79a9f | tools/codestyle/cpplint/cpplint.py | python | CheckSpacing | (filename, clean_lines, linenum, error) | Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
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. | Checks for the correctness of various spacing issues in the code. | [
"Checks",
"for",
"the",
"correctness",
"of",
"various",
"spacing",
"issues",
"in",
"the",
"code",
"."
] | def CheckSpacing(filename, clean_lines, linenum, error):
"""Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
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.
"""
raw = clean_lines.raw_lines
line = raw[linenum]
# Before nixing comments, check if the line is blank for no good
# reason. This includes the first line after a block is opened, and
# blank lines at the end of a function (ie, right before a line like '}'
if IsBlankLine(line):
elided = clean_lines.elided
prev_line = elided[linenum - 1]
prevbrace = prev_line.rfind('{')
# TODO(unknown): Don't complain if line before blank line, and line after,
# both start with alnums and are indented the same amount.
# This ignores whitespace at the start of a namespace block
# because those are not usually indented.
if (prevbrace != -1 and prev_line[prevbrace:].find('}') == -1
and prev_line[:prevbrace].find('namespace') == -1):
# OK, we have a blank line at the start of a code block. Before we
# complain, we check if it is an exception to the rule: The previous
# non-empty line has the parameters of a function header that are indented
# 4 spaces (because they did not fit in a 80 column line when placed on
# the same line as the function name). We also check for the case where
# the previous line is indented 6 spaces, which may happen when the
# initializers of a constructor do not fit into a 80 column line.
exception = False
if Match(r' {6}\w', prev_line): # Initializer list?
# We are looking for the opening column of initializer list, which
# should be indented 4 spaces to cause 6 space indentation afterwards.
search_position = linenum-2
while (search_position >= 0
and Match(r' {6}\w', elided[search_position])):
search_position -= 1
exception = (search_position >= 0
and elided[search_position][:5] == ' :')
else:
# Search for the function arguments or an initializer list. We use a
# simple heuristic here: If the line is indented 4 spaces; and we have a
# closing paren, without the opening paren, followed by an opening brace
# or colon (for initializer lists) we assume that it is the last line of
# a function header. If we have a colon indented 4 spaces, it is an
# initializer list.
exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
prev_line)
or Match(r' {4}:', prev_line))
if not exception:
error(filename, linenum, 'whitespace/blank_line', 2,
'Blank line at the start of a code block. Is this needed?')
# This doesn't ignore whitespace at the end of a namespace block
# because that is too hard without pairing open/close braces;
# however, a special exception is made for namespace closing
# brackets which have a comment containing "namespace".
#
# Also, ignore blank lines at the end of a block in a long if-else
# chain, like this:
# if (condition1) {
# // Something followed by a blank line
#
# } else if (condition2) {
# // Something else
# }
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
if (next_line
and Match(r'\s*}', next_line)
and next_line.find('namespace') == -1
and next_line.find('} else ') == -1):
error(filename, linenum, 'whitespace/blank_line', 3,
'Blank line at the end of a code block. Is this needed?')
matched = Match(r'\s*(public|protected|private):', prev_line)
if matched:
error(filename, linenum, 'whitespace/blank_line', 3,
'Do not leave a blank line after "%s:"' % matched.group(1))
# Next, we complain if there's a comment too near the text
commentpos = line.find('//')
if commentpos != -1:
# Check if the // may be in quotes. If so, ignore it
# Comparisons made explicit for clarity -- pylint: disable-msg=C6403
if (line.count('"', 0, commentpos) -
line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
# Allow one space for new scopes, two spaces otherwise:
if (not Match(r'^\s*{ //', line) and
((commentpos >= 1 and
line[commentpos-1] not in string.whitespace) or
(commentpos >= 2 and
line[commentpos-2] not in string.whitespace))):
error(filename, linenum, 'whitespace/comments', 2,
'At least two spaces is best between code and comments')
# There should always be a space between the // and the comment
commentend = commentpos + 2
if commentend < len(line) and not line[commentend] == ' ':
# but some lines are exceptions -- e.g. if they're big
# comment delimiters like:
# //----------------------------------------------------------
# or are an empty C++ style Doxygen comment, like:
# ///
# or they begin with multiple slashes followed by a space:
# //////// Header comment
match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
Search(r'^/$', line[commentend:]) or
Search(r'^/+ ', line[commentend:]))
if not match:
error(filename, linenum, 'whitespace/comments', 4,
'Should have a space between // and comment')
CheckComment(line[commentpos:], filename, linenum, error)
line = clean_lines.elided[linenum] # get rid of comments and strings
# Don't try to do spacing checks for operator methods
line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
# We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
# Otherwise not. Note we only check for non-spaces on *both* sides;
# sometimes people put non-spaces on one side when aligning ='s among
# many lines (not that this is behavior that I approve of...)
if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while|catch) ', line):
error(filename, linenum, 'whitespace/operators', 4,
'Missing spaces around =')
# It's ok not to have spaces around binary operators like + - * /, but if
# there's too little whitespace, we get concerned. It's hard to tell,
# though, so we punt on this one for now. TODO.
# You should always have whitespace around binary operators.
# Alas, we can't test < or > because they're legitimately used sans spaces
# (a->b, vector<int> a). The only time we can tell is a < with no >, and
# only if it's not template params list spilling into the next line.
match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
if not match:
# Note that while it seems that the '<[^<]*' term in the following
# regexp could be simplified to '<.*', which would indeed match
# the same class of strings, the [^<] means that searching for the
# regexp takes linear rather than quadratic time.
if not Search(r'<[^<]*,\s*$', line): # template params spill
match = Search(r'[^<>=!\s](<)[^<>=!\s]([^>]|->)*$', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around %s' % match.group(1))
# We allow no-spaces around << and >> when used like this: 10<<20, but
# not otherwise (particularly, not when used as streams)
match = Search(r'[^0-9\s](<<|>>)[^0-9\s]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around %s' % match.group(1))
# There shouldn't be space around unary operators
match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
if match:
error(filename, linenum, 'whitespace/operators', 4,
'Extra space for operator %s' % match.group(1))
# A pet peeve of mine: no spaces after an if, while, switch, or for
match = Search(r' (if\(|for\(|while\(|switch\()', line)
if match:
error(filename, linenum, 'whitespace/parens', 5,
'Missing space before ( in %s' % match.group(1))
# For if/for/while/switch, the left and right parens should be
# consistent about how many spaces are inside the parens, and
# there should either be zero or one spaces inside the parens.
# We don't want: "if ( foo)" or "if ( foo )".
# Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
match = Search(r'\b(if|for|while|switch)\s*'
r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
line)
if match:
if len(match.group(2)) != len(match.group(4)):
if not (match.group(3) == ';' and
len(match.group(2)) == 1 + len(match.group(4)) or
not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
error(filename, linenum, 'whitespace/parens', 5,
'Mismatching spaces inside () in %s' % match.group(1))
if not len(match.group(2)) in [0, 1]:
error(filename, linenum, 'whitespace/parens', 5,
'Should have zero or one spaces inside ( and ) in %s' %
match.group(1))
# You should always have a space after a comma (either as fn arg or operator)
if Search(r',[^\s]', line):
error(filename, linenum, 'whitespace/comma', 3,
'Missing space after ,')
# You should always have a space after a semicolon
# except for few corner cases
# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
# space after ;
if Search(r';[^\s};\\)/]', line):
error(filename, linenum, 'whitespace/semicolon', 3,
'Missing space after ;')
# Next we will look for issues with function calls.
CheckSpacingForFunctionCall(filename, line, linenum, error)
# Except after an opening paren, or after another opening brace (in case of
# an initializer list, for instance), you should have spaces before your
# braces. And since you should never have braces at the beginning of a line,
# this is an easy test.
if Search(r'[^ ({]{', line):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before {')
# Make sure '} else {' has spaces.
if Search(r'}else', line):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before else')
# You shouldn't have spaces before your brackets, except maybe after
# 'delete []' or 'new char * []'.
if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
error(filename, linenum, 'whitespace/braces', 5,
'Extra space before [')
# You shouldn't have a space before a semicolon at the end of the line.
# There's a special case for "for" since the style guide allows space before
# the semicolon there.
if Search(r':\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Semicolon defining empty statement. Use { } instead.')
elif Search(r'^\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Line contains only semicolon. If this should be an empty statement, '
'use { } instead.')
elif (Search(r'\s+;\s*$', line) and
not Search(r'\bfor\b', line)):
error(filename, linenum, 'whitespace/semicolon', 5,
'Extra space before last semicolon. If this should be an empty '
'statement, use { } instead.') | [
"def",
"CheckSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"raw",
"=",
"clean_lines",
".",
"raw_lines",
"line",
"=",
"raw",
"[",
"linenum",
"]",
"# Before nixing comments, check if the line is blank for no good",
"# reason. Th... | https://github.com/jubatus/jubatus/blob/1251ce551bac980488a6313728e72b3fe0b79a9f/tools/codestyle/cpplint/cpplint.py#L1687-L1930 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | documentation/doxygen/converttonotebook.py | python | processmain | (text) | return text, argumentsCell | Evaluates whether the main function returns a TCanvas or requires input. If it
does then the keepfunction flag is True, meaning the function wont be extracted
by cppFunction. If the initial condition is true then an extra cell is added
before at the end that calls the main function is returned, and added later.
>>> processmain('''void function(){
... content of function
... spanning several
... lines
... }''')
('void function(){\\n content of function\\n spanning several\\n lines\\n}', '')
>>> processmain('''void function(arguments = values){
... content of function
... spanning several
... lines
... }''')
('void function(arguments = values){\\n content of function\\n spanning several\\n lines\\n}', '# <markdowncell> \\n Arguments are defined. \\n# <codecell>\\narguments = values;\\n# <codecell>\\n')
>>> processmain('''void function(argument1 = value1, //comment 1
... argument2 = value2 /*comment 2*/ ,
... argument3 = value3,
... argument4 = value4)
... {
... content of function
... spanning several
... lines
... }''')
('void function(argument1 = value1, //comment 1\\n argument2 = value2 /*comment 2*/ ,\\n argument3 = value3, \\n argument4 = value4)\\n{\\n content of function\\n spanning several\\n lines\\n}', '# <markdowncell> \\n Arguments are defined. \\n# <codecell>\\nargument1 = value1;\\nargument2 = value2;\\nargument3 = value3;\\nargument4 = value4;\\n# <codecell>\\n')
>>> processmain('''TCanvas function(){
... content of function
... spanning several
... lines
... return c1
... }''')
('TCanvas function(){\\n content of function\\n spanning several \\n lines\\n return c1\\n}', '') | Evaluates whether the main function returns a TCanvas or requires input. If it
does then the keepfunction flag is True, meaning the function wont be extracted
by cppFunction. If the initial condition is true then an extra cell is added
before at the end that calls the main function is returned, and added later.
>>> processmain('''void function(){
... content of function
... spanning several
... lines
... }''')
('void function(){\\n content of function\\n spanning several\\n lines\\n}', '')
>>> processmain('''void function(arguments = values){
... content of function
... spanning several
... lines
... }''')
('void function(arguments = values){\\n content of function\\n spanning several\\n lines\\n}', '# <markdowncell> \\n Arguments are defined. \\n# <codecell>\\narguments = values;\\n# <codecell>\\n')
>>> processmain('''void function(argument1 = value1, //comment 1
... argument2 = value2 /*comment 2*/ ,
... argument3 = value3,
... argument4 = value4)
... {
... content of function
... spanning several
... lines
... }''')
('void function(argument1 = value1, //comment 1\\n argument2 = value2 /*comment 2*/ ,\\n argument3 = value3, \\n argument4 = value4)\\n{\\n content of function\\n spanning several\\n lines\\n}', '# <markdowncell> \\n Arguments are defined. \\n# <codecell>\\nargument1 = value1;\\nargument2 = value2;\\nargument3 = value3;\\nargument4 = value4;\\n# <codecell>\\n')
>>> processmain('''TCanvas function(){
... content of function
... spanning several
... lines
... return c1
... }''')
('TCanvas function(){\\n content of function\\n spanning several \\n lines\\n return c1\\n}', '') | [
"Evaluates",
"whether",
"the",
"main",
"function",
"returns",
"a",
"TCanvas",
"or",
"requires",
"input",
".",
"If",
"it",
"does",
"then",
"the",
"keepfunction",
"flag",
"is",
"True",
"meaning",
"the",
"function",
"wont",
"be",
"extracted",
"by",
"cppFunction",... | def processmain(text):
"""
Evaluates whether the main function returns a TCanvas or requires input. If it
does then the keepfunction flag is True, meaning the function wont be extracted
by cppFunction. If the initial condition is true then an extra cell is added
before at the end that calls the main function is returned, and added later.
>>> processmain('''void function(){
... content of function
... spanning several
... lines
... }''')
('void function(){\\n content of function\\n spanning several\\n lines\\n}', '')
>>> processmain('''void function(arguments = values){
... content of function
... spanning several
... lines
... }''')
('void function(arguments = values){\\n content of function\\n spanning several\\n lines\\n}', '# <markdowncell> \\n Arguments are defined. \\n# <codecell>\\narguments = values;\\n# <codecell>\\n')
>>> processmain('''void function(argument1 = value1, //comment 1
... argument2 = value2 /*comment 2*/ ,
... argument3 = value3,
... argument4 = value4)
... {
... content of function
... spanning several
... lines
... }''')
('void function(argument1 = value1, //comment 1\\n argument2 = value2 /*comment 2*/ ,\\n argument3 = value3, \\n argument4 = value4)\\n{\\n content of function\\n spanning several\\n lines\\n}', '# <markdowncell> \\n Arguments are defined. \\n# <codecell>\\nargument1 = value1;\\nargument2 = value2;\\nargument3 = value3;\\nargument4 = value4;\\n# <codecell>\\n')
>>> processmain('''TCanvas function(){
... content of function
... spanning several
... lines
... return c1
... }''')
('TCanvas function(){\\n content of function\\n spanning several \\n lines\\n return c1\\n}', '')
"""
argumentsCell = ''
if text:
argumentsre = re.compile(r'(?<=\().*?(?=\))', flags = re.DOTALL | re.MULTILINE)
arguments = argumentsre.search(text)
if len(arguments.group()) > 3:
argumentsCell = "# <markdowncell> \n Arguments are defined. \n# <codecell>\n"
individualArgumentre = re.compile(r'[^/\n,]*?=[^/\n,]*') #, flags = re.DOTALL) #| re.MULTILINE)
argumentList=individualArgumentre.findall(arguments.group())
for argument in argumentList:
argumentsCell += argument.strip("\n ") + ";\n"
argumentsCell += "# <codecell>\n"
return text, argumentsCell | [
"def",
"processmain",
"(",
"text",
")",
":",
"argumentsCell",
"=",
"''",
"if",
"text",
":",
"argumentsre",
"=",
"re",
".",
"compile",
"(",
"r'(?<=\\().*?(?=\\))'",
",",
"flags",
"=",
"re",
".",
"DOTALL",
"|",
"re",
".",
"MULTILINE",
")",
"arguments",
"="... | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/documentation/doxygen/converttonotebook.py#L505-L556 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/CallTips.py | python | CallTips.try_open_calltip_event | (self, event) | Happens when it would be nice to open a CallTip, but not really
necessary, for example after an opening bracket, so function calls
won't be made. | Happens when it would be nice to open a CallTip, but not really
necessary, for example after an opening bracket, so function calls
won't be made. | [
"Happens",
"when",
"it",
"would",
"be",
"nice",
"to",
"open",
"a",
"CallTip",
"but",
"not",
"really",
"necessary",
"for",
"example",
"after",
"an",
"opening",
"bracket",
"so",
"function",
"calls",
"won",
"t",
"be",
"made",
"."
] | def try_open_calltip_event(self, event):
"""Happens when it would be nice to open a CallTip, but not really
necessary, for example after an opening bracket, so function calls
won't be made.
"""
self.open_calltip(False) | [
"def",
"try_open_calltip_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"open_calltip",
"(",
"False",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/CallTips.py#L52-L57 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/internals/construction.py | python | init_dict | (data, index, columns, dtype=None) | return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype) | Segregate Series based on type and coerce into matrices.
Needs to handle a lot of exceptional cases. | Segregate Series based on type and coerce into matrices.
Needs to handle a lot of exceptional cases. | [
"Segregate",
"Series",
"based",
"on",
"type",
"and",
"coerce",
"into",
"matrices",
".",
"Needs",
"to",
"handle",
"a",
"lot",
"of",
"exceptional",
"cases",
"."
] | def init_dict(data, index, columns, dtype=None):
"""
Segregate Series based on type and coerce into matrices.
Needs to handle a lot of exceptional cases.
"""
if columns is not None:
from pandas.core.series import Series
arrays = Series(data, index=columns, dtype=object)
data_names = arrays.index
missing = arrays.isna()
if index is None:
# GH10856
# raise ValueError if only scalars in dict
index = extract_index(arrays[~missing])
else:
index = ensure_index(index)
# no obvious "empty" int column
if missing.any() and not is_integer_dtype(dtype):
if dtype is None or np.issubdtype(dtype, np.flexible):
# GH#1783
nan_dtype = object
else:
nan_dtype = dtype
val = construct_1d_arraylike_from_scalar(np.nan, len(index), nan_dtype)
arrays.loc[missing] = [val] * missing.sum()
else:
keys = list(data.keys())
columns = data_names = Index(keys)
arrays = (com.maybe_iterable_to_list(data[k]) for k in keys)
# GH#24096 need copy to be deep for datetime64tz case
# TODO: See if we can avoid these copies
arrays = [
arr if not isinstance(arr, ABCIndexClass) else arr._data for arr in arrays
]
arrays = [
arr if not is_datetime64tz_dtype(arr) else arr.copy() for arr in arrays
]
return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype) | [
"def",
"init_dict",
"(",
"data",
",",
"index",
",",
"columns",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"columns",
"is",
"not",
"None",
":",
"from",
"pandas",
".",
"core",
".",
"series",
"import",
"Series",
"arrays",
"=",
"Series",
"(",
"data",
","... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/internals/construction.py#L213-L254 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | VarHScrollHelper.IsColumnVisible | (*args, **kwargs) | return _windows_.VarHScrollHelper_IsColumnVisible(*args, **kwargs) | IsColumnVisible(self, size_t column) -> bool | IsColumnVisible(self, size_t column) -> bool | [
"IsColumnVisible",
"(",
"self",
"size_t",
"column",
")",
"-",
">",
"bool"
] | def IsColumnVisible(*args, **kwargs):
"""IsColumnVisible(self, size_t column) -> bool"""
return _windows_.VarHScrollHelper_IsColumnVisible(*args, **kwargs) | [
"def",
"IsColumnVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"VarHScrollHelper_IsColumnVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L2356-L2358 | |
junhyukoh/caffe-lstm | 598d45456fa2a1b127a644f4aa38daa8fb9fc722 | scripts/cpp_lint.py | python | RemoveMultiLineComments | (filename, lines, error) | Removes multiline (c-style) comments from lines. | Removes multiline (c-style) comments from lines. | [
"Removes",
"multiline",
"(",
"c",
"-",
"style",
")",
"comments",
"from",
"lines",
"."
] | def RemoveMultiLineComments(filename, lines, error):
"""Removes multiline (c-style) comments from lines."""
lineix = 0
while lineix < len(lines):
lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
if lineix_begin >= len(lines):
return
lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
if lineix_end >= len(lines):
error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
'Could not find end of multi-line comment')
return
RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
lineix = lineix_end + 1 | [
"def",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"lineix",
"=",
"0",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"lineix_begin",
"=",
"FindNextMultiLineCommentStart",
"(",
"lines",
",",
"lineix",
")",
"if",
... | https://github.com/junhyukoh/caffe-lstm/blob/598d45456fa2a1b127a644f4aa38daa8fb9fc722/scripts/cpp_lint.py#L1151-L1164 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/glacier/vault.py | python | Vault.delete | (self) | Delete's this vault. WARNING! | Delete's this vault. WARNING! | [
"Delete",
"s",
"this",
"vault",
".",
"WARNING!"
] | def delete(self):
"""
Delete's this vault. WARNING!
"""
self.layer1.delete_vault(self.name) | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"layer1",
".",
"delete_vault",
"(",
"self",
".",
"name",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/glacier/vault.py#L66-L70 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/python_gflags/gflags.py | python | Flag.SetDefault | (self, value) | Changes the default value (and current value too) for this Flag. | Changes the default value (and current value too) for this Flag. | [
"Changes",
"the",
"default",
"value",
"(",
"and",
"current",
"value",
"too",
")",
"for",
"this",
"Flag",
"."
] | def SetDefault(self, value):
"""Changes the default value (and current value too) for this Flag."""
# We can't allow a None override because it may end up not being
# passed to C++ code when we're overriding C++ flags. So we
# cowardly bail out until someone fixes the semantics of trying to
# pass None to a C++ flag. See swig_flags.Init() for details on
# this behavior.
# TODO(olexiy): Users can directly call this method, bypassing all flags
# validators (we don't have FlagValues here, so we can not check
# validators).
# The simplest solution I see is to make this method private.
# Another approach would be to store reference to the corresponding
# FlagValues with each flag, but this seems to be an overkill.
if value is None and self.allow_override:
raise DuplicateFlagCannotPropagateNoneToSwig(self.name)
self.default = value
self.Unparse()
self.default_as_str = self.__GetParsedValueAsString(self.value) | [
"def",
"SetDefault",
"(",
"self",
",",
"value",
")",
":",
"# We can't allow a None override because it may end up not being",
"# passed to C++ code when we're overriding C++ flags. So we",
"# cowardly bail out until someone fixes the semantics of trying to",
"# pass None to a C++ flag. See s... | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/python_gflags/gflags.py#L1910-L1928 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py | python | Mailbox.get | (self, key, default=None) | Return the keyed message, or default if it doesn't exist. | Return the keyed message, or default if it doesn't exist. | [
"Return",
"the",
"keyed",
"message",
"or",
"default",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | def get(self, key, default=None):
"""Return the keyed message, or default if it doesn't exist."""
try:
return self.__getitem__(key)
except KeyError:
return default | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"__getitem__",
"(",
"key",
")",
"except",
"KeyError",
":",
"return",
"default"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py#L72-L77 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | DateSpan_Years | (*args, **kwargs) | return _misc_.DateSpan_Years(*args, **kwargs) | DateSpan_Years(int years) -> DateSpan | DateSpan_Years(int years) -> DateSpan | [
"DateSpan_Years",
"(",
"int",
"years",
")",
"-",
">",
"DateSpan"
] | def DateSpan_Years(*args, **kwargs):
"""DateSpan_Years(int years) -> DateSpan"""
return _misc_.DateSpan_Years(*args, **kwargs) | [
"def",
"DateSpan_Years",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_Years",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L4776-L4778 | |
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py | python | BeautifulStoneSoup.__init__ | (self, markup="", parseOnlyThese=None, fromEncoding=None,
markupMassage=True, smartQuotesTo=XML_ENTITIES,
convertEntities=None, selfClosingTags=None, isHTML=False) | The Soup object is initialized as the 'root tag', and the
provided markup (which can be a string or a file-like object)
is fed into the underlying parser.
sgmllib will process most bad HTML, and the BeautifulSoup
class has some tricks for dealing with some HTML that kills
sgmllib, but Beautiful Soup can nonetheless choke or lose data
if your data uses self-closing tags or declarations
incorrectly.
By default, Beautiful Soup uses regexes to sanitize input,
avoiding the vast majority of these problems. If the problems
don't apply to you, pass in False for markupMassage, and
you'll get better performance.
The default parser massage techniques fix the two most common
instances of invalid HTML that choke sgmllib:
<br/> (No space between name of closing tag and tag close)
<! --Comment--> (Extraneous whitespace in declaration)
You can pass in a custom list of (RE object, replace method)
tuples to get Beautiful Soup to scrub your input the way you
want. | The Soup object is initialized as the 'root tag', and the
provided markup (which can be a string or a file-like object)
is fed into the underlying parser. | [
"The",
"Soup",
"object",
"is",
"initialized",
"as",
"the",
"root",
"tag",
"and",
"the",
"provided",
"markup",
"(",
"which",
"can",
"be",
"a",
"string",
"or",
"a",
"file",
"-",
"like",
"object",
")",
"is",
"fed",
"into",
"the",
"underlying",
"parser",
"... | def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None,
markupMassage=True, smartQuotesTo=XML_ENTITIES,
convertEntities=None, selfClosingTags=None, isHTML=False):
"""The Soup object is initialized as the 'root tag', and the
provided markup (which can be a string or a file-like object)
is fed into the underlying parser.
sgmllib will process most bad HTML, and the BeautifulSoup
class has some tricks for dealing with some HTML that kills
sgmllib, but Beautiful Soup can nonetheless choke or lose data
if your data uses self-closing tags or declarations
incorrectly.
By default, Beautiful Soup uses regexes to sanitize input,
avoiding the vast majority of these problems. If the problems
don't apply to you, pass in False for markupMassage, and
you'll get better performance.
The default parser massage techniques fix the two most common
instances of invalid HTML that choke sgmllib:
<br/> (No space between name of closing tag and tag close)
<! --Comment--> (Extraneous whitespace in declaration)
You can pass in a custom list of (RE object, replace method)
tuples to get Beautiful Soup to scrub your input the way you
want."""
self.parseOnlyThese = parseOnlyThese
self.fromEncoding = fromEncoding
self.smartQuotesTo = smartQuotesTo
self.convertEntities = convertEntities
# Set the rules for how we'll deal with the entities we
# encounter
if self.convertEntities:
# It doesn't make sense to convert encoded characters to
# entities even while you're converting entities to Unicode.
# Just convert it all to Unicode.
self.smartQuotesTo = None
if convertEntities == self.HTML_ENTITIES:
self.convertXMLEntities = False
self.convertHTMLEntities = True
self.escapeUnrecognizedEntities = True
elif convertEntities == self.XHTML_ENTITIES:
self.convertXMLEntities = True
self.convertHTMLEntities = True
self.escapeUnrecognizedEntities = False
elif convertEntities == self.XML_ENTITIES:
self.convertXMLEntities = True
self.convertHTMLEntities = False
self.escapeUnrecognizedEntities = False
else:
self.convertXMLEntities = False
self.convertHTMLEntities = False
self.escapeUnrecognizedEntities = False
self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags)
SGMLParser.__init__(self)
if hasattr(markup, 'read'): # It's a file-type object.
markup = markup.read()
self.markup = markup
self.markupMassage = markupMassage
try:
self._feed(isHTML=isHTML)
except StopParsing:
pass
self.markup = None | [
"def",
"__init__",
"(",
"self",
",",
"markup",
"=",
"\"\"",
",",
"parseOnlyThese",
"=",
"None",
",",
"fromEncoding",
"=",
"None",
",",
"markupMassage",
"=",
"True",
",",
"smartQuotesTo",
"=",
"XML_ENTITIES",
",",
"convertEntities",
"=",
"None",
",",
"selfClo... | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py#L1080-L1147 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/psutil/psutil/__init__.py | python | Process.nice | (self) | return self.get_nice() | Get or set process niceness (priority).
Deprecated, use get_nice() instead. | Get or set process niceness (priority).
Deprecated, use get_nice() instead. | [
"Get",
"or",
"set",
"process",
"niceness",
"(",
"priority",
")",
".",
"Deprecated",
"use",
"get_nice",
"()",
"instead",
"."
] | def nice(self):
"""Get or set process niceness (priority).
Deprecated, use get_nice() instead.
"""
msg = "this property is deprecated; use Process.get_nice() method instead"
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
return self.get_nice() | [
"def",
"nice",
"(",
"self",
")",
":",
"msg",
"=",
"\"this property is deprecated; use Process.get_nice() method instead\"",
"warnings",
".",
"warn",
"(",
"msg",
",",
"category",
"=",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"self",
".",
"g... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/__init__.py#L808-L814 | |
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 | Base.scanner_map_delete | (self, kw=None) | Delete the cached scanner map (if we need to). | Delete the cached scanner map (if we need to). | [
"Delete",
"the",
"cached",
"scanner",
"map",
"(",
"if",
"we",
"need",
"to",
")",
"."
] | def scanner_map_delete(self, kw=None):
"""Delete the cached scanner map (if we need to).
"""
try:
del self._memo['_gsm']
except KeyError:
pass | [
"def",
"scanner_map_delete",
"(",
"self",
",",
"kw",
"=",
"None",
")",
":",
"try",
":",
"del",
"self",
".",
"_memo",
"[",
"'_gsm'",
"]",
"except",
"KeyError",
":",
"pass"
] | 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#L1090-L1096 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/xrc.py | python | XmlResource.LoadIcon | (*args, **kwargs) | return _xrc.XmlResource_LoadIcon(*args, **kwargs) | LoadIcon(self, String name) -> Icon | LoadIcon(self, String name) -> Icon | [
"LoadIcon",
"(",
"self",
"String",
"name",
")",
"-",
">",
"Icon"
] | def LoadIcon(*args, **kwargs):
"""LoadIcon(self, String name) -> Icon"""
return _xrc.XmlResource_LoadIcon(*args, **kwargs) | [
"def",
"LoadIcon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlResource_LoadIcon",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/xrc.py#L179-L181 | |
simsong/bulk_extractor | 738911df22b7066ca9e1662f4131fb44090a4196 | python/bulk_extractor_reader.py | python | get_property_line | (line) | return None | If it is a property line return the (property, value) | If it is a property line return the (property, value) | [
"If",
"it",
"is",
"a",
"property",
"line",
"return",
"the",
"(",
"property",
"value",
")"
] | def get_property_line(line):
"""If it is a property line return the (property, value)"""
if line[0:1]=='#':
m = property_re.search(line)
if m:
return (m.group(1),m.group(2))
return None | [
"def",
"get_property_line",
"(",
"line",
")",
":",
"if",
"line",
"[",
"0",
":",
"1",
"]",
"==",
"'#'",
":",
"m",
"=",
"property_re",
".",
"search",
"(",
"line",
")",
"if",
"m",
":",
"return",
"(",
"m",
".",
"group",
"(",
"1",
")",
",",
"m",
"... | https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/bulk_extractor_reader.py#L87-L93 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/robotsim.py | python | Simulator.getStatusString | (self, s: int=-1) | return _robotsim.Simulator_getStatusString(self, s) | r"""
Returns a string indicating the simulator's status. If s is provided and >= 0,
this function maps the indicator code s to a string.
Args:
s (int, optional): default value -1 | r"""
Returns a string indicating the simulator's status. If s is provided and >= 0,
this function maps the indicator code s to a string. | [
"r",
"Returns",
"a",
"string",
"indicating",
"the",
"simulator",
"s",
"status",
".",
"If",
"s",
"is",
"provided",
"and",
">",
"=",
"0",
"this",
"function",
"maps",
"the",
"indicator",
"code",
"s",
"to",
"a",
"string",
"."
] | def getStatusString(self, s: int=-1) ->str:
r"""
Returns a string indicating the simulator's status. If s is provided and >= 0,
this function maps the indicator code s to a string.
Args:
s (int, optional): default value -1
"""
return _robotsim.Simulator_getStatusString(self, s) | [
"def",
"getStatusString",
"(",
"self",
",",
"s",
":",
"int",
"=",
"-",
"1",
")",
"->",
"str",
":",
"return",
"_robotsim",
".",
"Simulator_getStatusString",
"(",
"self",
",",
"s",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L7799-L7807 | |
goldeneye-source/ges-code | 2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d | thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py | python | _AddPropertiesForNonRepeatedScalarField | (field, cls) | Adds a public property for a nonrepeated, scalar protocol message field.
Clients can use this property to get and directly set the value of the field.
Note that when the client sets the value of a field by using this property,
all necessary "has" bits are set as a side-effect, and we also perform
type-checking.
Args:
field: A FieldDescriptor for this field.
cls: The class we're constructing. | Adds a public property for a nonrepeated, scalar protocol message field.
Clients can use this property to get and directly set the value of the field.
Note that when the client sets the value of a field by using this property,
all necessary "has" bits are set as a side-effect, and we also perform
type-checking. | [
"Adds",
"a",
"public",
"property",
"for",
"a",
"nonrepeated",
"scalar",
"protocol",
"message",
"field",
".",
"Clients",
"can",
"use",
"this",
"property",
"to",
"get",
"and",
"directly",
"set",
"the",
"value",
"of",
"the",
"field",
".",
"Note",
"that",
"whe... | def _AddPropertiesForNonRepeatedScalarField(field, cls):
"""Adds a public property for a nonrepeated, scalar protocol message field.
Clients can use this property to get and directly set the value of the field.
Note that when the client sets the value of a field by using this property,
all necessary "has" bits are set as a side-effect, and we also perform
type-checking.
Args:
field: A FieldDescriptor for this field.
cls: The class we're constructing.
"""
proto_field_name = field.name
property_name = _PropertyName(proto_field_name)
type_checker = type_checkers.GetTypeChecker(field.cpp_type, field.type)
default_value = field.default_value
def getter(self):
return self._fields.get(field, default_value)
getter.__module__ = None
getter.__doc__ = 'Getter for %s.' % proto_field_name
def setter(self, new_value):
type_checker.CheckValue(new_value)
self._fields[field] = new_value
# Check _cached_byte_size_dirty inline to improve performance, since scalar
# setters are called frequently.
if not self._cached_byte_size_dirty:
self._Modified()
setter.__module__ = None
setter.__doc__ = 'Setter for %s.' % proto_field_name
# Add a property to encapsulate the getter/setter.
doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name
setattr(cls, property_name, property(getter, setter, doc=doc)) | [
"def",
"_AddPropertiesForNonRepeatedScalarField",
"(",
"field",
",",
"cls",
")",
":",
"proto_field_name",
"=",
"field",
".",
"name",
"property_name",
"=",
"_PropertyName",
"(",
"proto_field_name",
")",
"type_checker",
"=",
"type_checkers",
".",
"GetTypeChecker",
"(",
... | https://github.com/goldeneye-source/ges-code/blob/2630cd8ef3d015af53c72ec2e19fc1f7e7fe8d9d/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L489-L521 | ||
baidu/bigflow | 449245016c0df7d1252e85581e588bfc60cefad3 | bigflow_python/python/bigflow/schema.py | python | _select_cols | (val, select_fields) | return tuple(ret) | 内部函数 | 内部函数 | [
"内部函数"
] | def _select_cols(val, select_fields):
""" 内部函数 """
def _get_field(field):
return val.map(lambda v: v[field],
serde=_get_serde_of_field(
val.serde(),
field,
val.pipeline().default_objector()))
ret = list(_get_field(field) for field in select_fields)
ret.append(val)
return tuple(ret) | [
"def",
"_select_cols",
"(",
"val",
",",
"select_fields",
")",
":",
"def",
"_get_field",
"(",
"field",
")",
":",
"return",
"val",
".",
"map",
"(",
"lambda",
"v",
":",
"v",
"[",
"field",
"]",
",",
"serde",
"=",
"_get_serde_of_field",
"(",
"val",
".",
"... | https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/schema.py#L114-L124 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBDebugger.GetNumCategories | (self) | return _lldb.SBDebugger_GetNumCategories(self) | GetNumCategories(self) -> uint32_t | GetNumCategories(self) -> uint32_t | [
"GetNumCategories",
"(",
"self",
")",
"-",
">",
"uint32_t"
] | def GetNumCategories(self):
"""GetNumCategories(self) -> uint32_t"""
return _lldb.SBDebugger_GetNumCategories(self) | [
"def",
"GetNumCategories",
"(",
"self",
")",
":",
"return",
"_lldb",
".",
"SBDebugger_GetNumCategories",
"(",
"self",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L3495-L3497 | |
mingchen/protobuf-ios | 0958df34558cd54cb7b6e6ca5c8855bf3d475046 | compiler/python/google/protobuf/reflection.py | python | _AddInitMethod | (message_descriptor, cls) | Adds an __init__ method to cls. | Adds an __init__ method to cls. | [
"Adds",
"an",
"__init__",
"method",
"to",
"cls",
"."
] | def _AddInitMethod(message_descriptor, cls):
"""Adds an __init__ method to cls."""
fields = message_descriptor.fields
def init(self, **kwargs):
self._cached_byte_size = 0
self._cached_byte_size_dirty = False
self._listener = message_listener_mod.NullMessageListener()
self._called_transition_to_nonempty = False
# TODO(robinson): We should only create a lock if we really need one
# in this class.
self._lock = threading.Lock()
for field in fields:
default_value = _DefaultValueForField(self, field)
python_field_name = _ValueFieldName(field.name)
setattr(self, python_field_name, default_value)
if field.label != _FieldDescriptor.LABEL_REPEATED:
setattr(self, _HasFieldName(field.name), False)
self.Extensions = _ExtensionDict(self, cls._known_extensions)
for field_name, field_value in kwargs.iteritems():
field = _GetFieldByName(message_descriptor, field_name)
_MergeFieldOrExtension(self, field, field_value)
init.__module__ = None
init.__doc__ = None
cls.__init__ = init | [
"def",
"_AddInitMethod",
"(",
"message_descriptor",
",",
"cls",
")",
":",
"fields",
"=",
"message_descriptor",
".",
"fields",
"def",
"init",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_cached_byte_size",
"=",
"0",
"self",
".",
"_cached_b... | https://github.com/mingchen/protobuf-ios/blob/0958df34558cd54cb7b6e6ca5c8855bf3d475046/compiler/python/google/protobuf/reflection.py#L292-L316 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | modules/thermal_hydraulics/python/peacock/UnitConversion.py | python | Unit.name | (self) | return None | Human readable name of the unit
@return[string] Unit name | Human readable name of the unit | [
"Human",
"readable",
"name",
"of",
"the",
"unit"
] | def name(self):
"""
Human readable name of the unit
@return[string] Unit name
"""
return None | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"None"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/modules/thermal_hydraulics/python/peacock/UnitConversion.py#L15-L21 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/python/ops/seq2seq.py | python | tied_rnn_seq2seq | (encoder_inputs, decoder_inputs, cell,
loop_function=None, dtype=dtypes.float32, scope=None) | RNN sequence-to-sequence model with tied encoder and decoder parameters.
This model first runs an RNN to encode encoder_inputs into a state vector, and
then runs decoder, initialized with the last encoder state, on decoder_inputs.
Encoder and decoder use the same RNN cell and share parameters.
Args:
encoder_inputs: A list of 2D Tensors [batch_size x input_size].
decoder_inputs: A list of 2D Tensors [batch_size x input_size].
cell: rnn_cell.RNNCell defining the cell function and size.
loop_function: If not None, this function will be applied to i-th output
in order to generate i+1-th input, and decoder_inputs will be ignored,
except for the first element ("GO" symbol), see rnn_decoder for details.
dtype: The dtype of the initial state of the rnn cell (default: tf.float32).
scope: VariableScope for the created subgraph; default: "tied_rnn_seq2seq".
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors with
shape [batch_size x output_size] containing the generated outputs.
state: The state of each decoder cell in each time-step. This is a list
with length len(decoder_inputs) -- one item for each time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size]. | RNN sequence-to-sequence model with tied encoder and decoder parameters. | [
"RNN",
"sequence",
"-",
"to",
"-",
"sequence",
"model",
"with",
"tied",
"encoder",
"and",
"decoder",
"parameters",
"."
] | def tied_rnn_seq2seq(encoder_inputs, decoder_inputs, cell,
loop_function=None, dtype=dtypes.float32, scope=None):
"""RNN sequence-to-sequence model with tied encoder and decoder parameters.
This model first runs an RNN to encode encoder_inputs into a state vector, and
then runs decoder, initialized with the last encoder state, on decoder_inputs.
Encoder and decoder use the same RNN cell and share parameters.
Args:
encoder_inputs: A list of 2D Tensors [batch_size x input_size].
decoder_inputs: A list of 2D Tensors [batch_size x input_size].
cell: rnn_cell.RNNCell defining the cell function and size.
loop_function: If not None, this function will be applied to i-th output
in order to generate i+1-th input, and decoder_inputs will be ignored,
except for the first element ("GO" symbol), see rnn_decoder for details.
dtype: The dtype of the initial state of the rnn cell (default: tf.float32).
scope: VariableScope for the created subgraph; default: "tied_rnn_seq2seq".
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors with
shape [batch_size x output_size] containing the generated outputs.
state: The state of each decoder cell in each time-step. This is a list
with length len(decoder_inputs) -- one item for each time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
"""
with variable_scope.variable_scope("combined_tied_rnn_seq2seq"):
scope = scope or "tied_rnn_seq2seq"
_, enc_state = rnn.rnn(
cell, encoder_inputs, dtype=dtype, scope=scope)
variable_scope.get_variable_scope().reuse_variables()
return rnn_decoder(decoder_inputs, enc_state, cell,
loop_function=loop_function, scope=scope) | [
"def",
"tied_rnn_seq2seq",
"(",
"encoder_inputs",
",",
"decoder_inputs",
",",
"cell",
",",
"loop_function",
"=",
"None",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
",",
"scope",
"=",
"None",
")",
":",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"... | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/seq2seq.py#L179-L211 | ||
google/shaka-player-embedded | dabbeb5b47cc257b37b9a254661546352aaf0afe | shaka/tools/webidl/webidl/parser.py | python | IdlParser.p_StringType | (self, p) | return types.IdlType(
name=p[1], nullable=False, element_type=None, extensions=[]) | r"""StringType : BYTESTRING
| DOMSTRING
| USVSTRING | r"""StringType : BYTESTRING
| DOMSTRING
| USVSTRING | [
"r",
"StringType",
":",
"BYTESTRING",
"|",
"DOMSTRING",
"|",
"USVSTRING"
] | def p_StringType(self, p):
r"""StringType : BYTESTRING
| DOMSTRING
| USVSTRING"""
return types.IdlType(
name=p[1], nullable=False, element_type=None, extensions=[]) | [
"def",
"p_StringType",
"(",
"self",
",",
"p",
")",
":",
"return",
"types",
".",
"IdlType",
"(",
"name",
"=",
"p",
"[",
"1",
"]",
",",
"nullable",
"=",
"False",
",",
"element_type",
"=",
"None",
",",
"extensions",
"=",
"[",
"]",
")"
] | https://github.com/google/shaka-player-embedded/blob/dabbeb5b47cc257b37b9a254661546352aaf0afe/shaka/tools/webidl/webidl/parser.py#L436-L441 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/learn/python/learn/experiment.py | python | Experiment.extend_train_hooks | (self, additional_hooks) | Extends the hooks for training. | Extends the hooks for training. | [
"Extends",
"the",
"hooks",
"for",
"training",
"."
] | def extend_train_hooks(self, additional_hooks):
"""Extends the hooks for training."""
self._train_monitors.extend(additional_hooks) | [
"def",
"extend_train_hooks",
"(",
"self",
",",
"additional_hooks",
")",
":",
"self",
".",
"_train_monitors",
".",
"extend",
"(",
"additional_hooks",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/experiment.py#L293-L295 | ||
keyboardio/Kaleidoscope | d59604e98b2439d108647f15be52984a6837d360 | bin/cpplint.py | python | FindEndOfExpressionInLine | (line, startpos, stack) | return (-1, stack) | Find the position just after the end of current parenthesized expression.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
stack: nesting stack at startpos.
Returns:
On finding matching end: (index just after matching end, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at end of this line) | Find the position just after the end of current parenthesized expression. | [
"Find",
"the",
"position",
"just",
"after",
"the",
"end",
"of",
"current",
"parenthesized",
"expression",
"."
] | def FindEndOfExpressionInLine(line, startpos, stack):
"""Find the position just after the end of current parenthesized expression.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
stack: nesting stack at startpos.
Returns:
On finding matching end: (index just after matching end, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at end of this line)
"""
for i in xrange(startpos, len(line)):
char = line[i]
if char in '([{':
# Found start of parenthesized expression, push to expression stack
stack.append(char)
elif char == '<':
# Found potential start of template argument list
if i > 0 and line[i - 1] == '<':
# Left shift operator
if stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
# operator<, don't add to stack
continue
else:
# Tentative start of template argument list
stack.append('<')
elif char in ')]}':
# Found end of parenthesized expression.
#
# If we are currently expecting a matching '>', the pending '<'
# must have been an operator. Remove them from expression stack.
while stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
if ((stack[-1] == '(' and char == ')') or
(stack[-1] == '[' and char == ']') or
(stack[-1] == '{' and char == '}')):
stack.pop()
if not stack:
return (i + 1, None)
else:
# Mismatched parentheses
return (-1, None)
elif char == '>':
# Found potential end of template argument list.
# Ignore "->" and operator functions
if (i > 0 and
(line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
continue
# Pop the stack if there is a matching '<'. Otherwise, ignore
# this '>' since it must be an operator.
if stack:
if stack[-1] == '<':
stack.pop()
if not stack:
return (i + 1, None)
elif char == ';':
# Found something that look like end of statements. If we are currently
# expecting a '>', the matching '<' must have been an operator, since
# template argument list should not contain statements.
while stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
# Did not find end of expression or unbalanced parentheses on this line
return (-1, stack) | [
"def",
"FindEndOfExpressionInLine",
"(",
"line",
",",
"startpos",
",",
"stack",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"startpos",
",",
"len",
"(",
"line",
")",
")",
":",
"char",
"=",
"line",
"[",
"i",
"]",
"if",
"char",
"in",
"'([{'",
":",
"# ... | https://github.com/keyboardio/Kaleidoscope/blob/d59604e98b2439d108647f15be52984a6837d360/bin/cpplint.py#L1735-L1810 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | GetOsDescription | (*args) | return _misc_.GetOsDescription(*args) | GetOsDescription() -> String | GetOsDescription() -> String | [
"GetOsDescription",
"()",
"-",
">",
"String"
] | def GetOsDescription(*args):
"""GetOsDescription() -> String"""
return _misc_.GetOsDescription(*args) | [
"def",
"GetOsDescription",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"GetOsDescription",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L340-L342 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/symbol/symbol.py | python | Symbol.prod | (self, *args, **kwargs) | return op.prod(self, *args, **kwargs) | Convenience fluent method for :py:func:`prod`.
The arguments are the same as for :py:func:`prod`, with
this array as data. | Convenience fluent method for :py:func:`prod`. | [
"Convenience",
"fluent",
"method",
"for",
":",
"py",
":",
"func",
":",
"prod",
"."
] | def prod(self, *args, **kwargs):
"""Convenience fluent method for :py:func:`prod`.
The arguments are the same as for :py:func:`prod`, with
this array as data.
"""
return op.prod(self, *args, **kwargs) | [
"def",
"prod",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"op",
".",
"prod",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/symbol/symbol.py#L1999-L2005 | |
facebook/ThreatExchange | 31914a51820c73c8a0daffe62ccca29a6e3d359e | api-reference-examples/python/pytx/pytx/batch.py | python | Batch.__init__ | (self, **kwargs) | Initialized the object. | Initialized the object. | [
"Initialized",
"the",
"object",
"."
] | def __init__(self, **kwargs):
"""
Initialized the object.
""" | [
"def",
"__init__",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":"
] | https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/api-reference-examples/python/pytx/pytx/batch.py#L20-L23 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | BookCtrlBase.DeletePage | (*args, **kwargs) | return _core_.BookCtrlBase_DeletePage(*args, **kwargs) | DeletePage(self, size_t n) -> bool | DeletePage(self, size_t n) -> bool | [
"DeletePage",
"(",
"self",
"size_t",
"n",
")",
"-",
">",
"bool"
] | def DeletePage(*args, **kwargs):
"""DeletePage(self, size_t n) -> bool"""
return _core_.BookCtrlBase_DeletePage(*args, **kwargs) | [
"def",
"DeletePage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"BookCtrlBase_DeletePage",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13606-L13608 | |
GoSSIP-SJTU/TripleDoggy | 03648d6b19c812504b14e8b98c8c7b3f443f4e54 | utils/lit/lit/run.py | python | Run.execute_tests | (self, display, jobs, max_time=None) | execute_tests(display, jobs, [max_time])
Execute each of the tests in the run, using up to jobs number of
parallel tasks, and inform the display of each individual result. The
provided tests should be a subset of the tests available in this run
object.
If max_time is non-None, it should be a time in seconds after which to
stop executing tests.
The display object will have its update method called with each test as
it is completed. The calls are guaranteed to be locked with respect to
one another, but are *not* guaranteed to be called on the same thread as
this method was invoked on.
Upon completion, each test in the run will have its result
computed. Tests which were not actually executed (for any reason) will
be given an UNRESOLVED result. | execute_tests(display, jobs, [max_time]) | [
"execute_tests",
"(",
"display",
"jobs",
"[",
"max_time",
"]",
")"
] | def execute_tests(self, display, jobs, max_time=None):
"""
execute_tests(display, jobs, [max_time])
Execute each of the tests in the run, using up to jobs number of
parallel tasks, and inform the display of each individual result. The
provided tests should be a subset of the tests available in this run
object.
If max_time is non-None, it should be a time in seconds after which to
stop executing tests.
The display object will have its update method called with each test as
it is completed. The calls are guaranteed to be locked with respect to
one another, but are *not* guaranteed to be called on the same thread as
this method was invoked on.
Upon completion, each test in the run will have its result
computed. Tests which were not actually executed (for any reason) will
be given an UNRESOLVED result.
"""
# Don't do anything if we aren't going to run any tests.
if not self.tests or jobs == 0:
return
# Save the display object on the runner so that we can update it from
# our task completion callback.
self.display = display
self.failure_count = 0
self.hit_max_failures = False
if self.lit_config.singleProcess:
global child_lit_config
child_lit_config = self.lit_config
for test_index, test in enumerate(self.tests):
result = worker_run_one_test(test_index, test)
self.consume_test_result(result)
else:
self.execute_tests_in_pool(jobs, max_time)
# Mark any tests that weren't run as UNRESOLVED.
for test in self.tests:
if test.result is None:
test.setResult(lit.Test.Result(lit.Test.UNRESOLVED, '', 0.0)) | [
"def",
"execute_tests",
"(",
"self",
",",
"display",
",",
"jobs",
",",
"max_time",
"=",
"None",
")",
":",
"# Don't do anything if we aren't going to run any tests.",
"if",
"not",
"self",
".",
"tests",
"or",
"jobs",
"==",
"0",
":",
"return",
"# Save the display obj... | https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/utils/lit/lit/run.py#L114-L157 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | ItemContainer.InsertItems | (*args, **kwargs) | return _core_.ItemContainer_InsertItems(*args, **kwargs) | InsertItems(self, List strings, int pos) --> int
Inserts several items at once into the control. Returns the index of
the last item inserted. | InsertItems(self, List strings, int pos) --> int | [
"InsertItems",
"(",
"self",
"List",
"strings",
"int",
"pos",
")",
"--",
">",
"int"
] | def InsertItems(*args, **kwargs):
"""
InsertItems(self, List strings, int pos) --> int
Inserts several items at once into the control. Returns the index of
the last item inserted.
"""
return _core_.ItemContainer_InsertItems(*args, **kwargs) | [
"def",
"InsertItems",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"ItemContainer_InsertItems",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L12885-L12892 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/sql.py | python | SQLTable._query_iterator | (
self, result, chunksize, columns, coerce_float=True, parse_dates=None
) | Return generator through chunked result set. | Return generator through chunked result set. | [
"Return",
"generator",
"through",
"chunked",
"result",
"set",
"."
] | def _query_iterator(
self, result, chunksize, columns, coerce_float=True, parse_dates=None
):
"""Return generator through chunked result set."""
while True:
data = result.fetchmany(chunksize)
if not data:
break
else:
self.frame = DataFrame.from_records(
data, columns=columns, coerce_float=coerce_float
)
self._harmonize_columns(parse_dates=parse_dates)
if self.index is not None:
self.frame.set_index(self.index, inplace=True)
yield self.frame | [
"def",
"_query_iterator",
"(",
"self",
",",
"result",
",",
"chunksize",
",",
"columns",
",",
"coerce_float",
"=",
"True",
",",
"parse_dates",
"=",
"None",
")",
":",
"while",
"True",
":",
"data",
"=",
"result",
".",
"fetchmany",
"(",
"chunksize",
")",
"if... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/sql.py#L757-L776 | ||
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py | python | Tag.__eq__ | (self, other) | return True | Returns true iff this tag has the same name, the same attributes,
and the same contents (recursively) as the given tag.
NOTE: right now this will return false if two tags have the
same attributes in a different order. Should this be fixed? | Returns true iff this tag has the same name, the same attributes,
and the same contents (recursively) as the given tag. | [
"Returns",
"true",
"iff",
"this",
"tag",
"has",
"the",
"same",
"name",
"the",
"same",
"attributes",
"and",
"the",
"same",
"contents",
"(",
"recursively",
")",
"as",
"the",
"given",
"tag",
"."
] | def __eq__(self, other):
"""Returns true iff this tag has the same name, the same attributes,
and the same contents (recursively) as the given tag.
NOTE: right now this will return false if two tags have the
same attributes in a different order. Should this be fixed?"""
if other is self:
return True
if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other):
return False
for i in range(0, len(self.contents)):
if self.contents[i] != other.contents[i]:
return False
return True | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"self",
":",
"return",
"True",
"if",
"not",
"hasattr",
"(",
"other",
",",
"'name'",
")",
"or",
"not",
"hasattr",
"(",
"other",
",",
"'attrs'",
")",
"or",
"not",
"hasattr",
"... | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py#L657-L670 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py | python | PtyProcess.terminate | (self, force=False) | This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated. | This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated. | [
"This",
"forces",
"a",
"child",
"process",
"to",
"terminate",
".",
"It",
"starts",
"nicely",
"with",
"SIGHUP",
"and",
"SIGINT",
".",
"If",
"force",
"is",
"True",
"then",
"moves",
"onto",
"SIGKILL",
".",
"This",
"returns",
"True",
"if",
"the",
"child",
"w... | def terminate(self, force=False):
'''This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated. '''
if not self.isalive():
return True
try:
self.kill(signal.SIGHUP)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
self.kill(signal.SIGCONT)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
self.kill(signal.SIGINT)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
if force:
self.kill(signal.SIGKILL)
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
else:
return False
return False
except OSError:
# I think there are kernel timing issues that sometimes cause
# this to happen. I think isalive() reports True, but the
# process is dead to the kernel.
# Make one last attempt to see if the kernel is up to date.
time.sleep(self.delayafterterminate)
if not self.isalive():
return True
else:
return False | [
"def",
"terminate",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"isalive",
"(",
")",
":",
"return",
"True",
"try",
":",
"self",
".",
"kill",
"(",
"signal",
".",
"SIGHUP",
")",
"time",
".",
"sleep",
"(",
"self",
".... | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py#L616-L654 | ||
tiny-dnn/tiny-dnn | c0f576f5cb7b35893f62127cb7aec18f77a3bcc5 | examples/char_rnn/python/utils/encoder.py | python | Encoder.encode | (self, input, output) | Encodes input with the dictionary
Args:
input: input string to encode
output: string output path | Encodes input with the dictionary
Args:
input: input string to encode
output: string output path | [
"Encodes",
"input",
"with",
"the",
"dictionary",
"Args",
":",
"input",
":",
"input",
"string",
"to",
"encode",
"output",
":",
"string",
"output",
"path"
] | def encode(self, input, output):
"""
Encodes input with the dictionary
Args:
input: input string to encode
output: string output path
"""
assert (len(self.dec_dict) > 0 and len(self.enc_dict.keys()) > 0)
with io.FileIO(output.split('.')[0] + '.raw', 'w') as out:
for c in input:
out.write(bytes([self.enc_dict[c]])) | [
"def",
"encode",
"(",
"self",
",",
"input",
",",
"output",
")",
":",
"assert",
"(",
"len",
"(",
"self",
".",
"dec_dict",
")",
">",
"0",
"and",
"len",
"(",
"self",
".",
"enc_dict",
".",
"keys",
"(",
")",
")",
">",
"0",
")",
"with",
"io",
".",
... | https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/examples/char_rnn/python/utils/encoder.py#L60-L70 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/server.py | python | CGIHTTPRequestHandler.send_head | (self) | Version of send_head that support CGI scripts | Version of send_head that support CGI scripts | [
"Version",
"of",
"send_head",
"that",
"support",
"CGI",
"scripts"
] | def send_head(self):
"""Version of send_head that support CGI scripts"""
if self.is_cgi():
return self.run_cgi()
else:
return SimpleHTTPRequestHandler.send_head(self) | [
"def",
"send_head",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_cgi",
"(",
")",
":",
"return",
"self",
".",
"run_cgi",
"(",
")",
"else",
":",
"return",
"SimpleHTTPRequestHandler",
".",
"send_head",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/http/server.py#L985-L990 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/io_ops.py | python | ReaderBase.read_up_to | (self, queue, num_records, # pylint: disable=invalid-name
name=None) | Returns up to num_records (key, value) pairs produced by a reader.
Will dequeue a work unit from queue if necessary (e.g., when the
Reader needs to start reading from a new file since it has
finished with the previous file).
It may return less than num_records even before the last batch.
Args:
queue: A Queue or a mutable string Tensor representing a handle
to a Queue, with string work items.
num_records: Number of records to read.
name: A name for the operation (optional).
Returns:
A tuple of Tensors (keys, values).
keys: A 1-D string Tensor.
values: A 1-D string Tensor. | Returns up to num_records (key, value) pairs produced by a reader. | [
"Returns",
"up",
"to",
"num_records",
"(",
"key",
"value",
")",
"pairs",
"produced",
"by",
"a",
"reader",
"."
] | def read_up_to(self, queue, num_records, # pylint: disable=invalid-name
name=None):
"""Returns up to num_records (key, value) pairs produced by a reader.
Will dequeue a work unit from queue if necessary (e.g., when the
Reader needs to start reading from a new file since it has
finished with the previous file).
It may return less than num_records even before the last batch.
Args:
queue: A Queue or a mutable string Tensor representing a handle
to a Queue, with string work items.
num_records: Number of records to read.
name: A name for the operation (optional).
Returns:
A tuple of Tensors (keys, values).
keys: A 1-D string Tensor.
values: A 1-D string Tensor.
"""
if isinstance(queue, ops.Tensor):
queue_ref = queue
else:
queue_ref = queue.queue_ref
if self._reader_ref.dtype == dtypes.resource:
return gen_io_ops._reader_read_up_to_v2(self._reader_ref,
queue_ref,
num_records,
name=name)
else:
# For compatibility with pre-resource queues, create a ref(string) tensor
# which can be looked up as the same queue by a resource manager.
old_queue_op = gen_data_flow_ops._fake_queue(queue_ref)
return gen_io_ops._reader_read_up_to(self._reader_ref,
old_queue_op,
num_records,
name=name) | [
"def",
"read_up_to",
"(",
"self",
",",
"queue",
",",
"num_records",
",",
"# pylint: disable=invalid-name",
"name",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"queue",
",",
"ops",
".",
"Tensor",
")",
":",
"queue_ref",
"=",
"queue",
"else",
":",
"queue_... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/io_ops.py#L202-L238 | ||
xiaohaoChen/rrc_detection | 4f2b110cd122da7f55e8533275a9b4809a88785a | scripts/download_model_binary.py | python | reporthook | (count, block_size, total_size) | From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/ | From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/ | [
"From",
"http",
":",
"//",
"blog",
".",
"moleculea",
".",
"com",
"/",
"2012",
"/",
"10",
"/",
"04",
"/",
"urlretrieve",
"-",
"progres",
"-",
"indicator",
"/"
] | def reporthook(count, block_size, total_size):
"""
From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/
"""
global start_time
if count == 0:
start_time = time.time()
return
duration = (time.time() - start_time) or 0.01
progress_size = int(count * block_size)
speed = int(progress_size / (1024 * duration))
percent = int(count * block_size * 100 / total_size)
sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" %
(percent, progress_size / (1024 * 1024), speed, duration))
sys.stdout.flush() | [
"def",
"reporthook",
"(",
"count",
",",
"block_size",
",",
"total_size",
")",
":",
"global",
"start_time",
"if",
"count",
"==",
"0",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"return",
"duration",
"=",
"(",
"time",
".",
"time",
"(",
")",
... | https://github.com/xiaohaoChen/rrc_detection/blob/4f2b110cd122da7f55e8533275a9b4809a88785a/scripts/download_model_binary.py#L13-L27 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd_identity.py | python | OperatorPDIdentity.verify_pd | (self) | return self._verify_pd | Whether to verify that this `Operator` is positive definite. | Whether to verify that this `Operator` is positive definite. | [
"Whether",
"to",
"verify",
"that",
"this",
"Operator",
"is",
"positive",
"definite",
"."
] | def verify_pd(self):
"""Whether to verify that this `Operator` is positive definite."""
return self._verify_pd | [
"def",
"verify_pd",
"(",
"self",
")",
":",
"return",
"self",
".",
"_verify_pd"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd_identity.py#L129-L131 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | clang/tools/scan-build-py/libscanbuild/analyze.py | python | report_failure | (opts) | Create report when analyzer failed.
The major report is the preprocessor output. The output filename generated
randomly. The compiler output also captured into '.stderr.txt' file.
And some more execution context also saved into '.info.txt' file. | Create report when analyzer failed. | [
"Create",
"report",
"when",
"analyzer",
"failed",
"."
] | def report_failure(opts):
""" Create report when analyzer failed.
The major report is the preprocessor output. The output filename generated
randomly. The compiler output also captured into '.stderr.txt' file.
And some more execution context also saved into '.info.txt' file. """
def extension():
""" Generate preprocessor file extension. """
mapping = {'objective-c++': '.mii', 'objective-c': '.mi', 'c++': '.ii'}
return mapping.get(opts['language'], '.i')
def destination():
""" Creates failures directory if not exits yet. """
failures_dir = os.path.join(opts['output_dir'], 'failures')
if not os.path.isdir(failures_dir):
os.makedirs(failures_dir)
return failures_dir
# Classify error type: when Clang terminated by a signal it's a 'Crash'.
# (python subprocess Popen.returncode is negative when child terminated
# by signal.) Everything else is 'Other Error'.
error = 'crash' if opts['exit_code'] < 0 else 'other_error'
# Create preprocessor output file name. (This is blindly following the
# Perl implementation.)
(handle, name) = tempfile.mkstemp(suffix=extension(),
prefix='clang_' + error + '_',
dir=destination())
os.close(handle)
# Execute Clang again, but run the syntax check only.
cwd = opts['directory']
cmd = [opts['clang'], '-fsyntax-only', '-E'] + opts['flags'] + \
[opts['file'], '-o', name]
try:
cmd = get_arguments(cmd, cwd)
run_command(cmd, cwd=cwd)
except subprocess.CalledProcessError:
pass
except ClangErrorException:
pass
# write general information about the crash
with open(name + '.info.txt', 'w') as handle:
handle.write(opts['file'] + os.linesep)
handle.write(error.title().replace('_', ' ') + os.linesep)
handle.write(' '.join(cmd) + os.linesep)
handle.write(' '.join(os.uname()) + os.linesep)
handle.write(get_version(opts['clang']))
handle.close()
# write the captured output too
with open(name + '.stderr.txt', 'w') as handle:
handle.writelines(opts['error_output'])
handle.close() | [
"def",
"report_failure",
"(",
"opts",
")",
":",
"def",
"extension",
"(",
")",
":",
"\"\"\" Generate preprocessor file extension. \"\"\"",
"mapping",
"=",
"{",
"'objective-c++'",
":",
"'.mii'",
",",
"'objective-c'",
":",
"'.mi'",
",",
"'c++'",
":",
"'.ii'",
"}",
... | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/tools/scan-build-py/libscanbuild/analyze.py#L466-L519 | ||
ArduPilot/ardupilot | 6e684b3496122b8158ac412b609d00004b7ac306 | Tools/scripts/build_binaries.py | python | build_binaries.board_options | (self, board) | return [] | return board-specific options | return board-specific options | [
"return",
"board",
"-",
"specific",
"options"
] | def board_options(self, board):
'''return board-specific options'''
if board in ["bebop", "disco"]:
return ["--static"]
return [] | [
"def",
"board_options",
"(",
"self",
",",
"board",
")",
":",
"if",
"board",
"in",
"[",
"\"bebop\"",
",",
"\"disco\"",
"]",
":",
"return",
"[",
"\"--static\"",
"]",
"return",
"[",
"]"
] | https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/Tools/scripts/build_binaries.py#L89-L93 | |
bristolcrypto/SPDZ-2 | 721abfae849625a02ea49aabc534f9cf41ca643f | Compiler/program.py | python | Program.read_memory | (self, filename) | Read the clear and shared memory from a file | Read the clear and shared memory from a file | [
"Read",
"the",
"clear",
"and",
"shared",
"memory",
"from",
"a",
"file"
] | def read_memory(self, filename):
""" Read the clear and shared memory from a file """
f = open(filename)
n = int(f.next())
self.mem_c = [0]*n
self.mem_s = [0]*n
mem = self.mem_c
done_c = False
for line in f:
line = line.split(' ')
a = int(line[0])
b = int(line[1])
if a != -1:
mem[a] = b
elif done_c:
break
else:
mem = self.mem_s
done_c = True | [
"def",
"read_memory",
"(",
"self",
",",
"filename",
")",
":",
"f",
"=",
"open",
"(",
"filename",
")",
"n",
"=",
"int",
"(",
"f",
".",
"next",
"(",
")",
")",
"self",
".",
"mem_c",
"=",
"[",
"0",
"]",
"*",
"n",
"self",
".",
"mem_s",
"=",
"[",
... | https://github.com/bristolcrypto/SPDZ-2/blob/721abfae849625a02ea49aabc534f9cf41ca643f/Compiler/program.py#L194-L212 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/stats.py | python | fisher_exact | (table, alternative='two-sided') | return oddsratio, pvalue | Performs a Fisher exact test on a 2x2 contingency table.
Parameters
----------
table : array_like of ints
A 2x2 contingency table. Elements should be non-negative integers.
alternative : {'two-sided', 'less', 'greater'}, optional
Which alternative hypothesis to the null hypothesis the test uses.
Default is 'two-sided'.
Returns
-------
oddsratio : float
This is prior odds ratio and not a posterior estimate.
p_value : float
P-value, the probability of obtaining a distribution at least as
extreme as the one that was actually observed, assuming that the
null hypothesis is true.
See Also
--------
chi2_contingency : Chi-square test of independence of variables in a
contingency table.
Notes
-----
The calculated odds ratio is different from the one R uses. This scipy
implementation returns the (more common) "unconditional Maximum
Likelihood Estimate", while R uses the "conditional Maximum Likelihood
Estimate".
For tables with large numbers, the (inexact) chi-square test implemented
in the function `chi2_contingency` can also be used.
Examples
--------
Say we spend a few days counting whales and sharks in the Atlantic and
Indian oceans. In the Atlantic ocean we find 8 whales and 1 shark, in the
Indian ocean 2 whales and 5 sharks. Then our contingency table is::
Atlantic Indian
whales 8 2
sharks 1 5
We use this table to find the p-value:
>>> import scipy.stats as stats
>>> oddsratio, pvalue = stats.fisher_exact([[8, 2], [1, 5]])
>>> pvalue
0.0349...
The probability that we would observe this or an even more imbalanced ratio
by chance is about 3.5%. A commonly used significance level is 5%--if we
adopt that, we can therefore conclude that our observed imbalance is
statistically significant; whales prefer the Atlantic while sharks prefer
the Indian ocean. | Performs a Fisher exact test on a 2x2 contingency table. | [
"Performs",
"a",
"Fisher",
"exact",
"test",
"on",
"a",
"2x2",
"contingency",
"table",
"."
] | def fisher_exact(table, alternative='two-sided'):
"""Performs a Fisher exact test on a 2x2 contingency table.
Parameters
----------
table : array_like of ints
A 2x2 contingency table. Elements should be non-negative integers.
alternative : {'two-sided', 'less', 'greater'}, optional
Which alternative hypothesis to the null hypothesis the test uses.
Default is 'two-sided'.
Returns
-------
oddsratio : float
This is prior odds ratio and not a posterior estimate.
p_value : float
P-value, the probability of obtaining a distribution at least as
extreme as the one that was actually observed, assuming that the
null hypothesis is true.
See Also
--------
chi2_contingency : Chi-square test of independence of variables in a
contingency table.
Notes
-----
The calculated odds ratio is different from the one R uses. This scipy
implementation returns the (more common) "unconditional Maximum
Likelihood Estimate", while R uses the "conditional Maximum Likelihood
Estimate".
For tables with large numbers, the (inexact) chi-square test implemented
in the function `chi2_contingency` can also be used.
Examples
--------
Say we spend a few days counting whales and sharks in the Atlantic and
Indian oceans. In the Atlantic ocean we find 8 whales and 1 shark, in the
Indian ocean 2 whales and 5 sharks. Then our contingency table is::
Atlantic Indian
whales 8 2
sharks 1 5
We use this table to find the p-value:
>>> import scipy.stats as stats
>>> oddsratio, pvalue = stats.fisher_exact([[8, 2], [1, 5]])
>>> pvalue
0.0349...
The probability that we would observe this or an even more imbalanced ratio
by chance is about 3.5%. A commonly used significance level is 5%--if we
adopt that, we can therefore conclude that our observed imbalance is
statistically significant; whales prefer the Atlantic while sharks prefer
the Indian ocean.
"""
hypergeom = distributions.hypergeom
c = np.asarray(table, dtype=np.int64) # int32 is not enough for the algorithm
if not c.shape == (2, 2):
raise ValueError("The input `table` must be of shape (2, 2).")
if np.any(c < 0):
raise ValueError("All values in `table` must be nonnegative.")
if 0 in c.sum(axis=0) or 0 in c.sum(axis=1):
# If both values in a row or column are zero, the p-value is 1 and
# the odds ratio is NaN.
return np.nan, 1.0
if c[1,0] > 0 and c[0,1] > 0:
oddsratio = c[0,0] * c[1,1] / float(c[1,0] * c[0,1])
else:
oddsratio = np.inf
n1 = c[0,0] + c[0,1]
n2 = c[1,0] + c[1,1]
n = c[0,0] + c[1,0]
def binary_search(n, n1, n2, side):
"""Binary search for where to begin lower/upper halves in two-sided
test.
"""
if side == "upper":
minval = mode
maxval = n
else:
minval = 0
maxval = mode
guess = -1
while maxval - minval > 1:
if maxval == minval + 1 and guess == minval:
guess = maxval
else:
guess = (maxval + minval) // 2
pguess = hypergeom.pmf(guess, n1 + n2, n1, n)
if side == "upper":
ng = guess - 1
else:
ng = guess + 1
if pguess <= pexact < hypergeom.pmf(ng, n1 + n2, n1, n):
break
elif pguess < pexact:
maxval = guess
else:
minval = guess
if guess == -1:
guess = minval
if side == "upper":
while guess > 0 and hypergeom.pmf(guess, n1 + n2, n1, n) < pexact * epsilon:
guess -= 1
while hypergeom.pmf(guess, n1 + n2, n1, n) > pexact / epsilon:
guess += 1
else:
while hypergeom.pmf(guess, n1 + n2, n1, n) < pexact * epsilon:
guess += 1
while guess > 0 and hypergeom.pmf(guess, n1 + n2, n1, n) > pexact / epsilon:
guess -= 1
return guess
if alternative == 'less':
pvalue = hypergeom.cdf(c[0,0], n1 + n2, n1, n)
elif alternative == 'greater':
# Same formula as the 'less' case, but with the second column.
pvalue = hypergeom.cdf(c[0,1], n1 + n2, n1, c[0,1] + c[1,1])
elif alternative == 'two-sided':
mode = int(float((n + 1) * (n1 + 1)) / (n1 + n2 + 2))
pexact = hypergeom.pmf(c[0,0], n1 + n2, n1, n)
pmode = hypergeom.pmf(mode, n1 + n2, n1, n)
epsilon = 1 - 1e-4
if np.abs(pexact - pmode) / np.maximum(pexact, pmode) <= 1 - epsilon:
return oddsratio, 1.
elif c[0,0] < mode:
plower = hypergeom.cdf(c[0,0], n1 + n2, n1, n)
if hypergeom.pmf(n, n1 + n2, n1, n) > pexact / epsilon:
return oddsratio, plower
guess = binary_search(n, n1, n2, "upper")
pvalue = plower + hypergeom.sf(guess - 1, n1 + n2, n1, n)
else:
pupper = hypergeom.sf(c[0,0] - 1, n1 + n2, n1, n)
if hypergeom.pmf(0, n1 + n2, n1, n) > pexact / epsilon:
return oddsratio, pupper
guess = binary_search(n, n1, n2, "lower")
pvalue = pupper + hypergeom.cdf(guess, n1 + n2, n1, n)
else:
msg = "`alternative` should be one of {'two-sided', 'less', 'greater'}"
raise ValueError(msg)
if pvalue > 1.0:
pvalue = 1.0
return oddsratio, pvalue | [
"def",
"fisher_exact",
"(",
"table",
",",
"alternative",
"=",
"'two-sided'",
")",
":",
"hypergeom",
"=",
"distributions",
".",
"hypergeom",
"c",
"=",
"np",
".",
"asarray",
"(",
"table",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"# int32 is not enough for t... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/stats.py#L3044-L3201 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/array_analysis.py | python | wrap_index | (typingctx, idx, size) | return signature(unified_ty, idx, size), codegen | Calculate index value "idx" relative to a size "size" value as
(idx % size), where "size" is known to be positive.
Note that we use the mod(%) operation here instead of
(idx < 0 ? idx + size : idx) because we may have situations
where idx > size due to the way indices are calculated
during slice/range analysis. | Calculate index value "idx" relative to a size "size" value as
(idx % size), where "size" is known to be positive.
Note that we use the mod(%) operation here instead of
(idx < 0 ? idx + size : idx) because we may have situations
where idx > size due to the way indices are calculated
during slice/range analysis. | [
"Calculate",
"index",
"value",
"idx",
"relative",
"to",
"a",
"size",
"size",
"value",
"as",
"(",
"idx",
"%",
"size",
")",
"where",
"size",
"is",
"known",
"to",
"be",
"positive",
".",
"Note",
"that",
"we",
"use",
"the",
"mod",
"(",
"%",
")",
"operatio... | def wrap_index(typingctx, idx, size):
"""
Calculate index value "idx" relative to a size "size" value as
(idx % size), where "size" is known to be positive.
Note that we use the mod(%) operation here instead of
(idx < 0 ? idx + size : idx) because we may have situations
where idx > size due to the way indices are calculated
during slice/range analysis.
"""
unified_ty = typingctx.unify_types(idx, size)
if not unified_ty:
raise ValueError("Argument types for wrap_index must match")
def codegen(context, builder, sig, args):
ll_unified_ty = context.get_data_type(unified_ty)
idx = builder.sext(args[0], ll_unified_ty)
size = builder.sext(args[1], ll_unified_ty)
neg_size = builder.neg(size)
zero = llvmlite.ir.Constant(ll_unified_ty, 0)
idx_negative = builder.icmp_signed('<', idx, zero)
pos_oversize = builder.icmp_signed('>=', idx, size)
neg_oversize = builder.icmp_signed('<=', idx, neg_size)
pos_res = builder.select(pos_oversize, size, idx)
neg_res = builder.select(neg_oversize, zero, builder.add(idx, size))
mod = builder.select(idx_negative, neg_res, pos_res)
return mod
return signature(unified_ty, idx, size), codegen | [
"def",
"wrap_index",
"(",
"typingctx",
",",
"idx",
",",
"size",
")",
":",
"unified_ty",
"=",
"typingctx",
".",
"unify_types",
"(",
"idx",
",",
"size",
")",
"if",
"not",
"unified_ty",
":",
"raise",
"ValueError",
"(",
"\"Argument types for wrap_index must match\""... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/array_analysis.py#L62-L89 | |
apple/swift-clang | d7403439fc6641751840b723e7165fb02f52db95 | bindings/python/clang/cindex.py | python | Index.read | (self, path) | return TranslationUnit.from_ast_file(path, self) | Load a TranslationUnit from the given AST file. | Load a TranslationUnit from the given AST file. | [
"Load",
"a",
"TranslationUnit",
"from",
"the",
"given",
"AST",
"file",
"."
] | def read(self, path):
"""Load a TranslationUnit from the given AST file."""
return TranslationUnit.from_ast_file(path, self) | [
"def",
"read",
"(",
"self",
",",
"path",
")",
":",
"return",
"TranslationUnit",
".",
"from_ast_file",
"(",
"path",
",",
"self",
")"
] | https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/bindings/python/clang/cindex.py#L2703-L2705 | |
rootm0s/Protectors | 5b3f4d11687a5955caf9c3af30666c4bfc2c19ab | OWASP-ZSC/module/readline_windows/pyreadline/console/ironpython_console.py | python | Console.cursor | (self, visible=True, size=None) | Set cursor on or off. | Set cursor on or off. | [
"Set",
"cursor",
"on",
"or",
"off",
"."
] | def cursor(self, visible=True, size=None):
'''Set cursor on or off.'''
System.Console.CursorVisible = visible | [
"def",
"cursor",
"(",
"self",
",",
"visible",
"=",
"True",
",",
"size",
"=",
"None",
")",
":",
"System",
".",
"Console",
".",
"CursorVisible",
"=",
"visible"
] | https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/console/ironpython_console.py#L359-L361 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pluggy/py2/pluggy/callers.py | python | _Result.get_result | (self) | Get the result(s) for this hook call.
If the hook was marked as a ``firstresult`` only a single value
will be returned otherwise a list of results. | Get the result(s) for this hook call. | [
"Get",
"the",
"result",
"(",
"s",
")",
"for",
"this",
"hook",
"call",
"."
] | def get_result(self):
"""Get the result(s) for this hook call.
If the hook was marked as a ``firstresult`` only a single value
will be returned otherwise a list of results.
"""
__tracebackhide__ = True
if self._excinfo is None:
return self._result
else:
ex = self._excinfo
if _py3:
raise ex[1].with_traceback(ex[2])
_reraise(*ex) | [
"def",
"get_result",
"(",
"self",
")",
":",
"__tracebackhide__",
"=",
"True",
"if",
"self",
".",
"_excinfo",
"is",
"None",
":",
"return",
"self",
".",
"_result",
"else",
":",
"ex",
"=",
"self",
".",
"_excinfo",
"if",
"_py3",
":",
"raise",
"ex",
"[",
... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pluggy/py2/pluggy/callers.py#L68-L81 | ||
GrammaTech/gtirb | 415dd72e1e3c475004d013723c16cdcb29c0826e | python/gtirb/ir.py | python | IR.cfg_nodes | (self) | return itertools.chain.from_iterable(m.cfg_nodes for m in self.modules) | The :class:`CfgNode`\\s in this IR. | The :class:`CfgNode`\\s in this IR. | [
"The",
":",
"class",
":",
"CfgNode",
"\\\\",
"s",
"in",
"this",
"IR",
"."
] | def cfg_nodes(self) -> typing.Iterator[CfgNode]:
"""The :class:`CfgNode`\\s in this IR."""
return itertools.chain.from_iterable(m.cfg_nodes for m in self.modules) | [
"def",
"cfg_nodes",
"(",
"self",
")",
"->",
"typing",
".",
"Iterator",
"[",
"CfgNode",
"]",
":",
"return",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"m",
".",
"cfg_nodes",
"for",
"m",
"in",
"self",
".",
"modules",
")"
] | https://github.com/GrammaTech/gtirb/blob/415dd72e1e3c475004d013723c16cdcb29c0826e/python/gtirb/ir.py#L242-L245 | |
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | execer.py | python | execipynb | (filename, glb=None, loc=None) | A function equivalent to the Python 2.x execfile statement but for IPython
notebooks. | A function equivalent to the Python 2.x execfile statement but for IPython
notebooks. | [
"A",
"function",
"equivalent",
"to",
"the",
"Python",
"2",
".",
"x",
"execfile",
"statement",
"but",
"for",
"IPython",
"notebooks",
"."
] | def execipynb(filename, glb=None, loc=None):
"""A function equivalent to the Python 2.x execfile statement but for IPython
notebooks."""
glb = {} if glb is None else glb
glb['get_ipython'] = get_ipython
out = NamedTemporaryFile()
err = NamedTemporaryFile()
env = os.environ.copy()
env['TERM'] = 'dumb'
env['PYTHONIOENCODING'] = 'utf-8'
rtn = subprocess.check_call(['jupyter', 'nbconvert', '--to=python', '--stdout',
filename], stdout=out, stderr=err, env=env)
out.seek(0)
src = out.read()
out.close()
err.close()
exec(compile(src, filename, "exec"), glb, loc) | [
"def",
"execipynb",
"(",
"filename",
",",
"glb",
"=",
"None",
",",
"loc",
"=",
"None",
")",
":",
"glb",
"=",
"{",
"}",
"if",
"glb",
"is",
"None",
"else",
"glb",
"glb",
"[",
"'get_ipython'",
"]",
"=",
"get_ipython",
"out",
"=",
"NamedTemporaryFile",
"... | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/execer.py#L23-L39 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/dataview.py | python | DataViewEvent.GetColumn | (*args, **kwargs) | return _dataview.DataViewEvent_GetColumn(*args, **kwargs) | GetColumn(self) -> int | GetColumn(self) -> int | [
"GetColumn",
"(",
"self",
")",
"-",
">",
"int"
] | def GetColumn(*args, **kwargs):
"""GetColumn(self) -> int"""
return _dataview.DataViewEvent_GetColumn(*args, **kwargs) | [
"def",
"GetColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewEvent_GetColumn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L1908-L1910 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/client/session.py | python | Session.reset | (target, containers=None, config=None) | Resets resource containers on `target`, and close all connected sessions.
A resource container is distributed across all workers in the
same cluster as `target`. When a resource container on `target`
is reset, resources associated with that container will be cleared.
In particular, all Variables in the container will become undefined:
they lose their values and shapes.
NOTE:
(i) reset() is currently only implemented for distributed sessions.
(ii) Any sessions on the master named by `target` will be closed.
If no resource containers are provided, all containers are reset.
Args:
target: The execution engine to connect to.
containers: A list of resource container name strings, or `None` if all of
all the containers are to be reset.
config: (Optional.) Protocol buffer with configuration options.
Raises:
tf.errors.OpError: Or one of its subclasses if an error occurs while
resetting containers. | Resets resource containers on `target`, and close all connected sessions. | [
"Resets",
"resource",
"containers",
"on",
"target",
"and",
"close",
"all",
"connected",
"sessions",
"."
] | def reset(target, containers=None, config=None):
"""Resets resource containers on `target`, and close all connected sessions.
A resource container is distributed across all workers in the
same cluster as `target`. When a resource container on `target`
is reset, resources associated with that container will be cleared.
In particular, all Variables in the container will become undefined:
they lose their values and shapes.
NOTE:
(i) reset() is currently only implemented for distributed sessions.
(ii) Any sessions on the master named by `target` will be closed.
If no resource containers are provided, all containers are reset.
Args:
target: The execution engine to connect to.
containers: A list of resource container name strings, or `None` if all of
all the containers are to be reset.
config: (Optional.) Protocol buffer with configuration options.
Raises:
tf.errors.OpError: Or one of its subclasses if an error occurs while
resetting containers.
"""
if target is not None:
target = compat.as_bytes(target)
if containers is not None:
containers = [compat.as_bytes(c) for c in containers]
else:
containers = []
tf_session.TF_Reset(target, containers, config) | [
"def",
"reset",
"(",
"target",
",",
"containers",
"=",
"None",
",",
"config",
"=",
"None",
")",
":",
"if",
"target",
"is",
"not",
"None",
":",
"target",
"=",
"compat",
".",
"as_bytes",
"(",
"target",
")",
"if",
"containers",
"is",
"not",
"None",
":",... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/client/session.py#L1512-L1543 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/cgi.py | python | print_environ_usage | () | Dump a list of environment variables used by CGI as HTML. | Dump a list of environment variables used by CGI as HTML. | [
"Dump",
"a",
"list",
"of",
"environment",
"variables",
"used",
"by",
"CGI",
"as",
"HTML",
"."
] | def print_environ_usage():
"""Dump a list of environment variables used by CGI as HTML."""
print """
<H3>These environment variables could have been set:</H3>
<UL>
<LI>AUTH_TYPE
<LI>CONTENT_LENGTH
<LI>CONTENT_TYPE
<LI>DATE_GMT
<LI>DATE_LOCAL
<LI>DOCUMENT_NAME
<LI>DOCUMENT_ROOT
<LI>DOCUMENT_URI
<LI>GATEWAY_INTERFACE
<LI>LAST_MODIFIED
<LI>PATH
<LI>PATH_INFO
<LI>PATH_TRANSLATED
<LI>QUERY_STRING
<LI>REMOTE_ADDR
<LI>REMOTE_HOST
<LI>REMOTE_IDENT
<LI>REMOTE_USER
<LI>REQUEST_METHOD
<LI>SCRIPT_NAME
<LI>SERVER_NAME
<LI>SERVER_PORT
<LI>SERVER_PROTOCOL
<LI>SERVER_ROOT
<LI>SERVER_SOFTWARE
</UL>
In addition, HTTP headers sent by the server may be passed in the
environment as well. Here are some common variable names:
<UL>
<LI>HTTP_ACCEPT
<LI>HTTP_CONNECTION
<LI>HTTP_HOST
<LI>HTTP_PRAGMA
<LI>HTTP_REFERER
<LI>HTTP_USER_AGENT
</UL>
""" | [
"def",
"print_environ_usage",
"(",
")",
":",
"print",
"\"\"\"\n<H3>These environment variables could have been set:</H3>\n<UL>\n<LI>AUTH_TYPE\n<LI>CONTENT_LENGTH\n<LI>CONTENT_TYPE\n<LI>DATE_GMT\n<LI>DATE_LOCAL\n<LI>DOCUMENT_NAME\n<LI>DOCUMENT_ROOT\n<LI>DOCUMENT_URI\n<LI>GATEWAY_INTERFACE\n<LI>LAST_MODIF... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/cgi.py#L983-L1024 | ||
geemaple/leetcode | 68bc5032e1ee52c22ef2f2e608053484c487af54 | leetcode/282.expression-add-operators.py | python | Solution.addOperators | (self, num, target) | return res | :type num: str
:type target: int
:rtype: List[str] | :type num: str
:type target: int
:rtype: List[str] | [
":",
"type",
"num",
":",
"str",
":",
"type",
"target",
":",
"int",
":",
"rtype",
":",
"List",
"[",
"str",
"]"
] | def addOperators(self, num, target):
"""
:type num: str
:type target: int
:rtype: List[str]
"""
if num is None or len(num) == 0:
return []
self.num = num
self.target = target
res = []
self.dfs(0, 0, 0, '', res)
return res | [
"def",
"addOperators",
"(",
"self",
",",
"num",
",",
"target",
")",
":",
"if",
"num",
"is",
"None",
"or",
"len",
"(",
"num",
")",
"==",
"0",
":",
"return",
"[",
"]",
"self",
".",
"num",
"=",
"num",
"self",
".",
"target",
"=",
"target",
"res",
"... | https://github.com/geemaple/leetcode/blob/68bc5032e1ee52c22ef2f2e608053484c487af54/leetcode/282.expression-add-operators.py#L7-L23 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/evaluation.py | python | _MultiStepStopAfterNEvalsHook.__init__ | (self, num_evals, steps_per_run=1) | Constructs the run hook.
Args:
num_evals: The number of evaluations to run for. if set to None, will
iterate the dataset until all inputs are exhausted.
steps_per_run: Number of steps executed per run call. | Constructs the run hook. | [
"Constructs",
"the",
"run",
"hook",
"."
] | def __init__(self, num_evals, steps_per_run=1):
"""Constructs the run hook.
Args:
num_evals: The number of evaluations to run for. if set to None, will
iterate the dataset until all inputs are exhausted.
steps_per_run: Number of steps executed per run call.
"""
self._num_evals = num_evals
self._evals_completed = None
self._steps_per_run_initial_value = steps_per_run | [
"def",
"__init__",
"(",
"self",
",",
"num_evals",
",",
"steps_per_run",
"=",
"1",
")",
":",
"self",
".",
"_num_evals",
"=",
"num_evals",
"self",
".",
"_evals_completed",
"=",
"None",
"self",
".",
"_steps_per_run_initial_value",
"=",
"steps_per_run"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/evaluation.py#L84-L94 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Draft/draftguitools/gui_pathtwistedarray.py | python | PathTwistedLinkArray.GetResources | (self) | return {'Pixmap': 'Draft_PathTwistedLinkArray',
'MenuText': QT_TRANSLATE_NOOP("Draft_PathTwistedLinkArray","Path twisted Link array"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_PathTwistedLinkArray","Like the PathTwistedArray tool, but creates a 'Link array' instead.\nA 'Link array' is more efficient when handling many copies but the 'Fuse' option cannot be used.")} | Set icon, menu and tooltip. | Set icon, menu and tooltip. | [
"Set",
"icon",
"menu",
"and",
"tooltip",
"."
] | def GetResources(self):
"""Set icon, menu and tooltip."""
return {'Pixmap': 'Draft_PathTwistedLinkArray',
'MenuText': QT_TRANSLATE_NOOP("Draft_PathTwistedLinkArray","Path twisted Link array"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_PathTwistedLinkArray","Like the PathTwistedArray tool, but creates a 'Link array' instead.\nA 'Link array' is more efficient when handling many copies but the 'Fuse' option cannot be used.")} | [
"def",
"GetResources",
"(",
"self",
")",
":",
"return",
"{",
"'Pixmap'",
":",
"'Draft_PathTwistedLinkArray'",
",",
"'MenuText'",
":",
"QT_TRANSLATE_NOOP",
"(",
"\"Draft_PathTwistedLinkArray\"",
",",
"\"Path twisted Link array\"",
")",
",",
"'ToolTip'",
":",
"QT_TRANSLAT... | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_pathtwistedarray.py#L117-L122 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TMemIn.__init__ | (self, *args) | __init__(TMemIn self, TMem _Mem, int const & _BfC=0) -> TMemIn
Parameters:
_Mem: TMem const &
_BfC: int const &
__init__(TMemIn self, TMem _Mem) -> TMemIn
Parameters:
_Mem: TMem const & | __init__(TMemIn self, TMem _Mem, int const & _BfC=0) -> TMemIn | [
"__init__",
"(",
"TMemIn",
"self",
"TMem",
"_Mem",
"int",
"const",
"&",
"_BfC",
"=",
"0",
")",
"-",
">",
"TMemIn"
] | def __init__(self, *args):
"""
__init__(TMemIn self, TMem _Mem, int const & _BfC=0) -> TMemIn
Parameters:
_Mem: TMem const &
_BfC: int const &
__init__(TMemIn self, TMem _Mem) -> TMemIn
Parameters:
_Mem: TMem const &
"""
_snap.TMemIn_swiginit(self,_snap.new_TMemIn(*args)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"_snap",
".",
"TMemIn_swiginit",
"(",
"self",
",",
"_snap",
".",
"new_TMemIn",
"(",
"*",
"args",
")",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L8346-L8360 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/external/bazel_tools/tools/objc/j2objc_dead_code_pruner.py | python | BuildReachableFileSet | (entry_classes, reachability_tree, header_mapping,
archive_source_file_mapping=None) | return reachable_files | Builds a set of reachable translated files from entry Java classes.
Args:
entry_classes: A comma separated list of Java entry classes.
reachability_tree: A dict mapping translated files to their direct
dependencies.
header_mapping: A dict mapping Java class names to translated source files.
archive_source_file_mapping: A dict mapping source files to the associated
archive file that contains them.
Returns:
A set of reachable translated files from the given list of entry classes.
Raises:
Exception: If there is an entry class that is not being transpiled in this
j2objc_library. | Builds a set of reachable translated files from entry Java classes. | [
"Builds",
"a",
"set",
"of",
"reachable",
"translated",
"files",
"from",
"entry",
"Java",
"classes",
"."
] | def BuildReachableFileSet(entry_classes, reachability_tree, header_mapping,
archive_source_file_mapping=None):
"""Builds a set of reachable translated files from entry Java classes.
Args:
entry_classes: A comma separated list of Java entry classes.
reachability_tree: A dict mapping translated files to their direct
dependencies.
header_mapping: A dict mapping Java class names to translated source files.
archive_source_file_mapping: A dict mapping source files to the associated
archive file that contains them.
Returns:
A set of reachable translated files from the given list of entry classes.
Raises:
Exception: If there is an entry class that is not being transpiled in this
j2objc_library.
"""
transpiled_entry_files = []
for entry_class in entry_classes.split(','):
if entry_class not in header_mapping:
raise Exception(entry_class +
'is not in the transitive Java deps of included ' +
'j2objc_library rules.')
transpiled_entry_files.append(header_mapping[entry_class])
# Translated files going into the same static library archive with duplicated
# base names also need to be added to the set of entry files.
#
# This edge case is ignored because we currently cannot correctly perform
# dead code removal in this case. The object file entries in static library
# archives are named by the base names of the original source files. If two
# source files (e.g., foo/bar.m, bar/bar.m) go into the same archive and
# share the same base name (bar.m), their object file entries inside the
# archive will have the same name (bar.o). We cannot correctly handle this
# case because current archive tools (ar, ranlib, etc.) do not handle this
# case very well.
if archive_source_file_mapping:
transpiled_entry_files.extend(_DuplicatedFiles(archive_source_file_mapping))
# Translated files from package-info.java are also added to the entry files
# because they are needed to resolve ObjC class names with prefixes and these
# files may also have dependencies.
for transpiled_file in reachability_tree:
if transpiled_file.endswith('package-info'):
transpiled_entry_files.append(transpiled_file)
reachable_files = set()
for transpiled_entry_file in transpiled_entry_files:
reachable_files.add(transpiled_entry_file)
current_level_deps = []
# We need to check if the transpiled file is in the reachability tree
# because J2ObjC protos are not analyzed for dead code stripping and
# therefore are not in the reachability tree at all.
if transpiled_entry_file in reachability_tree:
current_level_deps = reachability_tree[transpiled_entry_file]
while current_level_deps:
next_level_deps = []
for dep in current_level_deps:
if dep not in reachable_files:
reachable_files.add(dep)
if dep in reachability_tree:
next_level_deps.extend(reachability_tree[dep])
current_level_deps = next_level_deps
return reachable_files | [
"def",
"BuildReachableFileSet",
"(",
"entry_classes",
",",
"reachability_tree",
",",
"header_mapping",
",",
"archive_source_file_mapping",
"=",
"None",
")",
":",
"transpiled_entry_files",
"=",
"[",
"]",
"for",
"entry_class",
"in",
"entry_classes",
".",
"split",
"(",
... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/tools/objc/j2objc_dead_code_pruner.py#L88-L151 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/mozjar.py | python | JarFileReader.seek | (self, pos, whence=os.SEEK_SET) | return self.uncompressed_data.seek(pos, whence) | Change the current position in the uncompressed data. Subsequent reads
will start from there. | Change the current position in the uncompressed data. Subsequent reads
will start from there. | [
"Change",
"the",
"current",
"position",
"in",
"the",
"uncompressed",
"data",
".",
"Subsequent",
"reads",
"will",
"start",
"from",
"there",
"."
] | def seek(self, pos, whence=os.SEEK_SET):
'''
Change the current position in the uncompressed data. Subsequent reads
will start from there.
'''
return self.uncompressed_data.seek(pos, whence) | [
"def",
"seek",
"(",
"self",
",",
"pos",
",",
"whence",
"=",
"os",
".",
"SEEK_SET",
")",
":",
"return",
"self",
".",
"uncompressed_data",
".",
"seek",
"(",
"pos",
",",
"whence",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mozbuild/mozpack/mozjar.py#L290-L295 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/prefdlg.py | python | PreferencesDialog.__init__ | (self, parent, id_=wx.ID_ANY,
style=wx.DEFAULT_DIALOG_STYLE | wx.TAB_TRAVERSAL) | Initializes the preference dialog
@param parent: The parent window of this window
@keyword id_: The id of this window
@keyword style: Window Style bitmask | Initializes the preference dialog
@param parent: The parent window of this window
@keyword id_: The id of this window
@keyword style: Window Style bitmask | [
"Initializes",
"the",
"preference",
"dialog",
"@param",
"parent",
":",
"The",
"parent",
"window",
"of",
"this",
"window",
"@keyword",
"id_",
":",
"The",
"id",
"of",
"this",
"window",
"@keyword",
"style",
":",
"Window",
"Style",
"bitmask"
] | def __init__(self, parent, id_=wx.ID_ANY,
style=wx.DEFAULT_DIALOG_STYLE | wx.TAB_TRAVERSAL):
"""Initializes the preference dialog
@param parent: The parent window of this window
@keyword id_: The id of this window
@keyword style: Window Style bitmask
"""
super(PreferencesDialog, self).__init__(parent, id_,
_("Preferences - Editra"),
style=style)
util.SetWindowIcon(self)
# Extra Styles
self.SetTransparent(Profile_Get('ALPHA', default=255))
# Attributes
self._accel = wx.AcceleratorTable([(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, wx.ID_CLOSE)])
self.SetAcceleratorTable(self._accel)
self._tbook = PrefTools(self)
sizer = wx.BoxSizer(wx.VERTICAL)
# Layout
sizer.Add(self._tbook, 1, wx.EXPAND)
self.SetSizer(sizer)
self.SetAutoLayout(True)
self.SetInitialSize()
wx.GetApp().RegisterWindow(repr(self), self, True)
# Bind Events
self.Bind(wx.EVT_MENU, lambda evt: self.Close(), id=wx.ID_CLOSE)
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.Bind(wx.EVT_SHOW, self.OnShow) | [
"def",
"__init__",
"(",
"self",
",",
"parent",
",",
"id_",
"=",
"wx",
".",
"ID_ANY",
",",
"style",
"=",
"wx",
".",
"DEFAULT_DIALOG_STYLE",
"|",
"wx",
".",
"TAB_TRAVERSAL",
")",
":",
"super",
"(",
"PreferencesDialog",
",",
"self",
")",
".",
"__init__",
... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/prefdlg.py#L101-L133 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/zipfile.py | python | ZipExtFile.readline | (self, limit=-1) | return io.BufferedIOBase.readline(self, limit) | Read and return a line from the stream.
If limit is specified, at most limit bytes will be read. | Read and return a line from the stream. | [
"Read",
"and",
"return",
"a",
"line",
"from",
"the",
"stream",
"."
] | def readline(self, limit=-1):
"""Read and return a line from the stream.
If limit is specified, at most limit bytes will be read.
"""
if limit < 0:
# Shortcut common case - newline found in buffer.
i = self._readbuffer.find(b'\n', self._offset) + 1
if i > 0:
line = self._readbuffer[self._offset: i]
self._offset = i
return line
return io.BufferedIOBase.readline(self, limit) | [
"def",
"readline",
"(",
"self",
",",
"limit",
"=",
"-",
"1",
")",
":",
"if",
"limit",
"<",
"0",
":",
"# Shortcut common case - newline found in buffer.",
"i",
"=",
"self",
".",
"_readbuffer",
".",
"find",
"(",
"b'\\n'",
",",
"self",
".",
"_offset",
")",
... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/zipfile.py#L875-L889 | |
Cantera/cantera | 0119484b261967ccb55a0066c020599cacc312e4 | interfaces/cython/cantera/ctml_writer.py | python | isnum | (a) | True if a is an integer or floating-point number. | True if a is an integer or floating-point number. | [
"True",
"if",
"a",
"is",
"an",
"integer",
"or",
"floating",
"-",
"point",
"number",
"."
] | def isnum(a):
"""True if a is an integer or floating-point number."""
if isinstance(a, (int, float)):
return 1
else:
return 0 | [
"def",
"isnum",
"(",
"a",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"1",
"else",
":",
"return",
"0"
] | https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/ctml_writer.py#L300-L305 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/pybind/mgr/dashboard/services/access_control.py | python | ac_user_set_password | (_, username: str, inbuf: str,
force_password: bool = False) | Set user password from -i <file> | Set user password from -i <file> | [
"Set",
"user",
"password",
"from",
"-",
"i",
"<file",
">"
] | def ac_user_set_password(_, username: str, inbuf: str,
force_password: bool = False):
'''
Set user password from -i <file>
'''
password = inbuf
try:
user = mgr.ACCESS_CTRL_DB.get_user(username)
if not force_password:
pw_check = PasswordPolicy(password, user.name)
pw_check.check_all()
user.set_password(password)
mgr.ACCESS_CTRL_DB.save()
return 0, json.dumps(user.to_dict()), ''
except PasswordPolicyException as ex:
return -errno.EINVAL, '', str(ex)
except UserDoesNotExist as ex:
return -errno.ENOENT, '', str(ex) | [
"def",
"ac_user_set_password",
"(",
"_",
",",
"username",
":",
"str",
",",
"inbuf",
":",
"str",
",",
"force_password",
":",
"bool",
"=",
"False",
")",
":",
"password",
"=",
"inbuf",
"try",
":",
"user",
"=",
"mgr",
".",
"ACCESS_CTRL_DB",
".",
"get_user",
... | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/dashboard/services/access_control.py#L872-L889 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | FontData.GetInitialFont | (*args, **kwargs) | return _windows_.FontData_GetInitialFont(*args, **kwargs) | GetInitialFont(self) -> Font
Gets the font that will be initially used by the font dialog. This
should have previously been set by the application. | GetInitialFont(self) -> Font | [
"GetInitialFont",
"(",
"self",
")",
"-",
">",
"Font"
] | def GetInitialFont(*args, **kwargs):
"""
GetInitialFont(self) -> Font
Gets the font that will be initially used by the font dialog. This
should have previously been set by the application.
"""
return _windows_.FontData_GetInitialFont(*args, **kwargs) | [
"def",
"GetInitialFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"FontData_GetInitialFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L3501-L3508 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py | python | Maildir._lookup | (self, key) | Use TOC to return subpath for given key, or raise a KeyError. | Use TOC to return subpath for given key, or raise a KeyError. | [
"Use",
"TOC",
"to",
"return",
"subpath",
"for",
"given",
"key",
"or",
"raise",
"a",
"KeyError",
"."
] | def _lookup(self, key):
"""Use TOC to return subpath for given key, or raise a KeyError."""
try:
if os.path.exists(os.path.join(self._path, self._toc[key])):
return self._toc[key]
except KeyError:
pass
self._refresh()
try:
return self._toc[key]
except KeyError:
raise KeyError('No message with key: %s' % key) from None | [
"def",
"_lookup",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"self",
".",
"_toc",
"[",
"key",
"]",
")",
")",
":",
"return",
"self... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py#L547-L558 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xpathParserContext.xpathBooleanFunction | (self, nargs) | Implement the boolean() XPath function boolean
boolean(object) The boolean function converts its argument
to a boolean as follows: - a number is true if and only if
it is neither positive or negative zero nor NaN - a
node-set is true if and only if it is non-empty - a string
is true if and only if its length is non-zero | Implement the boolean() XPath function boolean
boolean(object) The boolean function converts its argument
to a boolean as follows: - a number is true if and only if
it is neither positive or negative zero nor NaN - a
node-set is true if and only if it is non-empty - a string
is true if and only if its length is non-zero | [
"Implement",
"the",
"boolean",
"()",
"XPath",
"function",
"boolean",
"boolean",
"(",
"object",
")",
"The",
"boolean",
"function",
"converts",
"its",
"argument",
"to",
"a",
"boolean",
"as",
"follows",
":",
"-",
"a",
"number",
"is",
"true",
"if",
"and",
"onl... | def xpathBooleanFunction(self, nargs):
"""Implement the boolean() XPath function boolean
boolean(object) The boolean function converts its argument
to a boolean as follows: - a number is true if and only if
it is neither positive or negative zero nor NaN - a
node-set is true if and only if it is non-empty - a string
is true if and only if its length is non-zero """
libxml2mod.xmlXPathBooleanFunction(self._o, nargs) | [
"def",
"xpathBooleanFunction",
"(",
"self",
",",
"nargs",
")",
":",
"libxml2mod",
".",
"xmlXPathBooleanFunction",
"(",
"self",
".",
"_o",
",",
"nargs",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L7438-L7445 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py | python | BufferingFormatter.formatHeader | (self, records) | return "" | Return the header string for the specified records. | Return the header string for the specified records. | [
"Return",
"the",
"header",
"string",
"for",
"the",
"specified",
"records",
"."
] | def formatHeader(self, records):
"""
Return the header string for the specified records.
"""
return "" | [
"def",
"formatHeader",
"(",
"self",
",",
"records",
")",
":",
"return",
"\"\""
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py#L646-L650 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/google/protobuf-py/google/protobuf/internal/encoder.py | python | _SignedVarintEncoder | () | return EncodeSignedVarint | Return an encoder for a basic signed varint value (does not include
tag). | Return an encoder for a basic signed varint value (does not include
tag). | [
"Return",
"an",
"encoder",
"for",
"a",
"basic",
"signed",
"varint",
"value",
"(",
"does",
"not",
"include",
"tag",
")",
"."
] | def _SignedVarintEncoder():
"""Return an encoder for a basic signed varint value (does not include
tag)."""
local_chr = chr
def EncodeSignedVarint(write, value):
if value < 0:
value += (1 << 64)
bits = value & 0x7f
value >>= 7
while value:
write(local_chr(0x80|bits))
bits = value & 0x7f
value >>= 7
return write(local_chr(bits))
return EncodeSignedVarint | [
"def",
"_SignedVarintEncoder",
"(",
")",
":",
"local_chr",
"=",
"chr",
"def",
"EncodeSignedVarint",
"(",
"write",
",",
"value",
")",
":",
"if",
"value",
"<",
"0",
":",
"value",
"+=",
"(",
"1",
"<<",
"64",
")",
"bits",
"=",
"value",
"&",
"0x7f",
"valu... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/internal/encoder.py#L355-L371 | |
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/SConsign.py | python | Base.get_entry | (self, filename) | return self.entries[filename] | Fetch the specified entry attribute. | Fetch the specified entry attribute. | [
"Fetch",
"the",
"specified",
"entry",
"attribute",
"."
] | def get_entry(self, filename):
"""
Fetch the specified entry attribute.
"""
return self.entries[filename] | [
"def",
"get_entry",
"(",
"self",
",",
"filename",
")",
":",
"return",
"self",
".",
"entries",
"[",
"filename",
"]"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/SConsign.py#L177-L181 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | UpdateUIEvent.GetSetEnabled | (*args, **kwargs) | return _core_.UpdateUIEvent_GetSetEnabled(*args, **kwargs) | GetSetEnabled(self) -> bool
Returns ``True`` if the application has called `Enable`. For wxWidgets
internal use only. | GetSetEnabled(self) -> bool | [
"GetSetEnabled",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetSetEnabled(*args, **kwargs):
"""
GetSetEnabled(self) -> bool
Returns ``True`` if the application has called `Enable`. For wxWidgets
internal use only.
"""
return _core_.UpdateUIEvent_GetSetEnabled(*args, **kwargs) | [
"def",
"GetSetEnabled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"UpdateUIEvent_GetSetEnabled",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L6799-L6806 | |
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/ndarray/ndarray.py | python | NDArray.size | (self) | return size | Number of elements in the array.
Equivalent to the product of the array's dimensions.
Examples
--------
>>> import numpy as np
>>> x = mx.nd.zeros((3, 5, 2))
>>> x.size
30
>>> np.prod(x.shape)
30 | Number of elements in the array. | [
"Number",
"of",
"elements",
"in",
"the",
"array",
"."
] | def size(self):
"""Number of elements in the array.
Equivalent to the product of the array's dimensions.
Examples
--------
>>> import numpy as np
>>> x = mx.nd.zeros((3, 5, 2))
>>> x.size
30
>>> np.prod(x.shape)
30
"""
size = 1
for i in self.shape:
size *= i
return size | [
"def",
"size",
"(",
"self",
")",
":",
"size",
"=",
"1",
"for",
"i",
"in",
"self",
".",
"shape",
":",
"size",
"*=",
"i",
"return",
"size"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/ndarray/ndarray.py#L1657-L1674 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/special/orthogonal.py | python | laguerre | (n, monic=False) | return p | r"""Laguerre polynomial.
Defined to be the solution of
.. math::
x\frac{d^2}{dx^2}L_n + (1 - x)\frac{d}{dx}L_n + nL_n = 0;
:math:`L_n` is a polynomial of degree :math:`n`.
Parameters
----------
n : int
Degree of the polynomial.
monic : bool, optional
If `True`, scale the leading coefficient to be 1. Default is
`False`.
Returns
-------
L : orthopoly1d
Laguerre Polynomial.
Notes
-----
The polynomials :math:`L_n` are orthogonal over :math:`[0,
\infty)` with weight function :math:`e^{-x}`. | r"""Laguerre polynomial. | [
"r",
"Laguerre",
"polynomial",
"."
] | def laguerre(n, monic=False):
r"""Laguerre polynomial.
Defined to be the solution of
.. math::
x\frac{d^2}{dx^2}L_n + (1 - x)\frac{d}{dx}L_n + nL_n = 0;
:math:`L_n` is a polynomial of degree :math:`n`.
Parameters
----------
n : int
Degree of the polynomial.
monic : bool, optional
If `True`, scale the leading coefficient to be 1. Default is
`False`.
Returns
-------
L : orthopoly1d
Laguerre Polynomial.
Notes
-----
The polynomials :math:`L_n` are orthogonal over :math:`[0,
\infty)` with weight function :math:`e^{-x}`.
"""
if n < 0:
raise ValueError("n must be nonnegative.")
if n == 0:
n1 = n + 1
else:
n1 = n
x, w, mu0 = roots_laguerre(n1, mu=True)
if n == 0:
x, w = [], []
hn = 1.0
kn = (-1)**n / _gam(n + 1)
p = orthopoly1d(x, w, hn, kn, lambda x: exp(-x), (0, inf), monic,
lambda x: eval_laguerre(n, x))
return p | [
"def",
"laguerre",
"(",
"n",
",",
"monic",
"=",
"False",
")",
":",
"if",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"n must be nonnegative.\"",
")",
"if",
"n",
"==",
"0",
":",
"n1",
"=",
"n",
"+",
"1",
"else",
":",
"n1",
"=",
"n",
"x",
"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/special/orthogonal.py#L601-L644 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.