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
google/filament
d21f092645b8e1e312307cbf89f1484891347c63
third_party/libassimp/port/PyAssimp/scripts/transformations.py
python
quaternion_slerp
(quat0, quat1, fraction, spin=0, shortestpath=True)
return q0
Return spherical linear interpolation between two quaternions. >>> q0 = random_quaternion() >>> q1 = random_quaternion() >>> q = quaternion_slerp(q0, q1, 0.0) >>> numpy.allclose(q, q0) True >>> q = quaternion_slerp(q0, q1, 1.0, 1) >>> numpy.allclose(q, q1) True >>> q = quaternion_slerp(q0, q1, 0.5) >>> angle = math.acos(numpy.dot(q0, q)) >>> numpy.allclose(2.0, math.acos(numpy.dot(q0, q1)) / angle) or \ numpy.allclose(2.0, math.acos(-numpy.dot(q0, q1)) / angle) True
Return spherical linear interpolation between two quaternions.
[ "Return", "spherical", "linear", "interpolation", "between", "two", "quaternions", "." ]
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True): """Return spherical linear interpolation between two quaternions. >>> q0 = random_quaternion() >>> q1 = random_quaternion() >>> q = quaternion_slerp(q0, q1, 0.0) >>> numpy.allclose(q, q0) True >>> q = quaternion_slerp(q0, q1, 1.0, 1) >>> numpy.allclose(q, q1) True >>> q = quaternion_slerp(q0, q1, 0.5) >>> angle = math.acos(numpy.dot(q0, q)) >>> numpy.allclose(2.0, math.acos(numpy.dot(q0, q1)) / angle) or \ numpy.allclose(2.0, math.acos(-numpy.dot(q0, q1)) / angle) True """ q0 = unit_vector(quat0[:4]) q1 = unit_vector(quat1[:4]) if fraction == 0.0: return q0 elif fraction == 1.0: return q1 d = numpy.dot(q0, q1) if abs(abs(d) - 1.0) < _EPS: return q0 if shortestpath and d < 0.0: # invert rotation d = -d q1 *= -1.0 angle = math.acos(d) + spin * math.pi if abs(angle) < _EPS: return q0 isin = 1.0 / math.sin(angle) q0 *= math.sin((1.0 - fraction) * angle) * isin q1 *= math.sin(fraction * angle) * isin q0 += q1 return q0
[ "def", "quaternion_slerp", "(", "quat0", ",", "quat1", ",", "fraction", ",", "spin", "=", "0", ",", "shortestpath", "=", "True", ")", ":", "q0", "=", "unit_vector", "(", "quat0", "[", ":", "4", "]", ")", "q1", "=", "unit_vector", "(", "quat1", "[", ":", "4", "]", ")", "if", "fraction", "==", "0.0", ":", "return", "q0", "elif", "fraction", "==", "1.0", ":", "return", "q1", "d", "=", "numpy", ".", "dot", "(", "q0", ",", "q1", ")", "if", "abs", "(", "abs", "(", "d", ")", "-", "1.0", ")", "<", "_EPS", ":", "return", "q0", "if", "shortestpath", "and", "d", "<", "0.0", ":", "# invert rotation", "d", "=", "-", "d", "q1", "*=", "-", "1.0", "angle", "=", "math", ".", "acos", "(", "d", ")", "+", "spin", "*", "math", ".", "pi", "if", "abs", "(", "angle", ")", "<", "_EPS", ":", "return", "q0", "isin", "=", "1.0", "/", "math", ".", "sin", "(", "angle", ")", "q0", "*=", "math", ".", "sin", "(", "(", "1.0", "-", "fraction", ")", "*", "angle", ")", "*", "isin", "q1", "*=", "math", ".", "sin", "(", "fraction", "*", "angle", ")", "*", "isin", "q0", "+=", "q1", "return", "q0" ]
https://github.com/google/filament/blob/d21f092645b8e1e312307cbf89f1484891347c63/third_party/libassimp/port/PyAssimp/scripts/transformations.py#L1270-L1308
Illumina/strelka
d7377443b62319f7c7bd70c241c4b2df3459e29a
src/python/scoringModelTraining/somatic/lib/evs/strelka_rf_indel.py
python
StrelkaRFIndel.train
(self, tp, fp, columns, *args, **kwargs)
Train model from sets of TPs and FPs :param tp: data frame with rows of TP instances. :type tp: pandas.DataFrame :param fp: data frame with rows of FP instances. :type fp: pandas.DataFrame :param columns: the feature columns to use
Train model from sets of TPs and FPs
[ "Train", "model", "from", "sets", "of", "TPs", "and", "FPs" ]
def train(self, tp, fp, columns, *args, **kwargs): """ Train model from sets of TPs and FPs :param tp: data frame with rows of TP instances. :type tp: pandas.DataFrame :param fp: data frame with rows of FP instances. :type fp: pandas.DataFrame :param columns: the feature columns to use """ # import pdb; pdb.set_trace() tdf = pandas.DataFrame(tp[tp["NT"] == "ref"]) fdf = pandas.DataFrame(fp[fp["NT"] == "ref"]) tdf["tag"] = "TP" fdf["tag"] = "FP" allrows = pandas.concat([tdf, fdf]) # TODO: parameters to try # {'max_depth' : range(1,20,1), 'n_estimators' : range(5, 30+1,5)}, if not kwargs: kwargs = {"n_jobs": 8, "max_depth": 4, "n_estimators": 50, "max_features": "log2" } allrows["INDELTYPE"] = allrows["INDELTYPE"].astype(float).round().astype(int) self.clf = {} for it in self.itypes: self.clf[it] = RandomForestClassifier(**kwargs) irows = allrows[allrows["INDELTYPE"] == it] self.clf[it].fit(irows[columns].values, irows["tag"].values)
[ "def", "train", "(", "self", ",", "tp", ",", "fp", ",", "columns", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# import pdb; pdb.set_trace()", "tdf", "=", "pandas", ".", "DataFrame", "(", "tp", "[", "tp", "[", "\"NT\"", "]", "==", "\"ref\"", "]", ")", "fdf", "=", "pandas", ".", "DataFrame", "(", "fp", "[", "fp", "[", "\"NT\"", "]", "==", "\"ref\"", "]", ")", "tdf", "[", "\"tag\"", "]", "=", "\"TP\"", "fdf", "[", "\"tag\"", "]", "=", "\"FP\"", "allrows", "=", "pandas", ".", "concat", "(", "[", "tdf", ",", "fdf", "]", ")", "# TODO: parameters to try", "# {'max_depth' : range(1,20,1), 'n_estimators' : range(5, 30+1,5)},", "if", "not", "kwargs", ":", "kwargs", "=", "{", "\"n_jobs\"", ":", "8", ",", "\"max_depth\"", ":", "4", ",", "\"n_estimators\"", ":", "50", ",", "\"max_features\"", ":", "\"log2\"", "}", "allrows", "[", "\"INDELTYPE\"", "]", "=", "allrows", "[", "\"INDELTYPE\"", "]", ".", "astype", "(", "float", ")", ".", "round", "(", ")", ".", "astype", "(", "int", ")", "self", ".", "clf", "=", "{", "}", "for", "it", "in", "self", ".", "itypes", ":", "self", ".", "clf", "[", "it", "]", "=", "RandomForestClassifier", "(", "*", "*", "kwargs", ")", "irows", "=", "allrows", "[", "allrows", "[", "\"INDELTYPE\"", "]", "==", "it", "]", "self", ".", "clf", "[", "it", "]", ".", "fit", "(", "irows", "[", "columns", "]", ".", "values", ",", "irows", "[", "\"tag\"", "]", ".", "values", ")" ]
https://github.com/Illumina/strelka/blob/d7377443b62319f7c7bd70c241c4b2df3459e29a/src/python/scoringModelTraining/somatic/lib/evs/strelka_rf_indel.py#L35-L71
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
examples/pycaffe/layers/pascal_multilabel_datalayers.py
python
print_info
(name, params)
Ouput some info regarding the class
Ouput some info regarding the class
[ "Ouput", "some", "info", "regarding", "the", "class" ]
def print_info(name, params): """ Ouput some info regarding the class """ print "{} initialized for split: {}, with bs: {}, im_shape: {}.".format( name, params['split'], params['batch_size'], params['im_shape'])
[ "def", "print_info", "(", "name", ",", "params", ")", ":", "print", "\"{} initialized for split: {}, with bs: {}, im_shape: {}.\"", ".", "format", "(", "name", ",", "params", "[", "'split'", "]", ",", "params", "[", "'batch_size'", "]", ",", "params", "[", "'im_shape'", "]", ")" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L244-L252
Illumina/strelka
d7377443b62319f7c7bd70c241c4b2df3459e29a
src/python/lib/strelkaSequenceErrorEstimation.py
python
getSequenceErrorEstimatesForSample
(self, estimationIntervals, sampleIndex, taskPrefix="", dependencies=None)
return nextStepWait
Count sequencing errors in one sample and use these to estimate sample error parameters
Count sequencing errors in one sample and use these to estimate sample error parameters
[ "Count", "sequencing", "errors", "in", "one", "sample", "and", "use", "these", "to", "estimate", "sample", "error", "parameters" ]
def getSequenceErrorEstimatesForSample(self, estimationIntervals, sampleIndex, taskPrefix="", dependencies=None): """ Count sequencing errors in one sample and use these to estimate sample error parameters """ segmentTasks = set() segFiles = TempSequenceAlleleCountsSegmentFiles() if self.params.isErrorEstimationFromAllData : # get error counts from full data set: segmentTasks |= countAllEligibleSequenceEvidence(self, estimationIntervals, sampleIndex, segFiles, taskPrefix, dependencies) else : # Launch tasks until the required counts are found segmentTasks |= countSequenceEvidenceUntilTargetIsReached(self, estimationIntervals, sampleIndex, segFiles, taskPrefix, dependencies) # create a checkpoint for all segments: completeSegmentsTask = self.addTask(preJoin(taskPrefix,"completedAllGenomeSegments"),dependencies=segmentTasks) # merge segment stats: mergeCountsTask = mergeSequenceAlleleCounts(self, sampleIndex, segFiles.counts, taskPrefix=taskPrefix, dependencies=completeSegmentsTask) # get error parameters: estimateTask = estimateParametersFromAlleleCounts(self, sampleIndex, taskPrefix=taskPrefix, dependencies=mergeCountsTask) nextStepWait = set() nextStepWait.add(estimateTask) return nextStepWait
[ "def", "getSequenceErrorEstimatesForSample", "(", "self", ",", "estimationIntervals", ",", "sampleIndex", ",", "taskPrefix", "=", "\"\"", ",", "dependencies", "=", "None", ")", ":", "segmentTasks", "=", "set", "(", ")", "segFiles", "=", "TempSequenceAlleleCountsSegmentFiles", "(", ")", "if", "self", ".", "params", ".", "isErrorEstimationFromAllData", ":", "# get error counts from full data set:", "segmentTasks", "|=", "countAllEligibleSequenceEvidence", "(", "self", ",", "estimationIntervals", ",", "sampleIndex", ",", "segFiles", ",", "taskPrefix", ",", "dependencies", ")", "else", ":", "# Launch tasks until the required counts are found", "segmentTasks", "|=", "countSequenceEvidenceUntilTargetIsReached", "(", "self", ",", "estimationIntervals", ",", "sampleIndex", ",", "segFiles", ",", "taskPrefix", ",", "dependencies", ")", "# create a checkpoint for all segments:", "completeSegmentsTask", "=", "self", ".", "addTask", "(", "preJoin", "(", "taskPrefix", ",", "\"completedAllGenomeSegments\"", ")", ",", "dependencies", "=", "segmentTasks", ")", "# merge segment stats:", "mergeCountsTask", "=", "mergeSequenceAlleleCounts", "(", "self", ",", "sampleIndex", ",", "segFiles", ".", "counts", ",", "taskPrefix", "=", "taskPrefix", ",", "dependencies", "=", "completeSegmentsTask", ")", "# get error parameters:", "estimateTask", "=", "estimateParametersFromAlleleCounts", "(", "self", ",", "sampleIndex", ",", "taskPrefix", "=", "taskPrefix", ",", "dependencies", "=", "mergeCountsTask", ")", "nextStepWait", "=", "set", "(", ")", "nextStepWait", ".", "add", "(", "estimateTask", ")", "return", "nextStepWait" ]
https://github.com/Illumina/strelka/blob/d7377443b62319f7c7bd70c241c4b2df3459e29a/src/python/lib/strelkaSequenceErrorEstimation.py#L381-L410
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/core/cros_interface.py
python
GetAllCmdOutput
(args, cwd=None, quiet=False)
Open a subprocess to execute a program and returns its output. Args: args: A string or a sequence of program arguments. The program to execute is the string or the first item in the args sequence. cwd: If not None, the subprocess's current directory will be changed to |cwd| before it's executed. Returns: Captures and returns the command's stdout. Prints the command's stderr to logger (which defaults to stdout).
Open a subprocess to execute a program and returns its output.
[ "Open", "a", "subprocess", "to", "execute", "a", "program", "and", "returns", "its", "output", "." ]
def GetAllCmdOutput(args, cwd=None, quiet=False): """Open a subprocess to execute a program and returns its output. Args: args: A string or a sequence of program arguments. The program to execute is the string or the first item in the args sequence. cwd: If not None, the subprocess's current directory will be changed to |cwd| before it's executed. Returns: Captures and returns the command's stdout. Prints the command's stderr to logger (which defaults to stdout). """ if not quiet: logging.debug(' '.join(args) + ' ' + (cwd or '')) with open(os.devnull, 'w') as devnull: p = subprocess.Popen(args=args, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=devnull) stdout, stderr = p.communicate() if not quiet: logging.debug(' > stdout=[%s], stderr=[%s]', stdout, stderr) return stdout, stderr
[ "def", "GetAllCmdOutput", "(", "args", ",", "cwd", "=", "None", ",", "quiet", "=", "False", ")", ":", "if", "not", "quiet", ":", "logging", ".", "debug", "(", "' '", ".", "join", "(", "args", ")", "+", "' '", "+", "(", "cwd", "or", "''", ")", ")", "with", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "as", "devnull", ":", "p", "=", "subprocess", ".", "Popen", "(", "args", "=", "args", ",", "cwd", "=", "cwd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "stdin", "=", "devnull", ")", "stdout", ",", "stderr", "=", "p", ".", "communicate", "(", ")", "if", "not", "quiet", ":", "logging", ".", "debug", "(", "' > stdout=[%s], stderr=[%s]'", ",", "stdout", ",", "stderr", ")", "return", "stdout", ",", "stderr" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/core/cros_interface.py#L44-L68
Caffe-MPI/Caffe-MPI.github.io
df5992af571a2a19981b69635115c393f18d1c76
scripts/cpp_lint.py
python
RemoveMultiLineCommentsFromRange
(lines, begin, end)
Clears a range of lines for multi-line comments.
Clears a range of lines for multi-line comments.
[ "Clears", "a", "range", "of", "lines", "for", "multi", "-", "line", "comments", "." ]
def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '// dummy'
[ "def", "RemoveMultiLineCommentsFromRange", "(", "lines", ",", "begin", ",", "end", ")", ":", "# Having // dummy comments makes the lines non-empty, so we will not get", "# unnecessary blank line warnings later in the code.", "for", "i", "in", "range", "(", "begin", ",", "end", ")", ":", "lines", "[", "i", "]", "=", "'// dummy'" ]
https://github.com/Caffe-MPI/Caffe-MPI.github.io/blob/df5992af571a2a19981b69635115c393f18d1c76/scripts/cpp_lint.py#L1143-L1148
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py
python
QueueListener.__init__
(self, queue, *handlers, respect_handler_level=False)
Initialise an instance with the specified queue and handlers.
Initialise an instance with the specified queue and handlers.
[ "Initialise", "an", "instance", "with", "the", "specified", "queue", "and", "handlers", "." ]
def __init__(self, queue, *handlers, respect_handler_level=False): """ Initialise an instance with the specified queue and handlers. """ self.queue = queue self.handlers = handlers self._thread = None self.respect_handler_level = respect_handler_level
[ "def", "__init__", "(", "self", ",", "queue", ",", "*", "handlers", ",", "respect_handler_level", "=", "False", ")", ":", "self", ".", "queue", "=", "queue", "self", ".", "handlers", "=", "handlers", "self", ".", "_thread", "=", "None", "self", ".", "respect_handler_level", "=", "respect_handler_level" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/handlers.py#L1410-L1418
ros-planning/moveit2
dd240ef6fd8b9932a7a53964140f2952786187a9
moveit_commander/src/moveit_commander/planning_scene_interface.py
python
PlanningSceneInterface.add_object
(self, collision_object)
Add an object to the planning scene
Add an object to the planning scene
[ "Add", "an", "object", "to", "the", "planning", "scene" ]
def add_object(self, collision_object): """ Add an object to the planning scene """ self.__submit(collision_object, attach=False)
[ "def", "add_object", "(", "self", ",", "collision_object", ")", ":", "self", ".", "__submit", "(", "collision_object", ",", "attach", "=", "False", ")" ]
https://github.com/ros-planning/moveit2/blob/dd240ef6fd8b9932a7a53964140f2952786187a9/moveit_commander/src/moveit_commander/planning_scene_interface.py#L96-L98
SIPp/sipp
f44d0cf5dec0013eff8fd7b4da885d455aa82e0e
cpplint.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/SIPp/sipp/blob/f44d0cf5dec0013eff8fd7b4da885d455aa82e0e/cpplint.py#L1924-L1936
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/model_helper.py
python
ModelHelper.get_param_to_grad
(self, params)
return param_to_grad
Given a list of parameters returns a dict from a parameter to a corresponding gradient
Given a list of parameters returns a dict from a parameter to a corresponding gradient
[ "Given", "a", "list", "of", "parameters", "returns", "a", "dict", "from", "a", "parameter", "to", "a", "corresponding", "gradient" ]
def get_param_to_grad(self, params): ''' Given a list of parameters returns a dict from a parameter to a corresponding gradient ''' param_to_grad = {} if not self.gradient_ops_added: raise RuntimeError("You need to run AddGradientOperators first.") # We need to use empty namescope when creating the gradients # to prevent duplicating the namescope prefix for gradient blobs. for p in params: if str(p) in self.grad_map: param_to_grad[p] = self.grad_map[str(p)] return param_to_grad
[ "def", "get_param_to_grad", "(", "self", ",", "params", ")", ":", "param_to_grad", "=", "{", "}", "if", "not", "self", ".", "gradient_ops_added", ":", "raise", "RuntimeError", "(", "\"You need to run AddGradientOperators first.\"", ")", "# We need to use empty namescope when creating the gradients", "# to prevent duplicating the namescope prefix for gradient blobs.", "for", "p", "in", "params", ":", "if", "str", "(", "p", ")", "in", "self", ".", "grad_map", ":", "param_to_grad", "[", "p", "]", "=", "self", ".", "grad_map", "[", "str", "(", "p", ")", "]", "return", "param_to_grad" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/model_helper.py#L334-L348
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/_html.py
python
SyntaxData.GetKeywords
(self)
Returns Specified Keywords List
Returns Specified Keywords List
[ "Returns", "Specified", "Keywords", "List" ]
def GetKeywords(self): """Returns Specified Keywords List""" if self.LangId == synglob.ID_LANG_COLDFUSION: return [(HTML_TAGS[0], HTML_TAGS[1] + " " + CF_TAGS), JS_KEYWORDS] else: return [HTML_TAGS, JS_KEYWORDS, SGML_KEYWORDS, VBS_KEYWORDS]
[ "def", "GetKeywords", "(", "self", ")", ":", "if", "self", ".", "LangId", "==", "synglob", ".", "ID_LANG_COLDFUSION", ":", "return", "[", "(", "HTML_TAGS", "[", "0", "]", ",", "HTML_TAGS", "[", "1", "]", "+", "\" \"", "+", "CF_TAGS", ")", ",", "JS_KEYWORDS", "]", "else", ":", "return", "[", "HTML_TAGS", ",", "JS_KEYWORDS", ",", "SGML_KEYWORDS", ",", "VBS_KEYWORDS", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_html.py#L211-L216
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/index/collector.py
python
_get_html_response
(url, session)
return resp
Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_NotHTML` if it is not HTML. 2. Actually perform the request. Raise HTTP exceptions on network failures. 3. Check the Content-Type header to make sure we got HTML, and raise `_NotHTML` otherwise.
Access an HTML page with GET, and return the response.
[ "Access", "an", "HTML", "page", "with", "GET", "and", "return", "the", "response", "." ]
def _get_html_response(url, session): # type: (str, PipSession) -> Response """Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large file. Raise `_NotHTTP` if the content type cannot be determined, or `_NotHTML` if it is not HTML. 2. Actually perform the request. Raise HTTP exceptions on network failures. 3. Check the Content-Type header to make sure we got HTML, and raise `_NotHTML` otherwise. """ if is_archive_file(Link(url).filename): _ensure_html_response(url, session=session) logger.debug('Getting page %s', redact_auth_from_url(url)) resp = session.get( url, headers={ "Accept": "text/html", # We don't want to blindly returned cached data for # /simple/, because authors generally expecting that # twine upload && pip install will function, but if # they've done a pip install in the last ~10 minutes # it won't. Thus by setting this to zero we will not # blindly use any cached data, however the benefit of # using max-age=0 instead of no-cache, is that we will # still support conditional requests, so we will still # minimize traffic sent in cases where the page hasn't # changed at all, we will just always incur the round # trip for the conditional GET now instead of only # once per 10 minutes. # For more information, please see pypa/pip#5670. "Cache-Control": "max-age=0", }, ) raise_for_status(resp) # The check for archives above only works if the url ends with # something that looks like an archive. However that is not a # requirement of an url. Unless we issue a HEAD request on every # url we cannot know ahead of time for sure if something is HTML # or not. However we can check after we've downloaded it. _ensure_html_header(resp) return resp
[ "def", "_get_html_response", "(", "url", ",", "session", ")", ":", "# type: (str, PipSession) -> Response", "if", "is_archive_file", "(", "Link", "(", "url", ")", ".", "filename", ")", ":", "_ensure_html_response", "(", "url", ",", "session", "=", "session", ")", "logger", ".", "debug", "(", "'Getting page %s'", ",", "redact_auth_from_url", "(", "url", ")", ")", "resp", "=", "session", ".", "get", "(", "url", ",", "headers", "=", "{", "\"Accept\"", ":", "\"text/html\"", ",", "# We don't want to blindly returned cached data for", "# /simple/, because authors generally expecting that", "# twine upload && pip install will function, but if", "# they've done a pip install in the last ~10 minutes", "# it won't. Thus by setting this to zero we will not", "# blindly use any cached data, however the benefit of", "# using max-age=0 instead of no-cache, is that we will", "# still support conditional requests, so we will still", "# minimize traffic sent in cases where the page hasn't", "# changed at all, we will just always incur the round", "# trip for the conditional GET now instead of only", "# once per 10 minutes.", "# For more information, please see pypa/pip#5670.", "\"Cache-Control\"", ":", "\"max-age=0\"", ",", "}", ",", ")", "raise_for_status", "(", "resp", ")", "# The check for archives above only works if the url ends with", "# something that looks like an archive. However that is not a", "# requirement of an url. Unless we issue a HEAD request on every", "# url we cannot know ahead of time for sure if something is HTML", "# or not. However we can check after we've downloaded it.", "_ensure_html_header", "(", "resp", ")", "return", "resp" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/index/collector.py#L213-L309
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/third_party/jinja2/compiler.py
python
CodeGenerator.writeline
(self, x, node=None, extra=0)
Combination of newline and write.
Combination of newline and write.
[ "Combination", "of", "newline", "and", "write", "." ]
def writeline(self, x, node=None, extra=0): """Combination of newline and write.""" self.newline(node, extra) self.write(x)
[ "def", "writeline", "(", "self", ",", "x", ",", "node", "=", "None", ",", "extra", "=", "0", ")", ":", "self", ".", "newline", "(", "node", ",", "extra", ")", "self", ".", "write", "(", "x", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/third_party/jinja2/compiler.py#L397-L400
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/locale.py
python
atoi
(string)
return int(delocalize(string))
Converts a string to an integer according to the locale settings.
Converts a string to an integer according to the locale settings.
[ "Converts", "a", "string", "to", "an", "integer", "according", "to", "the", "locale", "settings", "." ]
def atoi(string): "Converts a string to an integer according to the locale settings." return int(delocalize(string))
[ "def", "atoi", "(", "string", ")", ":", "return", "int", "(", "delocalize", "(", "string", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/locale.py#L330-L332
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/hooks.py
python
dispatch_hook
(key, hooks, hook_data, **kwargs)
return hook_data
Dispatches a hook dictionary on a given piece of data.
Dispatches a hook dictionary on a given piece of data.
[ "Dispatches", "a", "hook", "dictionary", "on", "a", "given", "piece", "of", "data", "." ]
def dispatch_hook(key, hooks, hook_data, **kwargs): """Dispatches a hook dictionary on a given piece of data.""" hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, '__call__'): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **kwargs) if _hook_data is not None: hook_data = _hook_data return hook_data
[ "def", "dispatch_hook", "(", "key", ",", "hooks", ",", "hook_data", ",", "*", "*", "kwargs", ")", ":", "hooks", "=", "hooks", "or", "{", "}", "hooks", "=", "hooks", ".", "get", "(", "key", ")", "if", "hooks", ":", "if", "hasattr", "(", "hooks", ",", "'__call__'", ")", ":", "hooks", "=", "[", "hooks", "]", "for", "hook", "in", "hooks", ":", "_hook_data", "=", "hook", "(", "hook_data", ",", "*", "*", "kwargs", ")", "if", "_hook_data", "is", "not", "None", ":", "hook_data", "=", "_hook_data", "return", "hook_data" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/requests/hooks.py#L23-L34
citizenfx/fivem
88276d40cc7baf8285d02754cc5ae42ec7a8563f
vendor/chromium/mojo/public/tools/bindings/pylib/mojom/generate/translate.py
python
_Kind
(kinds, spec, scope)
return kind
Convert a type name into a mojom.Kind object. As a side-effect this function adds the result to 'kinds'. Args: kinds: {Dict[str, mojom.Kind]} All known kinds up to this point, indexed by their names. spec: {str} A name uniquely identifying a type. scope: {Tuple[str, str]} A tuple that looks like (namespace, struct/interface), referring to the location where the type is referenced. Returns: {mojom.Kind} The type corresponding to 'spec'.
Convert a type name into a mojom.Kind object.
[ "Convert", "a", "type", "name", "into", "a", "mojom", ".", "Kind", "object", "." ]
def _Kind(kinds, spec, scope): """Convert a type name into a mojom.Kind object. As a side-effect this function adds the result to 'kinds'. Args: kinds: {Dict[str, mojom.Kind]} All known kinds up to this point, indexed by their names. spec: {str} A name uniquely identifying a type. scope: {Tuple[str, str]} A tuple that looks like (namespace, struct/interface), referring to the location where the type is referenced. Returns: {mojom.Kind} The type corresponding to 'spec'. """ kind = _LookupKind(kinds, spec, scope) if kind: return kind if spec.startswith('?'): kind = _Kind(kinds, spec[1:], scope).MakeNullableKind() elif spec.startswith('a:'): kind = mojom.Array(_Kind(kinds, spec[2:], scope)) elif spec.startswith('asso:'): inner_kind = _Kind(kinds, spec[5:], scope) if isinstance(inner_kind, mojom.InterfaceRequest): kind = mojom.AssociatedInterfaceRequest(inner_kind) else: kind = mojom.AssociatedInterface(inner_kind) elif spec.startswith('a'): colon = spec.find(':') length = int(spec[1:colon]) kind = mojom.Array(_Kind(kinds, spec[colon+1:], scope), length) elif spec.startswith('r:'): kind = mojom.InterfaceRequest(_Kind(kinds, spec[2:], scope)) elif spec.startswith('rmt:'): kind = mojom.PendingRemote(_Kind(kinds, spec[4:], scope)) elif spec.startswith('rcv:'): kind = mojom.PendingReceiver(_Kind(kinds, spec[4:], scope)) elif spec.startswith('rma:'): kind = mojom.PendingAssociatedRemote(_Kind(kinds, spec[4:], scope)) elif spec.startswith('rca:'): kind = mojom.PendingAssociatedReceiver(_Kind(kinds, spec[4:], scope)) elif spec.startswith('m['): # Isolate the two types from their brackets. # It is not allowed to use map as key, so there shouldn't be nested ']'s # inside the key type spec. key_end = spec.find(']') assert key_end != -1 and key_end < len(spec) - 1 assert spec[key_end+1] == '[' and spec[-1] == ']' first_kind = spec[2:key_end] second_kind = spec[key_end+2:-1] kind = mojom.Map(_Kind(kinds, first_kind, scope), _Kind(kinds, second_kind, scope)) else: kind = mojom.Kind(spec) kinds[spec] = kind return kind
[ "def", "_Kind", "(", "kinds", ",", "spec", ",", "scope", ")", ":", "kind", "=", "_LookupKind", "(", "kinds", ",", "spec", ",", "scope", ")", "if", "kind", ":", "return", "kind", "if", "spec", ".", "startswith", "(", "'?'", ")", ":", "kind", "=", "_Kind", "(", "kinds", ",", "spec", "[", "1", ":", "]", ",", "scope", ")", ".", "MakeNullableKind", "(", ")", "elif", "spec", ".", "startswith", "(", "'a:'", ")", ":", "kind", "=", "mojom", ".", "Array", "(", "_Kind", "(", "kinds", ",", "spec", "[", "2", ":", "]", ",", "scope", ")", ")", "elif", "spec", ".", "startswith", "(", "'asso:'", ")", ":", "inner_kind", "=", "_Kind", "(", "kinds", ",", "spec", "[", "5", ":", "]", ",", "scope", ")", "if", "isinstance", "(", "inner_kind", ",", "mojom", ".", "InterfaceRequest", ")", ":", "kind", "=", "mojom", ".", "AssociatedInterfaceRequest", "(", "inner_kind", ")", "else", ":", "kind", "=", "mojom", ".", "AssociatedInterface", "(", "inner_kind", ")", "elif", "spec", ".", "startswith", "(", "'a'", ")", ":", "colon", "=", "spec", ".", "find", "(", "':'", ")", "length", "=", "int", "(", "spec", "[", "1", ":", "colon", "]", ")", "kind", "=", "mojom", ".", "Array", "(", "_Kind", "(", "kinds", ",", "spec", "[", "colon", "+", "1", ":", "]", ",", "scope", ")", ",", "length", ")", "elif", "spec", ".", "startswith", "(", "'r:'", ")", ":", "kind", "=", "mojom", ".", "InterfaceRequest", "(", "_Kind", "(", "kinds", ",", "spec", "[", "2", ":", "]", ",", "scope", ")", ")", "elif", "spec", ".", "startswith", "(", "'rmt:'", ")", ":", "kind", "=", "mojom", ".", "PendingRemote", "(", "_Kind", "(", "kinds", ",", "spec", "[", "4", ":", "]", ",", "scope", ")", ")", "elif", "spec", ".", "startswith", "(", "'rcv:'", ")", ":", "kind", "=", "mojom", ".", "PendingReceiver", "(", "_Kind", "(", "kinds", ",", "spec", "[", "4", ":", "]", ",", "scope", ")", ")", "elif", "spec", ".", "startswith", "(", "'rma:'", ")", ":", "kind", "=", "mojom", ".", "PendingAssociatedRemote", "(", "_Kind", "(", "kinds", ",", "spec", "[", "4", ":", "]", ",", "scope", ")", ")", "elif", "spec", ".", "startswith", "(", "'rca:'", ")", ":", "kind", "=", "mojom", ".", "PendingAssociatedReceiver", "(", "_Kind", "(", "kinds", ",", "spec", "[", "4", ":", "]", ",", "scope", ")", ")", "elif", "spec", ".", "startswith", "(", "'m['", ")", ":", "# Isolate the two types from their brackets.", "# It is not allowed to use map as key, so there shouldn't be nested ']'s", "# inside the key type spec.", "key_end", "=", "spec", ".", "find", "(", "']'", ")", "assert", "key_end", "!=", "-", "1", "and", "key_end", "<", "len", "(", "spec", ")", "-", "1", "assert", "spec", "[", "key_end", "+", "1", "]", "==", "'['", "and", "spec", "[", "-", "1", "]", "==", "']'", "first_kind", "=", "spec", "[", "2", ":", "key_end", "]", "second_kind", "=", "spec", "[", "key_end", "+", "2", ":", "-", "1", "]", "kind", "=", "mojom", ".", "Map", "(", "_Kind", "(", "kinds", ",", "first_kind", ",", "scope", ")", ",", "_Kind", "(", "kinds", ",", "second_kind", ",", "scope", ")", ")", "else", ":", "kind", "=", "mojom", ".", "Kind", "(", "spec", ")", "kinds", "[", "spec", "]", "=", "kind", "return", "kind" ]
https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/mojo/public/tools/bindings/pylib/mojom/generate/translate.py#L183-L245
baidu-research/persistent-rnn
dcb55b7bc4669021a9da82a3e847c7fe1377ef87
site_scons/site_init.py
python
getLibCXXPaths
()
return (inc_path, lib_path)
Determines libc++ path returns (inc_path, lib_path)
Determines libc++ path
[ "Determines", "libc", "++", "path" ]
def getLibCXXPaths(): """Determines libc++ path returns (inc_path, lib_path) """ # determine defaults if os.name == 'posix': inc_path = '/usr/include' lib_path = '/usr/lib/libc++.so' else: raise ValueError, 'Error: unknown OS. Where is libc++ installed?' # override with environement variables if 'LIBCXX_INC_PATH' in os.environ: inc_path = os.path.abspath(os.environ['LIBCXX_INC_PATH']) if 'LIBCXX_LIB_PATH' in os.environ: lib_path = os.path.abspath(os.environ['LIBCXX_LIB_PATH']) return (inc_path, lib_path)
[ "def", "getLibCXXPaths", "(", ")", ":", "# determine defaults", "if", "os", ".", "name", "==", "'posix'", ":", "inc_path", "=", "'/usr/include'", "lib_path", "=", "'/usr/lib/libc++.so'", "else", ":", "raise", "ValueError", ",", "'Error: unknown OS. Where is libc++ installed?'", "# override with environement variables", "if", "'LIBCXX_INC_PATH'", "in", "os", ".", "environ", ":", "inc_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "environ", "[", "'LIBCXX_INC_PATH'", "]", ")", "if", "'LIBCXX_LIB_PATH'", "in", "os", ".", "environ", ":", "lib_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "environ", "[", "'LIBCXX_LIB_PATH'", "]", ")", "return", "(", "inc_path", ",", "lib_path", ")" ]
https://github.com/baidu-research/persistent-rnn/blob/dcb55b7bc4669021a9da82a3e847c7fe1377ef87/site_scons/site_init.py#L95-L114
amd/OpenCL-caffe
638543108517265366c18ae5821f3096cf5cf34a
python/caffe/pycaffe.py
python
_Net_batch
(self, blobs)
Batch blob lists according to net's batch size. Parameters ---------- blobs: Keys blob names and values are lists of blobs (of any length). Naturally, all the lists should have the same length. Yields ------ batch: {blob name: list of blobs} dict for a single batch.
Batch blob lists according to net's batch size.
[ "Batch", "blob", "lists", "according", "to", "net", "s", "batch", "size", "." ]
def _Net_batch(self, blobs): """ Batch blob lists according to net's batch size. Parameters ---------- blobs: Keys blob names and values are lists of blobs (of any length). Naturally, all the lists should have the same length. Yields ------ batch: {blob name: list of blobs} dict for a single batch. """ num = len(blobs.itervalues().next()) batch_size = self.blobs.itervalues().next().num remainder = num % batch_size num_batches = num / batch_size # Yield full batches. for b in range(num_batches): i = b * batch_size yield {name: blobs[name][i:i + batch_size] for name in blobs} # Yield last padded batch, if any. if remainder > 0: padded_batch = {} for name in blobs: padding = np.zeros((batch_size - remainder,) + blobs[name].shape[1:]) padded_batch[name] = np.concatenate([blobs[name][-remainder:], padding]) yield padded_batch
[ "def", "_Net_batch", "(", "self", ",", "blobs", ")", ":", "num", "=", "len", "(", "blobs", ".", "itervalues", "(", ")", ".", "next", "(", ")", ")", "batch_size", "=", "self", ".", "blobs", ".", "itervalues", "(", ")", ".", "next", "(", ")", ".", "num", "remainder", "=", "num", "%", "batch_size", "num_batches", "=", "num", "/", "batch_size", "# Yield full batches.", "for", "b", "in", "range", "(", "num_batches", ")", ":", "i", "=", "b", "*", "batch_size", "yield", "{", "name", ":", "blobs", "[", "name", "]", "[", "i", ":", "i", "+", "batch_size", "]", "for", "name", "in", "blobs", "}", "# Yield last padded batch, if any.", "if", "remainder", ">", "0", ":", "padded_batch", "=", "{", "}", "for", "name", "in", "blobs", ":", "padding", "=", "np", ".", "zeros", "(", "(", "batch_size", "-", "remainder", ",", ")", "+", "blobs", "[", "name", "]", ".", "shape", "[", "1", ":", "]", ")", "padded_batch", "[", "name", "]", "=", "np", ".", "concatenate", "(", "[", "blobs", "[", "name", "]", "[", "-", "remainder", ":", "]", ",", "padding", "]", ")", "yield", "padded_batch" ]
https://github.com/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/python/caffe/pycaffe.py#L238-L269
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/AddonManager/package_list.py
python
PackageListItemModel.setData
(self, index: QModelIndex, value, role=Qt.EditRole)
Set the data for this row. The column of the index is ignored.
Set the data for this row. The column of the index is ignored.
[ "Set", "the", "data", "for", "this", "row", ".", "The", "column", "of", "the", "index", "is", "ignored", "." ]
def setData(self, index: QModelIndex, value, role=Qt.EditRole) -> None: """Set the data for this row. The column of the index is ignored.""" row = index.row() self.write_lock.acquire() if role == PackageListItemModel.StatusUpdateRole: self.repos[row].set_status(value) self.dataChanged.emit( self.index(row, 2), self.index(row, 2), [PackageListItemModel.StatusUpdateRole], ) elif role == PackageListItemModel.IconUpdateRole: self.repos[row].icon = value self.dataChanged.emit( self.index(row, 0), self.index(row, 0), [PackageListItemModel.IconUpdateRole], ) self.write_lock.release()
[ "def", "setData", "(", "self", ",", "index", ":", "QModelIndex", ",", "value", ",", "role", "=", "Qt", ".", "EditRole", ")", "->", "None", ":", "row", "=", "index", ".", "row", "(", ")", "self", ".", "write_lock", ".", "acquire", "(", ")", "if", "role", "==", "PackageListItemModel", ".", "StatusUpdateRole", ":", "self", ".", "repos", "[", "row", "]", ".", "set_status", "(", "value", ")", "self", ".", "dataChanged", ".", "emit", "(", "self", ".", "index", "(", "row", ",", "2", ")", ",", "self", ".", "index", "(", "row", ",", "2", ")", ",", "[", "PackageListItemModel", ".", "StatusUpdateRole", "]", ",", ")", "elif", "role", "==", "PackageListItemModel", ".", "IconUpdateRole", ":", "self", ".", "repos", "[", "row", "]", ".", "icon", "=", "value", "self", ".", "dataChanged", ".", "emit", "(", "self", ".", "index", "(", "row", ",", "0", ")", ",", "self", ".", "index", "(", "row", ",", "0", ")", ",", "[", "PackageListItemModel", ".", "IconUpdateRole", "]", ",", ")", "self", ".", "write_lock", ".", "release", "(", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/AddonManager/package_list.py#L224-L243
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
ObjectChangeAuthResponse.__init__
(self, outPrivate = None)
This command is used to change the authorization secret for a TPM-resident object. Attributes: outPrivate (TPM2B_PRIVATE): Private area containing the new authorization value
This command is used to change the authorization secret for a TPM-resident object.
[ "This", "command", "is", "used", "to", "change", "the", "authorization", "secret", "for", "a", "TPM", "-", "resident", "object", "." ]
def __init__(self, outPrivate = None): """ This command is used to change the authorization secret for a TPM-resident object. Attributes: outPrivate (TPM2B_PRIVATE): Private area containing the new authorization value """ self.outPrivate = outPrivate
[ "def", "__init__", "(", "self", ",", "outPrivate", "=", "None", ")", ":", "self", ".", "outPrivate", "=", "outPrivate" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L10126-L10134
GoSSIP-SJTU/TripleDoggy
03648d6b19c812504b14e8b98c8c7b3f443f4e54
tools/clang/tools/scan-build-py/libscanbuild/analyze.py
python
ctu_collect_phase
(opts)
Preprocess source by generating all data needed by CTU analysis.
Preprocess source by generating all data needed by CTU analysis.
[ "Preprocess", "source", "by", "generating", "all", "data", "needed", "by", "CTU", "analysis", "." ]
def ctu_collect_phase(opts): """ Preprocess source by generating all data needed by CTU analysis. """ def generate_ast(triple_arch): """ Generates ASTs for the current compilation command. """ args = opts['direct_args'] + opts['flags'] ast_joined_path = os.path.join(opts['ctu'].dir, triple_arch, 'ast', os.path.realpath(opts['file'])[1:] + '.ast') ast_path = os.path.abspath(ast_joined_path) ast_dir = os.path.dirname(ast_path) if not os.path.isdir(ast_dir): try: os.makedirs(ast_dir) except OSError: # In case an other process already created it. pass ast_command = [opts['clang'], '-emit-ast'] ast_command.extend(args) ast_command.append('-w') ast_command.append(opts['file']) ast_command.append('-o') ast_command.append(ast_path) logging.debug("Generating AST using '%s'", ast_command) run_command(ast_command, cwd=opts['directory']) def map_functions(triple_arch): """ Generate function map file for the current source. """ args = opts['direct_args'] + opts['flags'] funcmap_command = [opts['ctu'].func_map_cmd] funcmap_command.append(opts['file']) funcmap_command.append('--') funcmap_command.extend(args) logging.debug("Generating function map using '%s'", funcmap_command) func_src_list = run_command(funcmap_command, cwd=opts['directory']) func_ast_list = func_map_list_src_to_ast(func_src_list) extern_fns_map_folder = os.path.join(opts['ctu'].dir, triple_arch, CTU_TEMP_FNMAP_FOLDER) if not os.path.isdir(extern_fns_map_folder): try: os.makedirs(extern_fns_map_folder) except OSError: # In case an other process already created it. pass if func_ast_list: with tempfile.NamedTemporaryFile(mode='w', dir=extern_fns_map_folder, delete=False) as out_file: out_file.write("\n".join(func_ast_list) + "\n") cwd = opts['directory'] cmd = [opts['clang'], '--analyze'] + opts['direct_args'] + opts['flags'] \ + [opts['file']] triple_arch = get_triple_arch(cmd, cwd) generate_ast(triple_arch) map_functions(triple_arch)
[ "def", "ctu_collect_phase", "(", "opts", ")", ":", "def", "generate_ast", "(", "triple_arch", ")", ":", "\"\"\" Generates ASTs for the current compilation command. \"\"\"", "args", "=", "opts", "[", "'direct_args'", "]", "+", "opts", "[", "'flags'", "]", "ast_joined_path", "=", "os", ".", "path", ".", "join", "(", "opts", "[", "'ctu'", "]", ".", "dir", ",", "triple_arch", ",", "'ast'", ",", "os", ".", "path", ".", "realpath", "(", "opts", "[", "'file'", "]", ")", "[", "1", ":", "]", "+", "'.ast'", ")", "ast_path", "=", "os", ".", "path", ".", "abspath", "(", "ast_joined_path", ")", "ast_dir", "=", "os", ".", "path", ".", "dirname", "(", "ast_path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "ast_dir", ")", ":", "try", ":", "os", ".", "makedirs", "(", "ast_dir", ")", "except", "OSError", ":", "# In case an other process already created it.", "pass", "ast_command", "=", "[", "opts", "[", "'clang'", "]", ",", "'-emit-ast'", "]", "ast_command", ".", "extend", "(", "args", ")", "ast_command", ".", "append", "(", "'-w'", ")", "ast_command", ".", "append", "(", "opts", "[", "'file'", "]", ")", "ast_command", ".", "append", "(", "'-o'", ")", "ast_command", ".", "append", "(", "ast_path", ")", "logging", ".", "debug", "(", "\"Generating AST using '%s'\"", ",", "ast_command", ")", "run_command", "(", "ast_command", ",", "cwd", "=", "opts", "[", "'directory'", "]", ")", "def", "map_functions", "(", "triple_arch", ")", ":", "\"\"\" Generate function map file for the current source. \"\"\"", "args", "=", "opts", "[", "'direct_args'", "]", "+", "opts", "[", "'flags'", "]", "funcmap_command", "=", "[", "opts", "[", "'ctu'", "]", ".", "func_map_cmd", "]", "funcmap_command", ".", "append", "(", "opts", "[", "'file'", "]", ")", "funcmap_command", ".", "append", "(", "'--'", ")", "funcmap_command", ".", "extend", "(", "args", ")", "logging", ".", "debug", "(", "\"Generating function map using '%s'\"", ",", "funcmap_command", ")", "func_src_list", "=", "run_command", "(", "funcmap_command", ",", "cwd", "=", "opts", "[", "'directory'", "]", ")", "func_ast_list", "=", "func_map_list_src_to_ast", "(", "func_src_list", ")", "extern_fns_map_folder", "=", "os", ".", "path", ".", "join", "(", "opts", "[", "'ctu'", "]", ".", "dir", ",", "triple_arch", ",", "CTU_TEMP_FNMAP_FOLDER", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "extern_fns_map_folder", ")", ":", "try", ":", "os", ".", "makedirs", "(", "extern_fns_map_folder", ")", "except", "OSError", ":", "# In case an other process already created it.", "pass", "if", "func_ast_list", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'w'", ",", "dir", "=", "extern_fns_map_folder", ",", "delete", "=", "False", ")", "as", "out_file", ":", "out_file", ".", "write", "(", "\"\\n\"", ".", "join", "(", "func_ast_list", ")", "+", "\"\\n\"", ")", "cwd", "=", "opts", "[", "'directory'", "]", "cmd", "=", "[", "opts", "[", "'clang'", "]", ",", "'--analyze'", "]", "+", "opts", "[", "'direct_args'", "]", "+", "opts", "[", "'flags'", "]", "+", "[", "opts", "[", "'file'", "]", "]", "triple_arch", "=", "get_triple_arch", "(", "cmd", ",", "cwd", ")", "generate_ast", "(", "triple_arch", ")", "map_functions", "(", "triple_arch", ")" ]
https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/tools/clang/tools/scan-build-py/libscanbuild/analyze.py#L566-L623
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/torch/converter.py
python
TorchConverter._create_placeholder
(_input)
return mb.placeholder(shape, dtype=dtype)
Converts an InputType torch.Tensor into a Placeholder.
Converts an InputType torch.Tensor into a Placeholder.
[ "Converts", "an", "InputType", "torch", ".", "Tensor", "into", "a", "Placeholder", "." ]
def _create_placeholder(_input): """Converts an InputType torch.Tensor into a Placeholder. """ shape = _input.shape.shape dtype = _input.dtype return mb.placeholder(shape, dtype=dtype)
[ "def", "_create_placeholder", "(", "_input", ")", ":", "shape", "=", "_input", ".", "shape", ".", "shape", "dtype", "=", "_input", ".", "dtype", "return", "mb", ".", "placeholder", "(", "shape", ",", "dtype", "=", "dtype", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/torch/converter.py#L174-L179
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-blocks/python/blocks/qa_multiply_matrix_xx.py
python
test_multiply_matrix_xx.test_005_t
(self)
Tags
Tags
[ "Tags" ]
def test_005_t(self): """ Tags """ X_in = ( (1, 2, 3, 4), (5, 6, 7, 8), ) A = ( (0, 1), # Flip them round (1, 0), ) tag1 = gr.tag_t() tag1.offset = 0 tag1.key = pmt.intern("in1") tag1.value = pmt.PMT_T tag2 = gr.tag_t() tag2.offset = 0 tag2.key = pmt.intern("in2") tag2.value = pmt.PMT_T self.run_once(X_in, A, tpp=gr.TPP_ONE_TO_ONE, tags=(tag1, tag2)) self.assertTrue(pmt.equal(tag1.key, self.the_tags[0][0].key)) self.assertTrue(pmt.equal(tag2.key, self.the_tags[1][0].key))
[ "def", "test_005_t", "(", "self", ")", ":", "X_in", "=", "(", "(", "1", ",", "2", ",", "3", ",", "4", ")", ",", "(", "5", ",", "6", ",", "7", ",", "8", ")", ",", ")", "A", "=", "(", "(", "0", ",", "1", ")", ",", "# Flip them round", "(", "1", ",", "0", ")", ",", ")", "tag1", "=", "gr", ".", "tag_t", "(", ")", "tag1", ".", "offset", "=", "0", "tag1", ".", "key", "=", "pmt", ".", "intern", "(", "\"in1\"", ")", "tag1", ".", "value", "=", "pmt", ".", "PMT_T", "tag2", "=", "gr", ".", "tag_t", "(", ")", "tag2", ".", "offset", "=", "0", "tag2", ".", "key", "=", "pmt", ".", "intern", "(", "\"in2\"", ")", "tag2", ".", "value", "=", "pmt", ".", "PMT_T", "self", ".", "run_once", "(", "X_in", ",", "A", ",", "tpp", "=", "gr", ".", "TPP_ONE_TO_ONE", ",", "tags", "=", "(", "tag1", ",", "tag2", ")", ")", "self", ".", "assertTrue", "(", "pmt", ".", "equal", "(", "tag1", ".", "key", ",", "self", ".", "the_tags", "[", "0", "]", "[", "0", "]", ".", "key", ")", ")", "self", ".", "assertTrue", "(", "pmt", ".", "equal", "(", "tag2", ".", "key", ",", "self", ".", "the_tags", "[", "1", "]", "[", "0", "]", ".", "key", ")", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-blocks/python/blocks/qa_multiply_matrix_xx.py#L156-L176
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/extras/codelite.py
python
vsnode.ptype
(self)
Return a special uuid for projects written in the solution file
Return a special uuid for projects written in the solution file
[ "Return", "a", "special", "uuid", "for", "projects", "written", "in", "the", "solution", "file" ]
def ptype(self): """ Return a special uuid for projects written in the solution file """ pass
[ "def", "ptype", "(", "self", ")", ":", "pass" ]
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/extras/codelite.py#L409-L413
zhaoweicai/hwgq
ebc706bee3e2d145de1da4be446ce8de8740738f
scripts/cpp_lint.py
python
CheckMakePairUsesDeduction
(filename, clean_lines, linenum, error)
Check that make_pair's template arguments are deduced. G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Check that make_pair's template arguments are deduced.
[ "Check", "that", "make_pair", "s", "template", "arguments", "are", "deduced", "." ]
def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): """Check that make_pair's template arguments are deduced. G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) if match: error(filename, linenum, 'build/explicit_make_pair', 4, # 4 = high confidence 'For C++11-compatibility, omit template arguments from make_pair' ' OR use pair directly OR if appropriate, construct a pair directly')
[ "def", "CheckMakePairUsesDeduction", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "_RE_PATTERN_EXPLICIT_MAKEPAIR", ".", "search", "(", "line", ")", "if", "match", ":", "error", "(", "filename", ",", "linenum", ",", "'build/explicit_make_pair'", ",", "4", ",", "# 4 = high confidence", "'For C++11-compatibility, omit template arguments from make_pair'", "' OR use pair directly OR if appropriate, construct a pair directly'", ")" ]
https://github.com/zhaoweicai/hwgq/blob/ebc706bee3e2d145de1da4be446ce8de8740738f/scripts/cpp_lint.py#L4579-L4597
facebook/watchman
0917460c71b000b96be9b9575d77f06f2f6053bb
build/fbcode_builder/getdeps/platform.py
python
get_available_ram
()
Returns a platform-appropriate available RAM metric in MiB.
Returns a platform-appropriate available RAM metric in MiB.
[ "Returns", "a", "platform", "-", "appropriate", "available", "RAM", "metric", "in", "MiB", "." ]
def get_available_ram() -> int: """ Returns a platform-appropriate available RAM metric in MiB. """ if sys.platform == "linux": return _get_available_ram_linux() elif sys.platform == "darwin": return _get_available_ram_macos() elif sys.platform == "win32": return _get_available_ram_windows() elif sys.platform.startswith("freebsd"): return _get_available_ram_freebsd() else: raise NotImplementedError( f"platform {sys.platform} does not have an implementation of get_available_ram" )
[ "def", "get_available_ram", "(", ")", "->", "int", ":", "if", "sys", ".", "platform", "==", "\"linux\"", ":", "return", "_get_available_ram_linux", "(", ")", "elif", "sys", ".", "platform", "==", "\"darwin\"", ":", "return", "_get_available_ram_macos", "(", ")", "elif", "sys", ".", "platform", "==", "\"win32\"", ":", "return", "_get_available_ram_windows", "(", ")", "elif", "sys", ".", "platform", ".", "startswith", "(", "\"freebsd\"", ")", ":", "return", "_get_available_ram_freebsd", "(", ")", "else", ":", "raise", "NotImplementedError", "(", "f\"platform {sys.platform} does not have an implementation of get_available_ram\"", ")" ]
https://github.com/facebook/watchman/blob/0917460c71b000b96be9b9575d77f06f2f6053bb/build/fbcode_builder/getdeps/platform.py#L159-L174
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/backends/chrome_inspector/devtools_http.py
python
DevToolsHttp._Connect
(self, timeout)
Attempts to establish a connection to Chrome devtools.
Attempts to establish a connection to Chrome devtools.
[ "Attempts", "to", "establish", "a", "connection", "to", "Chrome", "devtools", "." ]
def _Connect(self, timeout): """Attempts to establish a connection to Chrome devtools.""" assert not self._conn try: host_port = '127.0.0.1:%i' % self._devtools_port self._conn = httplib.HTTPConnection(host_port, timeout=timeout) except (socket.error, httplib.HTTPException) as e: raise DevToolsClientConnectionError, (e,), sys.exc_info()[2]
[ "def", "_Connect", "(", "self", ",", "timeout", ")", ":", "assert", "not", "self", ".", "_conn", "try", ":", "host_port", "=", "'127.0.0.1:%i'", "%", "self", ".", "_devtools_port", "self", ".", "_conn", "=", "httplib", ".", "HTTPConnection", "(", "host_port", ",", "timeout", "=", "timeout", ")", "except", "(", "socket", ".", "error", ",", "httplib", ".", "HTTPException", ")", "as", "e", ":", "raise", "DevToolsClientConnectionError", ",", "(", "e", ",", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/backends/chrome_inspector/devtools_http.py#L38-L45
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/torch.py
python
_make_torch_function
(handle)
return ret_function
Create a Torch function from the FunctionHandle.
Create a Torch function from the FunctionHandle.
[ "Create", "a", "Torch", "function", "from", "the", "FunctionHandle", "." ]
def _make_torch_function(handle): """Create a Torch function from the FunctionHandle.""" # Get the property of function n_used_vars = mx_uint() n_scalars = mx_uint() n_mutate_vars = mx_uint() type_mask = ctypes.c_int() check_call(_LIB.MXFuncDescribe( handle, ctypes.byref(n_used_vars), ctypes.byref(n_scalars), ctypes.byref(n_mutate_vars), ctypes.byref(type_mask))) n_mutate_vars = n_mutate_vars.value n_used_vars = n_used_vars.value n_scalars = n_scalars.value type_mask = type_mask.value # Get the information from the function name = ctypes.c_char_p() desc = ctypes.c_char_p() num_args = mx_uint() arg_names = ctypes.POINTER(ctypes.c_char_p)() arg_types = ctypes.POINTER(ctypes.c_char_p)() arg_descs = ctypes.POINTER(ctypes.c_char_p)() ret_type = ctypes.c_char_p() check_call(_LIB.MXFuncGetInfo( handle, ctypes.byref(name), ctypes.byref(desc), ctypes.byref(num_args), ctypes.byref(arg_names), ctypes.byref(arg_types), ctypes.byref(arg_descs), ctypes.byref(ret_type))) func_name = py_str(name.value) if not func_name.startswith('_th_'): return None narg = int(num_args.value) param_str = _build_param_doc( [py_str(arg_names[i]) for i in range(narg)], [py_str(arg_types[i]) for i in range(narg)], [py_str(arg_descs[i]) for i in range(narg)]) if n_mutate_vars > 1: res = ','.join(['res%d '%i for i in range(n_mutate_vars)]) else: res = 'res ' doc_str = (('Interface for Torch function {name}.\n' + 'Invoke with\n{res}= mxnet.th.{name}(Parameters)\nor\n'+ 'mxnet.th.{name}({res}, Parameters).\n\n' + '{param_str}\n' + 'References: ' + 'https://github.com/torch/torch7/blob/master/doc/maths.md\n').format( name=func_name[4:], param_str=param_str, res=res)) def generic_torch_function(*args, **kwargs): """Invoke this function by passing in parameters. Parameters ---------- *args Positional arguments of inputs (both scalar and `NDArray`). Returns ------- out : NDArray The result NDArray(tuple) of result of computation. """ ndargs = [] arg_format = '' value = '' for arg in args: if isinstance(arg, NDArray): ndargs.append(arg) arg_format += 'n' value += ',' elif isinstance(arg, int): arg_format += 'i' value += str(arg) + ',' elif isinstance(arg, str): arg_format += 's' value += str(arg) + ',' elif isinstance(arg, float): arg_format += 'f' value += str(arg) + ',' elif isinstance(arg, bool): arg_format += 'b' value += str(arg) + ',' value = value[:-1] if len(ndargs) == n_used_vars: ndargs = [NDArray(_new_empty_handle()) for _ in range(n_mutate_vars)] + ndargs arg_format = 'n'*n_mutate_vars + arg_format value = ','*n_mutate_vars + value elif len(ndargs) == n_mutate_vars + n_used_vars: pass else: raise AssertionError(('Incorrect number of input NDArrays. ' + 'Need to be either %d (inputs) or %d ' + '(output buffer) + %d (input)') % (n_used_vars, n_mutate_vars, n_used_vars)) kwargs['format'] = arg_format kwargs['args'] = value for k in kwargs: kwargs[k] = str(kwargs[k]) check_call(_LIB.MXFuncInvokeEx( handle, c_handle_array(ndargs[n_mutate_vars:]), # pylint: disable=invalid-slice-index c_array(mx_float, []), c_handle_array(ndargs[:n_mutate_vars]), # pylint: disable=invalid-slice-index ctypes.c_int(len(kwargs)), c_str_array(kwargs.keys()), c_str_array(kwargs.values()))) if n_mutate_vars == 1: return ndargs[0] else: return ndargs[:n_mutate_vars] # pylint: disable=invalid-slice-index # End of function declaration ret_function = generic_torch_function ret_function.__name__ = func_name[4:] ret_function.__doc__ = doc_str return ret_function
[ "def", "_make_torch_function", "(", "handle", ")", ":", "# Get the property of function", "n_used_vars", "=", "mx_uint", "(", ")", "n_scalars", "=", "mx_uint", "(", ")", "n_mutate_vars", "=", "mx_uint", "(", ")", "type_mask", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXFuncDescribe", "(", "handle", ",", "ctypes", ".", "byref", "(", "n_used_vars", ")", ",", "ctypes", ".", "byref", "(", "n_scalars", ")", ",", "ctypes", ".", "byref", "(", "n_mutate_vars", ")", ",", "ctypes", ".", "byref", "(", "type_mask", ")", ")", ")", "n_mutate_vars", "=", "n_mutate_vars", ".", "value", "n_used_vars", "=", "n_used_vars", ".", "value", "n_scalars", "=", "n_scalars", ".", "value", "type_mask", "=", "type_mask", ".", "value", "# Get the information from the function", "name", "=", "ctypes", ".", "c_char_p", "(", ")", "desc", "=", "ctypes", ".", "c_char_p", "(", ")", "num_args", "=", "mx_uint", "(", ")", "arg_names", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char_p", ")", "(", ")", "arg_types", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char_p", ")", "(", ")", "arg_descs", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char_p", ")", "(", ")", "ret_type", "=", "ctypes", ".", "c_char_p", "(", ")", "check_call", "(", "_LIB", ".", "MXFuncGetInfo", "(", "handle", ",", "ctypes", ".", "byref", "(", "name", ")", ",", "ctypes", ".", "byref", "(", "desc", ")", ",", "ctypes", ".", "byref", "(", "num_args", ")", ",", "ctypes", ".", "byref", "(", "arg_names", ")", ",", "ctypes", ".", "byref", "(", "arg_types", ")", ",", "ctypes", ".", "byref", "(", "arg_descs", ")", ",", "ctypes", ".", "byref", "(", "ret_type", ")", ")", ")", "func_name", "=", "py_str", "(", "name", ".", "value", ")", "if", "not", "func_name", ".", "startswith", "(", "'_th_'", ")", ":", "return", "None", "narg", "=", "int", "(", "num_args", ".", "value", ")", "param_str", "=", "_build_param_doc", "(", "[", "py_str", "(", "arg_names", "[", "i", "]", ")", "for", "i", "in", "range", "(", "narg", ")", "]", ",", "[", "py_str", "(", "arg_types", "[", "i", "]", ")", "for", "i", "in", "range", "(", "narg", ")", "]", ",", "[", "py_str", "(", "arg_descs", "[", "i", "]", ")", "for", "i", "in", "range", "(", "narg", ")", "]", ")", "if", "n_mutate_vars", ">", "1", ":", "res", "=", "','", ".", "join", "(", "[", "'res%d '", "%", "i", "for", "i", "in", "range", "(", "n_mutate_vars", ")", "]", ")", "else", ":", "res", "=", "'res '", "doc_str", "=", "(", "(", "'Interface for Torch function {name}.\\n'", "+", "'Invoke with\\n{res}= mxnet.th.{name}(Parameters)\\nor\\n'", "+", "'mxnet.th.{name}({res}, Parameters).\\n\\n'", "+", "'{param_str}\\n'", "+", "'References: '", "+", "'https://github.com/torch/torch7/blob/master/doc/maths.md\\n'", ")", ".", "format", "(", "name", "=", "func_name", "[", "4", ":", "]", ",", "param_str", "=", "param_str", ",", "res", "=", "res", ")", ")", "def", "generic_torch_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Invoke this function by passing in parameters.\n\n Parameters\n ----------\n *args\n Positional arguments of inputs (both scalar and `NDArray`).\n\n Returns\n -------\n out : NDArray\n The result NDArray(tuple) of result of computation.\n \"\"\"", "ndargs", "=", "[", "]", "arg_format", "=", "''", "value", "=", "''", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "NDArray", ")", ":", "ndargs", ".", "append", "(", "arg", ")", "arg_format", "+=", "'n'", "value", "+=", "','", "elif", "isinstance", "(", "arg", ",", "int", ")", ":", "arg_format", "+=", "'i'", "value", "+=", "str", "(", "arg", ")", "+", "','", "elif", "isinstance", "(", "arg", ",", "str", ")", ":", "arg_format", "+=", "'s'", "value", "+=", "str", "(", "arg", ")", "+", "','", "elif", "isinstance", "(", "arg", ",", "float", ")", ":", "arg_format", "+=", "'f'", "value", "+=", "str", "(", "arg", ")", "+", "','", "elif", "isinstance", "(", "arg", ",", "bool", ")", ":", "arg_format", "+=", "'b'", "value", "+=", "str", "(", "arg", ")", "+", "','", "value", "=", "value", "[", ":", "-", "1", "]", "if", "len", "(", "ndargs", ")", "==", "n_used_vars", ":", "ndargs", "=", "[", "NDArray", "(", "_new_empty_handle", "(", ")", ")", "for", "_", "in", "range", "(", "n_mutate_vars", ")", "]", "+", "ndargs", "arg_format", "=", "'n'", "*", "n_mutate_vars", "+", "arg_format", "value", "=", "','", "*", "n_mutate_vars", "+", "value", "elif", "len", "(", "ndargs", ")", "==", "n_mutate_vars", "+", "n_used_vars", ":", "pass", "else", ":", "raise", "AssertionError", "(", "(", "'Incorrect number of input NDArrays. '", "+", "'Need to be either %d (inputs) or %d '", "+", "'(output buffer) + %d (input)'", ")", "%", "(", "n_used_vars", ",", "n_mutate_vars", ",", "n_used_vars", ")", ")", "kwargs", "[", "'format'", "]", "=", "arg_format", "kwargs", "[", "'args'", "]", "=", "value", "for", "k", "in", "kwargs", ":", "kwargs", "[", "k", "]", "=", "str", "(", "kwargs", "[", "k", "]", ")", "check_call", "(", "_LIB", ".", "MXFuncInvokeEx", "(", "handle", ",", "c_handle_array", "(", "ndargs", "[", "n_mutate_vars", ":", "]", ")", ",", "# pylint: disable=invalid-slice-index", "c_array", "(", "mx_float", ",", "[", "]", ")", ",", "c_handle_array", "(", "ndargs", "[", ":", "n_mutate_vars", "]", ")", ",", "# pylint: disable=invalid-slice-index", "ctypes", ".", "c_int", "(", "len", "(", "kwargs", ")", ")", ",", "c_str_array", "(", "kwargs", ".", "keys", "(", ")", ")", ",", "c_str_array", "(", "kwargs", ".", "values", "(", ")", ")", ")", ")", "if", "n_mutate_vars", "==", "1", ":", "return", "ndargs", "[", "0", "]", "else", ":", "return", "ndargs", "[", ":", "n_mutate_vars", "]", "# pylint: disable=invalid-slice-index", "# End of function declaration", "ret_function", "=", "generic_torch_function", "ret_function", ".", "__name__", "=", "func_name", "[", "4", ":", "]", "ret_function", ".", "__doc__", "=", "doc_str", "return", "ret_function" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/torch.py#L37-L163
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/datetime.py
python
timedelta.days
(self)
return self._days
days
days
[ "days" ]
def days(self): """days""" return self._days
[ "def", "days", "(", "self", ")", ":", "return", "self", ".", "_days" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/datetime.py#L607-L609
deepmodeling/deepmd-kit
159e45d248b0429844fb6a8cb3b3a201987c8d79
deepmd/fit/ener.py
python
EnerFitting.compute_input_stats
(self, all_stat : dict, protection : float = 1e-2)
Compute the input statistics Parameters ---------- all_stat if numb_fparam > 0 must have all_stat['fparam'] if numb_aparam > 0 must have all_stat['aparam'] can be prepared by model.make_stat_input protection Divided-by-zero protection
Compute the input statistics
[ "Compute", "the", "input", "statistics" ]
def compute_input_stats(self, all_stat : dict, protection : float = 1e-2) -> None: """ Compute the input statistics Parameters ---------- all_stat if numb_fparam > 0 must have all_stat['fparam'] if numb_aparam > 0 must have all_stat['aparam'] can be prepared by model.make_stat_input protection Divided-by-zero protection """ # stat fparam if self.numb_fparam > 0: cat_data = np.concatenate(all_stat['fparam'], axis = 0) cat_data = np.reshape(cat_data, [-1, self.numb_fparam]) self.fparam_avg = np.average(cat_data, axis = 0) self.fparam_std = np.std(cat_data, axis = 0) for ii in range(self.fparam_std.size): if self.fparam_std[ii] < protection: self.fparam_std[ii] = protection self.fparam_inv_std = 1./self.fparam_std # stat aparam if self.numb_aparam > 0: sys_sumv = [] sys_sumv2 = [] sys_sumn = [] for ss_ in all_stat['aparam'] : ss = np.reshape(ss_, [-1, self.numb_aparam]) sys_sumv.append(np.sum(ss, axis = 0)) sys_sumv2.append(np.sum(np.multiply(ss, ss), axis = 0)) sys_sumn.append(ss.shape[0]) sumv = np.sum(sys_sumv, axis = 0) sumv2 = np.sum(sys_sumv2, axis = 0) sumn = np.sum(sys_sumn) self.aparam_avg = (sumv)/sumn self.aparam_std = self._compute_std(sumv2, sumv, sumn) for ii in range(self.aparam_std.size): if self.aparam_std[ii] < protection: self.aparam_std[ii] = protection self.aparam_inv_std = 1./self.aparam_std
[ "def", "compute_input_stats", "(", "self", ",", "all_stat", ":", "dict", ",", "protection", ":", "float", "=", "1e-2", ")", "->", "None", ":", "# stat fparam", "if", "self", ".", "numb_fparam", ">", "0", ":", "cat_data", "=", "np", ".", "concatenate", "(", "all_stat", "[", "'fparam'", "]", ",", "axis", "=", "0", ")", "cat_data", "=", "np", ".", "reshape", "(", "cat_data", ",", "[", "-", "1", ",", "self", ".", "numb_fparam", "]", ")", "self", ".", "fparam_avg", "=", "np", ".", "average", "(", "cat_data", ",", "axis", "=", "0", ")", "self", ".", "fparam_std", "=", "np", ".", "std", "(", "cat_data", ",", "axis", "=", "0", ")", "for", "ii", "in", "range", "(", "self", ".", "fparam_std", ".", "size", ")", ":", "if", "self", ".", "fparam_std", "[", "ii", "]", "<", "protection", ":", "self", ".", "fparam_std", "[", "ii", "]", "=", "protection", "self", ".", "fparam_inv_std", "=", "1.", "/", "self", ".", "fparam_std", "# stat aparam", "if", "self", ".", "numb_aparam", ">", "0", ":", "sys_sumv", "=", "[", "]", "sys_sumv2", "=", "[", "]", "sys_sumn", "=", "[", "]", "for", "ss_", "in", "all_stat", "[", "'aparam'", "]", ":", "ss", "=", "np", ".", "reshape", "(", "ss_", ",", "[", "-", "1", ",", "self", ".", "numb_aparam", "]", ")", "sys_sumv", ".", "append", "(", "np", ".", "sum", "(", "ss", ",", "axis", "=", "0", ")", ")", "sys_sumv2", ".", "append", "(", "np", ".", "sum", "(", "np", ".", "multiply", "(", "ss", ",", "ss", ")", ",", "axis", "=", "0", ")", ")", "sys_sumn", ".", "append", "(", "ss", ".", "shape", "[", "0", "]", ")", "sumv", "=", "np", ".", "sum", "(", "sys_sumv", ",", "axis", "=", "0", ")", "sumv2", "=", "np", ".", "sum", "(", "sys_sumv2", ",", "axis", "=", "0", ")", "sumn", "=", "np", ".", "sum", "(", "sys_sumn", ")", "self", ".", "aparam_avg", "=", "(", "sumv", ")", "/", "sumn", "self", ".", "aparam_std", "=", "self", ".", "_compute_std", "(", "sumv2", ",", "sumv", ",", "sumn", ")", "for", "ii", "in", "range", "(", "self", ".", "aparam_std", ".", "size", ")", ":", "if", "self", ".", "aparam_std", "[", "ii", "]", "<", "protection", ":", "self", ".", "aparam_std", "[", "ii", "]", "=", "protection", "self", ".", "aparam_inv_std", "=", "1.", "/", "self", ".", "aparam_std" ]
https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/fit/ener.py#L204-L247
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/datetimelike.py
python
validate_inferred_freq
(freq, inferred_freq, freq_infer)
return freq, freq_infer
If the user passes a freq and another freq is inferred from passed data, require that they match. Parameters ---------- freq : DateOffset or None inferred_freq : DateOffset or None freq_infer : bool Returns ------- freq : DateOffset or None freq_infer : bool Notes ----- We assume at this point that `maybe_infer_freq` has been called, so `freq` is either a DateOffset object or None.
If the user passes a freq and another freq is inferred from passed data, require that they match.
[ "If", "the", "user", "passes", "a", "freq", "and", "another", "freq", "is", "inferred", "from", "passed", "data", "require", "that", "they", "match", "." ]
def validate_inferred_freq(freq, inferred_freq, freq_infer): """ If the user passes a freq and another freq is inferred from passed data, require that they match. Parameters ---------- freq : DateOffset or None inferred_freq : DateOffset or None freq_infer : bool Returns ------- freq : DateOffset or None freq_infer : bool Notes ----- We assume at this point that `maybe_infer_freq` has been called, so `freq` is either a DateOffset object or None. """ if inferred_freq is not None: if freq is not None and freq != inferred_freq: raise ValueError( f"Inferred frequency {inferred_freq} from passed " "values does not conform to passed frequency " f"{freq.freqstr}" ) elif freq is None: freq = inferred_freq freq_infer = False return freq, freq_infer
[ "def", "validate_inferred_freq", "(", "freq", ",", "inferred_freq", ",", "freq_infer", ")", ":", "if", "inferred_freq", "is", "not", "None", ":", "if", "freq", "is", "not", "None", "and", "freq", "!=", "inferred_freq", ":", "raise", "ValueError", "(", "f\"Inferred frequency {inferred_freq} from passed \"", "\"values does not conform to passed frequency \"", "f\"{freq.freqstr}\"", ")", "elif", "freq", "is", "None", ":", "freq", "=", "inferred_freq", "freq_infer", "=", "False", "return", "freq", ",", "freq_infer" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/datetimelike.py#L1655-L1687
potassco/clingo
e0c91d8f95cc28de1c480a871f9c97c30de83d40
.github/conda.py
python
get_build_number
(channels, version)
return build_number + 1
Get the next build number.
Get the next build number.
[ "Get", "the", "next", "build", "number", "." ]
def get_build_number(channels, version): ''' Get the next build number. ''' try: pkgs = json.loads(subprocess.check_output(['conda', 'search', '--json', '-c', channels[0], NAME])) except subprocess.CalledProcessError: pkgs = {NAME: []} build_number = -1 for pkg in pkgs.get(NAME, []): if pkg['channel'].find(channels[0]) >= 0 and pkg["version"] == version: build_number = max(build_number, pkg['build_number']) return build_number + 1
[ "def", "get_build_number", "(", "channels", ",", "version", ")", ":", "try", ":", "pkgs", "=", "json", ".", "loads", "(", "subprocess", ".", "check_output", "(", "[", "'conda'", ",", "'search'", ",", "'--json'", ",", "'-c'", ",", "channels", "[", "0", "]", ",", "NAME", "]", ")", ")", "except", "subprocess", ".", "CalledProcessError", ":", "pkgs", "=", "{", "NAME", ":", "[", "]", "}", "build_number", "=", "-", "1", "for", "pkg", "in", "pkgs", ".", "get", "(", "NAME", ",", "[", "]", ")", ":", "if", "pkg", "[", "'channel'", "]", ".", "find", "(", "channels", "[", "0", "]", ")", ">=", "0", "and", "pkg", "[", "\"version\"", "]", "==", "version", ":", "build_number", "=", "max", "(", "build_number", ",", "pkg", "[", "'build_number'", "]", ")", "return", "build_number", "+", "1" ]
https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/.github/conda.py#L14-L29
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
ExprRef.num_args
(self)
return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
Return the number of arguments of a Z3 application. >>> a = Int('a') >>> b = Int('b') >>> (a + b).num_args() 2 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.num_args() 3
Return the number of arguments of a Z3 application.
[ "Return", "the", "number", "of", "arguments", "of", "a", "Z3", "application", "." ]
def num_args(self): """Return the number of arguments of a Z3 application. >>> a = Int('a') >>> b = Int('b') >>> (a + b).num_args() 2 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) >>> t = f(a, b, 0) >>> t.num_args() 3 """ if z3_debug(): _z3_assert(is_app(self), "Z3 application expected") return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
[ "def", "num_args", "(", "self", ")", ":", "if", "z3_debug", "(", ")", ":", "_z3_assert", "(", "is_app", "(", "self", ")", ",", "\"Z3 application expected\"", ")", "return", "int", "(", "Z3_get_app_num_args", "(", "self", ".", "ctx_ref", "(", ")", ",", "self", ".", "as_ast", "(", ")", ")", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L1057-L1071
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/gradients_impl.py
python
_IndexedSlicesToTensor
(value, dtype=None, name=None, as_ref=False)
return math_ops.unsorted_segment_sum( value.values, value.indices, value.dense_shape[0], name=name)
Converts an IndexedSlices object `value` to a Tensor. NOTE(mrry): This function is potentially expensive. Args: value: An ops.IndexedSlices object. dtype: The dtype of the Tensor to be returned. name: Optional name to use for the returned Tensor. as_ref: True if a ref is requested. Returns: A dense Tensor representing the values in the given IndexedSlices. Raises: ValueError: If the IndexedSlices does not have the same dtype.
Converts an IndexedSlices object `value` to a Tensor.
[ "Converts", "an", "IndexedSlices", "object", "value", "to", "a", "Tensor", "." ]
def _IndexedSlicesToTensor(value, dtype=None, name=None, as_ref=False): """Converts an IndexedSlices object `value` to a Tensor. NOTE(mrry): This function is potentially expensive. Args: value: An ops.IndexedSlices object. dtype: The dtype of the Tensor to be returned. name: Optional name to use for the returned Tensor. as_ref: True if a ref is requested. Returns: A dense Tensor representing the values in the given IndexedSlices. Raises: ValueError: If the IndexedSlices does not have the same dtype. """ _ = as_ref if dtype and not dtype.is_compatible_with(value.dtype): raise ValueError( "Tensor conversion requested dtype %s for IndexedSlices with dtype %s" % (dtype.name, value.dtype.name)) if value.dense_shape is None: raise ValueError( "Tensor conversion requested for IndexedSlices without dense_shape: %s" % str(value)) # TODO(mrry): Consider adding static shape information to # IndexedSlices, to avoid using numpy here. dense_shape_value = tensor_util.constant_value(value.dense_shape) if dense_shape_value is not None: num_elements = np.prod(dense_shape_value) if num_elements >= _LARGE_SPARSE_NUM_ELEMENTS: warnings.warn( "Converting sparse IndexedSlices to a dense Tensor with %d elements. " "This may consume a large amount of memory." % num_elements) else: warnings.warn( "Converting sparse IndexedSlices to a dense Tensor of unknown shape. " "This may consume a large amount of memory.") return math_ops.unsorted_segment_sum( value.values, value.indices, value.dense_shape[0], name=name)
[ "def", "_IndexedSlicesToTensor", "(", "value", ",", "dtype", "=", "None", ",", "name", "=", "None", ",", "as_ref", "=", "False", ")", ":", "_", "=", "as_ref", "if", "dtype", "and", "not", "dtype", ".", "is_compatible_with", "(", "value", ".", "dtype", ")", ":", "raise", "ValueError", "(", "\"Tensor conversion requested dtype %s for IndexedSlices with dtype %s\"", "%", "(", "dtype", ".", "name", ",", "value", ".", "dtype", ".", "name", ")", ")", "if", "value", ".", "dense_shape", "is", "None", ":", "raise", "ValueError", "(", "\"Tensor conversion requested for IndexedSlices without dense_shape: %s\"", "%", "str", "(", "value", ")", ")", "# TODO(mrry): Consider adding static shape information to", "# IndexedSlices, to avoid using numpy here.", "dense_shape_value", "=", "tensor_util", ".", "constant_value", "(", "value", ".", "dense_shape", ")", "if", "dense_shape_value", "is", "not", "None", ":", "num_elements", "=", "np", ".", "prod", "(", "dense_shape_value", ")", "if", "num_elements", ">=", "_LARGE_SPARSE_NUM_ELEMENTS", ":", "warnings", ".", "warn", "(", "\"Converting sparse IndexedSlices to a dense Tensor with %d elements. \"", "\"This may consume a large amount of memory.\"", "%", "num_elements", ")", "else", ":", "warnings", ".", "warn", "(", "\"Converting sparse IndexedSlices to a dense Tensor of unknown shape. \"", "\"This may consume a large amount of memory.\"", ")", "return", "math_ops", ".", "unsorted_segment_sum", "(", "value", ".", "values", ",", "value", ".", "indices", ",", "value", ".", "dense_shape", "[", "0", "]", ",", "name", "=", "name", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/gradients_impl.py#L59-L99
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftutils/init_tools.py
python
init_toolbar
(workbench, toolbar, cmd_list)
Initialize a toolbar. Parameters ---------- workbench: Gui.Workbench The workbench. The commands from cmd_list must be available. toolbar: string The name of the toolbar. cmd_list: list of strings or list of strings and tuples See f.e. the return value of get_draft_drawing_commands.
Initialize a toolbar.
[ "Initialize", "a", "toolbar", "." ]
def init_toolbar(workbench, toolbar, cmd_list): """Initialize a toolbar. Parameters ---------- workbench: Gui.Workbench The workbench. The commands from cmd_list must be available. toolbar: string The name of the toolbar. cmd_list: list of strings or list of strings and tuples See f.e. the return value of get_draft_drawing_commands. """ for cmd in cmd_list: if isinstance(cmd, tuple): if len(cmd) == 1: workbench.appendToolbar(toolbar, [cmd[0]]) else: workbench.appendToolbar(toolbar, [cmd])
[ "def", "init_toolbar", "(", "workbench", ",", "toolbar", ",", "cmd_list", ")", ":", "for", "cmd", "in", "cmd_list", ":", "if", "isinstance", "(", "cmd", ",", "tuple", ")", ":", "if", "len", "(", "cmd", ")", "==", "1", ":", "workbench", ".", "appendToolbar", "(", "toolbar", ",", "[", "cmd", "[", "0", "]", "]", ")", "else", ":", "workbench", ".", "appendToolbar", "(", "toolbar", ",", "[", "cmd", "]", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftutils/init_tools.py#L205-L224
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/util/options.py
python
merge_options
(*options_list)
return result
Merges the given options, returning the result as a new options object. The input arguments are expected to have a matching type that derives from `OptionsBase` (and thus each represent a set of options). The method outputs an object of the same type created by merging the sets of options represented by the input arguments. The sets of options can be merged as long as there does not exist an option with different non-default values. If an option is an instance of `OptionsBase` itself, then this method is applied recursively to the set of options represented by this option. Args: *options_list: options to merge Raises: TypeError: if the input arguments are incompatible or not derived from `OptionsBase` ValueError: if the given options cannot be merged Returns: A new options object which is the result of merging the given options.
Merges the given options, returning the result as a new options object.
[ "Merges", "the", "given", "options", "returning", "the", "result", "as", "a", "new", "options", "object", "." ]
def merge_options(*options_list): """Merges the given options, returning the result as a new options object. The input arguments are expected to have a matching type that derives from `OptionsBase` (and thus each represent a set of options). The method outputs an object of the same type created by merging the sets of options represented by the input arguments. The sets of options can be merged as long as there does not exist an option with different non-default values. If an option is an instance of `OptionsBase` itself, then this method is applied recursively to the set of options represented by this option. Args: *options_list: options to merge Raises: TypeError: if the input arguments are incompatible or not derived from `OptionsBase` ValueError: if the given options cannot be merged Returns: A new options object which is the result of merging the given options. """ if len(options_list) < 1: raise ValueError("At least one options should be provided") result_type = type(options_list[0]) for options in options_list: if not isinstance(options, result_type): raise TypeError("Incompatible options type: %r vs %r" % (type(options), result_type)) if not isinstance(options_list[0], OptionsBase): raise TypeError("The inputs should inherit from `OptionsBase`") default_options = result_type() result = result_type() for options in options_list: # Iterate over all set options and merge the into the result. for name in options._options: # pylint: disable=protected-access this = getattr(result, name) that = getattr(options, name) default = getattr(default_options, name) if that == default: continue elif this == default: setattr(result, name, that) elif isinstance(this, OptionsBase): setattr(result, name, merge_options(this, that)) elif this != that: raise ValueError( "Cannot merge incompatible values (%r and %r) of option: %s" % (this, that, name)) return result
[ "def", "merge_options", "(", "*", "options_list", ")", ":", "if", "len", "(", "options_list", ")", "<", "1", ":", "raise", "ValueError", "(", "\"At least one options should be provided\"", ")", "result_type", "=", "type", "(", "options_list", "[", "0", "]", ")", "for", "options", "in", "options_list", ":", "if", "not", "isinstance", "(", "options", ",", "result_type", ")", ":", "raise", "TypeError", "(", "\"Incompatible options type: %r vs %r\"", "%", "(", "type", "(", "options", ")", ",", "result_type", ")", ")", "if", "not", "isinstance", "(", "options_list", "[", "0", "]", ",", "OptionsBase", ")", ":", "raise", "TypeError", "(", "\"The inputs should inherit from `OptionsBase`\"", ")", "default_options", "=", "result_type", "(", ")", "result", "=", "result_type", "(", ")", "for", "options", "in", "options_list", ":", "# Iterate over all set options and merge the into the result.", "for", "name", "in", "options", ".", "_options", ":", "# pylint: disable=protected-access", "this", "=", "getattr", "(", "result", ",", "name", ")", "that", "=", "getattr", "(", "options", ",", "name", ")", "default", "=", "getattr", "(", "default_options", ",", "name", ")", "if", "that", "==", "default", ":", "continue", "elif", "this", "==", "default", ":", "setattr", "(", "result", ",", "name", ",", "that", ")", "elif", "isinstance", "(", "this", ",", "OptionsBase", ")", ":", "setattr", "(", "result", ",", "name", ",", "merge_options", "(", "this", ",", "that", ")", ")", "elif", "this", "!=", "that", ":", "raise", "ValueError", "(", "\"Cannot merge incompatible values (%r and %r) of option: %s\"", "%", "(", "this", ",", "that", ",", "name", ")", ")", "return", "result" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/data/util/options.py#L89-L144
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/model_pruning/python/pruning_utils.py
python
factorized_pool
(input_tensor, window_shape, pooling_type, strides, padding, name=None)
return array_ops.squeeze( array_ops.transpose(width_pooling, perm=[0, 1, 3, 2]), axis=[0, 1])
Performs m x n pooling through a combination of 1xm and 1xn pooling. Args: input_tensor: Input tensor. Must be rank 2 window_shape: Pooling window shape pooling_type: Either 'MAX' or 'AVG' strides: The stride of the pooling window padding: 'SAME' or 'VALID'. name: Name of the op Returns: A rank 2 tensor containing the pooled output Raises: ValueError: if the input tensor is not rank 2
Performs m x n pooling through a combination of 1xm and 1xn pooling.
[ "Performs", "m", "x", "n", "pooling", "through", "a", "combination", "of", "1xm", "and", "1xn", "pooling", "." ]
def factorized_pool(input_tensor, window_shape, pooling_type, strides, padding, name=None): """Performs m x n pooling through a combination of 1xm and 1xn pooling. Args: input_tensor: Input tensor. Must be rank 2 window_shape: Pooling window shape pooling_type: Either 'MAX' or 'AVG' strides: The stride of the pooling window padding: 'SAME' or 'VALID'. name: Name of the op Returns: A rank 2 tensor containing the pooled output Raises: ValueError: if the input tensor is not rank 2 """ if input_tensor.get_shape().ndims != 2: raise ValueError('factorized_pool() accepts tensors of rank 2 only') [height, width] = input_tensor.get_shape() with ops.name_scope(name, 'factorized_pool'): input_tensor_aligned = array_ops.reshape( input_tensor, [1, 1, height, width], name=input_tensor.op.name + '_aligned') height_pooling = nn_ops.pool( input_tensor_aligned, window_shape=[1, window_shape[0]], pooling_type=pooling_type, strides=[1, strides[0]], padding=padding) swap_height_width = array_ops.transpose(height_pooling, perm=[0, 1, 3, 2]) width_pooling = nn_ops.pool( swap_height_width, window_shape=[1, window_shape[1]], pooling_type=pooling_type, strides=[1, strides[1]], padding=padding) return array_ops.squeeze( array_ops.transpose(width_pooling, perm=[0, 1, 3, 2]), axis=[0, 1])
[ "def", "factorized_pool", "(", "input_tensor", ",", "window_shape", ",", "pooling_type", ",", "strides", ",", "padding", ",", "name", "=", "None", ")", ":", "if", "input_tensor", ".", "get_shape", "(", ")", ".", "ndims", "!=", "2", ":", "raise", "ValueError", "(", "'factorized_pool() accepts tensors of rank 2 only'", ")", "[", "height", ",", "width", "]", "=", "input_tensor", ".", "get_shape", "(", ")", "with", "ops", ".", "name_scope", "(", "name", ",", "'factorized_pool'", ")", ":", "input_tensor_aligned", "=", "array_ops", ".", "reshape", "(", "input_tensor", ",", "[", "1", ",", "1", ",", "height", ",", "width", "]", ",", "name", "=", "input_tensor", ".", "op", ".", "name", "+", "'_aligned'", ")", "height_pooling", "=", "nn_ops", ".", "pool", "(", "input_tensor_aligned", ",", "window_shape", "=", "[", "1", ",", "window_shape", "[", "0", "]", "]", ",", "pooling_type", "=", "pooling_type", ",", "strides", "=", "[", "1", ",", "strides", "[", "0", "]", "]", ",", "padding", "=", "padding", ")", "swap_height_width", "=", "array_ops", ".", "transpose", "(", "height_pooling", ",", "perm", "=", "[", "0", ",", "1", ",", "3", ",", "2", "]", ")", "width_pooling", "=", "nn_ops", ".", "pool", "(", "swap_height_width", ",", "window_shape", "=", "[", "1", ",", "window_shape", "[", "1", "]", "]", ",", "pooling_type", "=", "pooling_type", ",", "strides", "=", "[", "1", ",", "strides", "[", "1", "]", "]", ",", "padding", "=", "padding", ")", "return", "array_ops", ".", "squeeze", "(", "array_ops", ".", "transpose", "(", "width_pooling", ",", "perm", "=", "[", "0", ",", "1", ",", "3", ",", "2", "]", ")", ",", "axis", "=", "[", "0", ",", "1", "]", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/model_pruning/python/pruning_utils.py#L164-L211
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
Canvas.tag_raise
(self, *args)
Raise an item TAGORID given in ARGS (optional above another item).
Raise an item TAGORID given in ARGS (optional above another item).
[ "Raise", "an", "item", "TAGORID", "given", "in", "ARGS", "(", "optional", "above", "another", "item", ")", "." ]
def tag_raise(self, *args): """Raise an item TAGORID given in ARGS (optional above another item).""" self.tk.call((self._w, 'raise') + args)
[ "def", "tag_raise", "(", "self", ",", "*", "args", ")", ":", "self", ".", "tk", ".", "call", "(", "(", "self", ".", "_w", ",", "'raise'", ")", "+", "args", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L2599-L2602
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/MooseDocs/extensions/floats.py
python
caption_settings
()
return settings
Return settings necessary for captions.
Return settings necessary for captions.
[ "Return", "settings", "necessary", "for", "captions", "." ]
def caption_settings(): """Return settings necessary for captions.""" settings = dict() settings['caption'] = (None, "The caption text for the float object.") settings['prefix'] = (None, "The numbered caption label to include prior to the caption text.") return settings
[ "def", "caption_settings", "(", ")", ":", "settings", "=", "dict", "(", ")", "settings", "[", "'caption'", "]", "=", "(", "None", ",", "\"The caption text for the float object.\"", ")", "settings", "[", "'prefix'", "]", "=", "(", "None", ",", "\"The numbered caption label to include prior to the caption text.\"", ")", "return", "settings" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/MooseDocs/extensions/floats.py#L53-L58
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/lmbr_aws/cleanup_utils/cleanup_utils.py
python
wait_for
(fn, attempts, interval, timeout_exception=None)
A custom waiter for AWS services that do not provide their own waiter. Uses a default attempt and interval which can be overridden. Continues to execute a given function until the function returns True. Raises an exception if the function does not return True before the timeout :param fn: The target function to execute :param attempts: The set amount of attempts before raising an exception :param timeout_exception: The exception to raise. An assertion error is raise by default :param interval: The time to wait between subsequent function calls
A custom waiter for AWS services that do not provide their own waiter. Uses a default attempt and interval which can be overridden. Continues to execute a given function until the function returns True. Raises an exception if the function does not return True before the timeout :param fn: The target function to execute :param attempts: The set amount of attempts before raising an exception :param timeout_exception: The exception to raise. An assertion error is raise by default :param interval: The time to wait between subsequent function calls
[ "A", "custom", "waiter", "for", "AWS", "services", "that", "do", "not", "provide", "their", "own", "waiter", ".", "Uses", "a", "default", "attempt", "and", "interval", "which", "can", "be", "overridden", ".", "Continues", "to", "execute", "a", "given", "function", "until", "the", "function", "returns", "True", ".", "Raises", "an", "exception", "if", "the", "function", "does", "not", "return", "True", "before", "the", "timeout", ":", "param", "fn", ":", "The", "target", "function", "to", "execute", ":", "param", "attempts", ":", "The", "set", "amount", "of", "attempts", "before", "raising", "an", "exception", ":", "param", "timeout_exception", ":", "The", "exception", "to", "raise", ".", "An", "assertion", "error", "is", "raise", "by", "default", ":", "param", "interval", ":", "The", "time", "to", "wait", "between", "subsequent", "function", "calls" ]
def wait_for(fn, attempts, interval, timeout_exception=None): """ A custom waiter for AWS services that do not provide their own waiter. Uses a default attempt and interval which can be overridden. Continues to execute a given function until the function returns True. Raises an exception if the function does not return True before the timeout :param fn: The target function to execute :param attempts: The set amount of attempts before raising an exception :param timeout_exception: The exception to raise. An assertion error is raise by default :param interval: The time to wait between subsequent function calls """ attempt_counter = 0 while attempt_counter < attempts: if fn(): return time.sleep(interval) attempt_counter += 1 if timeout_exception is not None: raise timeout_exception else: assert False, 'Timeout waiting for {}() after {} attempts.'.format(fn.__name__, attempts)
[ "def", "wait_for", "(", "fn", ",", "attempts", ",", "interval", ",", "timeout_exception", "=", "None", ")", ":", "attempt_counter", "=", "0", "while", "attempt_counter", "<", "attempts", ":", "if", "fn", "(", ")", ":", "return", "time", ".", "sleep", "(", "interval", ")", "attempt_counter", "+=", "1", "if", "timeout_exception", "is", "not", "None", ":", "raise", "timeout_exception", "else", ":", "assert", "False", ",", "'Timeout waiting for {}() after {} attempts.'", ".", "format", "(", "fn", ".", "__name__", ",", "attempts", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/lmbr_aws/cleanup_utils/cleanup_utils.py#L34-L53
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py
python
_IPAddressBase.exploded
(self)
return self._explode_shorthand_ip_string()
Return the longhand version of the IP address as a string.
Return the longhand version of the IP address as a string.
[ "Return", "the", "longhand", "version", "of", "the", "IP", "address", "as", "a", "string", "." ]
def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string()
[ "def", "exploded", "(", "self", ")", ":", "return", "self", ".", "_explode_shorthand_ip_string", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/ipaddress.py#L392-L394
bumptop/BumpTop
466d23597a07ae738f4265262fa01087fc6e257c
trunk/win/Source/Includes/QtIncludes/src/3rdparty/freetype/src/tools/docmaker/content.py
python
ContentProcessor.set_section
( self, section_name )
set current section during parsing
set current section during parsing
[ "set", "current", "section", "during", "parsing" ]
def set_section( self, section_name ): """set current section during parsing""" if not self.sections.has_key( section_name ): section = DocSection( section_name ) self.sections[section_name] = section self.section = section else: self.section = self.sections[section_name]
[ "def", "set_section", "(", "self", ",", "section_name", ")", ":", "if", "not", "self", ".", "sections", ".", "has_key", "(", "section_name", ")", ":", "section", "=", "DocSection", "(", "section_name", ")", "self", ".", "sections", "[", "section_name", "]", "=", "section", "self", ".", "section", "=", "section", "else", ":", "self", ".", "section", "=", "self", ".", "sections", "[", "section_name", "]" ]
https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/Includes/QtIncludes/src/3rdparty/freetype/src/tools/docmaker/content.py#L353-L360
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/third_party/jedi/jedi/parser/representation.py
python
Name.get_code
(self)
return ".".join(self.names)
Returns the names in a full string format
Returns the names in a full string format
[ "Returns", "the", "names", "in", "a", "full", "string", "format" ]
def get_code(self): """ Returns the names in a full string format """ return ".".join(self.names)
[ "def", "get_code", "(", "self", ")", ":", "return", "\".\"", ".", "join", "(", "self", ".", "names", ")" ]
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/jedi/jedi/parser/representation.py#L1403-L1405
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/sparse/coo.py
python
coo_matrix._check
(self)
Checks data structure for consistency
Checks data structure for consistency
[ "Checks", "data", "structure", "for", "consistency" ]
def _check(self): """ Checks data structure for consistency """ # index arrays should have integer data types if self.row.dtype.kind != 'i': warn("row index array has non-integer dtype (%s) " % self.row.dtype.name) if self.col.dtype.kind != 'i': warn("col index array has non-integer dtype (%s) " % self.col.dtype.name) idx_dtype = get_index_dtype(maxval=max(self.shape)) self.row = np.asarray(self.row, dtype=idx_dtype) self.col = np.asarray(self.col, dtype=idx_dtype) self.data = to_native(self.data) if self.nnz > 0: if self.row.max() >= self.shape[0]: raise ValueError('row index exceeds matrix dimensions') if self.col.max() >= self.shape[1]: raise ValueError('column index exceeds matrix dimensions') if self.row.min() < 0: raise ValueError('negative row index found') if self.col.min() < 0: raise ValueError('negative column index found')
[ "def", "_check", "(", "self", ")", ":", "# index arrays should have integer data types", "if", "self", ".", "row", ".", "dtype", ".", "kind", "!=", "'i'", ":", "warn", "(", "\"row index array has non-integer dtype (%s) \"", "%", "self", ".", "row", ".", "dtype", ".", "name", ")", "if", "self", ".", "col", ".", "dtype", ".", "kind", "!=", "'i'", ":", "warn", "(", "\"col index array has non-integer dtype (%s) \"", "%", "self", ".", "col", ".", "dtype", ".", "name", ")", "idx_dtype", "=", "get_index_dtype", "(", "maxval", "=", "max", "(", "self", ".", "shape", ")", ")", "self", ".", "row", "=", "np", ".", "asarray", "(", "self", ".", "row", ",", "dtype", "=", "idx_dtype", ")", "self", ".", "col", "=", "np", ".", "asarray", "(", "self", ".", "col", ",", "dtype", "=", "idx_dtype", ")", "self", ".", "data", "=", "to_native", "(", "self", ".", "data", ")", "if", "self", ".", "nnz", ">", "0", ":", "if", "self", ".", "row", ".", "max", "(", ")", ">=", "self", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "'row index exceeds matrix dimensions'", ")", "if", "self", ".", "col", ".", "max", "(", ")", ">=", "self", ".", "shape", "[", "1", "]", ":", "raise", "ValueError", "(", "'column index exceeds matrix dimensions'", ")", "if", "self", ".", "row", ".", "min", "(", ")", "<", "0", ":", "raise", "ValueError", "(", "'negative row index found'", ")", "if", "self", ".", "col", ".", "min", "(", ")", "<", "0", ":", "raise", "ValueError", "(", "'negative column index found'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/sparse/coo.py#L212-L236
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
buildscripts/resmoke.py
python
_dump_suite_config
(suite, logging_config)
return "\n".join(sb)
Returns a string that represents the YAML configuration of a suite. TODO: include the "options" key in the result
Returns a string that represents the YAML configuration of a suite.
[ "Returns", "a", "string", "that", "represents", "the", "YAML", "configuration", "of", "a", "suite", "." ]
def _dump_suite_config(suite, logging_config): """ Returns a string that represents the YAML configuration of a suite. TODO: include the "options" key in the result """ sb = [] sb.append("YAML configuration of suite %s" % (suite.get_name())) sb.append(resmokelib.utils.dump_yaml({"selector": suite.get_selector_config()})) sb.append("") sb.append(resmokelib.utils.dump_yaml({"executor": suite.get_executor_config()})) sb.append("") sb.append(resmokelib.utils.dump_yaml({"logging": logging_config})) return "\n".join(sb)
[ "def", "_dump_suite_config", "(", "suite", ",", "logging_config", ")", ":", "sb", "=", "[", "]", "sb", ".", "append", "(", "\"YAML configuration of suite %s\"", "%", "(", "suite", ".", "get_name", "(", ")", ")", ")", "sb", ".", "append", "(", "resmokelib", ".", "utils", ".", "dump_yaml", "(", "{", "\"selector\"", ":", "suite", ".", "get_selector_config", "(", ")", "}", ")", ")", "sb", ".", "append", "(", "\"\"", ")", "sb", ".", "append", "(", "resmokelib", ".", "utils", ".", "dump_yaml", "(", "{", "\"executor\"", ":", "suite", ".", "get_executor_config", "(", ")", "}", ")", ")", "sb", ".", "append", "(", "\"\"", ")", "sb", ".", "append", "(", "resmokelib", ".", "utils", ".", "dump_yaml", "(", "{", "\"logging\"", ":", "logging_config", "}", ")", ")", "return", "\"\\n\"", ".", "join", "(", "sb", ")" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/resmoke.py#L101-L115
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/email/_parseaddr.py
python
AddrlistClass.getquote
(self)
return self.getdelimited('"', '"\r', False)
Get a quote-delimited fragment from self's field.
Get a quote-delimited fragment from self's field.
[ "Get", "a", "quote", "-", "delimited", "fragment", "from", "self", "s", "field", "." ]
def getquote(self): """Get a quote-delimited fragment from self's field.""" return self.getdelimited('"', '"\r', False)
[ "def", "getquote", "(", "self", ")", ":", "return", "self", ".", "getdelimited", "(", "'\"'", ",", "'\"\\r'", ",", "False", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/_parseaddr.py#L453-L455
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/lib/_iotools.py
python
LineSplitter.autostrip
(self, method)
return lambda input: [_.strip() for _ in method(input)]
Wrapper to strip each member of the output of `method`. Parameters ---------- method : function Function that takes a single argument and returns a sequence of strings. Returns ------- wrapped : function The result of wrapping `method`. `wrapped` takes a single input argument and returns a list of strings that are stripped of white-space.
Wrapper to strip each member of the output of `method`.
[ "Wrapper", "to", "strip", "each", "member", "of", "the", "output", "of", "method", "." ]
def autostrip(self, method): """ Wrapper to strip each member of the output of `method`. Parameters ---------- method : function Function that takes a single argument and returns a sequence of strings. Returns ------- wrapped : function The result of wrapping `method`. `wrapped` takes a single input argument and returns a list of strings that are stripped of white-space. """ return lambda input: [_.strip() for _ in method(input)]
[ "def", "autostrip", "(", "self", ",", "method", ")", ":", "return", "lambda", "input", ":", "[", "_", ".", "strip", "(", ")", "for", "_", "in", "method", "(", "input", ")", "]" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/_iotools.py#L161-L179
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pep517/wrappers.py
python
Pep517HookCaller.prepare_metadata_for_build_wheel
( self, metadata_directory, config_settings=None)
return self._call_hook('prepare_metadata_for_build_wheel', { 'metadata_directory': abspath(metadata_directory), 'config_settings': config_settings, })
Prepare a *.dist-info folder with metadata for this project. Returns the name of the newly created folder. If the build backend defines a hook with this name, it will be called in a subprocess. If not, the backend will be asked to build a wheel, and the dist-info extracted from that.
Prepare a *.dist-info folder with metadata for this project.
[ "Prepare", "a", "*", ".", "dist", "-", "info", "folder", "with", "metadata", "for", "this", "project", "." ]
def prepare_metadata_for_build_wheel( self, metadata_directory, config_settings=None): """Prepare a *.dist-info folder with metadata for this project. Returns the name of the newly created folder. If the build backend defines a hook with this name, it will be called in a subprocess. If not, the backend will be asked to build a wheel, and the dist-info extracted from that. """ return self._call_hook('prepare_metadata_for_build_wheel', { 'metadata_directory': abspath(metadata_directory), 'config_settings': config_settings, })
[ "def", "prepare_metadata_for_build_wheel", "(", "self", ",", "metadata_directory", ",", "config_settings", "=", "None", ")", ":", "return", "self", ".", "_call_hook", "(", "'prepare_metadata_for_build_wheel'", ",", "{", "'metadata_directory'", ":", "abspath", "(", "metadata_directory", ")", ",", "'config_settings'", ":", "config_settings", ",", "}", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pep517/wrappers.py#L74-L87
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Pygments/py3/pygments/lexers/textfmts.py
python
HttpLexer.get_tokens_unprocessed
(self, text, stack=('root',))
return RegexLexer.get_tokens_unprocessed(self, text, stack)
Reset the content-type state.
Reset the content-type state.
[ "Reset", "the", "content", "-", "type", "state", "." ]
def get_tokens_unprocessed(self, text, stack=('root',)): """Reset the content-type state.""" self.content_type = None return RegexLexer.get_tokens_unprocessed(self, text, stack)
[ "def", "get_tokens_unprocessed", "(", "self", ",", "text", ",", "stack", "=", "(", "'root'", ",", ")", ")", ":", "self", ".", "content_type", "=", "None", "return", "RegexLexer", ".", "get_tokens_unprocessed", "(", "self", ",", "text", ",", "stack", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/lexers/textfmts.py#L126-L129
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/viewer/pv/utils.py
python
pgMesh2pvMesh
(mesh, data=None, label=None)
return grid
pyGIMLi's mesh format is different from pyvista's needs, some preparation is necessary. Parameters ---------- mesh: pg.Mesh Structure generated by pyGIMLi to display. data: iterable Parameter to distribute to cells/nodes.
pyGIMLi's mesh format is different from pyvista's needs, some preparation is necessary.
[ "pyGIMLi", "s", "mesh", "format", "is", "different", "from", "pyvista", "s", "needs", "some", "preparation", "is", "necessary", "." ]
def pgMesh2pvMesh(mesh, data=None, label=None): """ pyGIMLi's mesh format is different from pyvista's needs, some preparation is necessary. Parameters ---------- mesh: pg.Mesh Structure generated by pyGIMLi to display. data: iterable Parameter to distribute to cells/nodes. """ _, tmp = tempfile.mkstemp(suffix=".vtk") # export given mesh temporarily is the easiest and fastest option ATM mesh.exportVTK(tmp) grid = pv.read(tmp) # check for parameters inside the pg.Mesh for key, values in mesh.dataMap(): if len(values) == mesh.cellCount(): grid.cell_arrays[key] = np.asarray(values) elif len(values) == mesh.nodeCount(): grid.point_arrays[key] = np.asarray(values) # check the given data as well try: if data is not None: if len(data) == mesh.cellCount(): grid.cell_arrays[label] = np.asarray(data) elif len(data) == mesh.nodeCount(): grid.point_arrays[label] = np.asarray(data) else: pg.warn("Given data fits neither cell count nor node count:") pg.warn("{} vs. {} vs. {}".format(len(data), mesh.cellCount(), mesh.nodeCount())) except Exception as e: print(e) pg.error("fix pyvista bindings") if label is None: # last data that was added label = grid.array_names[-1] elif label not in grid.array_names: pg.warn("Given label '{}' was not found.".format(label)) label = grid.array_names[-1] grid.set_active_scalars(label) return grid
[ "def", "pgMesh2pvMesh", "(", "mesh", ",", "data", "=", "None", ",", "label", "=", "None", ")", ":", "_", ",", "tmp", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "\".vtk\"", ")", "# export given mesh temporarily is the easiest and fastest option ATM", "mesh", ".", "exportVTK", "(", "tmp", ")", "grid", "=", "pv", ".", "read", "(", "tmp", ")", "# check for parameters inside the pg.Mesh", "for", "key", ",", "values", "in", "mesh", ".", "dataMap", "(", ")", ":", "if", "len", "(", "values", ")", "==", "mesh", ".", "cellCount", "(", ")", ":", "grid", ".", "cell_arrays", "[", "key", "]", "=", "np", ".", "asarray", "(", "values", ")", "elif", "len", "(", "values", ")", "==", "mesh", ".", "nodeCount", "(", ")", ":", "grid", ".", "point_arrays", "[", "key", "]", "=", "np", ".", "asarray", "(", "values", ")", "# check the given data as well", "try", ":", "if", "data", "is", "not", "None", ":", "if", "len", "(", "data", ")", "==", "mesh", ".", "cellCount", "(", ")", ":", "grid", ".", "cell_arrays", "[", "label", "]", "=", "np", ".", "asarray", "(", "data", ")", "elif", "len", "(", "data", ")", "==", "mesh", ".", "nodeCount", "(", ")", ":", "grid", ".", "point_arrays", "[", "label", "]", "=", "np", ".", "asarray", "(", "data", ")", "else", ":", "pg", ".", "warn", "(", "\"Given data fits neither cell count nor node count:\"", ")", "pg", ".", "warn", "(", "\"{} vs. {} vs. {}\"", ".", "format", "(", "len", "(", "data", ")", ",", "mesh", ".", "cellCount", "(", ")", ",", "mesh", ".", "nodeCount", "(", ")", ")", ")", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "pg", ".", "error", "(", "\"fix pyvista bindings\"", ")", "if", "label", "is", "None", ":", "# last data that was added", "label", "=", "grid", ".", "array_names", "[", "-", "1", "]", "elif", "label", "not", "in", "grid", ".", "array_names", ":", "pg", ".", "warn", "(", "\"Given label '{}' was not found.\"", ".", "format", "(", "label", ")", ")", "label", "=", "grid", ".", "array_names", "[", "-", "1", "]", "grid", ".", "set_active_scalars", "(", "label", ")", "return", "grid" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/viewer/pv/utils.py#L9-L57
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/nanfunctions.py
python
nanstd
(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False)
return std
Compute the standard deviation along the specified axis, while ignoring NaNs. Returns the standard deviation, a measure of the spread of a distribution, of the non-NaN array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. For all-NaN slices or slices with zero degrees of freedom, NaN is returned and a `RuntimeWarning` is raised. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Calculate the standard deviation of the non-NaN values. axis : int, optional Axis along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. dtype : dtype, optional Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary. ddof : int, optional Means Delta Degrees of Freedom. The divisor used in calculations is ``N - ddof``, where ``N`` represents the number of non-NaN elements. By default `ddof` is zero. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. Returns ------- standard_deviation : ndarray, see dtype parameter above. If `out` is None, return a new array containing the standard deviation, otherwise return a reference to the output array. If ddof is >= the number of non-NaN elements in a slice or the slice contains only NaNs, then the result for that slice is NaN. See Also -------- var, mean, std nanvar, nanmean numpy.doc.ufuncs : Section "Output arguments" Notes ----- The standard deviation is the square root of the average of the squared deviations from the mean: ``std = sqrt(mean(abs(x - x.mean())**2))``. The average squared deviation is normally calculated as ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1`` provides an unbiased estimator of the variance of the infinite population. ``ddof=0`` provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ``ddof=1``, it will not be an unbiased estimate of the standard deviation per se. Note that, for complex numbers, `std` takes the absolute value before squaring, so that the result is always real and nonnegative. For floating-point input, the *std* is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the `dtype` keyword can alleviate this issue. Examples -------- >>> a = np.array([[1, np.nan], [3, 4]]) >>> np.nanstd(a) 1.247219128924647 >>> np.nanstd(a, axis=0) array([ 1., 0.]) >>> np.nanstd(a, axis=1) array([ 0., 0.5])
Compute the standard deviation along the specified axis, while ignoring NaNs.
[ "Compute", "the", "standard", "deviation", "along", "the", "specified", "axis", "while", "ignoring", "NaNs", "." ]
def nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): """ Compute the standard deviation along the specified axis, while ignoring NaNs. Returns the standard deviation, a measure of the spread of a distribution, of the non-NaN array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. For all-NaN slices or slices with zero degrees of freedom, NaN is returned and a `RuntimeWarning` is raised. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Calculate the standard deviation of the non-NaN values. axis : int, optional Axis along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. dtype : dtype, optional Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary. ddof : int, optional Means Delta Degrees of Freedom. The divisor used in calculations is ``N - ddof``, where ``N`` represents the number of non-NaN elements. By default `ddof` is zero. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. Returns ------- standard_deviation : ndarray, see dtype parameter above. If `out` is None, return a new array containing the standard deviation, otherwise return a reference to the output array. If ddof is >= the number of non-NaN elements in a slice or the slice contains only NaNs, then the result for that slice is NaN. See Also -------- var, mean, std nanvar, nanmean numpy.doc.ufuncs : Section "Output arguments" Notes ----- The standard deviation is the square root of the average of the squared deviations from the mean: ``std = sqrt(mean(abs(x - x.mean())**2))``. The average squared deviation is normally calculated as ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1`` provides an unbiased estimator of the variance of the infinite population. ``ddof=0`` provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ``ddof=1``, it will not be an unbiased estimate of the standard deviation per se. Note that, for complex numbers, `std` takes the absolute value before squaring, so that the result is always real and nonnegative. For floating-point input, the *std* is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the `dtype` keyword can alleviate this issue. Examples -------- >>> a = np.array([[1, np.nan], [3, 4]]) >>> np.nanstd(a) 1.247219128924647 >>> np.nanstd(a, axis=0) array([ 1., 0.]) >>> np.nanstd(a, axis=1) array([ 0., 0.5]) """ var = nanvar(a, axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims) if isinstance(var, np.ndarray): std = np.sqrt(var, out=var) else: std = var.dtype.type(np.sqrt(var)) return std
[ "def", "nanstd", "(", "a", ",", "axis", "=", "None", ",", "dtype", "=", "None", ",", "out", "=", "None", ",", "ddof", "=", "0", ",", "keepdims", "=", "False", ")", ":", "var", "=", "nanvar", "(", "a", ",", "axis", "=", "axis", ",", "dtype", "=", "dtype", ",", "out", "=", "out", ",", "ddof", "=", "ddof", ",", "keepdims", "=", "keepdims", ")", "if", "isinstance", "(", "var", ",", "np", ".", "ndarray", ")", ":", "std", "=", "np", ".", "sqrt", "(", "var", ",", "out", "=", "var", ")", "else", ":", "std", "=", "var", ".", "dtype", ".", "type", "(", "np", ".", "sqrt", "(", "var", ")", ")", "return", "std" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/nanfunctions.py#L744-L838
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/sliceviewer/lineplots.py
python
LinePlots.plot_y_line
(self, x: np.array, y: np.array)
Plots cut parallel to the Y axis of the image. :param x: Array of values for X axis :param y: Array of values for Y axis
Plots cut parallel to the Y axis of the image. :param x: Array of values for X axis :param y: Array of values for Y axis
[ "Plots", "cut", "parallel", "to", "the", "Y", "axis", "of", "the", "image", ".", ":", "param", "x", ":", "Array", "of", "values", "for", "X", "axis", ":", "param", "y", ":", "Array", "of", "values", "for", "Y", "axis" ]
def plot_y_line(self, x: np.array, y: np.array): """ Plots cut parallel to the Y axis of the image. :param x: Array of values for X axis :param y: Array of values for Y axis """ try: self._yfig.set_data(y, x) except (AttributeError, IndexError): self._axy.clear() self._yfig = self._axy.plot(y, x, scaley=False)[0] self._yfig.set_linewidth(0.5) self.update_line_plot_labels()
[ "def", "plot_y_line", "(", "self", ",", "x", ":", "np", ".", "array", ",", "y", ":", "np", ".", "array", ")", ":", "try", ":", "self", ".", "_yfig", ".", "set_data", "(", "y", ",", "x", ")", "except", "(", "AttributeError", ",", "IndexError", ")", ":", "self", ".", "_axy", ".", "clear", "(", ")", "self", ".", "_yfig", "=", "self", ".", "_axy", ".", "plot", "(", "y", ",", "x", ",", "scaley", "=", "False", ")", "[", "0", "]", "self", ".", "_yfig", ".", "set_linewidth", "(", "0.5", ")", "self", ".", "update_line_plot_labels", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/sliceviewer/lineplots.py#L98-L110
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
Feature.ExportToJson
(self, as_object=False, options=None)
return output
Exports a GeoJSON object which represents the Feature. The as_object parameter determines whether the returned value should be a Python object instead of a string. Defaults to False. The options parameter is passed to Geometry.ExportToJson()
Exports a GeoJSON object which represents the Feature. The as_object parameter determines whether the returned value should be a Python object instead of a string. Defaults to False. The options parameter is passed to Geometry.ExportToJson()
[ "Exports", "a", "GeoJSON", "object", "which", "represents", "the", "Feature", ".", "The", "as_object", "parameter", "determines", "whether", "the", "returned", "value", "should", "be", "a", "Python", "object", "instead", "of", "a", "string", ".", "Defaults", "to", "False", ".", "The", "options", "parameter", "is", "passed", "to", "Geometry", ".", "ExportToJson", "()" ]
def ExportToJson(self, as_object=False, options=None): """Exports a GeoJSON object which represents the Feature. The as_object parameter determines whether the returned value should be a Python object instead of a string. Defaults to False. The options parameter is passed to Geometry.ExportToJson()""" try: import simplejson except ImportError: try: import json as simplejson except ImportError: raise ImportError("Unable to import simplejson or json, needed for ExportToJson.") geom = self.GetGeometryRef() if geom is not None: if options is None: options = [] geom_json_string = geom.ExportToJson(options=options) geom_json_object = simplejson.loads(geom_json_string) else: geom_json_object = None output = {'type':'Feature', 'geometry': geom_json_object, 'properties': {} } fid = self.GetFID() if fid != NullFID: output['id'] = fid for key in self.keys(): fld_defn = self.GetFieldDefnRef(self.GetFieldIndex(key)) if fld_defn.GetType() == _ogr.OFTInteger and fld_defn.GetSubType() == _ogr.OFSTBoolean: output['properties'][key] = bool(self.GetField(key)) else: output['properties'][key] = self.GetField(key) if not as_object: output = simplejson.dumps(output) return output
[ "def", "ExportToJson", "(", "self", ",", "as_object", "=", "False", ",", "options", "=", "None", ")", ":", "try", ":", "import", "simplejson", "except", "ImportError", ":", "try", ":", "import", "json", "as", "simplejson", "except", "ImportError", ":", "raise", "ImportError", "(", "\"Unable to import simplejson or json, needed for ExportToJson.\"", ")", "geom", "=", "self", ".", "GetGeometryRef", "(", ")", "if", "geom", "is", "not", "None", ":", "if", "options", "is", "None", ":", "options", "=", "[", "]", "geom_json_string", "=", "geom", ".", "ExportToJson", "(", "options", "=", "options", ")", "geom_json_object", "=", "simplejson", ".", "loads", "(", "geom_json_string", ")", "else", ":", "geom_json_object", "=", "None", "output", "=", "{", "'type'", ":", "'Feature'", ",", "'geometry'", ":", "geom_json_object", ",", "'properties'", ":", "{", "}", "}", "fid", "=", "self", ".", "GetFID", "(", ")", "if", "fid", "!=", "NullFID", ":", "output", "[", "'id'", "]", "=", "fid", "for", "key", "in", "self", ".", "keys", "(", ")", ":", "fld_defn", "=", "self", ".", "GetFieldDefnRef", "(", "self", ".", "GetFieldIndex", "(", "key", ")", ")", "if", "fld_defn", ".", "GetType", "(", ")", "==", "_ogr", ".", "OFTInteger", "and", "fld_defn", ".", "GetSubType", "(", ")", "==", "_ogr", ".", "OFSTBoolean", ":", "output", "[", "'properties'", "]", "[", "key", "]", "=", "bool", "(", "self", ".", "GetField", "(", "key", ")", ")", "else", ":", "output", "[", "'properties'", "]", "[", "key", "]", "=", "self", ".", "GetField", "(", "key", ")", "if", "not", "as_object", ":", "output", "=", "simplejson", ".", "dumps", "(", "output", ")", "return", "output" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L4431-L4473
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/datetime.py
python
datetime.fromtimestamp
(cls, t, tz=None)
return cls._fromtimestamp(t, tz is not None, tz)
Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well.
Construct a datetime from a POSIX timestamp (like time.time()).
[ "Construct", "a", "datetime", "from", "a", "POSIX", "timestamp", "(", "like", "time", ".", "time", "()", ")", "." ]
def fromtimestamp(cls, t, tz=None): """Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well. """ _check_tzinfo_arg(tz) return cls._fromtimestamp(t, tz is not None, tz)
[ "def", "fromtimestamp", "(", "cls", ",", "t", ",", "tz", "=", "None", ")", ":", "_check_tzinfo_arg", "(", "tz", ")", "return", "cls", ".", "_fromtimestamp", "(", "t", ",", "tz", "is", "not", "None", ",", "tz", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/datetime.py#L1627-L1634
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/nntplib.py
python
_NNTPBase.newnews
(self, group, date, *, file=None)
return self._longcmdstring(cmd, file)
Process a NEWNEWS command. Arguments: - group: group name or '*' - date: a date or datetime object Return: - resp: server response if successful - list: list of message ids
Process a NEWNEWS command. Arguments: - group: group name or '*' - date: a date or datetime object Return: - resp: server response if successful - list: list of message ids
[ "Process", "a", "NEWNEWS", "command", ".", "Arguments", ":", "-", "group", ":", "group", "name", "or", "*", "-", "date", ":", "a", "date", "or", "datetime", "object", "Return", ":", "-", "resp", ":", "server", "response", "if", "successful", "-", "list", ":", "list", "of", "message", "ids" ]
def newnews(self, group, date, *, file=None): """Process a NEWNEWS command. Arguments: - group: group name or '*' - date: a date or datetime object Return: - resp: server response if successful - list: list of message ids """ if not isinstance(date, (datetime.date, datetime.date)): raise TypeError( "the date parameter must be a date or datetime object, " "not '{:40}'".format(date.__class__.__name__)) date_str, time_str = _unparse_datetime(date, self.nntp_version < 2) cmd = 'NEWNEWS {0} {1} {2}'.format(group, date_str, time_str) return self._longcmdstring(cmd, file)
[ "def", "newnews", "(", "self", ",", "group", ",", "date", ",", "*", ",", "file", "=", "None", ")", ":", "if", "not", "isinstance", "(", "date", ",", "(", "datetime", ".", "date", ",", "datetime", ".", "date", ")", ")", ":", "raise", "TypeError", "(", "\"the date parameter must be a date or datetime object, \"", "\"not '{:40}'\"", ".", "format", "(", "date", ".", "__class__", ".", "__name__", ")", ")", "date_str", ",", "time_str", "=", "_unparse_datetime", "(", "date", ",", "self", ".", "nntp_version", "<", "2", ")", "cmd", "=", "'NEWNEWS {0} {1} {2}'", ".", "format", "(", "group", ",", "date_str", ",", "time_str", ")", "return", "self", ".", "_longcmdstring", "(", "cmd", ",", "file", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/nntplib.py#L580-L594
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/importIFClegacy.py
python
IfcEntity.getProperty
(self,propName)
return None
finds the value of the given property or quantity in this object, if exists
finds the value of the given property or quantity in this object, if exists
[ "finds", "the", "value", "of", "the", "given", "property", "or", "quantity", "in", "this", "object", "if", "exists" ]
def getProperty(self,propName): "finds the value of the given property or quantity in this object, if exists" propsets = self.doc.find('IFCRELDEFINESBYPROPERTIES','RelatedObjects',self) if not propsets: return None propset = [] for p in propsets: if hasattr(p.RelatingPropertyDefinition,"HasProperties"): propset.extend(p.RelatingPropertyDefinition.HasProperties) elif hasattr(p.RelatingPropertyDefinition,"Quantities"): propset.extend(p.RelatingPropertyDefinition.Quantities) for prop in propset: if prop.Name == propName: print("found valid",prop) if hasattr(prop,"LengthValue"): return prop.LengthValue elif hasattr(prop,"AreaValue"): return prop.AreaValue elif hasattr(prop,"VolumeValue"): return prop.VolumeValue elif hasattr(prop,"NominalValue"): return prop.NominalValue return None
[ "def", "getProperty", "(", "self", ",", "propName", ")", ":", "propsets", "=", "self", ".", "doc", ".", "find", "(", "'IFCRELDEFINESBYPROPERTIES'", ",", "'RelatedObjects'", ",", "self", ")", "if", "not", "propsets", ":", "return", "None", "propset", "=", "[", "]", "for", "p", "in", "propsets", ":", "if", "hasattr", "(", "p", ".", "RelatingPropertyDefinition", ",", "\"HasProperties\"", ")", ":", "propset", ".", "extend", "(", "p", ".", "RelatingPropertyDefinition", ".", "HasProperties", ")", "elif", "hasattr", "(", "p", ".", "RelatingPropertyDefinition", ",", "\"Quantities\"", ")", ":", "propset", ".", "extend", "(", "p", ".", "RelatingPropertyDefinition", ".", "Quantities", ")", "for", "prop", "in", "propset", ":", "if", "prop", ".", "Name", "==", "propName", ":", "print", "(", "\"found valid\"", ",", "prop", ")", "if", "hasattr", "(", "prop", ",", "\"LengthValue\"", ")", ":", "return", "prop", ".", "LengthValue", "elif", "hasattr", "(", "prop", ",", "\"AreaValue\"", ")", ":", "return", "prop", ".", "AreaValue", "elif", "hasattr", "(", "prop", ",", "\"VolumeValue\"", ")", ":", "return", "prop", ".", "VolumeValue", "elif", "hasattr", "(", "prop", ",", "\"NominalValue\"", ")", ":", "return", "prop", ".", "NominalValue", "return", "None" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/importIFClegacy.py#L1649-L1670
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/training/python/training/hparam.py
python
HParams._init_from_proto
(self, hparam_def)
Creates a new HParams from `HParamDef` protocol buffer. Args: hparam_def: `HParamDef` protocol buffer.
Creates a new HParams from `HParamDef` protocol buffer.
[ "Creates", "a", "new", "HParams", "from", "HParamDef", "protocol", "buffer", "." ]
def _init_from_proto(self, hparam_def): """Creates a new HParams from `HParamDef` protocol buffer. Args: hparam_def: `HParamDef` protocol buffer. """ assert isinstance(hparam_def, hparam_pb2.HParamDef) for name, value in hparam_def.hparam.items(): kind = value.WhichOneof('kind') if kind.endswith('_value'): # Single value. if kind.startswith('int64'): # Setting attribute value to be 'int' to ensure the type is compatible # with both Python2 and Python3. self.add_hparam(name, int(getattr(value, kind))) elif kind.startswith('bytes'): # Setting attribute value to be 'str' to ensure the type is compatible # with both Python2 and Python3. UTF-8 encoding is assumed. self.add_hparam(name, compat.as_str(getattr(value, kind))) else: self.add_hparam(name, getattr(value, kind)) else: # List of values. if kind.startswith('int64'): # Setting attribute value to be 'int' to ensure the type is compatible # with both Python2 and Python3. self.add_hparam(name, [int(v) for v in getattr(value, kind).value]) elif kind.startswith('bytes'): # Setting attribute value to be 'str' to ensure the type is compatible # with both Python2 and Python3. UTF-8 encoding is assumed. self.add_hparam(name, [compat.as_str(v) for v in getattr(value, kind).value]) else: self.add_hparam(name, [v for v in getattr(value, kind).value])
[ "def", "_init_from_proto", "(", "self", ",", "hparam_def", ")", ":", "assert", "isinstance", "(", "hparam_def", ",", "hparam_pb2", ".", "HParamDef", ")", "for", "name", ",", "value", "in", "hparam_def", ".", "hparam", ".", "items", "(", ")", ":", "kind", "=", "value", ".", "WhichOneof", "(", "'kind'", ")", "if", "kind", ".", "endswith", "(", "'_value'", ")", ":", "# Single value.", "if", "kind", ".", "startswith", "(", "'int64'", ")", ":", "# Setting attribute value to be 'int' to ensure the type is compatible", "# with both Python2 and Python3.", "self", ".", "add_hparam", "(", "name", ",", "int", "(", "getattr", "(", "value", ",", "kind", ")", ")", ")", "elif", "kind", ".", "startswith", "(", "'bytes'", ")", ":", "# Setting attribute value to be 'str' to ensure the type is compatible", "# with both Python2 and Python3. UTF-8 encoding is assumed.", "self", ".", "add_hparam", "(", "name", ",", "compat", ".", "as_str", "(", "getattr", "(", "value", ",", "kind", ")", ")", ")", "else", ":", "self", ".", "add_hparam", "(", "name", ",", "getattr", "(", "value", ",", "kind", ")", ")", "else", ":", "# List of values.", "if", "kind", ".", "startswith", "(", "'int64'", ")", ":", "# Setting attribute value to be 'int' to ensure the type is compatible", "# with both Python2 and Python3.", "self", ".", "add_hparam", "(", "name", ",", "[", "int", "(", "v", ")", "for", "v", "in", "getattr", "(", "value", ",", "kind", ")", ".", "value", "]", ")", "elif", "kind", ".", "startswith", "(", "'bytes'", ")", ":", "# Setting attribute value to be 'str' to ensure the type is compatible", "# with both Python2 and Python3. UTF-8 encoding is assumed.", "self", ".", "add_hparam", "(", "name", ",", "[", "compat", ".", "as_str", "(", "v", ")", "for", "v", "in", "getattr", "(", "value", ",", "kind", ")", ".", "value", "]", ")", "else", ":", "self", ".", "add_hparam", "(", "name", ",", "[", "v", "for", "v", "in", "getattr", "(", "value", ",", "kind", ")", ".", "value", "]", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/training/python/training/hparam.py#L246-L279
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/utils/tensorboard/writer.py
python
SummaryWriter.add_embedding
(self, mat, metadata=None, label_img=None, global_step=None, tag='default', metadata_header=None)
Add embedding projector data to summary. Args: mat (torch.Tensor or numpy.array): A matrix which each row is the feature vector of the data point metadata (list): A list of labels, each element will be convert to string label_img (torch.Tensor): Images correspond to each data point global_step (int): Global step value to record tag (string): Name for the embedding Shape: mat: :math:`(N, D)`, where N is number of data and D is feature dimension label_img: :math:`(N, C, H, W)` Examples:: import keyword import torch meta = [] while len(meta)<100: meta = meta+keyword.kwlist # get some strings meta = meta[:100] for i, v in enumerate(meta): meta[i] = v+str(i) label_img = torch.rand(100, 3, 10, 32) for i in range(100): label_img[i]*=i/100.0 writer.add_embedding(torch.randn(100, 5), metadata=meta, label_img=label_img) writer.add_embedding(torch.randn(100, 5), label_img=label_img) writer.add_embedding(torch.randn(100, 5), metadata=meta)
Add embedding projector data to summary.
[ "Add", "embedding", "projector", "data", "to", "summary", "." ]
def add_embedding(self, mat, metadata=None, label_img=None, global_step=None, tag='default', metadata_header=None): """Add embedding projector data to summary. Args: mat (torch.Tensor or numpy.array): A matrix which each row is the feature vector of the data point metadata (list): A list of labels, each element will be convert to string label_img (torch.Tensor): Images correspond to each data point global_step (int): Global step value to record tag (string): Name for the embedding Shape: mat: :math:`(N, D)`, where N is number of data and D is feature dimension label_img: :math:`(N, C, H, W)` Examples:: import keyword import torch meta = [] while len(meta)<100: meta = meta+keyword.kwlist # get some strings meta = meta[:100] for i, v in enumerate(meta): meta[i] = v+str(i) label_img = torch.rand(100, 3, 10, 32) for i in range(100): label_img[i]*=i/100.0 writer.add_embedding(torch.randn(100, 5), metadata=meta, label_img=label_img) writer.add_embedding(torch.randn(100, 5), label_img=label_img) writer.add_embedding(torch.randn(100, 5), metadata=meta) """ torch._C._log_api_usage_once("tensorboard.logging.add_embedding") mat = make_np(mat) if global_step is None: global_step = 0 # clear pbtxt? # Maybe we should encode the tag so slashes don't trip us up? # I don't think this will mess us up, but better safe than sorry. subdir = "%s/%s" % (str(global_step).zfill(5), self._encode(tag)) save_path = os.path.join(self._get_file_writer().get_logdir(), subdir) fs = tf.io.gfile.get_filesystem(save_path) if fs.exists(save_path): if fs.isdir(save_path): print( 'warning: Embedding dir exists, did you set global_step for add_embedding()?') else: raise Exception("Path: `%s` exists, but is a file. Cannot proceed." % save_path) else: fs.makedirs(save_path) if metadata is not None: assert mat.shape[0] == len( metadata), '#labels should equal with #data points' make_tsv(metadata, save_path, metadata_header=metadata_header) if label_img is not None: assert mat.shape[0] == label_img.shape[0], '#images should equal with #data points' make_sprite(label_img, save_path) assert mat.ndim == 2, 'mat should be 2D, where mat.size(0) is the number of data points' make_mat(mat, save_path) # Filesystem doesn't necessarily have append semantics, so we store an # internal buffer to append to and re-write whole file after each # embedding is added if not hasattr(self, "_projector_config"): self._projector_config = ProjectorConfig() embedding_info = get_embedding_info( metadata, label_img, fs, subdir, global_step, tag) self._projector_config.embeddings.extend([embedding_info]) from google.protobuf import text_format config_pbtxt = text_format.MessageToString(self._projector_config) write_pbtxt(self._get_file_writer().get_logdir(), config_pbtxt)
[ "def", "add_embedding", "(", "self", ",", "mat", ",", "metadata", "=", "None", ",", "label_img", "=", "None", ",", "global_step", "=", "None", ",", "tag", "=", "'default'", ",", "metadata_header", "=", "None", ")", ":", "torch", ".", "_C", ".", "_log_api_usage_once", "(", "\"tensorboard.logging.add_embedding\"", ")", "mat", "=", "make_np", "(", "mat", ")", "if", "global_step", "is", "None", ":", "global_step", "=", "0", "# clear pbtxt?", "# Maybe we should encode the tag so slashes don't trip us up?", "# I don't think this will mess us up, but better safe than sorry.", "subdir", "=", "\"%s/%s\"", "%", "(", "str", "(", "global_step", ")", ".", "zfill", "(", "5", ")", ",", "self", ".", "_encode", "(", "tag", ")", ")", "save_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_get_file_writer", "(", ")", ".", "get_logdir", "(", ")", ",", "subdir", ")", "fs", "=", "tf", ".", "io", ".", "gfile", ".", "get_filesystem", "(", "save_path", ")", "if", "fs", ".", "exists", "(", "save_path", ")", ":", "if", "fs", ".", "isdir", "(", "save_path", ")", ":", "print", "(", "'warning: Embedding dir exists, did you set global_step for add_embedding()?'", ")", "else", ":", "raise", "Exception", "(", "\"Path: `%s` exists, but is a file. Cannot proceed.\"", "%", "save_path", ")", "else", ":", "fs", ".", "makedirs", "(", "save_path", ")", "if", "metadata", "is", "not", "None", ":", "assert", "mat", ".", "shape", "[", "0", "]", "==", "len", "(", "metadata", ")", ",", "'#labels should equal with #data points'", "make_tsv", "(", "metadata", ",", "save_path", ",", "metadata_header", "=", "metadata_header", ")", "if", "label_img", "is", "not", "None", ":", "assert", "mat", ".", "shape", "[", "0", "]", "==", "label_img", ".", "shape", "[", "0", "]", ",", "'#images should equal with #data points'", "make_sprite", "(", "label_img", ",", "save_path", ")", "assert", "mat", ".", "ndim", "==", "2", ",", "'mat should be 2D, where mat.size(0) is the number of data points'", "make_mat", "(", "mat", ",", "save_path", ")", "# Filesystem doesn't necessarily have append semantics, so we store an", "# internal buffer to append to and re-write whole file after each", "# embedding is added", "if", "not", "hasattr", "(", "self", ",", "\"_projector_config\"", ")", ":", "self", ".", "_projector_config", "=", "ProjectorConfig", "(", ")", "embedding_info", "=", "get_embedding_info", "(", "metadata", ",", "label_img", ",", "fs", ",", "subdir", ",", "global_step", ",", "tag", ")", "self", ".", "_projector_config", ".", "embeddings", ".", "extend", "(", "[", "embedding_info", "]", ")", "from", "google", ".", "protobuf", "import", "text_format", "config_pbtxt", "=", "text_format", ".", "MessageToString", "(", "self", ".", "_projector_config", ")", "write_pbtxt", "(", "self", ".", "_get_file_writer", "(", ")", ".", "get_logdir", "(", ")", ",", "config_pbtxt", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/utils/tensorboard/writer.py#L765-L843
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/framework/dtypes.py
python
DType.is_unsigned
(self)
Returns whether this type is unsigned. Non-numeric, unordered, and quantized types are not considered unsigned, and this function returns `False`. Returns: Whether a `DType` is unsigned.
Returns whether this type is unsigned.
[ "Returns", "whether", "this", "type", "is", "unsigned", "." ]
def is_unsigned(self): """Returns whether this type is unsigned. Non-numeric, unordered, and quantized types are not considered unsigned, and this function returns `False`. Returns: Whether a `DType` is unsigned. """ try: return self.min == 0 except TypeError: return False
[ "def", "is_unsigned", "(", "self", ")", ":", "try", ":", "return", "self", ".", "min", "==", "0", "except", "TypeError", ":", "return", "False" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/dtypes.py#L160-L172
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
FWCore/PythonUtilities/python/XML2Python.py
python
xml2obj
(**kwargs)
return builder.topLevel()
Converts XML data into native Python object. Takes either file handle or string as input. Does NOT fix illegal characters. input source: Exactly one of the three following is needed filehandle - input from file handle contents - input from string filename - input from filename options: filtering - boolean value telling code whether or not to fileter input selection to remove illegal XML characters nameChangeDict - dictionaries of names to change in python object
Converts XML data into native Python object. Takes either file handle or string as input. Does NOT fix illegal characters.
[ "Converts", "XML", "data", "into", "native", "Python", "object", ".", "Takes", "either", "file", "handle", "or", "string", "as", "input", ".", "Does", "NOT", "fix", "illegal", "characters", "." ]
def xml2obj (**kwargs): ''' Converts XML data into native Python object. Takes either file handle or string as input. Does NOT fix illegal characters. input source: Exactly one of the three following is needed filehandle - input from file handle contents - input from string filename - input from filename options: filtering - boolean value telling code whether or not to fileter input selection to remove illegal XML characters nameChangeDict - dictionaries of names to change in python object''' # make sure we have exactly 1 input source filehandle = kwargs.get ('filehandle') contents = kwargs.get ('contents') filename = kwargs.get ('filename') if not filehandle and not contents and not filename: raise RuntimeError("You must provide 'filehandle', 'contents', or 'filename'") if filehandle and contents or \ filehandle and filename or \ contents and filename: raise RuntimeError("You must provide only ONE of 'filehandle', 'contents', or 'filename'") # are we filtering? filtering = kwargs.get ('filtering') if filtering: # if we are filtering, we need to read in the contents to modify them if not contents: if not filehandle: try: filehandle = open (filename, 'r') except: raise RuntimeError("Failed to open '%s'" % filename) contents = '' for line in filehandle: contents += line filehandle.close() filehandle = filename = '' contents = quoteRE.sub (fixQuoteValue, contents) ncDict = kwargs.get ('nameChangeDict', {}) builder = TreeBuilder (nameChangeDict = ncDict) if contents: xml.sax.parseString(contents, builder) else: if not filehandle: try: filehandle = open (filename, 'r') except: raise RuntimeError("Failed to open '%s'" % filename) xml.sax.parse(filehandle, builder) return builder.topLevel()
[ "def", "xml2obj", "(", "*", "*", "kwargs", ")", ":", "# make sure we have exactly 1 input source", "filehandle", "=", "kwargs", ".", "get", "(", "'filehandle'", ")", "contents", "=", "kwargs", ".", "get", "(", "'contents'", ")", "filename", "=", "kwargs", ".", "get", "(", "'filename'", ")", "if", "not", "filehandle", "and", "not", "contents", "and", "not", "filename", ":", "raise", "RuntimeError", "(", "\"You must provide 'filehandle', 'contents', or 'filename'\"", ")", "if", "filehandle", "and", "contents", "or", "filehandle", "and", "filename", "or", "contents", "and", "filename", ":", "raise", "RuntimeError", "(", "\"You must provide only ONE of 'filehandle', 'contents', or 'filename'\"", ")", "# are we filtering?", "filtering", "=", "kwargs", ".", "get", "(", "'filtering'", ")", "if", "filtering", ":", "# if we are filtering, we need to read in the contents to modify them", "if", "not", "contents", ":", "if", "not", "filehandle", ":", "try", ":", "filehandle", "=", "open", "(", "filename", ",", "'r'", ")", "except", ":", "raise", "RuntimeError", "(", "\"Failed to open '%s'\"", "%", "filename", ")", "contents", "=", "''", "for", "line", "in", "filehandle", ":", "contents", "+=", "line", "filehandle", ".", "close", "(", ")", "filehandle", "=", "filename", "=", "''", "contents", "=", "quoteRE", ".", "sub", "(", "fixQuoteValue", ",", "contents", ")", "ncDict", "=", "kwargs", ".", "get", "(", "'nameChangeDict'", ",", "{", "}", ")", "builder", "=", "TreeBuilder", "(", "nameChangeDict", "=", "ncDict", ")", "if", "contents", ":", "xml", ".", "sax", ".", "parseString", "(", "contents", ",", "builder", ")", "else", ":", "if", "not", "filehandle", ":", "try", ":", "filehandle", "=", "open", "(", "filename", ",", "'r'", ")", "except", ":", "raise", "RuntimeError", "(", "\"Failed to open '%s'\"", "%", "filename", ")", "xml", ".", "sax", ".", "parse", "(", "filehandle", ",", "builder", ")", "return", "builder", ".", "topLevel", "(", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/FWCore/PythonUtilities/python/XML2Python.py#L224-L277
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py
python
convert_size
(node, **kwargs)
return nodes
Map MXNet's size_array operator attributes to onnx's Size operator and return the created node.
Map MXNet's size_array operator attributes to onnx's Size operator and return the created node.
[ "Map", "MXNet", "s", "size_array", "operator", "attributes", "to", "onnx", "s", "Size", "operator", "and", "return", "the", "created", "node", "." ]
def convert_size(node, **kwargs): """Map MXNet's size_array operator attributes to onnx's Size operator and return the created node. """ from onnx.helper import make_node name, input_nodes, _ = get_inputs(node, kwargs) create_tensor([1], name+'_1', kwargs['initializer']) nodes = [ make_node('Size', [input_nodes[0]], [name+'_size']), make_node('Reshape', [name+'_size', name+'_1'], [name], name=name) ] return nodes
[ "def", "convert_size", "(", "node", ",", "*", "*", "kwargs", ")", ":", "from", "onnx", ".", "helper", "import", "make_node", "name", ",", "input_nodes", ",", "_", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "create_tensor", "(", "[", "1", "]", ",", "name", "+", "'_1'", ",", "kwargs", "[", "'initializer'", "]", ")", "nodes", "=", "[", "make_node", "(", "'Size'", ",", "[", "input_nodes", "[", "0", "]", "]", ",", "[", "name", "+", "'_size'", "]", ")", ",", "make_node", "(", "'Reshape'", ",", "[", "name", "+", "'_size'", ",", "name", "+", "'_1'", "]", ",", "[", "name", "]", ",", "name", "=", "name", ")", "]", "return", "nodes" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py#L2487-L2499
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/lib/function_base.py
python
trim_zeros
(filt, trim='fb')
return filt[first:last]
Trim the leading and/or trailing zeros from a 1-D array or sequence. Parameters ---------- filt : 1-D array or sequence Input array. trim : str, optional A string with 'f' representing trim from front and 'b' to trim from back. Default is 'fb', trim zeros from both front and back of the array. Returns ------- trimmed : 1-D array or sequence The result of trimming the input. The input data type is preserved. Examples -------- >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0)) >>> np.trim_zeros(a) array([1, 2, 3, 0, 2, 1]) >>> np.trim_zeros(a, 'b') array([0, 0, 0, ..., 0, 2, 1]) The input data type is preserved, list/tuple in means list/tuple out. >>> np.trim_zeros([0, 1, 2, 0]) [1, 2]
Trim the leading and/or trailing zeros from a 1-D array or sequence.
[ "Trim", "the", "leading", "and", "/", "or", "trailing", "zeros", "from", "a", "1", "-", "D", "array", "or", "sequence", "." ]
def trim_zeros(filt, trim='fb'): """ Trim the leading and/or trailing zeros from a 1-D array or sequence. Parameters ---------- filt : 1-D array or sequence Input array. trim : str, optional A string with 'f' representing trim from front and 'b' to trim from back. Default is 'fb', trim zeros from both front and back of the array. Returns ------- trimmed : 1-D array or sequence The result of trimming the input. The input data type is preserved. Examples -------- >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0)) >>> np.trim_zeros(a) array([1, 2, 3, 0, 2, 1]) >>> np.trim_zeros(a, 'b') array([0, 0, 0, ..., 0, 2, 1]) The input data type is preserved, list/tuple in means list/tuple out. >>> np.trim_zeros([0, 1, 2, 0]) [1, 2] """ first = 0 trim = trim.upper() if 'F' in trim: for i in filt: if i != 0.: break else: first = first + 1 last = len(filt) if 'B' in trim: for i in filt[::-1]: if i != 0.: break else: last = last - 1 return filt[first:last]
[ "def", "trim_zeros", "(", "filt", ",", "trim", "=", "'fb'", ")", ":", "first", "=", "0", "trim", "=", "trim", ".", "upper", "(", ")", "if", "'F'", "in", "trim", ":", "for", "i", "in", "filt", ":", "if", "i", "!=", "0.", ":", "break", "else", ":", "first", "=", "first", "+", "1", "last", "=", "len", "(", "filt", ")", "if", "'B'", "in", "trim", ":", "for", "i", "in", "filt", "[", ":", ":", "-", "1", "]", ":", "if", "i", "!=", "0.", ":", "break", "else", ":", "last", "=", "last", "-", "1", "return", "filt", "[", "first", ":", "last", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/function_base.py#L1645-L1694
ethereum/solidity
1210c3e60f2a0bd02ed7fb8f2da2f686ee38e1af
scripts/error_codes.py
python
find_ids_in_source_files
(file_names)
return id_to_file_names
Returns a dictionary with list of source files for every appearance of every id
Returns a dictionary with list of source files for every appearance of every id
[ "Returns", "a", "dictionary", "with", "list", "of", "source", "files", "for", "every", "appearance", "of", "every", "id" ]
def find_ids_in_source_files(file_names): """Returns a dictionary with list of source files for every appearance of every id""" id_to_file_names = {} for file_name in file_names: find_ids_in_source_file(file_name, id_to_file_names) return id_to_file_names
[ "def", "find_ids_in_source_files", "(", "file_names", ")", ":", "id_to_file_names", "=", "{", "}", "for", "file_name", "in", "file_names", ":", "find_ids_in_source_file", "(", "file_name", ",", "id_to_file_names", ")", "return", "id_to_file_names" ]
https://github.com/ethereum/solidity/blob/1210c3e60f2a0bd02ed7fb8f2da2f686ee38e1af/scripts/error_codes.py#L54-L60
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/base.py
python
IndexOpsMixin.shape
(self)
return self._values.shape
Return a tuple of the shape of the underlying data.
Return a tuple of the shape of the underlying data.
[ "Return", "a", "tuple", "of", "the", "shape", "of", "the", "underlying", "data", "." ]
def shape(self): """ Return a tuple of the shape of the underlying data. """ return self._values.shape
[ "def", "shape", "(", "self", ")", ":", "return", "self", ".", "_values", ".", "shape" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/base.py#L698-L702
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/shutil.py
python
_get_uid
(name)
return None
Returns an uid, given a user name.
Returns an uid, given a user name.
[ "Returns", "an", "uid", "given", "a", "user", "name", "." ]
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "def", "_get_uid", "(", "name", ")", ":", "if", "getpwnam", "is", "None", "or", "name", "is", "None", ":", "return", "None", "try", ":", "result", "=", "getpwnam", "(", "name", ")", "except", "KeyError", ":", "result", "=", "None", "if", "result", "is", "not", "None", ":", "return", "result", "[", "2", "]", "return", "None" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/shutil.py#L325-L335
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBCommunication.SetReadThreadBytesReceivedCallback
(self, callback, callback_baton)
return _lldb.SBCommunication_SetReadThreadBytesReceivedCallback(self, callback, callback_baton)
SetReadThreadBytesReceivedCallback(SBCommunication self, lldb::SBCommunication::ReadThreadBytesReceived callback, void * callback_baton) -> bool
SetReadThreadBytesReceivedCallback(SBCommunication self, lldb::SBCommunication::ReadThreadBytesReceived callback, void * callback_baton) -> bool
[ "SetReadThreadBytesReceivedCallback", "(", "SBCommunication", "self", "lldb", "::", "SBCommunication", "::", "ReadThreadBytesReceived", "callback", "void", "*", "callback_baton", ")", "-", ">", "bool" ]
def SetReadThreadBytesReceivedCallback(self, callback, callback_baton): """SetReadThreadBytesReceivedCallback(SBCommunication self, lldb::SBCommunication::ReadThreadBytesReceived callback, void * callback_baton) -> bool""" return _lldb.SBCommunication_SetReadThreadBytesReceivedCallback(self, callback, callback_baton)
[ "def", "SetReadThreadBytesReceivedCallback", "(", "self", ",", "callback", ",", "callback_baton", ")", ":", "return", "_lldb", ".", "SBCommunication_SetReadThreadBytesReceivedCallback", "(", "self", ",", "callback", ",", "callback_baton", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L3087-L3089
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/feature_column/feature_column.py
python
indicator_column
(categorical_column)
return _IndicatorColumn(categorical_column)
Represents multi-hot representation of given categorical column. Used to wrap any `categorical_column_*` (e.g., to feed to DNN). Use `embedding_column` if the inputs are sparse. ```python name = indicator_column(categorical_column_with_vocabulary_list( 'name', ['bob', 'george', 'wanda']) columns = [name, ...] features = tf.parse_example(..., features=make_parse_example_spec(columns)) dense_tensor = input_layer(features, columns) dense_tensor == [[1, 0, 0]] # If "name" bytes_list is ["bob"] dense_tensor == [[1, 0, 1]] # If "name" bytes_list is ["bob", "wanda"] dense_tensor == [[2, 0, 0]] # If "name" bytes_list is ["bob", "bob"] ``` Args: categorical_column: A `_CategoricalColumn` which is created by `categorical_column_with_*` or `crossed_column` functions. Returns: An `_IndicatorColumn`.
Represents multi-hot representation of given categorical column.
[ "Represents", "multi", "-", "hot", "representation", "of", "given", "categorical", "column", "." ]
def indicator_column(categorical_column): """Represents multi-hot representation of given categorical column. Used to wrap any `categorical_column_*` (e.g., to feed to DNN). Use `embedding_column` if the inputs are sparse. ```python name = indicator_column(categorical_column_with_vocabulary_list( 'name', ['bob', 'george', 'wanda']) columns = [name, ...] features = tf.parse_example(..., features=make_parse_example_spec(columns)) dense_tensor = input_layer(features, columns) dense_tensor == [[1, 0, 0]] # If "name" bytes_list is ["bob"] dense_tensor == [[1, 0, 1]] # If "name" bytes_list is ["bob", "wanda"] dense_tensor == [[2, 0, 0]] # If "name" bytes_list is ["bob", "bob"] ``` Args: categorical_column: A `_CategoricalColumn` which is created by `categorical_column_with_*` or `crossed_column` functions. Returns: An `_IndicatorColumn`. """ return _IndicatorColumn(categorical_column)
[ "def", "indicator_column", "(", "categorical_column", ")", ":", "return", "_IndicatorColumn", "(", "categorical_column", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/feature_column/feature_column.py#L1019-L1044
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
api/ctpx/ctpmd.py
python
CtpMd.onHeartBeatWarning
(self, lapsedTime)
@:param lapsedTime 距离上次接收报文的时间
[]
def onHeartBeatWarning(self, lapsedTime): """@:param lapsedTime 距离上次接收报文的时间""" pass
[ "def", "onHeartBeatWarning", "(", "self", ",", "lapsedTime", ")", ":", "pass" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctpmd.py#L43-L45
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/_appdirs.py
python
user_data_dir
(appname=None, appauthor=None, version=None, roaming=False)
return path
r"""Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user data directories are: Mac OS X: ~/Library/Application Support/<AppName> Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName> Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName> Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName> Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName> For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by default "~/.local/share/<AppName>".
r"""Return full path to the user-specific data dir for this application.
[ "r", "Return", "full", "path", "to", "the", "user", "-", "specific", "data", "dir", "for", "this", "application", "." ]
def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user data directories are: Mac OS X: ~/Library/Application Support/<AppName> Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName> Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName> Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName> Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName> For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by default "~/.local/share/<AppName>". """ if system == "win32": if appauthor is None: appauthor = appname const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA" path = os.path.normpath(_get_win_folder(const)) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) elif system == 'darwin': path = os.path.expanduser('~/Library/Application Support/') if appname: path = os.path.join(path, appname) else: path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path
[ "def", "user_data_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "roaming", "=", "False", ")", ":", "if", "system", "==", "\"win32\"", ":", "if", "appauthor", "is", "None", ":", "appauthor", "=", "appname", "const", "=", "roaming", "and", "\"CSIDL_APPDATA\"", "or", "\"CSIDL_LOCAL_APPDATA\"", "path", "=", "os", ".", "path", ".", "normpath", "(", "_get_win_folder", "(", "const", ")", ")", "if", "appname", ":", "if", "appauthor", "is", "not", "False", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appauthor", ",", "appname", ")", "else", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "elif", "system", "==", "'darwin'", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "'~/Library/Application Support/'", ")", "if", "appname", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "else", ":", "path", "=", "os", ".", "getenv", "(", "'XDG_DATA_HOME'", ",", "os", ".", "path", ".", "expanduser", "(", "\"~/.local/share\"", ")", ")", "if", "appname", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "if", "appname", "and", "version", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "version", ")", "return", "path" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/_appdirs.py#L75-L127
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/packaging/specifiers.py
python
BaseSpecifier.__hash__
(self)
Returns a hash value for this Specifier like object.
Returns a hash value for this Specifier like object.
[ "Returns", "a", "hash", "value", "for", "this", "Specifier", "like", "object", "." ]
def __hash__(self): """ Returns a hash value for this Specifier like object. """
[ "def", "__hash__", "(", "self", ")", ":" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/packaging/specifiers.py#L41-L44
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/sans/algorithm_detail/mask_workspace.py
python
mask_beam_stop
(mask_info, workspace)
return workspace
The beam stop is being masked here. :param mask_info: a SANSStateMask object. :param workspace: the workspace which is to be masked. :return: a masked workspace
The beam stop is being masked here.
[ "The", "beam", "stop", "is", "being", "masked", "here", "." ]
def mask_beam_stop(mask_info, workspace): """ The beam stop is being masked here. :param mask_info: a SANSStateMask object. :param workspace: the workspace which is to be masked. :return: a masked workspace """ beam_stop_arm_width = mask_info.beam_stop_arm_width beam_stop_arm_angle = mask_info.beam_stop_arm_angle beam_stop_arm_pos1 = mask_info.beam_stop_arm_pos1 beam_stop_arm_pos2 = mask_info.beam_stop_arm_pos2 if not beam_stop_arm_width or not beam_stop_arm_angle: return workspace lab_ipf_key = "low-angle-detector-name" lab_component_name = workspace.getInstrument().getStringParameter(lab_ipf_key) if not lab_component_name: raise KeyError("{0} was not found in the IPF file for this instrument") lab_component_name = lab_component_name[0] comp_info = workspace.componentInfo() detector_index = comp_info.indexOfAny(lab_component_name) detector_pos = comp_info.position(detector_index) z_position = detector_pos.getZ() start_point = [beam_stop_arm_pos1, beam_stop_arm_pos2, z_position] line_mask = create_line_mask(start_point, 100., beam_stop_arm_width, beam_stop_arm_angle) mask_name = "MaskDetectorsInShape" mask_options = {"Workspace": workspace, "ShapeXML": line_mask} mask_alg = create_unmanaged_algorithm(mask_name, **mask_options) mask_alg.execute() workspace = mask_alg.getProperty("Workspace").value return workspace
[ "def", "mask_beam_stop", "(", "mask_info", ",", "workspace", ")", ":", "beam_stop_arm_width", "=", "mask_info", ".", "beam_stop_arm_width", "beam_stop_arm_angle", "=", "mask_info", ".", "beam_stop_arm_angle", "beam_stop_arm_pos1", "=", "mask_info", ".", "beam_stop_arm_pos1", "beam_stop_arm_pos2", "=", "mask_info", ".", "beam_stop_arm_pos2", "if", "not", "beam_stop_arm_width", "or", "not", "beam_stop_arm_angle", ":", "return", "workspace", "lab_ipf_key", "=", "\"low-angle-detector-name\"", "lab_component_name", "=", "workspace", ".", "getInstrument", "(", ")", ".", "getStringParameter", "(", "lab_ipf_key", ")", "if", "not", "lab_component_name", ":", "raise", "KeyError", "(", "\"{0} was not found in the IPF file for this instrument\"", ")", "lab_component_name", "=", "lab_component_name", "[", "0", "]", "comp_info", "=", "workspace", ".", "componentInfo", "(", ")", "detector_index", "=", "comp_info", ".", "indexOfAny", "(", "lab_component_name", ")", "detector_pos", "=", "comp_info", ".", "position", "(", "detector_index", ")", "z_position", "=", "detector_pos", ".", "getZ", "(", ")", "start_point", "=", "[", "beam_stop_arm_pos1", ",", "beam_stop_arm_pos2", ",", "z_position", "]", "line_mask", "=", "create_line_mask", "(", "start_point", ",", "100.", ",", "beam_stop_arm_width", ",", "beam_stop_arm_angle", ")", "mask_name", "=", "\"MaskDetectorsInShape\"", "mask_options", "=", "{", "\"Workspace\"", ":", "workspace", ",", "\"ShapeXML\"", ":", "line_mask", "}", "mask_alg", "=", "create_unmanaged_algorithm", "(", "mask_name", ",", "*", "*", "mask_options", ")", "mask_alg", ".", "execute", "(", ")", "workspace", "=", "mask_alg", ".", "getProperty", "(", "\"Workspace\"", ")", ".", "value", "return", "workspace" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/mask_workspace.py#L322-L359
cksystemsgroup/scal
fa2208a97a77d65f4e90f85fef3404c27c1f2ac2
tools/cpplint.py
python
_AddFilters
(filters)
Adds more filter overrides. Unlike _SetFilters, this function does not reset the current list of filters available. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die.
Adds more filter overrides.
[ "Adds", "more", "filter", "overrides", "." ]
def _AddFilters(filters): """Adds more filter overrides. Unlike _SetFilters, this function does not reset the current list of filters available. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.AddFilters(filters)
[ "def", "_AddFilters", "(", "filters", ")", ":", "_cpplint_state", ".", "AddFilters", "(", "filters", ")" ]
https://github.com/cksystemsgroup/scal/blob/fa2208a97a77d65f4e90f85fef3404c27c1f2ac2/tools/cpplint.py#L893-L903
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/boosted_trees/estimator_batch/trainer_hooks.py
python
SwitchTrainOp.__init__
(self, first_train_op, train_steps, second_train_op)
Initializes a `SwitchTrainOp`.
Initializes a `SwitchTrainOp`.
[ "Initializes", "a", "SwitchTrainOp", "." ]
def __init__(self, first_train_op, train_steps, second_train_op): """Initializes a `SwitchTrainOp`.""" self._first_train_op = first_train_op self._second_train_op = second_train_op self._train_steps = train_steps
[ "def", "__init__", "(", "self", ",", "first_train_op", ",", "train_steps", ",", "second_train_op", ")", ":", "self", ".", "_first_train_op", "=", "first_train_op", "self", ".", "_second_train_op", "=", "second_train_op", "self", ".", "_train_steps", "=", "train_steps" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/boosted_trees/estimator_batch/trainer_hooks.py#L204-L208
Cantera/cantera
0119484b261967ccb55a0066c020599cacc312e4
interfaces/cython/cantera/onedim.py
python
FlameBase.write_hdf
(self, filename, *args, group=None, species='X', mode='a', description=None, compression=None, compression_opts=None, quiet=True, normalize=True, **kwargs)
Write the solution vector to a HDF container file. The `write_hdf` method preserves the structure of a `FlameBase`-derived object (such as `FreeFlame`). Each simulation is saved as a *group*, whereas individual domains are saved as subgroups. In addition to datasets, information on `Sim1D.settings` and `Domain1D.settings` is saved in form of HDF attributes. The internal HDF file structure is illustrated for a `FreeFlame` output as::: / Group /group0 Group /group0/Sim1D_type Attribute ... /group0/flame Group /group0/flame/Domain1D_type Attribute ... /group0/flame/T Dataset ... /group0/flame/phase Group /group0/products Group /group0/products/Domain1D_type Attribute ... /group0/products/T Dataset ... /group0/products/phase Group /group0/reactants Group /group0/reactants/Domain1D_type Attribute ... /group0/reactants/T Dataset ... /group0/reactants/phase Group where ``group0`` is the default name for the top level HDF entry, and ``reactants``, ``flame`` and ``products`` correspond to domain names. Note that it is possible to save multiple solutions to a single HDF container file. :param filename: HDF container file containing data to be restored :param group: Identifier for the group in the container file. A group may contain multiple `SolutionArray` objects. :param species: Attribute to use obtaining species profiles, e.g. ``X`` for mole fractions or ``Y`` for mass fractions. :param mode: Mode h5py uses to open the output file {'a' to read/write if file exists, create otherwise (default); 'w' to create file, truncate if exists; 'r+' to read/write, file must exist}. :param description: Custom comment describing the dataset to be stored. :param compression: Pre-defined h5py compression filters {None, 'gzip', 'lzf', 'szip'} used for data compression. :param compression_opts: Options for the h5py compression filter; for 'gzip', this corresponds to the compression level {None, 0-9}. :param quiet: Suppress message confirming successful file output. :param normalize: Boolean flag to indicate whether the mole/mass fractions should be normalized (default is ``True``) Additional arguments (i.e. *args* and *kwargs*) are passed on to `SolutionArray.collect_data`. The method exports data using `SolutionArray.write_hdf` via `to_solution_array` and requires a working installation of h5py (`h5py` can be installed using pip or conda).
Write the solution vector to a HDF container file.
[ "Write", "the", "solution", "vector", "to", "a", "HDF", "container", "file", "." ]
def write_hdf(self, filename, *args, group=None, species='X', mode='a', description=None, compression=None, compression_opts=None, quiet=True, normalize=True, **kwargs): """ Write the solution vector to a HDF container file. The `write_hdf` method preserves the structure of a `FlameBase`-derived object (such as `FreeFlame`). Each simulation is saved as a *group*, whereas individual domains are saved as subgroups. In addition to datasets, information on `Sim1D.settings` and `Domain1D.settings` is saved in form of HDF attributes. The internal HDF file structure is illustrated for a `FreeFlame` output as::: / Group /group0 Group /group0/Sim1D_type Attribute ... /group0/flame Group /group0/flame/Domain1D_type Attribute ... /group0/flame/T Dataset ... /group0/flame/phase Group /group0/products Group /group0/products/Domain1D_type Attribute ... /group0/products/T Dataset ... /group0/products/phase Group /group0/reactants Group /group0/reactants/Domain1D_type Attribute ... /group0/reactants/T Dataset ... /group0/reactants/phase Group where ``group0`` is the default name for the top level HDF entry, and ``reactants``, ``flame`` and ``products`` correspond to domain names. Note that it is possible to save multiple solutions to a single HDF container file. :param filename: HDF container file containing data to be restored :param group: Identifier for the group in the container file. A group may contain multiple `SolutionArray` objects. :param species: Attribute to use obtaining species profiles, e.g. ``X`` for mole fractions or ``Y`` for mass fractions. :param mode: Mode h5py uses to open the output file {'a' to read/write if file exists, create otherwise (default); 'w' to create file, truncate if exists; 'r+' to read/write, file must exist}. :param description: Custom comment describing the dataset to be stored. :param compression: Pre-defined h5py compression filters {None, 'gzip', 'lzf', 'szip'} used for data compression. :param compression_opts: Options for the h5py compression filter; for 'gzip', this corresponds to the compression level {None, 0-9}. :param quiet: Suppress message confirming successful file output. :param normalize: Boolean flag to indicate whether the mole/mass fractions should be normalized (default is ``True``) Additional arguments (i.e. *args* and *kwargs*) are passed on to `SolutionArray.collect_data`. The method exports data using `SolutionArray.write_hdf` via `to_solution_array` and requires a working installation of h5py (`h5py` can be installed using pip or conda). """ cols = ('extra', 'T', 'D', species) meta = self.settings meta['date'] = formatdate(localtime=True) meta['cantera_version'] = __version__ meta['git_commit'] = __git_commit__ if description is not None: meta['description'] = description for i in range(3): arr = self.to_solution_array(domain=self.domains[i], normalize=normalize) group = arr.write_hdf(filename, *args, group=group, cols=cols, subgroup=self.domains[i].name, attrs=meta, mode=mode, append=(i > 0), compression=compression, compression_opts=compression_opts, **kwargs) meta = {} mode = 'a' if not quiet: msg = "Solution saved to '{0}' as group '{1}'." print(msg.format(filename, group))
[ "def", "write_hdf", "(", "self", ",", "filename", ",", "*", "args", ",", "group", "=", "None", ",", "species", "=", "'X'", ",", "mode", "=", "'a'", ",", "description", "=", "None", ",", "compression", "=", "None", ",", "compression_opts", "=", "None", ",", "quiet", "=", "True", ",", "normalize", "=", "True", ",", "*", "*", "kwargs", ")", ":", "cols", "=", "(", "'extra'", ",", "'T'", ",", "'D'", ",", "species", ")", "meta", "=", "self", ".", "settings", "meta", "[", "'date'", "]", "=", "formatdate", "(", "localtime", "=", "True", ")", "meta", "[", "'cantera_version'", "]", "=", "__version__", "meta", "[", "'git_commit'", "]", "=", "__git_commit__", "if", "description", "is", "not", "None", ":", "meta", "[", "'description'", "]", "=", "description", "for", "i", "in", "range", "(", "3", ")", ":", "arr", "=", "self", ".", "to_solution_array", "(", "domain", "=", "self", ".", "domains", "[", "i", "]", ",", "normalize", "=", "normalize", ")", "group", "=", "arr", ".", "write_hdf", "(", "filename", ",", "*", "args", ",", "group", "=", "group", ",", "cols", "=", "cols", ",", "subgroup", "=", "self", ".", "domains", "[", "i", "]", ".", "name", ",", "attrs", "=", "meta", ",", "mode", "=", "mode", ",", "append", "=", "(", "i", ">", "0", ")", ",", "compression", "=", "compression", ",", "compression_opts", "=", "compression_opts", ",", "*", "*", "kwargs", ")", "meta", "=", "{", "}", "mode", "=", "'a'", "if", "not", "quiet", ":", "msg", "=", "\"Solution saved to '{0}' as group '{1}'.\"", "print", "(", "msg", ".", "format", "(", "filename", ",", "group", ")", ")" ]
https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/onedim.py#L496-L588
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/aui.py
python
AuiPaneInfo.FloatingPosition
(*args, **kwargs)
return _aui.AuiPaneInfo_FloatingPosition(*args, **kwargs)
FloatingPosition(self, Point pos) -> AuiPaneInfo
FloatingPosition(self, Point pos) -> AuiPaneInfo
[ "FloatingPosition", "(", "self", "Point", "pos", ")", "-", ">", "AuiPaneInfo" ]
def FloatingPosition(*args, **kwargs): """FloatingPosition(self, Point pos) -> AuiPaneInfo""" return _aui.AuiPaneInfo_FloatingPosition(*args, **kwargs)
[ "def", "FloatingPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiPaneInfo_FloatingPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/aui.py#L401-L403
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py
python
NDFrame.asfreq
( self: FrameOrSeries, freq, method=None, how: Optional[str] = None, normalize: bool_t = False, fill_value=None, )
return asfreq( self, freq, method=method, how=how, normalize=normalize, fill_value=fill_value, )
Convert TimeSeries to specified frequency. Optionally provide filling method to pad/backfill missing values. Returns the original data conformed to a new index with the specified frequency. ``resample`` is more appropriate if an operation, such as summarization, is necessary to represent the data at the new frequency. Parameters ---------- freq : DateOffset or str method : {'backfill'/'bfill', 'pad'/'ffill'}, default None Method to use for filling holes in reindexed Series (note this does not fill NaNs that already were present): * 'pad' / 'ffill': propagate last valid observation forward to next valid * 'backfill' / 'bfill': use NEXT valid observation to fill. how : {'start', 'end'}, default end For PeriodIndex only (see PeriodIndex.asfreq). normalize : bool, default False Whether to reset output index to midnight. fill_value : scalar, optional Value to use for missing values, applied during upsampling (note this does not fill NaNs that already were present). Returns ------- converted : same type as caller See Also -------- reindex Notes ----- To learn more about the frequency strings, please see `this link <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__. Examples -------- Start by creating a series with 4 one minute timestamps. >>> index = pd.date_range('1/1/2000', periods=4, freq='T') >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index) >>> df = pd.DataFrame({'s':series}) >>> df s 2000-01-01 00:00:00 0.0 2000-01-01 00:01:00 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:03:00 3.0 Upsample the series into 30 second bins. >>> df.asfreq(freq='30S') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 NaN 2000-01-01 00:03:00 3.0 Upsample again, providing a ``fill value``. >>> df.asfreq(freq='30S', fill_value=9.0) s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 9.0 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 9.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 9.0 2000-01-01 00:03:00 3.0 Upsample again, providing a ``method``. >>> df.asfreq(freq='30S', method='bfill') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 2.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 3.0 2000-01-01 00:03:00 3.0
Convert TimeSeries to specified frequency.
[ "Convert", "TimeSeries", "to", "specified", "frequency", "." ]
def asfreq( self: FrameOrSeries, freq, method=None, how: Optional[str] = None, normalize: bool_t = False, fill_value=None, ) -> FrameOrSeries: """ Convert TimeSeries to specified frequency. Optionally provide filling method to pad/backfill missing values. Returns the original data conformed to a new index with the specified frequency. ``resample`` is more appropriate if an operation, such as summarization, is necessary to represent the data at the new frequency. Parameters ---------- freq : DateOffset or str method : {'backfill'/'bfill', 'pad'/'ffill'}, default None Method to use for filling holes in reindexed Series (note this does not fill NaNs that already were present): * 'pad' / 'ffill': propagate last valid observation forward to next valid * 'backfill' / 'bfill': use NEXT valid observation to fill. how : {'start', 'end'}, default end For PeriodIndex only (see PeriodIndex.asfreq). normalize : bool, default False Whether to reset output index to midnight. fill_value : scalar, optional Value to use for missing values, applied during upsampling (note this does not fill NaNs that already were present). Returns ------- converted : same type as caller See Also -------- reindex Notes ----- To learn more about the frequency strings, please see `this link <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__. Examples -------- Start by creating a series with 4 one minute timestamps. >>> index = pd.date_range('1/1/2000', periods=4, freq='T') >>> series = pd.Series([0.0, None, 2.0, 3.0], index=index) >>> df = pd.DataFrame({'s':series}) >>> df s 2000-01-01 00:00:00 0.0 2000-01-01 00:01:00 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:03:00 3.0 Upsample the series into 30 second bins. >>> df.asfreq(freq='30S') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 NaN 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 NaN 2000-01-01 00:03:00 3.0 Upsample again, providing a ``fill value``. >>> df.asfreq(freq='30S', fill_value=9.0) s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 9.0 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 9.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 9.0 2000-01-01 00:03:00 3.0 Upsample again, providing a ``method``. >>> df.asfreq(freq='30S', method='bfill') s 2000-01-01 00:00:00 0.0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 NaN 2000-01-01 00:01:30 2.0 2000-01-01 00:02:00 2.0 2000-01-01 00:02:30 3.0 2000-01-01 00:03:00 3.0 """ from pandas.core.resample import asfreq return asfreq( self, freq, method=method, how=how, normalize=normalize, fill_value=fill_value, )
[ "def", "asfreq", "(", "self", ":", "FrameOrSeries", ",", "freq", ",", "method", "=", "None", ",", "how", ":", "Optional", "[", "str", "]", "=", "None", ",", "normalize", ":", "bool_t", "=", "False", ",", "fill_value", "=", "None", ",", ")", "->", "FrameOrSeries", ":", "from", "pandas", ".", "core", ".", "resample", "import", "asfreq", "return", "asfreq", "(", "self", ",", "freq", ",", "method", "=", "method", ",", "how", "=", "how", ",", "normalize", "=", "normalize", ",", "fill_value", "=", "fill_value", ",", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py#L7574-L7682
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
ListItemAttr.GetTextColour
(*args, **kwargs)
return _controls_.ListItemAttr_GetTextColour(*args, **kwargs)
GetTextColour(self) -> Colour
GetTextColour(self) -> Colour
[ "GetTextColour", "(", "self", ")", "-", ">", "Colour" ]
def GetTextColour(*args, **kwargs): """GetTextColour(self) -> Colour""" return _controls_.ListItemAttr_GetTextColour(*args, **kwargs)
[ "def", "GetTextColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListItemAttr_GetTextColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L4114-L4116
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/arrays/categorical.py
python
Categorical.itemsize
(self)
return self.categories.itemsize
return the size of a single category
return the size of a single category
[ "return", "the", "size", "of", "a", "single", "category" ]
def itemsize(self) -> int: """ return the size of a single category """ return self.categories.itemsize
[ "def", "itemsize", "(", "self", ")", "->", "int", ":", "return", "self", ".", "categories", ".", "itemsize" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/arrays/categorical.py#L543-L547
DaFuCoding/MTCNN_Caffe
09c30c3ff391bd9cb6b249c1910afaf147767ab3
tools/extra/parse_log.py
python
fix_initial_nan_learning_rate
(dict_list)
Correct initial value of learning rate Learning rate is normally not printed until after the initial test and training step, which means the initial testing and training rows have LearningRate = NaN. Fix this by copying over the LearningRate from the second row, if it exists.
Correct initial value of learning rate
[ "Correct", "initial", "value", "of", "learning", "rate" ]
def fix_initial_nan_learning_rate(dict_list): """Correct initial value of learning rate Learning rate is normally not printed until after the initial test and training step, which means the initial testing and training rows have LearningRate = NaN. Fix this by copying over the LearningRate from the second row, if it exists. """ if len(dict_list) > 1: dict_list[0]['LearningRate'] = dict_list[1]['LearningRate']
[ "def", "fix_initial_nan_learning_rate", "(", "dict_list", ")", ":", "if", "len", "(", "dict_list", ")", ">", "1", ":", "dict_list", "[", "0", "]", "[", "'LearningRate'", "]", "=", "dict_list", "[", "1", "]", "[", "'LearningRate'", "]" ]
https://github.com/DaFuCoding/MTCNN_Caffe/blob/09c30c3ff391bd9cb6b249c1910afaf147767ab3/tools/extra/parse_log.py#L116-L126
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/models/image/cifar10/cifar10.py
python
_variable_with_weight_decay
(name, shape, stddev, wd)
return var
Helper to create an initialized Variable with weight decay. Note that the Variable is initialized with a truncated normal distribution. A weight decay is added only if one is specified. Args: name: name of the variable shape: list of ints stddev: standard deviation of a truncated Gaussian wd: add L2Loss weight decay multiplied by this float. If None, weight decay is not added for this Variable. Returns: Variable Tensor
Helper to create an initialized Variable with weight decay.
[ "Helper", "to", "create", "an", "initialized", "Variable", "with", "weight", "decay", "." ]
def _variable_with_weight_decay(name, shape, stddev, wd): """Helper to create an initialized Variable with weight decay. Note that the Variable is initialized with a truncated normal distribution. A weight decay is added only if one is specified. Args: name: name of the variable shape: list of ints stddev: standard deviation of a truncated Gaussian wd: add L2Loss weight decay multiplied by this float. If None, weight decay is not added for this Variable. Returns: Variable Tensor """ dtype = tf.float16 if FLAGS.use_fp16 else tf.float32 var = _variable_on_cpu( name, shape, tf.truncated_normal_initializer(stddev=stddev, dtype=dtype)) if wd is not None: weight_decay = tf.mul(tf.nn.l2_loss(var), wd, name='weight_loss') tf.add_to_collection('losses', weight_decay) return var
[ "def", "_variable_with_weight_decay", "(", "name", ",", "shape", ",", "stddev", ",", "wd", ")", ":", "dtype", "=", "tf", ".", "float16", "if", "FLAGS", ".", "use_fp16", "else", "tf", ".", "float32", "var", "=", "_variable_on_cpu", "(", "name", ",", "shape", ",", "tf", ".", "truncated_normal_initializer", "(", "stddev", "=", "stddev", ",", "dtype", "=", "dtype", ")", ")", "if", "wd", "is", "not", "None", ":", "weight_decay", "=", "tf", ".", "mul", "(", "tf", ".", "nn", ".", "l2_loss", "(", "var", ")", ",", "wd", ",", "name", "=", "'weight_loss'", ")", "tf", ".", "add_to_collection", "(", "'losses'", ",", "weight_decay", ")", "return", "var" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/models/image/cifar10/cifar10.py#L115-L139
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/util/compat.py
python
as_str_any
(value)
Converts to `str` as `str(value)`, but use `as_str` for `bytes`. Args: value: A object that can be converted to `str`. Returns: A `str` object.
Converts to `str` as `str(value)`, but use `as_str` for `bytes`.
[ "Converts", "to", "str", "as", "str", "(", "value", ")", "but", "use", "as_str", "for", "bytes", "." ]
def as_str_any(value): """Converts to `str` as `str(value)`, but use `as_str` for `bytes`. Args: value: A object that can be converted to `str`. Returns: A `str` object. """ if isinstance(value, bytes): return as_str(value) else: return str(value)
[ "def", "as_str_any", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "return", "as_str", "(", "value", ")", "else", ":", "return", "str", "(", "value", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/util/compat.py#L75-L87
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/sysconfig.py
python
get_scheme_names
()
return tuple(sorted(_SCHEMES.sections()))
Return a tuple containing the schemes names.
Return a tuple containing the schemes names.
[ "Return", "a", "tuple", "containing", "the", "schemes", "names", "." ]
def get_scheme_names(): """Return a tuple containing the schemes names.""" return tuple(sorted(_SCHEMES.sections()))
[ "def", "get_scheme_names", "(", ")", ":", "return", "tuple", "(", "sorted", "(", "_SCHEMES", ".", "sections", "(", ")", ")", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/sysconfig.py#L431-L433
facebookresearch/habitat-sim
63b6c71d9ca8adaefb140b198196f5d0ca1f1e34
src_python/habitat_sim/robots/mobile_manipulator.py
python
MobileManipulator.reconfigure
(self)
Instantiates the robot the scene. Loads the URDF, sets initial state of parameters, joints, motors, etc...
Instantiates the robot the scene. Loads the URDF, sets initial state of parameters, joints, motors, etc...
[ "Instantiates", "the", "robot", "the", "scene", ".", "Loads", "the", "URDF", "sets", "initial", "state", "of", "parameters", "joints", "motors", "etc", "..." ]
def reconfigure(self) -> None: """Instantiates the robot the scene. Loads the URDF, sets initial state of parameters, joints, motors, etc...""" ao_mgr = self._sim.get_articulated_object_manager() self.sim_obj = ao_mgr.add_articulated_object_from_urdf( self.urdf_path, fixed_base=self._fixed_base ) if self._limit_robo_joints: # automatic joint limit clamping after each call to sim.step_physics() self.sim_obj.auto_clamp_joint_limits = True for link_id in self.sim_obj.get_link_ids(): self.joint_pos_indices[link_id] = self.sim_obj.get_link_joint_pos_offset( link_id ) self.joint_dof_indices[link_id] = self.sim_obj.get_link_dof_offset(link_id) self.joint_limits = self.sim_obj.joint_position_limits # remove any default damping motors for motor_id in self.sim_obj.existing_joint_motor_ids: self.sim_obj.remove_joint_motor(motor_id) # re-generate all joint motors with arm gains. jms = JointMotorSettings( 0, # position_target self.params.arm_mtr_pos_gain, # position_gain 0, # velocity_target self.params.arm_mtr_vel_gain, # velocity_gain self.params.arm_mtr_max_impulse, # max_impulse ) self.sim_obj.create_all_motors(jms) self._update_motor_settings_cache() # set correct gains for wheels if self.params.wheel_joints is not None: jms = JointMotorSettings( 0, # position_target self.params.wheel_mtr_pos_gain, # position_gain 0, # velocity_target self.params.wheel_mtr_vel_gain, # velocity_gain self.params.wheel_mtr_max_impulse, # max_impulse ) # pylint: disable=not-an-iterable for i in self.params.wheel_joints: self.sim_obj.update_joint_motor(self.joint_motors[i][0], jms) # set initial states and targets self.arm_joint_pos = self.params.arm_init_params self.gripper_joint_pos = self.params.gripper_init_params self._update_motor_settings_cache()
[ "def", "reconfigure", "(", "self", ")", "->", "None", ":", "ao_mgr", "=", "self", ".", "_sim", ".", "get_articulated_object_manager", "(", ")", "self", ".", "sim_obj", "=", "ao_mgr", ".", "add_articulated_object_from_urdf", "(", "self", ".", "urdf_path", ",", "fixed_base", "=", "self", ".", "_fixed_base", ")", "if", "self", ".", "_limit_robo_joints", ":", "# automatic joint limit clamping after each call to sim.step_physics()", "self", ".", "sim_obj", ".", "auto_clamp_joint_limits", "=", "True", "for", "link_id", "in", "self", ".", "sim_obj", ".", "get_link_ids", "(", ")", ":", "self", ".", "joint_pos_indices", "[", "link_id", "]", "=", "self", ".", "sim_obj", ".", "get_link_joint_pos_offset", "(", "link_id", ")", "self", ".", "joint_dof_indices", "[", "link_id", "]", "=", "self", ".", "sim_obj", ".", "get_link_dof_offset", "(", "link_id", ")", "self", ".", "joint_limits", "=", "self", ".", "sim_obj", ".", "joint_position_limits", "# remove any default damping motors", "for", "motor_id", "in", "self", ".", "sim_obj", ".", "existing_joint_motor_ids", ":", "self", ".", "sim_obj", ".", "remove_joint_motor", "(", "motor_id", ")", "# re-generate all joint motors with arm gains.", "jms", "=", "JointMotorSettings", "(", "0", ",", "# position_target", "self", ".", "params", ".", "arm_mtr_pos_gain", ",", "# position_gain", "0", ",", "# velocity_target", "self", ".", "params", ".", "arm_mtr_vel_gain", ",", "# velocity_gain", "self", ".", "params", ".", "arm_mtr_max_impulse", ",", "# max_impulse", ")", "self", ".", "sim_obj", ".", "create_all_motors", "(", "jms", ")", "self", ".", "_update_motor_settings_cache", "(", ")", "# set correct gains for wheels", "if", "self", ".", "params", ".", "wheel_joints", "is", "not", "None", ":", "jms", "=", "JointMotorSettings", "(", "0", ",", "# position_target", "self", ".", "params", ".", "wheel_mtr_pos_gain", ",", "# position_gain", "0", ",", "# velocity_target", "self", ".", "params", ".", "wheel_mtr_vel_gain", ",", "# velocity_gain", "self", ".", "params", ".", "wheel_mtr_max_impulse", ",", "# max_impulse", ")", "# pylint: disable=not-an-iterable", "for", "i", "in", "self", ".", "params", ".", "wheel_joints", ":", "self", ".", "sim_obj", ".", "update_joint_motor", "(", "self", ".", "joint_motors", "[", "i", "]", "[", "0", "]", ",", "jms", ")", "# set initial states and targets", "self", ".", "arm_joint_pos", "=", "self", ".", "params", ".", "arm_init_params", "self", ".", "gripper_joint_pos", "=", "self", ".", "params", ".", "gripper_init_params", "self", ".", "_update_motor_settings_cache", "(", ")" ]
https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/src_python/habitat_sim/robots/mobile_manipulator.py#L153-L200
google-ar/WebARonTango
e86965d2cbc652156b480e0fcf77c716745578cd
chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py
python
GENnHandler.WriteImmediateCmdComputeSize
(self, func, f)
Overrriden from TypeHandler.
Overrriden from TypeHandler.
[ "Overrriden", "from", "TypeHandler", "." ]
def WriteImmediateCmdComputeSize(self, func, f): """Overrriden from TypeHandler.""" f.write(" static uint32_t ComputeDataSize(GLsizei n) {\n") f.write( " return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\n") f.write(" }\n") f.write("\n") f.write(" static uint32_t ComputeSize(GLsizei n) {\n") f.write(" return static_cast<uint32_t>(\n") f.write(" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\n") f.write(" }\n") f.write("\n")
[ "def", "WriteImmediateCmdComputeSize", "(", "self", ",", "func", ",", "f", ")", ":", "f", ".", "write", "(", "\" static uint32_t ComputeDataSize(GLsizei n) {\\n\"", ")", "f", ".", "write", "(", "\" return static_cast<uint32_t>(sizeof(GLuint) * n); // NOLINT\\n\"", ")", "f", ".", "write", "(", "\" }\\n\"", ")", "f", ".", "write", "(", "\"\\n\"", ")", "f", ".", "write", "(", "\" static uint32_t ComputeSize(GLsizei n) {\\n\"", ")", "f", ".", "write", "(", "\" return static_cast<uint32_t>(\\n\"", ")", "f", ".", "write", "(", "\" sizeof(ValueType) + ComputeDataSize(n)); // NOLINT\\n\"", ")", "f", ".", "write", "(", "\" }\\n\"", ")", "f", ".", "write", "(", "\"\\n\"", ")" ]
https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L6128-L6139
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/command/install.py
python
install.convert_paths
(self, *names)
Call `convert_path` over `names`.
Call `convert_path` over `names`.
[ "Call", "convert_path", "over", "names", "." ]
def convert_paths(self, *names): """Call `convert_path` over `names`.""" for name in names: attr = "install_" + name setattr(self, attr, convert_path(getattr(self, attr)))
[ "def", "convert_paths", "(", "self", ",", "*", "names", ")", ":", "for", "name", "in", "names", ":", "attr", "=", "\"install_\"", "+", "name", "setattr", "(", "self", ",", "attr", ",", "convert_path", "(", "getattr", "(", "self", ",", "attr", ")", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/command/install.py#L483-L487
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
RegenerateOverview
(*args, **kwargs)
return _gdal.RegenerateOverview(*args, **kwargs)
r"""RegenerateOverview(Band srcBand, Band overviewBand, char const * resampling="average", GDALProgressFunc callback=0, void * callback_data=None) -> int
r"""RegenerateOverview(Band srcBand, Band overviewBand, char const * resampling="average", GDALProgressFunc callback=0, void * callback_data=None) -> int
[ "r", "RegenerateOverview", "(", "Band", "srcBand", "Band", "overviewBand", "char", "const", "*", "resampling", "=", "average", "GDALProgressFunc", "callback", "=", "0", "void", "*", "callback_data", "=", "None", ")", "-", ">", "int" ]
def RegenerateOverview(*args, **kwargs): r"""RegenerateOverview(Band srcBand, Band overviewBand, char const * resampling="average", GDALProgressFunc callback=0, void * callback_data=None) -> int""" return _gdal.RegenerateOverview(*args, **kwargs)
[ "def", "RegenerateOverview", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdal", ".", "RegenerateOverview", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L3959-L3961
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_one_hot_encoder.py
python
update_dimension
(model, input_dimension)
return out_dimension
Given a model that takes an array of dimension input_dimension, returns the output dimension.
Given a model that takes an array of dimension input_dimension, returns the output dimension.
[ "Given", "a", "model", "that", "takes", "an", "array", "of", "dimension", "input_dimension", "returns", "the", "output", "dimension", "." ]
def update_dimension(model, input_dimension): """ Given a model that takes an array of dimension input_dimension, returns the output dimension. """ if not (_HAS_SKLEARN): raise RuntimeError( "scikit-learn not found. scikit-learn conversion API is disabled." ) _sklearn_util.check_fitted(model, lambda m: hasattr(m, "active_features_")) _sklearn_util.check_fitted(model, lambda m: hasattr(m, "n_values_")) if model.categorical_features == "all": return len(model.active_features_) else: out_dimension = len(model.active_features_) + ( input_dimension - len(model.n_values_) ) return out_dimension
[ "def", "update_dimension", "(", "model", ",", "input_dimension", ")", ":", "if", "not", "(", "_HAS_SKLEARN", ")", ":", "raise", "RuntimeError", "(", "\"scikit-learn not found. scikit-learn conversion API is disabled.\"", ")", "_sklearn_util", ".", "check_fitted", "(", "model", ",", "lambda", "m", ":", "hasattr", "(", "m", ",", "\"active_features_\"", ")", ")", "_sklearn_util", ".", "check_fitted", "(", "model", ",", "lambda", "m", ":", "hasattr", "(", "m", ",", "\"n_values_\"", ")", ")", "if", "model", ".", "categorical_features", "==", "\"all\"", ":", "return", "len", "(", "model", ".", "active_features_", ")", "else", ":", "out_dimension", "=", "len", "(", "model", ".", "active_features_", ")", "+", "(", "input_dimension", "-", "len", "(", "model", ".", "n_values_", ")", ")", "return", "out_dimension" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_one_hot_encoder.py#L208-L228
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/api/position_api.py
python
PositionApi.position_update_risk_limit
(self, symbol, risk_limit, **kwargs)
Update your risk limit. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.position_update_risk_limit(symbol, risk_limit, async_req=True) >>> result = thread.get() :param async_req bool :param str symbol: Symbol of position to update risk limit on. (required) :param float risk_limit: New Risk Limit, in Satoshis. (required) :return: Position If the method is called asynchronously, returns the request thread.
Update your risk limit. # noqa: E501
[ "Update", "your", "risk", "limit", ".", "#", "noqa", ":", "E501" ]
def position_update_risk_limit(self, symbol, risk_limit, **kwargs): # noqa: E501 """Update your risk limit. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.position_update_risk_limit(symbol, risk_limit, async_req=True) >>> result = thread.get() :param async_req bool :param str symbol: Symbol of position to update risk limit on. (required) :param float risk_limit: New Risk Limit, in Satoshis. (required) :return: Position If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.position_update_risk_limit_with_http_info(symbol, risk_limit, **kwargs) # noqa: E501 else: (data) = self.position_update_risk_limit_with_http_info(symbol, risk_limit, **kwargs) # noqa: E501 return data
[ "def", "position_update_risk_limit", "(", "self", ",", "symbol", ",", "risk_limit", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "position_update_risk_limit_with_http_info", "(", "symbol", ",", "risk_limit", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "position_update_risk_limit_with_http_info", "(", "symbol", ",", "risk_limit", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/api/position_api.py#L450-L470
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/contextlib2.py
python
ExitStack.callback
(self, callback, *args, **kwds)
return callback
Registers an arbitrary callback and arguments. Cannot suppress exceptions.
Registers an arbitrary callback and arguments.
[ "Registers", "an", "arbitrary", "callback", "and", "arguments", "." ]
def callback(self, callback, *args, **kwds): """Registers an arbitrary callback and arguments. Cannot suppress exceptions. """ def _exit_wrapper(exc_type, exc, tb): callback(*args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection _exit_wrapper.__wrapped__ = callback self.push(_exit_wrapper) return callback
[ "def", "callback", "(", "self", ",", "callback", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "def", "_exit_wrapper", "(", "exc_type", ",", "exc", ",", "tb", ")", ":", "callback", "(", "*", "args", ",", "*", "*", "kwds", ")", "# We changed the signature, so using @wraps is not appropriate, but", "# setting __wrapped__ may still help with introspection", "_exit_wrapper", ".", "__wrapped__", "=", "callback", "self", ".", "push", "(", "_exit_wrapper", ")", "return", "callback" ]
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/_vendor/contextlib2.py#L420-L431
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/indentation.py
python
IndentationRules._AddToEach
(self, original, amount)
return set([x + amount for x in original])
Returns a new set with the given amount added to each element. Args: original: The original set of numbers amount: The amount to add to each element Returns: A new set containing each element of the original set added to the amount.
Returns a new set with the given amount added to each element.
[ "Returns", "a", "new", "set", "with", "the", "given", "amount", "added", "to", "each", "element", "." ]
def _AddToEach(self, original, amount): """Returns a new set with the given amount added to each element. Args: original: The original set of numbers amount: The amount to add to each element Returns: A new set containing each element of the original set added to the amount. """ return set([x + amount for x in original])
[ "def", "_AddToEach", "(", "self", ",", "original", ",", "amount", ")", ":", "return", "set", "(", "[", "x", "+", "amount", "for", "x", "in", "original", "]", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/indentation.py#L304-L314
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Hash/BLAKE2b.py
python
new
(**kwargs)
return BLAKE2b_Hash(data, key, digest_bytes, update_after_digest)
Create a new hash object. Args: data (bytes/bytearray/memoryview): Optional. The very first chunk of the message to hash. It is equivalent to an early call to :meth:`BLAKE2b_Hash.update`. digest_bytes (integer): Optional. The size of the digest, in bytes (1 to 64). Default is 64. digest_bits (integer): Optional and alternative to ``digest_bytes``. The size of the digest, in bits (8 to 512, in steps of 8). Default is 512. key (bytes/bytearray/memoryview): Optional. The key to use to compute the MAC (1 to 64 bytes). If not specified, no key will be used. update_after_digest (boolean): Optional. By default, a hash object cannot be updated anymore after the digest is computed. When this flag is ``True``, such check is no longer enforced. Returns: A :class:`BLAKE2b_Hash` hash object
Create a new hash object.
[ "Create", "a", "new", "hash", "object", "." ]
def new(**kwargs): """Create a new hash object. Args: data (bytes/bytearray/memoryview): Optional. The very first chunk of the message to hash. It is equivalent to an early call to :meth:`BLAKE2b_Hash.update`. digest_bytes (integer): Optional. The size of the digest, in bytes (1 to 64). Default is 64. digest_bits (integer): Optional and alternative to ``digest_bytes``. The size of the digest, in bits (8 to 512, in steps of 8). Default is 512. key (bytes/bytearray/memoryview): Optional. The key to use to compute the MAC (1 to 64 bytes). If not specified, no key will be used. update_after_digest (boolean): Optional. By default, a hash object cannot be updated anymore after the digest is computed. When this flag is ``True``, such check is no longer enforced. Returns: A :class:`BLAKE2b_Hash` hash object """ data = kwargs.pop("data", None) update_after_digest = kwargs.pop("update_after_digest", False) digest_bytes = kwargs.pop("digest_bytes", None) digest_bits = kwargs.pop("digest_bits", None) if None not in (digest_bytes, digest_bits): raise TypeError("Only one digest parameter must be provided") if (None, None) == (digest_bytes, digest_bits): digest_bytes = 64 if digest_bytes is not None: if not (1 <= digest_bytes <= 64): raise ValueError("'digest_bytes' not in range 1..64") else: if not (8 <= digest_bits <= 512) or (digest_bits % 8): raise ValueError("'digest_bytes' not in range 8..512, " "with steps of 8") digest_bytes = digest_bits // 8 key = kwargs.pop("key", b"") if len(key) > 64: raise ValueError("BLAKE2s key cannot exceed 64 bytes") if kwargs: raise TypeError("Unknown parameters: " + str(kwargs)) return BLAKE2b_Hash(data, key, digest_bytes, update_after_digest)
[ "def", "new", "(", "*", "*", "kwargs", ")", ":", "data", "=", "kwargs", ".", "pop", "(", "\"data\"", ",", "None", ")", "update_after_digest", "=", "kwargs", ".", "pop", "(", "\"update_after_digest\"", ",", "False", ")", "digest_bytes", "=", "kwargs", ".", "pop", "(", "\"digest_bytes\"", ",", "None", ")", "digest_bits", "=", "kwargs", ".", "pop", "(", "\"digest_bits\"", ",", "None", ")", "if", "None", "not", "in", "(", "digest_bytes", ",", "digest_bits", ")", ":", "raise", "TypeError", "(", "\"Only one digest parameter must be provided\"", ")", "if", "(", "None", ",", "None", ")", "==", "(", "digest_bytes", ",", "digest_bits", ")", ":", "digest_bytes", "=", "64", "if", "digest_bytes", "is", "not", "None", ":", "if", "not", "(", "1", "<=", "digest_bytes", "<=", "64", ")", ":", "raise", "ValueError", "(", "\"'digest_bytes' not in range 1..64\"", ")", "else", ":", "if", "not", "(", "8", "<=", "digest_bits", "<=", "512", ")", "or", "(", "digest_bits", "%", "8", ")", ":", "raise", "ValueError", "(", "\"'digest_bytes' not in range 8..512, \"", "\"with steps of 8\"", ")", "digest_bytes", "=", "digest_bits", "//", "8", "key", "=", "kwargs", ".", "pop", "(", "\"key\"", ",", "b\"\"", ")", "if", "len", "(", "key", ")", ">", "64", ":", "raise", "ValueError", "(", "\"BLAKE2s key cannot exceed 64 bytes\"", ")", "if", "kwargs", ":", "raise", "TypeError", "(", "\"Unknown parameters: \"", "+", "str", "(", "kwargs", ")", ")", "return", "BLAKE2b_Hash", "(", "data", ",", "key", ",", "digest_bytes", ",", "update_after_digest", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Hash/BLAKE2b.py#L197-L247
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/CrystalField/pointcharge.py
python
PointCharge.Charges
(self)
return self._charges
The current list of charges as a dictionary
The current list of charges as a dictionary
[ "The", "current", "list", "of", "charges", "as", "a", "dictionary" ]
def Charges(self): """The current list of charges as a dictionary""" return self._charges
[ "def", "Charges", "(", "self", ")", ":", "return", "self", ".", "_charges" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/CrystalField/pointcharge.py#L196-L198
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/common_shapes.py
python
max_pool_shape
(op)
return [tensor_shape.TensorShape(output_shape)]
Shape function for a MaxPool op. This op has one input: * input, a 4D tensor with shape = [batch_size, rows, cols, depth_in] The output is a 4D tensor with shape = [batch_size, out_rows, out_cols, depth_out], where out_rows, out_cols, and depth_out depend on the value of the op's "ksize", "strides", and "padding" attrs. Args: op: A MaxPool Operation. Returns: A single-element list containing the Shape of the MaxPool output. Raises: ValueError: If the shape of the input is invalid or incompatible with the values of the attrs.
Shape function for a MaxPool op.
[ "Shape", "function", "for", "a", "MaxPool", "op", "." ]
def max_pool_shape(op): """Shape function for a MaxPool op. This op has one input: * input, a 4D tensor with shape = [batch_size, rows, cols, depth_in] The output is a 4D tensor with shape = [batch_size, out_rows, out_cols, depth_out], where out_rows, out_cols, and depth_out depend on the value of the op's "ksize", "strides", and "padding" attrs. Args: op: A MaxPool Operation. Returns: A single-element list containing the Shape of the MaxPool output. Raises: ValueError: If the shape of the input is invalid or incompatible with the values of the attrs. """ input_shape = op.inputs[0].get_shape().with_rank(4) try: data_format = op.get_attr("data_format") except ValueError: data_format = None if data_format == b"NCHW": # Convert input shape to the default NHWC for inference. input_shape = [input_shape[0], input_shape[2], input_shape[3], input_shape[1]] if data_format == b"NCHW": ksize_b, ksize_d, ksize_r, ksize_c = op.get_attr("ksize") stride_b, stride_d, stride_r, stride_c = op.get_attr("strides") else: ksize_b, ksize_r, ksize_c, ksize_d = op.get_attr("ksize") stride_b, stride_r, stride_c, stride_d = op.get_attr("strides") batch_size = input_shape[0] in_rows = input_shape[1] in_cols = input_shape[2] depth = input_shape[3] if ksize_b != 1: raise ValueError("Current implementation does not support pooling " "in the batch dimension.") if stride_b != 1: raise ValueError("Current implementation does not support strides " "in the batch dimension.") if not ((ksize_r == 1 and ksize_c == 1) or ksize_d == 1): raise ValueError("MaxPooling supports exactly one of pooling across depth " "or pooling across width/height.") # TODO(mrry,shlens): Raise an error if the stride would cause # information in the input to be ignored. This will require a change # in the kernel implementation. if ksize_d == 1: padding = op.get_attr("padding") out_rows, out_cols = get2d_conv_output_size(in_rows, in_cols, ksize_r, ksize_c, stride_r, stride_c, padding) output_shape = [batch_size, out_rows, out_cols, depth] else: if depth % ksize_d > 0: raise ValueError("Depthwise max pooling requires the depth window " "to evenly divide the input depth.") if stride_d != ksize_d: raise ValueError("Depthwise max pooling requires the depth window " "to equal the depth stride.") output_shape = [batch_size, in_rows, in_cols, depth // ksize_d] if data_format == b"NCHW": # Convert output shape back to NCHW. output_shape = [output_shape[0], output_shape[3], output_shape[1], output_shape[2]] return [tensor_shape.TensorShape(output_shape)]
[ "def", "max_pool_shape", "(", "op", ")", ":", "input_shape", "=", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", ".", "with_rank", "(", "4", ")", "try", ":", "data_format", "=", "op", ".", "get_attr", "(", "\"data_format\"", ")", "except", "ValueError", ":", "data_format", "=", "None", "if", "data_format", "==", "b\"NCHW\"", ":", "# Convert input shape to the default NHWC for inference.", "input_shape", "=", "[", "input_shape", "[", "0", "]", ",", "input_shape", "[", "2", "]", ",", "input_shape", "[", "3", "]", ",", "input_shape", "[", "1", "]", "]", "if", "data_format", "==", "b\"NCHW\"", ":", "ksize_b", ",", "ksize_d", ",", "ksize_r", ",", "ksize_c", "=", "op", ".", "get_attr", "(", "\"ksize\"", ")", "stride_b", ",", "stride_d", ",", "stride_r", ",", "stride_c", "=", "op", ".", "get_attr", "(", "\"strides\"", ")", "else", ":", "ksize_b", ",", "ksize_r", ",", "ksize_c", ",", "ksize_d", "=", "op", ".", "get_attr", "(", "\"ksize\"", ")", "stride_b", ",", "stride_r", ",", "stride_c", ",", "stride_d", "=", "op", ".", "get_attr", "(", "\"strides\"", ")", "batch_size", "=", "input_shape", "[", "0", "]", "in_rows", "=", "input_shape", "[", "1", "]", "in_cols", "=", "input_shape", "[", "2", "]", "depth", "=", "input_shape", "[", "3", "]", "if", "ksize_b", "!=", "1", ":", "raise", "ValueError", "(", "\"Current implementation does not support pooling \"", "\"in the batch dimension.\"", ")", "if", "stride_b", "!=", "1", ":", "raise", "ValueError", "(", "\"Current implementation does not support strides \"", "\"in the batch dimension.\"", ")", "if", "not", "(", "(", "ksize_r", "==", "1", "and", "ksize_c", "==", "1", ")", "or", "ksize_d", "==", "1", ")", ":", "raise", "ValueError", "(", "\"MaxPooling supports exactly one of pooling across depth \"", "\"or pooling across width/height.\"", ")", "# TODO(mrry,shlens): Raise an error if the stride would cause", "# information in the input to be ignored. This will require a change", "# in the kernel implementation.", "if", "ksize_d", "==", "1", ":", "padding", "=", "op", ".", "get_attr", "(", "\"padding\"", ")", "out_rows", ",", "out_cols", "=", "get2d_conv_output_size", "(", "in_rows", ",", "in_cols", ",", "ksize_r", ",", "ksize_c", ",", "stride_r", ",", "stride_c", ",", "padding", ")", "output_shape", "=", "[", "batch_size", ",", "out_rows", ",", "out_cols", ",", "depth", "]", "else", ":", "if", "depth", "%", "ksize_d", ">", "0", ":", "raise", "ValueError", "(", "\"Depthwise max pooling requires the depth window \"", "\"to evenly divide the input depth.\"", ")", "if", "stride_d", "!=", "ksize_d", ":", "raise", "ValueError", "(", "\"Depthwise max pooling requires the depth window \"", "\"to equal the depth stride.\"", ")", "output_shape", "=", "[", "batch_size", ",", "in_rows", ",", "in_cols", ",", "depth", "//", "ksize_d", "]", "if", "data_format", "==", "b\"NCHW\"", ":", "# Convert output shape back to NCHW.", "output_shape", "=", "[", "output_shape", "[", "0", "]", ",", "output_shape", "[", "3", "]", ",", "output_shape", "[", "1", "]", ",", "output_shape", "[", "2", "]", "]", "return", "[", "tensor_shape", ".", "TensorShape", "(", "output_shape", ")", "]" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/common_shapes.py#L412-L489
google/fhir
d77f57706c1a168529b0b87ca7ccb1c0113e83c2
py/google/fhir/r4/primitive_handler.py
python
PrimitiveHandler.primitive_wrapper_from_json_value
( self, json_value: Optional[Any], primitive_cls: Type[message.Message], *, default_timezone: str = _primitive_time_utils.SIMPLE_ZULU )
return wrapper_cls.from_json_value(json_value, primitive_cls, wrapper_context)
See jsonformat PrimitiveHandler.primitive_wrapper_from_json_value.
See jsonformat PrimitiveHandler.primitive_wrapper_from_json_value.
[ "See", "jsonformat", "PrimitiveHandler", ".", "primitive_wrapper_from_json_value", "." ]
def primitive_wrapper_from_json_value( self, json_value: Optional[Any], primitive_cls: Type[message.Message], *, default_timezone: str = _primitive_time_utils.SIMPLE_ZULU ) -> _primitive_wrappers.PrimitiveWrapper: """See jsonformat PrimitiveHandler.primitive_wrapper_from_json_value.""" if not annotation_utils.is_primitive_type(primitive_cls.DESCRIPTOR): raise ValueError( f'Not a primitive type: {primitive_cls.DESCRIPTOR.full_name!r}.') wrapper_cls = self.get_primitive_wrapper_cls_for_primitive_cls( primitive_cls) wrapper_context = _primitive_wrappers.Context( separator_stride_cls=fhirproto_extensions_pb2 .Base64BinarySeparatorStride, code_cls=self.code_cls, default_timezone=default_timezone) return wrapper_cls.from_json_value(json_value, primitive_cls, wrapper_context)
[ "def", "primitive_wrapper_from_json_value", "(", "self", ",", "json_value", ":", "Optional", "[", "Any", "]", ",", "primitive_cls", ":", "Type", "[", "message", ".", "Message", "]", ",", "*", ",", "default_timezone", ":", "str", "=", "_primitive_time_utils", ".", "SIMPLE_ZULU", ")", "->", "_primitive_wrappers", ".", "PrimitiveWrapper", ":", "if", "not", "annotation_utils", ".", "is_primitive_type", "(", "primitive_cls", ".", "DESCRIPTOR", ")", ":", "raise", "ValueError", "(", "f'Not a primitive type: {primitive_cls.DESCRIPTOR.full_name!r}.'", ")", "wrapper_cls", "=", "self", ".", "get_primitive_wrapper_cls_for_primitive_cls", "(", "primitive_cls", ")", "wrapper_context", "=", "_primitive_wrappers", ".", "Context", "(", "separator_stride_cls", "=", "fhirproto_extensions_pb2", ".", "Base64BinarySeparatorStride", ",", "code_cls", "=", "self", ".", "code_cls", ",", "default_timezone", "=", "default_timezone", ")", "return", "wrapper_cls", ".", "from_json_value", "(", "json_value", ",", "primitive_cls", ",", "wrapper_context", ")" ]
https://github.com/google/fhir/blob/d77f57706c1a168529b0b87ca7ccb1c0113e83c2/py/google/fhir/r4/primitive_handler.py#L198-L218
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/google/protobuf/text_format.py
python
_Tokenizer.AtEnd
(self)
return self.token == ''
Checks the end of the text was reached. Returns: True iff the end was reached.
Checks the end of the text was reached.
[ "Checks", "the", "end", "of", "the", "text", "was", "reached", "." ]
def AtEnd(self): """Checks the end of the text was reached. Returns: True iff the end was reached. """ return self.token == ''
[ "def", "AtEnd", "(", "self", ")", ":", "return", "self", ".", "token", "==", "''" ]
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/google/protobuf/text_format.py#L328-L334
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pytz/tzfile.py
python
_std_string
(s)
return str(s.decode('ASCII'))
Cast a string or byte string to an ASCII string.
Cast a string or byte string to an ASCII string.
[ "Cast", "a", "string", "or", "byte", "string", "to", "an", "ASCII", "string", "." ]
def _std_string(s): """Cast a string or byte string to an ASCII string.""" return str(s.decode('ASCII'))
[ "def", "_std_string", "(", "s", ")", ":", "return", "str", "(", "s", ".", "decode", "(", "'ASCII'", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pytz/tzfile.py#L20-L22
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/array_ops.py
python
_ZerosLikeShape
(op)
return [op.inputs[0].get_shape()]
Shape function for the ZerosLike op.
Shape function for the ZerosLike op.
[ "Shape", "function", "for", "the", "ZerosLike", "op", "." ]
def _ZerosLikeShape(op): """Shape function for the ZerosLike op.""" return [op.inputs[0].get_shape()]
[ "def", "_ZerosLikeShape", "(", "op", ")", ":", "return", "[", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", "]" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L2145-L2147
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/network/routing.py
python
priorityDictionary.__setitem__
(self, key, val)
Change value stored in dictionary and add corresponding pair to heap. Rebuilds the heap if the number of deleted items grows too large, to avoid memory leakage.
Change value stored in dictionary and add corresponding pair to heap. Rebuilds the heap if the number of deleted items grows too large, to avoid memory leakage.
[ "Change", "value", "stored", "in", "dictionary", "and", "add", "corresponding", "pair", "to", "heap", ".", "Rebuilds", "the", "heap", "if", "the", "number", "of", "deleted", "items", "grows", "too", "large", "to", "avoid", "memory", "leakage", "." ]
def __setitem__(self, key, val): '''Change value stored in dictionary and add corresponding pair to heap. Rebuilds the heap if the number of deleted items grows too large, to avoid memory leakage.''' dict.__setitem__(self, key, val) heap = self.__heap if len(heap) > 2 * len(self): self.__heap = [(v, k) for k, v in self.iteritems()] self.__heap.sort() # builtin sort likely faster than O(n) heapify else: newPair = (val, key) insertionPoint = len(heap) heap.append(None) while insertionPoint > 0 and val < heap[(insertionPoint-1)//2][0]: heap[insertionPoint] = heap[(insertionPoint-1)//2] insertionPoint = (insertionPoint-1)//2 heap[insertionPoint] = newPair
[ "def", "__setitem__", "(", "self", ",", "key", ",", "val", ")", ":", "dict", ".", "__setitem__", "(", "self", ",", "key", ",", "val", ")", "heap", "=", "self", ".", "__heap", "if", "len", "(", "heap", ")", ">", "2", "*", "len", "(", "self", ")", ":", "self", ".", "__heap", "=", "[", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "self", ".", "iteritems", "(", ")", "]", "self", ".", "__heap", ".", "sort", "(", ")", "# builtin sort likely faster than O(n) heapify", "else", ":", "newPair", "=", "(", "val", ",", "key", ")", "insertionPoint", "=", "len", "(", "heap", ")", "heap", ".", "append", "(", "None", ")", "while", "insertionPoint", ">", "0", "and", "val", "<", "heap", "[", "(", "insertionPoint", "-", "1", ")", "//", "2", "]", "[", "0", "]", ":", "heap", "[", "insertionPoint", "]", "=", "heap", "[", "(", "insertionPoint", "-", "1", ")", "//", "2", "]", "insertionPoint", "=", "(", "insertionPoint", "-", "1", ")", "//", "2", "heap", "[", "insertionPoint", "]", "=", "newPair" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/network/routing.py#L70-L86
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/dataview.py
python
DataViewCtrl.GetCurrentColumn
(*args, **kwargs)
return _dataview.DataViewCtrl_GetCurrentColumn(*args, **kwargs)
GetCurrentColumn(self) -> DataViewColumn
GetCurrentColumn(self) -> DataViewColumn
[ "GetCurrentColumn", "(", "self", ")", "-", ">", "DataViewColumn" ]
def GetCurrentColumn(*args, **kwargs): """GetCurrentColumn(self) -> DataViewColumn""" return _dataview.DataViewCtrl_GetCurrentColumn(*args, **kwargs)
[ "def", "GetCurrentColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewCtrl_GetCurrentColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L1751-L1753
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/tools/stats-viewer.py
python
ChromeCounter.Name
(self)
return result
Return the ascii name of this counter.
Return the ascii name of this counter.
[ "Return", "the", "ascii", "name", "of", "this", "counter", "." ]
def Name(self): """Return the ascii name of this counter.""" result = "" index = self.name_offset current = self.data.ByteAt(index) while current: result += chr(current) index += 1 current = self.data.ByteAt(index) return result
[ "def", "Name", "(", "self", ")", ":", "result", "=", "\"\"", "index", "=", "self", ".", "name_offset", "current", "=", "self", ".", "data", ".", "ByteAt", "(", "index", ")", "while", "current", ":", "result", "+=", "chr", "(", "current", ")", "index", "+=", "1", "current", "=", "self", ".", "data", ".", "ByteAt", "(", "index", ")", "return", "result" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/tools/stats-viewer.py#L405-L414