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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DanielSWolf/rhubarb-lip-sync | 5cface0af3b6e4e58c0b829c51561d784fb9f52f | rhubarb/lib/webrtc-8d2248ff/tools/python_charts/webrtc/data_helper.py | python | DataHelper.CreateData | (self, field_name, start_frame=0, end_frame=0) | return result_table_description, result_data_table | Creates a data structure for a specified data field.
Creates a data structure (data type description dictionary and a list
of data dictionaries) to be used with the Google Visualization Python
API. The frame_number column is always present and one column per data
set is added and its field name is suffixed by _N where N is the number
of the data set (0, 1, 2...)
Args:
field_name: String name of the field, must be present in the data
structure this DataHelper was created with.
start_frame: Frame number to start at (zero indexed). Default: 0.
end_frame: Frame number to be the last frame. If zero all frames
will be included. Default: 0.
Returns:
A tuple containing:
- a dictionary describing the columns in the data result_data_table below.
This description uses the name for each data set specified by
names_list.
Example with two data sets named 'Foreman' and 'Crew':
{
'frame_number': ('number', 'Frame number'),
'ssim_0': ('number', 'Foreman'),
'ssim_1': ('number', 'Crew'),
}
- a list containing dictionaries (one per row) with the frame_number
column and one column of the specified field_name column per data
set.
Example with two data sets named 'Foreman' and 'Crew':
[
{'frame_number': 0, 'ssim_0': 0.98, 'ssim_1': 0.77 },
{'frame_number': 1, 'ssim_0': 0.81, 'ssim_1': 0.53 },
] | Creates a data structure for a specified data field. | [
"Creates",
"a",
"data",
"structure",
"for",
"a",
"specified",
"data",
"field",
"."
] | def CreateData(self, field_name, start_frame=0, end_frame=0):
""" Creates a data structure for a specified data field.
Creates a data structure (data type description dictionary and a list
of data dictionaries) to be used with the Google Visualization Python
API. The frame_number column is always present and one column per data
set is added and its field name is suffixed by _N where N is the number
of the data set (0, 1, 2...)
Args:
field_name: String name of the field, must be present in the data
structure this DataHelper was created with.
start_frame: Frame number to start at (zero indexed). Default: 0.
end_frame: Frame number to be the last frame. If zero all frames
will be included. Default: 0.
Returns:
A tuple containing:
- a dictionary describing the columns in the data result_data_table below.
This description uses the name for each data set specified by
names_list.
Example with two data sets named 'Foreman' and 'Crew':
{
'frame_number': ('number', 'Frame number'),
'ssim_0': ('number', 'Foreman'),
'ssim_1': ('number', 'Crew'),
}
- a list containing dictionaries (one per row) with the frame_number
column and one column of the specified field_name column per data
set.
Example with two data sets named 'Foreman' and 'Crew':
[
{'frame_number': 0, 'ssim_0': 0.98, 'ssim_1': 0.77 },
{'frame_number': 1, 'ssim_0': 0.81, 'ssim_1': 0.53 },
]
"""
# Build dictionary that describes the data types
result_table_description = {'frame_number': ('string', 'Frame number')}
for dataset_index in range(self.number_of_datasets):
column_name = '%s_%s' % (field_name, dataset_index)
column_type = self.table_description[field_name][0]
column_description = self.names_list[dataset_index]
result_table_description[column_name] = (column_type, column_description)
# Build data table of all the data
result_data_table = []
# We're going to have one dictionary per row.
# Create that and copy frame_number values from the first data set
for source_row in self.data_list[0]:
row_dict = {'frame_number': source_row['frame_number']}
result_data_table.append(row_dict)
# Pick target field data points from the all data tables
if end_frame == 0: # Default to all frames
end_frame = self.number_of_frames
for dataset_index in range(self.number_of_datasets):
for row_number in range(start_frame, end_frame):
column_name = '%s_%s' % (field_name, dataset_index)
# Stop if any of the data sets are missing the frame
try:
result_data_table[row_number][column_name] = \
self.data_list[dataset_index][row_number][field_name]
except IndexError:
self.messages.append("Couldn't find frame data for row %d "
"for %s" % (row_number, self.names_list[dataset_index]))
break
return result_table_description, result_data_table | [
"def",
"CreateData",
"(",
"self",
",",
"field_name",
",",
"start_frame",
"=",
"0",
",",
"end_frame",
"=",
"0",
")",
":",
"# Build dictionary that describes the data types",
"result_table_description",
"=",
"{",
"'frame_number'",
":",
"(",
"'string'",
",",
"'Frame number'",
")",
"}",
"for",
"dataset_index",
"in",
"range",
"(",
"self",
".",
"number_of_datasets",
")",
":",
"column_name",
"=",
"'%s_%s'",
"%",
"(",
"field_name",
",",
"dataset_index",
")",
"column_type",
"=",
"self",
".",
"table_description",
"[",
"field_name",
"]",
"[",
"0",
"]",
"column_description",
"=",
"self",
".",
"names_list",
"[",
"dataset_index",
"]",
"result_table_description",
"[",
"column_name",
"]",
"=",
"(",
"column_type",
",",
"column_description",
")",
"# Build data table of all the data",
"result_data_table",
"=",
"[",
"]",
"# We're going to have one dictionary per row.",
"# Create that and copy frame_number values from the first data set",
"for",
"source_row",
"in",
"self",
".",
"data_list",
"[",
"0",
"]",
":",
"row_dict",
"=",
"{",
"'frame_number'",
":",
"source_row",
"[",
"'frame_number'",
"]",
"}",
"result_data_table",
".",
"append",
"(",
"row_dict",
")",
"# Pick target field data points from the all data tables",
"if",
"end_frame",
"==",
"0",
":",
"# Default to all frames",
"end_frame",
"=",
"self",
".",
"number_of_frames",
"for",
"dataset_index",
"in",
"range",
"(",
"self",
".",
"number_of_datasets",
")",
":",
"for",
"row_number",
"in",
"range",
"(",
"start_frame",
",",
"end_frame",
")",
":",
"column_name",
"=",
"'%s_%s'",
"%",
"(",
"field_name",
",",
"dataset_index",
")",
"# Stop if any of the data sets are missing the frame",
"try",
":",
"result_data_table",
"[",
"row_number",
"]",
"[",
"column_name",
"]",
"=",
"self",
".",
"data_list",
"[",
"dataset_index",
"]",
"[",
"row_number",
"]",
"[",
"field_name",
"]",
"except",
"IndexError",
":",
"self",
".",
"messages",
".",
"append",
"(",
"\"Couldn't find frame data for row %d \"",
"\"for %s\"",
"%",
"(",
"row_number",
",",
"self",
".",
"names_list",
"[",
"dataset_index",
"]",
")",
")",
"break",
"return",
"result_table_description",
",",
"result_data_table"
] | https://github.com/DanielSWolf/rhubarb-lip-sync/blob/5cface0af3b6e4e58c0b829c51561d784fb9f52f/rhubarb/lib/webrtc-8d2248ff/tools/python_charts/webrtc/data_helper.py#L40-L110 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/gslib/boto_translation.py | python | BotoTranslation.ComposeObject | (self, src_objs_metadata, dst_obj_metadata,
preconditions=None, provider=None, fields=None) | See CloudApi class for function doc strings. | See CloudApi class for function doc strings. | [
"See",
"CloudApi",
"class",
"for",
"function",
"doc",
"strings",
"."
] | def ComposeObject(self, src_objs_metadata, dst_obj_metadata,
preconditions=None, provider=None, fields=None):
"""See CloudApi class for function doc strings."""
_ = provider
ValidateDstObjectMetadata(dst_obj_metadata)
dst_obj_name = dst_obj_metadata.name
dst_obj_metadata.name = None
dst_bucket_name = dst_obj_metadata.bucket
dst_obj_metadata.bucket = None
headers = HeadersFromObjectMetadata(dst_obj_metadata, self.provider)
if not dst_obj_metadata.contentType:
dst_obj_metadata.contentType = DEFAULT_CONTENT_TYPE
headers['content-type'] = dst_obj_metadata.contentType
self._AddApiVersionToHeaders(headers)
self._AddPreconditionsToHeaders(preconditions, headers)
dst_uri = self._StorageUriForObject(dst_bucket_name, dst_obj_name)
src_components = []
for src_obj in src_objs_metadata:
src_uri = self._StorageUriForObject(dst_bucket_name, src_obj.name,
generation=src_obj.generation)
src_components.append(src_uri)
try:
dst_uri.compose(src_components, headers=headers)
return self.GetObjectMetadata(dst_bucket_name, dst_obj_name,
fields=fields)
except TRANSLATABLE_BOTO_EXCEPTIONS, e:
self._TranslateExceptionAndRaise(e, dst_obj_metadata.bucket,
dst_obj_metadata.name) | [
"def",
"ComposeObject",
"(",
"self",
",",
"src_objs_metadata",
",",
"dst_obj_metadata",
",",
"preconditions",
"=",
"None",
",",
"provider",
"=",
"None",
",",
"fields",
"=",
"None",
")",
":",
"_",
"=",
"provider",
"ValidateDstObjectMetadata",
"(",
"dst_obj_metadata",
")",
"dst_obj_name",
"=",
"dst_obj_metadata",
".",
"name",
"dst_obj_metadata",
".",
"name",
"=",
"None",
"dst_bucket_name",
"=",
"dst_obj_metadata",
".",
"bucket",
"dst_obj_metadata",
".",
"bucket",
"=",
"None",
"headers",
"=",
"HeadersFromObjectMetadata",
"(",
"dst_obj_metadata",
",",
"self",
".",
"provider",
")",
"if",
"not",
"dst_obj_metadata",
".",
"contentType",
":",
"dst_obj_metadata",
".",
"contentType",
"=",
"DEFAULT_CONTENT_TYPE",
"headers",
"[",
"'content-type'",
"]",
"=",
"dst_obj_metadata",
".",
"contentType",
"self",
".",
"_AddApiVersionToHeaders",
"(",
"headers",
")",
"self",
".",
"_AddPreconditionsToHeaders",
"(",
"preconditions",
",",
"headers",
")",
"dst_uri",
"=",
"self",
".",
"_StorageUriForObject",
"(",
"dst_bucket_name",
",",
"dst_obj_name",
")",
"src_components",
"=",
"[",
"]",
"for",
"src_obj",
"in",
"src_objs_metadata",
":",
"src_uri",
"=",
"self",
".",
"_StorageUriForObject",
"(",
"dst_bucket_name",
",",
"src_obj",
".",
"name",
",",
"generation",
"=",
"src_obj",
".",
"generation",
")",
"src_components",
".",
"append",
"(",
"src_uri",
")",
"try",
":",
"dst_uri",
".",
"compose",
"(",
"src_components",
",",
"headers",
"=",
"headers",
")",
"return",
"self",
".",
"GetObjectMetadata",
"(",
"dst_bucket_name",
",",
"dst_obj_name",
",",
"fields",
"=",
"fields",
")",
"except",
"TRANSLATABLE_BOTO_EXCEPTIONS",
",",
"e",
":",
"self",
".",
"_TranslateExceptionAndRaise",
"(",
"e",
",",
"dst_obj_metadata",
".",
"bucket",
",",
"dst_obj_metadata",
".",
"name",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/boto_translation.py#L958-L990 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/SocketServer.py | python | TCPServer.shutdown_request | (self, request) | Called to shutdown and close an individual request. | Called to shutdown and close an individual request. | [
"Called",
"to",
"shutdown",
"and",
"close",
"an",
"individual",
"request",
"."
] | def shutdown_request(self, request):
"""Called to shutdown and close an individual request."""
try:
#explicitly shutdown. socket.close() merely releases
#the socket and waits for GC to perform the actual close.
request.shutdown(socket.SHUT_WR)
except socket.error:
pass #some platforms may raise ENOTCONN here
self.close_request(request) | [
"def",
"shutdown_request",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"#explicitly shutdown. socket.close() merely releases",
"#the socket and waits for GC to perform the actual close.",
"request",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_WR",
")",
"except",
"socket",
".",
"error",
":",
"pass",
"#some platforms may raise ENOTCONN here",
"self",
".",
"close_request",
"(",
"request",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/SocketServer.py#L465-L473 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2.py | python | xmlTextReader.ReadAttributeValue | (self) | return ret | Parses an attribute value into one or more Text and
EntityReference nodes. | Parses an attribute value into one or more Text and
EntityReference nodes. | [
"Parses",
"an",
"attribute",
"value",
"into",
"one",
"or",
"more",
"Text",
"and",
"EntityReference",
"nodes",
"."
] | def ReadAttributeValue(self):
"""Parses an attribute value into one or more Text and
EntityReference nodes. """
ret = libxml2mod.xmlTextReaderReadAttributeValue(self._o)
return ret | [
"def",
"ReadAttributeValue",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlTextReaderReadAttributeValue",
"(",
"self",
".",
"_o",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L6828-L6832 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/boto/boto/storage_uri.py | python | FileStorageUri.names_singleton | (self) | return not self.names_container() | Returns True if this URI names a file (or stream) or object. | Returns True if this URI names a file (or stream) or object. | [
"Returns",
"True",
"if",
"this",
"URI",
"names",
"a",
"file",
"(",
"or",
"stream",
")",
"or",
"object",
"."
] | def names_singleton(self):
"""Returns True if this URI names a file (or stream) or object."""
return not self.names_container() | [
"def",
"names_singleton",
"(",
"self",
")",
":",
"return",
"not",
"self",
".",
"names_container",
"(",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/storage_uri.py#L850-L852 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/math/optimize.py | python | GlobalOptimizer.solve | (self,problem,numIters=100,tol=1e-6) | Returns a pair (solved,x) where solved is True if the solver
found a valid solution, and x is the solution vector. | Returns a pair (solved,x) where solved is True if the solver
found a valid solution, and x is the solution vector. | [
"Returns",
"a",
"pair",
"(",
"solved",
"x",
")",
"where",
"solved",
"is",
"True",
"if",
"the",
"solver",
"found",
"a",
"valid",
"solution",
"and",
"x",
"is",
"the",
"solution",
"vector",
"."
] | def solve(self,problem,numIters=100,tol=1e-6):
"""Returns a pair (solved,x) where solved is True if the solver
found a valid solution, and x is the solution vector."""
if isinstance(self.method,(list,tuple)):
#sequential solve
seed = self.seed
for i,m in enumerate(self.method):
if hasattr(numIters,'__iter__'):
itersi = numIters[i]
else:
itersi = numIters
if hasattr(tol,'__iter__'):
toli = tol[i]
else:
toli = tol
print "GlobalOptimizer.solve(): Step",i,"method",m,'iters',itersi,'tol',toli
if m == 'auto':
opt = LocalOptimizer(m)
else:
opt = GlobalOptimizer(m)
#seed with previous seed, if necessary
opt.setSeed(seed)
(succ,xsol)=opt.solve(problem,itersi,toli)
if not succ: return (False,xsol)
seed = xsol[:]
return ((seed is not None),seed)
elif self.method == 'scipy.differential_evolution':
from scipy import optimize
if problem.bounds == None:
raise RuntimeError("Cannot use scipy differential_evolution method without a bounded search space")
flattenedProblem = problem.makeUnconstrained(objective_scale = 1e-5)
res = optimize.differential_evolution(flattenedProblem.objective,zip(*flattenedProblem.bounds))
print "GlobalOptimizer.solve(): scipy.differential_evolution solution:",res.x
print " Objective value",res.fun
print " Equality error:",[gx(res.x) for gx in problem.equalities]
return (True,res.x)
elif self.method == 'DIRECT':
import DIRECT
if problem.bounds == None:
raise RuntimeError("Cannot use DIRECT method without a bounded search space")
flattenedProblem = problem.makeUnconstrained(objective_scale = 1e-5)
minval = [float('inf'),None]
def objfunc(x,userdata):
v = flattenedProblem.objective(x)
if v < userdata[0]:
userdata[0] = v
userdata[1] = [float(xi) for xi in x]
return v
(x,fmin,ierror)=DIRECT.solve(objfunc,problem.bounds[0],problem.bounds[1],eps=tol,maxT=numIters,maxf=40000,algmethod=1,user_data=minval)
print "GlobalOptimizer.solve(): DIRECT solution:",x
print " Objective value",fmin
print " Minimum value",minval[0],minval[1]
print " Error:",ierror
print " Equality error:",[gx(x) for gx in problem.equalities]
return (True,minval[1])
elif self.method.startswith('random-restart'):
import random
if problem.bounds == None:
raise RuntimeError("Cannot use method %s without a bounded search space"%(self.method,))
localmethod = self.method[15:]
lopt = LocalOptimizer(localmethod)
seed = self.seed
best = self.seed
print "GlobalOptimizer.solve(): Random restart seed is:",best
fbest = (problem.objective(best) if (best is not None and problem.feasible(best)) else float('inf'))
for it in xrange(numIters[0]):
if seed is not None:
x = seed
seed = None
else:
x = [sample_range(a,b) for a,b in zip(*problem.bounds)]
print " Solving from",x
lopt.setSeed(x)
succ,x = lopt.solve(problem,numIters[1],tol)
print " Result is",succ,x
print " Equality:",problem.equalityResidual(x)
if succ:
fx = problem.objective(x)
if fx < fbest:
fbest = fx
best = x
return (best is not None, best)
else:
assert self.seed is not None,"Pure local optimization requires a seed to be set"
opt = LocalOptimizer(self.method)
opt.setSeed(self.seed)
return opt.solve(problem,numIters,tol) | [
"def",
"solve",
"(",
"self",
",",
"problem",
",",
"numIters",
"=",
"100",
",",
"tol",
"=",
"1e-6",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"method",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"#sequential solve",
"seed",
"=",
"self",
".",
"seed",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"self",
".",
"method",
")",
":",
"if",
"hasattr",
"(",
"numIters",
",",
"'__iter__'",
")",
":",
"itersi",
"=",
"numIters",
"[",
"i",
"]",
"else",
":",
"itersi",
"=",
"numIters",
"if",
"hasattr",
"(",
"tol",
",",
"'__iter__'",
")",
":",
"toli",
"=",
"tol",
"[",
"i",
"]",
"else",
":",
"toli",
"=",
"tol",
"print",
"\"GlobalOptimizer.solve(): Step\"",
",",
"i",
",",
"\"method\"",
",",
"m",
",",
"'iters'",
",",
"itersi",
",",
"'tol'",
",",
"toli",
"if",
"m",
"==",
"'auto'",
":",
"opt",
"=",
"LocalOptimizer",
"(",
"m",
")",
"else",
":",
"opt",
"=",
"GlobalOptimizer",
"(",
"m",
")",
"#seed with previous seed, if necessary",
"opt",
".",
"setSeed",
"(",
"seed",
")",
"(",
"succ",
",",
"xsol",
")",
"=",
"opt",
".",
"solve",
"(",
"problem",
",",
"itersi",
",",
"toli",
")",
"if",
"not",
"succ",
":",
"return",
"(",
"False",
",",
"xsol",
")",
"seed",
"=",
"xsol",
"[",
":",
"]",
"return",
"(",
"(",
"seed",
"is",
"not",
"None",
")",
",",
"seed",
")",
"elif",
"self",
".",
"method",
"==",
"'scipy.differential_evolution'",
":",
"from",
"scipy",
"import",
"optimize",
"if",
"problem",
".",
"bounds",
"==",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot use scipy differential_evolution method without a bounded search space\"",
")",
"flattenedProblem",
"=",
"problem",
".",
"makeUnconstrained",
"(",
"objective_scale",
"=",
"1e-5",
")",
"res",
"=",
"optimize",
".",
"differential_evolution",
"(",
"flattenedProblem",
".",
"objective",
",",
"zip",
"(",
"*",
"flattenedProblem",
".",
"bounds",
")",
")",
"print",
"\"GlobalOptimizer.solve(): scipy.differential_evolution solution:\"",
",",
"res",
".",
"x",
"print",
"\" Objective value\"",
",",
"res",
".",
"fun",
"print",
"\" Equality error:\"",
",",
"[",
"gx",
"(",
"res",
".",
"x",
")",
"for",
"gx",
"in",
"problem",
".",
"equalities",
"]",
"return",
"(",
"True",
",",
"res",
".",
"x",
")",
"elif",
"self",
".",
"method",
"==",
"'DIRECT'",
":",
"import",
"DIRECT",
"if",
"problem",
".",
"bounds",
"==",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot use DIRECT method without a bounded search space\"",
")",
"flattenedProblem",
"=",
"problem",
".",
"makeUnconstrained",
"(",
"objective_scale",
"=",
"1e-5",
")",
"minval",
"=",
"[",
"float",
"(",
"'inf'",
")",
",",
"None",
"]",
"def",
"objfunc",
"(",
"x",
",",
"userdata",
")",
":",
"v",
"=",
"flattenedProblem",
".",
"objective",
"(",
"x",
")",
"if",
"v",
"<",
"userdata",
"[",
"0",
"]",
":",
"userdata",
"[",
"0",
"]",
"=",
"v",
"userdata",
"[",
"1",
"]",
"=",
"[",
"float",
"(",
"xi",
")",
"for",
"xi",
"in",
"x",
"]",
"return",
"v",
"(",
"x",
",",
"fmin",
",",
"ierror",
")",
"=",
"DIRECT",
".",
"solve",
"(",
"objfunc",
",",
"problem",
".",
"bounds",
"[",
"0",
"]",
",",
"problem",
".",
"bounds",
"[",
"1",
"]",
",",
"eps",
"=",
"tol",
",",
"maxT",
"=",
"numIters",
",",
"maxf",
"=",
"40000",
",",
"algmethod",
"=",
"1",
",",
"user_data",
"=",
"minval",
")",
"print",
"\"GlobalOptimizer.solve(): DIRECT solution:\"",
",",
"x",
"print",
"\" Objective value\"",
",",
"fmin",
"print",
"\" Minimum value\"",
",",
"minval",
"[",
"0",
"]",
",",
"minval",
"[",
"1",
"]",
"print",
"\" Error:\"",
",",
"ierror",
"print",
"\" Equality error:\"",
",",
"[",
"gx",
"(",
"x",
")",
"for",
"gx",
"in",
"problem",
".",
"equalities",
"]",
"return",
"(",
"True",
",",
"minval",
"[",
"1",
"]",
")",
"elif",
"self",
".",
"method",
".",
"startswith",
"(",
"'random-restart'",
")",
":",
"import",
"random",
"if",
"problem",
".",
"bounds",
"==",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot use method %s without a bounded search space\"",
"%",
"(",
"self",
".",
"method",
",",
")",
")",
"localmethod",
"=",
"self",
".",
"method",
"[",
"15",
":",
"]",
"lopt",
"=",
"LocalOptimizer",
"(",
"localmethod",
")",
"seed",
"=",
"self",
".",
"seed",
"best",
"=",
"self",
".",
"seed",
"print",
"\"GlobalOptimizer.solve(): Random restart seed is:\"",
",",
"best",
"fbest",
"=",
"(",
"problem",
".",
"objective",
"(",
"best",
")",
"if",
"(",
"best",
"is",
"not",
"None",
"and",
"problem",
".",
"feasible",
"(",
"best",
")",
")",
"else",
"float",
"(",
"'inf'",
")",
")",
"for",
"it",
"in",
"xrange",
"(",
"numIters",
"[",
"0",
"]",
")",
":",
"if",
"seed",
"is",
"not",
"None",
":",
"x",
"=",
"seed",
"seed",
"=",
"None",
"else",
":",
"x",
"=",
"[",
"sample_range",
"(",
"a",
",",
"b",
")",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"*",
"problem",
".",
"bounds",
")",
"]",
"print",
"\" Solving from\"",
",",
"x",
"lopt",
".",
"setSeed",
"(",
"x",
")",
"succ",
",",
"x",
"=",
"lopt",
".",
"solve",
"(",
"problem",
",",
"numIters",
"[",
"1",
"]",
",",
"tol",
")",
"print",
"\" Result is\"",
",",
"succ",
",",
"x",
"print",
"\" Equality:\"",
",",
"problem",
".",
"equalityResidual",
"(",
"x",
")",
"if",
"succ",
":",
"fx",
"=",
"problem",
".",
"objective",
"(",
"x",
")",
"if",
"fx",
"<",
"fbest",
":",
"fbest",
"=",
"fx",
"best",
"=",
"x",
"return",
"(",
"best",
"is",
"not",
"None",
",",
"best",
")",
"else",
":",
"assert",
"self",
".",
"seed",
"is",
"not",
"None",
",",
"\"Pure local optimization requires a seed to be set\"",
"opt",
"=",
"LocalOptimizer",
"(",
"self",
".",
"method",
")",
"opt",
".",
"setSeed",
"(",
"self",
".",
"seed",
")",
"return",
"opt",
".",
"solve",
"(",
"problem",
",",
"numIters",
",",
"tol",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/optimize.py#L612-L698 | ||
intel-iot-devkit/how-to-code-samples | b4ea616f36bbfa2e042beb1698f968cfd651d79f | storage-unit-flood-detector/python/iot_storage_unit_flood_detector/storage.py | python | store_message | (payload, method="PUT") | Publish message to remote data store. | Publish message to remote data store. | [
"Publish",
"message",
"to",
"remote",
"data",
"store",
"."
] | def store_message(payload, method="PUT"):
"""
Publish message to remote data store.
"""
if not DATA_STORE_CONFIG:
return
server = DATA_STORE_CONFIG.server
auth_token = DATA_STORE_CONFIG.auth_token
headers = {
"X-Auth-Token": auth_token
}
def perform_request():
"""
Perform HTTP request.
"""
if method == "GET":
response = get_http(
server,
headers=headers,
json=payload
)
else:
response = put_http(
server,
headers=headers,
json=payload
)
response.raise_for_status()
print("saved to data store")
SCHEDULER.add_job(perform_request) | [
"def",
"store_message",
"(",
"payload",
",",
"method",
"=",
"\"PUT\"",
")",
":",
"if",
"not",
"DATA_STORE_CONFIG",
":",
"return",
"server",
"=",
"DATA_STORE_CONFIG",
".",
"server",
"auth_token",
"=",
"DATA_STORE_CONFIG",
".",
"auth_token",
"headers",
"=",
"{",
"\"X-Auth-Token\"",
":",
"auth_token",
"}",
"def",
"perform_request",
"(",
")",
":",
"\"\"\"\n Perform HTTP request.\n \"\"\"",
"if",
"method",
"==",
"\"GET\"",
":",
"response",
"=",
"get_http",
"(",
"server",
",",
"headers",
"=",
"headers",
",",
"json",
"=",
"payload",
")",
"else",
":",
"response",
"=",
"put_http",
"(",
"server",
",",
"headers",
"=",
"headers",
",",
"json",
"=",
"payload",
")",
"response",
".",
"raise_for_status",
"(",
")",
"print",
"(",
"\"saved to data store\"",
")",
"SCHEDULER",
".",
"add_job",
"(",
"perform_request",
")"
] | https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/storage-unit-flood-detector/python/iot_storage_unit_flood_detector/storage.py#L27-L65 | ||
cornell-zhang/heterocl | 6d9e4b4acc2ee2707b2d25b27298c0335bccedfd | python/heterocl/tvm/_ffi/ndarray.py | python | NDArrayBase.dtype | (self) | return str(self.handle.contents.dtype) | Type of this array | Type of this array | [
"Type",
"of",
"this",
"array"
] | def dtype(self):
"""Type of this array"""
return str(self.handle.contents.dtype) | [
"def",
"dtype",
"(",
"self",
")",
":",
"return",
"str",
"(",
"self",
".",
"handle",
".",
"contents",
".",
"dtype",
")"
] | https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/_ffi/ndarray.py#L129-L131 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py | python | XcodeSettings.GetCflagsObjCC | (self, configname) | return cflags_objcc | Returns flags that need to be added to .mm compilations. | Returns flags that need to be added to .mm compilations. | [
"Returns",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
".",
"mm",
"compilations",
"."
] | def GetCflagsObjCC(self, configname):
"""Returns flags that need to be added to .mm compilations."""
self.configname = configname
cflags_objcc = []
self._AddObjectiveCGarbageCollectionFlags(cflags_objcc)
self._AddObjectiveCARCFlags(cflags_objcc)
self._AddObjectiveCMissingPropertySynthesisFlags(cflags_objcc)
if self._Test('GCC_OBJC_CALL_CXX_CDTORS', 'YES', default='NO'):
cflags_objcc.append('-fobjc-call-cxx-cdtors')
self.configname = None
return cflags_objcc | [
"def",
"GetCflagsObjCC",
"(",
"self",
",",
"configname",
")",
":",
"self",
".",
"configname",
"=",
"configname",
"cflags_objcc",
"=",
"[",
"]",
"self",
".",
"_AddObjectiveCGarbageCollectionFlags",
"(",
"cflags_objcc",
")",
"self",
".",
"_AddObjectiveCARCFlags",
"(",
"cflags_objcc",
")",
"self",
".",
"_AddObjectiveCMissingPropertySynthesisFlags",
"(",
"cflags_objcc",
")",
"if",
"self",
".",
"_Test",
"(",
"'GCC_OBJC_CALL_CXX_CDTORS'",
",",
"'YES'",
",",
"default",
"=",
"'NO'",
")",
":",
"cflags_objcc",
".",
"append",
"(",
"'-fobjc-call-cxx-cdtors'",
")",
"self",
".",
"configname",
"=",
"None",
"return",
"cflags_objcc"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L674-L684 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | xpathParserContext.xpointerRangeToFunction | (self, nargs) | Implement the range-to() XPointer function | Implement the range-to() XPointer function | [
"Implement",
"the",
"range",
"-",
"to",
"()",
"XPointer",
"function"
] | def xpointerRangeToFunction(self, nargs):
"""Implement the range-to() XPointer function """
libxml2mod.xmlXPtrRangeToFunction(self._o, nargs) | [
"def",
"xpointerRangeToFunction",
"(",
"self",
",",
"nargs",
")",
":",
"libxml2mod",
".",
"xmlXPtrRangeToFunction",
"(",
"self",
".",
"_o",
",",
"nargs",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L7200-L7202 | ||
apache/arrow | af33dd1157eb8d7d9bfac25ebf61445b793b7943 | python/pyarrow/compute.py | python | scalar | (value) | return Expression._scalar(value) | Expression representing a scalar value.
Parameters
----------
value : bool, int, float or string
Python value of the scalar. Note that only a subset of types are
currently supported.
Returns
-------
scalar_expr : Expression | Expression representing a scalar value. | [
"Expression",
"representing",
"a",
"scalar",
"value",
"."
] | def scalar(value):
"""Expression representing a scalar value.
Parameters
----------
value : bool, int, float or string
Python value of the scalar. Note that only a subset of types are
currently supported.
Returns
-------
scalar_expr : Expression
"""
return Expression._scalar(value) | [
"def",
"scalar",
"(",
"value",
")",
":",
"return",
"Expression",
".",
"_scalar",
"(",
"value",
")"
] | https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/compute.py#L612-L625 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/linalg/_interpolative_backend.py | python | iddr_aidi | (m, n, k) | return _id.iddr_aidi(m, n, k) | Initialize array for :func:`iddr_aid`.
:param m:
Matrix row dimension.
:type m: int
:param n:
Matrix column dimension.
:type n: int
:param k:
Rank of ID.
:type k: int
:return:
Initialization array to be used by :func:`iddr_aid`.
:rtype: :class:`numpy.ndarray` | Initialize array for :func:`iddr_aid`. | [
"Initialize",
"array",
"for",
":",
"func",
":",
"iddr_aid",
"."
] | def iddr_aidi(m, n, k):
"""
Initialize array for :func:`iddr_aid`.
:param m:
Matrix row dimension.
:type m: int
:param n:
Matrix column dimension.
:type n: int
:param k:
Rank of ID.
:type k: int
:return:
Initialization array to be used by :func:`iddr_aid`.
:rtype: :class:`numpy.ndarray`
"""
return _id.iddr_aidi(m, n, k) | [
"def",
"iddr_aidi",
"(",
"m",
",",
"n",
",",
"k",
")",
":",
"return",
"_id",
".",
"iddr_aidi",
"(",
"m",
",",
"n",
",",
"k",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/linalg/_interpolative_backend.py#L736-L754 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/generator/msvs.py | python | _NormalizedSource | (source) | return source | Normalize the path.
But not if that gets rid of a variable, as this may expand to something
larger than one directory.
Arguments:
source: The path to be normalize.d
Returns:
The normalized path. | Normalize the path. | [
"Normalize",
"the",
"path",
"."
] | def _NormalizedSource(source):
"""Normalize the path.
But not if that gets rid of a variable, as this may expand to something
larger than one directory.
Arguments:
source: The path to be normalize.d
Returns:
The normalized path.
"""
normalized = os.path.normpath(source)
if source.count('$') == normalized.count('$'):
source = normalized
return source | [
"def",
"_NormalizedSource",
"(",
"source",
")",
":",
"normalized",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"source",
")",
"if",
"source",
".",
"count",
"(",
"'$'",
")",
"==",
"normalized",
".",
"count",
"(",
"'$'",
")",
":",
"source",
"=",
"normalized",
"return",
"source"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/msvs.py#L140-L155 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/MooseDocs/base/Extension.py | python | Extension.preRender | (self, page, ast, result) | Called by Translator prior to rendering.
Inputs:
page[pages.Source]: The source object representing the content
ast[tokens.Token]: The root node of the token tree
result[tree.base.NodeBase]: The root node of the result tree | Called by Translator prior to rendering. | [
"Called",
"by",
"Translator",
"prior",
"to",
"rendering",
"."
] | def preRender(self, page, ast, result):
"""
Called by Translator prior to rendering.
Inputs:
page[pages.Source]: The source object representing the content
ast[tokens.Token]: The root node of the token tree
result[tree.base.NodeBase]: The root node of the result tree
"""
pass | [
"def",
"preRender",
"(",
"self",
",",
"page",
",",
"ast",
",",
"result",
")",
":",
"pass"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/base/Extension.py#L129-L138 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/reduction_workflow/reducer.py | python | Reducer.clear_data_files | (self) | Empty the list of files to reduce while keeping all the
other options the same. | Empty the list of files to reduce while keeping all the
other options the same. | [
"Empty",
"the",
"list",
"of",
"files",
"to",
"reduce",
"while",
"keeping",
"all",
"the",
"other",
"options",
"the",
"same",
"."
] | def clear_data_files(self):
"""
Empty the list of files to reduce while keeping all the
other options the same.
"""
self._data_files = {} | [
"def",
"clear_data_files",
"(",
"self",
")",
":",
"self",
".",
"_data_files",
"=",
"{",
"}"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_workflow/reducer.py#L87-L92 | ||
ablab/quast | 5f6709528129a6ad266a6b24ef3f40b88f0fe04b | quast_libs/busco/BuscoAnalysis.py | python | BuscoAnalysis._reformats_seq_id | (self, seq_id) | return seq_id | This function reformats the sequence id to its original values,
if it was somehow modified during the process
It has to be overriden by subclasses when needed
:param seq_id: the seq id to reformats
:type seq_id: str
:return: the reformatted seq_id
:rtype: str | This function reformats the sequence id to its original values,
if it was somehow modified during the process
It has to be overriden by subclasses when needed
:param seq_id: the seq id to reformats
:type seq_id: str
:return: the reformatted seq_id
:rtype: str | [
"This",
"function",
"reformats",
"the",
"sequence",
"id",
"to",
"its",
"original",
"values",
"if",
"it",
"was",
"somehow",
"modified",
"during",
"the",
"process",
"It",
"has",
"to",
"be",
"overriden",
"by",
"subclasses",
"when",
"needed",
":",
"param",
"seq_id",
":",
"the",
"seq",
"id",
"to",
"reformats",
":",
"type",
"seq_id",
":",
"str",
":",
"return",
":",
"the",
"reformatted",
"seq_id",
":",
"rtype",
":",
"str"
] | def _reformats_seq_id(self, seq_id):
"""
This function reformats the sequence id to its original values,
if it was somehow modified during the process
It has to be overriden by subclasses when needed
:param seq_id: the seq id to reformats
:type seq_id: str
:return: the reformatted seq_id
:rtype: str
"""
return seq_id | [
"def",
"_reformats_seq_id",
"(",
"self",
",",
"seq_id",
")",
":",
"return",
"seq_id"
] | https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/busco/BuscoAnalysis.py#L946-L956 | |
CGRU/cgru | 1881a4128530e3d31ac6c25314c18314fc50c2c7 | lib/python/Qt.py | python | _pyside | () | Initialise PySide | Initialise PySide | [
"Initialise",
"PySide"
] | def _pyside():
"""Initialise PySide"""
import PySide as module
extras = ["QtUiTools"]
try:
try:
# Before merge of PySide and shiboken
import shiboken
except ImportError:
# After merge of PySide and shiboken, May 2017
from PySide import shiboken
extras.append("shiboken")
except ImportError:
pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
if hasattr(Qt, "_shiboken"):
Qt.QtCompat.wrapInstance = _wrapinstance
Qt.QtCompat.getCppPointer = _getcpppointer
Qt.QtCompat.delete = shiboken.delete
if hasattr(Qt, "_QtUiTools"):
Qt.QtCompat.loadUi = _loadUi
if hasattr(Qt, "_QtGui"):
setattr(Qt, "QtWidgets", _new_module("QtWidgets"))
setattr(Qt, "_QtWidgets", Qt._QtGui)
if hasattr(Qt._QtGui, "QX11Info"):
setattr(Qt, "QtX11Extras", _new_module("QtX11Extras"))
Qt.QtX11Extras.QX11Info = Qt._QtGui.QX11Info
Qt.QtCompat.setSectionResizeMode = Qt._QtGui.QHeaderView.setResizeMode
if hasattr(Qt, "_QtCore"):
Qt.__qt_version__ = Qt._QtCore.qVersion()
Qt.QtCompat.dataChanged = (
lambda self, topleft, bottomright, roles=None:
self.dataChanged.emit(topleft, bottomright)
)
_reassign_misplaced_members("PySide")
_build_compatibility_members("PySide") | [
"def",
"_pyside",
"(",
")",
":",
"import",
"PySide",
"as",
"module",
"extras",
"=",
"[",
"\"QtUiTools\"",
"]",
"try",
":",
"try",
":",
"# Before merge of PySide and shiboken",
"import",
"shiboken",
"except",
"ImportError",
":",
"# After merge of PySide and shiboken, May 2017",
"from",
"PySide",
"import",
"shiboken",
"extras",
".",
"append",
"(",
"\"shiboken\"",
")",
"except",
"ImportError",
":",
"pass",
"_setup",
"(",
"module",
",",
"extras",
")",
"Qt",
".",
"__binding_version__",
"=",
"module",
".",
"__version__",
"if",
"hasattr",
"(",
"Qt",
",",
"\"_shiboken\"",
")",
":",
"Qt",
".",
"QtCompat",
".",
"wrapInstance",
"=",
"_wrapinstance",
"Qt",
".",
"QtCompat",
".",
"getCppPointer",
"=",
"_getcpppointer",
"Qt",
".",
"QtCompat",
".",
"delete",
"=",
"shiboken",
".",
"delete",
"if",
"hasattr",
"(",
"Qt",
",",
"\"_QtUiTools\"",
")",
":",
"Qt",
".",
"QtCompat",
".",
"loadUi",
"=",
"_loadUi",
"if",
"hasattr",
"(",
"Qt",
",",
"\"_QtGui\"",
")",
":",
"setattr",
"(",
"Qt",
",",
"\"QtWidgets\"",
",",
"_new_module",
"(",
"\"QtWidgets\"",
")",
")",
"setattr",
"(",
"Qt",
",",
"\"_QtWidgets\"",
",",
"Qt",
".",
"_QtGui",
")",
"if",
"hasattr",
"(",
"Qt",
".",
"_QtGui",
",",
"\"QX11Info\"",
")",
":",
"setattr",
"(",
"Qt",
",",
"\"QtX11Extras\"",
",",
"_new_module",
"(",
"\"QtX11Extras\"",
")",
")",
"Qt",
".",
"QtX11Extras",
".",
"QX11Info",
"=",
"Qt",
".",
"_QtGui",
".",
"QX11Info",
"Qt",
".",
"QtCompat",
".",
"setSectionResizeMode",
"=",
"Qt",
".",
"_QtGui",
".",
"QHeaderView",
".",
"setResizeMode",
"if",
"hasattr",
"(",
"Qt",
",",
"\"_QtCore\"",
")",
":",
"Qt",
".",
"__qt_version__",
"=",
"Qt",
".",
"_QtCore",
".",
"qVersion",
"(",
")",
"Qt",
".",
"QtCompat",
".",
"dataChanged",
"=",
"(",
"lambda",
"self",
",",
"topleft",
",",
"bottomright",
",",
"roles",
"=",
"None",
":",
"self",
".",
"dataChanged",
".",
"emit",
"(",
"topleft",
",",
"bottomright",
")",
")",
"_reassign_misplaced_members",
"(",
"\"PySide\"",
")",
"_build_compatibility_members",
"(",
"\"PySide\"",
")"
] | https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/lib/python/Qt.py#L1473-L1517 | ||
syoyo/tinygltf | e7f1ff5c59d3ca2489923beb239bdf93d863498f | deps/cpplint.py | python | GetLineWidth | (line) | Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters. | Determines the width of the line in column positions. | [
"Determines",
"the",
"width",
"of",
"the",
"line",
"in",
"column",
"positions",
"."
] | def GetLineWidth(line):
"""Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters.
"""
if isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if unicodedata.east_asian_width(uc) in ('W', 'F'):
width += 2
elif not unicodedata.combining(uc):
width += 1
return width
else:
return len(line) | [
"def",
"GetLineWidth",
"(",
"line",
")",
":",
"if",
"isinstance",
"(",
"line",
",",
"unicode",
")",
":",
"width",
"=",
"0",
"for",
"uc",
"in",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"line",
")",
":",
"if",
"unicodedata",
".",
"east_asian_width",
"(",
"uc",
")",
"in",
"(",
"'W'",
",",
"'F'",
")",
":",
"width",
"+=",
"2",
"elif",
"not",
"unicodedata",
".",
"combining",
"(",
"uc",
")",
":",
"width",
"+=",
"1",
"return",
"width",
"else",
":",
"return",
"len",
"(",
"line",
")"
] | https://github.com/syoyo/tinygltf/blob/e7f1ff5c59d3ca2489923beb239bdf93d863498f/deps/cpplint.py#L4351-L4370 | ||
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | src/third_party/protobuf/python/google/protobuf/internal/containers.py | python | RepeatedCompositeFieldContainer.remove | (self, elem) | Removes an item from the list. Similar to list.remove(). | Removes an item from the list. Similar to list.remove(). | [
"Removes",
"an",
"item",
"from",
"the",
"list",
".",
"Similar",
"to",
"list",
".",
"remove",
"()",
"."
] | def remove(self, elem):
"""Removes an item from the list. Similar to list.remove()."""
self._values.remove(elem)
self._message_listener.Modified() | [
"def",
"remove",
"(",
"self",
",",
"elem",
")",
":",
"self",
".",
"_values",
".",
"remove",
"(",
"elem",
")",
"self",
".",
"_message_listener",
".",
"Modified",
"(",
")"
] | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/internal/containers.py#L399-L402 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py | python | ServerConnection.topic | (self, channel, new_topic=None) | Send a TOPIC command. | Send a TOPIC command. | [
"Send",
"a",
"TOPIC",
"command",
"."
] | def topic(self, channel, new_topic=None):
"""Send a TOPIC command."""
if new_topic is None:
self.send_raw("TOPIC " + channel)
else:
self.send_raw("TOPIC %s :%s" % (channel, new_topic)) | [
"def",
"topic",
"(",
"self",
",",
"channel",
",",
"new_topic",
"=",
"None",
")",
":",
"if",
"new_topic",
"is",
"None",
":",
"self",
".",
"send_raw",
"(",
"\"TOPIC \"",
"+",
"channel",
")",
"else",
":",
"self",
".",
"send_raw",
"(",
"\"TOPIC %s :%s\"",
"%",
"(",
"channel",
",",
"new_topic",
")",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py#L809-L814 | ||
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | parserCtxt.nextChar | (self) | Skip to the next char input char. | Skip to the next char input char. | [
"Skip",
"to",
"the",
"next",
"char",
"input",
"char",
"."
] | def nextChar(self):
"""Skip to the next char input char. """
libxml2mod.xmlNextChar(self._o) | [
"def",
"nextChar",
"(",
"self",
")",
":",
"libxml2mod",
".",
"xmlNextChar",
"(",
"self",
".",
"_o",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L5167-L5169 | ||
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | third_party/mbedtls/repo/scripts/config.py | python | Config.all | (self, *names) | return all(self.__contains__(name) for name in names) | True if all the elements of names are active (i.e. set). | True if all the elements of names are active (i.e. set). | [
"True",
"if",
"all",
"the",
"elements",
"of",
"names",
"are",
"active",
"(",
"i",
".",
"e",
".",
"set",
")",
"."
] | def all(self, *names):
"""True if all the elements of names are active (i.e. set)."""
return all(self.__contains__(name) for name in names) | [
"def",
"all",
"(",
"self",
",",
"*",
"names",
")",
":",
"return",
"all",
"(",
"self",
".",
"__contains__",
"(",
"name",
")",
"for",
"name",
"in",
"names",
")"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/third_party/mbedtls/repo/scripts/config.py#L74-L76 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/LoadNMoldyn4Ascii.py | python | LoadNMoldyn4Ascii._axis_conversion | (self, data, unit, name) | return (data, unit, name) | Converts an axis to a Mantid axis type (possibly performing a unit
conversion).
@param data The axis data as Numpy array
@param unit The axis unit as read from the file
@param name The axis name as read from the file
@return Tuple containing updated axis details | Converts an axis to a Mantid axis type (possibly performing a unit
conversion). | [
"Converts",
"an",
"axis",
"to",
"a",
"Mantid",
"axis",
"type",
"(",
"possibly",
"performing",
"a",
"unit",
"conversion",
")",
"."
] | def _axis_conversion(self, data, unit, name):
"""
Converts an axis to a Mantid axis type (possibly performing a unit
conversion).
@param data The axis data as Numpy array
@param unit The axis unit as read from the file
@param name The axis name as read from the file
@return Tuple containing updated axis details
"""
logger.debug('Axis for conversion: name={0}, unit={1}'.format(name, unit))
# Q (nm**-1) to Q (Angstrom**-1)
if name.lower() == 'q' and unit.lower() == 'inv_nm':
logger.information('Axis {0} will be converted to Q in Angstrom**-1'.format(name))
unit = 'MomentumTransfer'
data /= sc.nano # nm to m
data *= sc.angstrom # m to Angstrom
# Frequency (THz) to Energy (meV)
elif name.lower() == 'frequency' and unit.lower() == 'thz':
logger.information('Axis {0} will be converted to energy in meV'.format(name))
unit = 'Energy'
data *= sc.tera # THz to Hz
data *= sc.value('Planck constant in eV s') # Hz to eV
data /= sc.milli # eV to meV
# Time (ps) to TOF (s)
elif name.lower() == 'time' and unit.lower() == 'ps':
logger.information('Axis {0} will be converted to time in microsecond'.format(name))
unit = 'TOF'
data *= sc.micro # ps to us
# No conversion
else:
unit = 'Empty'
return (data, unit, name) | [
"def",
"_axis_conversion",
"(",
"self",
",",
"data",
",",
"unit",
",",
"name",
")",
":",
"logger",
".",
"debug",
"(",
"'Axis for conversion: name={0}, unit={1}'",
".",
"format",
"(",
"name",
",",
"unit",
")",
")",
"# Q (nm**-1) to Q (Angstrom**-1)",
"if",
"name",
".",
"lower",
"(",
")",
"==",
"'q'",
"and",
"unit",
".",
"lower",
"(",
")",
"==",
"'inv_nm'",
":",
"logger",
".",
"information",
"(",
"'Axis {0} will be converted to Q in Angstrom**-1'",
".",
"format",
"(",
"name",
")",
")",
"unit",
"=",
"'MomentumTransfer'",
"data",
"/=",
"sc",
".",
"nano",
"# nm to m",
"data",
"*=",
"sc",
".",
"angstrom",
"# m to Angstrom",
"# Frequency (THz) to Energy (meV)",
"elif",
"name",
".",
"lower",
"(",
")",
"==",
"'frequency'",
"and",
"unit",
".",
"lower",
"(",
")",
"==",
"'thz'",
":",
"logger",
".",
"information",
"(",
"'Axis {0} will be converted to energy in meV'",
".",
"format",
"(",
"name",
")",
")",
"unit",
"=",
"'Energy'",
"data",
"*=",
"sc",
".",
"tera",
"# THz to Hz",
"data",
"*=",
"sc",
".",
"value",
"(",
"'Planck constant in eV s'",
")",
"# Hz to eV",
"data",
"/=",
"sc",
".",
"milli",
"# eV to meV",
"# Time (ps) to TOF (s)",
"elif",
"name",
".",
"lower",
"(",
")",
"==",
"'time'",
"and",
"unit",
".",
"lower",
"(",
")",
"==",
"'ps'",
":",
"logger",
".",
"information",
"(",
"'Axis {0} will be converted to time in microsecond'",
".",
"format",
"(",
"name",
")",
")",
"unit",
"=",
"'TOF'",
"data",
"*=",
"sc",
".",
"micro",
"# ps to us",
"# No conversion",
"else",
":",
"unit",
"=",
"'Empty'",
"return",
"(",
"data",
",",
"unit",
",",
"name",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/LoadNMoldyn4Ascii.py#L273-L310 | |
hfinkel/llvm-project-cxxjit | 91084ef018240bbb8e24235ff5cd8c355a9c1a1e | llvm/utils/llvm-build/llvmbuild/main.py | python | LLVMProjectInfo.write_cmake_exports_fragment | (self, output_path, enabled_optional_components) | write_cmake_exports_fragment(output_path) -> None
Generate a CMake fragment which includes LLVMBuild library
dependencies expressed similarly to how CMake would write
them via install(EXPORT). | write_cmake_exports_fragment(output_path) -> None | [
"write_cmake_exports_fragment",
"(",
"output_path",
")",
"-",
">",
"None"
] | def write_cmake_exports_fragment(self, output_path, enabled_optional_components):
"""
write_cmake_exports_fragment(output_path) -> None
Generate a CMake fragment which includes LLVMBuild library
dependencies expressed similarly to how CMake would write
them via install(EXPORT).
"""
dependencies = list(self.get_fragment_dependencies())
# Write out the CMake exports fragment.
make_install_dir(os.path.dirname(output_path))
f = open(output_path, 'w')
f.write("""\
# Explicit library dependency information.
#
# The following property assignments tell CMake about link
# dependencies of libraries imported from LLVM.
""")
self.foreach_cmake_library(
lambda ci:
f.write("""\
set_property(TARGET %s PROPERTY IMPORTED_LINK_INTERFACE_LIBRARIES %s)\n""" % (
ci.get_prefixed_library_name(), " ".join(sorted(
dep.get_prefixed_library_name()
for dep in self.get_required_libraries_for_component(ci)))))
,
enabled_optional_components,
skip_disabled = True,
skip_not_installed = True # Do not export internal libraries like gtest
)
f.close() | [
"def",
"write_cmake_exports_fragment",
"(",
"self",
",",
"output_path",
",",
"enabled_optional_components",
")",
":",
"dependencies",
"=",
"list",
"(",
"self",
".",
"get_fragment_dependencies",
"(",
")",
")",
"# Write out the CMake exports fragment.",
"make_install_dir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"output_path",
")",
")",
"f",
"=",
"open",
"(",
"output_path",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"\"\"\"\\\n# Explicit library dependency information.\n#\n# The following property assignments tell CMake about link\n# dependencies of libraries imported from LLVM.\n\"\"\"",
")",
"self",
".",
"foreach_cmake_library",
"(",
"lambda",
"ci",
":",
"f",
".",
"write",
"(",
"\"\"\"\\\nset_property(TARGET %s PROPERTY IMPORTED_LINK_INTERFACE_LIBRARIES %s)\\n\"\"\"",
"%",
"(",
"ci",
".",
"get_prefixed_library_name",
"(",
")",
",",
"\" \"",
".",
"join",
"(",
"sorted",
"(",
"dep",
".",
"get_prefixed_library_name",
"(",
")",
"for",
"dep",
"in",
"self",
".",
"get_required_libraries_for_component",
"(",
"ci",
")",
")",
")",
")",
")",
",",
"enabled_optional_components",
",",
"skip_disabled",
"=",
"True",
",",
"skip_not_installed",
"=",
"True",
"# Do not export internal libraries like gtest",
")",
"f",
".",
"close",
"(",
")"
] | https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/llvm/utils/llvm-build/llvmbuild/main.py#L604-L638 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | DC.GetBackground | (*args, **kwargs) | return _gdi_.DC_GetBackground(*args, **kwargs) | GetBackground(self) -> Brush
Gets the brush used for painting the background. | GetBackground(self) -> Brush | [
"GetBackground",
"(",
"self",
")",
"-",
">",
"Brush"
] | def GetBackground(*args, **kwargs):
"""
GetBackground(self) -> Brush
Gets the brush used for painting the background.
"""
return _gdi_.DC_GetBackground(*args, **kwargs) | [
"def",
"GetBackground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_GetBackground",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L4329-L4335 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/protobuf/python/mox.py | python | MockMethod.AndRaise | (self, exception) | Set the exception to raise when this method is called.
Args:
# exception: the exception to raise when this method is called.
exception: Exception | Set the exception to raise when this method is called. | [
"Set",
"the",
"exception",
"to",
"raise",
"when",
"this",
"method",
"is",
"called",
"."
] | def AndRaise(self, exception):
"""Set the exception to raise when this method is called.
Args:
# exception: the exception to raise when this method is called.
exception: Exception
"""
self._exception = exception | [
"def",
"AndRaise",
"(",
"self",
",",
"exception",
")",
":",
"self",
".",
"_exception",
"=",
"exception"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/mox.py#L728-L736 | ||
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | cyber/tools/cyber_launch/cyber_launch.py | python | start | (launch_file='') | Start all modules in xml config | Start all modules in xml config | [
"Start",
"all",
"modules",
"in",
"xml",
"config"
] | def start(launch_file=''):
"""
Start all modules in xml config
"""
pmon = ProcessMonitor()
# Find launch file
if launch_file[0] == '/':
launch_file = launch_file
elif launch_file == os.path.basename(launch_file):
launch_file = os.path.join(cyber_path, 'launch', launch_file)
else:
if os.path.exists(os.path.join(g_pwd, launch_file)):
launch_file = os.path.join(g_pwd, launch_file)
else:
logger.error('Cannot find launch file: %s ' % launch_file)
sys.exit(1)
logger.info('Launch file [%s]' % launch_file)
logger.info('=' * 120)
if not os.path.isfile(launch_file):
logger.error('Launch xml file %s does not exist' % launch_file)
sys.exit(1)
try:
tree = ET.parse(launch_file)
except Exception:
logger.error('Parse xml failed. illegal xml!')
sys.exit(1)
total_dag_num = 0
dictionary = {}
dag_dict = {}
root1 = tree.getroot()
for module in root1.findall('module'):
dag_conf = module.find('dag_conf').text
process_name = module.find('process_name').text
process_type = module.find('type')
if process_type is None:
process_type = 'library'
else:
process_type = process_type.text
if process_type is None:
process_type = 'library'
process_type = process_type.strip()
if process_type != 'binary':
if dag_conf is None or not dag_conf.strip():
logger.error('Library dag conf is null')
continue
if process_name is None:
process_name = 'mainboard_default_' + str(os.getpid())
process_name = process_name.strip()
if str(process_name) in dictionary:
dictionary[str(process_name)] += 1
else:
dictionary[str(process_name)] = 1
if str(process_name) not in dag_dict:
dag_dict[str(process_name)] = [str(dag_conf)]
else:
dag_dict[str(process_name)].append(str(dag_conf))
if dag_conf is not None:
total_dag_num += 1
process_list = []
root = tree.getroot()
for env in root.findall('environment'):
for var in env.getchildren():
os.environ[var.tag] = str(var.text)
for module in root.findall('module'):
module_name = module.find('name').text
dag_conf = module.find('dag_conf').text
process_name = module.find('process_name').text
sched_name = module.find('sched_name')
process_type = module.find('type')
exception_handler = module.find('exception_handler')
if process_type is None:
process_type = 'library'
else:
process_type = process_type.text
if process_type is None:
process_type = 'library'
process_type = process_type.strip()
if sched_name is None:
sched_name = "CYBER_DEFAULT"
else:
sched_name = sched_name.text
if process_name is None:
process_name = 'mainboard_default_' + str(os.getpid())
if dag_conf is None:
dag_conf = ''
if module_name is None:
module_name = ''
if exception_handler is None:
exception_handler = ''
else:
exception_handler = exception_handler.text
module_name = module_name.strip()
dag_conf = dag_conf.strip()
process_name = process_name.strip()
sched_name = sched_name.strip()
exception_handler = exception_handler.strip()
logger.info('Load module [%s] %s: [%s] [%s] conf: [%s] exception_handler: [%s]' %
(module_name, process_type, process_name, sched_name, dag_conf,
exception_handler))
if process_name not in process_list:
if process_type == 'binary':
if len(process_name) == 0:
logger.error(
'Start binary failed. Binary process_name is null.')
continue
pw = ProcessWrapper(
process_name.split()[0], 0, [
""], process_name, process_type,
exception_handler)
# Default is library
else:
pw = ProcessWrapper(
g_binary_name, 0, dag_dict[
str(process_name)], process_name,
process_type, sched_name, exception_handler)
result = pw.start()
if result != 0:
logger.error(
'Start manager [%s] failed. Stop all!' % process_name)
stop()
pmon.register(pw)
process_list.append(process_name)
# No module in xml
if not process_list:
logger.error("No module was found in xml config.")
return
all_died = pmon.run()
if not all_died:
logger.info("Stop all processes...")
stop()
logger.info("Cyber exit.") | [
"def",
"start",
"(",
"launch_file",
"=",
"''",
")",
":",
"pmon",
"=",
"ProcessMonitor",
"(",
")",
"# Find launch file",
"if",
"launch_file",
"[",
"0",
"]",
"==",
"'/'",
":",
"launch_file",
"=",
"launch_file",
"elif",
"launch_file",
"==",
"os",
".",
"path",
".",
"basename",
"(",
"launch_file",
")",
":",
"launch_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cyber_path",
",",
"'launch'",
",",
"launch_file",
")",
"else",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"g_pwd",
",",
"launch_file",
")",
")",
":",
"launch_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"g_pwd",
",",
"launch_file",
")",
"else",
":",
"logger",
".",
"error",
"(",
"'Cannot find launch file: %s '",
"%",
"launch_file",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"logger",
".",
"info",
"(",
"'Launch file [%s]'",
"%",
"launch_file",
")",
"logger",
".",
"info",
"(",
"'='",
"*",
"120",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"launch_file",
")",
":",
"logger",
".",
"error",
"(",
"'Launch xml file %s does not exist'",
"%",
"launch_file",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"try",
":",
"tree",
"=",
"ET",
".",
"parse",
"(",
"launch_file",
")",
"except",
"Exception",
":",
"logger",
".",
"error",
"(",
"'Parse xml failed. illegal xml!'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"total_dag_num",
"=",
"0",
"dictionary",
"=",
"{",
"}",
"dag_dict",
"=",
"{",
"}",
"root1",
"=",
"tree",
".",
"getroot",
"(",
")",
"for",
"module",
"in",
"root1",
".",
"findall",
"(",
"'module'",
")",
":",
"dag_conf",
"=",
"module",
".",
"find",
"(",
"'dag_conf'",
")",
".",
"text",
"process_name",
"=",
"module",
".",
"find",
"(",
"'process_name'",
")",
".",
"text",
"process_type",
"=",
"module",
".",
"find",
"(",
"'type'",
")",
"if",
"process_type",
"is",
"None",
":",
"process_type",
"=",
"'library'",
"else",
":",
"process_type",
"=",
"process_type",
".",
"text",
"if",
"process_type",
"is",
"None",
":",
"process_type",
"=",
"'library'",
"process_type",
"=",
"process_type",
".",
"strip",
"(",
")",
"if",
"process_type",
"!=",
"'binary'",
":",
"if",
"dag_conf",
"is",
"None",
"or",
"not",
"dag_conf",
".",
"strip",
"(",
")",
":",
"logger",
".",
"error",
"(",
"'Library dag conf is null'",
")",
"continue",
"if",
"process_name",
"is",
"None",
":",
"process_name",
"=",
"'mainboard_default_'",
"+",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
"process_name",
"=",
"process_name",
".",
"strip",
"(",
")",
"if",
"str",
"(",
"process_name",
")",
"in",
"dictionary",
":",
"dictionary",
"[",
"str",
"(",
"process_name",
")",
"]",
"+=",
"1",
"else",
":",
"dictionary",
"[",
"str",
"(",
"process_name",
")",
"]",
"=",
"1",
"if",
"str",
"(",
"process_name",
")",
"not",
"in",
"dag_dict",
":",
"dag_dict",
"[",
"str",
"(",
"process_name",
")",
"]",
"=",
"[",
"str",
"(",
"dag_conf",
")",
"]",
"else",
":",
"dag_dict",
"[",
"str",
"(",
"process_name",
")",
"]",
".",
"append",
"(",
"str",
"(",
"dag_conf",
")",
")",
"if",
"dag_conf",
"is",
"not",
"None",
":",
"total_dag_num",
"+=",
"1",
"process_list",
"=",
"[",
"]",
"root",
"=",
"tree",
".",
"getroot",
"(",
")",
"for",
"env",
"in",
"root",
".",
"findall",
"(",
"'environment'",
")",
":",
"for",
"var",
"in",
"env",
".",
"getchildren",
"(",
")",
":",
"os",
".",
"environ",
"[",
"var",
".",
"tag",
"]",
"=",
"str",
"(",
"var",
".",
"text",
")",
"for",
"module",
"in",
"root",
".",
"findall",
"(",
"'module'",
")",
":",
"module_name",
"=",
"module",
".",
"find",
"(",
"'name'",
")",
".",
"text",
"dag_conf",
"=",
"module",
".",
"find",
"(",
"'dag_conf'",
")",
".",
"text",
"process_name",
"=",
"module",
".",
"find",
"(",
"'process_name'",
")",
".",
"text",
"sched_name",
"=",
"module",
".",
"find",
"(",
"'sched_name'",
")",
"process_type",
"=",
"module",
".",
"find",
"(",
"'type'",
")",
"exception_handler",
"=",
"module",
".",
"find",
"(",
"'exception_handler'",
")",
"if",
"process_type",
"is",
"None",
":",
"process_type",
"=",
"'library'",
"else",
":",
"process_type",
"=",
"process_type",
".",
"text",
"if",
"process_type",
"is",
"None",
":",
"process_type",
"=",
"'library'",
"process_type",
"=",
"process_type",
".",
"strip",
"(",
")",
"if",
"sched_name",
"is",
"None",
":",
"sched_name",
"=",
"\"CYBER_DEFAULT\"",
"else",
":",
"sched_name",
"=",
"sched_name",
".",
"text",
"if",
"process_name",
"is",
"None",
":",
"process_name",
"=",
"'mainboard_default_'",
"+",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
"if",
"dag_conf",
"is",
"None",
":",
"dag_conf",
"=",
"''",
"if",
"module_name",
"is",
"None",
":",
"module_name",
"=",
"''",
"if",
"exception_handler",
"is",
"None",
":",
"exception_handler",
"=",
"''",
"else",
":",
"exception_handler",
"=",
"exception_handler",
".",
"text",
"module_name",
"=",
"module_name",
".",
"strip",
"(",
")",
"dag_conf",
"=",
"dag_conf",
".",
"strip",
"(",
")",
"process_name",
"=",
"process_name",
".",
"strip",
"(",
")",
"sched_name",
"=",
"sched_name",
".",
"strip",
"(",
")",
"exception_handler",
"=",
"exception_handler",
".",
"strip",
"(",
")",
"logger",
".",
"info",
"(",
"'Load module [%s] %s: [%s] [%s] conf: [%s] exception_handler: [%s]'",
"%",
"(",
"module_name",
",",
"process_type",
",",
"process_name",
",",
"sched_name",
",",
"dag_conf",
",",
"exception_handler",
")",
")",
"if",
"process_name",
"not",
"in",
"process_list",
":",
"if",
"process_type",
"==",
"'binary'",
":",
"if",
"len",
"(",
"process_name",
")",
"==",
"0",
":",
"logger",
".",
"error",
"(",
"'Start binary failed. Binary process_name is null.'",
")",
"continue",
"pw",
"=",
"ProcessWrapper",
"(",
"process_name",
".",
"split",
"(",
")",
"[",
"0",
"]",
",",
"0",
",",
"[",
"\"\"",
"]",
",",
"process_name",
",",
"process_type",
",",
"exception_handler",
")",
"# Default is library",
"else",
":",
"pw",
"=",
"ProcessWrapper",
"(",
"g_binary_name",
",",
"0",
",",
"dag_dict",
"[",
"str",
"(",
"process_name",
")",
"]",
",",
"process_name",
",",
"process_type",
",",
"sched_name",
",",
"exception_handler",
")",
"result",
"=",
"pw",
".",
"start",
"(",
")",
"if",
"result",
"!=",
"0",
":",
"logger",
".",
"error",
"(",
"'Start manager [%s] failed. Stop all!'",
"%",
"process_name",
")",
"stop",
"(",
")",
"pmon",
".",
"register",
"(",
"pw",
")",
"process_list",
".",
"append",
"(",
"process_name",
")",
"# No module in xml",
"if",
"not",
"process_list",
":",
"logger",
".",
"error",
"(",
"\"No module was found in xml config.\"",
")",
"return",
"all_died",
"=",
"pmon",
".",
"run",
"(",
")",
"if",
"not",
"all_died",
":",
"logger",
".",
"info",
"(",
"\"Stop all processes...\"",
")",
"stop",
"(",
")",
"logger",
".",
"info",
"(",
"\"Cyber exit.\"",
")"
] | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/cyber/tools/cyber_launch/cyber_launch.py#L309-L447 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/web-page-replay/httparchive.py | python | HttpArchive.__setstate__ | (self, state) | Influence how to unpickle.
Args:
state: a dictionary for __dict__ | Influence how to unpickle. | [
"Influence",
"how",
"to",
"unpickle",
"."
] | def __setstate__(self, state):
"""Influence how to unpickle.
Args:
state: a dictionary for __dict__
"""
self.__dict__.update(state)
self.responses_by_host = defaultdict(dict)
for request in self:
self.responses_by_host[request.host][request] = self[request] | [
"def",
"__setstate__",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"__dict__",
".",
"update",
"(",
"state",
")",
"self",
".",
"responses_by_host",
"=",
"defaultdict",
"(",
"dict",
")",
"for",
"request",
"in",
"self",
":",
"self",
".",
"responses_by_host",
"[",
"request",
".",
"host",
"]",
"[",
"request",
"]",
"=",
"self",
"[",
"request",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/httparchive.py#L94-L103 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/layers/python/layers/layers.py | python | flatten | (inputs,
outputs_collections=None,
scope=None) | Flattens the input while maintaining the batch_size.
Assumes that the first dimension represents the batch.
Args:
inputs: a tensor of size [batch_size, ...].
outputs_collections: collection to add the outputs.
scope: Optional scope for op_scope.
Returns:
a flattened tensor with shape [batch_size, k].
Raises:
ValueError: if inputs.shape is wrong. | Flattens the input while maintaining the batch_size. | [
"Flattens",
"the",
"input",
"while",
"maintaining",
"the",
"batch_size",
"."
] | def flatten(inputs,
outputs_collections=None,
scope=None):
"""Flattens the input while maintaining the batch_size.
Assumes that the first dimension represents the batch.
Args:
inputs: a tensor of size [batch_size, ...].
outputs_collections: collection to add the outputs.
scope: Optional scope for op_scope.
Returns:
a flattened tensor with shape [batch_size, k].
Raises:
ValueError: if inputs.shape is wrong.
"""
with ops.op_scope([inputs], scope, 'Flatten') as sc:
inputs = ops.convert_to_tensor(inputs)
inputs_shape = inputs.get_shape()
inputs_rank = inputs_shape.ndims
if (inputs_rank is None) or (inputs_rank < 2):
raise ValueError('Inputs must have a least 2 dimensions.')
dims = inputs_shape[1:]
if not dims.is_fully_defined():
raise ValueError('Inputs 2nd dimension must be defined.')
k = dims.num_elements()
outputs = array_ops.reshape(inputs, [-1, k])
return utils.collect_named_outputs(outputs_collections, sc, outputs) | [
"def",
"flatten",
"(",
"inputs",
",",
"outputs_collections",
"=",
"None",
",",
"scope",
"=",
"None",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"inputs",
"]",
",",
"scope",
",",
"'Flatten'",
")",
"as",
"sc",
":",
"inputs",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"inputs",
")",
"inputs_shape",
"=",
"inputs",
".",
"get_shape",
"(",
")",
"inputs_rank",
"=",
"inputs_shape",
".",
"ndims",
"if",
"(",
"inputs_rank",
"is",
"None",
")",
"or",
"(",
"inputs_rank",
"<",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'Inputs must have a least 2 dimensions.'",
")",
"dims",
"=",
"inputs_shape",
"[",
"1",
":",
"]",
"if",
"not",
"dims",
".",
"is_fully_defined",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Inputs 2nd dimension must be defined.'",
")",
"k",
"=",
"dims",
".",
"num_elements",
"(",
")",
"outputs",
"=",
"array_ops",
".",
"reshape",
"(",
"inputs",
",",
"[",
"-",
"1",
",",
"k",
"]",
")",
"return",
"utils",
".",
"collect_named_outputs",
"(",
"outputs_collections",
",",
"sc",
",",
"outputs",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/layers/python/layers/layers.py#L696-L724 | ||
include-what-you-use/include-what-you-use | 208fbfffa5d69364b9f78e427caa443441279283 | mapgen/iwyu-mapgen-cpython.py | python | generate_imp_lines | (include_names) | Generate a sequence of json-formatted strings in .imp format.
This should ideally return a jsonable structure instead, and use json.dump
to write it to the output file directly. But there doesn't seem to be a
simple way to convince Python's json library to generate a "packed"
formatting, it always prefers to wrap dicts onto multiple lines.
Cheat, and use json.dumps for escaping each line. | Generate a sequence of json-formatted strings in .imp format. | [
"Generate",
"a",
"sequence",
"of",
"json",
"-",
"formatted",
"strings",
"in",
".",
"imp",
"format",
"."
] | def generate_imp_lines(include_names):
""" Generate a sequence of json-formatted strings in .imp format.
This should ideally return a jsonable structure instead, and use json.dump
to write it to the output file directly. But there doesn't seem to be a
simple way to convince Python's json library to generate a "packed"
formatting, it always prefers to wrap dicts onto multiple lines.
Cheat, and use json.dumps for escaping each line.
"""
def jsonline(mapping, indent):
return (indent * ' ') + json.dumps(mapping)
for name in sorted(include_names):
# Regex-escape period and build a regex matching both "" and <>.
map_from = r'@["<]%s[">]' % name.replace('.', '\\.')
mapping = {'include': [map_from, 'private', '<Python.h>', 'public']}
yield jsonline(mapping, indent=2) | [
"def",
"generate_imp_lines",
"(",
"include_names",
")",
":",
"def",
"jsonline",
"(",
"mapping",
",",
"indent",
")",
":",
"return",
"(",
"indent",
"*",
"' '",
")",
"+",
"json",
".",
"dumps",
"(",
"mapping",
")",
"for",
"name",
"in",
"sorted",
"(",
"include_names",
")",
":",
"# Regex-escape period and build a regex matching both \"\" and <>.",
"map_from",
"=",
"r'@[\"<]%s[\">]'",
"%",
"name",
".",
"replace",
"(",
"'.'",
",",
"'\\\\.'",
")",
"mapping",
"=",
"{",
"'include'",
":",
"[",
"map_from",
",",
"'private'",
",",
"'<Python.h>'",
",",
"'public'",
"]",
"}",
"yield",
"jsonline",
"(",
"mapping",
",",
"indent",
"=",
"2",
")"
] | https://github.com/include-what-you-use/include-what-you-use/blob/208fbfffa5d69364b9f78e427caa443441279283/mapgen/iwyu-mapgen-cpython.py#L47-L64 | ||
shedskin/shedskin | ae88dbca7b1d9671cd8be448cb0b497122758936 | examples/bh.py | python | Vec3.__imul__ | (self, s) | return self | Multiply the vector times a scalar.
@param s the scalar value | Multiply the vector times a scalar. | [
"Multiply",
"the",
"vector",
"times",
"a",
"scalar",
"."
] | def __imul__(self, s):
"""
Multiply the vector times a scalar.
@param s the scalar value
"""
self.d0 *= s
self.d1 *= s
self.d2 *= s
return self | [
"def",
"__imul__",
"(",
"self",
",",
"s",
")",
":",
"self",
".",
"d0",
"*=",
"s",
"self",
".",
"d1",
"*=",
"s",
"self",
".",
"d2",
"*=",
"s",
"return",
"self"
] | https://github.com/shedskin/shedskin/blob/ae88dbca7b1d9671cd8be448cb0b497122758936/examples/bh.py#L114-L122 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/locators.py | python | Locator.locate | (self, requirement, prereleases=False) | return result | Find the most recent distribution which matches the given
requirement.
:param requirement: A requirement of the form 'foo (1.0)' or perhaps
'foo (>= 1.0, < 2.0, != 1.3)'
:param prereleases: If ``True``, allow pre-release versions
to be located. Otherwise, pre-release versions
are not returned.
:return: A :class:`Distribution` instance, or ``None`` if no such
distribution could be located. | Find the most recent distribution which matches the given
requirement. | [
"Find",
"the",
"most",
"recent",
"distribution",
"which",
"matches",
"the",
"given",
"requirement",
"."
] | def locate(self, requirement, prereleases=False):
"""
Find the most recent distribution which matches the given
requirement.
:param requirement: A requirement of the form 'foo (1.0)' or perhaps
'foo (>= 1.0, < 2.0, != 1.3)'
:param prereleases: If ``True``, allow pre-release versions
to be located. Otherwise, pre-release versions
are not returned.
:return: A :class:`Distribution` instance, or ``None`` if no such
distribution could be located.
"""
result = None
r = parse_requirement(requirement)
if r is None:
raise DistlibException('Not a valid requirement: %r' % requirement)
scheme = get_scheme(self.scheme)
self.matcher = matcher = scheme.matcher(r.requirement)
logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__)
versions = self.get_project(r.name)
if versions:
# sometimes, versions are invalid
slist = []
vcls = matcher.version_class
for k in versions:
try:
if not matcher.match(k):
logger.debug('%s did not match %r', matcher, k)
else:
if prereleases or not vcls(k).is_prerelease:
slist.append(k)
else:
logger.debug('skipping pre-release '
'version %s of %s', k, matcher.name)
except Exception:
logger.warning('error matching %s with %r', matcher, k)
pass # slist.append(k)
if len(slist) > 1:
slist = sorted(slist, key=scheme.key)
if slist:
logger.debug('sorted list: %s', slist)
version = slist[-1]
result = versions[version]
if result:
if r.extras:
result.extras = r.extras
result.download_urls = versions.get('urls', {}).get(version, set())
d = {}
sd = versions.get('digests', {})
for url in result.download_urls:
if url in sd:
d[url] = sd[url]
result.digests = d
self.matcher = None
return result | [
"def",
"locate",
"(",
"self",
",",
"requirement",
",",
"prereleases",
"=",
"False",
")",
":",
"result",
"=",
"None",
"r",
"=",
"parse_requirement",
"(",
"requirement",
")",
"if",
"r",
"is",
"None",
":",
"raise",
"DistlibException",
"(",
"'Not a valid requirement: %r'",
"%",
"requirement",
")",
"scheme",
"=",
"get_scheme",
"(",
"self",
".",
"scheme",
")",
"self",
".",
"matcher",
"=",
"matcher",
"=",
"scheme",
".",
"matcher",
"(",
"r",
".",
"requirement",
")",
"logger",
".",
"debug",
"(",
"'matcher: %s (%s)'",
",",
"matcher",
",",
"type",
"(",
"matcher",
")",
".",
"__name__",
")",
"versions",
"=",
"self",
".",
"get_project",
"(",
"r",
".",
"name",
")",
"if",
"versions",
":",
"# sometimes, versions are invalid",
"slist",
"=",
"[",
"]",
"vcls",
"=",
"matcher",
".",
"version_class",
"for",
"k",
"in",
"versions",
":",
"try",
":",
"if",
"not",
"matcher",
".",
"match",
"(",
"k",
")",
":",
"logger",
".",
"debug",
"(",
"'%s did not match %r'",
",",
"matcher",
",",
"k",
")",
"else",
":",
"if",
"prereleases",
"or",
"not",
"vcls",
"(",
"k",
")",
".",
"is_prerelease",
":",
"slist",
".",
"append",
"(",
"k",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'skipping pre-release '",
"'version %s of %s'",
",",
"k",
",",
"matcher",
".",
"name",
")",
"except",
"Exception",
":",
"logger",
".",
"warning",
"(",
"'error matching %s with %r'",
",",
"matcher",
",",
"k",
")",
"pass",
"# slist.append(k)",
"if",
"len",
"(",
"slist",
")",
">",
"1",
":",
"slist",
"=",
"sorted",
"(",
"slist",
",",
"key",
"=",
"scheme",
".",
"key",
")",
"if",
"slist",
":",
"logger",
".",
"debug",
"(",
"'sorted list: %s'",
",",
"slist",
")",
"version",
"=",
"slist",
"[",
"-",
"1",
"]",
"result",
"=",
"versions",
"[",
"version",
"]",
"if",
"result",
":",
"if",
"r",
".",
"extras",
":",
"result",
".",
"extras",
"=",
"r",
".",
"extras",
"result",
".",
"download_urls",
"=",
"versions",
".",
"get",
"(",
"'urls'",
",",
"{",
"}",
")",
".",
"get",
"(",
"version",
",",
"set",
"(",
")",
")",
"d",
"=",
"{",
"}",
"sd",
"=",
"versions",
".",
"get",
"(",
"'digests'",
",",
"{",
"}",
")",
"for",
"url",
"in",
"result",
".",
"download_urls",
":",
"if",
"url",
"in",
"sd",
":",
"d",
"[",
"url",
"]",
"=",
"sd",
"[",
"url",
"]",
"result",
".",
"digests",
"=",
"d",
"self",
".",
"matcher",
"=",
"None",
"return",
"result"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/locators.py#L314-L369 | |
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/atom/data.py | python | LinkFinder.find_self_link | (self) | return self.find_url('self') | Find the first link with rel set to 'self'
Returns:
A str containing the link's href or None if none of the links had rel
equal to 'self' | Find the first link with rel set to 'self' | [
"Find",
"the",
"first",
"link",
"with",
"rel",
"set",
"to",
"self"
] | def find_self_link(self):
"""Find the first link with rel set to 'self'
Returns:
A str containing the link's href or None if none of the links had rel
equal to 'self'
"""
return self.find_url('self') | [
"def",
"find_self_link",
"(",
"self",
")",
":",
"return",
"self",
".",
"find_url",
"(",
"'self'",
")"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/atom/data.py#L208-L215 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/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",
"(",
"src",
",",
"dst",
")",
"copymode",
"(",
"src",
",",
"dst",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/shutil.py#L111-L120 | ||
Yelp/MOE | 5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c | moe/optimal_learning/python/cpp_wrappers/log_likelihood.py | python | GaussianProcessLogLikelihood.compute_hessian_log_likelihood | (self) | We do not currently support computation of the (hyperparameter) hessian of log likelihood-like metrics. | We do not currently support computation of the (hyperparameter) hessian of log likelihood-like metrics. | [
"We",
"do",
"not",
"currently",
"support",
"computation",
"of",
"the",
"(",
"hyperparameter",
")",
"hessian",
"of",
"log",
"likelihood",
"-",
"like",
"metrics",
"."
] | def compute_hessian_log_likelihood(self):
"""We do not currently support computation of the (hyperparameter) hessian of log likelihood-like metrics."""
raise NotImplementedError('Currently C++ does not expose Hessian computation of log likelihood-like metrics.') | [
"def",
"compute_hessian_log_likelihood",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Currently C++ does not expose Hessian computation of log likelihood-like metrics.'",
")"
] | https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/cpp_wrappers/log_likelihood.py#L342-L344 | ||
TimoSaemann/caffe-segnet-cudnn5 | abcf30dca449245e101bf4ced519f716177f0885 | scripts/cpp_lint.py | python | IsBlankLine | (line) | return not line or line.isspace() | Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank. | Returns true if the given line is blank. | [
"Returns",
"true",
"if",
"the",
"given",
"line",
"is",
"blank",
"."
] | def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace() | [
"def",
"IsBlankLine",
"(",
"line",
")",
":",
"return",
"not",
"line",
"or",
"line",
".",
"isspace",
"(",
")"
] | https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/scripts/cpp_lint.py#L2369-L2381 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/xcodeproj_file.py | python | PBXGroup.TakeOverOnlyChild | (self, recurse=False) | If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children.
This function will continue to take over only children when those children
are groups. If there are three PBXGroups representing a, b, and c, with
c inside b and b inside a, and a and b have no other children, this will
result in a taking over both b and c, forming a PBXGroup for a/b/c.
If recurse is True, this function will recurse into children and ask them
to collapse themselves by taking over only children as well. Assuming
an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f
(d1, d2, and f are files, the rest are groups), recursion will result in
a group for a/b/c containing a group for d3/e. | If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children. | [
"If",
"this",
"PBXGroup",
"has",
"only",
"one",
"child",
"and",
"it",
"s",
"also",
"a",
"PBXGroup",
"take",
"it",
"over",
"by",
"making",
"all",
"of",
"its",
"children",
"this",
"object",
"s",
"children",
"."
] | def TakeOverOnlyChild(self, recurse=False):
"""If this PBXGroup has only one child and it's also a PBXGroup, take
it over by making all of its children this object's children.
This function will continue to take over only children when those children
are groups. If there are three PBXGroups representing a, b, and c, with
c inside b and b inside a, and a and b have no other children, this will
result in a taking over both b and c, forming a PBXGroup for a/b/c.
If recurse is True, this function will recurse into children and ask them
to collapse themselves by taking over only children as well. Assuming
an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f
(d1, d2, and f are files, the rest are groups), recursion will result in
a group for a/b/c containing a group for d3/e.
"""
# At this stage, check that child class types are PBXGroup exactly,
# instead of using isinstance. The only subclass of PBXGroup,
# PBXVariantGroup, should not participate in reparenting in the same way:
# reparenting by merging different object types would be wrong.
while len(self._properties['children']) == 1 and \
self._properties['children'][0].__class__ == PBXGroup:
# Loop to take over the innermost only-child group possible.
child = self._properties['children'][0]
# Assume the child's properties, including its children. Save a copy
# of this object's old properties, because they'll still be needed.
# This object retains its existing id and parent attributes.
old_properties = self._properties
self._properties = child._properties
self._children_by_path = child._children_by_path
if not 'sourceTree' in self._properties or \
self._properties['sourceTree'] == '<group>':
# The child was relative to its parent. Fix up the path. Note that
# children with a sourceTree other than "<group>" are not relative to
# their parents, so no path fix-up is needed in that case.
if 'path' in old_properties:
if 'path' in self._properties:
# Both the original parent and child have paths set.
self._properties['path'] = posixpath.join(old_properties['path'],
self._properties['path'])
else:
# Only the original parent has a path, use it.
self._properties['path'] = old_properties['path']
if 'sourceTree' in old_properties:
# The original parent had a sourceTree set, use it.
self._properties['sourceTree'] = old_properties['sourceTree']
# If the original parent had a name set, keep using it. If the original
# parent didn't have a name but the child did, let the child's name
# live on. If the name attribute seems unnecessary now, get rid of it.
if 'name' in old_properties and old_properties['name'] != None and \
old_properties['name'] != self.Name():
self._properties['name'] = old_properties['name']
if 'name' in self._properties and 'path' in self._properties and \
self._properties['name'] == self._properties['path']:
del self._properties['name']
# Notify all children of their new parent.
for child in self._properties['children']:
child.parent = self
# If asked to recurse, recurse.
if recurse:
for child in self._properties['children']:
if child.__class__ == PBXGroup:
child.TakeOverOnlyChild(recurse) | [
"def",
"TakeOverOnlyChild",
"(",
"self",
",",
"recurse",
"=",
"False",
")",
":",
"# At this stage, check that child class types are PBXGroup exactly,",
"# instead of using isinstance. The only subclass of PBXGroup,",
"# PBXVariantGroup, should not participate in reparenting in the same way:",
"# reparenting by merging different object types would be wrong.",
"while",
"len",
"(",
"self",
".",
"_properties",
"[",
"'children'",
"]",
")",
"==",
"1",
"and",
"self",
".",
"_properties",
"[",
"'children'",
"]",
"[",
"0",
"]",
".",
"__class__",
"==",
"PBXGroup",
":",
"# Loop to take over the innermost only-child group possible.",
"child",
"=",
"self",
".",
"_properties",
"[",
"'children'",
"]",
"[",
"0",
"]",
"# Assume the child's properties, including its children. Save a copy",
"# of this object's old properties, because they'll still be needed.",
"# This object retains its existing id and parent attributes.",
"old_properties",
"=",
"self",
".",
"_properties",
"self",
".",
"_properties",
"=",
"child",
".",
"_properties",
"self",
".",
"_children_by_path",
"=",
"child",
".",
"_children_by_path",
"if",
"not",
"'sourceTree'",
"in",
"self",
".",
"_properties",
"or",
"self",
".",
"_properties",
"[",
"'sourceTree'",
"]",
"==",
"'<group>'",
":",
"# The child was relative to its parent. Fix up the path. Note that",
"# children with a sourceTree other than \"<group>\" are not relative to",
"# their parents, so no path fix-up is needed in that case.",
"if",
"'path'",
"in",
"old_properties",
":",
"if",
"'path'",
"in",
"self",
".",
"_properties",
":",
"# Both the original parent and child have paths set.",
"self",
".",
"_properties",
"[",
"'path'",
"]",
"=",
"posixpath",
".",
"join",
"(",
"old_properties",
"[",
"'path'",
"]",
",",
"self",
".",
"_properties",
"[",
"'path'",
"]",
")",
"else",
":",
"# Only the original parent has a path, use it.",
"self",
".",
"_properties",
"[",
"'path'",
"]",
"=",
"old_properties",
"[",
"'path'",
"]",
"if",
"'sourceTree'",
"in",
"old_properties",
":",
"# The original parent had a sourceTree set, use it.",
"self",
".",
"_properties",
"[",
"'sourceTree'",
"]",
"=",
"old_properties",
"[",
"'sourceTree'",
"]",
"# If the original parent had a name set, keep using it. If the original",
"# parent didn't have a name but the child did, let the child's name",
"# live on. If the name attribute seems unnecessary now, get rid of it.",
"if",
"'name'",
"in",
"old_properties",
"and",
"old_properties",
"[",
"'name'",
"]",
"!=",
"None",
"and",
"old_properties",
"[",
"'name'",
"]",
"!=",
"self",
".",
"Name",
"(",
")",
":",
"self",
".",
"_properties",
"[",
"'name'",
"]",
"=",
"old_properties",
"[",
"'name'",
"]",
"if",
"'name'",
"in",
"self",
".",
"_properties",
"and",
"'path'",
"in",
"self",
".",
"_properties",
"and",
"self",
".",
"_properties",
"[",
"'name'",
"]",
"==",
"self",
".",
"_properties",
"[",
"'path'",
"]",
":",
"del",
"self",
".",
"_properties",
"[",
"'name'",
"]",
"# Notify all children of their new parent.",
"for",
"child",
"in",
"self",
".",
"_properties",
"[",
"'children'",
"]",
":",
"child",
".",
"parent",
"=",
"self",
"# If asked to recurse, recurse.",
"if",
"recurse",
":",
"for",
"child",
"in",
"self",
".",
"_properties",
"[",
"'children'",
"]",
":",
"if",
"child",
".",
"__class__",
"==",
"PBXGroup",
":",
"child",
".",
"TakeOverOnlyChild",
"(",
"recurse",
")"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/xcodeproj_file.py#L1333-L1401 | ||
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | bindings/experimental/distrdf/python/DistRDF/Backends/Utils.py | python | _ | (resultptr) | return resultptr | Results coming from an `AsNumpy` operation can be merged with others, but
we need to make sure to call its `GetValue` method since that will populate
the private attribute `_py_arrays` (which is the actual dictionary of
numpy arrays extracted from the RDataFrame columns). This extra call is an
insurance against backends that do not automatically serialize objects
returned by the mapper function (otherwise this would be taken care by the
`AsNumpyResult`'s `__getstate__` method). | Results coming from an `AsNumpy` operation can be merged with others, but
we need to make sure to call its `GetValue` method since that will populate
the private attribute `_py_arrays` (which is the actual dictionary of
numpy arrays extracted from the RDataFrame columns). This extra call is an
insurance against backends that do not automatically serialize objects
returned by the mapper function (otherwise this would be taken care by the
`AsNumpyResult`'s `__getstate__` method). | [
"Results",
"coming",
"from",
"an",
"AsNumpy",
"operation",
"can",
"be",
"merged",
"with",
"others",
"but",
"we",
"need",
"to",
"make",
"sure",
"to",
"call",
"its",
"GetValue",
"method",
"since",
"that",
"will",
"populate",
"the",
"private",
"attribute",
"_py_arrays",
"(",
"which",
"is",
"the",
"actual",
"dictionary",
"of",
"numpy",
"arrays",
"extracted",
"from",
"the",
"RDataFrame",
"columns",
")",
".",
"This",
"extra",
"call",
"is",
"an",
"insurance",
"against",
"backends",
"that",
"do",
"not",
"automatically",
"serialize",
"objects",
"returned",
"by",
"the",
"mapper",
"function",
"(",
"otherwise",
"this",
"would",
"be",
"taken",
"care",
"by",
"the",
"AsNumpyResult",
"s",
"__getstate__",
"method",
")",
"."
] | def _(resultptr):
"""
Results coming from an `AsNumpy` operation can be merged with others, but
we need to make sure to call its `GetValue` method since that will populate
the private attribute `_py_arrays` (which is the actual dictionary of
numpy arrays extracted from the RDataFrame columns). This extra call is an
insurance against backends that do not automatically serialize objects
returned by the mapper function (otherwise this would be taken care by the
`AsNumpyResult`'s `__getstate__` method).
"""
resultptr.GetValue()
return resultptr | [
"def",
"_",
"(",
"resultptr",
")",
":",
"resultptr",
".",
"GetValue",
"(",
")",
"return",
"resultptr"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/bindings/experimental/distrdf/python/DistRDF/Backends/Utils.py#L166-L177 | |
Z3Prover/z3 | d745d03afdfdf638d66093e2bfbacaf87187f35b | src/api/python/z3/z3.py | python | IndexOf | (s, substr, offset=None) | return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx) | Retrieve the index of substring within a string starting at a specified offset.
>>> simplify(IndexOf("abcabc", "bc", 0))
1
>>> simplify(IndexOf("abcabc", "bc", 2))
4 | Retrieve the index of substring within a string starting at a specified offset.
>>> simplify(IndexOf("abcabc", "bc", 0))
1
>>> simplify(IndexOf("abcabc", "bc", 2))
4 | [
"Retrieve",
"the",
"index",
"of",
"substring",
"within",
"a",
"string",
"starting",
"at",
"a",
"specified",
"offset",
".",
">>>",
"simplify",
"(",
"IndexOf",
"(",
"abcabc",
"bc",
"0",
"))",
"1",
">>>",
"simplify",
"(",
"IndexOf",
"(",
"abcabc",
"bc",
"2",
"))",
"4"
] | def IndexOf(s, substr, offset=None):
"""Retrieve the index of substring within a string starting at a specified offset.
>>> simplify(IndexOf("abcabc", "bc", 0))
1
>>> simplify(IndexOf("abcabc", "bc", 2))
4
"""
if offset is None:
offset = IntVal(0)
ctx = None
if is_expr(offset):
ctx = offset.ctx
ctx = _get_ctx2(s, substr, ctx)
s = _coerce_seq(s, ctx)
substr = _coerce_seq(substr, ctx)
if _is_int(offset):
offset = IntVal(offset, ctx)
return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx) | [
"def",
"IndexOf",
"(",
"s",
",",
"substr",
",",
"offset",
"=",
"None",
")",
":",
"if",
"offset",
"is",
"None",
":",
"offset",
"=",
"IntVal",
"(",
"0",
")",
"ctx",
"=",
"None",
"if",
"is_expr",
"(",
"offset",
")",
":",
"ctx",
"=",
"offset",
".",
"ctx",
"ctx",
"=",
"_get_ctx2",
"(",
"s",
",",
"substr",
",",
"ctx",
")",
"s",
"=",
"_coerce_seq",
"(",
"s",
",",
"ctx",
")",
"substr",
"=",
"_coerce_seq",
"(",
"substr",
",",
"ctx",
")",
"if",
"_is_int",
"(",
"offset",
")",
":",
"offset",
"=",
"IntVal",
"(",
"offset",
",",
"ctx",
")",
"return",
"ArithRef",
"(",
"Z3_mk_seq_index",
"(",
"s",
".",
"ctx_ref",
"(",
")",
",",
"s",
".",
"as_ast",
"(",
")",
",",
"substr",
".",
"as_ast",
"(",
")",
",",
"offset",
".",
"as_ast",
"(",
")",
")",
",",
"s",
".",
"ctx",
")"
] | https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L10929-L10946 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/mailbox.py | python | Babyl._generate_toc | (self) | Generate key-to-(start, stop) table of contents. | Generate key-to-(start, stop) table of contents. | [
"Generate",
"key",
"-",
"to",
"-",
"(",
"start",
"stop",
")",
"table",
"of",
"contents",
"."
] | def _generate_toc(self):
"""Generate key-to-(start, stop) table of contents."""
starts, stops = [], []
self._file.seek(0)
next_pos = 0
label_lists = []
while True:
line_pos = next_pos
line = self._file.readline()
next_pos = self._file.tell()
if line == '\037\014' + os.linesep:
if len(stops) < len(starts):
stops.append(line_pos - len(os.linesep))
starts.append(next_pos)
labels = [label.strip() for label
in self._file.readline()[1:].split(',')
if label.strip() != '']
label_lists.append(labels)
elif line == '\037' or line == '\037' + os.linesep:
if len(stops) < len(starts):
stops.append(line_pos - len(os.linesep))
elif line == '':
stops.append(line_pos - len(os.linesep))
break
self._toc = dict(enumerate(zip(starts, stops)))
self._labels = dict(enumerate(label_lists))
self._next_key = len(self._toc)
self._file.seek(0, 2)
self._file_length = self._file.tell() | [
"def",
"_generate_toc",
"(",
"self",
")",
":",
"starts",
",",
"stops",
"=",
"[",
"]",
",",
"[",
"]",
"self",
".",
"_file",
".",
"seek",
"(",
"0",
")",
"next_pos",
"=",
"0",
"label_lists",
"=",
"[",
"]",
"while",
"True",
":",
"line_pos",
"=",
"next_pos",
"line",
"=",
"self",
".",
"_file",
".",
"readline",
"(",
")",
"next_pos",
"=",
"self",
".",
"_file",
".",
"tell",
"(",
")",
"if",
"line",
"==",
"'\\037\\014'",
"+",
"os",
".",
"linesep",
":",
"if",
"len",
"(",
"stops",
")",
"<",
"len",
"(",
"starts",
")",
":",
"stops",
".",
"append",
"(",
"line_pos",
"-",
"len",
"(",
"os",
".",
"linesep",
")",
")",
"starts",
".",
"append",
"(",
"next_pos",
")",
"labels",
"=",
"[",
"label",
".",
"strip",
"(",
")",
"for",
"label",
"in",
"self",
".",
"_file",
".",
"readline",
"(",
")",
"[",
"1",
":",
"]",
".",
"split",
"(",
"','",
")",
"if",
"label",
".",
"strip",
"(",
")",
"!=",
"''",
"]",
"label_lists",
".",
"append",
"(",
"labels",
")",
"elif",
"line",
"==",
"'\\037'",
"or",
"line",
"==",
"'\\037'",
"+",
"os",
".",
"linesep",
":",
"if",
"len",
"(",
"stops",
")",
"<",
"len",
"(",
"starts",
")",
":",
"stops",
".",
"append",
"(",
"line_pos",
"-",
"len",
"(",
"os",
".",
"linesep",
")",
")",
"elif",
"line",
"==",
"''",
":",
"stops",
".",
"append",
"(",
"line_pos",
"-",
"len",
"(",
"os",
".",
"linesep",
")",
")",
"break",
"self",
".",
"_toc",
"=",
"dict",
"(",
"enumerate",
"(",
"zip",
"(",
"starts",
",",
"stops",
")",
")",
")",
"self",
".",
"_labels",
"=",
"dict",
"(",
"enumerate",
"(",
"label_lists",
")",
")",
"self",
".",
"_next_key",
"=",
"len",
"(",
"self",
".",
"_toc",
")",
"self",
".",
"_file",
".",
"seek",
"(",
"0",
",",
"2",
")",
"self",
".",
"_file_length",
"=",
"self",
".",
"_file",
".",
"tell",
"(",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mailbox.py#L1204-L1232 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/PyShell.py | python | extended_linecache_checkcache | (filename=None,
orig_checkcache=linecache.checkcache) | Extend linecache.checkcache to preserve the <pyshell#...> entries
Rather than repeating the linecache code, patch it to save the
<pyshell#...> entries, call the original linecache.checkcache()
(skipping them), and then restore the saved entries.
orig_checkcache is bound at definition time to the original
method, allowing it to be patched. | Extend linecache.checkcache to preserve the <pyshell#...> entries | [
"Extend",
"linecache",
".",
"checkcache",
"to",
"preserve",
"the",
"<pyshell#",
"...",
">",
"entries"
] | def extended_linecache_checkcache(filename=None,
orig_checkcache=linecache.checkcache):
"""Extend linecache.checkcache to preserve the <pyshell#...> entries
Rather than repeating the linecache code, patch it to save the
<pyshell#...> entries, call the original linecache.checkcache()
(skipping them), and then restore the saved entries.
orig_checkcache is bound at definition time to the original
method, allowing it to be patched.
"""
cache = linecache.cache
save = {}
for key in list(cache):
if key[:1] + key[-1:] == '<>':
save[key] = cache.pop(key)
orig_checkcache(filename)
cache.update(save) | [
"def",
"extended_linecache_checkcache",
"(",
"filename",
"=",
"None",
",",
"orig_checkcache",
"=",
"linecache",
".",
"checkcache",
")",
":",
"cache",
"=",
"linecache",
".",
"cache",
"save",
"=",
"{",
"}",
"for",
"key",
"in",
"list",
"(",
"cache",
")",
":",
"if",
"key",
"[",
":",
"1",
"]",
"+",
"key",
"[",
"-",
"1",
":",
"]",
"==",
"'<>'",
":",
"save",
"[",
"key",
"]",
"=",
"cache",
".",
"pop",
"(",
"key",
")",
"orig_checkcache",
"(",
"filename",
")",
"cache",
".",
"update",
"(",
"save",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/PyShell.py#L83-L100 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/collection.py | python | ResourceCollection.all | (self) | return self._clone() | Get all items from the collection, optionally with a custom
page size and item count limit.
This method returns an iterable generator which yields
individual resource instances. Example use::
# Iterate through items
>>> for queue in sqs.queues.all():
... print(queue.url)
'https://url1'
'https://url2'
# Convert to list
>>> queues = list(sqs.queues.all())
>>> len(queues)
2 | Get all items from the collection, optionally with a custom
page size and item count limit. | [
"Get",
"all",
"items",
"from",
"the",
"collection",
"optionally",
"with",
"a",
"custom",
"page",
"size",
"and",
"item",
"count",
"limit",
"."
] | def all(self):
"""
Get all items from the collection, optionally with a custom
page size and item count limit.
This method returns an iterable generator which yields
individual resource instances. Example use::
# Iterate through items
>>> for queue in sqs.queues.all():
... print(queue.url)
'https://url1'
'https://url2'
# Convert to list
>>> queues = list(sqs.queues.all())
>>> len(queues)
2
"""
return self._clone() | [
"def",
"all",
"(",
"self",
")",
":",
"return",
"self",
".",
"_clone",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/boto3/resources/collection.py#L183-L202 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/nn/layer/rnn.py | python | LSTMCell.state_shape | (self) | return ((self.hidden_size, ), (self.hidden_size, )) | r"""
The `state_shape` of LSTMCell is a tuple with two shapes:
`((hidden_size, ), (hidden_size,))`. (-1 for batch size would be
automatically inserted into shape). These two shapes correspond
to :math:`h_{t-1}` and :math:`c_{t-1}` separately. | r"""
The `state_shape` of LSTMCell is a tuple with two shapes:
`((hidden_size, ), (hidden_size,))`. (-1 for batch size would be
automatically inserted into shape). These two shapes correspond
to :math:`h_{t-1}` and :math:`c_{t-1}` separately. | [
"r",
"The",
"state_shape",
"of",
"LSTMCell",
"is",
"a",
"tuple",
"with",
"two",
"shapes",
":",
"((",
"hidden_size",
")",
"(",
"hidden_size",
"))",
".",
"(",
"-",
"1",
"for",
"batch",
"size",
"would",
"be",
"automatically",
"inserted",
"into",
"shape",
")",
".",
"These",
"two",
"shapes",
"correspond",
"to",
":",
"math",
":",
"h_",
"{",
"t",
"-",
"1",
"}",
"and",
":",
"math",
":",
"c_",
"{",
"t",
"-",
"1",
"}",
"separately",
"."
] | def state_shape(self):
r"""
The `state_shape` of LSTMCell is a tuple with two shapes:
`((hidden_size, ), (hidden_size,))`. (-1 for batch size would be
automatically inserted into shape). These two shapes correspond
to :math:`h_{t-1}` and :math:`c_{t-1}` separately.
"""
return ((self.hidden_size, ), (self.hidden_size, )) | [
"def",
"state_shape",
"(",
"self",
")",
":",
"return",
"(",
"(",
"self",
".",
"hidden_size",
",",
")",
",",
"(",
"self",
".",
"hidden_size",
",",
")",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/nn/layer/rnn.py#L538-L545 | |
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py | python | _AddClassAttributesForNestedExtensions | (message_descriptor, dictionary) | Adds class attributes for the nested extensions. | Adds class attributes for the nested extensions. | [
"Adds",
"class",
"attributes",
"for",
"the",
"nested",
"extensions",
"."
] | def _AddClassAttributesForNestedExtensions(message_descriptor, dictionary):
"""Adds class attributes for the nested extensions."""
extension_dict = message_descriptor.extensions_by_name
for extension_name, extension_field in extension_dict.iteritems():
assert extension_name not in dictionary
dictionary[extension_name] = extension_field | [
"def",
"_AddClassAttributesForNestedExtensions",
"(",
"message_descriptor",
",",
"dictionary",
")",
":",
"extension_dict",
"=",
"message_descriptor",
".",
"extensions_by_name",
"for",
"extension_name",
",",
"extension_field",
"in",
"extension_dict",
".",
"iteritems",
"(",
")",
":",
"assert",
"extension_name",
"not",
"in",
"dictionary",
"dictionary",
"[",
"extension_name",
"]",
"=",
"extension_field"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/cpp_message.py#L420-L425 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | GetMxDegNId | (*args) | return _snap.GetMxDegNId(*args) | GetMxDegNId(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const & | GetMxDegNId(PNEANet Graph) -> int | [
"GetMxDegNId",
"(",
"PNEANet",
"Graph",
")",
"-",
">",
"int"
] | def GetMxDegNId(*args):
"""
GetMxDegNId(PNEANet Graph) -> int
Parameters:
Graph: TPt< TNEANet > const &
"""
return _snap.GetMxDegNId(*args) | [
"def",
"GetMxDegNId",
"(",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"GetMxDegNId",
"(",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L24788-L24796 | |
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | lldb/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py | python | SpawnBase.isatty | (self) | return False | Overridden in subclass using tty | Overridden in subclass using tty | [
"Overridden",
"in",
"subclass",
"using",
"tty"
] | def isatty(self):
"""Overridden in subclass using tty"""
return False | [
"def",
"isatty",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py#L511-L513 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/ipython/py2/IPython/lib/demo.py | python | Demo.reset | (self) | Reset the namespace and seek pointer to restart the demo | Reset the namespace and seek pointer to restart the demo | [
"Reset",
"the",
"namespace",
"and",
"seek",
"pointer",
"to",
"restart",
"the",
"demo"
] | def reset(self):
"""Reset the namespace and seek pointer to restart the demo"""
self.user_ns = {}
self.finished = False
self.block_index = 0 | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"user_ns",
"=",
"{",
"}",
"self",
".",
"finished",
"=",
"False",
"self",
".",
"block_index",
"=",
"0"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/lib/demo.py#L312-L316 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewRenderer.FinishEditing | (*args, **kwargs) | return _dataview.DataViewRenderer_FinishEditing(*args, **kwargs) | FinishEditing(self) -> bool | FinishEditing(self) -> bool | [
"FinishEditing",
"(",
"self",
")",
"-",
">",
"bool"
] | def FinishEditing(*args, **kwargs):
"""FinishEditing(self) -> bool"""
return _dataview.DataViewRenderer_FinishEditing(*args, **kwargs) | [
"def",
"FinishEditing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewRenderer_FinishEditing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1216-L1218 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | TextAttrBorder.__init__ | (self, *args, **kwargs) | __init__(self) -> TextAttrBorder | __init__(self) -> TextAttrBorder | [
"__init__",
"(",
"self",
")",
"-",
">",
"TextAttrBorder"
] | def __init__(self, *args, **kwargs):
"""__init__(self) -> TextAttrBorder"""
_richtext.TextAttrBorder_swiginit(self,_richtext.new_TextAttrBorder(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_richtext",
".",
"TextAttrBorder_swiginit",
"(",
"self",
",",
"_richtext",
".",
"new_TextAttrBorder",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L322-L324 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py | python | TurtleScreenBase._drawpoly | (self, polyitem, coordlist, fill=None,
outline=None, width=None, top=False) | Configure polygonitem polyitem according to provided
arguments:
coordlist is sequence of coordinates
fill is filling color
outline is outline color
top is a boolean value, which specifies if polyitem
will be put on top of the canvas' displaylist so it
will not be covered by other items. | Configure polygonitem polyitem according to provided
arguments:
coordlist is sequence of coordinates
fill is filling color
outline is outline color
top is a boolean value, which specifies if polyitem
will be put on top of the canvas' displaylist so it
will not be covered by other items. | [
"Configure",
"polygonitem",
"polyitem",
"according",
"to",
"provided",
"arguments",
":",
"coordlist",
"is",
"sequence",
"of",
"coordinates",
"fill",
"is",
"filling",
"color",
"outline",
"is",
"outline",
"color",
"top",
"is",
"a",
"boolean",
"value",
"which",
"specifies",
"if",
"polyitem",
"will",
"be",
"put",
"on",
"top",
"of",
"the",
"canvas",
"displaylist",
"so",
"it",
"will",
"not",
"be",
"covered",
"by",
"other",
"items",
"."
] | def _drawpoly(self, polyitem, coordlist, fill=None,
outline=None, width=None, top=False):
"""Configure polygonitem polyitem according to provided
arguments:
coordlist is sequence of coordinates
fill is filling color
outline is outline color
top is a boolean value, which specifies if polyitem
will be put on top of the canvas' displaylist so it
will not be covered by other items.
"""
cl = []
for x, y in coordlist:
cl.append(x * self.xscale)
cl.append(-y * self.yscale)
self.cv.coords(polyitem, *cl)
if fill is not None:
self.cv.itemconfigure(polyitem, fill=fill)
if outline is not None:
self.cv.itemconfigure(polyitem, outline=outline)
if width is not None:
self.cv.itemconfigure(polyitem, width=width)
if top:
self.cv.tag_raise(polyitem) | [
"def",
"_drawpoly",
"(",
"self",
",",
"polyitem",
",",
"coordlist",
",",
"fill",
"=",
"None",
",",
"outline",
"=",
"None",
",",
"width",
"=",
"None",
",",
"top",
"=",
"False",
")",
":",
"cl",
"=",
"[",
"]",
"for",
"x",
",",
"y",
"in",
"coordlist",
":",
"cl",
".",
"append",
"(",
"x",
"*",
"self",
".",
"xscale",
")",
"cl",
".",
"append",
"(",
"-",
"y",
"*",
"self",
".",
"yscale",
")",
"self",
".",
"cv",
".",
"coords",
"(",
"polyitem",
",",
"*",
"cl",
")",
"if",
"fill",
"is",
"not",
"None",
":",
"self",
".",
"cv",
".",
"itemconfigure",
"(",
"polyitem",
",",
"fill",
"=",
"fill",
")",
"if",
"outline",
"is",
"not",
"None",
":",
"self",
".",
"cv",
".",
"itemconfigure",
"(",
"polyitem",
",",
"outline",
"=",
"outline",
")",
"if",
"width",
"is",
"not",
"None",
":",
"self",
".",
"cv",
".",
"itemconfigure",
"(",
"polyitem",
",",
"width",
"=",
"width",
")",
"if",
"top",
":",
"self",
".",
"cv",
".",
"tag_raise",
"(",
"polyitem",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/turtle.py#L523-L546 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/RNN/rnn_quantizer/tensorflow/tf_nndct/utils/convert_to_constants.py | python | _run_inline_graph_optimization | (func, lower_control_flow) | return tf_optimizer.OptimizeGraph(config, meta_graph) | Apply function inline optimization to the graph.
Returns the GraphDef after Grappler's function inlining optimization is
applied. This optimization does not work on models with control flow.
Args:
func: ConcreteFunction.
lower_control_flow: Boolean indicating whether or not to lower control flow
ops such as If and While. (default True)
Returns:
GraphDef | Apply function inline optimization to the graph. | [
"Apply",
"function",
"inline",
"optimization",
"to",
"the",
"graph",
"."
] | def _run_inline_graph_optimization(func, lower_control_flow):
"""Apply function inline optimization to the graph.
Returns the GraphDef after Grappler's function inlining optimization is
applied. This optimization does not work on models with control flow.
Args:
func: ConcreteFunction.
lower_control_flow: Boolean indicating whether or not to lower control flow
ops such as If and While. (default True)
Returns:
GraphDef
"""
graph_def = func.graph.as_graph_def()
if not lower_control_flow:
graph_def = disable_lower_using_switch_merge(graph_def)
# In some cases, a secondary implementation of the function (e.g. for GPU) is
# written to the "api_implements" attribute. (e.g. `tf.keras.layers.LSTM` in
# TF2 produces a CuDNN-based RNN for GPU).
# This function suppose to inline all functions calls, but "api_implements"
# prevents this from happening. Removing the attribute solves the problem.
# To learn more about "api_implements", see:
# tensorflow/core/grappler/optimizers/implementation_selector.h
for function in graph_def.library.function:
if "api_implements" in function.attr:
del function.attr["api_implements"]
meta_graph = export_meta_graph(graph_def=graph_def, graph=func.graph)
# Clear the initializer_name for the variables collections, since they are not
# needed after saved to saved_model.
for name in [
"variables", "model_variables", "trainable_variables", "local_variables"
]:
raw_list = []
for raw in meta_graph.collection_def["variables"].bytes_list.value:
variable = variable_pb2.VariableDef()
variable.ParseFromString(raw)
variable.ClearField("initializer_name")
raw_list.append(variable.SerializeToString())
meta_graph.collection_def[name].bytes_list.value[:] = raw_list
# Add a collection 'train_op' so that Grappler knows the outputs.
fetch_collection = meta_graph_pb2.CollectionDef()
for array in func.inputs + func.outputs:
fetch_collection.node_list.value.append(array.name)
meta_graph.collection_def["train_op"].CopyFrom(fetch_collection)
# Initialize RewriterConfig with everything disabled except function inlining.
config = config_pb2.ConfigProto()
rewrite_options = config.graph_options.rewrite_options
rewrite_options.min_graph_nodes = -1 # do not skip small graphs
rewrite_options.optimizers.append("function")
return tf_optimizer.OptimizeGraph(config, meta_graph) | [
"def",
"_run_inline_graph_optimization",
"(",
"func",
",",
"lower_control_flow",
")",
":",
"graph_def",
"=",
"func",
".",
"graph",
".",
"as_graph_def",
"(",
")",
"if",
"not",
"lower_control_flow",
":",
"graph_def",
"=",
"disable_lower_using_switch_merge",
"(",
"graph_def",
")",
"# In some cases, a secondary implementation of the function (e.g. for GPU) is",
"# written to the \"api_implements\" attribute. (e.g. `tf.keras.layers.LSTM` in",
"# TF2 produces a CuDNN-based RNN for GPU).",
"# This function suppose to inline all functions calls, but \"api_implements\"",
"# prevents this from happening. Removing the attribute solves the problem.",
"# To learn more about \"api_implements\", see:",
"# tensorflow/core/grappler/optimizers/implementation_selector.h",
"for",
"function",
"in",
"graph_def",
".",
"library",
".",
"function",
":",
"if",
"\"api_implements\"",
"in",
"function",
".",
"attr",
":",
"del",
"function",
".",
"attr",
"[",
"\"api_implements\"",
"]",
"meta_graph",
"=",
"export_meta_graph",
"(",
"graph_def",
"=",
"graph_def",
",",
"graph",
"=",
"func",
".",
"graph",
")",
"# Clear the initializer_name for the variables collections, since they are not",
"# needed after saved to saved_model.",
"for",
"name",
"in",
"[",
"\"variables\"",
",",
"\"model_variables\"",
",",
"\"trainable_variables\"",
",",
"\"local_variables\"",
"]",
":",
"raw_list",
"=",
"[",
"]",
"for",
"raw",
"in",
"meta_graph",
".",
"collection_def",
"[",
"\"variables\"",
"]",
".",
"bytes_list",
".",
"value",
":",
"variable",
"=",
"variable_pb2",
".",
"VariableDef",
"(",
")",
"variable",
".",
"ParseFromString",
"(",
"raw",
")",
"variable",
".",
"ClearField",
"(",
"\"initializer_name\"",
")",
"raw_list",
".",
"append",
"(",
"variable",
".",
"SerializeToString",
"(",
")",
")",
"meta_graph",
".",
"collection_def",
"[",
"name",
"]",
".",
"bytes_list",
".",
"value",
"[",
":",
"]",
"=",
"raw_list",
"# Add a collection 'train_op' so that Grappler knows the outputs.",
"fetch_collection",
"=",
"meta_graph_pb2",
".",
"CollectionDef",
"(",
")",
"for",
"array",
"in",
"func",
".",
"inputs",
"+",
"func",
".",
"outputs",
":",
"fetch_collection",
".",
"node_list",
".",
"value",
".",
"append",
"(",
"array",
".",
"name",
")",
"meta_graph",
".",
"collection_def",
"[",
"\"train_op\"",
"]",
".",
"CopyFrom",
"(",
"fetch_collection",
")",
"# Initialize RewriterConfig with everything disabled except function inlining.",
"config",
"=",
"config_pb2",
".",
"ConfigProto",
"(",
")",
"rewrite_options",
"=",
"config",
".",
"graph_options",
".",
"rewrite_options",
"rewrite_options",
".",
"min_graph_nodes",
"=",
"-",
"1",
"# do not skip small graphs",
"rewrite_options",
".",
"optimizers",
".",
"append",
"(",
"\"function\"",
")",
"return",
"tf_optimizer",
".",
"OptimizeGraph",
"(",
"config",
",",
"meta_graph",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/RNN/rnn_quantizer/tensorflow/tf_nndct/utils/convert_to_constants.py#L75-L130 | |
zhaoweicai/mscnn | 534bcac5710a579d60827f192035f7eef6d8c585 | 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",
"lineix_begin",
">=",
"len",
"(",
"lines",
")",
":",
"return",
"lineix_end",
"=",
"FindNextMultiLineCommentEnd",
"(",
"lines",
",",
"lineix_begin",
")",
"if",
"lineix_end",
">=",
"len",
"(",
"lines",
")",
":",
"error",
"(",
"filename",
",",
"lineix_begin",
"+",
"1",
",",
"'readability/multiline_comment'",
",",
"5",
",",
"'Could not find end of multi-line comment'",
")",
"return",
"RemoveMultiLineCommentsFromRange",
"(",
"lines",
",",
"lineix_begin",
",",
"lineix_end",
"+",
"1",
")",
"lineix",
"=",
"lineix_end",
"+",
"1"
] | https://github.com/zhaoweicai/mscnn/blob/534bcac5710a579d60827f192035f7eef6d8c585/scripts/cpp_lint.py#L1151-L1164 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | FWCore/ParameterSet/python/Config.py | python | Process.producers_ | (self) | return DictTypes.FixedKeysDict(self.__producers) | returns a dict of the producers that have been added to the Process | returns a dict of the producers that have been added to the Process | [
"returns",
"a",
"dict",
"of",
"the",
"producers",
"that",
"have",
"been",
"added",
"to",
"the",
"Process"
] | def producers_(self):
"""returns a dict of the producers that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__producers) | [
"def",
"producers_",
"(",
"self",
")",
":",
"return",
"DictTypes",
".",
"FixedKeysDict",
"(",
"self",
".",
"__producers",
")"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/FWCore/ParameterSet/python/Config.py#L199-L201 | |
libfive/libfive | ab5e354cf6fd992f80aaa9432c52683219515c8a | libfive/bind/python/libfive/stdlib/transforms.py | python | reflect_x | (t, x0=0) | return Shape(stdlib.reflect_x(
args[0].ptr,
args[1].ptr)) | Reflects a shape about the x origin or an optional offset | Reflects a shape about the x origin or an optional offset | [
"Reflects",
"a",
"shape",
"about",
"the",
"x",
"origin",
"or",
"an",
"optional",
"offset"
] | def reflect_x(t, x0=0):
""" Reflects a shape about the x origin or an optional offset
"""
args = [Shape.wrap(t), Shape.wrap(x0)]
return Shape(stdlib.reflect_x(
args[0].ptr,
args[1].ptr)) | [
"def",
"reflect_x",
"(",
"t",
",",
"x0",
"=",
"0",
")",
":",
"args",
"=",
"[",
"Shape",
".",
"wrap",
"(",
"t",
")",
",",
"Shape",
".",
"wrap",
"(",
"x0",
")",
"]",
"return",
"Shape",
"(",
"stdlib",
".",
"reflect_x",
"(",
"args",
"[",
"0",
"]",
".",
"ptr",
",",
"args",
"[",
"1",
"]",
".",
"ptr",
")",
")"
] | https://github.com/libfive/libfive/blob/ab5e354cf6fd992f80aaa9432c52683219515c8a/libfive/bind/python/libfive/stdlib/transforms.py#L29-L35 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | uCSIsOsmanya | (code) | return ret | Check whether the character is part of Osmanya UCS Block | Check whether the character is part of Osmanya UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"Osmanya",
"UCS",
"Block"
] | def uCSIsOsmanya(code):
"""Check whether the character is part of Osmanya UCS Block """
ret = libxml2mod.xmlUCSIsOsmanya(code)
return ret | [
"def",
"uCSIsOsmanya",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsOsmanya",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L2812-L2815 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/externals/joblib/memory.py | python | MemorizedFunc.__init__ | (self, func, cachedir, ignore=None, mmap_mode=None,
compress=False, verbose=1, timestamp=None) | Parameters
----------
func: callable
The function to decorate
cachedir: string
The path of the base directory to use as a data store
ignore: list or None
List of variable names to ignore.
mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
The memmapping mode used when loading from cache
numpy arrays. See numpy.load for the meaning of the
arguments.
compress : boolean, or integer
Whether to zip the stored data on disk. If an integer is
given, it should be between 1 and 9, and sets the amount
of compression. Note that compressed arrays cannot be
read by memmapping.
verbose: int, optional
Verbosity flag, controls the debug messages that are issued
as functions are evaluated. The higher, the more verbose
timestamp: float, optional
The reference time from which times in tracing messages
are reported. | Parameters
----------
func: callable
The function to decorate
cachedir: string
The path of the base directory to use as a data store
ignore: list or None
List of variable names to ignore.
mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
The memmapping mode used when loading from cache
numpy arrays. See numpy.load for the meaning of the
arguments.
compress : boolean, or integer
Whether to zip the stored data on disk. If an integer is
given, it should be between 1 and 9, and sets the amount
of compression. Note that compressed arrays cannot be
read by memmapping.
verbose: int, optional
Verbosity flag, controls the debug messages that are issued
as functions are evaluated. The higher, the more verbose
timestamp: float, optional
The reference time from which times in tracing messages
are reported. | [
"Parameters",
"----------",
"func",
":",
"callable",
"The",
"function",
"to",
"decorate",
"cachedir",
":",
"string",
"The",
"path",
"of",
"the",
"base",
"directory",
"to",
"use",
"as",
"a",
"data",
"store",
"ignore",
":",
"list",
"or",
"None",
"List",
"of",
"variable",
"names",
"to",
"ignore",
".",
"mmap_mode",
":",
"{",
"None",
"r",
"+",
"r",
"w",
"+",
"c",
"}",
"optional",
"The",
"memmapping",
"mode",
"used",
"when",
"loading",
"from",
"cache",
"numpy",
"arrays",
".",
"See",
"numpy",
".",
"load",
"for",
"the",
"meaning",
"of",
"the",
"arguments",
".",
"compress",
":",
"boolean",
"or",
"integer",
"Whether",
"to",
"zip",
"the",
"stored",
"data",
"on",
"disk",
".",
"If",
"an",
"integer",
"is",
"given",
"it",
"should",
"be",
"between",
"1",
"and",
"9",
"and",
"sets",
"the",
"amount",
"of",
"compression",
".",
"Note",
"that",
"compressed",
"arrays",
"cannot",
"be",
"read",
"by",
"memmapping",
".",
"verbose",
":",
"int",
"optional",
"Verbosity",
"flag",
"controls",
"the",
"debug",
"messages",
"that",
"are",
"issued",
"as",
"functions",
"are",
"evaluated",
".",
"The",
"higher",
"the",
"more",
"verbose",
"timestamp",
":",
"float",
"optional",
"The",
"reference",
"time",
"from",
"which",
"times",
"in",
"tracing",
"messages",
"are",
"reported",
"."
] | def __init__(self, func, cachedir, ignore=None, mmap_mode=None,
compress=False, verbose=1, timestamp=None):
"""
Parameters
----------
func: callable
The function to decorate
cachedir: string
The path of the base directory to use as a data store
ignore: list or None
List of variable names to ignore.
mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
The memmapping mode used when loading from cache
numpy arrays. See numpy.load for the meaning of the
arguments.
compress : boolean, or integer
Whether to zip the stored data on disk. If an integer is
given, it should be between 1 and 9, and sets the amount
of compression. Note that compressed arrays cannot be
read by memmapping.
verbose: int, optional
Verbosity flag, controls the debug messages that are issued
as functions are evaluated. The higher, the more verbose
timestamp: float, optional
The reference time from which times in tracing messages
are reported.
"""
Logger.__init__(self)
self.mmap_mode = mmap_mode
self.func = func
if ignore is None:
ignore = []
self.ignore = ignore
self._verbose = verbose
self.cachedir = cachedir
self.compress = compress
if compress and self.mmap_mode is not None:
warnings.warn('Compressed results cannot be memmapped',
stacklevel=2)
if timestamp is None:
timestamp = time.time()
self.timestamp = timestamp
mkdirp(self.cachedir)
try:
functools.update_wrapper(self, func)
except:
" Objects like ufunc don't like that "
if inspect.isfunction(func):
doc = pydoc.TextDoc().document(func)
# Remove blank line
doc = doc.replace('\n', '\n\n', 1)
# Strip backspace-overprints for compatibility with autodoc
doc = re.sub('\x08.', '', doc)
else:
# Pydoc does a poor job on other objects
doc = func.__doc__
self.__doc__ = 'Memoized version of %s' % doc | [
"def",
"__init__",
"(",
"self",
",",
"func",
",",
"cachedir",
",",
"ignore",
"=",
"None",
",",
"mmap_mode",
"=",
"None",
",",
"compress",
"=",
"False",
",",
"verbose",
"=",
"1",
",",
"timestamp",
"=",
"None",
")",
":",
"Logger",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"mmap_mode",
"=",
"mmap_mode",
"self",
".",
"func",
"=",
"func",
"if",
"ignore",
"is",
"None",
":",
"ignore",
"=",
"[",
"]",
"self",
".",
"ignore",
"=",
"ignore",
"self",
".",
"_verbose",
"=",
"verbose",
"self",
".",
"cachedir",
"=",
"cachedir",
"self",
".",
"compress",
"=",
"compress",
"if",
"compress",
"and",
"self",
".",
"mmap_mode",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"'Compressed results cannot be memmapped'",
",",
"stacklevel",
"=",
"2",
")",
"if",
"timestamp",
"is",
"None",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"timestamp",
"=",
"timestamp",
"mkdirp",
"(",
"self",
".",
"cachedir",
")",
"try",
":",
"functools",
".",
"update_wrapper",
"(",
"self",
",",
"func",
")",
"except",
":",
"\" Objects like ufunc don't like that \"",
"if",
"inspect",
".",
"isfunction",
"(",
"func",
")",
":",
"doc",
"=",
"pydoc",
".",
"TextDoc",
"(",
")",
".",
"document",
"(",
"func",
")",
"# Remove blank line",
"doc",
"=",
"doc",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n\\n'",
",",
"1",
")",
"# Strip backspace-overprints for compatibility with autodoc",
"doc",
"=",
"re",
".",
"sub",
"(",
"'\\x08.'",
",",
"''",
",",
"doc",
")",
"else",
":",
"# Pydoc does a poor job on other objects",
"doc",
"=",
"func",
".",
"__doc__",
"self",
".",
"__doc__",
"=",
"'Memoized version of %s'",
"%",
"doc"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/externals/joblib/memory.py#L343-L400 | ||
Lavender105/DFF | 152397cec4a3dac2aa86e92a65cc27e6c8016ab9 | pytorch-encoding/encoding/functions/encoding.py | python | pairwise_cosine | (X, C, normalize=False) | return torch.matmul(X, C.t()) | r"""Pairwise Cosine Similarity or Dot-product Similarity
Shape:
- Input: :math:`X\in\mathcal{R}^{B\times N\times D}`
:math:`C\in\mathcal{R}^{K\times D}` :math:`S\in \mathcal{R}^K`
(where :math:`B` is batch, :math:`N` is total number of features,
:math:`K` is number is codewords, :math:`D` is feature dimensions.)
- Output: :math:`E\in\mathcal{R}^{B\times N\times K}` | r"""Pairwise Cosine Similarity or Dot-product Similarity
Shape:
- Input: :math:`X\in\mathcal{R}^{B\times N\times D}`
:math:`C\in\mathcal{R}^{K\times D}` :math:`S\in \mathcal{R}^K`
(where :math:`B` is batch, :math:`N` is total number of features,
:math:`K` is number is codewords, :math:`D` is feature dimensions.)
- Output: :math:`E\in\mathcal{R}^{B\times N\times K}` | [
"r",
"Pairwise",
"Cosine",
"Similarity",
"or",
"Dot",
"-",
"product",
"Similarity",
"Shape",
":",
"-",
"Input",
":",
":",
"math",
":",
"X",
"\\",
"in",
"\\",
"mathcal",
"{",
"R",
"}",
"^",
"{",
"B",
"\\",
"times",
"N",
"\\",
"times",
"D",
"}",
":",
"math",
":",
"C",
"\\",
"in",
"\\",
"mathcal",
"{",
"R",
"}",
"^",
"{",
"K",
"\\",
"times",
"D",
"}",
":",
"math",
":",
"S",
"\\",
"in",
"\\",
"mathcal",
"{",
"R",
"}",
"^K",
"(",
"where",
":",
"math",
":",
"B",
"is",
"batch",
":",
"math",
":",
"N",
"is",
"total",
"number",
"of",
"features",
":",
"math",
":",
"K",
"is",
"number",
"is",
"codewords",
":",
"math",
":",
"D",
"is",
"feature",
"dimensions",
".",
")",
"-",
"Output",
":",
":",
"math",
":",
"E",
"\\",
"in",
"\\",
"mathcal",
"{",
"R",
"}",
"^",
"{",
"B",
"\\",
"times",
"N",
"\\",
"times",
"K",
"}"
] | def pairwise_cosine(X, C, normalize=False):
r"""Pairwise Cosine Similarity or Dot-product Similarity
Shape:
- Input: :math:`X\in\mathcal{R}^{B\times N\times D}`
:math:`C\in\mathcal{R}^{K\times D}` :math:`S\in \mathcal{R}^K`
(where :math:`B` is batch, :math:`N` is total number of features,
:math:`K` is number is codewords, :math:`D` is feature dimensions.)
- Output: :math:`E\in\mathcal{R}^{B\times N\times K}`
"""
if normalize:
X = F.normalize(X, dim=2, eps=1e-8)
C = F.normalize(C, dim=1, eps=1e-8)
return torch.matmul(X, C.t()) | [
"def",
"pairwise_cosine",
"(",
"X",
",",
"C",
",",
"normalize",
"=",
"False",
")",
":",
"if",
"normalize",
":",
"X",
"=",
"F",
".",
"normalize",
"(",
"X",
",",
"dim",
"=",
"2",
",",
"eps",
"=",
"1e-8",
")",
"C",
"=",
"F",
".",
"normalize",
"(",
"C",
",",
"dim",
"=",
"1",
",",
"eps",
"=",
"1e-8",
")",
"return",
"torch",
".",
"matmul",
"(",
"X",
",",
"C",
".",
"t",
"(",
")",
")"
] | https://github.com/Lavender105/DFF/blob/152397cec4a3dac2aa86e92a65cc27e6c8016ab9/pytorch-encoding/encoding/functions/encoding.py#L98-L110 | |
maidsafe-archive/MaidSafe | defd65e1c8cfb6a1cbdeaaa0eee31d065421792d | tools/cpplint.py | python | FindNextMultiLineCommentStart | (lines, lineix) | return len(lines) | Find the beginning marker for a multiline comment. | Find the beginning marker for a multiline comment. | [
"Find",
"the",
"beginning",
"marker",
"for",
"a",
"multiline",
"comment",
"."
] | def FindNextMultiLineCommentStart(lines, lineix):
"""Find the beginning marker for a multiline comment."""
while lineix < len(lines):
if lines[lineix].strip().startswith('/*'):
# Only return this marker if the comment goes beyond this line
if lines[lineix].strip().find('*/', 2) < 0:
return lineix
lineix += 1
return len(lines) | [
"def",
"FindNextMultiLineCommentStart",
"(",
"lines",
",",
"lineix",
")",
":",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'/*'",
")",
":",
"# Only return this marker if the comment goes beyond this line",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"find",
"(",
"'*/'",
",",
"2",
")",
"<",
"0",
":",
"return",
"lineix",
"lineix",
"+=",
"1",
"return",
"len",
"(",
"lines",
")"
] | https://github.com/maidsafe-archive/MaidSafe/blob/defd65e1c8cfb6a1cbdeaaa0eee31d065421792d/tools/cpplint.py#L929-L937 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/interpolate/fitpack2.py | python | BivariateSpline.integral | (self, xa, xb, ya, yb) | return dfitpack.dblint(tx,ty,c,kx,ky,xa,xb,ya,yb) | Evaluate the integral of the spline over area [xa,xb] x [ya,yb].
Parameters
----------
xa, xb : float
The end-points of the x integration interval.
ya, yb : float
The end-points of the y integration interval.
Returns
-------
integ : float
The value of the resulting integral. | Evaluate the integral of the spline over area [xa,xb] x [ya,yb]. | [
"Evaluate",
"the",
"integral",
"of",
"the",
"spline",
"over",
"area",
"[",
"xa",
"xb",
"]",
"x",
"[",
"ya",
"yb",
"]",
"."
] | def integral(self, xa, xb, ya, yb):
"""
Evaluate the integral of the spline over area [xa,xb] x [ya,yb].
Parameters
----------
xa, xb : float
The end-points of the x integration interval.
ya, yb : float
The end-points of the y integration interval.
Returns
-------
integ : float
The value of the resulting integral.
"""
tx,ty,c = self.tck[:3]
kx,ky = self.degrees
return dfitpack.dblint(tx,ty,c,kx,ky,xa,xb,ya,yb) | [
"def",
"integral",
"(",
"self",
",",
"xa",
",",
"xb",
",",
"ya",
",",
"yb",
")",
":",
"tx",
",",
"ty",
",",
"c",
"=",
"self",
".",
"tck",
"[",
":",
"3",
"]",
"kx",
",",
"ky",
"=",
"self",
".",
"degrees",
"return",
"dfitpack",
".",
"dblint",
"(",
"tx",
",",
"ty",
",",
"c",
",",
"kx",
",",
"ky",
",",
"xa",
",",
"xb",
",",
"ya",
",",
"yb",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/interpolate/fitpack2.py#L971-L990 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/tools/grit/grit/node/base.py | python | Node.ExpandVariables | (self) | return False | Whether we need to expand variables on a given node. | Whether we need to expand variables on a given node. | [
"Whether",
"we",
"need",
"to",
"expand",
"variables",
"on",
"a",
"given",
"node",
"."
] | def ExpandVariables(self):
'''Whether we need to expand variables on a given node.'''
return False | [
"def",
"ExpandVariables",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/node/base.py#L619-L621 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/io/resource.py | python | visual_edit_types | () | return ['Config','Configs','Trajectory','Vector3','Point','RigidTransform','Rotation','WorldModel'] | Returns types that can be visually edited | Returns types that can be visually edited | [
"Returns",
"types",
"that",
"can",
"be",
"visually",
"edited"
] | def visual_edit_types():
"""Returns types that can be visually edited"""
return ['Config','Configs','Trajectory','Vector3','Point','RigidTransform','Rotation','WorldModel'] | [
"def",
"visual_edit_types",
"(",
")",
":",
"return",
"[",
"'Config'",
",",
"'Configs'",
",",
"'Trajectory'",
",",
"'Vector3'",
",",
"'Point'",
",",
"'RigidTransform'",
",",
"'Rotation'",
",",
"'WorldModel'",
"]"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/io/resource.py#L110-L112 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/base_subprocess.py | python | BaseSubprocessTransport._wait | (self) | return await waiter | Wait until the process exit and return the process return code.
This method is a coroutine. | Wait until the process exit and return the process return code. | [
"Wait",
"until",
"the",
"process",
"exit",
"and",
"return",
"the",
"process",
"return",
"code",
"."
] | async def _wait(self):
"""Wait until the process exit and return the process return code.
This method is a coroutine."""
if self._returncode is not None:
return self._returncode
waiter = self._loop.create_future()
self._exit_waiters.append(waiter)
return await waiter | [
"async",
"def",
"_wait",
"(",
"self",
")",
":",
"if",
"self",
".",
"_returncode",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_returncode",
"waiter",
"=",
"self",
".",
"_loop",
".",
"create_future",
"(",
")",
"self",
".",
"_exit_waiters",
".",
"append",
"(",
"waiter",
")",
"return",
"await",
"waiter"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/asyncio/base_subprocess.py#L225-L234 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/framework/auto_control_deps.py | python | collective_manager_ids_from_op | (op) | return [] | Returns CollectiveManager ID from the op if one exists, else None.
CollectiveManager adds collective and no_op operations tagged with an ID,
unique to the manager object. This function extracts that ID, or None, if the
node was not generated by a CollectiveManager.
Args:
op: `Operation` to get the collective manager ID from.
Returns:
List of CollectiveManager IDs used by the op. | Returns CollectiveManager ID from the op if one exists, else None. | [
"Returns",
"CollectiveManager",
"ID",
"from",
"the",
"op",
"if",
"one",
"exists",
"else",
"None",
"."
] | def collective_manager_ids_from_op(op):
"""Returns CollectiveManager ID from the op if one exists, else None.
CollectiveManager adds collective and no_op operations tagged with an ID,
unique to the manager object. This function extracts that ID, or None, if the
node was not generated by a CollectiveManager.
Args:
op: `Operation` to get the collective manager ID from.
Returns:
List of CollectiveManager IDs used by the op.
"""
if op.type == "CollectiveReduce":
try:
return [op.get_attr("_collective_manager_id")]
except ValueError:
pass
elif op.type == "StatefulPartitionedCall":
try:
return op.get_attr(utils.COLLECTIVE_MANAGER_IDS)
except ValueError:
pass
return [] | [
"def",
"collective_manager_ids_from_op",
"(",
"op",
")",
":",
"if",
"op",
".",
"type",
"==",
"\"CollectiveReduce\"",
":",
"try",
":",
"return",
"[",
"op",
".",
"get_attr",
"(",
"\"_collective_manager_id\"",
")",
"]",
"except",
"ValueError",
":",
"pass",
"elif",
"op",
".",
"type",
"==",
"\"StatefulPartitionedCall\"",
":",
"try",
":",
"return",
"op",
".",
"get_attr",
"(",
"utils",
".",
"COLLECTIVE_MANAGER_IDS",
")",
"except",
"ValueError",
":",
"pass",
"return",
"[",
"]"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/auto_control_deps.py#L157-L180 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/distutils/fancy_getopt.py | python | FancyGetopt.set_aliases | (self, alias) | Set the aliases for this option parser. | Set the aliases for this option parser. | [
"Set",
"the",
"aliases",
"for",
"this",
"option",
"parser",
"."
] | def set_aliases(self, alias):
"""Set the aliases for this option parser."""
self._check_alias_dict(alias, "alias")
self.alias = alias | [
"def",
"set_aliases",
"(",
"self",
",",
"alias",
")",
":",
"self",
".",
"_check_alias_dict",
"(",
"alias",
",",
"\"alias\"",
")",
"self",
".",
"alias",
"=",
"alias"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/fancy_getopt.py#L120-L123 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/cluster/vq.py | python | _py_vq_1d | (obs, code_book) | return code, sqrt(min_dist) | Python version of vq algorithm for rank 1 only.
Parameters
----------
obs : ndarray
Expects a rank 1 array. Each item is one observation.
code_book : ndarray
Code book to use. Same format than obs. Should rank 1 too.
Returns
-------
code : ndarray
code[i] gives the label of the ith obversation, that its code is
code_book[code[i]].
mind_dist : ndarray
min_dist[i] gives the distance between the ith observation and its
corresponding code. | Python version of vq algorithm for rank 1 only. | [
"Python",
"version",
"of",
"vq",
"algorithm",
"for",
"rank",
"1",
"only",
"."
] | def _py_vq_1d(obs, code_book):
""" Python version of vq algorithm for rank 1 only.
Parameters
----------
obs : ndarray
Expects a rank 1 array. Each item is one observation.
code_book : ndarray
Code book to use. Same format than obs. Should rank 1 too.
Returns
-------
code : ndarray
code[i] gives the label of the ith obversation, that its code is
code_book[code[i]].
mind_dist : ndarray
min_dist[i] gives the distance between the ith observation and its
corresponding code.
"""
raise RuntimeError("_py_vq_1d buggy, do not use rank 1 arrays for now")
n = obs.size
nc = code_book.size
dist = np.zeros((n, nc))
for i in range(nc):
dist[:, i] = np.sum(obs - code_book[i])
print(dist)
code = argmin(dist)
min_dist = dist[code]
return code, sqrt(min_dist) | [
"def",
"_py_vq_1d",
"(",
"obs",
",",
"code_book",
")",
":",
"raise",
"RuntimeError",
"(",
"\"_py_vq_1d buggy, do not use rank 1 arrays for now\"",
")",
"n",
"=",
"obs",
".",
"size",
"nc",
"=",
"code_book",
".",
"size",
"dist",
"=",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"nc",
")",
")",
"for",
"i",
"in",
"range",
"(",
"nc",
")",
":",
"dist",
"[",
":",
",",
"i",
"]",
"=",
"np",
".",
"sum",
"(",
"obs",
"-",
"code_book",
"[",
"i",
"]",
")",
"print",
"(",
"dist",
")",
"code",
"=",
"argmin",
"(",
"dist",
")",
"min_dist",
"=",
"dist",
"[",
"code",
"]",
"return",
"code",
",",
"sqrt",
"(",
"min_dist",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/cluster/vq.py#L298-L328 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py | python | reshape | (a, new_shape, order='C') | Returns an array containing the same data with a new shape.
Refer to `MaskedArray.reshape` for full documentation.
See Also
--------
MaskedArray.reshape : equivalent function | Returns an array containing the same data with a new shape. | [
"Returns",
"an",
"array",
"containing",
"the",
"same",
"data",
"with",
"a",
"new",
"shape",
"."
] | def reshape(a, new_shape, order='C'):
"""
Returns an array containing the same data with a new shape.
Refer to `MaskedArray.reshape` for full documentation.
See Also
--------
MaskedArray.reshape : equivalent function
"""
# We can't use 'frommethod', it whine about some parameters. Dmmit.
try:
return a.reshape(new_shape, order=order)
except AttributeError:
_tmp = narray(a, copy=False).reshape(new_shape, order=order)
return _tmp.view(MaskedArray) | [
"def",
"reshape",
"(",
"a",
",",
"new_shape",
",",
"order",
"=",
"'C'",
")",
":",
"# We can't use 'frommethod', it whine about some parameters. Dmmit.",
"try",
":",
"return",
"a",
".",
"reshape",
"(",
"new_shape",
",",
"order",
"=",
"order",
")",
"except",
"AttributeError",
":",
"_tmp",
"=",
"narray",
"(",
"a",
",",
"copy",
"=",
"False",
")",
".",
"reshape",
"(",
"new_shape",
",",
"order",
"=",
"order",
")",
"return",
"_tmp",
".",
"view",
"(",
"MaskedArray",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py#L7043-L7059 | ||
etotheipi/BitcoinArmory | 2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98 | qtdialogs.py | python | excludeChange | (outputPairs, wlt) | return nonChangeOutputPairs | NOTE: this method works ONLY because we always generate a new address
whenever creating a change-output, which means it must have a
higher chainIndex than all other addresses. If you did something
creative with this tx, this may not actually work. | NOTE: this method works ONLY because we always generate a new address
whenever creating a change-output, which means it must have a
higher chainIndex than all other addresses. If you did something
creative with this tx, this may not actually work. | [
"NOTE",
":",
"this",
"method",
"works",
"ONLY",
"because",
"we",
"always",
"generate",
"a",
"new",
"address",
"whenever",
"creating",
"a",
"change",
"-",
"output",
"which",
"means",
"it",
"must",
"have",
"a",
"higher",
"chainIndex",
"than",
"all",
"other",
"addresses",
".",
"If",
"you",
"did",
"something",
"creative",
"with",
"this",
"tx",
"this",
"may",
"not",
"actually",
"work",
"."
] | def excludeChange(outputPairs, wlt):
"""
NOTE: this method works ONLY because we always generate a new address
whenever creating a change-output, which means it must have a
higher chainIndex than all other addresses. If you did something
creative with this tx, this may not actually work.
"""
maxChainIndex = -5
nonChangeOutputPairs = []
currentMaxChainPair = None
for script,val in outputPairs:
scrType = getTxOutScriptType(script)
addr = ''
if scrType in CPP_TXOUT_HAS_ADDRSTR:
scrAddr = script_to_scrAddr(script)
addr = wlt.getAddrByHash160(scrAddr_to_hash160(scrAddr)[1])
# this logic excludes the pair with the maximum chainIndex from the
# returned list
if addr:
if addr.chainIndex > maxChainIndex:
maxChainIndex = addr.chainIndex
if currentMaxChainPair:
nonChangeOutputPairs.append(currentMaxChainPair)
currentMaxChainPair = [script,val]
else:
nonChangeOutputPairs.append([script,val])
return nonChangeOutputPairs | [
"def",
"excludeChange",
"(",
"outputPairs",
",",
"wlt",
")",
":",
"maxChainIndex",
"=",
"-",
"5",
"nonChangeOutputPairs",
"=",
"[",
"]",
"currentMaxChainPair",
"=",
"None",
"for",
"script",
",",
"val",
"in",
"outputPairs",
":",
"scrType",
"=",
"getTxOutScriptType",
"(",
"script",
")",
"addr",
"=",
"''",
"if",
"scrType",
"in",
"CPP_TXOUT_HAS_ADDRSTR",
":",
"scrAddr",
"=",
"script_to_scrAddr",
"(",
"script",
")",
"addr",
"=",
"wlt",
".",
"getAddrByHash160",
"(",
"scrAddr_to_hash160",
"(",
"scrAddr",
")",
"[",
"1",
"]",
")",
"# this logic excludes the pair with the maximum chainIndex from the",
"# returned list",
"if",
"addr",
":",
"if",
"addr",
".",
"chainIndex",
">",
"maxChainIndex",
":",
"maxChainIndex",
"=",
"addr",
".",
"chainIndex",
"if",
"currentMaxChainPair",
":",
"nonChangeOutputPairs",
".",
"append",
"(",
"currentMaxChainPair",
")",
"currentMaxChainPair",
"=",
"[",
"script",
",",
"val",
"]",
"else",
":",
"nonChangeOutputPairs",
".",
"append",
"(",
"[",
"script",
",",
"val",
"]",
")",
"return",
"nonChangeOutputPairs"
] | https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/qtdialogs.py#L4828-L4855 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/manifest.py | python | Manifest._exclude_pattern | (self, pattern, anchor=True, prefix=None,
is_regex=False) | return found | Remove strings (presumably filenames) from 'files' that match
'pattern'.
Other parameters are the same as for 'include_pattern()', above.
The list 'self.files' is modified in place. Return True if files are
found.
This API is public to allow e.g. exclusion of SCM subdirs, e.g. when
packaging source distributions | Remove strings (presumably filenames) from 'files' that match | [
"Remove",
"strings",
"(",
"presumably",
"filenames",
")",
"from",
"files",
"that",
"match"
] | def _exclude_pattern(self, pattern, anchor=True, prefix=None,
is_regex=False):
"""Remove strings (presumably filenames) from 'files' that match
'pattern'.
Other parameters are the same as for 'include_pattern()', above.
The list 'self.files' is modified in place. Return True if files are
found.
This API is public to allow e.g. exclusion of SCM subdirs, e.g. when
packaging source distributions
"""
found = False
pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
for f in list(self.files):
if pattern_re.search(f):
self.files.remove(f)
found = True
return found | [
"def",
"_exclude_pattern",
"(",
"self",
",",
"pattern",
",",
"anchor",
"=",
"True",
",",
"prefix",
"=",
"None",
",",
"is_regex",
"=",
"False",
")",
":",
"found",
"=",
"False",
"pattern_re",
"=",
"self",
".",
"_translate_pattern",
"(",
"pattern",
",",
"anchor",
",",
"prefix",
",",
"is_regex",
")",
"for",
"f",
"in",
"list",
"(",
"self",
".",
"files",
")",
":",
"if",
"pattern_re",
".",
"search",
"(",
"f",
")",
":",
"self",
".",
"files",
".",
"remove",
"(",
"f",
")",
"found",
"=",
"True",
"return",
"found"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/manifest.py#L593-L629 | |
Harick1/caffe-yolo | eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3 | python/caffe/draw.py | python | choose_color_by_layertype | (layertype) | return color | Define colors for nodes based on the layer type. | Define colors for nodes based on the layer type. | [
"Define",
"colors",
"for",
"nodes",
"based",
"on",
"the",
"layer",
"type",
"."
] | def choose_color_by_layertype(layertype):
"""Define colors for nodes based on the layer type.
"""
color = '#6495ED' # Default
if layertype == 'Convolution' or layertype == 'Deconvolution':
color = '#FF5050'
elif layertype == 'Pooling':
color = '#FF9900'
elif layertype == 'InnerProduct':
color = '#CC33FF'
return color | [
"def",
"choose_color_by_layertype",
"(",
"layertype",
")",
":",
"color",
"=",
"'#6495ED'",
"# Default",
"if",
"layertype",
"==",
"'Convolution'",
"or",
"layertype",
"==",
"'Deconvolution'",
":",
"color",
"=",
"'#FF5050'",
"elif",
"layertype",
"==",
"'Pooling'",
":",
"color",
"=",
"'#FF9900'",
"elif",
"layertype",
"==",
"'InnerProduct'",
":",
"color",
"=",
"'#CC33FF'",
"return",
"color"
] | https://github.com/Harick1/caffe-yolo/blob/eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3/python/caffe/draw.py#L117-L127 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/operations/install/wheel.py | python | rehash | (path, blocksize=1 << 20) | return (digest, str(length)) | Return (encoded_digest, length) for path using hashlib.sha256() | Return (encoded_digest, length) for path using hashlib.sha256() | [
"Return",
"(",
"encoded_digest",
"length",
")",
"for",
"path",
"using",
"hashlib",
".",
"sha256",
"()"
] | def rehash(path, blocksize=1 << 20):
# type: (str, int) -> Tuple[str, str]
"""Return (encoded_digest, length) for path using hashlib.sha256()"""
h, length = hash_file(path, blocksize)
digest = 'sha256=' + urlsafe_b64encode(
h.digest()
).decode('latin1').rstrip('=')
return (digest, str(length)) | [
"def",
"rehash",
"(",
"path",
",",
"blocksize",
"=",
"1",
"<<",
"20",
")",
":",
"# type: (str, int) -> Tuple[str, str]",
"h",
",",
"length",
"=",
"hash_file",
"(",
"path",
",",
"blocksize",
")",
"digest",
"=",
"'sha256='",
"+",
"urlsafe_b64encode",
"(",
"h",
".",
"digest",
"(",
")",
")",
".",
"decode",
"(",
"'latin1'",
")",
".",
"rstrip",
"(",
"'='",
")",
"return",
"(",
"digest",
",",
"str",
"(",
"length",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/operations/install/wheel.py#L86-L93 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py2/sklearn/linear_model/omp.py | python | OrthogonalMatchingPursuit.fit | (self, X, y) | return self | Fit the model using X, y as training data.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data.
y : array-like, shape (n_samples,) or (n_samples, n_targets)
Target values.
Returns
-------
self : object
returns an instance of self. | Fit the model using X, y as training data. | [
"Fit",
"the",
"model",
"using",
"X",
"y",
"as",
"training",
"data",
"."
] | def fit(self, X, y):
"""Fit the model using X, y as training data.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data.
y : array-like, shape (n_samples,) or (n_samples, n_targets)
Target values.
Returns
-------
self : object
returns an instance of self.
"""
X, y = check_X_y(X, y, multi_output=True, y_numeric=True)
n_features = X.shape[1]
X, y, X_offset, y_offset, X_scale, Gram, Xy = \
_pre_fit(X, y, None, self.precompute, self.normalize,
self.fit_intercept, copy=True)
if y.ndim == 1:
y = y[:, np.newaxis]
if self.n_nonzero_coefs is None and self.tol is None:
# default for n_nonzero_coefs is 0.1 * n_features
# but at least one.
self.n_nonzero_coefs_ = max(int(0.1 * n_features), 1)
else:
self.n_nonzero_coefs_ = self.n_nonzero_coefs
if Gram is False:
coef_, self.n_iter_ = orthogonal_mp(
X, y, self.n_nonzero_coefs_, self.tol,
precompute=False, copy_X=True,
return_n_iter=True)
else:
norms_sq = np.sum(y ** 2, axis=0) if self.tol is not None else None
coef_, self.n_iter_ = orthogonal_mp_gram(
Gram, Xy=Xy, n_nonzero_coefs=self.n_nonzero_coefs_,
tol=self.tol, norms_squared=norms_sq,
copy_Gram=True, copy_Xy=True,
return_n_iter=True)
self.coef_ = coef_.T
self._set_intercept(X_offset, y_offset, X_scale)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"X",
",",
"y",
"=",
"check_X_y",
"(",
"X",
",",
"y",
",",
"multi_output",
"=",
"True",
",",
"y_numeric",
"=",
"True",
")",
"n_features",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"X",
",",
"y",
",",
"X_offset",
",",
"y_offset",
",",
"X_scale",
",",
"Gram",
",",
"Xy",
"=",
"_pre_fit",
"(",
"X",
",",
"y",
",",
"None",
",",
"self",
".",
"precompute",
",",
"self",
".",
"normalize",
",",
"self",
".",
"fit_intercept",
",",
"copy",
"=",
"True",
")",
"if",
"y",
".",
"ndim",
"==",
"1",
":",
"y",
"=",
"y",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"if",
"self",
".",
"n_nonzero_coefs",
"is",
"None",
"and",
"self",
".",
"tol",
"is",
"None",
":",
"# default for n_nonzero_coefs is 0.1 * n_features",
"# but at least one.",
"self",
".",
"n_nonzero_coefs_",
"=",
"max",
"(",
"int",
"(",
"0.1",
"*",
"n_features",
")",
",",
"1",
")",
"else",
":",
"self",
".",
"n_nonzero_coefs_",
"=",
"self",
".",
"n_nonzero_coefs",
"if",
"Gram",
"is",
"False",
":",
"coef_",
",",
"self",
".",
"n_iter_",
"=",
"orthogonal_mp",
"(",
"X",
",",
"y",
",",
"self",
".",
"n_nonzero_coefs_",
",",
"self",
".",
"tol",
",",
"precompute",
"=",
"False",
",",
"copy_X",
"=",
"True",
",",
"return_n_iter",
"=",
"True",
")",
"else",
":",
"norms_sq",
"=",
"np",
".",
"sum",
"(",
"y",
"**",
"2",
",",
"axis",
"=",
"0",
")",
"if",
"self",
".",
"tol",
"is",
"not",
"None",
"else",
"None",
"coef_",
",",
"self",
".",
"n_iter_",
"=",
"orthogonal_mp_gram",
"(",
"Gram",
",",
"Xy",
"=",
"Xy",
",",
"n_nonzero_coefs",
"=",
"self",
".",
"n_nonzero_coefs_",
",",
"tol",
"=",
"self",
".",
"tol",
",",
"norms_squared",
"=",
"norms_sq",
",",
"copy_Gram",
"=",
"True",
",",
"copy_Xy",
"=",
"True",
",",
"return_n_iter",
"=",
"True",
")",
"self",
".",
"coef_",
"=",
"coef_",
".",
"T",
"self",
".",
"_set_intercept",
"(",
"X_offset",
",",
"y_offset",
",",
"X_scale",
")",
"return",
"self"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/linear_model/omp.py#L619-L668 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/idl/idl/cpp_types.py | python | CppTypeBase.disable_xvalue | (self) | Return True if the type should have the xvalue getter disabled. | Return True if the type should have the xvalue getter disabled. | [
"Return",
"True",
"if",
"the",
"type",
"should",
"have",
"the",
"xvalue",
"getter",
"disabled",
"."
] | def disable_xvalue(self):
# type: () -> bool
"""Return True if the type should have the xvalue getter disabled."""
pass | [
"def",
"disable_xvalue",
"(",
"self",
")",
":",
"# type: () -> bool",
"pass"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/cpp_types.py#L119-L122 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/abc.py | python | PathEntryFinder.find_loader | (self, fullname) | Return (loader, namespace portion) for the path entry.
The fullname is a str. The namespace portion is a sequence of
path entries contributing to part of a namespace package. The
sequence may be empty. If loader is not None, the portion will
be ignored.
The portion will be discarded if another path entry finder
locates the module as a normal module or package.
This method is deprecated since Python 3.4 in favor of
finder.find_spec(). If find_spec() is provided than backwards-compatible
functionality is provided. | Return (loader, namespace portion) for the path entry. | [
"Return",
"(",
"loader",
"namespace",
"portion",
")",
"for",
"the",
"path",
"entry",
"."
] | def find_loader(self, fullname):
"""Return (loader, namespace portion) for the path entry.
The fullname is a str. The namespace portion is a sequence of
path entries contributing to part of a namespace package. The
sequence may be empty. If loader is not None, the portion will
be ignored.
The portion will be discarded if another path entry finder
locates the module as a normal module or package.
This method is deprecated since Python 3.4 in favor of
finder.find_spec(). If find_spec() is provided than backwards-compatible
functionality is provided.
"""
warnings.warn("PathEntryFinder.find_loader() is deprecated since Python "
"3.4 in favor of PathEntryFinder.find_spec() "
"(available since 3.4)",
DeprecationWarning,
stacklevel=2)
if not hasattr(self, 'find_spec'):
return None, []
found = self.find_spec(fullname)
if found is not None:
if not found.submodule_search_locations:
portions = []
else:
portions = found.submodule_search_locations
return found.loader, portions
else:
return None, [] | [
"def",
"find_loader",
"(",
"self",
",",
"fullname",
")",
":",
"warnings",
".",
"warn",
"(",
"\"PathEntryFinder.find_loader() is deprecated since Python \"",
"\"3.4 in favor of PathEntryFinder.find_spec() \"",
"\"(available since 3.4)\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'find_spec'",
")",
":",
"return",
"None",
",",
"[",
"]",
"found",
"=",
"self",
".",
"find_spec",
"(",
"fullname",
")",
"if",
"found",
"is",
"not",
"None",
":",
"if",
"not",
"found",
".",
"submodule_search_locations",
":",
"portions",
"=",
"[",
"]",
"else",
":",
"portions",
"=",
"found",
".",
"submodule_search_locations",
"return",
"found",
".",
"loader",
",",
"portions",
"else",
":",
"return",
"None",
",",
"[",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/abc.py#L94-L124 | ||
infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | elle/drake/src/drake/__init__.py | python | Version.__contains__ | (self, other) | return True | Whether a version includes another.
>>> Version(1, 2, 3) in Version(1, 2, 3)
True
>>> Version(1, 2, 2) in Version(1, 2, 3)
False
>>> Version(1, 2, 4) in Version(1, 2, 3)
False
>>> Version(1, 2) in Version(1, 2, 3)
False
>>> Version(1, 2, 3) in Version(1, 2)
True
>>> Version(1, 3) in Version(1, Range(2, 4))
True
>>> Version(1, 2, 3) in Version()
True | Whether a version includes another. | [
"Whether",
"a",
"version",
"includes",
"another",
"."
] | def __contains__(self, other):
"""Whether a version includes another.
>>> Version(1, 2, 3) in Version(1, 2, 3)
True
>>> Version(1, 2, 2) in Version(1, 2, 3)
False
>>> Version(1, 2, 4) in Version(1, 2, 3)
False
>>> Version(1, 2) in Version(1, 2, 3)
False
>>> Version(1, 2, 3) in Version(1, 2)
True
>>> Version(1, 3) in Version(1, Range(2, 4))
True
>>> Version(1, 2, 3) in Version()
True
"""
if self.__major is not None:
if other.__major is None or \
not other.__major in self.__major:
return False
if self.__minor is not None:
if other.__minor is None or \
not other.__minor in self.__minor:
return False
if self.__subminor is not None:
if other.__subminor is None or \
not other.__subminor in self.__subminor:
return False
return True | [
"def",
"__contains__",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"__major",
"is",
"not",
"None",
":",
"if",
"other",
".",
"__major",
"is",
"None",
"or",
"not",
"other",
".",
"__major",
"in",
"self",
".",
"__major",
":",
"return",
"False",
"if",
"self",
".",
"__minor",
"is",
"not",
"None",
":",
"if",
"other",
".",
"__minor",
"is",
"None",
"or",
"not",
"other",
".",
"__minor",
"in",
"self",
".",
"__minor",
":",
"return",
"False",
"if",
"self",
".",
"__subminor",
"is",
"not",
"None",
":",
"if",
"other",
".",
"__subminor",
"is",
"None",
"or",
"not",
"other",
".",
"__subminor",
"in",
"self",
".",
"__subminor",
":",
"return",
"False",
"return",
"True"
] | https://github.com/infinit/memo/blob/3a8394d0f647efe03ccb8bfe885a7279cb8be8a6/elle/drake/src/drake/__init__.py#L3871-L3901 | |
tiann/android-native-debug | 198903ed9346dc4a74327a63cb98d449b97d8047 | app/source/art/tools/cpplint.py | python | Error | (filename, linenum, category, confidence, message) | Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
False positives can be suppressed by the use of
"cpplint(category)" comments on the offending line. These are
parsed into _error_suppressions.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message. | Logs the fact we've found a lint error. | [
"Logs",
"the",
"fact",
"we",
"ve",
"found",
"a",
"lint",
"error",
"."
] | def Error(filename, linenum, category, confidence, message):
"""Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
False positives can be suppressed by the use of
"cpplint(category)" comments on the offending line. These are
parsed into _error_suppressions.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message.
"""
if _ShouldPrintError(category, confidence, linenum):
_cpplint_state.IncrementErrorCount(category)
if _cpplint_state.output_format == 'vs7':
sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
elif _cpplint_state.output_format == 'eclipse':
sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
else:
sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence)) | [
"def",
"Error",
"(",
"filename",
",",
"linenum",
",",
"category",
",",
"confidence",
",",
"message",
")",
":",
"if",
"_ShouldPrintError",
"(",
"category",
",",
"confidence",
",",
"linenum",
")",
":",
"_cpplint_state",
".",
"IncrementErrorCount",
"(",
"category",
")",
"if",
"_cpplint_state",
".",
"output_format",
"==",
"'vs7'",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s(%s): %s [%s] [%d]\\n'",
"%",
"(",
"filename",
",",
"linenum",
",",
"message",
",",
"category",
",",
"confidence",
")",
")",
"elif",
"_cpplint_state",
".",
"output_format",
"==",
"'eclipse'",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s:%s: warning: %s [%s] [%d]\\n'",
"%",
"(",
"filename",
",",
"linenum",
",",
"message",
",",
"category",
",",
"confidence",
")",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'%s:%s: %s [%s] [%d]\\n'",
"%",
"(",
"filename",
",",
"linenum",
",",
"message",
",",
"category",
",",
"confidence",
")",
")"
] | https://github.com/tiann/android-native-debug/blob/198903ed9346dc4a74327a63cb98d449b97d8047/app/source/art/tools/cpplint.py#L859-L891 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/painting-a-grid-with-three-different-colors.py | python | Solution.colorTheGrid | (self, m, n) | return reduce(lambda x,y: (x+y)%MOD,
matrix_mult([normalized_mask_cnt.values()],
matrix_expo([[normalized_adj[mask1][mask2]
for mask2 in normalized_mask_cnt.iterkeys()]
for mask1 in normalized_mask_cnt.iterkeys()], n-1))[0],
0) | :type m: int
:type n: int
:rtype: int | :type m: int
:type n: int
:rtype: int | [
":",
"type",
"m",
":",
"int",
":",
"type",
"n",
":",
"int",
":",
"rtype",
":",
"int"
] | def colorTheGrid(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
MOD = 10**9+7
def backtracking(mask1, mask2, basis, result): # Time: O(2^m), Space: O(2^m)
if not basis:
result.append(mask2)
return
for i in xrange(3):
if (mask1 == -1 or mask1//basis%3 != i) and (mask2 == -1 or mask2//(basis*3)%3 != i):
backtracking(mask1, mask2+i*basis if mask2 != -1 else i*basis, basis//3, result)
def matrix_mult(A, B):
ZB = zip(*B)
return [[sum(a*b % MOD for a, b in itertools.izip(row, col)) % MOD for col in ZB] for row in A]
def matrix_expo(A, K):
result = [[int(i == j) for j in xrange(len(A))] for i in xrange(len(A))]
while K:
if K % 2:
result = matrix_mult(result, A)
A = matrix_mult(A, A)
K /= 2
return result
def normalize(basis, mask):
norm = {}
result = 0
while basis:
x = mask//basis%3
if x not in norm:
norm[x] = len(norm)
result += norm[x]*basis
basis //= 3
return result
if m > n:
m, n = n, m
basis = 3**(m-1)
masks = []
backtracking(-1, -1, basis, masks) # Time: O(2^m), Space: O(2^m)
assert(len(masks) == 3 * 2**(m-1))
lookup = {mask:normalize(basis, mask) for mask in masks} # Time: O(m * 2^m)
normalized_mask_cnt = collections.Counter(lookup[mask] for mask in masks)
assert(len(normalized_mask_cnt) == 3*2**(m-1) // 3 // (2 if m >= 2 else 1)) # divided by 3 * 2 is since the first two colors are normalized to speed up performance
adj = collections.defaultdict(list)
for mask in normalized_mask_cnt.iterkeys(): # O(3^m) leaves which are all in depth m => Time: O(3^m), Space: O(3^m)
backtracking(mask, -1, basis, adj[mask])
normalized_adj = collections.defaultdict(lambda:collections.defaultdict(int))
for mask1, masks2 in adj.iteritems():
for mask2 in masks2:
normalized_adj[mask1][lookup[mask2]] = (normalized_adj[mask1][lookup[mask2]]+1)%MOD
# divided by 3 * 2 is since the first two colors in upper row are normalized to speed up performance,
# since first two colors in lower row which has at most 3 choices could be also normalized, lower bound is upper bound divided by at most 3
assert(2*3**m // 3 // 2 // 3 <= sum(len(v) for v in normalized_adj.itervalues()) <= 2*3**m // 3 // 2)
return reduce(lambda x,y: (x+y)%MOD,
matrix_mult([normalized_mask_cnt.values()],
matrix_expo([[normalized_adj[mask1][mask2]
for mask2 in normalized_mask_cnt.iterkeys()]
for mask1 in normalized_mask_cnt.iterkeys()], n-1))[0],
0) | [
"def",
"colorTheGrid",
"(",
"self",
",",
"m",
",",
"n",
")",
":",
"MOD",
"=",
"10",
"**",
"9",
"+",
"7",
"def",
"backtracking",
"(",
"mask1",
",",
"mask2",
",",
"basis",
",",
"result",
")",
":",
"# Time: O(2^m), Space: O(2^m)",
"if",
"not",
"basis",
":",
"result",
".",
"append",
"(",
"mask2",
")",
"return",
"for",
"i",
"in",
"xrange",
"(",
"3",
")",
":",
"if",
"(",
"mask1",
"==",
"-",
"1",
"or",
"mask1",
"//",
"basis",
"%",
"3",
"!=",
"i",
")",
"and",
"(",
"mask2",
"==",
"-",
"1",
"or",
"mask2",
"//",
"(",
"basis",
"*",
"3",
")",
"%",
"3",
"!=",
"i",
")",
":",
"backtracking",
"(",
"mask1",
",",
"mask2",
"+",
"i",
"*",
"basis",
"if",
"mask2",
"!=",
"-",
"1",
"else",
"i",
"*",
"basis",
",",
"basis",
"//",
"3",
",",
"result",
")",
"def",
"matrix_mult",
"(",
"A",
",",
"B",
")",
":",
"ZB",
"=",
"zip",
"(",
"*",
"B",
")",
"return",
"[",
"[",
"sum",
"(",
"a",
"*",
"b",
"%",
"MOD",
"for",
"a",
",",
"b",
"in",
"itertools",
".",
"izip",
"(",
"row",
",",
"col",
")",
")",
"%",
"MOD",
"for",
"col",
"in",
"ZB",
"]",
"for",
"row",
"in",
"A",
"]",
"def",
"matrix_expo",
"(",
"A",
",",
"K",
")",
":",
"result",
"=",
"[",
"[",
"int",
"(",
"i",
"==",
"j",
")",
"for",
"j",
"in",
"xrange",
"(",
"len",
"(",
"A",
")",
")",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"A",
")",
")",
"]",
"while",
"K",
":",
"if",
"K",
"%",
"2",
":",
"result",
"=",
"matrix_mult",
"(",
"result",
",",
"A",
")",
"A",
"=",
"matrix_mult",
"(",
"A",
",",
"A",
")",
"K",
"/=",
"2",
"return",
"result",
"def",
"normalize",
"(",
"basis",
",",
"mask",
")",
":",
"norm",
"=",
"{",
"}",
"result",
"=",
"0",
"while",
"basis",
":",
"x",
"=",
"mask",
"//",
"basis",
"%",
"3",
"if",
"x",
"not",
"in",
"norm",
":",
"norm",
"[",
"x",
"]",
"=",
"len",
"(",
"norm",
")",
"result",
"+=",
"norm",
"[",
"x",
"]",
"*",
"basis",
"basis",
"//=",
"3",
"return",
"result",
"if",
"m",
">",
"n",
":",
"m",
",",
"n",
"=",
"n",
",",
"m",
"basis",
"=",
"3",
"**",
"(",
"m",
"-",
"1",
")",
"masks",
"=",
"[",
"]",
"backtracking",
"(",
"-",
"1",
",",
"-",
"1",
",",
"basis",
",",
"masks",
")",
"# Time: O(2^m), Space: O(2^m)",
"assert",
"(",
"len",
"(",
"masks",
")",
"==",
"3",
"*",
"2",
"**",
"(",
"m",
"-",
"1",
")",
")",
"lookup",
"=",
"{",
"mask",
":",
"normalize",
"(",
"basis",
",",
"mask",
")",
"for",
"mask",
"in",
"masks",
"}",
"# Time: O(m * 2^m)",
"normalized_mask_cnt",
"=",
"collections",
".",
"Counter",
"(",
"lookup",
"[",
"mask",
"]",
"for",
"mask",
"in",
"masks",
")",
"assert",
"(",
"len",
"(",
"normalized_mask_cnt",
")",
"==",
"3",
"*",
"2",
"**",
"(",
"m",
"-",
"1",
")",
"//",
"3",
"//",
"(",
"2",
"if",
"m",
">=",
"2",
"else",
"1",
")",
")",
"# divided by 3 * 2 is since the first two colors are normalized to speed up performance",
"adj",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"mask",
"in",
"normalized_mask_cnt",
".",
"iterkeys",
"(",
")",
":",
"# O(3^m) leaves which are all in depth m => Time: O(3^m), Space: O(3^m)",
"backtracking",
"(",
"mask",
",",
"-",
"1",
",",
"basis",
",",
"adj",
"[",
"mask",
"]",
")",
"normalized_adj",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"collections",
".",
"defaultdict",
"(",
"int",
")",
")",
"for",
"mask1",
",",
"masks2",
"in",
"adj",
".",
"iteritems",
"(",
")",
":",
"for",
"mask2",
"in",
"masks2",
":",
"normalized_adj",
"[",
"mask1",
"]",
"[",
"lookup",
"[",
"mask2",
"]",
"]",
"=",
"(",
"normalized_adj",
"[",
"mask1",
"]",
"[",
"lookup",
"[",
"mask2",
"]",
"]",
"+",
"1",
")",
"%",
"MOD",
"# divided by 3 * 2 is since the first two colors in upper row are normalized to speed up performance,",
"# since first two colors in lower row which has at most 3 choices could be also normalized, lower bound is upper bound divided by at most 3",
"assert",
"(",
"2",
"*",
"3",
"**",
"m",
"//",
"3",
"//",
"2",
"//",
"3",
"<=",
"sum",
"(",
"len",
"(",
"v",
")",
"for",
"v",
"in",
"normalized_adj",
".",
"itervalues",
"(",
")",
")",
"<=",
"2",
"*",
"3",
"**",
"m",
"//",
"3",
"//",
"2",
")",
"return",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"(",
"x",
"+",
"y",
")",
"%",
"MOD",
",",
"matrix_mult",
"(",
"[",
"normalized_mask_cnt",
".",
"values",
"(",
")",
"]",
",",
"matrix_expo",
"(",
"[",
"[",
"normalized_adj",
"[",
"mask1",
"]",
"[",
"mask2",
"]",
"for",
"mask2",
"in",
"normalized_mask_cnt",
".",
"iterkeys",
"(",
")",
"]",
"for",
"mask1",
"in",
"normalized_mask_cnt",
".",
"iterkeys",
"(",
")",
"]",
",",
"n",
"-",
"1",
")",
")",
"[",
"0",
"]",
",",
"0",
")"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/painting-a-grid-with-three-different-colors.py#L11-L74 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | DELnHandler.WriteImmediateCmdSet | (self, func, file) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteImmediateCmdSet(self, func, file):
"""Overrriden from TypeHandler."""
last_arg = func.GetLastOriginalArg()
copy_args = func.MakeCmdArgString("_", False)
file.Write(" void* Set(void* cmd%s, %s _%s) {\n" %
(func.MakeTypedCmdArgString("_", True),
last_arg.type, last_arg.name))
file.Write(" static_cast<ValueType*>(cmd)->Init(%s, _%s);\n" %
(copy_args, last_arg.name))
file.Write(" const uint32 size = ComputeSize(_n);\n")
file.Write(" return NextImmediateCmdAddressTotalSize<ValueType>("
"cmd, size);\n")
file.Write(" }\n")
file.Write("\n") | [
"def",
"WriteImmediateCmdSet",
"(",
"self",
",",
"func",
",",
"file",
")",
":",
"last_arg",
"=",
"func",
".",
"GetLastOriginalArg",
"(",
")",
"copy_args",
"=",
"func",
".",
"MakeCmdArgString",
"(",
"\"_\"",
",",
"False",
")",
"file",
".",
"Write",
"(",
"\" void* Set(void* cmd%s, %s _%s) {\\n\"",
"%",
"(",
"func",
".",
"MakeTypedCmdArgString",
"(",
"\"_\"",
",",
"True",
")",
",",
"last_arg",
".",
"type",
",",
"last_arg",
".",
"name",
")",
")",
"file",
".",
"Write",
"(",
"\" static_cast<ValueType*>(cmd)->Init(%s, _%s);\\n\"",
"%",
"(",
"copy_args",
",",
"last_arg",
".",
"name",
")",
")",
"file",
".",
"Write",
"(",
"\" const uint32 size = ComputeSize(_n);\\n\"",
")",
"file",
".",
"Write",
"(",
"\" return NextImmediateCmdAddressTotalSize<ValueType>(\"",
"\"cmd, size);\\n\"",
")",
"file",
".",
"Write",
"(",
"\" }\\n\"",
")",
"file",
".",
"Write",
"(",
"\"\\n\"",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L4438-L4451 | ||
adnanaziz/epicode | e81d4387d2ae442d21631dfc958690d424e1d84d | cpp/cpplint.py | python | CheckForNewlineAtEOF | (filename, lines, error) | Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found. | Logs an error if there is no newline char at the end of the file. | [
"Logs",
"an",
"error",
"if",
"there",
"is",
"no",
"newline",
"char",
"at",
"the",
"end",
"of",
"the",
"file",
"."
] | def CheckForNewlineAtEOF(filename, lines, error):
"""Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
# The array lines() was created by adding two newlines to the
# original file (go figure), then splitting on \n.
# To verify that the file ends in \n, we just have to make sure the
# last-but-two element of lines() exists and is empty.
if len(lines) < 3 or lines[-2]:
error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
'Could not find a newline character at the end of the file.') | [
"def",
"CheckForNewlineAtEOF",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"# The array lines() was created by adding two newlines to the",
"# original file (go figure), then splitting on \\n.",
"# To verify that the file ends in \\n, we just have to make sure the",
"# last-but-two element of lines() exists and is empty.",
"if",
"len",
"(",
"lines",
")",
"<",
"3",
"or",
"lines",
"[",
"-",
"2",
"]",
":",
"error",
"(",
"filename",
",",
"len",
"(",
"lines",
")",
"-",
"2",
",",
"'whitespace/ending_newline'",
",",
"5",
",",
"'Could not find a newline character at the end of the file.'",
")"
] | https://github.com/adnanaziz/epicode/blob/e81d4387d2ae442d21631dfc958690d424e1d84d/cpp/cpplint.py#L1134-L1149 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/spec.py | python | AbstractFileSystem.cp | (self, path1, path2, **kwargs) | return self.copy(path1, path2, **kwargs) | Alias of :ref:`FilesystemSpec.copy`. | Alias of :ref:`FilesystemSpec.copy`. | [
"Alias",
"of",
":",
"ref",
":",
"FilesystemSpec",
".",
"copy",
"."
] | def cp(self, path1, path2, **kwargs):
"""Alias of :ref:`FilesystemSpec.copy`."""
return self.copy(path1, path2, **kwargs) | [
"def",
"cp",
"(",
"self",
",",
"path1",
",",
"path2",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"copy",
"(",
"path1",
",",
"path2",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/fsspec/spec.py#L946-L948 | |
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | clang/tools/scan-build-py/libscanbuild/intercept.py | python | capture | (args) | The entry point of build command interception. | The entry point of build command interception. | [
"The",
"entry",
"point",
"of",
"build",
"command",
"interception",
"."
] | def capture(args):
""" The entry point of build command interception. """
def post_processing(commands):
""" To make a compilation database, it needs to filter out commands
which are not compiler calls. Needs to find the source file name
from the arguments. And do shell escaping on the command.
To support incremental builds, it is desired to read elements from
an existing compilation database from a previous run. These elements
shall be merged with the new elements. """
# create entries from the current run
current = itertools.chain.from_iterable(
# creates a sequence of entry generators from an exec,
format_entry(command) for command in commands)
# read entries from previous run
if 'append' in args and args.append and os.path.isfile(args.cdb):
with open(args.cdb) as handle:
previous = iter(json.load(handle))
else:
previous = iter([])
# filter out duplicate entries from both
duplicate = duplicate_check(entry_hash)
return (entry
for entry in itertools.chain(previous, current)
if os.path.exists(entry['file']) and not duplicate(entry))
with TemporaryDirectory(prefix='intercept-') as tmp_dir:
# run the build command
environment = setup_environment(args, tmp_dir)
exit_code = run_build(args.build, env=environment)
# read the intercepted exec calls
exec_traces = itertools.chain.from_iterable(
parse_exec_trace(os.path.join(tmp_dir, filename))
for filename in sorted(glob.iglob(os.path.join(tmp_dir, '*.cmd'))))
# do post processing
entries = post_processing(exec_traces)
# dump the compilation database
with open(args.cdb, 'w+') as handle:
json.dump(list(entries), handle, sort_keys=True, indent=4)
return exit_code | [
"def",
"capture",
"(",
"args",
")",
":",
"def",
"post_processing",
"(",
"commands",
")",
":",
"\"\"\" To make a compilation database, it needs to filter out commands\n which are not compiler calls. Needs to find the source file name\n from the arguments. And do shell escaping on the command.\n\n To support incremental builds, it is desired to read elements from\n an existing compilation database from a previous run. These elements\n shall be merged with the new elements. \"\"\"",
"# create entries from the current run",
"current",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"# creates a sequence of entry generators from an exec,",
"format_entry",
"(",
"command",
")",
"for",
"command",
"in",
"commands",
")",
"# read entries from previous run",
"if",
"'append'",
"in",
"args",
"and",
"args",
".",
"append",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"args",
".",
"cdb",
")",
":",
"with",
"open",
"(",
"args",
".",
"cdb",
")",
"as",
"handle",
":",
"previous",
"=",
"iter",
"(",
"json",
".",
"load",
"(",
"handle",
")",
")",
"else",
":",
"previous",
"=",
"iter",
"(",
"[",
"]",
")",
"# filter out duplicate entries from both",
"duplicate",
"=",
"duplicate_check",
"(",
"entry_hash",
")",
"return",
"(",
"entry",
"for",
"entry",
"in",
"itertools",
".",
"chain",
"(",
"previous",
",",
"current",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"entry",
"[",
"'file'",
"]",
")",
"and",
"not",
"duplicate",
"(",
"entry",
")",
")",
"with",
"TemporaryDirectory",
"(",
"prefix",
"=",
"'intercept-'",
")",
"as",
"tmp_dir",
":",
"# run the build command",
"environment",
"=",
"setup_environment",
"(",
"args",
",",
"tmp_dir",
")",
"exit_code",
"=",
"run_build",
"(",
"args",
".",
"build",
",",
"env",
"=",
"environment",
")",
"# read the intercepted exec calls",
"exec_traces",
"=",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"parse_exec_trace",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tmp_dir",
",",
"filename",
")",
")",
"for",
"filename",
"in",
"sorted",
"(",
"glob",
".",
"iglob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tmp_dir",
",",
"'*.cmd'",
")",
")",
")",
")",
"# do post processing",
"entries",
"=",
"post_processing",
"(",
"exec_traces",
")",
"# dump the compilation database",
"with",
"open",
"(",
"args",
".",
"cdb",
",",
"'w+'",
")",
"as",
"handle",
":",
"json",
".",
"dump",
"(",
"list",
"(",
"entries",
")",
",",
"handle",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")",
"return",
"exit_code"
] | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/clang/tools/scan-build-py/libscanbuild/intercept.py#L58-L99 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/contrib/autograd.py | python | backward | (outputs, out_grads=None, retain_graph=False) | Compute the gradients of outputs w.r.t variables.
Parameters
----------
outputs: list of NDArray
out_grads: list of NDArray or None | Compute the gradients of outputs w.r.t variables. | [
"Compute",
"the",
"gradients",
"of",
"outputs",
"w",
".",
"r",
".",
"t",
"variables",
"."
] | def backward(outputs, out_grads=None, retain_graph=False):
"""Compute the gradients of outputs w.r.t variables.
Parameters
----------
outputs: list of NDArray
out_grads: list of NDArray or None
"""
assert isinstance(outputs, (list, tuple)), \
"outputs must be a list or tuple of NDArrays"
if out_grads is None:
check_call(_LIB.MXAutogradBackward(
len(outputs),
c_handle_array(outputs),
ctypes.c_void_p(0),
ctypes.c_int(retain_graph)))
return
ograd_handles = []
for arr in out_grads:
if arr is not None:
ograd_handles.append(arr.handle)
else:
ograd_handles.append(NDArrayHandle(0))
assert len(ograd_handles) == len(outputs), \
"outputs and out_grads must have the same length"
check_call(_LIB.MXAutogradBackward(
len(outputs),
c_handle_array(outputs),
c_array(NDArrayHandle, ograd_handles),
ctypes.c_int(retain_graph))) | [
"def",
"backward",
"(",
"outputs",
",",
"out_grads",
"=",
"None",
",",
"retain_graph",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"outputs",
",",
"(",
"list",
",",
"tuple",
")",
")",
",",
"\"outputs must be a list or tuple of NDArrays\"",
"if",
"out_grads",
"is",
"None",
":",
"check_call",
"(",
"_LIB",
".",
"MXAutogradBackward",
"(",
"len",
"(",
"outputs",
")",
",",
"c_handle_array",
"(",
"outputs",
")",
",",
"ctypes",
".",
"c_void_p",
"(",
"0",
")",
",",
"ctypes",
".",
"c_int",
"(",
"retain_graph",
")",
")",
")",
"return",
"ograd_handles",
"=",
"[",
"]",
"for",
"arr",
"in",
"out_grads",
":",
"if",
"arr",
"is",
"not",
"None",
":",
"ograd_handles",
".",
"append",
"(",
"arr",
".",
"handle",
")",
"else",
":",
"ograd_handles",
".",
"append",
"(",
"NDArrayHandle",
"(",
"0",
")",
")",
"assert",
"len",
"(",
"ograd_handles",
")",
"==",
"len",
"(",
"outputs",
")",
",",
"\"outputs and out_grads must have the same length\"",
"check_call",
"(",
"_LIB",
".",
"MXAutogradBackward",
"(",
"len",
"(",
"outputs",
")",
",",
"c_handle_array",
"(",
"outputs",
")",
",",
"c_array",
"(",
"NDArrayHandle",
",",
"ograd_handles",
")",
",",
"ctypes",
".",
"c_int",
"(",
"retain_graph",
")",
")",
")"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/contrib/autograd.py#L123-L155 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/mstats_extras.py | python | rsh | (data, points=None) | return (nhi-nlo) / (2.*n*h) | Evaluates Rosenblatt's shifted histogram estimators for each point
on the dataset 'data'.
Parameters
----------
data : sequence
Input data. Masked values are ignored.
points : sequence or None, optional
Sequence of points where to evaluate Rosenblatt shifted histogram.
If None, use the data. | Evaluates Rosenblatt's shifted histogram estimators for each point
on the dataset 'data'. | [
"Evaluates",
"Rosenblatt",
"s",
"shifted",
"histogram",
"estimators",
"for",
"each",
"point",
"on",
"the",
"dataset",
"data",
"."
] | def rsh(data, points=None):
"""
Evaluates Rosenblatt's shifted histogram estimators for each point
on the dataset 'data'.
Parameters
----------
data : sequence
Input data. Masked values are ignored.
points : sequence or None, optional
Sequence of points where to evaluate Rosenblatt shifted histogram.
If None, use the data.
"""
data = ma.array(data, copy=False)
if points is None:
points = data
else:
points = np.array(points, copy=False, ndmin=1)
if data.ndim != 1:
raise AttributeError("The input array should be 1D only !")
n = data.count()
r = idealfourths(data, axis=None)
h = 1.2 * (r[-1]-r[0]) / n**(1./5)
nhi = (data[:,None] <= points[None,:] + h).sum(0)
nlo = (data[:,None] < points[None,:] - h).sum(0)
return (nhi-nlo) / (2.*n*h) | [
"def",
"rsh",
"(",
"data",
",",
"points",
"=",
"None",
")",
":",
"data",
"=",
"ma",
".",
"array",
"(",
"data",
",",
"copy",
"=",
"False",
")",
"if",
"points",
"is",
"None",
":",
"points",
"=",
"data",
"else",
":",
"points",
"=",
"np",
".",
"array",
"(",
"points",
",",
"copy",
"=",
"False",
",",
"ndmin",
"=",
"1",
")",
"if",
"data",
".",
"ndim",
"!=",
"1",
":",
"raise",
"AttributeError",
"(",
"\"The input array should be 1D only !\"",
")",
"n",
"=",
"data",
".",
"count",
"(",
")",
"r",
"=",
"idealfourths",
"(",
"data",
",",
"axis",
"=",
"None",
")",
"h",
"=",
"1.2",
"*",
"(",
"r",
"[",
"-",
"1",
"]",
"-",
"r",
"[",
"0",
"]",
")",
"/",
"n",
"**",
"(",
"1.",
"/",
"5",
")",
"nhi",
"=",
"(",
"data",
"[",
":",
",",
"None",
"]",
"<=",
"points",
"[",
"None",
",",
":",
"]",
"+",
"h",
")",
".",
"sum",
"(",
"0",
")",
"nlo",
"=",
"(",
"data",
"[",
":",
",",
"None",
"]",
"<",
"points",
"[",
"None",
",",
":",
"]",
"-",
"h",
")",
".",
"sum",
"(",
"0",
")",
"return",
"(",
"nhi",
"-",
"nlo",
")",
"/",
"(",
"2.",
"*",
"n",
"*",
"h",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/mstats_extras.py#L422-L450 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py | python | Context.copy_sign | (self, a, b) | return a.copy_sign(b) | Copies the second operand's sign to the first one.
In detail, it returns a copy of the first operand with the sign
equal to the sign of the second operand.
>>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Decimal('1.50')
>>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Decimal('1.50')
>>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Decimal('-1.50')
>>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Decimal('-1.50')
>>> ExtendedContext.copy_sign(1, -2)
Decimal('-1')
>>> ExtendedContext.copy_sign(Decimal(1), -2)
Decimal('-1')
>>> ExtendedContext.copy_sign(1, Decimal(-2))
Decimal('-1') | Copies the second operand's sign to the first one. | [
"Copies",
"the",
"second",
"operand",
"s",
"sign",
"to",
"the",
"first",
"one",
"."
] | def copy_sign(self, a, b):
"""Copies the second operand's sign to the first one.
In detail, it returns a copy of the first operand with the sign
equal to the sign of the second operand.
>>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Decimal('1.50')
>>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Decimal('1.50')
>>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Decimal('-1.50')
>>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Decimal('-1.50')
>>> ExtendedContext.copy_sign(1, -2)
Decimal('-1')
>>> ExtendedContext.copy_sign(Decimal(1), -2)
Decimal('-1')
>>> ExtendedContext.copy_sign(1, Decimal(-2))
Decimal('-1')
"""
a = _convert_other(a, raiseit=True)
return a.copy_sign(b) | [
"def",
"copy_sign",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"copy_sign",
"(",
"b",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py#L4334-L4356 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py | python | alloca_once_value | (builder, value, name='') | return storage | Like alloca_once(), but passing a *value* instead of a type. The
type is inferred and the allocated slot is also initialized with the
given value. | Like alloca_once(), but passing a *value* instead of a type. The
type is inferred and the allocated slot is also initialized with the
given value. | [
"Like",
"alloca_once",
"()",
"but",
"passing",
"a",
"*",
"value",
"*",
"instead",
"of",
"a",
"type",
".",
"The",
"type",
"is",
"inferred",
"and",
"the",
"allocated",
"slot",
"is",
"also",
"initialized",
"with",
"the",
"given",
"value",
"."
] | def alloca_once_value(builder, value, name=''):
"""
Like alloca_once(), but passing a *value* instead of a type. The
type is inferred and the allocated slot is also initialized with the
given value.
"""
storage = alloca_once(builder, value.type)
builder.store(value, storage)
return storage | [
"def",
"alloca_once_value",
"(",
"builder",
",",
"value",
",",
"name",
"=",
"''",
")",
":",
"storage",
"=",
"alloca_once",
"(",
"builder",
",",
"value",
".",
"type",
")",
"builder",
".",
"store",
"(",
"value",
",",
"storage",
")",
"return",
"storage"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py#L384-L392 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/v7.9.317/third_party/jinja2/ext.py | python | babel_extract | (fileobj, keywords, comment_tags, options) | Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best preceeding comment that begins with one of the
keywords. For best results, make sure to not have more than one
gettext call in one line of code and the matching comment in the
same line or the line before.
.. versionchanged:: 2.5.1
The `newstyle_gettext` flag can be set to `True` to enable newstyle
gettext calls.
.. versionchanged:: 2.7
A `silent` option can now be provided. If set to `False` template
syntax errors are propagated instead of being ignored.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results.
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
(comments will be empty currently) | Babel extraction method for Jinja templates. | [
"Babel",
"extraction",
"method",
"for",
"Jinja",
"templates",
"."
] | def babel_extract(fileobj, keywords, comment_tags, options):
"""Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best preceeding comment that begins with one of the
keywords. For best results, make sure to not have more than one
gettext call in one line of code and the matching comment in the
same line or the line before.
.. versionchanged:: 2.5.1
The `newstyle_gettext` flag can be set to `True` to enable newstyle
gettext calls.
.. versionchanged:: 2.7
A `silent` option can now be provided. If set to `False` template
syntax errors are propagated instead of being ignored.
:param fileobj: the file-like object the messages should be extracted from
:param keywords: a list of keywords (i.e. function names) that should be
recognized as translation functions
:param comment_tags: a list of translator tags to search for and include
in the results.
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
(comments will be empty currently)
"""
extensions = set()
for extension in options.get('extensions', '').split(','):
extension = extension.strip()
if not extension:
continue
extensions.add(import_string(extension))
if InternationalizationExtension not in extensions:
extensions.add(InternationalizationExtension)
def getbool(options, key, default=False):
return options.get(key, str(default)).lower() in \
('1', 'on', 'yes', 'true')
silent = getbool(options, 'silent', True)
environment = Environment(
options.get('block_start_string', BLOCK_START_STRING),
options.get('block_end_string', BLOCK_END_STRING),
options.get('variable_start_string', VARIABLE_START_STRING),
options.get('variable_end_string', VARIABLE_END_STRING),
options.get('comment_start_string', COMMENT_START_STRING),
options.get('comment_end_string', COMMENT_END_STRING),
options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
getbool(options, 'trim_blocks', TRIM_BLOCKS),
getbool(options, 'lstrip_blocks', LSTRIP_BLOCKS),
NEWLINE_SEQUENCE,
getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE),
frozenset(extensions),
cache_size=0,
auto_reload=False
)
if getbool(options, 'trimmed'):
environment.policies['ext.i18n.trimmed'] = True
if getbool(options, 'newstyle_gettext'):
environment.newstyle_gettext = True
source = fileobj.read().decode(options.get('encoding', 'utf-8'))
try:
node = environment.parse(source)
tokens = list(environment.lex(environment.preprocess(source)))
except TemplateSyntaxError as e:
if not silent:
raise
# skip templates with syntax errors
return
finder = _CommentFinder(tokens, comment_tags)
for lineno, func, message in extract_from_ast(node, keywords):
yield lineno, func, message, finder.find_comments(lineno) | [
"def",
"babel_extract",
"(",
"fileobj",
",",
"keywords",
",",
"comment_tags",
",",
"options",
")",
":",
"extensions",
"=",
"set",
"(",
")",
"for",
"extension",
"in",
"options",
".",
"get",
"(",
"'extensions'",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
":",
"extension",
"=",
"extension",
".",
"strip",
"(",
")",
"if",
"not",
"extension",
":",
"continue",
"extensions",
".",
"add",
"(",
"import_string",
"(",
"extension",
")",
")",
"if",
"InternationalizationExtension",
"not",
"in",
"extensions",
":",
"extensions",
".",
"add",
"(",
"InternationalizationExtension",
")",
"def",
"getbool",
"(",
"options",
",",
"key",
",",
"default",
"=",
"False",
")",
":",
"return",
"options",
".",
"get",
"(",
"key",
",",
"str",
"(",
"default",
")",
")",
".",
"lower",
"(",
")",
"in",
"(",
"'1'",
",",
"'on'",
",",
"'yes'",
",",
"'true'",
")",
"silent",
"=",
"getbool",
"(",
"options",
",",
"'silent'",
",",
"True",
")",
"environment",
"=",
"Environment",
"(",
"options",
".",
"get",
"(",
"'block_start_string'",
",",
"BLOCK_START_STRING",
")",
",",
"options",
".",
"get",
"(",
"'block_end_string'",
",",
"BLOCK_END_STRING",
")",
",",
"options",
".",
"get",
"(",
"'variable_start_string'",
",",
"VARIABLE_START_STRING",
")",
",",
"options",
".",
"get",
"(",
"'variable_end_string'",
",",
"VARIABLE_END_STRING",
")",
",",
"options",
".",
"get",
"(",
"'comment_start_string'",
",",
"COMMENT_START_STRING",
")",
",",
"options",
".",
"get",
"(",
"'comment_end_string'",
",",
"COMMENT_END_STRING",
")",
",",
"options",
".",
"get",
"(",
"'line_statement_prefix'",
")",
"or",
"LINE_STATEMENT_PREFIX",
",",
"options",
".",
"get",
"(",
"'line_comment_prefix'",
")",
"or",
"LINE_COMMENT_PREFIX",
",",
"getbool",
"(",
"options",
",",
"'trim_blocks'",
",",
"TRIM_BLOCKS",
")",
",",
"getbool",
"(",
"options",
",",
"'lstrip_blocks'",
",",
"LSTRIP_BLOCKS",
")",
",",
"NEWLINE_SEQUENCE",
",",
"getbool",
"(",
"options",
",",
"'keep_trailing_newline'",
",",
"KEEP_TRAILING_NEWLINE",
")",
",",
"frozenset",
"(",
"extensions",
")",
",",
"cache_size",
"=",
"0",
",",
"auto_reload",
"=",
"False",
")",
"if",
"getbool",
"(",
"options",
",",
"'trimmed'",
")",
":",
"environment",
".",
"policies",
"[",
"'ext.i18n.trimmed'",
"]",
"=",
"True",
"if",
"getbool",
"(",
"options",
",",
"'newstyle_gettext'",
")",
":",
"environment",
".",
"newstyle_gettext",
"=",
"True",
"source",
"=",
"fileobj",
".",
"read",
"(",
")",
".",
"decode",
"(",
"options",
".",
"get",
"(",
"'encoding'",
",",
"'utf-8'",
")",
")",
"try",
":",
"node",
"=",
"environment",
".",
"parse",
"(",
"source",
")",
"tokens",
"=",
"list",
"(",
"environment",
".",
"lex",
"(",
"environment",
".",
"preprocess",
"(",
"source",
")",
")",
")",
"except",
"TemplateSyntaxError",
"as",
"e",
":",
"if",
"not",
"silent",
":",
"raise",
"# skip templates with syntax errors",
"return",
"finder",
"=",
"_CommentFinder",
"(",
"tokens",
",",
"comment_tags",
")",
"for",
"lineno",
",",
"func",
",",
"message",
"in",
"extract_from_ast",
"(",
"node",
",",
"keywords",
")",
":",
"yield",
"lineno",
",",
"func",
",",
"message",
",",
"finder",
".",
"find_comments",
"(",
"lineno",
")"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/ext.py#L542-L619 | ||
qgis/QGIS | 15a77662d4bb712184f6aa60d0bd663010a76a75 | python/plugins/processing/script/ScriptEditorDialog.py | python | ScriptEditorDialog.update_dialog_title | (self) | Updates the script editor dialog title | Updates the script editor dialog title | [
"Updates",
"the",
"script",
"editor",
"dialog",
"title"
] | def update_dialog_title(self):
"""
Updates the script editor dialog title
"""
if self.filePath:
path, file_name = os.path.split(self.filePath)
else:
file_name = self.tr('Untitled Script')
if self.hasChanged:
file_name = '*' + file_name
self.setWindowTitle(self.tr('{} - Processing Script Editor').format(file_name)) | [
"def",
"update_dialog_title",
"(",
"self",
")",
":",
"if",
"self",
".",
"filePath",
":",
"path",
",",
"file_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"filePath",
")",
"else",
":",
"file_name",
"=",
"self",
".",
"tr",
"(",
"'Untitled Script'",
")",
"if",
"self",
".",
"hasChanged",
":",
"file_name",
"=",
"'*'",
"+",
"file_name",
"self",
".",
"setWindowTitle",
"(",
"self",
".",
"tr",
"(",
"'{} - Processing Script Editor'",
")",
".",
"format",
"(",
"file_name",
")",
")"
] | https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/processing/script/ScriptEditorDialog.py#L123-L135 | ||
lmb-freiburg/flownet2 | b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc | python/caffe/draw.py | python | get_edge_label | (layer) | return edge_label | Define edge label based on layer type. | Define edge label based on layer type. | [
"Define",
"edge",
"label",
"based",
"on",
"layer",
"type",
"."
] | def get_edge_label(layer):
"""Define edge label based on layer type.
"""
if layer.type == 'Data':
edge_label = 'Batch ' + str(layer.data_param.batch_size)
elif layer.type == 'Convolution' or layer.type == 'Deconvolution':
edge_label = str(layer.convolution_param.num_output)
elif layer.type == 'InnerProduct':
edge_label = str(layer.inner_product_param.num_output)
else:
edge_label = '""'
return edge_label | [
"def",
"get_edge_label",
"(",
"layer",
")",
":",
"if",
"layer",
".",
"type",
"==",
"'Data'",
":",
"edge_label",
"=",
"'Batch '",
"+",
"str",
"(",
"layer",
".",
"data_param",
".",
"batch_size",
")",
"elif",
"layer",
".",
"type",
"==",
"'Convolution'",
"or",
"layer",
".",
"type",
"==",
"'Deconvolution'",
":",
"edge_label",
"=",
"str",
"(",
"layer",
".",
"convolution_param",
".",
"num_output",
")",
"elif",
"layer",
".",
"type",
"==",
"'InnerProduct'",
":",
"edge_label",
"=",
"str",
"(",
"layer",
".",
"inner_product_param",
".",
"num_output",
")",
"else",
":",
"edge_label",
"=",
"'\"\"'",
"return",
"edge_label"
] | https://github.com/lmb-freiburg/flownet2/blob/b92e198b56b0e52e1ba0a5a98dc0e39fa5ae70cc/python/caffe/draw.py#L46-L59 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/v8/third_party/jinja2/utils.py | python | LRUCache.copy | (self) | return rv | Return a shallow copy of the instance. | Return a shallow copy of the instance. | [
"Return",
"a",
"shallow",
"copy",
"of",
"the",
"instance",
"."
] | def copy(self):
"""Return a shallow copy of the instance."""
rv = self.__class__(self.capacity)
rv._mapping.update(self._mapping)
rv._queue = deque(self._queue)
return rv | [
"def",
"copy",
"(",
"self",
")",
":",
"rv",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"capacity",
")",
"rv",
".",
"_mapping",
".",
"update",
"(",
"self",
".",
"_mapping",
")",
"rv",
".",
"_queue",
"=",
"deque",
"(",
"self",
".",
"_queue",
")",
"return",
"rv"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/utils.py#L340-L345 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | python/mock-1.0.0/mock.py | python | _patch.start | (self) | return result | Activate a patch, returning any created mock. | Activate a patch, returning any created mock. | [
"Activate",
"a",
"patch",
"returning",
"any",
"created",
"mock",
"."
] | def start(self):
"""Activate a patch, returning any created mock."""
result = self.__enter__()
self._active_patches.add(self)
return result | [
"def",
"start",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"__enter__",
"(",
")",
"self",
".",
"_active_patches",
".",
"add",
"(",
"self",
")",
"return",
"result"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mock-1.0.0/mock.py#L1383-L1387 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/util/connection.py | python | create_connection | (
address,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None,
socket_options=None,
) | Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default. | Connect to *address* and return the socket object. | [
"Connect",
"to",
"*",
"address",
"*",
"and",
"return",
"the",
"socket",
"object",
"."
] | def create_connection(
address,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None,
socket_options=None,
):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default.
"""
host, port = address
if host.startswith("["):
host = host.strip("[]")
err = None
# Using the value from allowed_gai_family() in the context of getaddrinfo lets
# us select whether to work with IPv4 DNS records, IPv6 records, or both.
# The original create_connection function always returns all records.
family = allowed_gai_family()
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socket.socket(af, socktype, proto)
# If provided, set socket level options before connecting.
_set_socket_options(sock, socket_options)
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except socket.error as e:
err = e
if sock is not None:
sock.close()
sock = None
if err is not None:
raise err
raise socket.error("getaddrinfo returns an empty list") | [
"def",
"create_connection",
"(",
"address",
",",
"timeout",
"=",
"socket",
".",
"_GLOBAL_DEFAULT_TIMEOUT",
",",
"source_address",
"=",
"None",
",",
"socket_options",
"=",
"None",
",",
")",
":",
"host",
",",
"port",
"=",
"address",
"if",
"host",
".",
"startswith",
"(",
"\"[\"",
")",
":",
"host",
"=",
"host",
".",
"strip",
"(",
"\"[]\"",
")",
"err",
"=",
"None",
"# Using the value from allowed_gai_family() in the context of getaddrinfo lets",
"# us select whether to work with IPv4 DNS records, IPv6 records, or both.",
"# The original create_connection function always returns all records.",
"family",
"=",
"allowed_gai_family",
"(",
")",
"for",
"res",
"in",
"socket",
".",
"getaddrinfo",
"(",
"host",
",",
"port",
",",
"family",
",",
"socket",
".",
"SOCK_STREAM",
")",
":",
"af",
",",
"socktype",
",",
"proto",
",",
"canonname",
",",
"sa",
"=",
"res",
"sock",
"=",
"None",
"try",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"af",
",",
"socktype",
",",
"proto",
")",
"# If provided, set socket level options before connecting.",
"_set_socket_options",
"(",
"sock",
",",
"socket_options",
")",
"if",
"timeout",
"is",
"not",
"socket",
".",
"_GLOBAL_DEFAULT_TIMEOUT",
":",
"sock",
".",
"settimeout",
"(",
"timeout",
")",
"if",
"source_address",
":",
"sock",
".",
"bind",
"(",
"source_address",
")",
"sock",
".",
"connect",
"(",
"sa",
")",
"return",
"sock",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"err",
"=",
"e",
"if",
"sock",
"is",
"not",
"None",
":",
"sock",
".",
"close",
"(",
")",
"sock",
"=",
"None",
"if",
"err",
"is",
"not",
"None",
":",
"raise",
"err",
"raise",
"socket",
".",
"error",
"(",
"\"getaddrinfo returns an empty list\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/util/connection.py#L33-L86 | ||
usdot-fhwa-stol/carma-platform | d9d9b93f9689b2c7dd607cf5432d5296fc1000f5 | guidance_plugin_validator/src/guidance_plugin_validator/guidance_plugin_components.py | python | RequiredTacticalComponents.__init__ | (self, plugin_name) | Constructor for RequiredTacticalComponents | Constructor for RequiredTacticalComponents | [
"Constructor",
"for",
"RequiredTacticalComponents"
] | def __init__(self, plugin_name):
"""Constructor for RequiredTacticalComponents"""
# Validation result indicating whether tactical plugin's node successfully launches
self.has_node = False
# Validation result indicating whether tactical plugin's node advertises required service
self.plan_trajectory_service = "/guidance/plugins/" + str(plugin_name) + "/plan_trajectory"
self.has_plan_trajectory_service = False
# Validation result indicating whether tactical plugin's node publishes to required topic
self.plugin_discovery_topic = "/guidance/plugin_discovery"
self.has_plugin_discovery_pub = False
# Validation results indicating whether tactical plugin's node publishes required information to the plugin_discovery topic
self.correct_plugin_discovery_type = Plugin.TACTICAL
self.has_correct_plugin_discovery_type = False
self.correct_plugin_discovery_capability = "tactical_plan/plan_trajectory"
self.has_correct_plugin_discovery_capability = False | [
"def",
"__init__",
"(",
"self",
",",
"plugin_name",
")",
":",
"# Validation result indicating whether tactical plugin's node successfully launches",
"self",
".",
"has_node",
"=",
"False",
"# Validation result indicating whether tactical plugin's node advertises required service",
"self",
".",
"plan_trajectory_service",
"=",
"\"/guidance/plugins/\"",
"+",
"str",
"(",
"plugin_name",
")",
"+",
"\"/plan_trajectory\"",
"self",
".",
"has_plan_trajectory_service",
"=",
"False",
"# Validation result indicating whether tactical plugin's node publishes to required topic",
"self",
".",
"plugin_discovery_topic",
"=",
"\"/guidance/plugin_discovery\"",
"self",
".",
"has_plugin_discovery_pub",
"=",
"False",
"# Validation results indicating whether tactical plugin's node publishes required information to the plugin_discovery topic",
"self",
".",
"correct_plugin_discovery_type",
"=",
"Plugin",
".",
"TACTICAL",
"self",
".",
"has_correct_plugin_discovery_type",
"=",
"False",
"self",
".",
"correct_plugin_discovery_capability",
"=",
"\"tactical_plan/plan_trajectory\"",
"self",
".",
"has_correct_plugin_discovery_capability",
"=",
"False"
] | https://github.com/usdot-fhwa-stol/carma-platform/blob/d9d9b93f9689b2c7dd607cf5432d5296fc1000f5/guidance_plugin_validator/src/guidance_plugin_validator/guidance_plugin_components.py#L242-L261 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.BatchingUndo | (*args, **kwargs) | return _richtext.RichTextCtrl_BatchingUndo(*args, **kwargs) | BatchingUndo(self) -> bool
Are we batching undo history for commands? | BatchingUndo(self) -> bool | [
"BatchingUndo",
"(",
"self",
")",
"-",
">",
"bool"
] | def BatchingUndo(*args, **kwargs):
"""
BatchingUndo(self) -> bool
Are we batching undo history for commands?
"""
return _richtext.RichTextCtrl_BatchingUndo(*args, **kwargs) | [
"def",
"BatchingUndo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_BatchingUndo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3861-L3867 | |
mhammond/pywin32 | 44afd86ba8485194df93234639243252deeb40d5 | win32/Lib/win32pdhquery.py | python | BaseQuery.close | (self) | Makes certain that the underlying query object has been closed,
and that all counters have been removed from it. This is
important for reference counting.
You should only need to call close if you have previously called
open. The collectdata methods all can handle opening and
closing the query. Calling close multiple times is acceptable. | Makes certain that the underlying query object has been closed,
and that all counters have been removed from it. This is
important for reference counting.
You should only need to call close if you have previously called
open. The collectdata methods all can handle opening and
closing the query. Calling close multiple times is acceptable. | [
"Makes",
"certain",
"that",
"the",
"underlying",
"query",
"object",
"has",
"been",
"closed",
"and",
"that",
"all",
"counters",
"have",
"been",
"removed",
"from",
"it",
".",
"This",
"is",
"important",
"for",
"reference",
"counting",
".",
"You",
"should",
"only",
"need",
"to",
"call",
"close",
"if",
"you",
"have",
"previously",
"called",
"open",
".",
"The",
"collectdata",
"methods",
"all",
"can",
"handle",
"opening",
"and",
"closing",
"the",
"query",
".",
"Calling",
"close",
"multiple",
"times",
"is",
"acceptable",
"."
] | def close(self):
"""
Makes certain that the underlying query object has been closed,
and that all counters have been removed from it. This is
important for reference counting.
You should only need to call close if you have previously called
open. The collectdata methods all can handle opening and
closing the query. Calling close multiple times is acceptable.
"""
try:
self.killbase(self._base)
except AttributeError:
self.killbase() | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"killbase",
"(",
"self",
".",
"_base",
")",
"except",
"AttributeError",
":",
"self",
".",
"killbase",
"(",
")"
] | https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/win32/Lib/win32pdhquery.py#L278-L290 | ||
eclipse/omr | 056e7c9ce9d503649190bc5bd9931fac30b4e4bc | jitbuilder/apigen/genutils.py | python | APIDescription.get_class_by_name | (self, c) | return self.class_table[c] | Returns the description of a class from its name. | Returns the description of a class from its name. | [
"Returns",
"the",
"description",
"of",
"a",
"class",
"from",
"its",
"name",
"."
] | def get_class_by_name(self, c):
"""Returns the description of a class from its name."""
assert self.is_class(c), "'{}' is not a class in the {} API".format(c, self.project())
return self.class_table[c] | [
"def",
"get_class_by_name",
"(",
"self",
",",
"c",
")",
":",
"assert",
"self",
".",
"is_class",
"(",
"c",
")",
",",
"\"'{}' is not a class in the {} API\"",
".",
"format",
"(",
"c",
",",
"self",
".",
"project",
"(",
")",
")",
"return",
"self",
".",
"class_table",
"[",
"c",
"]"
] | https://github.com/eclipse/omr/blob/056e7c9ce9d503649190bc5bd9931fac30b4e4bc/jitbuilder/apigen/genutils.py#L429-L432 | |
htcondor/htcondor | 4829724575176d1d6c936e4693dfd78a728569b0 | src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/settings.py | python | ISettings.Avatar | (self, Id=1, Set=None) | Sets user avatar picture from file.
@param Id: Optional avatar Id.
@type Id: int
@param Set: New avatar file name.
@type Set: unicode
@deprecated: Use L{LoadAvatarFromFile} instead. | Sets user avatar picture from file. | [
"Sets",
"user",
"avatar",
"picture",
"from",
"file",
"."
] | def Avatar(self, Id=1, Set=None):
'''Sets user avatar picture from file.
@param Id: Optional avatar Id.
@type Id: int
@param Set: New avatar file name.
@type Set: unicode
@deprecated: Use L{LoadAvatarFromFile} instead.
'''
from warnings import warn
warn('ISettings.Avatar: Use ISettings.LoadAvatarFromFile instead.', DeprecationWarning, stacklevel=2)
if Set is None:
raise TypeError('Argument \'Set\' is mandatory!')
self.LoadAvatarFromFile(Set, Id) | [
"def",
"Avatar",
"(",
"self",
",",
"Id",
"=",
"1",
",",
"Set",
"=",
"None",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"'ISettings.Avatar: Use ISettings.LoadAvatarFromFile instead.'",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"if",
"Set",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'Argument \\'Set\\' is mandatory!'",
")",
"self",
".",
"LoadAvatarFromFile",
"(",
"Set",
",",
"Id",
")"
] | https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/settings.py#L21-L34 | ||
albertz/openlierox | d316c14a8eb57848ef56e9bfa7b23a56f694a51b | tools/DedicatedServerVideo/gdata/youtube/service.py | python | YouTubeService.UpdateContact | (self, contact_username, new_contact_status,
new_contact_category, my_username='default') | return self.Put(contact_entry, contact_put_uri,
converter=gdata.youtube.YouTubeContactEntryFromString) | Update a contact, providing a new status and a new category.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that is to be updated.
new_contact_status: A string representing the new status of the contact.
This can either be set to 'accepted' or 'rejected'.
new_contact_category: A string representing the new category for the
contact, either 'Friends' or 'Family'.
my_username: An optional string representing the username of the user
whose contact feed we are modifying. Defaults to the currently
authenticated user.
Returns:
A YouTubeContactEntry if updated succesfully.
Raises:
YouTubeError: New contact status must be within the accepted values. Or
new contact category must be within the accepted categories. | Update a contact, providing a new status and a new category. | [
"Update",
"a",
"contact",
"providing",
"a",
"new",
"status",
"and",
"a",
"new",
"category",
"."
] | def UpdateContact(self, contact_username, new_contact_status,
new_contact_category, my_username='default'):
"""Update a contact, providing a new status and a new category.
Needs authentication.
Args:
contact_username: A string representing the username of the contact
that is to be updated.
new_contact_status: A string representing the new status of the contact.
This can either be set to 'accepted' or 'rejected'.
new_contact_category: A string representing the new category for the
contact, either 'Friends' or 'Family'.
my_username: An optional string representing the username of the user
whose contact feed we are modifying. Defaults to the currently
authenticated user.
Returns:
A YouTubeContactEntry if updated succesfully.
Raises:
YouTubeError: New contact status must be within the accepted values. Or
new contact category must be within the accepted categories.
"""
if new_contact_status not in YOUTUBE_CONTACT_STATUS:
raise YouTubeError('New contact status must be one of %s' %
(' '.join(YOUTUBE_CONTACT_STATUS)))
if new_contact_category not in YOUTUBE_CONTACT_CATEGORY:
raise YouTubeError('New contact category must be one of %s' %
(' '.join(YOUTUBE_CONTACT_CATEGORY)))
contact_category = atom.Category(
scheme='http://gdata.youtube.com/schemas/2007/contact.cat',
term=new_contact_category)
contact_status = gdata.youtube.Status(text=new_contact_status)
contact_entry = gdata.youtube.YouTubeContactEntry(
category=contact_category,
status=contact_status)
contact_put_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username,
'contacts', contact_username)
return self.Put(contact_entry, contact_put_uri,
converter=gdata.youtube.YouTubeContactEntryFromString) | [
"def",
"UpdateContact",
"(",
"self",
",",
"contact_username",
",",
"new_contact_status",
",",
"new_contact_category",
",",
"my_username",
"=",
"'default'",
")",
":",
"if",
"new_contact_status",
"not",
"in",
"YOUTUBE_CONTACT_STATUS",
":",
"raise",
"YouTubeError",
"(",
"'New contact status must be one of %s'",
"%",
"(",
"' '",
".",
"join",
"(",
"YOUTUBE_CONTACT_STATUS",
")",
")",
")",
"if",
"new_contact_category",
"not",
"in",
"YOUTUBE_CONTACT_CATEGORY",
":",
"raise",
"YouTubeError",
"(",
"'New contact category must be one of %s'",
"%",
"(",
"' '",
".",
"join",
"(",
"YOUTUBE_CONTACT_CATEGORY",
")",
")",
")",
"contact_category",
"=",
"atom",
".",
"Category",
"(",
"scheme",
"=",
"'http://gdata.youtube.com/schemas/2007/contact.cat'",
",",
"term",
"=",
"new_contact_category",
")",
"contact_status",
"=",
"gdata",
".",
"youtube",
".",
"Status",
"(",
"text",
"=",
"new_contact_status",
")",
"contact_entry",
"=",
"gdata",
".",
"youtube",
".",
"YouTubeContactEntry",
"(",
"category",
"=",
"contact_category",
",",
"status",
"=",
"contact_status",
")",
"contact_put_uri",
"=",
"'%s/%s/%s/%s'",
"%",
"(",
"YOUTUBE_USER_FEED_URI",
",",
"my_username",
",",
"'contacts'",
",",
"contact_username",
")",
"return",
"self",
".",
"Put",
"(",
"contact_entry",
",",
"contact_put_uri",
",",
"converter",
"=",
"gdata",
".",
"youtube",
".",
"YouTubeContactEntryFromString",
")"
] | https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/youtube/service.py#L1196-L1240 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | Rect.Deflate | (*args, **kwargs) | return _core_.Rect_Deflate(*args, **kwargs) | Deflate(self, int dx, int dy) -> Rect
Decrease the rectangle size. This method is the opposite of `Inflate`
in that Deflate(a,b) is equivalent to Inflate(-a,-b). Please refer to
`Inflate` for a full description. | Deflate(self, int dx, int dy) -> Rect | [
"Deflate",
"(",
"self",
"int",
"dx",
"int",
"dy",
")",
"-",
">",
"Rect"
] | def Deflate(*args, **kwargs):
"""
Deflate(self, int dx, int dy) -> Rect
Decrease the rectangle size. This method is the opposite of `Inflate`
in that Deflate(a,b) is equivalent to Inflate(-a,-b). Please refer to
`Inflate` for a full description.
"""
return _core_.Rect_Deflate(*args, **kwargs) | [
"def",
"Deflate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect_Deflate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L1417-L1425 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/compiler/xla/python/xla_client.py | python | ComputationBuilder.Tuple | (self, *elems) | return ops.Tuple(self._builder, list(elems)) | Enqueues a tuple operation onto the computation.
Args:
elems: a sequence of tuple operands (each a XlaOp).
Returns:
An XlaOp representing the added Tuple op. | Enqueues a tuple operation onto the computation. | [
"Enqueues",
"a",
"tuple",
"operation",
"onto",
"the",
"computation",
"."
] | def Tuple(self, *elems):
"""Enqueues a tuple operation onto the computation.
Args:
elems: a sequence of tuple operands (each a XlaOp).
Returns:
An XlaOp representing the added Tuple op.
"""
return ops.Tuple(self._builder, list(elems)) | [
"def",
"Tuple",
"(",
"self",
",",
"*",
"elems",
")",
":",
"return",
"ops",
".",
"Tuple",
"(",
"self",
".",
"_builder",
",",
"list",
"(",
"elems",
")",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/compiler/xla/python/xla_client.py#L1092-L1101 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | driver/python/bson/objectid.py | python | _machine_bytes | () | return machine_hash.digest()[0:3] | Get the machine portion of an ObjectId. | Get the machine portion of an ObjectId. | [
"Get",
"the",
"machine",
"portion",
"of",
"an",
"ObjectId",
"."
] | def _machine_bytes():
"""Get the machine portion of an ObjectId.
"""
machine_hash = _md5func()
if PY3:
# gethostname() returns a unicode string in python 3.x
# while update() requires a byte string.
machine_hash.update(socket.gethostname().encode())
else:
# Calling encode() here will fail with non-ascii hostnames
machine_hash.update(socket.gethostname())
return machine_hash.digest()[0:3] | [
"def",
"_machine_bytes",
"(",
")",
":",
"machine_hash",
"=",
"_md5func",
"(",
")",
"if",
"PY3",
":",
"# gethostname() returns a unicode string in python 3.x",
"# while update() requires a byte string.",
"machine_hash",
".",
"update",
"(",
"socket",
".",
"gethostname",
"(",
")",
".",
"encode",
"(",
")",
")",
"else",
":",
"# Calling encode() here will fail with non-ascii hostnames",
"machine_hash",
".",
"update",
"(",
"socket",
".",
"gethostname",
"(",
")",
")",
"return",
"machine_hash",
".",
"digest",
"(",
")",
"[",
"0",
":",
"3",
"]"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/driver/python/bson/objectid.py#L47-L58 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/difflib.py | python | Differ.__init__ | (self, linejunk=None, charjunk=None) | Construct a text differencer, with optional filters.
The two optional keyword parameters are for filter functions:
- `linejunk`: A function that should accept a single string argument,
and return true iff the string is junk. The module-level function
`IS_LINE_JUNK` may be used to filter out lines without visible
characters, except for at most one splat ('#'). It is recommended
to leave linejunk None; the underlying SequenceMatcher class has
an adaptive notion of "noise" lines that's better than any static
definition the author has ever been able to craft.
- `charjunk`: A function that should accept a string of length 1. The
module-level function `IS_CHARACTER_JUNK` may be used to filter out
whitespace characters (a blank or tab; **note**: bad idea to include
newline in this!). Use of IS_CHARACTER_JUNK is recommended. | Construct a text differencer, with optional filters. | [
"Construct",
"a",
"text",
"differencer",
"with",
"optional",
"filters",
"."
] | def __init__(self, linejunk=None, charjunk=None):
"""
Construct a text differencer, with optional filters.
The two optional keyword parameters are for filter functions:
- `linejunk`: A function that should accept a single string argument,
and return true iff the string is junk. The module-level function
`IS_LINE_JUNK` may be used to filter out lines without visible
characters, except for at most one splat ('#'). It is recommended
to leave linejunk None; the underlying SequenceMatcher class has
an adaptive notion of "noise" lines that's better than any static
definition the author has ever been able to craft.
- `charjunk`: A function that should accept a string of length 1. The
module-level function `IS_CHARACTER_JUNK` may be used to filter out
whitespace characters (a blank or tab; **note**: bad idea to include
newline in this!). Use of IS_CHARACTER_JUNK is recommended.
"""
self.linejunk = linejunk
self.charjunk = charjunk | [
"def",
"__init__",
"(",
"self",
",",
"linejunk",
"=",
"None",
",",
"charjunk",
"=",
"None",
")",
":",
"self",
".",
"linejunk",
"=",
"linejunk",
"self",
".",
"charjunk",
"=",
"charjunk"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/difflib.py#L845-L866 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.